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: add project Docs and watcher management (#274)

I'm Groot 🌳740dbfd1e2db
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 04c65641..f6ec9041 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -134,6 +134,7 @@ export const app = new Elysia()
},
{ name: 'Agent Schedules', description: 'Recurring tasks for internal agents' },
{ name: 'Dashboards', description: 'Saved analytics dashboards' },
+ { name: 'Documents', description: 'Shared project Docs pages' },
{ name: 'Note boards', description: 'Freeform canvases of sticky notes' },
{ name: 'Notifications', description: "The session user's inbox notifications" },
{ name: 'Sync', description: 'Change markers a client polls for live refresh' },
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
index 8e04c8f9..3c4b532f 100644
--- a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '#tests/helpers/app';
+import { apiKeyApi, authedApi, type Api } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { untaggedRoutes } from '#tests/helpers/mcp';
@@ -439,12 +439,30 @@ describe('ai agents', () => {
const { asOwner } = await setup();
const created = await agents(asOwner).post({ name: 'Bot', username: 'bot', kind: 'external' });
const agentId = created.data!.agent.id;
+ const asAgent = apiKeyApi(created.data!.apiKey!);
+ const agentDocuments = asAgent.projects({ projectKey: 'MKT' }).documents;
+ const shared = (await agentDocuments.post({ title: 'Agent handbook' })).data!;
+ const privatePage = (
+ await agentDocuments.post({ title: 'Agent private notes', isPrivate: true })
+ ).data!;
const del = await agents(asOwner)({ agentId }).delete();
expect(del.status).toBe(204);
const list = await agents(asOwner).get();
expect(list.data).toHaveLength(0);
const project = await asOwner.projects({ projectKey: 'MKT' }).get();
expect(project.data?.assignees.some((a) => a.kind === 'agent')).toBe(false);
+ expect(
+ (await asOwner.projects({ projectKey: 'MKT' }).documents({ documentId: shared.id }).get())
+ .data,
+ ).toMatchObject({ ownerUserId: null, isPrivate: false });
+ expect(
+ (
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: privatePage.id })
+ .get()
+ ).status,
+ ).toBe(404);
});
it('rejects a duplicate username with 409', async () => {
diff --git a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts
index 08a13b63..7c7b6a74 100644
--- a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts
@@ -43,7 +43,7 @@ describe('normalizeToolKeys', () => {
});
it('puts every action in a known feature group (the config UI groups by it)', () => {
- const groups = new Set(['issues', 'initiatives', 'cycles', 'notes', 'project']);
+ const groups = new Set(['issues', 'initiatives', 'cycles', 'documents', 'notes', 'project']);
for (const tool of [...AGENT_ACTIONS, ...ALWAYS_ON_ACTIONS]) {
expect(groups.has(tool.group)).toBe(true);
}
@@ -77,6 +77,17 @@ describe('normalizeToolKeys', () => {
for (const key of keys) expect(alwaysOn.has(key)).toBe(false);
});
+ it('registers document actions as grantable, including the reads', () => {
+ const keys = [
+ 'list_documents',
+ 'get_document',
+ 'create_document',
+ 'update_document',
+ 'delete_document',
+ ];
+ expect(normalizeToolKeys(keys)).toEqual(keys);
+ });
+
// Agent-management tools are exposed over MCP (for an external MCP client to manage
// agents) but must never be reachable by an internal agent: they are not in the
// catalog, so normalizeToolKeys drops them and they are not always-on. This locks
diff --git a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
index 5dcbeade..01ea63b6 100644
--- a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
+++ b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
@@ -3,7 +3,8 @@
//
// - AGENT_ACTIONS: actions the user opts an agent into. The enabled subset is stored
// in ai_agent.tools and becomes the tools the runtime exposes. Mutating actions
-// belong here; so do the note board reads, since notes are an optional feature.
+// belong here; so do document and note-board reads, since both are optional
+// project knowledge surfaces.
// - ALWAYS_ON_ACTIONS: actions always granted, so an agent can always see its
// project and read the files dropped in its chat regardless of which other
// actions it is allowed to take. Listed only so the UI can show them (always
@@ -18,7 +19,7 @@
// and its project role.
// The feature an action belongs to, so the config UI can group the catalog.
-export type ToolGroup = 'issues' | 'initiatives' | 'cycles' | 'notes' | 'project';
+export type ToolGroup = 'issues' | 'initiatives' | 'cycles' | 'documents' | 'notes' | 'project';
export interface ToolMeta {
key: string;
@@ -196,6 +197,41 @@ export const AGENT_ACTIONS: ToolMeta[] = [
description: "Move a cycle's unfinished issues to another cycle, or off any cycle.",
always: false,
},
+ {
+ key: 'list_documents',
+ group: 'documents',
+ label: 'List documents',
+ description: 'List and search the shared project Docs tree.',
+ always: false,
+ },
+ {
+ key: 'get_document',
+ group: 'documents',
+ label: 'Read documents',
+ description: 'Read a shared project document and its Markdown content.',
+ always: false,
+ },
+ {
+ key: 'create_document',
+ group: 'documents',
+ label: 'Create documents',
+ description: 'Create shared project documents and nested pages.',
+ always: false,
+ },
+ {
+ key: 'update_document',
+ group: 'documents',
+ label: 'Update documents',
+ description: 'Edit document titles, Markdown content, nesting, and order.',
+ always: false,
+ },
+ {
+ key: 'delete_document',
+ group: 'documents',
+ label: 'Delete documents',
+ description: 'Permanently delete shared project documents.',
+ always: false,
+ },
{
key: 'list_note_boards',
group: 'notes',
diff --git a/apps/api/src/modules/agents/core/service.ts b/apps/api/src/modules/agents/core/service.ts
index 42b5fa60..7cf2cbb8 100644
--- a/apps/api/src/modules/agents/core/service.ts
+++ b/apps/api/src/modules/agents/core/service.ts
@@ -19,6 +19,7 @@ import { encryptSecret, decryptSecret } from '@repo/crypto';
import { normalizeToolKeys, ALWAYS_ON_ACTIONS } from './runtime/tools/catalog';
import { deleteThreadsWhere } from './runtime/memory';
import { listAgentMemberFieldIds } from '#modules/custom-fields/service';
+import { deleteAccount } from '#shared/account-deletion';
// Data access for AI agents. Each agent is backed by a hidden bot user
// (ai_agent.user_id -> user.id): that user is what a work item is assigned to,
@@ -724,7 +725,7 @@ export async function deleteAgent(id: number, projectId: number): Promise<boolea
if (!agent) return false;
await deleteThreadsWhere({ agentId: id });
await db.delete(apikey).where(eq(apikey.referenceId, agent.userId));
- await db.delete(user).where(eq(user.id, agent.userId));
+ await deleteAccount(agent.userId);
return true;
}
diff --git a/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
index 585e62c9..62694510 100644
--- a/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
+++ b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
@@ -75,6 +75,50 @@ describe('attachments', () => {
expect(res.status).toBe(400);
});
+ it('serializes the shared project quota across issue, chat, and document uploads', async () => {
+ const { asOwner, issueId } = await setupIssue();
+ await asOwner.god['storage-settings'].put({ projectQuotaMb: 1 });
+ const initial = 'x'.repeat(256 * 1024);
+
+ expect((await uploadFile(asOwner, issueId, 'issue.txt', 'text/plain', initial)).status).toBe(
+ 201,
+ );
+ expect(
+ (
+ await asOwner.projects({ projectKey: 'MKT' })['chat-attachments'].post({
+ filename: 'chat.txt',
+ contentType: 'text/plain',
+ contentBase64: Buffer.from(initial).toString('base64'),
+ })
+ ).status,
+ ).toBe(201);
+ const page = (
+ await asOwner.projects({ projectKey: 'MKT' }).documents.post({ title: 'Handbook' })
+ ).data!;
+ expect(
+ (
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: page.id })
+ .assets.post({
+ file: new File([initial], 'document.txt', { type: 'text/plain' }),
+ })
+ ).status,
+ ).toBe(201);
+
+ const contender = 'y'.repeat(200 * 1024);
+ const results = await Promise.all([
+ uploadFile(asOwner, issueId, 'parallel-issue.txt', 'text/plain', contender),
+ asOwner
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: page.id })
+ .assets.post({
+ file: new File([contender], 'parallel-document.txt', { type: 'text/plain' }),
+ }),
+ ]);
+ expect(results.map((result) => result.status).sort()).toEqual([201, 413]);
+ });
+
it('denies a non-member uploading to an issue', async () => {
const { issueId } = await setupIssue();
const outsider = authedApi((await signUpTestUser()).cookie);
@@ -126,6 +170,35 @@ describe('attachments', () => {
expect(list.data).toHaveLength(1);
});
+ it('counts a replacement as the new bytes minus the current bytes under the quota lock', async () => {
+ const { asOwner, issueId } = await setupIssue();
+ await asOwner.god['storage-settings'].put({ projectQuotaMb: 1 });
+ const first = await uploadFile(
+ asOwner,
+ issueId,
+ 'first.txt',
+ 'text/plain',
+ 'a'.repeat(700 * 1024),
+ );
+ expect(
+ (await uploadFile(asOwner, issueId, 'second.txt', 'text/plain', 'b'.repeat(250 * 1024)))
+ .status,
+ ).toBe(201);
+
+ const replaced = await asOwner.attachments({ publicId: first.data!.id }).put({
+ file: new File(['c'.repeat(750 * 1024)], 'first.txt', { type: 'text/plain' }),
+ });
+ expect(replaced.status).toBe(200);
+ expect(replaced.data?.sizeBytes).toBe(750 * 1024);
+
+ const rejected = await asOwner.attachments({ publicId: first.data!.id }).put({
+ file: new File(['d'.repeat(800 * 1024)], 'first.txt', { type: 'text/plain' }),
+ });
+ expect(rejected.status).toBe(413);
+ const raw = await api.attachments({ publicId: first.data!.id }).raw.get();
+ expect(String(raw.data)).toHaveLength(750 * 1024);
+ });
+
it('serves the replaced bytes to a client holding the old entity tag', async () => {
const { asOwner, issueId } = await setupIssue();
const up = await uploadFile(asOwner, issueId, 'shot.png', 'image/png', 'before');
diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.ts
index 9e0b0fb7..a08c3d87 100644
--- a/apps/api/src/modules/attachments/index.ts
+++ b/apps/api/src/modules/attachments/index.ts
@@ -1,20 +1,14 @@
import { Elysia, t } from 'elysia';
-import { randomUUID, createHash } from 'node:crypto';
import { noContent } from '#shared/http';
import { authContext } from '#shared/auth-context';
import { entityGuard } from '#shared/guards';
import { HttpError } from '#shared/lib';
-import { putObject, getObject, deleteObject } from '#shared/s3';
+import { getObject } from '#shared/s3';
import { assertPublicHttpUrl } from '#shared/net';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { getIssueProjectId } from '#modules/issues/service';
-import {
- getStorageSettings,
- mimeAllowed,
- MB,
- type StorageSettings,
-} from '#modules/settings/service';
+import { getStorageSettings, MB } from '#modules/settings/service';
import {
AttachmentResponse,
AttachmentListResponse,
@@ -31,61 +25,17 @@ import {
replaceAttachmentContent,
deleteAttachmentByPublicId,
removeAttachmentEmbeds,
- getProjectAttachmentBytes,
type AttachmentRow,
} from './service';
-
-// The upload limits are instance settings (see modules/settings/service.ts), read per
-// request so a change in god mode takes effect without a restart.
-async function assertUploadAllowed(
- limits: StorageSettings,
- projectId: number,
- size: number,
- contentType: string,
- // Bytes the new file takes the place of, which the quota gets back.
- replacedBytes = 0,
-): Promise<void> {
- if (size > limits.maxAttachmentMb * MB) {
- throw new HttpError(413, `File exceeds the ${limits.maxAttachmentMb} MB limit`);
- }
- if (!mimeAllowed(contentType, limits.attachmentMimeTypes)) {
- throw new HttpError(400, `Files of type "${contentType}" are not accepted on this instance`);
- }
- if (limits.projectQuotaMb > 0) {
- const used = (await getProjectAttachmentBytes(projectId)) - replacedBytes;
- if (used + size > limits.projectQuotaMb * MB) {
- throw new HttpError(
- 413,
- `The project has used its ${limits.projectQuotaMb} MB storage quota. Delete attachments to free space.`,
- );
- }
- }
-}
-
-// A failed write to the object store is nothing the caller can fix, so it is
-// logged with what it takes to find the object and reported as a bad gateway.
-async function storeObject(key: string, bytes: Buffer, contentType: string): Promise<void> {
- try {
- await putObject(key, bytes, contentType);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- console.error(
- `[planner] object store PUT failed (bucket=${process.env.S3_BUCKET}, key=${key}, size=${bytes.length}):`,
- err,
- );
- throw new HttpError(502, `Object store error: ${msg}`);
- }
-}
-
-// Object keys are grouped by project so a project's bytes sit under one prefix in
-// the bucket, which is what makes per-project listing, cleanup, and policies
-// possible. Keys already stored keep their old form; the full key lives in the row.
-function attachmentKey(projectId: number, issueId: number, filename: string): string {
- // Keep the original filename as the last key segment so the extension is visible
- // in the bucket and to any tool that sniffs the key by suffix.
- const safeName = filename.replace(/[^\w.-]+/g, '_').slice(-100);
- return `projects/${projectId}/attachments/${issueId}/${randomUUID()}-${safeName}`;
-}
+import {
+ assertAttachmentUploadAllowed,
+ attachmentEtag,
+ attachmentObjectKey,
+ attachmentResponseHeaders,
+ deleteAttachmentObject,
+ safeAttachmentFilename,
+ storeAttachmentObject,
+} from './storage';
// Public shape returned to the UI: never exposes the internal serial id or the
// object key. `url` is the public, no-auth download route — it can be embedded in
@@ -147,20 +97,27 @@ export const attachmentRoutes = new Elysia({
if (!(file instanceof File)) throw new HttpError(400, 'No file uploaded (form field "file")');
if (file.size === 0) throw new HttpError(400, 'Uploaded file is empty');
- const filename = file.name || 'file';
+ const filename = safeAttachmentFilename(file.name);
const contentType = file.type || 'application/octet-stream';
- await assertUploadAllowed(await getStorageSettings(), projectId, file.size, contentType);
+ await assertAttachmentUploadAllowed(projectId, file.size, contentType);
- const key = attachmentKey(projectId, issueId, filename);
- await storeObject(key, Buffer.from(await file.arrayBuffer()), contentType);
+ const key = attachmentObjectKey(projectId, 'attachments', issueId, filename);
+ await storeAttachmentObject(key, Buffer.from(await file.arrayBuffer()), contentType);
- const row = await createAttachment({
- issueId,
- s3Key: key,
- filename,
- contentType,
- sizeBytes: file.size,
- });
+ let row;
+ try {
+ row = await createAttachment({
+ projectId,
+ issueId,
+ s3Key: key,
+ filename,
+ contentType,
+ sizeBytes: file.size,
+ });
+ } catch (error) {
+ await deleteAttachmentObject(key);
+ throw error;
+ }
set.status = 201;
return attachmentDto(row);
},
@@ -181,7 +138,8 @@ export const attachmentRoutes = new Elysia({
'/issues/:issueId/attachments/import',
async ({ params, body, set, projectId }) => {
const issueId = params.issueId;
- const { filename, url, contentBase64 } = body;
+ const filename = safeAttachmentFilename(body.filename);
+ const { url, contentBase64 } = body;
if ((url == null) === (contentBase64 == null)) {
throw new HttpError(400, 'Provide exactly one of url or contentBase64');
}
@@ -218,18 +176,25 @@ export const attachmentRoutes = new Elysia({
}
if (bytes.length === 0) throw new HttpError(400, 'The file is empty');
- await assertUploadAllowed(limits, projectId, bytes.length, contentType);
+ await assertAttachmentUploadAllowed(projectId, bytes.length, contentType);
- const key = attachmentKey(projectId, issueId, filename);
- await storeObject(key, bytes, contentType);
+ const key = attachmentObjectKey(projectId, 'attachments', issueId, filename);
+ await storeAttachmentObject(key, bytes, contentType);
- const row = await createAttachment({
- issueId,
- s3Key: key,
- filename,
- contentType,
- sizeBytes: bytes.length,
- });
+ let row;
+ try {
+ row = await createAttachment({
+ projectId,
+ issueId,
+ s3Key: key,
+ filename,
+ contentType,
+ sizeBytes: bytes.length,
+ });
+ } catch (error) {
+ await deleteAttachmentObject(key);
+ throw error;
+ }
set.status = 201;
return attachmentDto(row);
},
@@ -260,36 +225,31 @@ export const attachmentRoutes = new Elysia({
if (!(file instanceof File)) throw new HttpError(400, 'No file uploaded (form field "file")');
if (file.size === 0) throw new HttpError(400, 'Uploaded file is empty');
- const filename = file.name || existing.filename;
+ const filename = safeAttachmentFilename(file.name, existing.filename);
const contentType = file.type || 'application/octet-stream';
- await assertUploadAllowed(
- await getStorageSettings(),
- projectId,
- file.size,
- contentType,
- existing.sizeBytes,
- );
+ await assertAttachmentUploadAllowed(projectId, file.size, contentType, existing.sizeBytes);
- const key = attachmentKey(projectId, existing.issueId, filename);
- await storeObject(key, Buffer.from(await file.arrayBuffer()), contentType);
+ const key = attachmentObjectKey(projectId, 'attachments', existing.issueId, filename);
+ await storeAttachmentObject(key, Buffer.from(await file.arrayBuffer()), contentType);
- const row = await replaceAttachmentContent(params.publicId, {
- s3Key: key,
- filename,
- contentType,
- sizeBytes: file.size,
- });
- if (!row) throw new HttpError(404, 'Attachment not found');
+ let replacement;
+ try {
+ replacement = await replaceAttachmentContent(params.publicId, projectId, {
+ s3Key: key,
+ filename,
+ contentType,
+ sizeBytes: file.size,
+ });
+ if (!replacement) throw new HttpError(404, 'Attachment not found');
+ } catch (error) {
+ await deleteAttachmentObject(key);
+ throw error;
+ }
// The row already points at the new object, so a failed delete only
// orphans the old bytes.
- await deleteObject(existing.s3Key).catch((err) => {
- console.error(
- `[planner] failed to delete object ${existing.s3Key}:`,
- err instanceof Error ? err.message : err,
- );
- });
- return attachmentDto(row);
+ await deleteAttachmentObject(replacement.replacedS3Key);
+ return attachmentDto(replacement.attachment);
},
{
body: uploadAttachmentBody,
@@ -309,12 +269,7 @@ export const attachmentRoutes = new Elysia({
await removeAttachmentEmbeds(row.issueId, row.publicId);
// Row is already gone; a failed object delete only orphans bytes, so don't
// fail the request over it.
- await deleteObject(row.s3Key).catch((err) => {
- console.error(
- `[planner] failed to delete object ${row.s3Key}:`,
- err instanceof Error ? err.message : err,
- );
- });
+ await deleteAttachmentObject(row.s3Key);
return noContent();
},
{
@@ -342,7 +297,7 @@ export const attachmentRoutes = new Elysia({
// under a key with a fresh uuid, so a digest of the key changes with the
// bytes. It is the digest, not the key, because this route is public and
// the key carries the project id, the issue id and the stored filename.
- const etag = `"${createHash('sha256').update(row.s3Key).digest('base64url').slice(0, 22)}"`;
+ const etag = attachmentEtag(row.s3Key);
if (request.headers.get('if-none-match') === etag) {
return new Response(null, { status: 304, headers: { ETag: etag } });
}
@@ -360,18 +315,13 @@ export const attachmentRoutes = new Elysia({
// stops MIME sniffing, and inline rendering is allowed only for a strict
// media allowlist (raster images, video, audio). Everything else — html,
// svg, xml, scripts — is forced to download and cannot execute.
- const ct = row.contentType || obj.contentType;
- const inlineSafe = /^(image\/(png|jpe?g|gif|webp|avif|bmp)|video\/|audio\/)/i.test(ct);
- const inline = inlineSafe && query.download == null;
- const headers: Record<string, string> = {
- 'Content-Type': ct,
- 'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(row.filename)}`,
- 'X-Content-Type-Options': 'nosniff',
- 'Cache-Control': 'no-cache',
- ETag: etag,
- };
- if (obj.contentLength != null) headers['Content-Length'] = String(obj.contentLength);
- if (!inline) headers['Content-Security-Policy'] = "default-src 'none'; sandbox";
+ const headers = attachmentResponseHeaders({
+ contentType: row.contentType || obj.contentType,
+ filename: row.filename,
+ contentLength: obj.contentLength,
+ etag,
+ download: query.download != null,
+ });
return new Response(obj.body, { headers });
},
{
diff --git a/apps/api/src/modules/attachments/service.ts b/apps/api/src/modules/attachments/service.ts
index 51e51d96..c2be2a53 100644
--- a/apps/api/src/modules/attachments/service.ts
+++ b/apps/api/src/modules/attachments/service.ts
@@ -1,6 +1,7 @@
import { db, issue, issueAttachment, issueFieldValue } from '@repo/db';
-import { eq, sql } from 'drizzle-orm';
+import { and, eq, sql } from 'drizzle-orm';
import { iso, num } from '#shared/lib';
+import { assertAttachmentStorageCapacity, lockAttachmentStorage } 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
@@ -31,23 +32,28 @@ export function mapAttachment(row: typeof issueAttachment.$inferSelect): Attachm
}
export async function createAttachment(input: {
+ projectId: number;
issueId: number;
s3Key: string;
filename: string;
contentType: string;
sizeBytes: number;
}): Promise<AttachmentRow> {
- const [row] = await db
- .insert(issueAttachment)
- .values({
- issueId: input.issueId,
- s3Key: input.s3Key,
- filename: input.filename,
- contentType: input.contentType,
- sizeBytes: input.sizeBytes,
- })
- .returning();
- return mapAttachment(row);
+ return db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, input.projectId);
+ await assertAttachmentStorageCapacity(input.projectId, input.sizeBytes, 0, tx);
+ const [row] = await tx
+ .insert(issueAttachment)
+ .values({
+ issueId: input.issueId,
+ s3Key: input.s3Key,
+ filename: input.filename,
+ contentType: input.contentType,
+ sizeBytes: input.sizeBytes,
+ })
+ .returning();
+ return mapAttachment(row);
+ });
}
export async function listAttachments(issueId: number): Promise<AttachmentRow[]> {
@@ -83,14 +89,34 @@ export async function getAttachmentByPublicId(publicId: string): Promise<Attachm
// makes editing an attachment in place possible. Returns null if no row matched.
export async function replaceAttachmentContent(
publicId: string,
+ projectId: number,
input: { s3Key: string; filename: string; contentType: string; sizeBytes: number },
-): Promise<AttachmentRow | null> {
- const rows = await db
- .update(issueAttachment)
- .set(input)
- .where(eq(issueAttachment.publicId, publicId))
- .returning();
- return rows[0] ? mapAttachment(rows[0]) : null;
+): Promise<{ attachment: AttachmentRow; replacedS3Key: string } | null> {
+ return db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, projectId);
+ const [current] = await tx
+ .select({ attachment: issueAttachment })
+ .from(issueAttachment)
+ .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
+ .where(and(eq(issueAttachment.publicId, publicId), eq(issue.projectId, projectId)));
+ if (!current) return null;
+ await assertAttachmentStorageCapacity(
+ projectId,
+ input.sizeBytes,
+ num(current.attachment.sizeBytes),
+ tx,
+ );
+ const rows = await tx
+ .update(issueAttachment)
+ .set(input)
+ .where(eq(issueAttachment.id, current.attachment.id))
+ .returning();
+ if (!rows[0]) return null;
+ return {
+ attachment: mapAttachment(rows[0]),
+ replacedS3Key: current.attachment.s3Key,
+ };
+ });
}
// Deletes the row and returns it (with its s3Key) so the caller can remove the
diff --git a/apps/api/src/modules/attachments/storage.ts b/apps/api/src/modules/attachments/storage.ts
new file mode 100644
index 00000000..70619d52
--- /dev/null
+++ b/apps/api/src/modules/attachments/storage.ts
@@ -0,0 +1,184 @@
+import { createHash, randomUUID } from 'node:crypto';
+import {
+ chatAttachment,
+ db,
+ documentAsset,
+ issue,
+ issueAttachment,
+ projectDocument,
+} 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';
+
+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 three 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));
+ return num(issues[0]?.total ?? 0) + num(chats[0]?.total ?? 0) + num(documents[0]?.total ?? 0);
+}
+
+export async function assertAttachmentStorageCapacity(
+ projectId: number,
+ addedBytes: number,
+ replacedBytes = 0,
+ executor: AttachmentStorageExecutor = db,
+): Promise<void> {
+ const limits = await getStorageSettings();
+ if (limits.projectQuotaMb <= 0) return;
+ const used = (await projectStoredBytes(executor, projectId)) - replacedBytes;
+ if (used + addedBytes > limits.projectQuotaMb * MB) {
+ throw new HttpError(
+ 413,
+ `The project has used its ${limits.projectQuotaMb} MB storage quota. Delete attachments to free space.`,
+ );
+ }
+}
+
+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,
+ contentType: string,
+ replacedBytes = 0,
+): Promise<void> {
+ await assertAttachmentFileAllowed(size, contentType);
+ await assertAttachmentStorageCapacity(projectId, size, replacedBytes);
+}
+
+export async function assertAttachmentFileAllowed(
+ size: number,
+ contentType: string,
+): Promise<void> {
+ const limits = await getStorageSettings();
+ if (size > limits.maxAttachmentMb * MB) {
+ throw new HttpError(413, `File exceeds the ${limits.maxAttachmentMb} MB limit`);
+ }
+ if (!mimeAllowed(contentType, limits.attachmentMimeTypes)) {
+ throw new HttpError(400, `Files of type "${contentType}" are not accepted on this instance`);
+ }
+}
+
+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',
+ 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,
+ contentType: string,
+): Promise<void> {
+ try {
+ await putObject(key, bytes, contentType);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(
+ `[planner] object store PUT failed (bucket=${process.env.S3_BUCKET}, key=${key}, size=${bytes.length}):`,
+ error,
+ );
+ throw new HttpError(502, `Object store error: ${message}`);
+ }
+}
+
+export async function cloneAttachmentObject(
+ sourceKey: string,
+ targetKey: string,
+ contentType: string,
+): Promise<void> {
+ const source = await getObject(sourceKey).catch((error) => {
+ throw new HttpError(
+ 502,
+ `Could not read the source asset: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
+ const bytes = Buffer.from(await new Response(source.body).arrayBuffer());
+ await storeAttachmentObject(targetKey, bytes, contentType || source.contentType);
+}
+
+export async function deleteAttachmentObject(key: string): Promise<void> {
+ await deleteObject(key).catch((error) => {
+ console.error(
+ `[planner] failed to delete object ${key}:`,
+ error instanceof Error ? error.message : error,
+ );
+ });
+}
+
+export function attachmentEtag(s3Key: string): string {
+ return `"${createHash('sha256').update(s3Key).digest('base64url').slice(0, 22)}"`;
+}
+
+export function attachmentResponseHeaders(input: {
+ contentType: string;
+ filename: string;
+ contentLength?: number;
+ etag: string;
+ download: boolean;
+}): Record<string, string> {
+ const inlineSafe = /^(image\/(png|jpe?g|gif|webp|avif|bmp)|video\/|audio\/)/i.test(
+ input.contentType,
+ );
+ const inline = inlineSafe && !input.download;
+ const headers: Record<string, string> = {
+ 'Content-Type': input.contentType,
+ 'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(input.filename)}`,
+ 'X-Content-Type-Options': 'nosniff',
+ 'Cache-Control': 'private, no-cache',
+ ETag: input.etag,
+ };
+ if (input.contentLength !== undefined) headers['Content-Length'] = String(input.contentLength);
+ if (!inline) headers['Content-Security-Policy'] = "default-src 'none'; sandbox";
+ return headers;
+}
diff --git a/apps/api/src/modules/chat-attachments/index.ts b/apps/api/src/modules/chat-attachments/index.ts
index f83d8a1c..1ef0fc15 100644
--- a/apps/api/src/modules/chat-attachments/index.ts
+++ b/apps/api/src/modules/chat-attachments/index.ts
@@ -1,19 +1,19 @@
import { Elysia } from 'elysia';
-import { randomUUID, createHash } from 'node:crypto';
import { authContext } from '#shared/auth-context';
import { guards, entityGuard } from '#shared/guards';
import { HttpError } from '#shared/lib';
-import { putObject, getObject } from '#shared/s3';
+import { getObject } from '#shared/s3';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { requireUser } from '#shared/access';
import {
- getStorageSettings,
- mimeAllowed,
- MB,
- type StorageSettings,
-} from '#modules/settings/service';
-import { getProjectAttachmentBytes } from '#modules/attachments/service';
+ assertAttachmentUploadAllowed,
+ attachmentEtag,
+ attachmentObjectKey,
+ deleteAttachmentObject,
+ safeAttachmentFilename,
+ storeAttachmentObject,
+} from '#modules/attachments/storage';
import {
ChatAttachmentContentResponse,
ChatAttachmentResponse,
@@ -27,7 +27,6 @@ import {
createChatAttachment,
getChatAttachmentByPublicId,
getChatAttachmentProjectId,
- getProjectChatAttachmentBytes,
readChatAttachmentContent,
type ChatAttachmentRow,
} from './service';
@@ -37,33 +36,6 @@ import {
// file and read one back; the download route is public, like an issue
// attachment's, so the link a chat message renders works for anyone viewing it.
-// The upload limits are instance settings, read per request. The quota counts
-// both issue and chat attachments, the two tenants of a project's stored bytes.
-async function assertUploadAllowed(
- limits: StorageSettings,
- projectId: number,
- size: number,
- contentType: string,
-): Promise<void> {
- if (size > limits.maxAttachmentMb * MB) {
- throw new HttpError(413, `File exceeds the ${limits.maxAttachmentMb} MB limit`);
- }
- if (!mimeAllowed(contentType, limits.attachmentMimeTypes)) {
- throw new HttpError(400, `Files of type "${contentType}" are not accepted on this instance`);
- }
- if (limits.projectQuotaMb > 0) {
- const used =
- (await getProjectAttachmentBytes(projectId)) +
- (await getProjectChatAttachmentBytes(projectId));
- if (used + size > limits.projectQuotaMb * MB) {
- throw new HttpError(
- 413,
- `The project has used its ${limits.projectQuotaMb} MB storage quota. Delete attachments to free space.`,
- );
- }
- }
-}
-
// A browser reports no type for a .md or .txt file on some platforms, and the
// instance allowlist matches on the type, so the extension answers for it.
const EXTENSION_TYPES: Record<string, string> = {
@@ -75,11 +47,6 @@ const EXTENSION_TYPES: Record<string, string> = {
// the bucket, which is what makes per-project listing, cleanup, and policies
// possible. The original filename stays the last key segment so the extension is
// visible in the bucket.
-function chatAttachmentKey(projectId: number, filename: string): string {
- const safeName = filename.replace(/[^\w.-]+/g, '_').slice(-100);
- return `projects/${projectId}/chat/${randomUUID()}-${safeName}`;
-}
-
// Public shape: never exposes the internal serial id or the object key. `url` is
// the public, no-auth download route.
function chatAttachmentDto(a: ChatAttachmentRow) {
@@ -114,11 +81,11 @@ export const chatAttachmentRoutes = new Elysia({
if (bytes.length === 0) {
throw new HttpError(400, 'contentBase64 is empty or not valid base64');
}
- let filename = body.filename;
+ let filename = safeAttachmentFilename(body.filename);
const extension = filename.toLowerCase().split('.').pop() ?? '';
let contentType =
body.contentType || EXTENSION_TYPES[extension] || 'application/octet-stream';
- await assertUploadAllowed(await getStorageSettings(), project.id, bytes.length, contentType);
+ await assertAttachmentUploadAllowed(project.id, bytes.length, contentType);
// A PDF is stored as the Markdown it converts to: the original is
// discarded, so the row, the download link, and the agent all see text.
@@ -127,23 +94,26 @@ export const chatAttachmentRoutes = new Elysia({
content = Buffer.from(await pdfToMarkdown(bytes), 'utf8');
filename = filename.replace(/\.pdf$/i, '') + '.md';
contentType = 'text/markdown';
+ await assertAttachmentUploadAllowed(project.id, content.length, contentType);
}
- const key = chatAttachmentKey(project.id, filename);
+ const key = attachmentObjectKey(project.id, 'chat', null, filename);
+ await storeAttachmentObject(key, content, contentType);
+
+ let row;
try {
- await putObject(key, content, contentType);
- } catch (err) {
- throw new HttpError(502, `Object store error: ${err instanceof Error ? err.message : err}`);
+ row = await createChatAttachment({
+ projectId: project.id,
+ uploadedByUserId: requireUser(user).id,
+ s3Key: key,
+ filename,
+ contentType,
+ sizeBytes: content.length,
+ });
+ } catch (error) {
+ await deleteAttachmentObject(key);
+ throw error;
}
-
- const row = await createChatAttachment({
- projectId: project.id,
- uploadedByUserId: requireUser(user).id,
- s3Key: key,
- filename,
- contentType,
- sizeBytes: content.length,
- });
set.status = 201;
return chatAttachmentDto(row);
},
@@ -203,7 +173,7 @@ export const chatAttachmentRoutes = new Elysia({
// The etag is a digest of the key rather than the key itself: this route is
// public, and the key carries the project id and the stored filename.
- const etag = `"${createHash('sha256').update(row.s3Key).digest('base64url').slice(0, 22)}"`;
+ const etag = attachmentEtag(row.s3Key);
if (request.headers.get('if-none-match') === etag) {
return new Response(null, { status: 304, headers: { ETag: etag } });
}
diff --git a/apps/api/src/modules/chat-attachments/service.ts b/apps/api/src/modules/chat-attachments/service.ts
index a9452999..be86be12 100644
--- a/apps/api/src/modules/chat-attachments/service.ts
+++ b/apps/api/src/modules/chat-attachments/service.ts
@@ -3,6 +3,10 @@ import { eq, sql } from 'drizzle-orm';
import { HttpError, iso, num } from '#shared/lib';
import { getObject } from '#shared/s3';
import { isTableFilename, parseImportFile } from './parse';
+import {
+ assertAttachmentStorageCapacity,
+ lockAttachmentStorage,
+} 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
@@ -43,8 +47,12 @@ export async function createChatAttachment(input: {
contentType: string;
sizeBytes: number;
}): Promise<ChatAttachmentRow> {
- const [row] = await db.insert(chatAttachment).values(input).returning();
- return mapRow(row);
+ return db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, input.projectId);
+ await assertAttachmentStorageCapacity(input.projectId, input.sizeBytes, 0, tx);
+ const [row] = await tx.insert(chatAttachment).values(input).returning();
+ return mapRow(row);
+ });
}
export async function getChatAttachmentByPublicId(
diff --git a/apps/api/src/modules/documents/__tests__/integration/assets.test.ts b/apps/api/src/modules/documents/__tests__/integration/assets.test.ts
new file mode 100644
index 00000000..34759143
--- /dev/null
+++ b/apps/api/src/modules/documents/__tests__/integration/assets.test.ts
@@ -0,0 +1,297 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { api, authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+type Client = ReturnType<typeof authedApi>;
+
+async function setupProject() {
+ const owner = await signUpTestUser();
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { asOwner, owner };
+}
+
+async function addMember(owner: Client, roleId?: number) {
+ const user = await signUpTestUser();
+ const invite = await owner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: user.email, role: 'member' });
+ const client = authedApi(user.cookie);
+ await client.invites({ token: invite.data!.token }).accept.post();
+ if (roleId != null) {
+ await owner
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: user.userId })
+ .patch({ role: 'member', roleId });
+ }
+ return { client, user };
+}
+
+function documents(client: Client, projectKey = 'MKT') {
+ return client.projects({ projectKey }).documents;
+}
+
+function upload(client: Client, documentId: number, filename = 'diagram.png', type = 'image/png') {
+ return documents(client)({ documentId }).assets.post({
+ file: new File(['asset bytes'], filename, { type }),
+ });
+}
+
+describe('document assets', () => {
+ beforeEach(resetDb);
+
+ it('uploads, lists, securely downloads, and deletes an asset', async () => {
+ const { asOwner } = await setupProject();
+ const page = (await documents(asOwner).post({ title: 'Guide' })).data!;
+ const uploaded = await upload(asOwner, page.id, '../unsafe.svg', 'image/svg+xml');
+ expect(uploaded.status).toBe(201);
+ expect(uploaded.data).toMatchObject({
+ filename: 'unsafe.svg',
+ contentType: 'image/svg+xml',
+ sizeBytes: 11,
+ });
+ expect(uploaded.data!.url).toBe(
+ `/projects/MKT/documents/${page.id}/assets/${uploaded.data!.id}/raw`,
+ );
+ expect(uploaded.data).not.toHaveProperty('s3Key');
+
+ const list = await documents(asOwner)({ documentId: page.id }).assets.get();
+ expect(list.data?.map((asset) => asset.id)).toEqual([uploaded.data!.id]);
+
+ const raw = await documents(asOwner)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get();
+ expect(raw.status).toBe(200);
+ expect(String(raw.data)).toBe('asset bytes');
+ expect(raw.response.headers.get('content-disposition')).toContain('attachment');
+ expect(raw.response.headers.get('x-content-type-options')).toBe('nosniff');
+ expect(raw.response.headers.get('content-security-policy')).toContain('sandbox');
+ expect(raw.response.headers.get('cache-control')).toContain('private');
+
+ const anonymous = await api
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get();
+ expect(anonymous.status).toBe(401);
+
+ expect(
+ (
+ await documents(asOwner)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .delete()
+ ).status,
+ ).toBe(204);
+ expect(
+ (
+ await documents(asOwner)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get()
+ ).status,
+ ).toBe(404);
+ });
+
+ it('keeps private assets owner-only without leaking page or asset existence', async () => {
+ const { asOwner } = await setupProject();
+ const member = await addMember(asOwner);
+ const page = (await documents(asOwner).post({ title: 'Secret', isPrivate: true })).data!;
+ const uploaded = await upload(asOwner, page.id);
+
+ expect((await documents(member.client)({ documentId: page.id }).assets.get()).status).toBe(404);
+ expect((await upload(member.client, page.id)).status).toBe(404);
+ expect(
+ (
+ await documents(member.client)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get()
+ ).status,
+ ).toBe(404);
+ expect(
+ (
+ await documents(member.client)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .delete()
+ ).status,
+ ).toBe(404);
+ });
+
+ it('uses project permissions and refuses writes to locked or archived pages', async () => {
+ const { asOwner } = await setupProject();
+ const page = (await documents(asOwner).post({ title: 'Public' })).data!;
+ const uploaded = await upload(asOwner, page.id);
+ const member = await addMember(asOwner);
+ expect(
+ (
+ await documents(member.client)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .delete()
+ ).status,
+ ).toBe(403);
+
+ const memberPage = (await documents(member.client).post({ title: 'Member page' })).data!;
+ const memberAsset = await upload(member.client, memberPage.id, 'member.png');
+ expect(
+ (
+ await documents(asOwner)({ documentId: memberPage.id })
+ .assets({ publicId: memberAsset.data!.id })
+ .delete()
+ ).status,
+ ).toBe(204);
+
+ const readerRole = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .roles.post({ name: 'Reader', permissions: { documents: { read: true } } });
+ const reader = await addMember(asOwner, readerRole.data!.id);
+
+ expect((await documents(reader.client)({ documentId: page.id }).assets.get()).status).toBe(200);
+ expect(
+ (
+ await documents(reader.client)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get()
+ ).status,
+ ).toBe(200);
+ expect((await upload(reader.client, page.id)).status).toBe(403);
+ expect(
+ (
+ await documents(reader.client)({ documentId: page.id })
+ .assets({ publicId: uploaded.data!.id })
+ .delete()
+ ).status,
+ ).toBe(403);
+
+ const editorRole = await asOwner.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'Docs editor',
+ permissions: { documents: { read: true, edit: true } },
+ });
+ const editor = await addMember(asOwner, editorRole.data!.id);
+ const editorAsset = await upload(editor.client, page.id, 'editor.png');
+ expect(editorAsset.status).toBe(201);
+ expect(
+ (
+ await documents(editor.client)({ documentId: page.id })
+ .assets({ publicId: editorAsset.data!.id })
+ .delete()
+ ).status,
+ ).toBe(403);
+
+ const locked = await documents(asOwner)({ documentId: page.id }).lock.post({ version: 1 });
+ expect((await upload(asOwner, page.id)).status).toBe(409);
+ const unlocked = await documents(asOwner)({ documentId: page.id }).unlock.post({
+ version: locked.data!.version,
+ });
+ await documents(asOwner)({ documentId: page.id }).archive.post({
+ version: unlocked.data!.version,
+ });
+ expect((await upload(asOwner, page.id)).status).toBe(409);
+ });
+
+ it('rejects empty uploads and cross-document asset ids', async () => {
+ const { asOwner } = await setupProject();
+ const first = (await documents(asOwner).post({ title: 'First' })).data!;
+ const second = (await documents(asOwner).post({ title: 'Second' })).data!;
+ expect(
+ (
+ await documents(asOwner)({ documentId: first.id }).assets.post({
+ file: new File([], 'empty.txt', { type: 'text/plain' }),
+ })
+ ).status,
+ ).toBe(400);
+ const uploaded = await upload(asOwner, first.id);
+ expect(
+ (
+ await documents(asOwner)({ documentId: second.id })
+ .assets({ publicId: uploaded.data!.id })
+ .raw.get()
+ ).status,
+ ).toBe(404);
+ });
+
+ it('clones asset bytes and rewrites Markdown and JSON when duplicating a page', async () => {
+ const { asOwner } = await setupProject();
+ const page = (await documents(asOwner).post({ title: 'Source' })).data!;
+ const asset = await upload(asOwner, page.id);
+ const sourceUrl = asset.data!.url;
+ const mediaUrl = `/protected-media${sourceUrl}`;
+ const updated = await documents(asOwner)({ documentId: page.id }).patch({
+ version: 1,
+ content: `![diagram](${mediaUrl})`,
+ contentJson: {
+ type: 'doc',
+ content: [{ type: 'image', attrs: { src: mediaUrl } }],
+ },
+ });
+ const duplicate = await documents(asOwner)({ documentId: page.id }).duplicate.post({
+ version: updated.data!.version,
+ });
+ expect(duplicate.status).toBe(201);
+ expect(duplicate.data!.content).not.toContain(mediaUrl);
+ expect(JSON.stringify(duplicate.data!.contentJson)).not.toContain(mediaUrl);
+ const copiedAssets = await documents(asOwner)({ documentId: duplicate.data!.id }).assets.get();
+ expect(copiedAssets.data).toHaveLength(1);
+ expect(duplicate.data!.content).toContain(`/protected-media${copiedAssets.data![0].url}`);
+
+ const archived = await documents(asOwner)({ documentId: page.id }).archive.post({
+ version: updated.data!.version,
+ });
+ await documents(asOwner)({ documentId: page.id }).delete(
+ {},
+ { query: { version: archived.data!.version } },
+ );
+ const rawCopy = await documents(asOwner)({ documentId: duplicate.data!.id })
+ .assets({ publicId: copiedAssets.data![0].id })
+ .raw.get();
+ expect(String(rawCopy.data)).toBe('asset bytes');
+ });
+
+ it('copies assets and embedded URLs with the project', async () => {
+ const { asOwner } = await setupProject();
+ const page = (await documents(asOwner).post({ title: 'Source' })).data!;
+ const asset = await upload(asOwner, page.id);
+ const mediaUrl = `/protected-media${asset.data!.url}`;
+ await documents(asOwner)({ documentId: page.id }).patch({
+ version: 1,
+ content: `![diagram](${mediaUrl})`,
+ contentJson: { type: 'doc', content: [{ type: 'text', text: mediaUrl }] },
+ });
+ expect(
+ (await asOwner.projects({ projectKey: 'MKT' }).copy.post({ key: 'CPY', name: 'Copy' }))
+ .status,
+ ).toBe(201);
+ const copiedPage = (await documents(asOwner, 'CPY').get({ query: {} })).data![0];
+ const copied = await documents(asOwner, 'CPY')({ documentId: copiedPage.id }).get();
+ const copiedAssets = await documents(
+ asOwner,
+ 'CPY',
+ )({ documentId: copiedPage.id }).assets.get();
+ expect(copiedAssets.data).toHaveLength(1);
+ expect(copied.data!.content).toContain(`/protected-media${copiedAssets.data![0].url}`);
+ expect(copied.data!.content).not.toContain(mediaUrl);
+ expect(JSON.stringify(copied.data!.contentJson)).toContain(
+ `/protected-media${copiedAssets.data![0].url}`,
+ );
+ });
+
+ it('removes asset access when an archived page is permanently deleted', async () => {
+ const { asOwner } = await setupProject();
+ const page = (await documents(asOwner).post({ title: 'Disposable' })).data!;
+ const asset = await upload(asOwner, page.id);
+ const archived = await documents(asOwner)({ documentId: page.id }).archive.post({ version: 1 });
+ expect(
+ (
+ await documents(asOwner)({ documentId: page.id }).delete(
+ {},
+ { query: { version: archived.data!.version } },
+ )
+ ).status,
+ ).toBe(204);
+ expect(
+ (
+ await documents(asOwner)({ documentId: page.id })
+ .assets({ publicId: asset.data!.id })
+ .raw.get()
+ ).status,
+ ).toBe(404);
+ });
+});
diff --git a/apps/api/src/modules/documents/__tests__/integration/documents.test.ts b/apps/api/src/modules/documents/__tests__/integration/documents.test.ts
new file mode 100644
index 00000000..45bfd915
--- /dev/null
+++ b/apps/api/src/modules/documents/__tests__/integration/documents.test.ts
@@ -0,0 +1,1386 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+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 };
+}
+
+async function addMember(owner: Client, roleId?: number): Promise<{ api: Client; userId: string }> {
+ 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 (roleId != null) {
+ await owner
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: user.userId })
+ .patch({ role: 'member', roleId });
+ }
+ return { api, userId: user.userId };
+}
+
+function documents(api: Client, projectKey = 'MKT') {
+ return api.projects({ projectKey }).documents;
+}
+
+describe('documents', () => {
+ beforeEach(resetDb);
+
+ it('creates, lists, reads, searches, updates, and deletes a document', async () => {
+ const owner = await setupOwnerProject();
+
+ const created = await documents(owner.api).post({ title: 'Release guide' });
+ expect(created.status).toBe(201);
+ expect(created.data).toMatchObject({
+ title: 'Release guide',
+ content: '',
+ parentId: null,
+ version: 1,
+ position: 1024,
+ createdByUserId: owner.userId,
+ updatedByUserId: owner.userId,
+ });
+
+ const documentId = created.data!.id;
+ const updated = await documents(owner.api)({ documentId }).patch({
+ version: 1,
+ title: 'Production release guide',
+ content: '# Deploy\n\nRun the release workflow.',
+ });
+ expect(updated.status).toBe(200);
+ expect(updated.data).toMatchObject({
+ title: 'Production release guide',
+ content: '# Deploy\n\nRun the release workflow.',
+ version: 2,
+ updatedByUserId: owner.userId,
+ });
+
+ const list = await documents(owner.api).get({ query: {} });
+ expect(list.status).toBe(200);
+ expect(list.data).toHaveLength(1);
+ expect(list.data?.[0]).toMatchObject({ id: documentId, version: 2 });
+ expect(list.data?.[0]).not.toHaveProperty('content');
+ expect(list.data?.[0]).not.toHaveProperty('contentJson');
+
+ const byTitle = await documents(owner.api).get({ query: { q: 'production' } });
+ const byContent = await documents(owner.api).get({ query: { q: 'workflow' } });
+ const noMatch = await documents(owner.api).get({ query: { q: 'onboarding' } });
+ expect(byTitle.data?.map((document) => document.id)).toEqual([documentId]);
+ expect(byContent.data?.map((document) => document.id)).toEqual([documentId]);
+ expect(noMatch.data).toEqual([]);
+
+ const read = await documents(owner.api)({ documentId }).get();
+ expect(read.status).toBe(200);
+ expect(read.data).toMatchObject(updated.data!);
+
+ const archived = await documents(owner.api)({ documentId }).archive.post({ version: 2 });
+ expect(archived.status).toBe(200);
+ expect(
+ (
+ await documents(owner.api)({ documentId }).delete(
+ {},
+ { query: { version: archived.data!.version } },
+ )
+ ).status,
+ ).toBe(204);
+ expect((await documents(owner.api)({ documentId }).get()).status).toBe(404);
+ });
+
+ it('builds a tree and rejects self, descendant, and cross-project parents', async () => {
+ const { api } = await setupOwnerProject();
+ const root = (await documents(api).post({ title: 'Root' })).data!;
+ const child = (await documents(api).post({ title: 'Child', parentId: root.id })).data!;
+ const grandchild = (await documents(api).post({ title: 'Grandchild', parentId: child.id }))
+ .data!;
+
+ expect(child.parentId).toBe(root.id);
+ expect(grandchild.parentId).toBe(child.id);
+ expect(
+ (await documents(api)({ documentId: root.id }).patch({ version: 1, parentId: root.id }))
+ .status,
+ ).toBe(400);
+ expect(
+ (await documents(api)({ documentId: root.id }).patch({ version: 1, parentId: grandchild.id }))
+ .status,
+ ).toBe(400);
+
+ await api.projects.post({ key: 'OPS', name: 'Operations' });
+ const other = (await documents(api, 'OPS').post({ title: 'Other' })).data!;
+ expect((await documents(api).post({ title: 'Invalid', parentId: other.id })).status).toBe(400);
+ expect(
+ (await documents(api)({ documentId: child.id }).patch({ version: 1, parentId: other.id }))
+ .status,
+ ).toBe(400);
+
+ const list = await documents(api).get({ query: {} });
+ expect(list.data).toMatchObject([
+ { id: root.id, parentId: null },
+ { id: child.id, parentId: root.id },
+ { id: grandchild.id, parentId: child.id },
+ ]);
+ });
+
+ it('serializes concurrent moves so they cannot create a cycle', async () => {
+ const { api } = await setupOwnerProject();
+ const first = (await documents(api).post({ title: 'First' })).data!;
+ const second = (await documents(api).post({ title: 'Second' })).data!;
+
+ const results = await Promise.all([
+ documents(api)({ documentId: first.id }).patch({ version: 1, parentId: second.id }),
+ documents(api)({ documentId: second.id }).patch({ version: 1, parentId: first.id }),
+ ]);
+ expect(results.map((result) => result.status).sort()).toEqual([200, 400]);
+
+ const currentFirst = (await documents(api)({ documentId: first.id }).get()).data!;
+ const currentSecond = (await documents(api)({ documentId: second.id }).get()).data!;
+ expect(currentFirst.parentId === null || currentSecond.parentId === null).toBe(true);
+ });
+
+ it('rebalances anchored drag positions without midpoint saturation', async () => {
+ const { api } = await setupOwnerProject();
+ const first = (await documents(api).post({ title: 'First' })).data!;
+ const second = (await documents(api).post({ title: 'Second' })).data!;
+ let moving = (await documents(api).post({ title: 'Moving' })).data!;
+
+ for (let index = 0; index < 60; index += 1) {
+ const between = index % 2 === 0;
+ const moved = await documents(api)({ documentId: moving.id }).patch({
+ version: moving.version,
+ parentId: null,
+ position: between ? 1536 : 4096,
+ previousSiblingId: between ? first.id : second.id,
+ nextSiblingId: between ? second.id : null,
+ });
+ expect(moved.status).toBe(200);
+ moving = moved.data!;
+ const ordered = (await documents(api).get({ query: {} })).data!;
+ expect(ordered.map((page) => page.title)).toEqual(
+ between ? ['First', 'Moving', 'Second'] : ['First', 'Second', 'Moving'],
+ );
+ expect(ordered.map((page) => page.position)).toEqual(
+ between ? [1024, 1536, 2048] : [1024, 2048, 3072],
+ );
+ }
+
+ const stable = (await documents(api).get({ query: {} })).data!;
+ expect(stable.every((page) => Number.isFinite(page.position))).toBe(true);
+ expect(stable.find((page) => page.id === first.id)?.version).toBe(1);
+ expect(stable.find((page) => page.id === second.id)?.version).toBe(1);
+ expect(
+ (await documents(api)({ documentId: first.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([1]);
+ expect(
+ (await documents(api)({ documentId: second.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([1]);
+ });
+
+ it('rebalances only when sibling position precision is exhausted', async () => {
+ const { api } = await setupOwnerProject();
+ const first = (await documents(api).post({ title: 'First' })).data!;
+ const second = (await documents(api).post({ title: 'Second' })).data!;
+ const moving = (await documents(api).post({ title: 'Moving' })).data!;
+ const firstTight = await documents(api)({ documentId: first.id }).patch({
+ version: first.version,
+ position: 1,
+ });
+ const secondTight = await documents(api)({ documentId: second.id }).patch({
+ version: second.version,
+ position: 1 + Number.EPSILON,
+ });
+ const historiesBefore = await Promise.all([
+ documents(api)({ documentId: first.id }).revisions.get(),
+ documents(api)({ documentId: second.id }).revisions.get(),
+ ]);
+
+ const moved = await documents(api)({ documentId: moving.id }).patch({
+ version: moving.version,
+ parentId: null,
+ position: 1,
+ previousSiblingId: first.id,
+ nextSiblingId: second.id,
+ });
+ expect(moved.status).toBe(200);
+ const ordered = (await documents(api).get({ query: {} })).data!;
+ expect(ordered.map((page) => page.title)).toEqual(['First', 'Moving', 'Second']);
+ expect(ordered.map((page) => page.position)).toEqual([1024, 2048, 3072]);
+ expect(ordered.find((page) => page.id === first.id)?.version).toBe(firstTight.data!.version);
+ expect(ordered.find((page) => page.id === second.id)?.version).toBe(secondTight.data!.version);
+ const historiesAfter = await Promise.all([
+ documents(api)({ documentId: first.id }).revisions.get(),
+ documents(api)({ documentId: second.id }).revisions.get(),
+ ]);
+ expect(historiesAfter.map((response) => response.data)).toEqual(
+ historiesBefore.map((response) => response.data),
+ );
+ });
+
+ it('serializes anchored and position-only moves without losing a successful write', async () => {
+ const { api } = await setupOwnerProject();
+ const first = (await documents(api).post({ title: 'First' })).data!;
+ const second = (await documents(api).post({ title: 'Second' })).data!;
+ const moving = (await documents(api).post({ title: 'Moving' })).data!;
+
+ const [anchored, rawPosition] = await Promise.all([
+ documents(api)({ documentId: moving.id }).patch({
+ version: moving.version,
+ parentId: null,
+ position: 1536,
+ previousSiblingId: first.id,
+ nextSiblingId: second.id,
+ }),
+ documents(api)({ documentId: moving.id }).patch({
+ version: moving.version,
+ position: 8192,
+ }),
+ ]);
+
+ expect([anchored.status, rawPosition.status].sort()).toEqual([200, 409]);
+ const successful = anchored.status === 200 ? anchored.data! : rawPosition.data!;
+ const current = await documents(api)({ documentId: moving.id }).get();
+ expect(current.data).toMatchObject({
+ version: successful.version,
+ position: successful.position,
+ });
+ expect(current.data?.version).toBe(moving.version + 1);
+ });
+
+ it('rejects a stale update without overwriting the current document', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await documents(api).post({ title: 'Runbook' })).data!;
+
+ const first = await documents(api)({ documentId: created.id }).patch({
+ version: created.version,
+ content: 'Current content',
+ });
+ expect(first.status).toBe(200);
+ expect(first.data?.version).toBe(2);
+
+ const stale = await documents(api)({ documentId: created.id }).patch({
+ version: created.version,
+ content: 'Stale content',
+ });
+ expect(stale.status).toBe(409);
+
+ const read = await documents(api)({ documentId: created.id }).get();
+ expect(read.data).toMatchObject({ content: 'Current content', version: 2 });
+
+ const staleDelete = await documents(api)({ documentId: created.id }).delete(
+ {},
+ {
+ query: { version: created.version },
+ },
+ );
+ expect(staleDelete.status).toBe(409);
+ expect((await documents(api)({ documentId: created.id }).get()).data).toMatchObject({
+ content: 'Current content',
+ version: 2,
+ });
+ });
+
+ it('moves children to the root when their parent is deleted', async () => {
+ const { api } = await setupOwnerProject();
+ const parent = (await documents(api).post({ title: 'Parent' })).data!;
+ const child = (await documents(api).post({ title: 'Child', parentId: parent.id })).data!;
+
+ const archived = await documents(api)({ documentId: parent.id }).archive.post({ version: 1 });
+ expect(archived.status).toBe(200);
+ expect(
+ (
+ await documents(api)({ documentId: parent.id }).delete(
+ {},
+ { query: { version: archived.data!.version } },
+ )
+ ).status,
+ ).toBe(204);
+ expect(await documents(api)({ documentId: child.id }).get()).toMatchObject({
+ status: 200,
+ data: { parentId: null, version: 3 },
+ });
+ });
+
+ it('enforces document permissions for default, read-only, and blocked members', async () => {
+ const owner = await setupOwnerProject();
+ const document = (await documents(owner.api).post({ title: 'Shared' })).data!;
+ const member = await addMember(owner.api);
+
+ const memberDocument = await documents(member.api).post({ title: 'Member page' });
+ expect(memberDocument.status).toBe(201);
+ expect(
+ (
+ await documents(member.api)({ documentId: memberDocument.data!.id }).patch({
+ version: 1,
+ title: 'Member edit',
+ })
+ ).status,
+ ).toBe(200);
+ const archivedMemberDocument = await documents(member.api)({
+ documentId: memberDocument.data!.id,
+ }).archive.post({ version: 2 });
+ expect(archivedMemberDocument.status).toBe(200);
+ expect(
+ (
+ await documents(member.api)({ documentId: memberDocument.data!.id }).delete(
+ {},
+ {
+ query: { version: archivedMemberDocument.data!.version },
+ },
+ )
+ ).status,
+ ).toBe(204);
+
+ const readerRole = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .roles.post({ name: 'Reader', permissions: { documents: { read: true } } });
+ const reader = await addMember(owner.api, readerRole.data!.id);
+ expect((await documents(reader.api).get({ query: {} })).status).toBe(200);
+ expect((await documents(reader.api)({ documentId: document.id }).get()).status).toBe(200);
+ expect((await documents(reader.api).post({ title: 'Nope' })).status).toBe(403);
+ expect(
+ (
+ await documents(reader.api)({ documentId: document.id }).patch({
+ version: document.version,
+ title: 'Nope',
+ })
+ ).status,
+ ).toBe(403);
+ expect(
+ (
+ await documents(reader.api)({ documentId: document.id }).delete(
+ {},
+ {
+ query: { version: document.version },
+ },
+ )
+ ).status,
+ ).toBe(403);
+
+ const blockedRole = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .roles.post({ name: 'No documents', permissions: {} });
+ const blocked = await addMember(owner.api, blockedRole.data!.id);
+ expect((await documents(blocked.api).get({ query: {} })).status).toBe(403);
+ expect((await documents(blocked.api)({ documentId: document.id }).get()).status).toBe(403);
+ });
+
+ it('links visible Docs and work items in both directions with combined permissions', async () => {
+ const owner = await setupOwnerProject();
+ const project = await owner.api.projects({ projectKey: 'MKT' }).get();
+ const workItem = (
+ await owner.api
+ .projects({ projectKey: 'MKT' })
+ .issues.post({ columnId: project.data!.columns[0]!.id, title: 'Ship release' })
+ ).data!;
+ const page = (await documents(owner.api).post({ title: 'Release guide' })).data!;
+
+ const linked = await documents(owner.api)({ documentId: page.id }).issues.post({
+ issueId: workItem.id,
+ });
+ expect(linked.status).toBe(201);
+ expect(linked.data).toMatchObject({
+ issueId: workItem.id,
+ identifier: 'MKT-1',
+ title: 'Ship release',
+ });
+ expect((await documents(owner.api)({ documentId: page.id }).issues.get()).data).toMatchObject([
+ { issueId: workItem.id, identifier: 'MKT-1' },
+ ]);
+ expect(
+ (await documents(owner.api)['for-issue']({ issueId: workItem.id }).get()).data,
+ ).toMatchObject([{ documentId: page.id, title: 'Release guide' }]);
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id })
+ .issues({ issueId: workItem.id })
+ .delete()
+ ).status,
+ ).toBe(204);
+
+ const readerRole = await owner.api.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'Context reader',
+ permissions: { documents: { read: true }, work_items: { read: true } },
+ });
+ const reader = await addMember(owner.api, readerRole.data!.id);
+ expect((await documents(reader.api)({ documentId: page.id }).issues.get()).status).toBe(200);
+ expect(
+ (
+ await documents(reader.api)({ documentId: page.id }).issues.post({
+ issueId: workItem.id,
+ })
+ ).status,
+ ).toBe(403);
+
+ const privatePage = (await documents(owner.api).post({ title: 'Owner notes', isPrivate: true }))
+ .data!;
+ await documents(owner.api)({ documentId: privatePage.id }).issues.post({
+ issueId: workItem.id,
+ });
+ expect((await documents(reader.api)['for-issue']({ issueId: workItem.id }).get()).data).toEqual(
+ [],
+ );
+ });
+
+ it('limits permanent deletion to the page owner or a project owner for public pages', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+
+ const ownerPage = (await documents(owner.api).post({ title: 'Owner page' })).data!;
+ const archivedOwnerPage = await documents(owner.api)({
+ documentId: ownerPage.id,
+ }).archive.post({ version: ownerPage.version });
+ expect(
+ (
+ await documents(member.api)({ documentId: ownerPage.id }).delete(
+ {},
+ { query: { version: archivedOwnerPage.data!.version } },
+ )
+ ).status,
+ ).toBe(403);
+ expect(
+ (
+ await documents(owner.api)({ documentId: ownerPage.id }).delete(
+ {},
+ { query: { version: archivedOwnerPage.data!.version } },
+ )
+ ).status,
+ ).toBe(204);
+
+ const memberPage = (await documents(member.api).post({ title: 'Member public page' })).data!;
+ const archivedMemberPage = await documents(member.api)({
+ documentId: memberPage.id,
+ }).archive.post({ version: memberPage.version });
+ expect(
+ (
+ await documents(owner.api)({ documentId: memberPage.id }).delete(
+ {},
+ { query: { version: archivedMemberPage.data!.version } },
+ )
+ ).status,
+ ).toBe(204);
+
+ const privatePage = (
+ await documents(member.api).post({ title: 'Member private page', isPrivate: true })
+ ).data!;
+ const archivedPrivatePage = await documents(member.api)({
+ documentId: privatePage.id,
+ }).archive.post({ version: privatePage.version });
+ expect(
+ (
+ await documents(owner.api)({ documentId: privatePage.id }).delete(
+ {},
+ { query: { version: archivedPrivatePage.data!.version } },
+ )
+ ).status,
+ ).toBe(404);
+ });
+
+ it('denies an outsider and hides documents that belong to another project', async () => {
+ const owner = await setupOwnerProject();
+ const document = (await documents(owner.api).post({ title: 'Private' })).data!;
+ const outsider = authedApi((await signUpTestUser()).cookie);
+
+ expect((await documents(outsider).get({ query: {} })).status).toBe(403);
+ expect((await documents(outsider)({ documentId: document.id }).get()).status).toBe(403);
+
+ await owner.api.projects.post({ key: 'OPS', name: 'Operations' });
+ expect((await documents(owner.api, 'OPS')({ documentId: document.id }).get()).status).toBe(404);
+ });
+
+ it('validates document fields and returns 404 for missing documents', async () => {
+ const { api } = await setupOwnerProject();
+ expect((await documents(api).post({ title: 'x'.repeat(256) })).status).toBe(400);
+ expect(
+ (
+ await documents(api).post({
+ title: 'Oversized metadata',
+ metadata: { value: 'x'.repeat(17_000) },
+ })
+ ).status,
+ ).toBe(400);
+ expect((await documents(api).post({ title: 'Invalid', parentId: 999_999 })).status).toBe(400);
+ const document = (await documents(api).post({ title: 'Valid' })).data!;
+ expect(
+ (
+ await documents(api)({ documentId: document.id }).patch({
+ version: 0,
+ title: 'Invalid',
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (await documents(api)({ documentId: 999_999 }).patch({ version: 1, title: 'Missing' }))
+ .status,
+ ).toBe(404);
+ expect(
+ (await documents(api)({ documentId: 999_999 }).delete({}, { query: { version: 1 } })).status,
+ ).toBe(404);
+ });
+
+ it('copies document content and remaps the document tree', async () => {
+ const { api } = await setupOwnerProject();
+ const root = (await documents(api).post({ title: 'Runbook' })).data!;
+ await documents(api)({ documentId: root.id }).patch({
+ version: root.version,
+ content: 'Source content',
+ });
+ const child = (await documents(api).post({ title: 'Deploy', parentId: root.id })).data!;
+
+ expect(
+ (await api.projects({ projectKey: 'MKT' }).copy.post({ key: 'CPY', name: 'Copy' })).status,
+ ).toBe(201);
+ const copied = await documents(api, 'CPY').get({ query: {} });
+ expect(copied.status).toBe(200);
+ expect(copied.data).toHaveLength(2);
+ const copiedRoot = copied.data!.find((document) => document.title === 'Runbook')!;
+ const copiedChild = copied.data!.find((document) => document.title === 'Deploy')!;
+ expect(copiedRoot.id).not.toBe(root.id);
+ expect(copiedChild.id).not.toBe(child.id);
+ expect(copiedChild.parentId).toBe(copiedRoot.id);
+ expect((await documents(api, 'CPY')({ documentId: copiedRoot.id }).get()).data).toMatchObject({
+ content: 'Source content',
+ version: 1,
+ });
+ const copiedChildHistory = await documents(
+ api,
+ 'CPY',
+ )({
+ documentId: copiedChild.id,
+ }).revisions.get();
+ expect(copiedChildHistory.data?.map((revision) => revision.version)).toEqual([1]);
+ expect(
+ (
+ await documents(
+ api,
+ 'CPY',
+ )({ documentId: copiedChild.id })
+ .revisions({ revisionId: copiedChildHistory.data![0]!.id })
+ .get()
+ ).data?.parentId,
+ ).toBe(copiedRoot.id);
+ });
+
+ it('stores every revision and restores history as a new optimistic version', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (
+ await documents(api).post({
+ title: 'Runbook',
+ content: 'Version one',
+ icon: '📘',
+ metadata: { audience: 'ops' },
+ fullWidth: true,
+ })
+ ).data!;
+ const updated = await documents(api)({ documentId: created.id }).patch({
+ version: 1,
+ title: 'Release runbook',
+ content: 'Version two',
+ metadata: { audience: 'engineering' },
+ });
+ expect(updated.status).toBe(200);
+
+ const revisions = await documents(api)({ documentId: created.id }).revisions.get();
+ expect(revisions.status).toBe(200);
+ expect(revisions.data?.map((revision) => revision.version)).toEqual([2, 1]);
+ const firstRevision = revisions.data!.find((revision) => revision.version === 1)!;
+ const snapshot = await documents(api)({ documentId: created.id })
+ .revisions({ revisionId: firstRevision.id })
+ .get();
+ expect(snapshot.data).toMatchObject({
+ title: 'Runbook',
+ content: 'Version one',
+ metadata: { audience: 'ops' },
+ fullWidth: true,
+ });
+
+ const restored = await documents(api)({ documentId: created.id })
+ .revisions({ revisionId: firstRevision.id })
+ .restore.post({ version: 2 });
+ expect(restored.status).toBe(200);
+ expect(restored.data).toMatchObject({
+ title: 'Runbook',
+ content: 'Version one',
+ version: 3,
+ });
+ expect(
+ (
+ await documents(api)({ documentId: created.id })
+ .revisions({ revisionId: firstRevision.id })
+ .restore.post({ version: 2 })
+ ).status,
+ ).toBe(409);
+ expect(
+ (await documents(api)({ documentId: created.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([3, 2, 1]);
+ });
+
+ it('archives a tree and restores a child at the root when its parent stays archived', async () => {
+ const { api } = await setupOwnerProject();
+ const root = (await documents(api).post({ title: 'Root' })).data!;
+ const child = (await documents(api).post({ title: 'Child', parentId: root.id })).data!;
+ const grandchild = (await documents(api).post({ title: 'Grandchild', parentId: child.id }))
+ .data!;
+
+ const archived = await documents(api)({ documentId: root.id }).archive.post({ version: 1 });
+ expect(archived.status).toBe(200);
+ expect(archived.data).toMatchObject({ archivedAt: expect.any(Date), version: 2 });
+ expect((await documents(api).get({ query: {} })).data).toEqual([]);
+ expect(
+ (await documents(api).get({ query: { archived: 'true' } })).data?.map(
+ (document) => document.id,
+ ),
+ ).toEqual([root.id, child.id, grandchild.id]);
+ expect((await documents(api).post({ title: 'Invalid', parentId: root.id })).status).toBe(400);
+
+ const restored = await documents(api)({ documentId: child.id }).restore.post({ version: 2 });
+ expect(restored.status).toBe(200);
+ expect(restored.data).toMatchObject({ parentId: null, archivedAt: null, version: 3 });
+ expect((await documents(api)({ documentId: grandchild.id }).get()).data).toMatchObject({
+ parentId: child.id,
+ archivedAt: null,
+ version: 3,
+ });
+ expect((await documents(api)({ documentId: root.id }).get()).data?.archivedAt).not.toBeNull();
+ });
+
+ it('restores only descendants archived by the same tree operation', async () => {
+ const { api } = await setupOwnerProject();
+ const root = (await documents(api).post({ title: 'Root' })).data!;
+ const independentlyArchived = (
+ await documents(api).post({ title: 'Independent', parentId: root.id })
+ ).data!;
+ const independentChild = (
+ await documents(api).post({ title: 'Independent child', parentId: independentlyArchived.id })
+ ).data!;
+ const cascaded = (await documents(api).post({ title: 'Cascaded', parentId: root.id })).data!;
+
+ const archivedIndependent = await documents(api)({
+ documentId: independentlyArchived.id,
+ }).archive.post({ version: independentlyArchived.version });
+ expect(archivedIndependent.status).toBe(200);
+ const archivedRoot = await documents(api)({ documentId: root.id }).archive.post({
+ version: root.version,
+ });
+ const restoredRoot = await documents(api)({ documentId: root.id }).restore.post({
+ version: archivedRoot.data!.version,
+ });
+
+ expect(restoredRoot.status).toBe(200);
+ expect((await documents(api)({ documentId: cascaded.id }).get()).data).toMatchObject({
+ archivedAt: null,
+ parentId: root.id,
+ });
+ expect(
+ (await documents(api)({ documentId: independentlyArchived.id }).get()).data?.archivedAt,
+ ).not.toBeNull();
+ expect(
+ (await documents(api)({ documentId: independentChild.id }).get()).data?.archivedAt,
+ ).not.toBeNull();
+ });
+
+ it('uses optimistic versions for archive, restore, and permanent delete', async () => {
+ const { api } = await setupOwnerProject();
+ const page = (await documents(api).post({ title: 'Lifecycle' })).data!;
+ const updated = await documents(api)({ documentId: page.id }).patch({
+ version: 1,
+ content: 'Current',
+ });
+ expect(
+ (
+ await documents(api)({ documentId: page.id }).archive.post({
+ version: 1,
+ })
+ ).status,
+ ).toBe(409);
+ const archived = await documents(api)({ documentId: page.id }).archive.post({ version: 2 });
+ expect(archived.data?.version).toBe(3);
+ expect(
+ (
+ await documents(api)({ documentId: page.id }).restore.post({
+ version: 2,
+ })
+ ).status,
+ ).toBe(409);
+ const restored = await documents(api)({ documentId: page.id }).restore.post({ version: 3 });
+ expect(restored.data?.version).toBe(4);
+ expect(
+ (
+ await documents(api)({ documentId: page.id }).delete(
+ {},
+ { query: { version: restored.data!.version } },
+ )
+ ).status,
+ ).toBe(409);
+ expect(updated.data?.content).toBe('Current');
+ });
+
+ it('does not archive a private descendant that the page owner cannot see', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const root = (await documents(owner.api).post({ title: 'Shared root' })).data!;
+ const privateChild = (
+ await documents(member.api).post({
+ title: 'Member private child',
+ parentId: root.id,
+ isPrivate: true,
+ })
+ ).data!;
+
+ expect(
+ (
+ await documents(owner.api)({ documentId: root.id }).archive.post({
+ version: root.version,
+ })
+ ).status,
+ ).toBe(200);
+ expect((await documents(owner.api)({ documentId: privateChild.id }).get()).status).toBe(404);
+ expect((await documents(member.api)({ documentId: privateChild.id }).get()).data).toMatchObject(
+ {
+ archivedAt: null,
+ parentId: root.id,
+ },
+ );
+ expect((await documents(member.api).get({ query: {} })).data).toMatchObject([
+ { id: privateChild.id, parentId: null },
+ ]);
+ });
+
+ it('keeps private pages owner-only without leaking their existence', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const page = (
+ await documents(owner.api).post({
+ title: 'Private plan',
+ content: 'Secret',
+ isPrivate: true,
+ })
+ ).data!;
+ expect(page).toMatchObject({ isPrivate: true, ownerUserId: owner.userId });
+ expect((await documents(member.api).get({ query: {} })).data).toEqual([]);
+ expect((await documents(member.api)({ documentId: page.id }).get()).status).toBe(404);
+ expect(
+ (
+ await documents(member.api)({ documentId: page.id }).duplicate.post({
+ version: page.version,
+ })
+ ).status,
+ ).toBe(404);
+
+ const publicPage = await documents(owner.api)({ documentId: page.id }).access.post({
+ version: page.version,
+ isPrivate: false,
+ });
+ expect(publicPage.data).toMatchObject({ isPrivate: false, version: 2 });
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id }).access.post({
+ version: 1,
+ isPrivate: true,
+ })
+ ).status,
+ ).toBe(409);
+ expect((await documents(member.api)({ documentId: page.id }).get()).status).toBe(200);
+ expect(
+ (
+ await documents(member.api)({ documentId: page.id }).access.post({
+ version: 2,
+ isPrivate: true,
+ })
+ ).status,
+ ).toBe(403);
+
+ const ownerHistory = await documents(owner.api)({ documentId: page.id }).revisions.get();
+ const memberHistory = await documents(member.api)({ documentId: page.id }).revisions.get();
+ expect(ownerHistory.data?.map((revision) => revision.version)).toEqual([2, 1]);
+ expect(memberHistory.data?.map((revision) => revision.version)).toEqual([2]);
+
+ const privateRevision = ownerHistory.data!.find((revision) => revision.version === 1)!;
+ const restoredPrivate = await documents(owner.api)({ documentId: page.id })
+ .revisions({ revisionId: privateRevision.id })
+ .restore.post({ version: publicPage.data!.version });
+ expect(restoredPrivate.data).toMatchObject({
+ content: 'Secret',
+ isPrivate: true,
+ ownerUserId: owner.userId,
+ });
+ expect((await documents(member.api)({ documentId: page.id }).get()).status).toBe(404);
+ });
+
+ it('hides a private parent from public child details and history', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const parent = (await documents(owner.api).post({ title: 'Initially shared' })).data!;
+ const child = (await documents(member.api).post({ title: 'Public child', parentId: parent.id }))
+ .data!;
+ const privateParent = await documents(owner.api)({ documentId: parent.id }).access.post({
+ version: parent.version,
+ isPrivate: true,
+ });
+ expect(privateParent.status).toBe(200);
+
+ expect((await documents(member.api).get({ query: {} })).data).toMatchObject([
+ { id: child.id, parentId: null },
+ ]);
+ expect((await documents(member.api)({ documentId: child.id }).get()).data).toMatchObject({
+ id: child.id,
+ parentId: null,
+ });
+ const revisions = await documents(member.api)({ documentId: child.id }).revisions.get();
+ const snapshot = await documents(member.api)({ documentId: child.id })
+ .revisions({ revisionId: revisions.data![0]!.id })
+ .get();
+ expect(snapshot.data).toMatchObject({ documentId: child.id, parentId: null });
+ });
+
+ it('enforces locks and keeps favorites personal', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const page = (await documents(owner.api).post({ title: 'Handbook' })).data!;
+
+ const locked = await documents(owner.api)({ documentId: page.id }).lock.post({ version: 1 });
+ expect(locked.data).toMatchObject({ isLocked: true, version: 2 });
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id }).patch({
+ version: 2,
+ content: 'Blocked',
+ })
+ ).status,
+ ).toBe(409);
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id }).unlock.post({
+ version: 1,
+ })
+ ).status,
+ ).toBe(409);
+ expect(
+ (
+ await documents(member.api)({ documentId: page.id }).unlock.post({
+ version: 2,
+ })
+ ).status,
+ ).toBe(403);
+ const unlocked = await documents(owner.api)({ documentId: page.id }).unlock.post({
+ version: 2,
+ });
+ expect(unlocked.data).toMatchObject({ isLocked: false, version: 3 });
+
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id }).preferences.patch({
+ isFavorite: true,
+ })
+ ).data,
+ ).toEqual({ isFavorite: true });
+ expect((await documents(owner.api)({ documentId: page.id }).get()).data?.isFavorite).toBe(true);
+ expect((await documents(member.api)({ documentId: page.id }).get()).data?.isFavorite).toBe(
+ false,
+ );
+ await documents(member.api)({ documentId: page.id }).preferences.patch({ isFavorite: true });
+ expect((await documents(member.api)({ documentId: page.id }).get()).data?.isFavorite).toBe(
+ true,
+ );
+ const saved = await documents(owner.api)({ documentId: page.id }).patch({
+ version: 3,
+ content: 'Favorite stays favorite',
+ });
+ expect(saved.data).toMatchObject({ version: 4, isFavorite: true });
+ });
+
+ it('duplicates appearance and exports stable Markdown without accepting a stale source', async () => {
+ const { api } = await setupOwnerProject();
+ const page = (
+ await documents(api).post({
+ title: 'Release/Guide?',
+ content: '# Ship it',
+ icon: '🚀',
+ metadata: { owner: 'platform' },
+ fullWidth: true,
+ })
+ ).data!;
+ const updated = await documents(api)({ documentId: page.id }).patch({
+ version: 1,
+ content: '# Ship safely',
+ });
+ expect(
+ (
+ await documents(api)({ documentId: page.id }).duplicate.post({
+ version: 1,
+ })
+ ).status,
+ ).toBe(409);
+ const duplicate = await documents(api)({ documentId: page.id }).duplicate.post({
+ version: updated.data!.version,
+ });
+ expect(duplicate.status).toBe(201);
+ expect(duplicate.data).toMatchObject({
+ title: 'Release/Guide? (Copy)',
+ content: '# Ship safely',
+ icon: '🚀',
+ metadata: { owner: 'platform' },
+ fullWidth: true,
+ version: 1,
+ });
+
+ const exported = await documents(api)({ documentId: page.id }).export.get();
+ expect(exported.data).toMatchObject({
+ filename: 'Release-Guide-.md',
+ mimeType: 'text/markdown',
+ content: '# Ship safely',
+ version: 2,
+ });
+ });
+
+ it('omits another member private pages when a project is copied', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ await documents(owner.api).post({ title: 'Shared' });
+ await documents(member.api).post({ title: 'Member secret', isPrivate: true });
+ await documents(owner.api).post({
+ title: 'Owner private',
+ isPrivate: true,
+ icon: '🔒',
+ metadata: { copied: true },
+ fullWidth: true,
+ });
+
+ expect(
+ (await owner.api.projects({ projectKey: 'MKT' }).copy.post({ key: 'CPY', name: 'Copy' }))
+ .status,
+ ).toBe(201);
+ const copied = await documents(owner.api, 'CPY').get({ query: {} });
+ expect(copied.data?.map((document) => document.title).sort()).toEqual([
+ 'Owner private',
+ 'Shared',
+ ]);
+ expect(copied.data?.find((document) => document.title === 'Owner private')).toMatchObject({
+ isPrivate: true,
+ ownerUserId: owner.userId,
+ icon: '🔒',
+ metadata: { copied: true },
+ fullWidth: true,
+ });
+ });
+
+ it('lets project owners administer public pages and recover ownership without exposing private pages', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const publicPage = (await documents(member.api).post({ title: 'Team handbook' })).data!;
+ const privatePage = (
+ await documents(member.api).post({ title: 'Private draft', isPrivate: true })
+ ).data!;
+
+ expect(
+ (
+ await documents(owner.api)({ documentId: publicPage.id }).access.post({
+ version: publicPage.version,
+ isPrivate: true,
+ })
+ ).status,
+ ).toBe(403);
+
+ const locked = await documents(owner.api)({ documentId: publicPage.id }).lock.post({
+ version: publicPage.version,
+ });
+ expect(locked.data).toMatchObject({ isLocked: true, version: 2 });
+ const unlocked = await documents(owner.api)({ documentId: publicPage.id }).unlock.post({
+ version: locked.data!.version,
+ });
+ const archived = await documents(owner.api)({ documentId: publicPage.id }).archive.post({
+ version: unlocked.data!.version,
+ });
+ const restored = await documents(owner.api)({ documentId: publicPage.id }).restore.post({
+ version: archived.data!.version,
+ });
+ expect(restored.status).toBe(200);
+
+ expect(
+ (
+ await documents(owner.api)({ documentId: privatePage.id }).lock.post({
+ version: privatePage.version,
+ })
+ ).status,
+ ).toBe(404);
+ expect(
+ (
+ await documents(owner.api)({ documentId: privatePage.id }).ownership.post({
+ version: privatePage.version,
+ ownerUserId: owner.userId,
+ })
+ ).status,
+ ).toBe(404);
+
+ const formerlyPrivate = (
+ await documents(member.api).post({
+ title: 'Formerly private',
+ content: 'Original owner secret',
+ isPrivate: true,
+ })
+ ).data!;
+ const privateRevision = (
+ await documents(member.api)({ documentId: formerlyPrivate.id }).revisions.get()
+ ).data![0]!;
+ const published = await documents(member.api)({ documentId: formerlyPrivate.id }).access.post({
+ version: formerlyPrivate.version,
+ isPrivate: false,
+ });
+ const transferred = await documents(owner.api)({
+ documentId: formerlyPrivate.id,
+ }).ownership.post({
+ version: published.data!.version,
+ ownerUserId: owner.userId,
+ });
+ expect(transferred.data).toMatchObject({ ownerUserId: owner.userId, version: 3 });
+ expect(
+ (
+ await documents(owner.api)({ documentId: formerlyPrivate.id })
+ .revisions({ revisionId: privateRevision.id })
+ .get()
+ ).status,
+ ).toBe(404);
+ expect(
+ (
+ await documents(member.api)({ documentId: formerlyPrivate.id })
+ .revisions({ revisionId: privateRevision.id })
+ .restore.post({ version: transferred.data!.version })
+ ).status,
+ ).toBe(403);
+ expect(
+ (await documents(member.api)({ documentId: formerlyPrivate.id }).get()).data,
+ ).toMatchObject({ isPrivate: false, ownerUserId: owner.userId, version: 3 });
+ expect(
+ (
+ await documents(owner.api)({ documentId: formerlyPrivate.id })
+ .revisions({ revisionId: privateRevision.id })
+ .restore.post({ version: transferred.data!.version })
+ ).status,
+ ).toBe(404);
+ expect(
+ (await documents(owner.api)({ documentId: formerlyPrivate.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([3, 2]);
+
+ const outsider = await signUpTestUser();
+ expect(
+ (
+ await documents(owner.api)({ documentId: publicPage.id }).ownership.post({
+ version: restored.data!.version,
+ ownerUserId: outsider.userId,
+ })
+ ).status,
+ ).toBe(400);
+ await owner.api.projects({ projectKey: 'MKT' }).members({ userId: member.userId }).delete();
+ const claimed = await documents(owner.api)({ documentId: publicPage.id }).ownership.post({
+ version: restored.data!.version,
+ ownerUserId: owner.userId,
+ });
+ expect(claimed.data).toMatchObject({ ownerUserId: owner.userId });
+ expect(
+ (
+ await documents(owner.api)({ documentId: publicPage.id }).ownership.post({
+ version: restored.data!.version,
+ ownerUserId: owner.userId,
+ })
+ ).status,
+ ).toBe(409);
+ });
+
+ it('preserves rich JSON through history restore, duplicate, and project copy', async () => {
+ const owner = await setupOwnerProject();
+ const member = await addMember(owner.api);
+ const firstJson = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Red', marks: [{ type: 'textStyle', attrs: { color: '#f00' } }] },
+ ],
+ },
+ ],
+ };
+ const secondJson = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ attrs: { textAlign: 'center' },
+ content: [
+ {
+ type: 'text',
+ text: 'Centered',
+ marks: [{ type: 'highlight', attrs: { color: '#fef08a' } }],
+ },
+ ],
+ },
+ ],
+ };
+ const page = (
+ await documents(owner.api).post({
+ title: 'Rich page',
+ content: 'Red',
+ contentJson: firstJson,
+ })
+ ).data!;
+ const edited = await documents(member.api)({ documentId: page.id }).patch({
+ version: 1,
+ content: 'Centered',
+ contentJson: secondJson,
+ });
+ expect(edited.data?.contentJson).toEqual(secondJson);
+ const revisions = await documents(owner.api)({ documentId: page.id }).revisions.get();
+ expect(revisions.data?.map((revision) => revision.version)).toEqual([2, 1]);
+ const firstRevision = revisions.data!.find((revision) => revision.version === 1)!;
+ expect(
+ (
+ await documents(owner.api)({ documentId: page.id })
+ .revisions({ revisionId: firstRevision.id })
+ .get()
+ ).data?.contentJson,
+ ).toEqual(firstJson);
+ const restored = await documents(owner.api)({ documentId: page.id })
+ .revisions({ revisionId: firstRevision.id })
+ .restore.post({ version: edited.data!.version });
+ expect(restored.data?.contentJson).toEqual(firstJson);
+
+ const duplicate = await documents(owner.api)({ documentId: page.id }).duplicate.post({
+ version: restored.data!.version,
+ });
+ expect(duplicate.data?.contentJson).toEqual(firstJson);
+ await owner.api.projects({ projectKey: 'MKT' }).copy.post({ key: 'CPY', name: 'Copy' });
+ const copied = await documents(owner.api, 'CPY').get({ query: {} });
+ const copiedPage = copied.data!.find((document) => document.title === 'Rich page')!;
+ expect(
+ (await documents(owner.api, 'CPY')({ documentId: copiedPage.id }).get()).data?.contentJson,
+ ).toEqual(firstJson);
+
+ expect(
+ (
+ await documents(owner.api).post({
+ title: 'Invalid JSON',
+ contentJson: { type: 'doc', content: [{ type: 'unknownWidget' }] },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await documents(owner.api).post({
+ title: 'Invalid mark',
+ contentJson: {
+ type: 'doc',
+ content: [{ type: 'text', text: 'Bad', marks: [{ type: 'unknownMark' }] }],
+ },
+ })
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await documents(owner.api).post({
+ title: 'Invalid highlight',
+ contentJson: {
+ type: 'doc',
+ content: [
+ {
+ type: 'text',
+ text: 'Bad',
+ marks: [{ type: 'highlight', attrs: { color: 'url(javascript:alert(1))' } }],
+ },
+ ],
+ },
+ })
+ ).status,
+ ).toBe(400);
+ });
+
+ it('accepts safe rich-content attrs and rejects executable or malformed attrs', async () => {
+ const { api } = await setupOwnerProject();
+ const assetId = '11111111-1111-4111-8111-111111111111';
+ const safeJson = {
+ type: 'doc',
+ content: [
+ {
+ type: 'heading',
+ attrs: { level: 2, textAlign: 'right' },
+ content: [{ type: 'text', text: 'Safe rich content' }],
+ },
+ {
+ type: 'paragraph',
+ attrs: { textAlign: 'center' },
+ content: [
+ {
+ type: 'text',
+ text: 'External',
+ marks: [
+ {
+ type: 'link',
+ attrs: {
+ href: 'https://example.com/docs',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ class: 'docs-link',
+ },
+ },
+ { type: 'textStyle', attrs: { color: '#abcdef' } },
+ { type: 'highlight', attrs: { color: '#fff' } },
+ ],
+ },
+ { type: 'text', text: 'Relative', marks: [{ type: 'link', attrs: { href: '/docs' } }] },
+ { type: 'text', text: 'Anchor', marks: [{ type: 'link', attrs: { href: '#part' } }] },
+ {
+ type: 'text',
+ text: 'Mail',
+ marks: [{ type: 'link', attrs: { href: 'mailto:[email protected]' } }],
+ },
+ { type: 'text', text: 'Phone', marks: [{ type: 'link', attrs: { href: 'tel:+123' } }] },
+ ],
+ },
+ {
+ type: 'image',
+ attrs: {
+ src: `/protected-media/projects/MKT/documents/1/assets/${assetId}/raw`,
+ alt: 'Architecture',
+ title: 'Architecture diagram',
+ width: 640,
+ style: 'max-width: 100%;',
+ },
+ },
+ {
+ type: 'image',
+ attrs: { src: `/projects/MKT/documents/1/assets/${assetId}/raw` },
+ },
+ { type: 'image', attrs: { src: 'https://example.com/diagram.png' } },
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: true },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Done' }] }],
+ },
+ ],
+ },
+ {
+ type: 'table',
+ content: [
+ {
+ type: 'tableRow',
+ content: [
+ {
+ type: 'tableHeader',
+ attrs: { colspan: 1, rowspan: 1, colwidth: [240] },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Header' }] }],
+ },
+ {
+ type: 'tableCell',
+ attrs: { colspan: 2, rowspan: 1, colwidth: null },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Cell' }] }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+ expect((await documents(api).post({ title: 'Safe attrs', contentJson: safeJson })).status).toBe(
+ 201,
+ );
+
+ const withMark = (mark: Record<string, unknown>) => ({
+ type: 'doc',
+ content: [{ type: 'text', text: 'Unsafe', marks: [mark] }],
+ });
+ const withNode = (node: Record<string, unknown>) => ({ type: 'doc', content: [node] });
+ const invalidJson = [
+ withMark({ type: 'link', attrs: { href: 'javascript:alert(1)' } }),
+ withMark({ type: 'link', attrs: { href: 'data:text/html,unsafe' } }),
+ withMark({ type: 'link', attrs: { href: 'vbscript:msgbox(1)' } }),
+ withMark({ type: 'link', attrs: { href: ' javascript:alert(1)' } }),
+ withMark({ type: 'link', attrs: { href: 'java\nscript:alert(1)' } }),
+ withMark({ type: 'link', attrs: { href: 'java\u0000script:alert(1)' } }),
+ withMark({ type: 'link', attrs: { href: 'java\u200bscript:alert(1)' } }),
+ withMark({ type: 'link', attrs: { href: '//evil.example/path' } }),
+ withMark({ type: 'link', attrs: { href: 'https://user:[email protected]' } }),
+ withMark({ type: 'link', attrs: { href: 'https://example.com', onclick: 'alert(1)' } }),
+ withNode({ type: 'image', attrs: { src: 'data:image/svg+xml,unsafe' } }),
+ withNode({ type: 'image', attrs: { src: 'javascript:alert(1)' } }),
+ withNode({
+ type: 'image',
+ attrs: { src: `/media/projects/MKT/documents/1/assets/${assetId}/raw` },
+ }),
+ withNode({ type: 'image', attrs: { src: '//evil.example/image.png' } }),
+ withNode({
+ type: 'image',
+ attrs: { src: 'https://example.com/image.png', onerror: 'alert(1)' },
+ }),
+ withNode({
+ type: 'image',
+ attrs: { src: 'https://example.com/image.png', alt: 'x'.repeat(1_001) },
+ }),
+ withNode({
+ type: 'image',
+ attrs: { src: 'https://example.com/image.png', style: 'position:fixed' },
+ }),
+ withNode({ type: 'heading', attrs: { level: 0 } }),
+ withNode({ type: 'heading', attrs: { level: 7 } }),
+ withNode({ type: 'heading', attrs: { level: 2, textAlign: 'justify' } }),
+ withNode({ type: 'paragraph', attrs: { textAlign: 'justify' } }),
+ withNode({ type: 'taskItem', attrs: { checked: 'true' } }),
+ withNode({ type: 'tableCell', attrs: { colspan: 0 } }),
+ withNode({ type: 'tableHeader', attrs: { rowspan: 101 } }),
+ withNode({ type: 'tableCell', attrs: { colwidth: [] } }),
+ withNode({ type: 'tableCell', attrs: { colwidth: [0] } }),
+ withMark({ type: 'textStyle', attrs: { color: 'rgb(255, 0, 0)' } }),
+ withMark({ type: 'highlight', attrs: { color: '#12' } }),
+ withMark({ type: 'highlight', attrs: { color: '#12345' } }),
+ ];
+ for (const contentJson of invalidJson) {
+ expect((await documents(api).post({ title: 'Unsafe attrs', contentJson })).status).toBe(400);
+ }
+ });
+
+ it('coalesces autosaves and retains at most twenty useful revisions', async () => {
+ const { api } = await setupOwnerProject();
+ const page = (await documents(api).post({ title: 'Autosave' })).data!;
+ let version = page.version;
+ for (let index = 0; index < 3; index += 1) {
+ const updated = await documents(api)({ documentId: page.id }).patch({
+ version,
+ content: `Draft ${index}`,
+ contentJson: { type: 'doc', content: [{ type: 'text', text: `Draft ${index}` }] },
+ });
+ version = updated.data!.version;
+ }
+ expect(
+ (await documents(api)({ documentId: page.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([version, 1]);
+
+ for (let index = 0; index < 24; index += 1) {
+ const updated = await documents(api)({ documentId: page.id }).patch({
+ version,
+ fullWidth: index % 2 === 0,
+ });
+ version = updated.data!.version;
+ }
+ const retained = await documents(api)({ documentId: page.id }).revisions.get();
+ expect(retained.data).toHaveLength(20);
+ expect(retained.data?.[0].version).toBe(version);
+ expect(retained.data?.at(-1)!.version).toBe(version - 19);
+ });
+});
diff --git a/apps/api/src/modules/documents/index.ts b/apps/api/src/modules/documents/index.ts
new file mode 100644
index 00000000..eca0f5dd
--- /dev/null
+++ b/apps/api/src/modules/documents/index.ts
@@ -0,0 +1,746 @@
+import { Elysia, t } from 'elysia';
+import { authContext } from '#shared/auth-context';
+import { assertPermission, requireUser } from '#shared/access';
+import { guards } from '#shared/guards';
+import { noContent } from '#shared/http';
+import { HttpError } from '#shared/lib';
+import { getObject } from '#shared/s3';
+import { mcpTool } from '#mcp/generate';
+import { commonErrors, errors } from '#shared/responses';
+import { getMembership } from '#modules/members/service';
+import { rawAttachmentQuery } from '#modules/attachments/model';
+import {
+ assertAttachmentUploadAllowed,
+ attachmentEtag,
+ attachmentObjectKey,
+ attachmentResponseHeaders,
+ deleteAttachmentObject,
+ safeAttachmentFilename,
+ storeAttachmentObject,
+} from '#modules/attachments/storage';
+import {
+ createDocumentBody,
+ deleteDocumentQuery,
+ documentAssetParams,
+ documentAccessBody,
+ documentOwnershipBody,
+ documentParams,
+ documentRevisionParams,
+ DocumentExportResponse,
+ DocumentAssetListResponse,
+ DocumentAssetResponse,
+ DocumentPreferenceResponse,
+ DocumentIssueLinkListResponse,
+ DocumentIssueLinkResponse,
+ IssueDocumentLinkListResponse,
+ DocumentResponse,
+ DocumentRevisionListResponse,
+ DocumentRevisionResponse,
+ DocumentSummaryListResponse,
+ documentVersionBody,
+ documentIssueParams,
+ duplicateDocumentBody,
+ issueDocumentsParams,
+ linkDocumentIssueBody,
+ listDocumentsQuery,
+ updateDocumentBody,
+ updateDocumentPreferenceBody,
+ uploadDocumentAssetBody,
+} from './model';
+import {
+ archiveDocument,
+ assertDocumentAssetUploadTarget,
+ createDocument,
+ createDocumentAsset,
+ deleteDocument,
+ deleteDocumentAsset,
+ duplicateDocument,
+ exportDocument,
+ getDocument,
+ getDocumentAsset,
+ getDocumentRevision,
+ listDocumentRevisions,
+ listDocumentAssets,
+ listDocuments,
+ restoreDocument,
+ restoreDocumentRevision,
+ setDocumentAccess,
+ setDocumentLocked,
+ setDocumentPreference,
+ transferDocumentOwnership,
+ updateDocument,
+ type DocumentAssetRow,
+} from './service';
+import {
+ addDocumentIssueLink,
+ listDocumentIssueLinks,
+ listIssueDocumentLinks,
+ removeDocumentIssueLink,
+} from './issue-links';
+
+function documentAssetDto(projectKey: string, documentId: number, asset: DocumentAssetRow) {
+ return {
+ id: asset.publicId,
+ filename: asset.filename,
+ contentType: asset.contentType,
+ sizeBytes: asset.sizeBytes,
+ uploadedByUserId: asset.uploadedByUserId,
+ createdAt: asset.createdAt,
+ url: `/projects/${encodeURIComponent(projectKey)}/documents/${documentId}/assets/${asset.publicId}/raw`,
+ };
+}
+
+async function isProjectOwner(projectId: number, userId: string): Promise<boolean> {
+ return (await getMembership(projectId, userId)) === 'owner';
+}
+
+export const documentRoutes = new Elysia({
+ name: 'documents',
+ detail: { tags: ['Documents'] },
+})
+ .use(authContext)
+ .use(guards)
+ .get(
+ '/projects/:projectKey/documents',
+ async ({ project, query, user }) =>
+ listDocuments(project.id, requireUser(user).id, {
+ q: query.q,
+ archived: query.archived === 'true',
+ }),
+ {
+ permission: ['documents', 'read'],
+ query: listDocumentsQuery,
+ response: { 200: DocumentSummaryListResponse, ...commonErrors },
+ detail: {
+ summary: "List a project's documents",
+ description:
+ 'Return the visible Docs tree without document bodies. Use q to search Markdown and archived=true for the archive.',
+ ...mcpTool('list_documents'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId',
+ async ({ project, params, user }) => {
+ const document = await getDocument(project.id, params.documentId, requireUser(user).id);
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ response: { 200: DocumentResponse, ...commonErrors },
+ detail: {
+ summary: 'Get a document',
+ description: 'Return one visible project document with its Markdown content.',
+ ...mcpTool('get_document'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/issues',
+ async ({ project, params, user }) => {
+ const current = requireUser(user);
+ await assertPermission(project.id, current, 'work_items', 'read');
+ const links = await listDocumentIssueLinks(
+ project.id,
+ project.key,
+ params.documentId,
+ current.id,
+ );
+ if (!links) throw new HttpError(404, 'Document not found');
+ return links;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ response: { 200: DocumentIssueLinkListResponse, ...commonErrors },
+ detail: {
+ summary: 'List work items linked to a document',
+ description: 'Return work items explicitly linked to one visible Docs page.',
+ ...mcpTool('list_document_issues'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/issues',
+ async ({ project, params, body, user, set }) => {
+ const current = requireUser(user);
+ await assertPermission(project.id, current, 'work_items', 'edit');
+ const link = await addDocumentIssueLink({
+ projectId: project.id,
+ projectKey: project.key,
+ documentId: params.documentId,
+ issueId: body.issueId,
+ userId: current.id,
+ });
+ set.status = 201;
+ return link;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: linkDocumentIssueBody,
+ response: { 201: DocumentIssueLinkResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Link a document to a work item',
+ description:
+ 'Link one active Docs page to a work item in the same project. Editing both resources is required.',
+ ...mcpTool('link_document_issue'),
+ },
+ },
+ )
+ .delete(
+ '/projects/:projectKey/documents/:documentId/issues/:issueId',
+ async ({ project, params, user }) => {
+ const current = requireUser(user);
+ await assertPermission(project.id, current, 'work_items', 'edit');
+ const removed = await removeDocumentIssueLink({
+ projectId: project.id,
+ documentId: params.documentId,
+ issueId: params.issueId,
+ userId: current.id,
+ });
+ if (!removed) throw new HttpError(404, 'Document link not found');
+ return noContent();
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentIssueParams,
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Unlink a document from a work item',
+ description: 'Remove an explicit Docs-to-work-item link.',
+ ...mcpTool('unlink_document_issue'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/for-issue/:issueId',
+ async ({ project, params, user }) => {
+ const current = requireUser(user);
+ await assertPermission(project.id, current, 'documents', 'read');
+ const links = await listIssueDocumentLinks(project.id, params.issueId, current.id);
+ if (!links) throw new HttpError(404, 'Issue not found');
+ return links;
+ },
+ {
+ permission: ['work_items', 'read'],
+ params: issueDocumentsParams,
+ response: { 200: IssueDocumentLinkListResponse, ...commonErrors },
+ detail: {
+ summary: 'List Docs linked to a work item',
+ description: 'Return visible Docs pages explicitly linked to one work item.',
+ ...mcpTool('list_issue_documents'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/assets',
+ async ({ project, params, user }) => {
+ const assets = await listDocumentAssets(project.id, params.documentId, requireUser(user).id);
+ if (!assets) throw new HttpError(404, 'Document not found');
+ return assets.map((asset) => documentAssetDto(project.key, params.documentId, asset));
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ response: { 200: DocumentAssetListResponse, ...commonErrors },
+ detail: {
+ summary: 'List document assets',
+ description: 'List files embedded in a visible Docs page.',
+ ...mcpTool('list_document_assets'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/assets',
+ async ({ project, params, user, body, set }) => {
+ const userId = requireUser(user).id;
+ if (!(await assertDocumentAssetUploadTarget(project.id, params.documentId, userId))) {
+ throw new HttpError(404, 'Document not found');
+ }
+ const file = body.file;
+ if (!(file instanceof File) || file.size === 0) throw new HttpError(400, 'File is empty');
+ const filename = safeAttachmentFilename(file.name);
+ const contentType = file.type || 'application/octet-stream';
+ await assertAttachmentUploadAllowed(project.id, file.size, contentType);
+ const key = attachmentObjectKey(project.id, 'documents', params.documentId, filename);
+ const bytes = Buffer.from(await file.arrayBuffer());
+ await storeAttachmentObject(key, bytes, contentType);
+ try {
+ const asset = await createDocumentAsset({
+ projectId: project.id,
+ documentId: params.documentId,
+ userId,
+ s3Key: key,
+ filename,
+ contentType,
+ sizeBytes: bytes.length,
+ });
+ if (!asset) throw new HttpError(404, 'Document not found');
+ set.status = 201;
+ return documentAssetDto(project.key, params.documentId, asset);
+ } catch (error) {
+ await deleteAttachmentObject(key);
+ throw error;
+ }
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: uploadDocumentAssetBody,
+ response: { 201: DocumentAssetResponse, ...commonErrors, ...errors(409, 413, 502) },
+ detail: {
+ summary: 'Upload a document asset',
+ description:
+ 'Store a file for an active, unlocked Docs page. Instance MIME, file-size and project-quota limits apply.',
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/assets/:publicId/raw',
+ async ({ project, params, query, request, user }) => {
+ const asset = await getDocumentAsset(
+ project.id,
+ params.documentId,
+ params.publicId,
+ requireUser(user).id,
+ );
+ if (!asset) throw new HttpError(404, 'Asset not found');
+ const etag = attachmentEtag(asset.s3Key);
+ if (request.headers.get('if-none-match') === etag) {
+ return new Response(null, { status: 304, headers: { ETag: etag } });
+ }
+ let object;
+ try {
+ object = await getObject(asset.s3Key);
+ } catch (error) {
+ throw new HttpError(404, error instanceof Error ? error.message : 'Asset not found');
+ }
+ return new Response(object.body, {
+ headers: attachmentResponseHeaders({
+ contentType: asset.contentType || object.contentType,
+ filename: asset.filename,
+ contentLength: object.contentLength,
+ etag,
+ download: query.download != null,
+ }),
+ });
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentAssetParams,
+ query: rawAttachmentQuery,
+ response: { ...commonErrors },
+ detail: {
+ summary: 'Download a document asset',
+ description: 'Download an asset after re-checking current project and private-page access.',
+ },
+ },
+ )
+ .delete(
+ '/projects/:projectKey/documents/:documentId/assets/:publicId',
+ async ({ project, params, user }) => {
+ const userId = requireUser(user).id;
+ const asset = await deleteDocumentAsset(
+ project.id,
+ params.documentId,
+ params.publicId,
+ userId,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!asset) throw new HttpError(404, 'Asset not found');
+ await deleteAttachmentObject(asset.s3Key);
+ return noContent();
+ },
+ {
+ permission: ['documents', 'delete'],
+ params: documentAssetParams,
+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Delete a document asset',
+ description: 'Delete one asset from an active, unlocked Docs page.',
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/export',
+ async ({ project, params, user }) => {
+ const exported = await exportDocument(project.id, params.documentId, requireUser(user).id);
+ if (!exported) throw new HttpError(404, 'Document not found');
+ return exported;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ response: { 200: DocumentExportResponse, ...commonErrors },
+ detail: {
+ summary: 'Export a document',
+ description: 'Return stable filename, Markdown body and version metadata for export tools.',
+ ...mcpTool('export_document'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/revisions',
+ async ({ project, params, user }) => {
+ const revisions = await listDocumentRevisions(
+ project.id,
+ params.documentId,
+ requireUser(user).id,
+ );
+ if (!revisions) throw new HttpError(404, 'Document not found');
+ return revisions;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ response: { 200: DocumentRevisionListResponse, ...commonErrors },
+ detail: {
+ summary: 'List document revisions',
+ description: 'Return immutable document versions, newest first.',
+ ...mcpTool('list_document_revisions'),
+ },
+ },
+ )
+ .get(
+ '/projects/:projectKey/documents/:documentId/revisions/:revisionId',
+ async ({ project, params, user }) => {
+ const revision = await getDocumentRevision(
+ project.id,
+ params.documentId,
+ params.revisionId,
+ requireUser(user).id,
+ );
+ if (!revision) throw new HttpError(404, 'Document revision not found');
+ return revision;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentRevisionParams,
+ response: { 200: DocumentRevisionResponse, ...commonErrors },
+ detail: {
+ summary: 'Get a document revision',
+ description: 'Return one historical Markdown snapshot.',
+ ...mcpTool('get_document_revision'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents',
+ async ({ project, user, body, set }) => {
+ set.status = 201;
+ return createDocument({
+ projectId: project.id,
+ userId: requireUser(user).id,
+ title: body.title,
+ content: body.content,
+ contentJson: body.contentJson,
+ icon: body.icon,
+ metadata: body.metadata,
+ fullWidth: body.fullWidth,
+ isPrivate: body.isPrivate,
+ parentId: body.parentId,
+ });
+ },
+ {
+ permission: ['documents', 'create'],
+ body: createDocumentBody,
+ response: { 201: DocumentResponse, ...commonErrors },
+ detail: {
+ summary: 'Create a document',
+ description:
+ 'Create a public or private Markdown page, optionally nested under another page.',
+ ...mcpTool('create_document'),
+ },
+ },
+ )
+ .patch(
+ '/projects/:projectKey/documents/:documentId',
+ async ({ project, user, params, body }) => {
+ const document = await updateDocument(
+ project.id,
+ params.documentId,
+ requireUser(user).id,
+ body,
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: updateDocumentBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Update a document',
+ description:
+ 'Update Markdown, appearance, nesting or position. Send the version last read; a stale or locked page returns 409.',
+ ...mcpTool('update_document'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/access',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await setDocumentAccess(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ body.isPrivate,
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: documentAccessBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Change document access',
+ description:
+ 'The document owner can make a page public to the project or private to themselves. A project owner must explicitly claim an orphaned public page first.',
+ ...mcpTool('set_document_access'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/ownership',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await transferDocumentOwnership(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ body.ownerUserId,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: documentOwnershipBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Transfer document ownership',
+ description:
+ 'Transfer a page to another project member. A project owner can claim or transfer a public page whose previous owner left the project.',
+ ...mcpTool('transfer_document_ownership'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/lock',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await setDocumentLocked(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ true,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: documentVersionBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: { summary: 'Lock a document', ...mcpTool('lock_document') },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/unlock',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await setDocumentLocked(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ false,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentParams,
+ body: documentVersionBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: { summary: 'Unlock a document', ...mcpTool('unlock_document') },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/archive',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await archiveDocument(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'delete'],
+ params: documentParams,
+ body: documentVersionBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Archive a document tree',
+ description:
+ 'Archive a page and all descendants without deleting their content or history.',
+ ...mcpTool('archive_document'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/restore',
+ async ({ project, user, params, body }) => {
+ const userId = requireUser(user).id;
+ const document = await restoreDocument(
+ project.id,
+ params.documentId,
+ userId,
+ body.version,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'delete'],
+ params: documentParams,
+ body: documentVersionBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Restore a document tree',
+ description:
+ 'Restore an archived page and its descendants. It returns to the root if its parent remains archived.',
+ ...mcpTool('restore_document'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/duplicate',
+ async ({ project, user, params, body, set }) => {
+ const document = await duplicateDocument({
+ projectId: project.id,
+ documentId: params.documentId,
+ userId: requireUser(user).id,
+ version: body.version,
+ title: body.title,
+ parentId: body.parentId,
+ });
+ if (!document) throw new HttpError(404, 'Document not found');
+ set.status = 201;
+ return document;
+ },
+ {
+ permission: ['documents', 'create'],
+ params: documentParams,
+ body: duplicateDocumentBody,
+ response: { 201: DocumentResponse, ...commonErrors, ...errors(409, 413, 502) },
+ detail: {
+ summary: 'Duplicate a document',
+ description:
+ 'Copy one visible page and its appearance into a new page owned by the caller.',
+ ...mcpTool('duplicate_document'),
+ },
+ },
+ )
+ .patch(
+ '/projects/:projectKey/documents/:documentId/preferences',
+ async ({ project, user, params, body }) => {
+ const preference = await setDocumentPreference(
+ project.id,
+ params.documentId,
+ requireUser(user).id,
+ body.isFavorite,
+ );
+ if (!preference) throw new HttpError(404, 'Document not found');
+ return preference;
+ },
+ {
+ permission: ['documents', 'read'],
+ params: documentParams,
+ body: updateDocumentPreferenceBody,
+ response: { 200: DocumentPreferenceResponse, ...commonErrors },
+ detail: {
+ summary: 'Update document preferences',
+ description: 'Favorite or unfavorite a page for the current user.',
+ ...mcpTool('set_document_preference'),
+ },
+ },
+ )
+ .post(
+ '/projects/:projectKey/documents/:documentId/revisions/:revisionId/restore',
+ async ({ project, user, params, body }) => {
+ const document = await restoreDocumentRevision(
+ project.id,
+ params.documentId,
+ params.revisionId,
+ requireUser(user).id,
+ body.version,
+ );
+ if (!document) throw new HttpError(404, 'Document not found');
+ return document;
+ },
+ {
+ permission: ['documents', 'edit'],
+ params: documentRevisionParams,
+ body: documentVersionBody,
+ response: { 200: DocumentResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Restore a document revision',
+ description:
+ 'Copy a historical snapshot into a new current version without rewriting history.',
+ ...mcpTool('restore_document_revision'),
+ },
+ },
+ )
+ .delete(
+ '/projects/:projectKey/documents/:documentId',
+ async ({ project, params, query, user }) => {
+ const userId = requireUser(user).id;
+ const assetKeys = await deleteDocument(
+ project.id,
+ params.documentId,
+ userId,
+ query.version,
+ await isProjectOwner(project.id, userId),
+ );
+ if (!assetKeys) {
+ throw new HttpError(404, 'Document not found');
+ }
+ await Promise.all(assetKeys.map(deleteAttachmentObject));
+ return noContent();
+ },
+ {
+ permission: ['documents', 'delete'],
+ params: documentParams,
+ query: deleteDocumentQuery,
+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Delete a document',
+ description:
+ 'Permanently delete an archived document and its history. Its child pages move to the project root.',
+ ...mcpTool('delete_document'),
+ },
+ },
+ );
diff --git a/apps/api/src/modules/documents/issue-links.ts b/apps/api/src/modules/documents/issue-links.ts
new file mode 100644
index 00000000..5488a6f7
--- /dev/null
+++ b/apps/api/src/modules/documents/issue-links.ts
@@ -0,0 +1,190 @@
+import { db, issue, projectDocument, projectDocumentIssue } from '@repo/db';
+import { and, asc, eq, or } from 'drizzle-orm';
+import { HttpError } from '#shared/lib';
+
+export interface DocumentIssueLinkRow {
+ issueId: number;
+ sequenceNumber: number;
+ identifier: string;
+ title: string;
+ archived: boolean;
+ createdAt: string;
+}
+
+export interface IssueDocumentLinkRow {
+ documentId: number;
+ title: string;
+ icon: string | null;
+ isPrivate: boolean;
+ archived: boolean;
+ createdAt: string;
+}
+
+const documentAccess = (userId: string) =>
+ or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, userId));
+
+async function visibleDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ tx: Pick<typeof db, 'select'> = db,
+) {
+ const [document] = await tx
+ .select({ id: projectDocument.id, archivedAt: projectDocument.archivedAt })
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.projectId, projectId),
+ documentAccess(userId),
+ ),
+ )
+ .limit(1);
+ return document ?? null;
+}
+
+export async function listDocumentIssueLinks(
+ projectId: number,
+ projectKey: string,
+ documentId: number,
+ userId: string,
+): Promise<DocumentIssueLinkRow[] | null> {
+ if (!(await visibleDocument(projectId, documentId, userId))) return null;
+ const rows = await db
+ .select({
+ issueId: issue.id,
+ sequenceNumber: issue.sequenceNumber,
+ title: issue.title,
+ archivedAt: issue.archivedAt,
+ createdAt: projectDocumentIssue.createdAt,
+ })
+ .from(projectDocumentIssue)
+ .innerJoin(issue, eq(issue.id, projectDocumentIssue.issueId))
+ .where(and(eq(projectDocumentIssue.documentId, documentId), eq(issue.projectId, projectId)))
+ .orderBy(asc(issue.sequenceNumber));
+ return rows.map((row) => ({
+ issueId: row.issueId,
+ sequenceNumber: row.sequenceNumber,
+ identifier: `${projectKey}-${row.sequenceNumber}`,
+ title: row.title,
+ archived: row.archivedAt !== null,
+ createdAt: row.createdAt.toISOString(),
+ }));
+}
+
+export async function listIssueDocumentLinks(
+ projectId: number,
+ issueId: number,
+ userId: string,
+): Promise<IssueDocumentLinkRow[] | null> {
+ const [workItem] = await db
+ .select({ id: issue.id })
+ .from(issue)
+ .where(and(eq(issue.id, issueId), eq(issue.projectId, projectId)))
+ .limit(1);
+ if (!workItem) return null;
+
+ const rows = await db
+ .select({
+ documentId: projectDocument.id,
+ title: projectDocument.title,
+ icon: projectDocument.icon,
+ isPrivate: projectDocument.isPrivate,
+ archivedAt: projectDocument.archivedAt,
+ createdAt: projectDocumentIssue.createdAt,
+ })
+ .from(projectDocumentIssue)
+ .innerJoin(projectDocument, eq(projectDocument.id, projectDocumentIssue.documentId))
+ .where(
+ and(
+ eq(projectDocumentIssue.issueId, issueId),
+ eq(projectDocument.projectId, projectId),
+ documentAccess(userId),
+ ),
+ )
+ .orderBy(asc(projectDocument.title), asc(projectDocument.id));
+ return rows.map((row) => ({
+ documentId: row.documentId,
+ title: row.title,
+ icon: row.icon,
+ isPrivate: row.isPrivate,
+ archived: row.archivedAt !== null,
+ createdAt: row.createdAt.toISOString(),
+ }));
+}
+
+export async function addDocumentIssueLink(input: {
+ projectId: number;
+ projectKey: string;
+ documentId: number;
+ issueId: number;
+ userId: string;
+}): Promise<DocumentIssueLinkRow> {
+ return db.transaction(async (tx) => {
+ const document = await visibleDocument(input.projectId, input.documentId, input.userId, tx);
+ if (!document) throw new HttpError(404, 'Document not found');
+ if (document.archivedAt !== null)
+ throw new HttpError(409, 'Archived documents cannot be linked');
+
+ const [workItem] = await tx
+ .select({
+ id: issue.id,
+ sequenceNumber: issue.sequenceNumber,
+ title: issue.title,
+ archivedAt: issue.archivedAt,
+ })
+ .from(issue)
+ .where(and(eq(issue.id, input.issueId), eq(issue.projectId, input.projectId)))
+ .limit(1);
+ if (!workItem) throw new HttpError(404, 'Issue not found');
+
+ const [created] = await tx
+ .insert(projectDocumentIssue)
+ .values({
+ documentId: input.documentId,
+ issueId: input.issueId,
+ createdByUserId: input.userId,
+ })
+ .onConflictDoNothing()
+ .returning({ createdAt: projectDocumentIssue.createdAt });
+ if (!created) throw new HttpError(409, 'The document is already linked to this issue');
+
+ return {
+ issueId: workItem.id,
+ sequenceNumber: workItem.sequenceNumber,
+ identifier: `${input.projectKey}-${workItem.sequenceNumber}`,
+ title: workItem.title,
+ archived: workItem.archivedAt !== null,
+ createdAt: created.createdAt.toISOString(),
+ };
+ });
+}
+
+export async function removeDocumentIssueLink(input: {
+ projectId: number;
+ documentId: number;
+ issueId: number;
+ userId: string;
+}): Promise<boolean> {
+ return db.transaction(async (tx) => {
+ if (!(await visibleDocument(input.projectId, input.documentId, input.userId, tx))) {
+ throw new HttpError(404, 'Document not found');
+ }
+ const [workItem] = await tx
+ .select({ id: issue.id })
+ .from(issue)
+ .where(and(eq(issue.id, input.issueId), eq(issue.projectId, input.projectId)))
+ .limit(1);
+ if (!workItem) throw new HttpError(404, 'Issue not found');
+ const removed = await tx
+ .delete(projectDocumentIssue)
+ .where(
+ and(
+ eq(projectDocumentIssue.documentId, input.documentId),
+ eq(projectDocumentIssue.issueId, input.issueId),
+ ),
+ )
+ .returning({ issueId: projectDocumentIssue.issueId });
+ return removed.length > 0;
+ });
+}
diff --git a/apps/api/src/modules/documents/model.ts b/apps/api/src/modules/documents/model.ts
new file mode 100644
index 00000000..0ae68870
--- /dev/null
+++ b/apps/api/src/modules/documents/model.ts
@@ -0,0 +1,198 @@
+import { t } from 'elysia';
+
+export const documentParams = t.Object({
+ projectKey: t.String(),
+ documentId: t.Numeric(),
+});
+
+export const documentRevisionParams = t.Object({
+ projectKey: t.String(),
+ documentId: t.Numeric(),
+ revisionId: t.Numeric(),
+});
+
+export const documentAssetParams = t.Object({
+ projectKey: t.String(),
+ documentId: t.Numeric(),
+ publicId: t.String({ format: 'uuid' }),
+});
+
+const DocumentSummaryResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ parentId: t.Nullable(t.Number()),
+ title: t.String(),
+ icon: t.Nullable(t.String()),
+ metadata: t.Record(t.String(), t.Any()),
+ fullWidth: t.Boolean(),
+ isPrivate: t.Boolean(),
+ isLocked: t.Boolean(),
+ isFavorite: t.Boolean(),
+ archivedAt: t.Nullable(t.String()),
+ position: t.Number(),
+ version: t.Number(),
+ ownerUserId: t.Nullable(t.String()),
+ createdByUserId: t.Nullable(t.String()),
+ updatedByUserId: t.Nullable(t.String()),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+});
+
+export const DocumentResponse = t.Composite([
+ DocumentSummaryResponse,
+ t.Object({
+ content: t.String(),
+ contentJson: t.Nullable(t.Record(t.String(), t.Any())),
+ }),
+]);
+
+export const DocumentSummaryListResponse = t.Array(DocumentSummaryResponse);
+
+export const listDocumentsQuery = t.Object({
+ q: t.Optional(t.String({ maxLength: 200 })),
+ archived: t.Optional(
+ t.Union([t.Literal('true'), t.Literal('false')], {
+ description: "'true' lists archived pages; the default lists active pages.",
+ }),
+ ),
+});
+
+const documentFields = {
+ title: t.Optional(t.String({ maxLength: 255 })),
+ content: t.Optional(t.String({ maxLength: 250_000 })),
+ contentJson: t.Optional(t.Nullable(t.Record(t.String(), t.Any()))),
+ icon: t.Optional(t.Nullable(t.String({ maxLength: 64 }))),
+ metadata: t.Optional(t.Record(t.String(), t.Any())),
+ fullWidth: t.Optional(t.Boolean()),
+};
+
+export const createDocumentBody = t.Object({
+ ...documentFields,
+ parentId: t.Optional(t.Nullable(t.Integer({ minimum: 1 }))),
+ isPrivate: t.Optional(t.Boolean()),
+});
+
+export const updateDocumentBody = t.Object({
+ version: t.Integer({ minimum: 1 }),
+ ...documentFields,
+ parentId: t.Optional(t.Nullable(t.Integer({ minimum: 1 }))),
+ position: t.Optional(t.Number()),
+ previousSiblingId: t.Optional(t.Nullable(t.Integer({ minimum: 1 }))),
+ nextSiblingId: t.Optional(t.Nullable(t.Integer({ minimum: 1 }))),
+});
+
+export const documentVersionBody = t.Object({
+ version: t.Integer({ minimum: 1 }),
+});
+
+export const documentAccessBody = t.Object({
+ version: t.Integer({ minimum: 1 }),
+ isPrivate: t.Boolean(),
+});
+
+export const documentOwnershipBody = t.Object({
+ version: t.Integer({ minimum: 1 }),
+ ownerUserId: t.String({ minLength: 1 }),
+});
+
+export const duplicateDocumentBody = t.Object({
+ version: t.Integer({ minimum: 1 }),
+ title: t.Optional(t.String({ maxLength: 255 })),
+ parentId: t.Optional(t.Nullable(t.Integer({ minimum: 1 }))),
+});
+
+export const updateDocumentPreferenceBody = t.Object({
+ isFavorite: t.Boolean(),
+});
+
+export const DocumentPreferenceResponse = t.Object({ isFavorite: t.Boolean() });
+
+export const documentIssueParams = t.Object({
+ projectKey: t.String(),
+ documentId: t.Numeric(),
+ issueId: t.Numeric(),
+});
+
+export const issueDocumentsParams = t.Object({
+ projectKey: t.String(),
+ issueId: t.Numeric(),
+});
+
+export const linkDocumentIssueBody = t.Object({
+ issueId: t.Integer({ minimum: 1 }),
+});
+
+export const DocumentIssueLinkResponse = t.Object({
+ issueId: t.Number(),
+ sequenceNumber: t.Number(),
+ identifier: t.String(),
+ title: t.String(),
+ archived: t.Boolean(),
+ createdAt: t.String(),
+});
+
+export const DocumentIssueLinkListResponse = t.Array(DocumentIssueLinkResponse);
+
+export const IssueDocumentLinkResponse = t.Object({
+ documentId: t.Number(),
+ title: t.String(),
+ icon: t.Nullable(t.String()),
+ isPrivate: t.Boolean(),
+ archived: t.Boolean(),
+ createdAt: t.String(),
+});
+
+export const IssueDocumentLinkListResponse = t.Array(IssueDocumentLinkResponse);
+
+const DocumentRevisionSummaryResponse = t.Object({
+ id: t.Number(),
+ documentId: t.Number(),
+ version: t.Number(),
+ title: t.String(),
+ createdByUserId: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const DocumentRevisionResponse = t.Composite([
+ DocumentRevisionSummaryResponse,
+ t.Object({
+ parentId: t.Nullable(t.Number()),
+ content: t.String(),
+ contentJson: t.Nullable(t.Record(t.String(), t.Any())),
+ icon: t.Nullable(t.String()),
+ metadata: t.Record(t.String(), t.Any()),
+ fullWidth: t.Boolean(),
+ isPrivate: t.Boolean(),
+ isLocked: t.Boolean(),
+ archivedAt: t.Nullable(t.String()),
+ position: t.Number(),
+ }),
+]);
+
+export const DocumentRevisionListResponse = t.Array(DocumentRevisionSummaryResponse);
+
+export const DocumentExportResponse = t.Object({
+ filename: t.String(),
+ mimeType: t.Literal('text/markdown'),
+ content: t.String(),
+ version: t.Number(),
+ exportedAt: t.String(),
+});
+
+export const uploadDocumentAssetBody = t.Object({ file: t.File() });
+
+export const DocumentAssetResponse = t.Object({
+ id: t.String({ format: 'uuid' }),
+ filename: t.String(),
+ contentType: t.String(),
+ sizeBytes: t.Number(),
+ uploadedByUserId: t.Nullable(t.String()),
+ createdAt: t.String(),
+ url: t.String(),
+});
+
+export const DocumentAssetListResponse = t.Array(DocumentAssetResponse);
+
+export const deleteDocumentQuery = t.Object({
+ version: t.Integer({ minimum: 1 }),
+});
diff --git a/apps/api/src/modules/documents/service.ts b/apps/api/src/modules/documents/service.ts
new file mode 100644
index 00000000..4550508f
--- /dev/null
+++ b/apps/api/src/modules/documents/service.ts
@@ -0,0 +1,1670 @@
+import {
+ db,
+ documentAsset,
+ project,
+ projectDocument,
+ projectDocumentPreference,
+ projectDocumentRevision,
+ projectMember,
+} from '@repo/db';
+import { and, asc, desc, eq, ilike, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
+import { HttpError, iso } from '#shared/lib';
+import {
+ assertAttachmentStorageCapacity,
+ assertAttachmentFileAllowed,
+ attachmentObjectKey,
+ cloneAttachmentObject,
+ deleteAttachmentObject,
+ lockAttachmentStorage,
+} from '#modules/attachments/storage';
+
+type Executor = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+const DOCUMENT_TREE_LOCK_NAMESPACE = 1_145_390_931;
+
+async function lockDocumentActor(executor: Executor, userId: string): Promise<void> {
+ const rows = await executor.execute(
+ sql`select id from "user" where id = ${userId} for key share`,
+ );
+ if (rows.length === 0) throw new HttpError(404, 'User not found');
+}
+
+async function lockDocumentActors(
+ executor: Executor,
+ userIds: Array<string | null>,
+): Promise<void> {
+ const ordered = [...new Set(userIds.filter((id): id is string => id !== null))].sort();
+ for (const userId of ordered) await lockDocumentActor(executor, userId);
+}
+
+async function lockProjectDocumentActors(
+ executor: Executor,
+ projectId: number,
+ actorUserId: string,
+): Promise<void> {
+ const rows = await executor
+ .selectDistinct({ ownerUserId: projectDocument.ownerUserId })
+ .from(projectDocument)
+ .where(eq(projectDocument.projectId, projectId));
+ await lockDocumentActors(executor, [actorUserId, ...rows.map((row) => row.ownerUserId)]);
+}
+
+export interface DocumentSummaryRow {
+ id: number;
+ projectId: number;
+ parentId: number | null;
+ title: string;
+ icon: string | null;
+ metadata: Record<string, unknown>;
+ fullWidth: boolean;
+ isPrivate: boolean;
+ isLocked: boolean;
+ isFavorite: boolean;
+ archivedAt: string | null;
+ position: number;
+ version: number;
+ ownerUserId: string | null;
+ createdByUserId: string | null;
+ updatedByUserId: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface DocumentRow extends DocumentSummaryRow {
+ content: string;
+ contentJson: Record<string, unknown> | null;
+}
+
+export interface DocumentRevisionSummaryRow {
+ id: number;
+ documentId: number;
+ version: number;
+ title: string;
+ createdByUserId: string | null;
+ createdAt: string;
+}
+
+export interface DocumentRevisionRow extends DocumentRevisionSummaryRow {
+ parentId: number | null;
+ content: string;
+ contentJson: Record<string, unknown> | null;
+ icon: string | null;
+ metadata: Record<string, unknown>;
+ fullWidth: boolean;
+ isPrivate: boolean;
+ isLocked: boolean;
+ archivedAt: string | null;
+ position: number;
+}
+
+export interface DocumentAssetRow {
+ publicId: string;
+ documentId: number;
+ uploadedByUserId: string | null;
+ s3Key: string;
+ filename: string;
+ contentType: string;
+ sizeBytes: number;
+ createdAt: string;
+}
+
+function documentAccess(userId: string) {
+ return or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, userId));
+}
+
+function mapDocument(row: typeof projectDocument.$inferSelect, isFavorite = false): DocumentRow {
+ const { archivedByAncestorId: _archivedByAncestorId, ...publicRow } = row;
+ return {
+ ...publicRow,
+ isFavorite,
+ archivedAt: row.archivedAt ? iso(row.archivedAt) : null,
+ createdAt: iso(row.createdAt),
+ updatedAt: iso(row.updatedAt),
+ };
+}
+
+function summaryOf(
+ row: typeof projectDocument.$inferSelect,
+ isFavorite = false,
+): DocumentSummaryRow {
+ const { content: _content, contentJson: _contentJson, ...summary } = mapDocument(row, isFavorite);
+ return summary;
+}
+
+function mapRevision(row: typeof projectDocumentRevision.$inferSelect): DocumentRevisionRow {
+ const { ownerUserId: _ownerUserId, ...publicRow } = row;
+ return {
+ ...publicRow,
+ archivedAt: row.archivedAt ? iso(row.archivedAt) : null,
+ createdAt: iso(row.createdAt),
+ };
+}
+
+function mapAsset(row: typeof documentAsset.$inferSelect): DocumentAssetRow {
+ return { ...row, createdAt: iso(row.createdAt) };
+}
+
+export function replaceAssetReferences<T>(
+ value: T,
+ sourceDocumentId: number,
+ targetProjectKey: string,
+ targetDocumentId: number,
+ publicIds: Map<string, string>,
+): T {
+ if (typeof value === 'string') {
+ const replaced = value.replace(
+ new RegExp(
+ `(/(?:protected-)?media)?/projects/[^/\\s"']+/documents/${sourceDocumentId}/assets/([0-9a-f-]{36})/raw`,
+ 'gi',
+ ),
+ (match, mediaPrefix: string | undefined, publicId: string) => {
+ const targetPublicId = publicIds.get(publicId.toLowerCase());
+ return targetPublicId
+ ? `${mediaPrefix ?? ''}/projects/${encodeURIComponent(targetProjectKey)}/documents/${targetDocumentId}/assets/${targetPublicId}/raw`
+ : match;
+ },
+ );
+ return replaced as T;
+ }
+ if (Array.isArray(value)) {
+ return value.map((item) =>
+ replaceAssetReferences(item, sourceDocumentId, targetProjectKey, targetDocumentId, publicIds),
+ ) as T;
+ }
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [
+ key,
+ replaceAssetReferences(
+ item,
+ sourceDocumentId,
+ targetProjectKey,
+ targetDocumentId,
+ publicIds,
+ ),
+ ]),
+ ) as T;
+ }
+ return value;
+}
+
+function revisionSummaryOf(
+ row: typeof projectDocumentRevision.$inferSelect,
+): DocumentRevisionSummaryRow {
+ const {
+ parentId: _parentId,
+ content: _content,
+ contentJson: _contentJson,
+ icon: _icon,
+ metadata: _metadata,
+ fullWidth: _fullWidth,
+ isPrivate: _isPrivate,
+ isLocked: _isLocked,
+ archivedAt: _archivedAt,
+ position: _position,
+ ...summary
+ } = mapRevision(row);
+ return summary;
+}
+
+async function favoriteDocumentIds(
+ executor: Executor,
+ userId: string,
+ documentIds: number[],
+): Promise<Set<number>> {
+ if (documentIds.length === 0) return new Set();
+ const rows = await executor
+ .select({ documentId: projectDocumentPreference.documentId })
+ .from(projectDocumentPreference)
+ .where(
+ and(
+ eq(projectDocumentPreference.userId, userId),
+ eq(projectDocumentPreference.isFavorite, true),
+ inArray(projectDocumentPreference.documentId, documentIds),
+ ),
+ );
+ return new Set(rows.map((row) => row.documentId));
+}
+
+export async function listDocuments(
+ projectId: number,
+ userId: string,
+ options: { q?: string; archived?: boolean } = {},
+): Promise<DocumentSummaryRow[]> {
+ const term = options.q?.trim();
+ const conditions = [
+ eq(projectDocument.projectId, projectId),
+ documentAccess(userId),
+ options.archived ? isNotNull(projectDocument.archivedAt) : isNull(projectDocument.archivedAt),
+ ];
+ if (term) {
+ conditions.push(
+ or(ilike(projectDocument.title, `%${term}%`), ilike(projectDocument.content, `%${term}%`)),
+ );
+ }
+ const rows = await db
+ .select()
+ .from(projectDocument)
+ .where(and(...conditions))
+ .orderBy(asc(projectDocument.position), asc(projectDocument.id));
+ const visibleIds = new Set(rows.map((row) => row.id));
+ const favorites = await favoriteDocumentIds(
+ db,
+ userId,
+ rows.map((row) => row.id),
+ );
+ return rows.map((row) => ({
+ ...summaryOf(row, favorites.has(row.id)),
+ parentId: row.parentId !== null && visibleIds.has(row.parentId) ? row.parentId : null,
+ }));
+}
+
+async function selectDocument(
+ executor: Executor,
+ projectId: number,
+ documentId: number,
+ userId: string,
+) {
+ const [row] = await executor
+ .select()
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.projectId, projectId),
+ documentAccess(userId),
+ ),
+ );
+ return row ?? null;
+}
+
+export async function getDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<DocumentRow | null> {
+ const row = await selectDocument(db, projectId, documentId, userId);
+ if (!row) return null;
+ return mapDocumentForUser(db, row, userId);
+}
+
+export async function listDocumentAssets(
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<DocumentAssetRow[] | null> {
+ if (!(await selectDocument(db, projectId, documentId, userId))) return null;
+ const rows = await db
+ .select()
+ .from(documentAsset)
+ .where(eq(documentAsset.documentId, documentId))
+ .orderBy(asc(documentAsset.createdAt), asc(documentAsset.id));
+ return rows.map(mapAsset);
+}
+
+export async function assertDocumentAssetUploadTarget(
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<boolean> {
+ const current = await selectDocument(db, projectId, documentId, userId);
+ if (!current) return false;
+ assertActive(current);
+ assertUnlocked(current);
+ return true;
+}
+
+export async function createDocumentAsset(input: {
+ projectId: number;
+ documentId: number;
+ userId: string;
+ s3Key: string;
+ filename: string;
+ contentType: string;
+ sizeBytes: number;
+}): Promise<DocumentAssetRow | null> {
+ return db.transaction(async (tx) => {
+ // Global lock order for asset writes is quota -> actor -> document. Holding
+ // KEY SHARE prevents account deletion from taking the user row and then
+ // waiting on this document while the asset FK waits back on the user.
+ await lockAttachmentStorage(tx, input.projectId);
+ await lockDocumentActor(tx, input.userId);
+ await assertAttachmentStorageCapacity(input.projectId, input.sizeBytes, 0, tx);
+ await tx.execute(
+ sql`select 1 from ${projectDocument} where ${projectDocument.id} = ${input.documentId} and ${projectDocument.projectId} = ${input.projectId} for update`,
+ );
+ const current = await selectDocument(tx, input.projectId, input.documentId, input.userId);
+ if (!current) return null;
+ assertActive(current);
+ assertUnlocked(current);
+ const [row] = await tx
+ .insert(documentAsset)
+ .values({
+ documentId: input.documentId,
+ uploadedByUserId: input.userId,
+ s3Key: input.s3Key,
+ filename: input.filename,
+ contentType: input.contentType,
+ sizeBytes: input.sizeBytes,
+ })
+ .returning();
+ return mapAsset(row);
+ });
+}
+
+export async function getDocumentAsset(
+ projectId: number,
+ documentId: number,
+ publicId: string,
+ userId: string,
+): Promise<DocumentAssetRow | null> {
+ if (!(await selectDocument(db, projectId, documentId, userId))) return null;
+ const [row] = await db
+ .select()
+ .from(documentAsset)
+ .where(and(eq(documentAsset.documentId, documentId), eq(documentAsset.publicId, publicId)));
+ return row ? mapAsset(row) : null;
+}
+
+export async function deleteDocumentAsset(
+ projectId: number,
+ documentId: number,
+ publicId: string,
+ userId: string,
+ isProjectOwner: boolean,
+): Promise<DocumentAssetRow | null> {
+ return db.transaction(async (tx) => {
+ await tx.execute(
+ sql`select 1 from ${projectDocument} where ${projectDocument.id} = ${documentId} and ${projectDocument.projectId} = ${projectId} for update`,
+ );
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertActive(current);
+ assertUnlocked(current);
+ const [row] = await tx
+ .delete(documentAsset)
+ .where(and(eq(documentAsset.documentId, documentId), eq(documentAsset.publicId, publicId)))
+ .returning();
+ return row ? mapAsset(row) : null;
+ });
+}
+
+async function mapDocumentForUser(
+ executor: Executor,
+ row: typeof projectDocument.$inferSelect,
+ userId: string,
+): Promise<DocumentRow> {
+ const favorites = await favoriteDocumentIds(executor, userId, [row.id]);
+ const parentId = await visibleDocumentParentId(executor, row.projectId, row.parentId, userId);
+ return mapDocument({ ...row, parentId }, favorites.has(row.id));
+}
+
+async function visibleDocumentParentId(
+ executor: Executor,
+ projectId: number,
+ parentId: number | null,
+ userId: string,
+): Promise<number | null> {
+ if (parentId === null) return null;
+ const [parent] = await executor
+ .select({ id: projectDocument.id })
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.id, parentId),
+ eq(projectDocument.projectId, projectId),
+ documentAccess(userId),
+ ),
+ );
+ return parent?.id ?? null;
+}
+
+async function assertValidParent(
+ executor: Executor,
+ projectId: number,
+ documentId: number | null,
+ parentId: number | null,
+ userId: string,
+): Promise<void> {
+ let cursor = parentId;
+ const seen = new Set<number>();
+ while (cursor !== null) {
+ if (cursor === documentId || seen.has(cursor)) {
+ throw new HttpError(400, 'A document cannot be nested inside itself');
+ }
+ seen.add(cursor);
+ const [parent] = await executor
+ .select({
+ projectId: projectDocument.projectId,
+ parentId: projectDocument.parentId,
+ archivedAt: projectDocument.archivedAt,
+ })
+ .from(projectDocument)
+ .where(and(eq(projectDocument.id, cursor), documentAccess(userId)));
+ if (!parent || parent.projectId !== projectId) {
+ throw new HttpError(400, 'Parent document must belong to the same project');
+ }
+ if (parent.archivedAt !== null) {
+ throw new HttpError(400, 'An archived document cannot be used as a parent');
+ }
+ cursor = parent.parentId;
+ }
+}
+
+async function nextPosition(
+ executor: Executor,
+ projectId: number,
+ parentId: number | null,
+): Promise<number> {
+ const sameParent =
+ parentId === null ? isNull(projectDocument.parentId) : eq(projectDocument.parentId, parentId);
+ const [row] = await executor
+ .select({ value: sql<number>`coalesce(max(${projectDocument.position}), 0) + 1024` })
+ .from(projectDocument)
+ .where(
+ and(eq(projectDocument.projectId, projectId), isNull(projectDocument.archivedAt), sameParent),
+ );
+ return Number(row?.value ?? 1024);
+}
+
+interface DocumentMovePlan {
+ position: number;
+ siblingPositions: Array<{ id: number; position: number }>;
+}
+
+function safeDocumentPosition(
+ previous: { position: number } | undefined,
+ next: { position: number } | undefined,
+ occupied: Array<{ position: number }>,
+): number | null {
+ let candidate: number;
+ if (!previous && !next) candidate = 1024;
+ else if (!previous) candidate = next!.position - 1024;
+ else if (!next) candidate = previous.position + 1024;
+ else {
+ const gap = next.position - previous.position;
+ const scale = Math.max(1, Math.abs(previous.position), Math.abs(next.position));
+ if (!Number.isFinite(gap) || gap <= Number.EPSILON * scale * 4) return null;
+ candidate = previous.position + gap / 2;
+ if (!(candidate > previous.position && candidate < next.position)) return null;
+ }
+ if (!Number.isFinite(candidate)) return null;
+ return occupied.some((sibling) => sibling.position === candidate) ? null : candidate;
+}
+
+async function planDocumentMove(
+ executor: Executor,
+ projectId: number,
+ documentId: number,
+ parentId: number | null,
+ previousSiblingId: number | null,
+ nextSiblingId: number | null,
+): Promise<DocumentMovePlan> {
+ if (previousSiblingId === documentId || nextSiblingId === documentId) {
+ throw new HttpError(400, 'A document cannot be its own move anchor.');
+ }
+ const sameParent =
+ parentId === null ? isNull(projectDocument.parentId) : eq(projectDocument.parentId, parentId);
+ const siblings = (
+ await executor
+ .select({ id: projectDocument.id, position: projectDocument.position })
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.projectId, projectId),
+ sameParent,
+ isNull(projectDocument.archivedAt),
+ ),
+ )
+ .orderBy(asc(projectDocument.position), asc(projectDocument.id))
+ ).filter((sibling) => sibling.id !== documentId);
+
+ const previousIndex =
+ previousSiblingId === null
+ ? -1
+ : siblings.findIndex((sibling) => sibling.id === previousSiblingId);
+ const nextIndex =
+ nextSiblingId === null
+ ? siblings.length
+ : siblings.findIndex((sibling) => sibling.id === nextSiblingId);
+ if (
+ (previousSiblingId !== null && previousIndex < 0) ||
+ (nextSiblingId !== null && nextIndex < 0) ||
+ (previousSiblingId !== null && nextSiblingId !== null && previousIndex >= nextIndex)
+ ) {
+ throw new HttpError(409, 'Document order changed elsewhere. Reload it before moving.');
+ }
+
+ // Private siblings invisible to this caller may sit between two visible
+ // anchors. Preserve their relative order and place the moved page immediately
+ // after the previous anchor (or immediately before the next one at the start).
+ const insertionIndex =
+ previousSiblingId !== null ? previousIndex + 1 : nextSiblingId !== null ? nextIndex : 0;
+ const candidate = safeDocumentPosition(
+ siblings[insertionIndex - 1],
+ siblings[insertionIndex],
+ siblings,
+ );
+ if (candidate !== null) return { position: candidate, siblingPositions: [] };
+
+ const orderedIds = siblings.map((sibling) => sibling.id);
+ orderedIds.splice(insertionIndex, 0, documentId);
+ return {
+ position: (insertionIndex + 1) * 1024,
+ siblingPositions: orderedIds.map((id, index) => ({ id, position: (index + 1) * 1024 })),
+ };
+}
+
+export async function createDocument(input: {
+ projectId: number;
+ userId: string;
+ title?: string;
+ content?: string;
+ contentJson?: Record<string, unknown> | null;
+ icon?: string | null;
+ metadata?: Record<string, unknown>;
+ fullWidth?: boolean;
+ isPrivate?: boolean;
+ parentId?: number | null;
+}): Promise<DocumentRow> {
+ assertValidDocumentContentJson(input.contentJson);
+ assertValidMetadata(input.metadata);
+ const parentId = input.parentId ?? null;
+ return db.transaction(async (tx) => {
+ await lockDocumentActor(tx, input.userId);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${input.projectId})`,
+ );
+ await assertValidParent(tx, input.projectId, null, parentId, input.userId);
+ const [row] = await tx
+ .insert(projectDocument)
+ .values({
+ projectId: input.projectId,
+ parentId,
+ title: input.title ?? '',
+ content: input.content ?? '',
+ contentJson: input.contentJson ?? null,
+ icon: input.icon,
+ metadata: input.metadata ?? {},
+ fullWidth: input.fullWidth ?? false,
+ isPrivate: input.isPrivate ?? false,
+ position: await nextPosition(tx, input.projectId, parentId),
+ ownerUserId: input.userId,
+ createdByUserId: input.userId,
+ updatedByUserId: input.userId,
+ })
+ .returning();
+ return mapDocumentForUser(tx, row, input.userId);
+ });
+}
+
+function assertExpectedVersion(row: { version: number }, expected: number): void {
+ if (row.version !== expected) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+}
+
+function assertActive(row: { archivedAt: Date | null }): void {
+ if (row.archivedAt !== null) {
+ throw new HttpError(409, 'Restore this document before changing it.');
+ }
+}
+
+function assertUnlocked(row: { isLocked: boolean }): void {
+ if (row.isLocked) {
+ throw new HttpError(409, 'Unlock this document before changing it.');
+ }
+}
+
+const MAX_DOCUMENT_JSON_BYTES = 1_000_000;
+const MAX_DOCUMENT_JSON_NODES = 10_000;
+const MAX_DOCUMENT_JSON_DEPTH = 100;
+const MAX_DOCUMENT_METADATA_BYTES = 16_384;
+const DOCUMENT_NODE_TYPES = new Set([
+ 'doc',
+ 'paragraph',
+ 'text',
+ 'blockquote',
+ 'bulletList',
+ 'orderedList',
+ 'listItem',
+ 'heading',
+ 'horizontalRule',
+ 'hardBreak',
+ 'codeBlock',
+ 'image',
+ 'table',
+ 'tableRow',
+ 'tableHeader',
+ 'tableCell',
+ 'taskList',
+ 'taskItem',
+]);
+const DOCUMENT_MARK_TYPES = new Set([
+ 'bold',
+ 'italic',
+ 'strike',
+ 'code',
+ 'link',
+ 'textStyle',
+ 'underline',
+ 'highlight',
+]);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function assertJsonByteSize(value: unknown, maximum: number, field: string): void {
+ let bytes: number;
+ try {
+ bytes = Buffer.byteLength(JSON.stringify(value), 'utf8');
+ } catch {
+ throw new HttpError(400, `${field} must contain valid JSON values.`);
+ }
+ if (bytes > maximum) throw new HttpError(400, `${field} exceeds the ${maximum} byte limit.`);
+}
+
+function documentAttributes(value: Record<string, unknown>): Record<string, unknown> {
+ if (value.attrs == null) return {};
+ if (!isRecord(value.attrs)) throw new HttpError(400, 'Document attrs must be an object.');
+ return value.attrs;
+}
+
+function assertAllowedAttributes(
+ attrs: Record<string, unknown>,
+ allowed: readonly string[],
+ context: string,
+): void {
+ const allowedKeys = new Set(allowed);
+ const unknown = Object.keys(attrs).find((key) => !allowedKeys.has(key));
+ if (unknown) throw new HttpError(400, `${context} contains an unsupported "${unknown}" attr.`);
+}
+
+function assertOptionalBoundedString(value: unknown, maximum: number, context: string): void {
+ if (value == null) return;
+ if (typeof value !== 'string' || value.length > maximum) {
+ throw new HttpError(400, `${context} must be a string no longer than ${maximum} characters.`);
+ }
+}
+
+function containsUnsafeUrlCharacter(value: string): boolean {
+ return [...value].some(
+ (character) => character === '\\' || /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(character),
+ );
+}
+
+function assertSafeLinkHref(value: unknown): void {
+ if (typeof value !== 'string' || value.length === 0 || value.length > 2_048) {
+ throw new HttpError(400, 'A link href must be a non-empty string up to 2048 characters.');
+ }
+ if (containsUnsafeUrlCharacter(value)) {
+ throw new HttpError(400, 'A link href cannot contain whitespace, controls, or backslashes.');
+ }
+ if (value.startsWith('#')) return;
+ if (value.startsWith('/') && !value.startsWith('//')) return;
+ if (/^(mailto:|tel:)/i.test(value)) {
+ if (value.slice(value.indexOf(':') + 1).length > 0) return;
+ throw new HttpError(400, 'A mailto or tel link must contain a destination.');
+ }
+ try {
+ const parsed = new URL(value);
+ if (
+ (parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
+ !parsed.username &&
+ !parsed.password
+ ) {
+ return;
+ }
+ } catch {
+ // Fall through to the uniform validation error below.
+ }
+ throw new HttpError(400, 'A link href must use http, https, mailto, tel, /path, or #anchor.');
+}
+
+const DOCUMENT_ASSET_PATH =
+ /^\/(?:protected-media\/)?projects\/[A-Za-z0-9._~%+-]+\/documents\/[1-9]\d*\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/raw$/i;
+
+function assertSafeImageSource(value: unknown): void {
+ if (typeof value !== 'string' || value.length === 0 || value.length > 4_096) {
+ throw new HttpError(400, 'An image src must be a non-empty string up to 4096 characters.');
+ }
+ if (containsUnsafeUrlCharacter(value)) {
+ throw new HttpError(400, 'An image src cannot contain whitespace, controls, or backslashes.');
+ }
+ if (DOCUMENT_ASSET_PATH.test(value)) return;
+ try {
+ const parsed = new URL(value);
+ if (
+ (parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
+ !parsed.username &&
+ !parsed.password
+ ) {
+ return;
+ }
+ } catch {
+ // Fall through to the uniform validation error below.
+ }
+ throw new HttpError(400, 'An image src must use http, https, or a protected Docs asset URL.');
+}
+
+function assertSafeColor(value: unknown): void {
+ if (
+ value !== undefined &&
+ value !== null &&
+ (typeof value !== 'string' ||
+ !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value))
+ ) {
+ throw new HttpError(400, 'Document colors must use a hexadecimal color value.');
+ }
+}
+
+function assertDocumentNodeAttributes(node: Record<string, unknown>): void {
+ const attrs = documentAttributes(node);
+ switch (node.type) {
+ case 'paragraph':
+ assertAllowedAttributes(attrs, ['textAlign'], 'A paragraph');
+ if (
+ attrs.textAlign != null &&
+ !['left', 'center', 'right'].includes(String(attrs.textAlign))
+ ) {
+ throw new HttpError(400, 'Paragraph textAlign must be left, center, or right.');
+ }
+ return;
+ case 'heading':
+ assertAllowedAttributes(attrs, ['level', 'textAlign'], 'A heading');
+ if (!Number.isInteger(attrs.level) || Number(attrs.level) < 1 || Number(attrs.level) > 6) {
+ throw new HttpError(400, 'Heading level must be an integer from 1 to 6.');
+ }
+ if (
+ attrs.textAlign != null &&
+ !['left', 'center', 'right'].includes(String(attrs.textAlign))
+ ) {
+ throw new HttpError(400, 'Heading textAlign must be left, center, or right.');
+ }
+ return;
+ case 'image': {
+ assertAllowedAttributes(attrs, ['src', 'alt', 'title', 'width', 'style'], 'An image');
+ assertSafeImageSource(attrs.src);
+ assertOptionalBoundedString(attrs.alt, 1_000, 'Image alt');
+ assertOptionalBoundedString(attrs.title, 1_000, 'Image title');
+ if (
+ attrs.width != null &&
+ (!Number.isInteger(attrs.width) || Number(attrs.width) < 1 || Number(attrs.width) > 4_096)
+ ) {
+ throw new HttpError(400, 'Image width must be an integer from 1 to 4096.');
+ }
+ if (
+ attrs.style != null &&
+ (typeof attrs.style !== 'string' || !/^max-width: *(?:100|[1-9]\d?)%;?$/i.test(attrs.style))
+ ) {
+ throw new HttpError(400, 'Image style may only contain a max-width percentage.');
+ }
+ return;
+ }
+ case 'taskItem':
+ assertAllowedAttributes(attrs, ['checked'], 'A task item');
+ if (attrs.checked !== undefined && typeof attrs.checked !== 'boolean') {
+ throw new HttpError(400, 'Task item checked must be a boolean.');
+ }
+ return;
+ case 'tableCell':
+ case 'tableHeader': {
+ assertAllowedAttributes(attrs, ['colspan', 'rowspan', 'colwidth'], 'A table cell');
+ for (const key of ['colspan', 'rowspan'] as const) {
+ const span = attrs[key];
+ if (
+ span !== undefined &&
+ (!Number.isInteger(span) || Number(span) < 1 || Number(span) > 100)
+ ) {
+ throw new HttpError(400, `Table ${key} must be an integer from 1 to 100.`);
+ }
+ }
+ if (
+ attrs.colwidth != null &&
+ (!Array.isArray(attrs.colwidth) ||
+ attrs.colwidth.length === 0 ||
+ attrs.colwidth.length > 100 ||
+ attrs.colwidth.some(
+ (width) => !Number.isInteger(width) || Number(width) < 1 || Number(width) > 10_000,
+ ))
+ ) {
+ throw new HttpError(400, 'Table colwidth must contain positive integer widths.');
+ }
+ return;
+ }
+ case 'orderedList':
+ assertAllowedAttributes(attrs, ['start'], 'An ordered list');
+ if (
+ attrs.start !== undefined &&
+ (!Number.isInteger(attrs.start) ||
+ Number(attrs.start) < 1 ||
+ Number(attrs.start) > 1_000_000)
+ ) {
+ throw new HttpError(400, 'Ordered-list start must be a positive integer.');
+ }
+ return;
+ case 'codeBlock':
+ assertAllowedAttributes(attrs, ['language'], 'A code block');
+ assertOptionalBoundedString(attrs.language, 100, 'Code-block language');
+ return;
+ default:
+ assertAllowedAttributes(attrs, [], `A ${String(node.type)} node`);
+ }
+}
+
+function assertDocumentMarkAttributes(mark: Record<string, unknown>): void {
+ const attrs = documentAttributes(mark);
+ switch (mark.type) {
+ case 'link':
+ assertAllowedAttributes(attrs, ['href', 'target', 'rel', 'class'], 'A link');
+ assertSafeLinkHref(attrs.href);
+ if (attrs.target != null && !['_blank', '_self'].includes(String(attrs.target))) {
+ throw new HttpError(400, 'Link target must be _blank or _self.');
+ }
+ assertOptionalBoundedString(attrs.rel, 200, 'Link rel');
+ if (typeof attrs.rel === 'string' && !/^[a-z -]*$/i.test(attrs.rel)) {
+ throw new HttpError(400, 'Link rel contains unsupported characters.');
+ }
+ assertOptionalBoundedString(attrs.class, 200, 'Link class');
+ if (typeof attrs.class === 'string' && !/^[a-z0-9 _-]*$/i.test(attrs.class)) {
+ throw new HttpError(400, 'Link class contains unsupported characters.');
+ }
+ return;
+ case 'textStyle':
+ case 'highlight':
+ assertAllowedAttributes(attrs, ['color'], `A ${String(mark.type)} mark`);
+ assertSafeColor(attrs.color);
+ return;
+ default:
+ assertAllowedAttributes(attrs, [], `A ${String(mark.type)} mark`);
+ }
+}
+
+function assertDocumentJsonNode(value: unknown, depth: number, counter: { value: number }): void {
+ if (!isRecord(value) || typeof value.type !== 'string' || !DOCUMENT_NODE_TYPES.has(value.type)) {
+ throw new HttpError(400, 'contentJson contains an unsupported document node.');
+ }
+ counter.value += 1;
+ if (counter.value > MAX_DOCUMENT_JSON_NODES || depth > MAX_DOCUMENT_JSON_DEPTH) {
+ throw new HttpError(400, 'contentJson is too deeply nested or contains too many nodes.');
+ }
+ if (value.type === 'text' && typeof value.text !== 'string') {
+ throw new HttpError(400, 'A contentJson text node must contain text.');
+ }
+ assertDocumentNodeAttributes(value);
+ if ('content' in value) {
+ if (!Array.isArray(value.content)) {
+ throw new HttpError(400, 'contentJson node content must be an array.');
+ }
+ for (const child of value.content) assertDocumentJsonNode(child, depth + 1, counter);
+ }
+ if ('marks' in value) {
+ if (!Array.isArray(value.marks)) {
+ throw new HttpError(400, 'contentJson node marks must be an array.');
+ }
+ for (const mark of value.marks) {
+ if (!isRecord(mark) || typeof mark.type !== 'string' || !DOCUMENT_MARK_TYPES.has(mark.type)) {
+ throw new HttpError(400, 'contentJson contains an unsupported document mark.');
+ }
+ assertDocumentMarkAttributes(mark);
+ }
+ }
+}
+
+export function assertValidDocumentContentJson(
+ value: Record<string, unknown> | null | undefined,
+): void {
+ if (value == null) return;
+ if (!isRecord(value) || value.type !== 'doc') {
+ throw new HttpError(400, 'contentJson must be a Tiptap document object.');
+ }
+ assertJsonByteSize(value, MAX_DOCUMENT_JSON_BYTES, 'contentJson');
+ assertDocumentJsonNode(value, 0, { value: 0 });
+}
+
+function assertValidMetadata(value: Record<string, unknown> | undefined): void {
+ if (value === undefined) return;
+ if (!isRecord(value)) throw new HttpError(400, 'metadata must be an object.');
+ assertJsonByteSize(value, MAX_DOCUMENT_METADATA_BYTES, 'metadata');
+}
+
+export async function updateDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ input: {
+ version: number;
+ title?: string;
+ content?: string;
+ contentJson?: Record<string, unknown> | null;
+ icon?: string | null;
+ metadata?: Record<string, unknown>;
+ fullWidth?: boolean;
+ parentId?: number | null;
+ position?: number;
+ previousSiblingId?: number | null;
+ nextSiblingId?: number | null;
+ },
+): Promise<DocumentRow | null> {
+ assertValidDocumentContentJson(input.contentJson);
+ assertValidMetadata(input.metadata);
+ return db.transaction(async (tx) => {
+ const anchoredMove = input.previousSiblingId !== undefined || input.nextSiblingId !== undefined;
+ if (anchoredMove && (input.parentId === undefined || input.position === undefined)) {
+ throw new HttpError(400, 'An anchored move requires parentId and position.');
+ }
+ if (input.position !== undefined && !Number.isFinite(input.position)) {
+ throw new HttpError(400, 'Document position must be finite.');
+ }
+ const current = await selectDocument(tx, projectId, documentId, userId);
+ if (!current) return null;
+ await lockDocumentActors(tx, [userId, current.ownerUserId]);
+ if (input.parentId !== undefined || input.position !== undefined) {
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ }
+ assertExpectedVersion(current, input.version);
+ assertActive(current);
+ assertUnlocked(current);
+ if (input.parentId !== undefined) {
+ await assertValidParent(tx, projectId, documentId, input.parentId, userId);
+ }
+ const movePlan = anchoredMove
+ ? await planDocumentMove(
+ tx,
+ projectId,
+ documentId,
+ input.parentId!,
+ input.previousSiblingId ?? null,
+ input.nextSiblingId ?? null,
+ )
+ : null;
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ ...(input.title !== undefined ? { title: input.title } : {}),
+ ...(input.content !== undefined ? { content: input.content } : {}),
+ ...(input.contentJson !== undefined ? { contentJson: input.contentJson } : {}),
+ ...(input.icon !== undefined ? { icon: input.icon } : {}),
+ ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
+ ...(input.fullWidth !== undefined ? { fullWidth: input.fullWidth } : {}),
+ ...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
+ ...(input.position !== undefined ? { position: movePlan?.position ?? input.position } : {}),
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.projectId, projectId),
+ eq(projectDocument.version, input.version),
+ ),
+ )
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ if (movePlan) {
+ // Position normalization is implementation detail, not user-visible page
+ // history. The Docs sync trigger still fires so every client refetches the
+ // normalized sibling order, while sibling versions remain stable.
+ const normalized = movePlan.siblingPositions.filter((sibling) => sibling.id !== documentId);
+ if (normalized.length > 0) {
+ await tx.execute(sql`select set_config('app.document_rebalance', 'true', true)`);
+ const cases = sql.join(
+ normalized.map(
+ (sibling) => sql`when ${sibling.id} then ${sibling.position}::double precision`,
+ ),
+ sql` `,
+ );
+ await tx
+ .update(projectDocument)
+ .set({
+ position: sql`case ${projectDocument.id} ${cases} else ${projectDocument.position} end`,
+ })
+ .where(
+ and(
+ eq(projectDocument.projectId, projectId),
+ inArray(
+ projectDocument.id,
+ normalized.map((sibling) => sibling.id),
+ ),
+ ),
+ );
+ }
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+async function ownedDocument(
+ executor: Executor,
+ projectId: number,
+ documentId: number,
+ userId: string,
+ isProjectOwner: boolean,
+) {
+ const current = await selectDocument(executor, projectId, documentId, userId);
+ if (!current) return null;
+ if (current.ownerUserId !== userId && !(isProjectOwner && !current.isPrivate)) {
+ throw new HttpError(403, 'Only the document owner can change this setting.');
+ }
+ return current;
+}
+
+export async function setDocumentAccess(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ isPrivate: boolean,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ // Lock the owner before the page can become private. Account deletion then
+ // either sees and removes the committed private row, or finishes first and
+ // this request stops without creating an ownerless private page.
+ const visible = await selectDocument(tx, projectId, documentId, userId);
+ if (!visible) return null;
+ await lockDocumentActors(tx, [userId, visible.ownerUserId]);
+ const current = await ownedDocument(tx, projectId, documentId, userId, false);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ assertActive(current);
+ if (current.isPrivate === isPrivate) return mapDocumentForUser(tx, current, userId);
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ isPrivate,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(and(eq(projectDocument.id, documentId), eq(projectDocument.version, version)))
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+export async function transferDocumentOwnership(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ ownerUserId: string,
+ isProjectOwner: boolean,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ const visible = await selectDocument(tx, projectId, documentId, userId);
+ if (!visible) return null;
+ await lockDocumentActors(tx, [userId, visible.ownerUserId, ownerUserId]);
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ const [target] = await tx
+ .select({ userId: projectMember.userId })
+ .from(projectMember)
+ .where(and(eq(projectMember.projectId, projectId), eq(projectMember.userId, ownerUserId)));
+ if (!target) throw new HttpError(400, 'The new document owner must belong to this project.');
+ if (current.ownerUserId === ownerUserId) return mapDocumentForUser(tx, current, userId);
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ ownerUserId,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(and(eq(projectDocument.id, documentId), eq(projectDocument.version, version)))
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+export async function setDocumentLocked(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ isLocked: boolean,
+ isProjectOwner: boolean,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ const visible = await selectDocument(tx, projectId, documentId, userId);
+ if (!visible) return null;
+ await lockDocumentActors(tx, [userId, visible.ownerUserId]);
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ assertActive(current);
+ if (current.isLocked === isLocked) return mapDocumentForUser(tx, current, userId);
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ isLocked,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(and(eq(projectDocument.id, documentId), eq(projectDocument.version, version)))
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+async function documentSubtreeIds(
+ executor: Executor,
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<number[]> {
+ const rows = await executor
+ .select({ id: projectDocument.id, parentId: projectDocument.parentId })
+ .from(projectDocument)
+ .where(and(eq(projectDocument.projectId, projectId), documentAccess(userId)));
+ const ids = new Set<number>([documentId]);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const row of rows) {
+ if (row.parentId !== null && ids.has(row.parentId) && !ids.has(row.id)) {
+ ids.add(row.id);
+ changed = true;
+ }
+ }
+ }
+ return [...ids];
+}
+
+export async function archiveDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ isProjectOwner: boolean,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ await lockProjectDocumentActors(tx, projectId, userId);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ await tx.execute(
+ sql`select 1 from ${projectDocument} where ${projectDocument.id} = ${documentId} and ${projectDocument.projectId} = ${projectId} for update`,
+ );
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ assertActive(current);
+ assertUnlocked(current);
+ const ids = await documentSubtreeIds(tx, projectId, documentId, userId);
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ archivedAt: sql`now()`,
+ archivedByAncestorId: null,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.version, version),
+ isNull(projectDocument.archivedAt),
+ ),
+ )
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ const descendantIds = ids.filter((id) => id !== documentId);
+ if (descendantIds.length > 0) {
+ await tx
+ .update(projectDocument)
+ .set({
+ archivedAt: sql`now()`,
+ archivedByAncestorId: documentId,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(and(inArray(projectDocument.id, descendantIds), isNull(projectDocument.archivedAt)));
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+export async function restoreDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ isProjectOwner: boolean,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ await lockProjectDocumentActors(tx, projectId, userId);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ await tx.execute(
+ sql`select 1 from ${projectDocument} where ${projectDocument.id} = ${documentId} and ${projectDocument.projectId} = ${projectId} for update`,
+ );
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ if (current.archivedAt === null) {
+ throw new HttpError(409, 'This document is not archived.');
+ }
+ const archiveBatchId = current.archivedByAncestorId ?? documentId;
+ const ids = await documentSubtreeIds(tx, projectId, documentId, userId);
+ let detachFromParent = false;
+ if (current.parentId !== null) {
+ const [parent] = await tx
+ .select({ archivedAt: projectDocument.archivedAt })
+ .from(projectDocument)
+ .where(and(eq(projectDocument.id, current.parentId), documentAccess(userId)));
+ detachFromParent = !parent || parent.archivedAt !== null;
+ }
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ archivedAt: null,
+ archivedByAncestorId: null,
+ ...(detachFromParent ? { parentId: null } : {}),
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.version, version),
+ isNotNull(projectDocument.archivedAt),
+ ),
+ )
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ const descendantIds = ids.filter((id) => id !== documentId);
+ if (descendantIds.length > 0) {
+ await tx
+ .update(projectDocument)
+ .set({
+ archivedAt: null,
+ archivedByAncestorId: null,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(
+ and(
+ inArray(projectDocument.id, descendantIds),
+ eq(projectDocument.archivedByAncestorId, archiveBatchId),
+ isNotNull(projectDocument.archivedAt),
+ ),
+ );
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+export async function duplicateDocument(input: {
+ projectId: number;
+ documentId: number;
+ userId: string;
+ version: number;
+ title?: string;
+ parentId?: number | null;
+}): Promise<DocumentRow | null> {
+ const copiedObjectKeys: string[] = [];
+ try {
+ return await db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, input.projectId);
+ await lockDocumentActor(tx, input.userId);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${input.projectId})`,
+ );
+ await tx.execute(
+ sql`select 1 from ${projectDocument} where ${projectDocument.id} = ${input.documentId} and ${projectDocument.projectId} = ${input.projectId} for share`,
+ );
+ const source = await selectDocument(tx, input.projectId, input.documentId, input.userId);
+ if (!source) return null;
+ assertExpectedVersion(source, input.version);
+ assertValidDocumentContentJson(source.contentJson);
+ const parentId =
+ input.parentId === undefined
+ ? await usableRevisionParent(tx, input.projectId, null, source.parentId, input.userId)
+ : input.parentId;
+ if (input.parentId !== undefined) {
+ await assertValidParent(tx, input.projectId, null, parentId, input.userId);
+ }
+ const [row] = await tx
+ .insert(projectDocument)
+ .values({
+ projectId: input.projectId,
+ parentId,
+ title: input.title ?? `${source.title || 'Untitled'} (Copy)`,
+ content: source.content,
+ contentJson: source.contentJson,
+ icon: source.icon,
+ metadata: source.metadata,
+ fullWidth: source.fullWidth,
+ isPrivate: source.isPrivate,
+ position: await nextPosition(tx, input.projectId, parentId),
+ ownerUserId: input.userId,
+ createdByUserId: input.userId,
+ updatedByUserId: input.userId,
+ })
+ .returning();
+ const assets = await tx
+ .select()
+ .from(documentAsset)
+ .where(eq(documentAsset.documentId, source.id));
+ await assertAttachmentStorageCapacity(
+ input.projectId,
+ assets.reduce((total, asset) => total + asset.sizeBytes, 0),
+ 0,
+ tx,
+ );
+ for (const asset of assets) {
+ await assertAttachmentFileAllowed(asset.sizeBytes, asset.contentType);
+ }
+ const [projectRow] = await tx
+ .select({ key: project.key })
+ .from(project)
+ .where(eq(project.id, input.projectId));
+ const publicIds = new Map<string, string>();
+ for (const asset of assets) {
+ const key = attachmentObjectKey(input.projectId, 'documents', row.id, asset.filename);
+ await cloneAttachmentObject(asset.s3Key, key, asset.contentType);
+ copiedObjectKeys.push(key);
+ const [copy] = await tx
+ .insert(documentAsset)
+ .values({
+ documentId: row.id,
+ uploadedByUserId: input.userId,
+ s3Key: key,
+ filename: asset.filename,
+ contentType: asset.contentType,
+ sizeBytes: asset.sizeBytes,
+ })
+ .returning({ publicId: documentAsset.publicId });
+ publicIds.set(asset.publicId.toLowerCase(), copy.publicId);
+ }
+ if (publicIds.size > 0 && projectRow) {
+ const [rewritten] = await tx
+ .update(projectDocument)
+ .set({
+ content: replaceAssetReferences(
+ row.content,
+ source.id,
+ projectRow.key,
+ row.id,
+ publicIds,
+ ),
+ contentJson: replaceAssetReferences(
+ row.contentJson,
+ source.id,
+ projectRow.key,
+ row.id,
+ publicIds,
+ ),
+ })
+ .where(eq(projectDocument.id, row.id))
+ .returning();
+ return mapDocumentForUser(tx, rewritten, input.userId);
+ }
+ return mapDocumentForUser(tx, row, input.userId);
+ });
+ } catch (error) {
+ await Promise.all(copiedObjectKeys.map(deleteAttachmentObject));
+ throw error;
+ }
+}
+
+export async function setDocumentPreference(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ isFavorite: boolean,
+): Promise<{ isFavorite: boolean } | null> {
+ if (!(await selectDocument(db, projectId, documentId, userId))) return null;
+ await db
+ .insert(projectDocumentPreference)
+ .values({ documentId, userId, isFavorite, updatedAt: new Date() })
+ .onConflictDoUpdate({
+ target: [projectDocumentPreference.documentId, projectDocumentPreference.userId],
+ set: { isFavorite, updatedAt: new Date() },
+ });
+ return { isFavorite };
+}
+
+export async function listDocumentRevisions(
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<DocumentRevisionSummaryRow[] | null> {
+ const current = await selectDocument(db, projectId, documentId, userId);
+ if (!current) return null;
+ const rows = await db
+ .select()
+ .from(projectDocumentRevision)
+ .where(
+ and(
+ eq(projectDocumentRevision.documentId, documentId),
+ or(
+ eq(projectDocumentRevision.isPrivate, false),
+ eq(projectDocumentRevision.ownerUserId, userId),
+ ),
+ ),
+ )
+ .orderBy(desc(projectDocumentRevision.version));
+ return rows.map(revisionSummaryOf);
+}
+
+export async function getDocumentRevision(
+ projectId: number,
+ documentId: number,
+ revisionId: number,
+ userId: string,
+): Promise<DocumentRevisionRow | null> {
+ const current = await selectDocument(db, projectId, documentId, userId);
+ if (!current) return null;
+ const [row] = await db
+ .select()
+ .from(projectDocumentRevision)
+ .where(
+ and(
+ eq(projectDocumentRevision.id, revisionId),
+ eq(projectDocumentRevision.documentId, documentId),
+ or(
+ eq(projectDocumentRevision.isPrivate, false),
+ eq(projectDocumentRevision.ownerUserId, userId),
+ ),
+ ),
+ );
+ if (!row) return null;
+ const parentId = await visibleDocumentParentId(db, projectId, row.parentId, userId);
+ return mapRevision({ ...row, parentId });
+}
+
+async function usableRevisionParent(
+ executor: Executor,
+ projectId: number,
+ documentId: number | null,
+ parentId: number | null,
+ userId: string,
+): Promise<number | null> {
+ if (parentId === null) return null;
+ try {
+ await assertValidParent(executor, projectId, documentId, parentId, userId);
+ return parentId;
+ } catch (error) {
+ if (error instanceof HttpError && error.status === 400) return null;
+ throw error;
+ }
+}
+
+export async function restoreDocumentRevision(
+ projectId: number,
+ documentId: number,
+ revisionId: number,
+ userId: string,
+ version: number,
+): Promise<DocumentRow | null> {
+ return db.transaction(async (tx) => {
+ const visible = await selectDocument(tx, projectId, documentId, userId);
+ if (!visible) return null;
+ await lockDocumentActors(tx, [userId, visible.ownerUserId]);
+ await tx.execute(sql`select set_config('app.document_checkpoint', 'true', true)`);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ const current = await selectDocument(tx, projectId, documentId, userId);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ assertActive(current);
+ assertUnlocked(current);
+ const [revision] = await tx
+ .select()
+ .from(projectDocumentRevision)
+ .where(
+ and(
+ eq(projectDocumentRevision.id, revisionId),
+ eq(projectDocumentRevision.documentId, documentId),
+ or(
+ eq(projectDocumentRevision.isPrivate, false),
+ eq(projectDocumentRevision.ownerUserId, userId),
+ ),
+ ),
+ );
+ if (!revision) throw new HttpError(404, 'Document revision not found');
+ if (revision.isPrivate && (revision.ownerUserId !== userId || current.ownerUserId !== userId)) {
+ throw new HttpError(403, 'Only the current document owner can restore a private revision.');
+ }
+ assertValidDocumentContentJson(revision.contentJson);
+ const parentId = await usableRevisionParent(
+ tx,
+ projectId,
+ documentId,
+ revision.parentId,
+ userId,
+ );
+ const [row] = await tx
+ .update(projectDocument)
+ .set({
+ parentId,
+ title: revision.title,
+ content: revision.content,
+ contentJson: revision.contentJson,
+ icon: revision.icon,
+ metadata: revision.metadata,
+ fullWidth: revision.fullWidth,
+ position: revision.position,
+ // A historical secret may never be restored into a public current row.
+ // Restoring a public snapshot into a private page keeps the safer current
+ // access level instead of unexpectedly publishing it.
+ ...(revision.isPrivate ? { isPrivate: true } : {}),
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(and(eq(projectDocument.id, documentId), eq(projectDocument.version, version)))
+ .returning();
+ if (!row) {
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before continuing.');
+ }
+ return mapDocumentForUser(tx, row, userId);
+ });
+}
+
+export async function exportDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+): Promise<{
+ filename: string;
+ mimeType: 'text/markdown';
+ content: string;
+ version: number;
+ exportedAt: string;
+} | null> {
+ const document = await getDocument(projectId, documentId, userId);
+ if (!document) return null;
+ const printableTitle = [...document.title.trim()]
+ .map((character) => {
+ const code = character.charCodeAt(0);
+ return code < 32 || code === 127 ? '-' : character;
+ })
+ .join('');
+ const stem = printableTitle.replace(/[<>:"/\\|?*]/g, '-').slice(0, 120) || 'untitled';
+ return {
+ filename: `${stem}.md`,
+ mimeType: 'text/markdown',
+ content: document.content,
+ version: document.version,
+ exportedAt: iso(new Date()),
+ };
+}
+
+export async function deleteDocument(
+ projectId: number,
+ documentId: number,
+ userId: string,
+ version: number,
+ isProjectOwner: boolean,
+): Promise<string[] | null> {
+ return db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, projectId);
+ await lockProjectDocumentActors(tx, projectId, userId);
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ const current = await ownedDocument(tx, projectId, documentId, userId, isProjectOwner);
+ if (!current) return null;
+ assertExpectedVersion(current, version);
+ assertUnlocked(current);
+ if (current.archivedAt === null) {
+ throw new HttpError(409, 'Archive this document before deleting it.');
+ }
+ await tx
+ .update(projectDocument)
+ .set({
+ parentId: null,
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(
+ and(eq(projectDocument.projectId, projectId), eq(projectDocument.parentId, documentId)),
+ );
+ const assets = await tx
+ .select({ s3Key: documentAsset.s3Key })
+ .from(documentAsset)
+ .where(eq(documentAsset.documentId, documentId));
+ const rows = await tx
+ .delete(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.id, documentId),
+ eq(projectDocument.projectId, projectId),
+ eq(projectDocument.version, version),
+ ),
+ )
+ .returning({ id: projectDocument.id });
+ if (rows.length > 0) return assets.map((asset) => asset.s3Key);
+ throw new HttpError(409, 'This document changed elsewhere. Reload it before deleting.');
+ });
+}
diff --git a/apps/api/src/modules/god/__tests__/integration/god-users.test.ts b/apps/api/src/modules/god/__tests__/integration/god-users.test.ts
index da20ff9c..a37dd040 100644
--- a/apps/api/src/modules/god/__tests__/integration/god-users.test.ts
+++ b/apps/api/src/modules/god/__tests__/integration/god-users.test.ts
@@ -10,6 +10,19 @@ import { addUser, createAgentUser, joinProject, setup } from '../helpers';
const ALL = { kind: 'all' as const, limit: 50, offset: 0 };
+async function withoutDeadlock<T>(operation: Promise<T>): Promise<T> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const timeoutResult = new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error('concurrent document/account operation deadlocked')),
+ 10_000,
+ );
+ });
+ return Promise.race([operation, timeoutResult]).finally(() => {
+ if (timeout) clearTimeout(timeout);
+ });
+}
+
describe('god users', () => {
beforeEach(async () => {
await resetDb();
@@ -260,6 +273,143 @@ describe('god users', () => {
expect(remaining.data?.projects[0]).toMatchObject({ projectKey: 'MKT', ownerCount: 1 });
});
+ it('removes private documents while public documents remain recoverable', async () => {
+ const { god } = await setup();
+ const alice = await addUser({ email: '[email protected]' });
+ await alice.api.projects.post({ key: 'MKT', name: 'Marketing' });
+ await joinProject(alice, god, 'MKT', 'owner');
+ const pages = alice.api.projects({ projectKey: 'MKT' }).documents;
+ const shared = (await pages.post({ title: 'Shared handbook' })).data!;
+ const privatePage = (await pages.post({ title: 'Private draft', isPrivate: true })).data!;
+ const publicChild = (await pages.post({ title: 'Published child', parentId: privatePage.id }))
+ .data!;
+
+ expect((await god.api.god.users({ userId: alice.id }).delete()).status).toBe(204);
+
+ const documents = god.api.projects({ projectKey: 'MKT' }).documents;
+ const surviving = await documents({ documentId: shared.id }).get();
+ expect(surviving.data).toMatchObject({ ownerUserId: null, isPrivate: false, version: 2 });
+ expect((await documents({ documentId: privatePage.id }).get()).status).toBe(404);
+ expect((await documents({ documentId: publicChild.id }).get()).data).toMatchObject({
+ ownerUserId: null,
+ parentId: null,
+ version: 2,
+ });
+ expect(
+ (await documents({ documentId: publicChild.id }).revisions.get()).data?.map(
+ (revision) => revision.version,
+ ),
+ ).toEqual([2, 1]);
+ const claimed = await documents({ documentId: shared.id }).ownership.post({
+ version: surviving.data!.version,
+ ownerUserId: god.id,
+ });
+ expect(claimed.data).toMatchObject({ ownerUserId: god.id });
+ });
+
+ it('serializes a document upload with deletion of its uploader account', async () => {
+ const { god } = await setup();
+ const alice = await addUser({ email: '[email protected]' });
+ await alice.api.projects.post({ key: 'MKT', name: 'Marketing' });
+ await joinProject(alice, god, 'MKT', 'owner');
+ const pages = alice.api.projects({ projectKey: 'MKT' }).documents;
+ const privatePage = (await pages.post({ title: 'Private upload target', isPrivate: true }))
+ .data!;
+
+ const concurrent = Promise.all([
+ pages({ documentId: privatePage.id }).assets.post({
+ file: new File(['concurrent bytes'], 'race.txt', { type: 'text/plain' }),
+ }),
+ god.api.god.users({ userId: alice.id }).delete(),
+ ]);
+ const [upload, deletion] = await withoutDeadlock(concurrent);
+
+ expect(deletion.status).toBe(204);
+ expect([201, 401, 403, 404]).toContain(upload.status);
+ expect(
+ (
+ await god.api
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: privatePage.id })
+ .get()
+ ).status,
+ ).toBe(404);
+ });
+
+ it('does not leave an ownerless private page during access change and account deletion', async () => {
+ const { god } = await setup();
+ const alice = await addUser({ email: '[email protected]' });
+ await alice.api.projects.post({ key: 'MKT', name: 'Marketing' });
+ await joinProject(alice, god, 'MKT', 'owner');
+ const pages = alice.api.projects({ projectKey: 'MKT' }).documents;
+ const page = (await pages.post({ title: 'Public draft' })).data!;
+
+ const [privacy, deletion] = await withoutDeadlock(
+ Promise.all([
+ pages({ documentId: page.id }).access.post({
+ version: page.version,
+ isPrivate: true,
+ }),
+ god.api.god.users({ userId: alice.id }).delete(),
+ ]),
+ );
+
+ expect(deletion.status).toBe(204);
+ expect([200, 401, 403, 404]).toContain(privacy.status);
+ const surviving = await god.api
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: page.id })
+ .get();
+ if (surviving.status === 200) {
+ expect(surviving.data).toMatchObject({ isPrivate: false, ownerUserId: null });
+ } else {
+ expect(surviving.status).toBe(404);
+ }
+ });
+
+ it('does not expose or orphan a private revision during account deletion', async () => {
+ const { god } = await setup();
+ const alice = await addUser({ email: '[email protected]' });
+ await alice.api.projects.post({ key: 'MKT', name: 'Marketing' });
+ await joinProject(alice, god, 'MKT', 'owner');
+ const pages = alice.api.projects({ projectKey: 'MKT' }).documents;
+ const privatePage = (
+ await pages.post({ title: 'Private history', content: 'Secret', isPrivate: true })
+ ).data!;
+ const privateRevision = (await pages({ documentId: privatePage.id }).revisions.get())
+ .data![0]!;
+ const sanitized = await pages({ documentId: privatePage.id }).patch({
+ version: privatePage.version,
+ content: 'Public body',
+ });
+ const published = await pages({ documentId: privatePage.id }).access.post({
+ version: sanitized.data!.version,
+ isPrivate: false,
+ });
+
+ const [restore, deletion] = await withoutDeadlock(
+ Promise.all([
+ pages({ documentId: privatePage.id })
+ .revisions({ revisionId: privateRevision.id })
+ .restore.post({ version: published.data!.version }),
+ god.api.god.users({ userId: alice.id }).delete(),
+ ]),
+ );
+
+ expect(deletion.status).toBe(204);
+ expect([200, 401, 403, 404]).toContain(restore.status);
+ const surviving = await god.api
+ .projects({ projectKey: 'MKT' })
+ .documents({ documentId: privatePage.id })
+ .get();
+ if (surviving.status === 200) {
+ expect(surviving.data).toMatchObject({ isPrivate: false, ownerUserId: null });
+ expect(surviving.data?.content).not.toBe('Secret');
+ } else {
+ expect(surviving.status).toBe(404);
+ }
+ });
+
it('refuses to delete the instance owner', async () => {
const { god } = await setup();
diff --git a/apps/api/src/modules/god/service.ts b/apps/api/src/modules/god/service.ts
index 9aa3c29d..1f80365b 100644
--- a/apps/api/src/modules/god/service.ts
+++ b/apps/api/src/modules/god/service.ts
@@ -35,6 +35,7 @@ import {
} from 'drizzle-orm';
import type { AnyPgColumn, PgTable } from 'drizzle-orm/pg-core';
import { HttpError, iso } from '#shared/lib';
+import { deleteAccount } from '#shared/account-deletion';
import { mappedProjectIds, reconcileProjects } from '#modules/scim/reconcile';
import {
defaultMemberPermissions,
@@ -287,7 +288,7 @@ async function countOwnersByProject(projectIds: number[]): Promise<Map<number, n
// reference to null (assignee, activity actor, invites), so this is a single
// delete.
export async function deleteInstanceUser(userId: string): Promise<void> {
- await db.delete(user).where(eq(user.id, userId));
+ await deleteAccount(userId);
}
// ── Project directory ────────────────────────────────────────────────────────
diff --git a/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts b/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
index 5617e316..b5b59ca3 100644
--- a/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
@@ -1,14 +1,17 @@
import { describe, it, expect, beforeEach } from 'bun:test';
+import { db, issueWatcher } from '@repo/db';
+import { and, eq } from 'drizzle-orm';
import { authedApi, type Api } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
// Who follows an issue. A watcher receives the notifications the issue produces;
// the list comes back with the issue (GET /issues/:issueId → `watchers`) and is
-// changed through POST/DELETE /issues/:issueId/watch, which act on the caller
-// only. Members are subscribed automatically when they create an issue, are
-// assigned one, comment on it or are mentioned in it — unless they turned
-// auto-subscribe off, and never once they have unwatched it by hand.
+// changed through POST/DELETE /issues/:issueId/watch, which act on the caller,
+// or the editor-only /watchers/:userId routes for another human project member.
+// Members are subscribed automatically when they create an issue, are assigned
+// one, comment on it or are mentioned in it — unless they turned auto-subscribe
+// off, and never once they have unwatched it by hand.
interface Member {
api: Api;
@@ -27,13 +30,19 @@ async function setup(): Promise<{ owner: Member; columnId: number }> {
};
}
-async function addMember(owner: Member): Promise<Member> {
+async function addMember(owner: Member, opts: { roleId?: number } = {}): Promise<Member> {
const u = await signUpTestUser();
const invite = await owner.api
.projects({ projectKey: 'MKT' })
.invites.post({ email: u.email, role: 'member' });
const api = authedApi(u.cookie);
await api.invites({ token: invite.data!.token }).accept.post();
+ if (opts.roleId != null) {
+ await owner.api
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: u.userId })
+ .patch({ role: 'member', roleId: opts.roleId });
+ }
return { api, userId: u.userId, username: u.username };
}
@@ -95,6 +104,27 @@ describe('issue watchers', () => {
expect(await watcherIds(owner.api, issue.data!.id)).toContain(member.userId);
});
+ it('does not create a hidden watcher row for a mentioned AI agent', async () => {
+ const { owner, columnId } = await setup();
+ const agent = await owner.api.projects({ projectKey: 'MKT' })['ai-agents'].post({
+ name: 'Watcher Bot',
+ username: 'watcher-bot',
+ kind: 'external',
+ });
+ const issue = await createIssue(owner.api, columnId);
+ const agentUserId = agent.data!.agent.userId;
+
+ await owner.api
+ .issues({ issueId: issue.data!.id })
+ .comments.post({ body: '@watcher-bot take a look' });
+
+ const rows = await db
+ .select({ userId: issueWatcher.userId })
+ .from(issueWatcher)
+ .where(and(eq(issueWatcher.issueId, issue.data!.id), eq(issueWatcher.userId, agentUserId)));
+ expect(rows).toEqual([]);
+ });
+
it('leaves out a member who turned auto-subscribe off', async () => {
const { owner, columnId } = await setup();
const member = await addMember(owner);
@@ -169,6 +199,106 @@ describe('issue watchers', () => {
});
});
+ describe('managing other watchers', () => {
+ it('lets an editor add and remove a project member', async () => {
+ const { owner, columnId } = await setup();
+ const member = await addMember(owner);
+ const issue = await createIssue(owner.api, columnId);
+ const endpoint = owner.api
+ .issues({ issueId: issue.data!.id })
+ .watchers({ userId: member.userId });
+
+ const added = await endpoint.put();
+ expect(added.status).toBe(200);
+ expect(added.data!.map((watcher) => watcher.userId)).toContain(member.userId);
+
+ const removed = await endpoint.delete();
+ expect(removed.status).toBe(200);
+ expect(removed.data!.map((watcher) => watcher.userId)).not.toContain(member.userId);
+
+ // An editor's explicit removal is sticky just like the member's own unwatch.
+ await member.api
+ .issues({ issueId: issue.data!.id })
+ .comments.post({ body: 'still involved' });
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(member.userId);
+ });
+
+ it('rejects a user outside the project', async () => {
+ const { owner, columnId } = await setup();
+ const outsider = await signUpTestUser();
+ const issue = await createIssue(owner.api, columnId);
+
+ const res = await owner.api
+ .issues({ issueId: issue.data!.id })
+ .watchers({ userId: outsider.userId })
+ .put();
+
+ expect(res.status).toBe(400);
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(outsider.userId);
+ });
+
+ it('rejects an AI agent even though its bot user is a project member', async () => {
+ const { owner, columnId } = await setup();
+ const agent = await owner.api.projects({ projectKey: 'MKT' })['ai-agents'].post({
+ name: 'Watcher Bot',
+ username: 'watcher-bot',
+ kind: 'external',
+ });
+ const issue = await createIssue(owner.api, columnId);
+ const agentUserId = agent.data!.agent.userId;
+
+ const res = await owner.api
+ .issues({ issueId: issue.data!.id })
+ .watchers({ userId: agentUserId })
+ .put();
+
+ expect(res.status).toBe(400);
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(agentUserId);
+ });
+
+ it('rejects a member who cannot read work items', async () => {
+ const { owner, columnId } = await setup();
+ const role = await owner.api.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'No work items',
+ permissions: {},
+ });
+ const restricted = await addMember(owner, { roleId: role.data!.id });
+ const issue = await createIssue(owner.api, columnId);
+
+ const res = await owner.api
+ .issues({ issueId: issue.data!.id })
+ .watchers({ userId: restricted.userId })
+ .put();
+
+ expect(res.status).toBe(400);
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(restricted.userId);
+ });
+
+ it('keeps self-watch available to a reader but denies managing other people', async () => {
+ const { owner, columnId } = await setup();
+ const role = await owner.api.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'Reader',
+ permissions: {
+ work_items: { create: false, edit: false, read: true, delete: false },
+ },
+ });
+ const reader = await addMember(owner, { roleId: role.data!.id });
+ const target = await addMember(owner);
+ const issue = await createIssue(owner.api, columnId);
+
+ const selfWatch = await reader.api.issues({ issueId: issue.data!.id }).watch.post();
+ expect(selfWatch.status).toBe(200);
+ expect(selfWatch.data!.map((watcher) => watcher.userId)).toContain(reader.userId);
+
+ const manage = await reader.api
+ .issues({ issueId: issue.data!.id })
+ .watchers({ userId: target.userId })
+ .put();
+ expect(manage.status).toBe(403);
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(target.userId);
+ });
+ });
+
describe('notifications', () => {
it('notifies a watcher of a status change, and stops once they unwatch', async () => {
const { owner, columnId } = await setup();
@@ -202,5 +332,29 @@ describe('issue watchers', () => {
const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });
expect(inbox.data!.items).toHaveLength(1);
});
+
+ it('stops exposing watcher events after work-item read access is revoked', async () => {
+ const { owner, columnId } = await setup();
+ const member = await addMember(owner);
+ const view = await owner.api.projects({ projectKey: 'MKT' }).get();
+ const issue = await createIssue(owner.api, columnId);
+ await member.api.issues({ issueId: issue.data!.id }).watch.post();
+ const blockedRole = await owner.api.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'No issue access',
+ permissions: {},
+ });
+
+ await owner.api
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: member.userId })
+ .patch({ role: 'member', roleId: blockedRole.data!.id });
+ await owner.api.issues({ issueId: issue.data!.id }).patch({
+ columnId: view.data!.columns[1].id,
+ });
+
+ expect(await watcherIds(owner.api, issue.data!.id)).not.toContain(member.userId);
+ const inbox = await member.api.notifications.get({ query: { types: 'state_changed' } });
+ expect(inbox.data!.items).toHaveLength(0);
+ });
});
});
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index a8f3cc2a..ccde0c8c 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -45,7 +45,7 @@ import {
type SubtaskDisposition,
type SubtaskMode,
} from './subtasks';
-import { listIssueWatchers, setIssueWatching } from './watchers';
+import { isEligibleIssueWatcher, listIssueWatchers, setIssueWatching } from './watchers';
import {
createWorklog,
deleteWorklog,
@@ -75,6 +75,7 @@ import {
IssueResponse,
IssueLinkResponse,
IssueWatcherResponse,
+ issueWatcherParams,
ChecklistItemResponse,
ChecklistResponse,
OrderedIdsSchema,
@@ -908,9 +909,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
)
// Follows the issue: the caller receives every notification it produces until
- // they unwatch it. Only ever the caller — one member does not subscribe
- // another. Reading the issue is enough, since watching adds no other access.
- // Both routes return the resulting list, which the issue read also carries.
+ // they unwatch it. This self-service route only ever changes the caller; editors
+ // use the watcher-management routes below for other members. Reading the issue
+ // is enough, since watching adds no other access. Both routes return the same
+ // watcher list carried by the issue read.
.post(
'/issues/:issueId/watch',
async ({ params, projectId, user }) => {
@@ -948,6 +950,53 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
+ // Editors can curate the full watcher list when a handoff or review needs to
+ // reach someone immediately. The target must be a real project member: agents
+ // have their own delegation flow and must never receive human notifications.
+ .put(
+ '/issues/:issueId/watchers/:userId',
+ async ({ params, projectId }) => {
+ if (!(await isEligibleIssueWatcher(projectId, params.userId))) {
+ throw new HttpError(400, 'Watcher must be a human project member with work item access');
+ }
+ await setIssueWatching(params.issueId, params.userId, true);
+ return listIssueWatchers(projectId, params.issueId);
+ },
+ {
+ params: issueWatcherParams,
+ workItem: 'edit',
+ response: { 200: t.Array(IssueWatcherResponse), ...commonErrors },
+ detail: {
+ summary: 'Add an issue watcher',
+ description:
+ 'Subscribe another real project member to the issue. Requires permission to edit work items.',
+ ...mcpTool('add_issue_watcher'),
+ },
+ },
+ )
+
+ .delete(
+ '/issues/:issueId/watchers/:userId',
+ async ({ params, projectId }) => {
+ if (!(await isEligibleIssueWatcher(projectId, params.userId))) {
+ throw new HttpError(400, 'Watcher must be a human project member with work item access');
+ }
+ await setIssueWatching(params.issueId, params.userId, false);
+ return listIssueWatchers(projectId, params.issueId);
+ },
+ {
+ params: issueWatcherParams,
+ workItem: 'edit',
+ response: { 200: t.Array(IssueWatcherResponse), ...commonErrors },
+ detail: {
+ summary: 'Remove an issue watcher',
+ description:
+ 'Unsubscribe another real project member from the issue. Requires permission to edit work items.',
+ ...mcpTool('remove_issue_watcher'),
+ },
+ },
+ )
+
// One page of an issue's timeline, newest first: comments and change-log
// activity merged in issue_activity. `limit` (default 25) and an opaque
// `cursor` (the JSON-encoded nextCursor from the previous page) drive keyset
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
index 1466188b..14af667b 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -157,6 +157,11 @@ export const IssueWatcherResponse = t.Object({
image: t.Nullable(t.String()),
});
+export const issueWatcherParams = t.Object({
+ issueId: t.Numeric(),
+ userId: t.String(),
+});
+
// ChecklistItemRow / ChecklistRow from checklists.ts.
export const ChecklistItemResponse = t.Object({
id: t.Number(),
diff --git a/apps/api/src/modules/issues/watchers.ts b/apps/api/src/modules/issues/watchers.ts
index 704fefa6..0e38c3e4 100644
--- a/apps/api/src/modules/issues/watchers.ts
+++ b/apps/api/src/modules/issues/watchers.ts
@@ -1,5 +1,7 @@
-import { db, issueWatcher, projectMember, user, userPreference } from '@repo/db';
+import { aiAgent, db, issueWatcher, projectMember, user, userPreference } from '@repo/db';
import { and, asc, eq, inArray, isNull, or } from 'drizzle-orm';
+import { getMemberContext, listMemberContexts, type MemberContext } from '#modules/members/service';
+import { hasPermission } from '#shared/permissions';
// Who follows an issue. A watcher receives every notification the issue produces
// (see modules/notifications/service.ts); the assignment and mention notifications are
@@ -16,13 +18,20 @@ export interface IssueWatcherRow {
image: string | null;
}
+function canReadWorkItems(context: MemberContext | null | undefined): boolean {
+ return Boolean(
+ context &&
+ (context.role === 'owner' || hasPermission(context.permissions, 'work_items', 'read')),
+ );
+}
+
// The issue's watchers, by name. A watcher who has left the project is left out;
// their row survives, so rejoining puts them back on the list.
export async function listIssueWatchers(
projectId: number,
issueId: number,
): Promise<IssueWatcherRow[]> {
- return db
+ const rows = await db
.select({ userId: issueWatcher.userId, name: user.name, image: user.image })
.from(issueWatcher)
.innerJoin(user, eq(user.id, issueWatcher.userId))
@@ -30,8 +39,13 @@ export async function listIssueWatchers(
projectMember,
and(eq(projectMember.userId, issueWatcher.userId), eq(projectMember.projectId, projectId)),
)
- .where(and(eq(issueWatcher.issueId, issueId), eq(issueWatcher.subscribed, true)))
+ .leftJoin(aiAgent, eq(aiAgent.userId, issueWatcher.userId))
+ .where(
+ and(eq(issueWatcher.issueId, issueId), eq(issueWatcher.subscribed, true), isNull(aiAgent.id)),
+ )
.orderBy(asc(user.name));
+ const contexts = await listMemberContexts(projectId);
+ return rows.filter((row) => canReadWorkItems(contexts.get(row.userId)));
}
export async function watcherUserIds(projectId: number, issueId: number): Promise<Set<string>> {
@@ -39,6 +53,26 @@ export async function watcherUserIds(projectId: number, issueId: number): Promis
return new Set(rows.map((r) => r.userId));
}
+// Watchers represent people who receive the project's human notifications. An AI
+// agent also has a project_member row, so checking that table alone would make it
+// look like a valid target; the anti-join keeps the management endpoint human-only.
+export async function isEligibleIssueWatcher(projectId: number, userId: string): Promise<boolean> {
+ const rows = await db
+ .select({ userId: projectMember.userId })
+ .from(projectMember)
+ .leftJoin(aiAgent, eq(aiAgent.userId, projectMember.userId))
+ .where(
+ and(
+ eq(projectMember.projectId, projectId),
+ eq(projectMember.userId, userId),
+ isNull(aiAgent.id),
+ ),
+ )
+ .limit(1);
+ if (rows.length === 0) return false;
+ return canReadWorkItems(await getMemberContext(projectId, userId));
+}
+
// Subscribes or unsubscribes one member by hand. Both states are stored, so an
// unsubscription survives the auto-subscribe rules.
export async function setIssueWatching(
@@ -57,9 +91,8 @@ export async function setIssueWatching(
// Subscribes the members that just acted on the issue in a way that implies they
// want to follow it: they created it, were assigned it, commented on it, or were
-// mentioned in a comment. A candidate that is not a member of the project (an
-// agent's bot user is assigned as a delegate but is not one) or that turned
-// auto-subscribe off is skipped. `on conflict do nothing` is what makes an
+// mentioned in a comment. A candidate that is not a human member of the project
+// or that turned auto-subscribe off is skipped. `on conflict do nothing` is what makes an
// unsubscription stick: the row is there with subscribed = false and stays.
export async function autoWatchIssue(
projectId: number,
@@ -72,17 +105,22 @@ export async function autoWatchIssue(
.select({ userId: projectMember.userId })
.from(projectMember)
.leftJoin(userPreference, eq(userPreference.userId, projectMember.userId))
+ .leftJoin(aiAgent, eq(aiAgent.userId, projectMember.userId))
.where(
and(
eq(projectMember.projectId, projectId),
inArray(projectMember.userId, ids),
+ isNull(aiAgent.id),
// No preference row yet means the default, which is on.
or(isNull(userPreference.autoWatch), eq(userPreference.autoWatch, true)),
),
);
if (rows.length === 0) return;
+ const contexts = await listMemberContexts(projectId);
+ const eligible = rows.filter((row) => canReadWorkItems(contexts.get(row.userId)));
+ if (eligible.length === 0) return;
await db
.insert(issueWatcher)
- .values(rows.map((r) => ({ issueId, userId: r.userId })))
+ .values(eligible.map((r) => ({ issueId, userId: r.userId })))
.onConflictDoNothing();
}
diff --git a/apps/api/src/modules/members/service.ts b/apps/api/src/modules/members/service.ts
index 0a6d4a62..a8be94a6 100644
--- a/apps/api/src/modules/members/service.ts
+++ b/apps/api/src/modules/members/service.ts
@@ -13,6 +13,7 @@ import { DEFAULT_TIMEZONE } from '#modules/user-preferences/service';
import {
defaultMemberPermissions,
fullPermissions,
+ hasPermission,
normalizePermissions,
type Permissions,
} from '#shared/permissions';
@@ -147,6 +148,7 @@ export interface AssigneeCandidate {
// The user an 'owner'-scoped external agent works for: only their runs reach its
// runner, so delegating it to anyone else does nothing. Null for everyone else.
restrictedToUserId: string | null;
+ canReadWorkItems: boolean;
}
export async function listAssigneeCandidates(projectId: number): Promise<AssigneeCandidate[]> {
@@ -159,6 +161,7 @@ export async function listAssigneeCandidates(projectId: number): Promise<Assigne
username: user.username,
image: user.image,
role: projectMember.role,
+ permissions: projectRole.permissions,
description: projectMember.description,
})
.from(projectMember)
@@ -167,6 +170,7 @@ export async function listAssigneeCandidates(projectId: number): Promise<Assigne
// permissions). It is listed below as kind 'agent', so it is excluded here to
// keep the member candidates real people only. Same agent test as listMembers.
.leftJoin(aiAgent, eq(aiAgent.userId, projectMember.userId))
+ .leftJoin(projectRole, eq(projectRole.id, projectMember.roleId))
.where(and(eq(projectMember.projectId, projectId), isNull(aiAgent.id))),
db
.select({
@@ -183,18 +187,23 @@ export async function listAssigneeCandidates(projectId: number): Promise<Assigne
.innerJoin(user, eq(user.id, aiAgent.userId))
.where(eq(aiAgent.projectId, projectId)),
]);
- const members: AssigneeCandidate[] = memberRows.map((r) => ({
- userId: r.userId,
- name: r.name,
- email: r.email,
- username: r.username,
- image: r.image,
- kind: 'member',
- agentKind: null,
- role: r.role as MemberRole,
- description: r.description,
- restrictedToUserId: null,
- }));
+ const members: AssigneeCandidate[] = memberRows.map((r) => {
+ const context = toMemberContext(r.role as MemberRole, r.permissions);
+ return {
+ userId: r.userId,
+ name: r.name,
+ email: r.email,
+ username: r.username,
+ image: r.image,
+ kind: 'member',
+ agentKind: null,
+ role: r.role as MemberRole,
+ description: r.description,
+ restrictedToUserId: null,
+ canReadWorkItems:
+ context.role === 'owner' || hasPermission(context.permissions, 'work_items', 'read'),
+ };
+ });
const agents: AssigneeCandidate[] = agentRows.map((r) => ({
userId: r.userId,
name: r.name,
@@ -206,6 +215,7 @@ export async function listAssigneeCandidates(projectId: number): Promise<Assigne
role: null,
description: null,
restrictedToUserId: r.runnerScope === 'owner' ? r.ownerUserId : null,
+ canReadWorkItems: false,
}));
return [...members, ...agents].sort((a, b) => a.name.localeCompare(b.name));
}
diff --git a/apps/api/src/modules/projects/__tests__/integration/projects.test.ts b/apps/api/src/modules/projects/__tests__/integration/projects.test.ts
index dec3bbff..508b1146 100644
--- a/apps/api/src/modules/projects/__tests__/integration/projects.test.ts
+++ b/apps/api/src/modules/projects/__tests__/integration/projects.test.ts
@@ -282,6 +282,64 @@ describe('projects', () => {
expect(view.data?.viewer.role).toBe('owner');
});
+ it('does not copy wiki content for a member who cannot read documents', async () => {
+ const owner = await signUpClient();
+ await setupSource(owner.api);
+ const role = await owner.api.projects({ projectKey: 'SRC' }).roles.post({
+ name: 'Work items only',
+ permissions: { work_items: { create: false, edit: false, read: true, delete: false } },
+ });
+ const member = await addProjectMember(owner.api, 'SRC', role.data!.id);
+
+ const defaultCopy = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'LEAK',
+ name: 'Must not copy Docs',
+ });
+ expect(defaultCopy.status).toBe(403);
+
+ const safeCopy = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'SAFE',
+ name: 'Labels only',
+ include: { labels: true },
+ });
+ expect(safeCopy.status).toBe(201);
+ });
+
+ it('only lets an owner copy secret-bearing project sections', async () => {
+ const owner = await signUpClient();
+ await setupSource(owner.api);
+ const role = await owner.api.projects({ projectKey: 'SRC' }).roles.post({
+ name: 'Work items only',
+ permissions: { work_items: { create: false, edit: false, read: true, delete: false } },
+ });
+ const member = await addProjectMember(owner.api, 'SRC', role.data!.id);
+
+ const integrations = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'SECRET1',
+ name: 'No integration secrets',
+ include: { integrations: true },
+ });
+ const webhooks = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'SECRET2',
+ name: 'No webhook secrets',
+ include: { webhooks: true },
+ });
+ const notifications = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'SECRET3',
+ name: 'No notification credentials',
+ include: { notificationProviders: true },
+ });
+ const tools = await member.projects({ projectKey: 'SRC' }).copy.post({
+ key: 'SECRET4',
+ name: 'No tool credentials',
+ include: { tools: true },
+ });
+
+ expect([integrations.status, webhooks.status, notifications.status, tools.status]).toEqual([
+ 403, 403, 403, 403,
+ ]);
+ });
+
it("does not copy the source project's issues", async () => {
const { api } = await signUpClient();
await setupSource(api);
@@ -312,7 +370,7 @@ describe('projects', () => {
await api.projects.post({ key: 'SRC', name: 'Source' });
await api
.projects({ projectKey: 'SRC' })
- .settings.patch({ features: { notes: false, dashboards: false } });
+ .settings.patch({ features: { documents: false, notes: false, dashboards: false } });
await api.projects({ projectKey: 'SRC' }).copy.post({ key: 'DST', name: 'Destination' });
@@ -321,6 +379,7 @@ describe('projects', () => {
initiatives: true,
cycles: true,
dashboards: false,
+ documents: false,
notes: false,
subtasks: true,
checklists: true,
@@ -676,6 +735,7 @@ describe('projects', () => {
expect(res.data?.features).toMatchObject({
initiatives: true,
dashboards: true,
+ documents: true,
notes: true,
subtasks: true,
checklists: true,
@@ -684,6 +744,7 @@ describe('projects', () => {
expect((await viewOf(api, 'MKT')).data?.project).toMatchObject({
initiativesEnabled: true,
dashboardsEnabled: true,
+ documentsEnabled: true,
notesEnabled: true,
subtasksEnabled: true,
checklistsEnabled: true,
@@ -702,6 +763,7 @@ describe('projects', () => {
expect(off.data?.features).toMatchObject({
initiatives: false,
dashboards: true,
+ documents: true,
notes: true,
});
expect((await viewOf(api, 'MKT')).data?.project.initiativesEnabled).toBe(false);
diff --git a/apps/api/src/modules/projects/copy.ts b/apps/api/src/modules/projects/copy.ts
index 4afa1f18..233ce1d8 100644
--- a/apps/api/src/modules/projects/copy.ts
+++ b/apps/api/src/modules/projects/copy.ts
@@ -11,6 +11,8 @@ import {
customFieldOption,
projectView,
projectDashboard,
+ projectDocument,
+ documentAsset,
projectAction,
integrationCredential,
agentTool,
@@ -18,7 +20,7 @@ import {
projectNotificationSetting,
projectSetting,
} from '@repo/db';
-import { eq, inArray } from 'drizzle-orm';
+import { and, eq, inArray, or } from 'drizzle-orm';
import { iso } from '#shared/lib';
import { defaultMemberPermissions } from '#shared/permissions';
import { DEFAULT_COLUMNS, type ProjectRow } from './service';
@@ -36,6 +38,14 @@ import { listAgentToolLinks, setAgentTools } from '#modules/agents/tools/service
import { listAgentSchedules, createAgentSchedule } from '#modules/agents/schedules/service';
import { nextCronRun } from '#modules/agents/schedules/cron';
import { getObject } from '#shared/s3';
+import {
+ assertAttachmentStorageCapacity,
+ assertAttachmentFileAllowed,
+ attachmentObjectKey,
+ cloneAttachmentObject,
+ deleteAttachmentObject,
+} from '#modules/attachments/storage';
+import { assertValidDocumentContentJson, replaceAssetReferences } from '#modules/documents/service';
// Which parts of a source project the copy carries over. Each key mirrors a section
// of the project settings menu. A key set false skips that entity. Some sections
@@ -49,6 +59,7 @@ export interface CopyProjectInclude {
customFields: boolean;
views: boolean;
dashboards: boolean;
+ documents: boolean;
actions: boolean;
configuration: boolean;
roles: boolean;
@@ -68,6 +79,7 @@ export const COPY_INCLUDE_KEYS: (keyof CopyProjectInclude)[] = [
'customFields',
'views',
'dashboards',
+ 'documents',
'actions',
'configuration',
'roles',
@@ -94,6 +106,7 @@ const DEFAULT_INCLUDE: CopyProjectInclude = {
customFields: true,
views: true,
dashboards: true,
+ documents: true,
actions: true,
};
@@ -227,6 +240,7 @@ function mapProjectRow(row: typeof project.$inferSelect): ProjectRow {
mcpEnabled: row.mcpEnabled,
initiativesEnabled: row.initiativesEnabled,
dashboardsEnabled: row.dashboardsEnabled,
+ documentsEnabled: row.documentsEnabled,
notesEnabled: row.notesEnabled,
cyclesEnabled: row.cyclesEnabled,
subtasksEnabled: row.subtasksEnabled,
@@ -251,7 +265,7 @@ async function readObjectBytes(key: string): Promise<{ bytes: Buffer; contentTyp
// configuration, but none of its issues. The creator becomes the new project's owner.
//
// Pure-database entities (states, types, labels, custom fields, views, dashboards,
-// actions, roles, settings, webhooks, integration credentials, configured tools) are
+// documents, actions, roles, settings, webhooks, integration credentials, configured tools) are
// copied in one transaction, recording old id → new id so the ids that views/actions
// and tools/agents reference are remapped to the copied entities. Entities with side
// effects outside the database are copied after that transaction commits: skills copy
@@ -279,11 +293,13 @@ export async function copyProject(
const skillMap = new Map<number, number>();
const agentMap = new Map<number, number>();
+ const copiedDocumentAssetKeys: string[] = [];
+
// What a new project starts with, set instance-wide in god mode. Read before the
// transaction opens so the settings lookup is not part of it.
const defaults = await getProjectDefaults();
- const newProject = await db.transaction(async (tx) => {
+ const copyTransaction = db.transaction(async (tx) => {
// The optional sections the source project shows and the estimate kinds it
// carries are part of its configuration, so the copy starts with the same ones.
// mcpEnabled comes from the instance default instead, the same as it does for a
@@ -292,6 +308,7 @@ export async function copyProject(
.select({
initiativesEnabled: project.initiativesEnabled,
dashboardsEnabled: project.dashboardsEnabled,
+ documentsEnabled: project.documentsEnabled,
notesEnabled: project.notesEnabled,
cyclesEnabled: project.cyclesEnabled,
subtasksEnabled: project.subtasksEnabled,
@@ -524,6 +541,112 @@ export async function copyProject(
}
}
+ if (inc.documents) {
+ const documentRows = await tx
+ .select()
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.projectId, sourceProjectId),
+ or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, ownerId)),
+ ),
+ )
+ .orderBy(projectDocument.position, projectDocument.id);
+ const documentMap = new Map<number, number>();
+ for (const d of documentRows) {
+ assertValidDocumentContentJson(d.contentJson);
+ const [created] = await tx
+ .insert(projectDocument)
+ .values({
+ projectId: proj.id,
+ title: d.title,
+ content: d.content,
+ contentJson: d.contentJson,
+ icon: d.icon,
+ metadata: d.metadata,
+ fullWidth: d.fullWidth,
+ isPrivate: d.isPrivate,
+ isLocked: d.isLocked,
+ archivedAt: d.archivedAt,
+ position: d.position,
+ ownerUserId: ownerId,
+ createdByUserId: ownerId,
+ updatedByUserId: ownerId,
+ })
+ .returning({ id: projectDocument.id });
+ documentMap.set(d.id, created.id);
+ }
+ for (const d of documentRows) {
+ if (d.parentId == null) continue;
+ const id = documentMap.get(d.id);
+ const parentId = documentMap.get(d.parentId);
+ if (id == null || parentId == null) continue;
+ await tx.update(projectDocument).set({ parentId }).where(eq(projectDocument.id, id));
+ }
+ const sourceDocumentIds = documentRows.map((document) => document.id);
+ if (sourceDocumentIds.length > 0) {
+ const assetRows = await tx
+ .select()
+ .from(documentAsset)
+ .where(inArray(documentAsset.documentId, sourceDocumentIds));
+ await assertAttachmentStorageCapacity(
+ proj.id,
+ assetRows.reduce((total, asset) => total + asset.sizeBytes, 0),
+ 0,
+ tx,
+ );
+ for (const asset of assetRows) {
+ await assertAttachmentFileAllowed(asset.sizeBytes, asset.contentType);
+ }
+ const assetIdsByDocument = new Map<number, Map<string, string>>();
+ for (const asset of assetRows) {
+ const targetDocumentId = documentMap.get(asset.documentId);
+ if (targetDocumentId == null) continue;
+ const key = attachmentObjectKey(proj.id, 'documents', targetDocumentId, asset.filename);
+ await cloneAttachmentObject(asset.s3Key, key, asset.contentType);
+ copiedDocumentAssetKeys.push(key);
+ const [copy] = await tx
+ .insert(documentAsset)
+ .values({
+ documentId: targetDocumentId,
+ uploadedByUserId: ownerId,
+ s3Key: key,
+ filename: asset.filename,
+ contentType: asset.contentType,
+ sizeBytes: asset.sizeBytes,
+ })
+ .returning({ publicId: documentAsset.publicId });
+ const publicIds = assetIdsByDocument.get(asset.documentId) ?? new Map<string, string>();
+ publicIds.set(asset.publicId.toLowerCase(), copy.publicId);
+ assetIdsByDocument.set(asset.documentId, publicIds);
+ }
+ for (const source of documentRows) {
+ const targetDocumentId = documentMap.get(source.id);
+ const publicIds = assetIdsByDocument.get(source.id);
+ if (targetDocumentId == null || !publicIds || publicIds.size === 0) continue;
+ await tx
+ .update(projectDocument)
+ .set({
+ content: replaceAssetReferences(
+ source.content,
+ source.id,
+ input.key,
+ targetDocumentId,
+ publicIds,
+ ),
+ contentJson: replaceAssetReferences(
+ source.contentJson,
+ source.id,
+ input.key,
+ targetDocumentId,
+ publicIds,
+ ),
+ })
+ .where(eq(projectDocument.id, targetDocumentId));
+ }
+ }
+ }
+
// Actions: their condition (a FilterSet) and effect (a partial patch) hold ids
// captured above, so they are remapped to the copied entities.
if (inc.actions) {
@@ -647,6 +770,13 @@ export async function copyProject(
return proj;
});
+ let newProject: ProjectRow;
+ try {
+ newProject = await copyTransaction;
+ } catch (error) {
+ await Promise.all(copiedDocumentAssetKeys.map(deleteAttachmentObject));
+ throw error;
+ }
// Skills: copy each skill's object-store files into the new project's own prefix,
// then create the row through the same service the UI uses.
diff --git a/apps/api/src/modules/projects/index.ts b/apps/api/src/modules/projects/index.ts
index 00b9b267..53e2257e 100644
--- a/apps/api/src/modules/projects/index.ts
+++ b/apps/api/src/modules/projects/index.ts
@@ -4,7 +4,7 @@ import { noContent } from '#shared/http';
import { HttpError } from '#shared/lib';
import { authContext } from '#shared/auth-context';
import { guards } from '#shared/guards';
-import { requireUser } from '#shared/access';
+import { assertPermission, assertProjectOwner, requireUser } from '#shared/access';
import { isMcpRequest } from '#shared/mcp-request';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { getMemberContext, listAssigneeCandidates } from '#modules/members/service';
@@ -94,9 +94,28 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
'/projects/:projectKey/copy',
async ({ project, body, user, set }) => {
const { include, ...meta } = body;
+ const current = requireUser(user);
+ // Omitting include selects the legacy/default structure, which now contains
+ // the wiki. A caller who cannot read Docs must not become owner of a copied
+ // project containing their full text.
+ if (include === undefined || include.documents === true) {
+ await assertPermission(project.id, current, 'documents', 'read');
+ }
+ // These sections contain encrypted credentials or signing secrets. Read
+ // permissions expose only redacted metadata elsewhere; copying them into a
+ // new project owned by the caller would transfer the usable secret itself.
+ if (
+ include &&
+ (include.notificationProviders === true ||
+ include.webhooks === true ||
+ include.integrations === true ||
+ include.tools === true)
+ ) {
+ await assertProjectOwner(project.id, current);
+ }
try {
set.status = 201;
- return await copyProject(project.id, meta, requireUser(user).id, include);
+ return await copyProject(project.id, meta, current.id, include);
} catch (err) {
// Return the real cause in the body so the UI shows the actual error.
console.error('copyProject failed:', err);
@@ -113,7 +132,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
description:
"Copy a project's configuration into a new project you own, without its issues. " +
'By default the structure (states, issue types, labels, custom fields, views, ' +
- 'dashboards, actions) is copied. Pass `include` to choose sections; the API ' +
+ 'dashboards, documents, actions) is copied. Pass `include` to choose sections; the API ' +
'force-enables dependencies (e.g. a view pulls in the states it references).',
...mcpTool('copy_project'),
},
diff --git a/apps/api/src/modules/projects/model.ts b/apps/api/src/modules/projects/model.ts
index e50a2620..0b4fbf02 100644
--- a/apps/api/src/modules/projects/model.ts
+++ b/apps/api/src/modules/projects/model.ts
@@ -35,7 +35,7 @@ export const createProjectBody = t.Composite([
// Copy adds an optional selection of which parts of the source project to carry over.
// Omitted → the source project's structure (states, types, labels, custom fields,
-// views, dashboards, actions). Each flag maps to a section of the project settings
+// views, dashboards, documents, actions). Each flag maps to a project section
// menu; the service force-enables dependencies.
export const copyProjectBody = t.Composite([
projectBody,
@@ -68,6 +68,7 @@ export const ProjectResponse = t.Object({
// disabled section is hidden in the web app and its rows are kept.
initiativesEnabled: t.Boolean(),
dashboardsEnabled: t.Boolean(),
+ documentsEnabled: t.Boolean(),
notesEnabled: t.Boolean(),
cyclesEnabled: t.Boolean(),
subtasksEnabled: t.Boolean(),
@@ -103,6 +104,7 @@ const AssigneeCandidateResponse = t.Object({
kind: t.Union([t.Literal('member'), t.Literal('agent')]),
agentKind: t.Nullable(t.Union([t.Literal('external'), t.Literal('internal')])),
restrictedToUserId: t.Nullable(t.String()),
+ canReadWorkItems: t.Boolean(),
});
// The caller's own role in a project (from MemberContext in members/service). The
@@ -133,6 +135,7 @@ export const ProjectBoardResponse = t.Object({
const FeaturesResponse = t.Object({
initiatives: t.Boolean(),
dashboards: t.Boolean(),
+ documents: t.Boolean(),
notes: t.Boolean(),
cycles: t.Boolean(),
subtasks: t.Boolean(),
diff --git a/apps/api/src/modules/projects/service.ts b/apps/api/src/modules/projects/service.ts
index f0fb97b7..c1caaa79 100644
--- a/apps/api/src/modules/projects/service.ts
+++ b/apps/api/src/modules/projects/service.ts
@@ -1,10 +1,15 @@
import {
db,
+ chatAttachment,
+ documentAsset,
+ issue,
+ issueAttachment,
issueType,
project,
projectColumn,
projectMember,
projectRole,
+ projectDocument,
projectSetting,
} from '@repo/db';
import { and, eq } from 'drizzle-orm';
@@ -18,6 +23,8 @@ import {
import { getProjectSetting, setProjectSetting } from '#shared/project-settings';
import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';
import { getProjectDefaults } from '#modules/settings/service';
+import { deleteObjects } from '#shared/s3';
+import { lockAttachmentStorage } from '#modules/attachments/storage';
// Data access for projects: the top-level container that groups its own columns,
// issue types, labels, assignees, custom fields, issues, saved views, and
@@ -32,6 +39,7 @@ export interface ProjectRow {
mcpEnabled: boolean;
initiativesEnabled: boolean;
dashboardsEnabled: boolean;
+ documentsEnabled: boolean;
notesEnabled: boolean;
cyclesEnabled: boolean;
subtasksEnabled: boolean;
@@ -48,6 +56,7 @@ export interface ProjectRow {
export interface ProjectFeatures {
initiatives: boolean;
dashboards: boolean;
+ documents: boolean;
notes: boolean;
cycles: boolean;
subtasks: boolean;
@@ -74,6 +83,7 @@ function mapProject(row: typeof project.$inferSelect): ProjectRow {
mcpEnabled: row.mcpEnabled,
initiativesEnabled: row.initiativesEnabled,
dashboardsEnabled: row.dashboardsEnabled,
+ documentsEnabled: row.documentsEnabled,
notesEnabled: row.notesEnabled,
cyclesEnabled: row.cyclesEnabled,
subtasksEnabled: row.subtasksEnabled,
@@ -106,6 +116,7 @@ export async function listProjects(
mcpEnabled: project.mcpEnabled,
initiativesEnabled: project.initiativesEnabled,
dashboardsEnabled: project.dashboardsEnabled,
+ documentsEnabled: project.documentsEnabled,
notesEnabled: project.notesEnabled,
cyclesEnabled: project.cyclesEnabled,
subtasksEnabled: project.subtasksEnabled,
@@ -318,6 +329,7 @@ export function projectFeatures(row: ProjectRow): ProjectFeatures {
return {
initiatives: row.initiativesEnabled,
dashboards: row.dashboardsEnabled,
+ documents: row.documentsEnabled,
notes: row.notesEnabled,
cycles: row.cyclesEnabled,
subtasks: row.subtasksEnabled,
@@ -335,6 +347,7 @@ export async function setProjectFeatures(
const values: Partial<typeof project.$inferInsert> = {};
if (patch.initiatives !== undefined) values.initiativesEnabled = patch.initiatives;
if (patch.dashboards !== undefined) values.dashboardsEnabled = patch.dashboards;
+ if (patch.documents !== undefined) values.documentsEnabled = patch.documents;
if (patch.notes !== undefined) values.notesEnabled = patch.notes;
if (patch.cycles !== undefined) values.cyclesEnabled = patch.cycles;
if (patch.subtasks !== undefined) values.subtasksEnabled = patch.subtasks;
@@ -473,5 +486,26 @@ export async function setSubtaskAutomationSettings(
// outside those cascades.
export async function deleteProject(projectId: number): Promise<void> {
await deleteThreadsWhere({ projectId });
- await db.delete(project).where(eq(project.id, projectId));
+ const assetKeys = await db.transaction(async (tx) => {
+ // Serialize with the final upload quota check. A concurrent upload either
+ // commits before these reads or loses its FK race and cleans its S3 object.
+ await lockAttachmentStorage(tx, projectId);
+ const issueAssets = await tx
+ .select({ s3Key: issueAttachment.s3Key })
+ .from(issueAttachment)
+ .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
+ .where(eq(issue.projectId, projectId));
+ const chatAssets = await tx
+ .select({ s3Key: chatAttachment.s3Key })
+ .from(chatAttachment)
+ .where(eq(chatAttachment.projectId, projectId));
+ const documentAssets = await tx
+ .select({ s3Key: documentAsset.s3Key })
+ .from(documentAsset)
+ .innerJoin(projectDocument, eq(projectDocument.id, documentAsset.documentId))
+ .where(eq(projectDocument.projectId, projectId));
+ await tx.delete(project).where(eq(project.id, projectId));
+ return [...issueAssets, ...chatAssets, ...documentAssets].map((asset) => asset.s3Key);
+ });
+ await deleteObjects(assetKeys);
}
diff --git a/apps/api/src/modules/scim/service.ts b/apps/api/src/modules/scim/service.ts
index c02d2f1f..91ba2d58 100644
--- a/apps/api/src/modules/scim/service.ts
+++ b/apps/api/src/modules/scim/service.ts
@@ -2,7 +2,7 @@ import { db, aiAgent, projectMember, scimGroup, scimGroupMember, user } from '@r
import { and, eq, inArray, notExists, sql } from 'drizzle-orm';
import { generateUsername } from '@repo/auth';
import { iso } from '#shared/lib';
-import { deleteInstanceUser } from '#modules/god/service';
+import { deleteAccount } from '#shared/account-deletion';
import { countOwners } from '#modules/members/service';
import { ScimError, type ScimFilter, type ScimGroupRecord, type ScimUserRecord } from './resource';
import { mappedProjectIds, reconcileProjects } from './reconcile';
@@ -277,7 +277,7 @@ export async function deleteScimUser(id: string): Promise<void> {
'project over to another owner first.',
);
}
- await deleteInstanceUser(id);
+ await deleteAccount(id);
}
// The projects this user owns alone. Deleting them would leave those projects with
diff --git a/apps/api/src/modules/sync/__tests__/integration/sync.test.ts b/apps/api/src/modules/sync/__tests__/integration/sync.test.ts
index 232c9029..fb1fabae 100644
--- a/apps/api/src/modules/sync/__tests__/integration/sync.test.ts
+++ b/apps/api/src/modules/sync/__tests__/integration/sync.test.ts
@@ -266,6 +266,36 @@ describe('sync', () => {
});
});
+ describe('documents scope', () => {
+ it('moves for document, preference, and asset changes', async () => {
+ const { asOwner, projectId } = await setup();
+ const scope = `documents:${projectId}`;
+ const initial = await rev(asOwner, scope);
+ const documents = asOwner.projects({ projectKey: 'MKT' }).documents;
+
+ const page = (await documents.post({ title: 'Handbook' })).data!;
+ const created = await rev(asOwner, scope);
+ expect(created).not.toBe(initial);
+
+ await documents({ documentId: page.id }).patch({ version: page.version, content: 'Updated' });
+ const edited = await rev(asOwner, scope);
+ expect(edited).not.toBe(created);
+
+ await documents({ documentId: page.id }).preferences.patch({ isFavorite: true });
+ const favorited = await rev(asOwner, scope);
+ expect(favorited).not.toBe(edited);
+
+ const asset = await documents({ documentId: page.id }).assets.post({
+ file: new File(['diagram'], 'diagram.png', { type: 'image/png' }),
+ });
+ const uploaded = await rev(asOwner, scope);
+ expect(uploaded).not.toBe(favorited);
+
+ await documents({ documentId: page.id }).assets({ publicId: asset.data!.id }).delete();
+ expect(await rev(asOwner, scope)).not.toBe(uploaded);
+ });
+ });
+
describe('inbox scope', () => {
it("moves for the notified user only, and not for someone else's inbox", async () => {
const { asOwner, projectId, columnId } = await setup();
@@ -327,6 +357,27 @@ describe('sync', () => {
expect(await rev(asMember, board)).toBe('0');
});
+ it('hides a documents scope from a member without documents read access', async () => {
+ const { asOwner, projectId } = await setup();
+ await asOwner.projects({ projectKey: 'MKT' }).documents.post({ title: 'Handbook' });
+ const { userId, api: asMember } = await addMember(asOwner);
+ const scope = `documents:${projectId}`;
+ expect(await rev(asMember, scope)).not.toBe('0');
+
+ const role = (
+ await asOwner.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'Work items only',
+ permissions: { work_items: { read: true } },
+ })
+ ).data!;
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .members({ userId })
+ .patch({ role: 'member', roleId: role.id });
+
+ expect(await rev(asMember, scope)).toBe('0');
+ });
+
it('requires a session', async () => {
const { projectId } = await setup();
const res = await api.sync.rev.get({ query: { scopes: `board:${projectId}` } });
diff --git a/apps/api/src/modules/sync/service.ts b/apps/api/src/modules/sync/service.ts
index 37393ccc..7731100b 100644
--- a/apps/api/src/modules/sync/service.ts
+++ b/apps/api/src/modules/sync/service.ts
@@ -8,10 +8,9 @@ import { hasPermission, type PermissionResource } from '#shared/permissions';
// the marker whichever process it came from.
// A scope kind a client may ask for: the key it maps to in the revision table and
-// the resource the caller must be allowed to read to watch it. Three kinds are
-// addressed by the entity's id; the inbox is per user, so the session user is added
-// to its key here, clients never send or see it, and it needs no permission — it is
-// the caller's own.
+// the resource the caller must be allowed to read to watch it. Project-wide and
+// entity scopes use the supplied id. The inbox is per user, so the session user is
+// added to its key here; clients never send or see it, and it needs no permission.
export interface ScopeKind {
key: (id: number, userId: string) => string;
resource: PermissionResource | null;
@@ -19,6 +18,7 @@ export interface ScopeKind {
export const scopeKind: Record<string, ScopeKind> = {
board: { key: (projectId) => `board:${projectId}`, resource: 'work_items' },
+ documents: { key: (projectId) => `documents:${projectId}`, resource: 'documents' },
issue: { key: (issueId) => `issue:${issueId}`, resource: 'work_items' },
initiative: {
key: (initiativeId) => `initiative:${initiativeId}`,
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 18b20d6e..5fa0784f 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -28,6 +28,7 @@ import { webhookRoutes } from './modules/webhooks';
import { gitSettingsRoutes } from './modules/git';
import { dashboardRoutes } from './modules/dashboards';
import { noteBoardRoutes } from './modules/note-boards';
+import { documentRoutes } from './modules/documents';
import { analyticsRoutes } from './modules/analytics';
import { chartRoutes } from './modules/charts';
import { settingsRoutes } from './modules/settings';
@@ -109,6 +110,7 @@ export const planner = new Elysia({ name: 'planner' })
.use(agentChatRoutes)
.use(dashboardRoutes)
.use(noteBoardRoutes)
+ .use(documentRoutes)
.use(analyticsRoutes)
.use(chartRoutes)
.use(notificationRoutes)
diff --git a/apps/api/src/shared/__tests__/unit/permissions.test.ts b/apps/api/src/shared/__tests__/unit/permissions.test.ts
index 92336691..1311c4e4 100644
--- a/apps/api/src/shared/__tests__/unit/permissions.test.ts
+++ b/apps/api/src/shared/__tests__/unit/permissions.test.ts
@@ -29,6 +29,8 @@ describe('hasPermission', () => {
expect(hasPermission(p, 'work_items', 'delete')).toBe(true);
expect(hasPermission(p, 'note_boards', 'create')).toBe(true);
expect(hasPermission(p, 'note_boards', 'delete')).toBe(true);
+ expect(hasPermission(p, 'documents', 'create')).toBe(true);
+ expect(hasPermission(p, 'documents', 'delete')).toBe(true);
expect(hasPermission(p, 'dashboards', 'read')).toBe(true);
expect(hasPermission(p, 'dashboards', 'edit')).toBe(false);
expect(hasPermission(p, 'members_manage', 'read')).toBe(false);
diff --git a/apps/api/src/shared/account-deletion.ts b/apps/api/src/shared/account-deletion.ts
new file mode 100644
index 00000000..7c936389
--- /dev/null
+++ b/apps/api/src/shared/account-deletion.ts
@@ -0,0 +1,96 @@
+import { db, documentAsset, projectDocument, user } from '@repo/db';
+import { and, asc, eq, inArray, or, sql } from 'drizzle-orm';
+import { deleteObjects } from './s3';
+
+const DOCUMENT_TREE_LOCK_NAMESPACE = 1_145_390_931;
+
+export async function deleteAccount(userId: string): Promise<boolean> {
+ const result = await db.transaction(async (tx) => {
+ const locked = await tx.execute(sql`select id from "user" where id = ${userId} for update`);
+ if (locked.length === 0) return { deleted: false, assetKeys: [] as string[] };
+
+ // Document writers take an actor lock before the project tree lock. Keep the
+ // same ordering here so account deletion cannot race an autosave or move.
+ const ownedDocuments = await tx
+ .select({ projectId: projectDocument.projectId })
+ .from(projectDocument)
+ .where(eq(projectDocument.ownerUserId, userId));
+ const projectIds = [...new Set(ownedDocuments.map((document) => document.projectId))].sort(
+ (left, right) => left - right,
+ );
+ for (const projectId of projectIds) {
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${projectId})`,
+ );
+ }
+
+ // Lock the pages before reading their asset keys. An upload that started before
+ // account deletion either commits first and is included here, or observes the
+ // deleted page and removes the newly written object in its failure cleanup.
+ const privateDocuments = await tx
+ .select({ id: projectDocument.id })
+ .from(projectDocument)
+ .where(and(eq(projectDocument.ownerUserId, userId), eq(projectDocument.isPrivate, true)))
+ .for('update');
+ const assets =
+ privateDocuments.length === 0
+ ? []
+ : await tx
+ .select({ s3Key: documentAsset.s3Key })
+ .from(documentAsset)
+ .where(
+ inArray(
+ documentAsset.documentId,
+ privateDocuments.map((document) => document.id),
+ ),
+ );
+
+ // Detach surviving pages explicitly before FK cleanup. This creates a new
+ // optimistic version and immutable checkpoint instead of silently rewriting
+ // the latest revision when a private parent or owner disappears.
+ const privateDocumentIds = privateDocuments.map((document) => document.id);
+ const affectedPublicDocuments = await tx
+ .select({
+ id: projectDocument.id,
+ ownerUserId: projectDocument.ownerUserId,
+ parentId: projectDocument.parentId,
+ })
+ .from(projectDocument)
+ .where(
+ and(
+ eq(projectDocument.isPrivate, false),
+ privateDocumentIds.length > 0
+ ? or(
+ eq(projectDocument.ownerUserId, userId),
+ inArray(projectDocument.parentId, privateDocumentIds),
+ )
+ : eq(projectDocument.ownerUserId, userId),
+ ),
+ )
+ .orderBy(asc(projectDocument.id))
+ .for('update');
+ for (const document of affectedPublicDocuments) {
+ await tx
+ .update(projectDocument)
+ .set({
+ ...(document.ownerUserId === userId ? { ownerUserId: null } : {}),
+ ...(document.parentId !== null && privateDocumentIds.includes(document.parentId)
+ ? { parentId: null }
+ : {}),
+ updatedByUserId: userId,
+ updatedAt: sql`now()`,
+ version: sql`${projectDocument.version} + 1`,
+ })
+ .where(eq(projectDocument.id, document.id));
+ }
+
+ await tx
+ .delete(projectDocument)
+ .where(and(eq(projectDocument.ownerUserId, userId), eq(projectDocument.isPrivate, true)));
+ await tx.delete(user).where(eq(user.id, userId));
+ return { deleted: true, assetKeys: assets.map((asset) => asset.s3Key) };
+ });
+
+ await deleteObjects(result.assetKeys);
+ return result.deleted;
+}
diff --git a/apps/api/src/shared/permissions.ts b/apps/api/src/shared/permissions.ts
index 908abe80..cb64a4cd 100644
--- a/apps/api/src/shared/permissions.ts
+++ b/apps/api/src/shared/permissions.ts
@@ -10,6 +10,7 @@ export const PERMISSION_RESOURCES = [
'initiatives',
'cycles',
'dashboards',
+ 'documents',
'views',
'members_invite',
'members_manage',
@@ -63,6 +64,7 @@ export function defaultMemberPermissions(): Permissions {
p.work_items = fill(true);
p.initiatives = fill(true);
p.cycles = fill(true);
+ p.documents = fill(true);
p.note_boards = fill(true);
p.dashboards.read = true;
p.views.read = true;
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 5426d582..06e4930b 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -149,6 +149,7 @@
"initiatives": "المبادرات",
"cycles": "الدورات",
"dashboards": "لوحات المعلومات",
+ "documents": "Docs",
"notes": "الملاحظات",
"subtasks": "المهام الفرعية",
"checklists": "قوائم التحقّق (قائمة الحاجات اللي لازم تتراجع)",
diff --git a/apps/web/messages/ar/documents.json b/apps/web/messages/ar/documents.json
new file mode 100644
index 00000000..cedb3d97
--- /dev/null
+++ b/apps/web/messages/ar/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "صفحة جديدة",
+ "favoritePages": "المفضلة",
+ "newSubpage": "إضافة صفحة تحت {title}",
+ "addSubpage": "إضافة صفحة فرعية",
+ "untitled": "بلا عنوان",
+ "titlePlaceholder": "بلا عنوان",
+ "contentPlaceholder": "ابدأ الكتابة أو اضغط / للأوامر…",
+ "search": "البحث في Docs…",
+ "sort": "ترتيب الصفحات",
+ "manualOrder": "ترتيب يدوي",
+ "nameOrder": "الاسم",
+ "updatedOrder": "آخر تحديث",
+ "createdOrder": "تاريخ الإنشاء",
+ "sortAscending": "ترتيب تصاعدي",
+ "sortDescending": "ترتيب تنازلي",
+ "filters": "عوامل التصفية",
+ "createdBy": "أنشأها",
+ "createdDate": "تاريخ الإنشاء",
+ "anyone": "أي شخص",
+ "all": "أي وقت",
+ "today": "آخر 24 ساعة",
+ "week": "آخر 7 أيام",
+ "month": "آخر 30 يومًا",
+ "clearFilters": "مسح عوامل التصفية",
+ "noResults": "لم يتم العثور على صفحات.",
+ "noAccess": "ليس لديك حق الوصول إلى Docs المشروع.",
+ "treeLabel": "Docs المشروع",
+ "expand": "توسيع الصفحة",
+ "collapse": "طي الصفحة",
+ "backToDocuments": "العودة إلى Docs",
+ "documentActions": "إجراءات الصفحة",
+ "pageIcon": "أيقونة الصفحة",
+ "pageTitle": "عنوان الصفحة",
+ "saved": "تم الحفظ",
+ "saving": "جارٍ الحفظ…",
+ "saveFailed": "تعذر الحفظ",
+ "retrySave": "إعادة محاولة الحفظ",
+ "loadFailed": "تعذر تحميل Docs",
+ "conflict": "توجد نسخة أحدث",
+ "reload": "إعادة التحميل",
+ "reviewConflict": "مراجعة",
+ "discardTitle": "تجاهل المسودة المحلية؟",
+ "discardDescription": "ستستبدل إعادة التحميل النص غير المحفوظ بأحدث نسخة من الخادم. لا يمكن التراجع عن ذلك.",
+ "discardAndReload": "تجاهل وإعادة التحميل",
+ "updatedBy": "حدّثه {name} {time}",
+ "updated": "تم التحديث {time}",
+ "delete": "حذف",
+ "deleteTitle": "حذف الصفحة",
+ "deleteDescription": "حذف هذه الصفحة؟ ستنتقل صفحاتها الفرعية إلى المستوى الأعلى. لا يمكن التراجع عن ذلك.",
+ "emptyTitle": "لا توجد صفحات بعد",
+ "emptyDescription": "أنشئ الصفحة الأولى للقرارات والأدلة والملاحظات وسياق المشروع.",
+ "copyTitle": "نسخة من {title}",
+ "fullWidth": "العرض الكامل",
+ "stickyToolbar": "تثبيت شريط الأدوات",
+ "copyMarkdown": "نسخ Markdown",
+ "markdownCopied": "تم نسخ Markdown",
+ "copyLink": "نسخ الرابط",
+ "linkCopied": "تم نسخ الرابط",
+ "versionHistory": "سجل الإصدارات",
+ "versionHistoryDescription": "الإصدار الحالي المحفوظ من هذه الصفحة.",
+ "currentVersion": "الإصدار الحالي · v{version}",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "ستظهر الإصدارات السابقة عند توفر سجل المستندات على الخادم.",
+ "makeCopy": "إنشاء نسخة",
+ "privacy": "الوصول",
+ "projectAccess": "المشروع",
+ "archive": "أرشفة",
+ "apiRequired": "يتطلب API",
+ "export": "تصدير",
+ "exportTitle": "تصدير الصفحة",
+ "exportDescription": "نزّل نسخة قابلة للنقل من الصفحة الحالية.",
+ "exportFormat": "صيغة التصدير",
+ "markdown": "Markdown",
+ "markdownExportHint": "يُنزل كملف .md. إذا احتوت الصفحة على ملفات محمية، فسيتم تجميعها معها في ملف .zip.",
+ "html": "HTML",
+ "download": "تنزيل",
+ "exporting": "جارٍ التحضير…",
+ "exportFailed": "تعذّر تضمين جميع الملفات المحمية في التصدير. حاول مرة أخرى.",
+ "exportTooLarge": "تحتوي الصفحة على ملفات محمية كثيرة جدًا أو كبيرة جدًا لتصدير واحد (بحد أقصى 50 ملفًا و100 ميغابايت).",
+ "cancel": "إلغاء",
+ "publicPages": "عامة",
+ "privatePages": "خاصة",
+ "archivedPages": "مؤرشفة",
+ "changeIcon": "تغيير رمز الصفحة",
+ "removeIcon": "إزالة رمز الصفحة",
+ "searchIcons": "البحث في الرموز…",
+ "customIcon": "الصق رمزًا تعبيريًا",
+ "setIcon": "تعيين",
+ "frequentIcons": "متكررة",
+ "objectIcons": "أشياء",
+ "symbolIcons": "رموز",
+ "lockedReadOnly": "مقفلة",
+ "archivedReadOnly": "مؤرشفة",
+ "addFavorite": "إضافة إلى المفضلة",
+ "removeFavorite": "إزالة من المفضلة",
+ "lock": "قفل الصفحة",
+ "unlock": "فتح الصفحة",
+ "savedVersion": "الإصدار {version}",
+ "historyLoadFailed": "تعذر تحميل سجل الإصدارات.",
+ "restoreVersion": "استعادة",
+ "noHistory": "لا توجد إصدارات محفوظة بعد.",
+ "selectVersion": "اختر إصدارًا لمعاينته.",
+ "unknownAuthor": "مؤلف غير معروف",
+ "privatePage": "صفحة خاصة",
+ "restore": "استعادة",
+ "deletePermanently": "حذف نهائيًا",
+ "details": "تفاصيل الصفحة",
+ "detailsDescription": "مخطط هذه الصفحة ومعلوماتها وملفاتها.",
+ "openDetails": "فتح تفاصيل الصفحة",
+ "closeDetails": "إغلاق تفاصيل الصفحة",
+ "close": "إغلاق",
+ "outline": "المخطط",
+ "info": "المعلومات",
+ "assets": "الملفات",
+ "outlineEmpty": "أضف عناوين لإنشاء مخطط.",
+ "untitledHeading": "عنوان بلا اسم",
+ "owner": "المالك",
+ "createdAt": "تاريخ الإنشاء",
+ "updatedAt": "تاريخ التحديث",
+ "version": "الإصدار",
+ "assetsDescription": "الملفات المرفقة بهذه الصفحة",
+ "upload": "رفع",
+ "uploadAsset": "رفع ملف",
+ "assetsLoadFailed": "تعذر تحميل الملفات.",
+ "noAssets": "لا توجد ملفات بعد.",
+ "insertAsset": "إدراج {name}",
+ "copyAssetLink": "نسخ رابط {name}",
+ "assetLinkCopied": "تم نسخ رابط الملف",
+ "deleteAsset": "حذف {name}",
+ "deleteAssetConfirm": "حذف {name}؟ ستتوقف الروابط والتضمينات الحالية عن العمل.",
+ "movePage": "نقل {title}",
+ "dragInstructions": "اضغط مفتاح المسافة لالتقاط الصفحة. استخدم مفاتيح الأسهم لنقلها، ثم اضغط المسافة للإفلات أو Escape للإلغاء.",
+ "dragStarted": "تم التقاط {title}.",
+ "dragOver": "يتم النقل فوق {title}.",
+ "dragEnded": "تم النقل بالقرب من {title}.",
+ "dragCanceled": "تم إلغاء النقل.",
+ "linkWorkItem": {
+ "tab": "عناصر العمل",
+ "description": "عناصر العمل التي تستخدم هذه الصفحة كسياق.",
+ "add": "ربط",
+ "selectIssue": "ربط عنصر عمل",
+ "searchIssues": "البحث في عناصر العمل…",
+ "empty": "لا توجد عناصر عمل مرتبطة بعد.",
+ "loadFailed": "تعذر تحميل عناصر العمل المرتبطة. انقر لإعادة المحاولة.",
+ "remove": "إلغاء ربط {identifier}",
+ "selectDocument": "ربط صفحة Docs",
+ "searchDocuments": "البحث في Docs…",
+ "loading": "جارٍ تحميل Docs…",
+ "noDocuments": "لا توجد صفحات متاحة للربط."
+ },
+ "toolbar": {
+ "underline": "تسطير",
+ "textColor": "لون النص",
+ "backgroundColor": "لون الخلفية",
+ "noBackground": "بلا خلفية",
+ "defaultColor": "اللون الافتراضي",
+ "colorNumber": "اللون {number}",
+ "todoList": "قائمة مهام",
+ "table": "جدول",
+ "image": "صورة",
+ "imageUrl": "رابط الصورة",
+ "imageLibrary": "المكتبة",
+ "externalImage": "رابط خارجي",
+ "uploadImage": "رفع صورة",
+ "insertImage": "إدراج {name}",
+ "noImages": "لا توجد صور مرفوعة بعد.",
+ "insert": "إدراج",
+ "alignLeft": "محاذاة لليسار",
+ "alignCenter": "محاذاة للوسط",
+ "alignRight": "محاذاة لليمين",
+ "label": "شريط التنسيق",
+ "text": "نص",
+ "heading1": "عنوان 1",
+ "heading2": "عنوان 2",
+ "heading3": "عنوان 3",
+ "heading4": "عنوان 4",
+ "heading5": "عنوان 5",
+ "heading6": "عنوان 6",
+ "bold": "عريض",
+ "italic": "مائل",
+ "strike": "يتوسطه خط",
+ "inlineCode": "كود ضمن السطر",
+ "bulletList": "قائمة نقطية",
+ "numberedList": "قائمة مرقمة",
+ "quote": "اقتباس",
+ "codeBlock": "كتلة كود",
+ "divider": "فاصل",
+ "undo": "تراجع",
+ "redo": "إعادة"
+ }
+}
diff --git a/apps/web/messages/ar/issue.json b/apps/web/messages/ar/issue.json
index 87afd8f4..720ea725 100644
--- a/apps/web/messages/ar/issue.json
+++ b/apps/web/messages/ar/issue.json
@@ -345,6 +345,14 @@
"skipped": "تم تخطيه"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "ربط صفحة Docs",
+ "empty": "لا توجد صفحات Docs مرتبطة بعد.",
+ "loadFailed": "تعذر تحميل الصفحات المرتبطة. انقر لإعادة المحاولة.",
+ "remove": "إلغاء ربط {title}",
+ "untitled": "بلا عنوان"
+ },
"archived": "مؤرشفة",
"activityHeading": "النشاط",
"feedFlat": "مسطّح",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "متابعة",
- "unwatch": "إلغاء المتابعة"
+ "unwatch": "إلغاء المتابعة",
+ "manage": "إدارة المتابعين",
+ "search": "البحث عن أعضاء المشروع…",
+ "empty": "لم يتم العثور على أعضاء.",
+ "you": "{name} (أنت)",
+ "add": "إضافة {name} كمتابع",
+ "remove": "إزالة {name} من المتابعين",
+ "watchingCount": "{count} متابع"
},
"effects": {
"cleared": "تم المسح",
diff --git a/apps/web/messages/ar/nav.json b/apps/web/messages/ar/nav.json
index 6c4b7056..2a56b476 100644
--- a/apps/web/messages/ar/nav.json
+++ b/apps/web/messages/ar/nav.json
@@ -6,6 +6,7 @@
"initiatives": "المبادرات (initiatives)",
"cycles": "الدورات (cycles)",
"notes": "الملاحظات",
+ "documents": "Docs",
"aiTeam": "فريق الذكاء الاصطناعي",
"configure": "تهيئة",
"aiAgents": "وكلاء الذكاء الاصطناعي (AI agents)",
diff --git a/apps/web/messages/ar/newProject.json b/apps/web/messages/ar/newProject.json
index af92ccf4..b0aa832a 100644
--- a/apps/web/messages/ar/newProject.json
+++ b/apps/web/messages/ar/newProject.json
@@ -26,7 +26,8 @@
"automation": "الأتمتة",
"project": "المشروع",
"views": "العروض",
- "aiTeam": "فريق الذكاء الاصطناعي"
+ "aiTeam": "فريق الذكاء الاصطناعي",
+ "knowledge": "المعرفة"
},
"copyItems": {
"states": "الحالات",
@@ -35,6 +36,7 @@
"customFields": "الحقول المخصّصة",
"views": "العروض",
"dashboards": "لوحات المعلومات",
+ "documents": "Docs",
"actions": "الإجراءات",
"configuration": "التهيئة",
"roles": "الأدوار",
diff --git a/apps/web/messages/ar/permissions.json b/apps/web/messages/ar/permissions.json
index be71d951..60b92270 100644
--- a/apps/web/messages/ar/permissions.json
+++ b/apps/web/messages/ar/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "المبادرات (initiatives)",
"cycles": "الدورات (cycles)",
"dashboards": "لوحات المعلومات",
+ "documents": "Docs",
"views": "عروض عناصر العمل",
"members_invite": "الدعوات",
"members_manage": "الأعضاء",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "عناصر العمل",
"dashboards": "لوحات المعلومات",
+ "documents": "Docs",
"notes": "الملاحظات",
"ai": "الذكاء الاصطناعي",
"configuration": "التهيئة",
diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.json
index c0b7ef74..d165a47d 100644
--- a/apps/web/messages/ar/settings.json
+++ b/apps/web/messages/ar/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "اللي الوكيل يقدر يعمله في المشروع",
"searchActions": "بحث في الإجراءات",
"actionGroup": {
+ "documents": "Docs",
"issues": "المهام",
"initiatives": "المبادرات",
"cycles": "الدورات",
@@ -396,6 +397,7 @@
"features": "الميزات",
"featuresHint": "الأقسام اللي المشروع ده بيعرضها. لما توقف واحد بيتخفي بس محتواه بيفضل زي ما هو.",
"featureHints": {
+ "documents": "وثائق المشروع المشتركة والمنظمة كويكي.",
"dashboards": "رسوم بيانية ومقاييس على لوحات المعلومات المحفوظة.",
"initiatives": "مجموعات مهام بتتابعها كشغل واحد.",
"cycles": "فترات شغل محدّدة المدة بتتخطّط المهام جواها.",
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index 7d2ee268..c9d801db 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -149,6 +149,7 @@
"initiatives": "Initiatives",
"cycles": "Cycles",
"dashboards": "Dashboards",
+ "documents": "Docs",
"notes": "Notes",
"subtasks": "Subtasks",
"checklists": "Checklists",
diff --git a/apps/web/messages/en/documents.json b/apps/web/messages/en/documents.json
new file mode 100644
index 00000000..2d2462bc
--- /dev/null
+++ b/apps/web/messages/en/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "New page",
+ "favoritePages": "Favorites",
+ "publicPages": "Public",
+ "privatePages": "Private",
+ "archivedPages": "Archived",
+ "newSubpage": "Add a page below {title}",
+ "addSubpage": "Add subpage",
+ "untitled": "Untitled",
+ "titlePlaceholder": "Untitled",
+ "contentPlaceholder": "Write something, or press / for commands…",
+ "search": "Search Docs…",
+ "sort": "Sort pages",
+ "manualOrder": "Manual order",
+ "nameOrder": "Name",
+ "updatedOrder": "Last updated",
+ "createdOrder": "Created",
+ "sortAscending": "Sort ascending",
+ "sortDescending": "Sort descending",
+ "filters": "Filters",
+ "createdBy": "Created by",
+ "createdDate": "Created date",
+ "anyone": "Anyone",
+ "all": "Any time",
+ "today": "Past 24 hours",
+ "week": "Past 7 days",
+ "month": "Past 30 days",
+ "clearFilters": "Clear filters",
+ "noResults": "No pages found.",
+ "noAccess": "You do not have access to project Docs.",
+ "treeLabel": "Project Docs",
+ "expand": "Expand page",
+ "collapse": "Collapse page",
+ "backToDocuments": "Back to Docs",
+ "documentActions": "Page actions",
+ "pageIcon": "Page icon",
+ "changeIcon": "Change page icon",
+ "removeIcon": "Remove page icon",
+ "searchIcons": "Search icons…",
+ "customIcon": "Paste an emoji",
+ "setIcon": "Set",
+ "frequentIcons": "Frequent",
+ "objectIcons": "Objects",
+ "symbolIcons": "Symbols",
+ "pageTitle": "Page title",
+ "saved": "Saved",
+ "lockedReadOnly": "Locked",
+ "archivedReadOnly": "Archived",
+ "saving": "Saving…",
+ "saveFailed": "Could not save",
+ "retrySave": "Retry save",
+ "loadFailed": "Could not load Docs",
+ "conflict": "A newer version exists",
+ "reload": "Reload",
+ "reviewConflict": "Review",
+ "discardTitle": "Discard your local draft?",
+ "discardDescription": "Reloading replaces your unsaved text with the latest server version. This cannot be undone.",
+ "discardAndReload": "Discard and reload",
+ "updatedBy": "Updated by {name} {time}",
+ "updated": "Updated {time}",
+ "delete": "Delete",
+ "deleteTitle": "Delete page",
+ "deleteDescription": "Delete this page? Its subpages will move to the top level. This cannot be undone.",
+ "emptyTitle": "No pages yet",
+ "emptyDescription": "Create the first page for decisions, guides, notes, and project context.",
+ "copyTitle": "Copy of {title}",
+ "fullWidth": "Full width",
+ "stickyToolbar": "Sticky toolbar",
+ "copyMarkdown": "Copy Markdown",
+ "markdownCopied": "Markdown copied",
+ "copyLink": "Copy link",
+ "linkCopied": "Link copied",
+ "addFavorite": "Add to favorites",
+ "removeFavorite": "Remove from favorites",
+ "lock": "Lock page",
+ "unlock": "Unlock page",
+ "versionHistory": "Version history",
+ "versionHistoryDescription": "The current saved revision of this page.",
+ "currentVersion": "Current version · v{version}",
+ "savedVersion": "Version {version}",
+ "historyLoadFailed": "Could not load version history.",
+ "restoreVersion": "Restore",
+ "noHistory": "No saved versions yet.",
+ "selectVersion": "Select a version to preview.",
+ "unknownAuthor": "Unknown author",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "Earlier revisions will appear when document history is available on the server.",
+ "makeCopy": "Make a copy",
+ "privacy": "Access",
+ "projectAccess": "Project",
+ "privatePage": "Private page",
+ "archive": "Archive",
+ "restore": "Restore",
+ "deletePermanently": "Delete permanently",
+ "details": "Page details",
+ "detailsDescription": "Outline, information, and files for this page.",
+ "openDetails": "Open page details",
+ "closeDetails": "Close page details",
+ "close": "Close",
+ "outline": "Outline",
+ "info": "Info",
+ "assets": "Assets",
+ "outlineEmpty": "Add headings to build an outline.",
+ "untitledHeading": "Untitled heading",
+ "owner": "Owner",
+ "createdAt": "Created",
+ "updatedAt": "Updated",
+ "version": "Version",
+ "assetsDescription": "Files attached to this page",
+ "upload": "Upload",
+ "uploadAsset": "Upload an asset",
+ "assetsLoadFailed": "Could not load assets.",
+ "noAssets": "No assets yet.",
+ "insertAsset": "Insert {name}",
+ "copyAssetLink": "Copy link to {name}",
+ "assetLinkCopied": "Asset link copied",
+ "deleteAsset": "Delete {name}",
+ "deleteAssetConfirm": "Delete {name}? Existing links and embeds will stop working.",
+ "movePage": "Move {title}",
+ "dragInstructions": "Press Space to pick up a page. Use arrow keys to move it, then press Space to drop or Escape to cancel.",
+ "dragStarted": "Picked up {title}.",
+ "dragOver": "Moving over {title}.",
+ "dragEnded": "Moved near {title}.",
+ "dragCanceled": "Move canceled.",
+ "apiRequired": "API required",
+ "export": "Export",
+ "exportTitle": "Export page",
+ "exportDescription": "Download a portable copy of the current page.",
+ "exportFormat": "Export format",
+ "markdown": "Markdown",
+ "markdownExportHint": "Downloads as .md. If the page contains protected files, they are bundled in a .zip.",
+ "html": "HTML",
+ "download": "Download",
+ "exporting": "Preparing…",
+ "exportFailed": "The export could not include all protected assets. Try again.",
+ "exportTooLarge": "This page has too many or too much protected content to export at once (maximum 50 files and 100 MB).",
+ "cancel": "Cancel",
+ "linkWorkItem": {
+ "tab": "Work items",
+ "description": "Work items that use this page as context.",
+ "add": "Link",
+ "selectIssue": "Link a work item",
+ "searchIssues": "Search work items…",
+ "empty": "No linked work items yet.",
+ "loadFailed": "Could not load linked work items. Click to retry.",
+ "remove": "Unlink {identifier}",
+ "selectDocument": "Link a Docs page",
+ "searchDocuments": "Search Docs…",
+ "loading": "Loading Docs…",
+ "noDocuments": "No pages available to link."
+ },
+ "toolbar": {
+ "label": "Formatting toolbar",
+ "text": "Text",
+ "heading1": "Heading 1",
+ "heading2": "Heading 2",
+ "heading3": "Heading 3",
+ "heading4": "Heading 4",
+ "heading5": "Heading 5",
+ "heading6": "Heading 6",
+ "bold": "Bold",
+ "italic": "Italic",
+ "strike": "Strikethrough",
+ "underline": "Underline",
+ "inlineCode": "Inline code",
+ "textColor": "Text color",
+ "backgroundColor": "Background color",
+ "noBackground": "No background",
+ "defaultColor": "Default color",
+ "colorNumber": "Color {number}",
+ "bulletList": "Bulleted list",
+ "numberedList": "Numbered list",
+ "todoList": "To-do list",
+ "quote": "Quote",
+ "codeBlock": "Code block",
+ "divider": "Divider",
+ "table": "Table",
+ "image": "Image",
+ "imageUrl": "Image URL",
+ "imageLibrary": "Library",
+ "externalImage": "External URL",
+ "uploadImage": "Upload image",
+ "insertImage": "Insert {name}",
+ "noImages": "No uploaded images yet.",
+ "insert": "Insert",
+ "alignLeft": "Align left",
+ "alignCenter": "Align center",
+ "alignRight": "Align right",
+ "undo": "Undo",
+ "redo": "Redo"
+ }
+}
diff --git a/apps/web/messages/en/issue.json b/apps/web/messages/en/issue.json
index 8ef2c12c..2f6b9e7f 100644
--- a/apps/web/messages/en/issue.json
+++ b/apps/web/messages/en/issue.json
@@ -345,6 +345,14 @@
"skipped": "Skipped"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "Link a Docs page",
+ "empty": "No linked Docs yet.",
+ "loadFailed": "Could not load linked Docs. Click to retry.",
+ "remove": "Unlink {title}",
+ "untitled": "Untitled"
+ },
"archived": "Archived",
"activityHeading": "Activity",
"feedFlat": "Flat",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "Watch",
- "unwatch": "Unwatch"
+ "unwatch": "Unwatch",
+ "manage": "Manage watchers",
+ "search": "Search project members…",
+ "empty": "No members found.",
+ "you": "{name} (you)",
+ "add": "Add {name} as a watcher",
+ "remove": "Remove {name} from watchers",
+ "watchingCount": "{count, plural, =0 {No watchers} one {# watcher} other {# watchers}}"
},
"effects": {
"cleared": "Cleared",
diff --git a/apps/web/messages/en/nav.json b/apps/web/messages/en/nav.json
index 09bfa861..3098815e 100644
--- a/apps/web/messages/en/nav.json
+++ b/apps/web/messages/en/nav.json
@@ -6,6 +6,7 @@
"initiatives": "Initiatives",
"cycles": "Cycles",
"notes": "Notes",
+ "documents": "Docs",
"aiTeam": "AI Team",
"configure": "Configure",
"aiAgents": "AI agents",
diff --git a/apps/web/messages/en/newProject.json b/apps/web/messages/en/newProject.json
index 480bb76e..d69ef53f 100644
--- a/apps/web/messages/en/newProject.json
+++ b/apps/web/messages/en/newProject.json
@@ -26,7 +26,8 @@
"automation": "Automation",
"project": "Project",
"views": "Views",
- "aiTeam": "AI Team"
+ "aiTeam": "AI Team",
+ "knowledge": "Knowledge"
},
"copyItems": {
"states": "States",
@@ -35,6 +36,7 @@
"customFields": "Custom fields",
"views": "Views",
"dashboards": "Dashboards",
+ "documents": "Docs",
"actions": "Actions",
"configuration": "Configuration",
"roles": "Roles",
diff --git a/apps/web/messages/en/permissions.json b/apps/web/messages/en/permissions.json
index 61e95cad..d749bb15 100644
--- a/apps/web/messages/en/permissions.json
+++ b/apps/web/messages/en/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "Initiatives",
"cycles": "Cycles",
"dashboards": "Dashboards",
+ "documents": "Docs",
"views": "Work item views",
"members_invite": "Invites",
"members_manage": "Members",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "Work items",
"dashboards": "Dashboards",
+ "documents": "Docs",
"notes": "Notes",
"ai": "AI",
"configuration": "Configuration",
diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.json
index fd243351..eb3d45d1 100644
--- a/apps/web/messages/en/settings.json
+++ b/apps/web/messages/en/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "What the agent can do in the project",
"searchActions": "Search actions",
"actionGroup": {
+ "documents": "Docs",
"issues": "Issues",
"initiatives": "Initiatives",
"cycles": "Cycles",
@@ -396,6 +397,7 @@
"features": "Features",
"featuresHint": "Sections this project shows. Turning one off hides it and keeps its content.",
"featureHints": {
+ "documents": "Shared project documentation organized into pages.",
"dashboards": "Charts and metrics on saved dashboards.",
"initiatives": "Groups of issues tracked as one piece of work.",
"cycles": "Time-boxed periods of work the issues are planned into.",
diff --git a/apps/web/messages/fr/common.json b/apps/web/messages/fr/common.json
index 10cc94eb..7b1aa2ad 100644
--- a/apps/web/messages/fr/common.json
+++ b/apps/web/messages/fr/common.json
@@ -149,6 +149,7 @@
"initiatives": "Initiatives",
"cycles": "Cycles",
"dashboards": "Tableaux de bord",
+ "documents": "Docs",
"notes": "Notes",
"subtasks": "Sous-tâches",
"checklists": "Checklists",
diff --git a/apps/web/messages/fr/documents.json b/apps/web/messages/fr/documents.json
new file mode 100644
index 00000000..1b8ee4ed
--- /dev/null
+++ b/apps/web/messages/fr/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "Nouvelle page",
+ "favoritePages": "Favoris",
+ "publicPages": "Publiques",
+ "privatePages": "Privées",
+ "archivedPages": "Archivées",
+ "newSubpage": "Ajouter une page sous {title}",
+ "addSubpage": "Ajouter une sous-page",
+ "untitled": "Sans titre",
+ "titlePlaceholder": "Sans titre",
+ "contentPlaceholder": "Commencez à écrire ou appuyez sur / pour les commandes…",
+ "search": "Rechercher dans Docs…",
+ "sort": "Trier les pages",
+ "manualOrder": "Ordre manuel",
+ "nameOrder": "Nom",
+ "updatedOrder": "Dernière modification",
+ "createdOrder": "Création",
+ "sortAscending": "Tri croissant",
+ "sortDescending": "Tri décroissant",
+ "filters": "Filtres",
+ "createdBy": "Créée par",
+ "createdDate": "Date de création",
+ "anyone": "Tout le monde",
+ "all": "Toute période",
+ "today": "Dernières 24 heures",
+ "week": "7 derniers jours",
+ "month": "30 derniers jours",
+ "clearFilters": "Effacer les filtres",
+ "noResults": "Aucune page trouvée.",
+ "noAccess": "Vous n'avez pas accès aux Docs du projet.",
+ "treeLabel": "Docs du projet",
+ "expand": "Développer la page",
+ "collapse": "Réduire la page",
+ "backToDocuments": "Retour aux Docs",
+ "documentActions": "Actions de la page",
+ "pageIcon": "Icône de la page",
+ "changeIcon": "Modifier l'icône de la page",
+ "removeIcon": "Supprimer l'icône",
+ "searchIcons": "Rechercher des icônes…",
+ "customIcon": "Coller un emoji",
+ "setIcon": "Définir",
+ "frequentIcons": "Fréquentes",
+ "objectIcons": "Objets",
+ "symbolIcons": "Symboles",
+ "pageTitle": "Titre de la page",
+ "saved": "Enregistré",
+ "lockedReadOnly": "Verrouillée",
+ "archivedReadOnly": "Archivée",
+ "saving": "Enregistrement…",
+ "saveFailed": "Impossible d'enregistrer",
+ "retrySave": "Réessayer",
+ "loadFailed": "Impossible de charger Docs",
+ "conflict": "Une version plus récente existe",
+ "reload": "Recharger",
+ "reviewConflict": "Examiner",
+ "discardTitle": "Abandonner votre brouillon local ?",
+ "discardDescription": "Le rechargement remplacera votre texte non enregistré par la dernière version du serveur. Cette action est irréversible.",
+ "discardAndReload": "Abandonner et recharger",
+ "updatedBy": "Modifiée par {name} {time}",
+ "updated": "Modifiée {time}",
+ "delete": "Supprimer",
+ "deleteTitle": "Supprimer la page",
+ "deleteDescription": "Supprimer cette page ? Ses sous-pages seront déplacées au premier niveau. Cette action est irréversible.",
+ "emptyTitle": "Aucune page pour l'instant",
+ "emptyDescription": "Créez la première page pour les décisions, guides, notes et informations du projet.",
+ "copyTitle": "Copie de {title}",
+ "fullWidth": "Pleine largeur",
+ "stickyToolbar": "Barre d'outils fixe",
+ "copyMarkdown": "Copier le Markdown",
+ "markdownCopied": "Markdown copié",
+ "copyLink": "Copier le lien",
+ "linkCopied": "Lien copié",
+ "addFavorite": "Ajouter aux favoris",
+ "removeFavorite": "Retirer des favoris",
+ "lock": "Verrouiller la page",
+ "unlock": "Déverrouiller la page",
+ "versionHistory": "Historique des versions",
+ "versionHistoryDescription": "La révision actuellement enregistrée de cette page.",
+ "currentVersion": "Version actuelle · v{version}",
+ "savedVersion": "Version {version}",
+ "historyLoadFailed": "Impossible de charger l'historique des versions.",
+ "restoreVersion": "Restaurer",
+ "noHistory": "Aucune version enregistrée pour l'instant.",
+ "selectVersion": "Sélectionnez une version à prévisualiser.",
+ "unknownAuthor": "Auteur inconnu",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "Les révisions précédentes apparaîtront lorsque l'historique sera disponible sur le serveur.",
+ "makeCopy": "Créer une copie",
+ "privacy": "Accès",
+ "projectAccess": "Projet",
+ "privatePage": "Page privée",
+ "archive": "Archiver",
+ "restore": "Restaurer",
+ "deletePermanently": "Supprimer définitivement",
+ "details": "Détails de la page",
+ "detailsDescription": "Plan, informations et fichiers de cette page.",
+ "openDetails": "Ouvrir les détails de la page",
+ "closeDetails": "Fermer les détails de la page",
+ "close": "Fermer",
+ "outline": "Plan",
+ "info": "Informations",
+ "assets": "Fichiers",
+ "outlineEmpty": "Ajoutez des titres pour créer un plan.",
+ "untitledHeading": "Titre sans nom",
+ "owner": "Propriétaire",
+ "createdAt": "Créée",
+ "updatedAt": "Modifiée",
+ "version": "Version",
+ "assetsDescription": "Fichiers joints à cette page",
+ "upload": "Importer",
+ "uploadAsset": "Importer un fichier",
+ "assetsLoadFailed": "Impossible de charger les fichiers.",
+ "noAssets": "Aucun fichier pour l'instant.",
+ "insertAsset": "Insérer {name}",
+ "copyAssetLink": "Copier le lien vers {name}",
+ "assetLinkCopied": "Lien du fichier copié",
+ "deleteAsset": "Supprimer {name}",
+ "deleteAssetConfirm": "Supprimer {name} ? Les liens et intégrations existants ne fonctionneront plus.",
+ "movePage": "Déplacer {title}",
+ "dragInstructions": "Appuyez sur Espace pour saisir une page. Utilisez les flèches pour la déplacer, puis Espace pour la déposer ou Échap pour annuler.",
+ "dragStarted": "{title} saisie.",
+ "dragOver": "Déplacement sur {title}.",
+ "dragEnded": "Déplacée près de {title}.",
+ "dragCanceled": "Déplacement annulé.",
+ "apiRequired": "API requise",
+ "export": "Exporter",
+ "exportTitle": "Exporter la page",
+ "exportDescription": "Téléchargez une copie portable de la page actuelle.",
+ "exportFormat": "Format d'exportation",
+ "markdown": "Markdown",
+ "markdownExportHint": "Téléchargement au format .md. Si la page contient des fichiers protégés, ils seront regroupés dans un fichier .zip.",
+ "html": "HTML",
+ "download": "Télécharger",
+ "exporting": "Préparation…",
+ "exportFailed": "L'exportation n'a pas pu inclure tous les fichiers protégés. Réessayez.",
+ "exportTooLarge": "Cette page contient trop de contenu protégé pour être exportée en une fois (maximum 50 fichiers et 100 Mo).",
+ "cancel": "Annuler",
+ "linkWorkItem": {
+ "tab": "Tâches",
+ "description": "Tâches qui utilisent cette page comme contexte.",
+ "add": "Lier",
+ "selectIssue": "Lier une tâche",
+ "searchIssues": "Rechercher des tâches…",
+ "empty": "Aucune tâche liée.",
+ "loadFailed": "Impossible de charger les tâches liées. Cliquez pour réessayer.",
+ "remove": "Dissocier {identifier}",
+ "selectDocument": "Lier une page Docs",
+ "searchDocuments": "Rechercher dans Docs…",
+ "loading": "Chargement de Docs…",
+ "noDocuments": "Aucune page disponible à lier."
+ },
+ "toolbar": {
+ "label": "Barre de mise en forme",
+ "text": "Texte",
+ "heading1": "Titre 1",
+ "heading2": "Titre 2",
+ "heading3": "Titre 3",
+ "heading4": "Titre 4",
+ "heading5": "Titre 5",
+ "heading6": "Titre 6",
+ "bold": "Gras",
+ "italic": "Italique",
+ "strike": "Barré",
+ "underline": "Souligné",
+ "inlineCode": "Code en ligne",
+ "textColor": "Couleur du texte",
+ "backgroundColor": "Couleur d'arrière-plan",
+ "noBackground": "Sans arrière-plan",
+ "defaultColor": "Couleur par défaut",
+ "colorNumber": "Couleur {number}",
+ "bulletList": "Liste à puces",
+ "numberedList": "Liste numérotée",
+ "todoList": "Liste de tâches",
+ "quote": "Citation",
+ "codeBlock": "Bloc de code",
+ "divider": "Séparateur",
+ "table": "Tableau",
+ "image": "Image",
+ "imageUrl": "URL de l'image",
+ "imageLibrary": "Bibliothèque",
+ "externalImage": "URL externe",
+ "uploadImage": "Importer une image",
+ "insertImage": "Insérer {name}",
+ "noImages": "Aucune image importée pour l'instant.",
+ "insert": "Insérer",
+ "alignLeft": "Aligner à gauche",
+ "alignCenter": "Centrer",
+ "alignRight": "Aligner à droite",
+ "undo": "Annuler",
+ "redo": "Rétablir"
+ }
+}
diff --git a/apps/web/messages/fr/issue.json b/apps/web/messages/fr/issue.json
index c9dd4f8f..ed195057 100644
--- a/apps/web/messages/fr/issue.json
+++ b/apps/web/messages/fr/issue.json
@@ -345,6 +345,14 @@
"skipped": "Ignoré"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "Lier une page Docs",
+ "empty": "Aucune page Docs liée.",
+ "loadFailed": "Impossible de charger les pages liées. Cliquez pour réessayer.",
+ "remove": "Dissocier {title}",
+ "untitled": "Sans titre"
+ },
"archived": "Archivé",
"activityHeading": "Activité",
"feedFlat": "À plat",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "Suivre",
- "unwatch": "Ne plus suivre"
+ "unwatch": "Ne plus suivre",
+ "manage": "Gérer les abonnés",
+ "search": "Rechercher des membres du projet…",
+ "empty": "Aucun membre trouvé.",
+ "you": "{name} (vous)",
+ "add": "Ajouter {name} aux abonnés",
+ "remove": "Retirer {name} des abonnés",
+ "watchingCount": "{count, plural, =0 {Aucun abonné} one {# abonné} other {# abonnés}}"
},
"effects": {
"cleared": "Effacé",
diff --git a/apps/web/messages/fr/nav.json b/apps/web/messages/fr/nav.json
index 186cf4b2..04794a18 100644
--- a/apps/web/messages/fr/nav.json
+++ b/apps/web/messages/fr/nav.json
@@ -5,6 +5,7 @@
"allWorkItems": "Tous les tickets",
"initiatives": "Initiatives",
"cycles": "Cycles",
+ "documents": "Docs",
"notes": "Notes",
"aiTeam": "Équipe IA",
"configure": "Configurer",
diff --git a/apps/web/messages/fr/newProject.json b/apps/web/messages/fr/newProject.json
index deb8a0e0..ce5ad2b2 100644
--- a/apps/web/messages/fr/newProject.json
+++ b/apps/web/messages/fr/newProject.json
@@ -26,7 +26,8 @@
"automation": "Automatisation",
"project": "Projet",
"views": "Vues",
- "aiTeam": "Équipe IA"
+ "aiTeam": "Équipe IA",
+ "knowledge": "Connaissances"
},
"copyItems": {
"states": "États",
@@ -35,6 +36,7 @@
"customFields": "Champs personnalisés",
"views": "Vues",
"dashboards": "Tableaux de bord",
+ "documents": "Docs",
"actions": "Actions",
"configuration": "Configuration",
"roles": "Rôles",
diff --git a/apps/web/messages/fr/permissions.json b/apps/web/messages/fr/permissions.json
index 33e397cb..06b45b5d 100644
--- a/apps/web/messages/fr/permissions.json
+++ b/apps/web/messages/fr/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "Initiatives",
"cycles": "Cycles",
"dashboards": "Tableaux de bord",
+ "documents": "Docs",
"views": "Vues de tickets",
"members_invite": "Invitations",
"members_manage": "Membres",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "Tickets",
"dashboards": "Tableaux de bord",
+ "documents": "Docs",
"notes": "Notes",
"ai": "IA",
"configuration": "Configuration",
diff --git a/apps/web/messages/fr/settings.json b/apps/web/messages/fr/settings.json
index 970c543e..d5b208ad 100644
--- a/apps/web/messages/fr/settings.json
+++ b/apps/web/messages/fr/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "Ce que l'agent peut faire dans le projet",
"searchActions": "Rechercher une action",
"actionGroup": {
+ "documents": "Docs",
"issues": "Tickets",
"initiatives": "Initiatives",
"cycles": "Cycles",
@@ -396,6 +397,7 @@
"features": "Sections",
"featuresHint": "Les sections que ce projet affiche. En désactiver une la masque et conserve son contenu.",
"featureHints": {
+ "documents": "Documentation partagée du projet, organisée en pages.",
"dashboards": "Graphiques et métriques sur des tableaux de bord enregistrés.",
"initiatives": "Des groupes de tickets suivis comme un seul chantier.",
"cycles": "Des périodes délimitées dans lesquelles les tickets sont planifiés.",
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index 9ee75a18..ea87e9cc 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -149,6 +149,7 @@
"initiatives": "Инициативы",
"cycles": "Циклы",
"dashboards": "Дашборды",
+ "documents": "Docs",
"notes": "Заметки",
"subtasks": "Подзадачи",
"checklists": "Чек-листы",
diff --git a/apps/web/messages/ru/documents.json b/apps/web/messages/ru/documents.json
new file mode 100644
index 00000000..f071b37f
--- /dev/null
+++ b/apps/web/messages/ru/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "Новая страница",
+ "favoritePages": "Избранное",
+ "newSubpage": "Добавить страницу в {title}",
+ "addSubpage": "Добавить подстраницу",
+ "untitled": "Без названия",
+ "titlePlaceholder": "Без названия",
+ "contentPlaceholder": "Начните писать или нажмите / для команд…",
+ "search": "Поиск в Docs…",
+ "sort": "Сортировать страницы",
+ "manualOrder": "Вручную",
+ "nameOrder": "По названию",
+ "updatedOrder": "По обновлению",
+ "createdOrder": "По созданию",
+ "sortAscending": "По возрастанию",
+ "sortDescending": "По убыванию",
+ "filters": "Фильтры",
+ "createdBy": "Автор",
+ "createdDate": "Дата создания",
+ "anyone": "Любой",
+ "all": "За всё время",
+ "today": "За 24 часа",
+ "week": "За 7 дней",
+ "month": "За 30 дней",
+ "clearFilters": "Сбросить фильтры",
+ "noResults": "Страницы не найдены.",
+ "noAccess": "У вас нет доступа к Docs проекта.",
+ "treeLabel": "Docs проекта",
+ "expand": "Развернуть страницу",
+ "collapse": "Свернуть страницу",
+ "backToDocuments": "Назад в Docs",
+ "documentActions": "Действия со страницей",
+ "pageIcon": "Иконка страницы",
+ "pageTitle": "Название страницы",
+ "saved": "Сохранено",
+ "saving": "Сохраняем…",
+ "saveFailed": "Не удалось сохранить",
+ "retrySave": "Повторить сохранение",
+ "loadFailed": "Не удалось загрузить Docs",
+ "conflict": "Есть более новая версия",
+ "reload": "Обновить",
+ "reviewConflict": "Разобраться",
+ "discardTitle": "Сбросить локальный черновик?",
+ "discardDescription": "При обновлении несохранённый текст заменится последней версией с сервера. Это действие нельзя отменить.",
+ "discardAndReload": "Сбросить и обновить",
+ "updatedBy": "Обновил(а) {name} {time}",
+ "updated": "Обновлено {time}",
+ "delete": "Удалить",
+ "deleteTitle": "Удалить страницу",
+ "deleteDescription": "Удалить эту страницу? Её подстраницы переместятся на верхний уровень. Действие нельзя отменить.",
+ "emptyTitle": "Пока нет страниц",
+ "emptyDescription": "Создайте первую страницу для решений, инструкций, заметок и контекста проекта.",
+ "copyTitle": "Копия — {title}",
+ "fullWidth": "На всю ширину",
+ "stickyToolbar": "Закрепить панель",
+ "copyMarkdown": "Копировать Markdown",
+ "markdownCopied": "Markdown скопирован",
+ "copyLink": "Копировать ссылку",
+ "linkCopied": "Ссылка скопирована",
+ "versionHistory": "История версий",
+ "versionHistoryDescription": "Текущая сохранённая версия страницы.",
+ "currentVersion": "Текущая версия · v{version}",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "Предыдущие версии появятся после поддержки истории документов на сервере.",
+ "makeCopy": "Создать копию",
+ "privacy": "Доступ",
+ "projectAccess": "Проект",
+ "archive": "Архивировать",
+ "apiRequired": "Нужен API",
+ "export": "Экспорт",
+ "exportTitle": "Экспорт страницы",
+ "exportDescription": "Скачайте переносимую копию текущей страницы.",
+ "exportFormat": "Формат экспорта",
+ "markdown": "Markdown",
+ "markdownExportHint": "Скачивается как .md. Если на странице есть защищённые файлы, они будут упакованы вместе с ней в .zip.",
+ "html": "HTML",
+ "download": "Скачать",
+ "exporting": "Подготовка…",
+ "exportFailed": "Не удалось добавить в экспорт все защищённые файлы. Попробуйте ещё раз.",
+ "exportTooLarge": "На странице слишком много защищённых файлов или они слишком велики для одного экспорта (максимум 50 файлов и 100 МБ).",
+ "cancel": "Отмена",
+ "publicPages": "Общие",
+ "privatePages": "Личные",
+ "archivedPages": "Архив",
+ "changeIcon": "Изменить иконку страницы",
+ "removeIcon": "Удалить иконку страницы",
+ "searchIcons": "Поиск иконок…",
+ "customIcon": "Вставьте эмодзи",
+ "setIcon": "Выбрать",
+ "frequentIcons": "Частые",
+ "objectIcons": "Объекты",
+ "symbolIcons": "Символы",
+ "lockedReadOnly": "Заблокировано",
+ "archivedReadOnly": "В архиве",
+ "addFavorite": "Добавить в избранное",
+ "removeFavorite": "Убрать из избранного",
+ "lock": "Заблокировать страницу",
+ "unlock": "Разблокировать страницу",
+ "savedVersion": "Версия {version}",
+ "historyLoadFailed": "Не удалось загрузить историю версий.",
+ "restoreVersion": "Восстановить",
+ "noHistory": "Сохранённых версий пока нет.",
+ "selectVersion": "Выберите версию для просмотра.",
+ "unknownAuthor": "Автор неизвестен",
+ "privatePage": "Личная страница",
+ "restore": "Восстановить",
+ "deletePermanently": "Удалить навсегда",
+ "details": "Сведения о странице",
+ "detailsDescription": "Структура, сведения и файлы этой страницы.",
+ "openDetails": "Открыть сведения о странице",
+ "closeDetails": "Закрыть сведения о странице",
+ "close": "Закрыть",
+ "outline": "Структура",
+ "info": "Сведения",
+ "assets": "Файлы",
+ "outlineEmpty": "Добавьте заголовки, чтобы появилась структура.",
+ "untitledHeading": "Заголовок без названия",
+ "owner": "Владелец",
+ "createdAt": "Создано",
+ "updatedAt": "Обновлено",
+ "version": "Версия",
+ "assetsDescription": "Файлы этой страницы",
+ "upload": "Загрузить",
+ "uploadAsset": "Загрузить файл",
+ "assetsLoadFailed": "Не удалось загрузить файлы.",
+ "noAssets": "Файлов пока нет.",
+ "insertAsset": "Вставить {name}",
+ "copyAssetLink": "Копировать ссылку на {name}",
+ "assetLinkCopied": "Ссылка на файл скопирована",
+ "deleteAsset": "Удалить {name}",
+ "deleteAssetConfirm": "Удалить {name}? Существующие ссылки и вставки перестанут работать.",
+ "movePage": "Переместить {title}",
+ "dragInstructions": "Нажмите пробел, чтобы поднять страницу. Перемещайте её стрелками, затем нажмите пробел для подтверждения или Escape для отмены.",
+ "dragStarted": "Страница {title} поднята.",
+ "dragOver": "Перемещение над {title}.",
+ "dragEnded": "Перемещено рядом с {title}.",
+ "dragCanceled": "Перемещение отменено.",
+ "linkWorkItem": {
+ "tab": "Задачи",
+ "description": "Задачи, для которых эта страница служит контекстом.",
+ "add": "Связать",
+ "selectIssue": "Связать задачу",
+ "searchIssues": "Поиск задач…",
+ "empty": "Связанных задач пока нет.",
+ "loadFailed": "Не удалось загрузить связанные задачи. Нажмите, чтобы повторить.",
+ "remove": "Отвязать {identifier}",
+ "selectDocument": "Связать страницу Docs",
+ "searchDocuments": "Поиск в Docs…",
+ "loading": "Загрузка Docs…",
+ "noDocuments": "Нет доступных страниц для связи."
+ },
+ "toolbar": {
+ "underline": "Подчёркнутый",
+ "textColor": "Цвет текста",
+ "backgroundColor": "Цвет фона",
+ "noBackground": "Без фона",
+ "defaultColor": "Цвет по умолчанию",
+ "colorNumber": "Цвет {number}",
+ "todoList": "Список задач",
+ "table": "Таблица",
+ "image": "Изображение",
+ "imageUrl": "URL изображения",
+ "imageLibrary": "Библиотека",
+ "externalImage": "Внешний URL",
+ "uploadImage": "Загрузить изображение",
+ "insertImage": "Вставить {name}",
+ "noImages": "Загруженных изображений пока нет.",
+ "insert": "Вставить",
+ "alignLeft": "По левому краю",
+ "alignCenter": "По центру",
+ "alignRight": "По правому краю",
+ "label": "Панель форматирования",
+ "text": "Текст",
+ "heading1": "Заголовок 1",
+ "heading2": "Заголовок 2",
+ "heading3": "Заголовок 3",
+ "heading4": "Заголовок 4",
+ "heading5": "Заголовок 5",
+ "heading6": "Заголовок 6",
+ "bold": "Полужирный",
+ "italic": "Курсив",
+ "strike": "Зачёркнутый",
+ "inlineCode": "Код в строке",
+ "bulletList": "Маркированный список",
+ "numberedList": "Нумерованный список",
+ "quote": "Цитата",
+ "codeBlock": "Блок кода",
+ "divider": "Разделитель",
+ "undo": "Отменить",
+ "redo": "Повторить"
+ }
+}
diff --git a/apps/web/messages/ru/issue.json b/apps/web/messages/ru/issue.json
index f1f72bc6..5eeb69f4 100644
--- a/apps/web/messages/ru/issue.json
+++ b/apps/web/messages/ru/issue.json
@@ -345,6 +345,14 @@
"skipped": "Пропущен"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "Связать страницу Docs",
+ "empty": "Связанных страниц Docs пока нет.",
+ "loadFailed": "Не удалось загрузить связанные страницы. Нажмите, чтобы повторить.",
+ "remove": "Отвязать {title}",
+ "untitled": "Без названия"
+ },
"archived": "В архиве",
"activityHeading": "Активность",
"feedFlat": "Списком",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "Следить",
- "unwatch": "Не следить"
+ "unwatch": "Не следить",
+ "manage": "Управлять наблюдателями",
+ "search": "Найти участника проекта…",
+ "empty": "Участники не найдены.",
+ "you": "{name} (вы)",
+ "add": "Добавить {name} в наблюдатели",
+ "remove": "Убрать {name} из наблюдателей",
+ "watchingCount": "{count, plural, =0 {Никто не следит} one {# наблюдатель} few {# наблюдателя} many {# наблюдателей} other {# наблюдателя}}"
},
"effects": {
"cleared": "Очищено",
diff --git a/apps/web/messages/ru/nav.json b/apps/web/messages/ru/nav.json
index 5df91ee9..3a28774e 100644
--- a/apps/web/messages/ru/nav.json
+++ b/apps/web/messages/ru/nav.json
@@ -6,6 +6,7 @@
"initiatives": "Инициативы",
"cycles": "Циклы",
"notes": "Заметки",
+ "documents": "Docs",
"aiTeam": "AI-команда",
"configure": "Настроить",
"aiAgents": "AI-агенты",
diff --git a/apps/web/messages/ru/newProject.json b/apps/web/messages/ru/newProject.json
index 019bd8cb..1ffb8dcf 100644
--- a/apps/web/messages/ru/newProject.json
+++ b/apps/web/messages/ru/newProject.json
@@ -26,7 +26,8 @@
"automation": "Автоматизация",
"project": "Проект",
"views": "Представления",
- "aiTeam": "AI-команда"
+ "aiTeam": "AI-команда",
+ "knowledge": "Знания"
},
"copyItems": {
"states": "Статусы",
@@ -35,6 +36,7 @@
"customFields": "Пользовательские поля",
"views": "Представления",
"dashboards": "Дашборды",
+ "documents": "Docs",
"actions": "Действия",
"configuration": "Конфигурация",
"roles": "Роли",
diff --git a/apps/web/messages/ru/permissions.json b/apps/web/messages/ru/permissions.json
index 0762c9af..69b24e62 100644
--- a/apps/web/messages/ru/permissions.json
+++ b/apps/web/messages/ru/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "Инициативы",
"cycles": "Циклы",
"dashboards": "Дашборды",
+ "documents": "Docs",
"views": "Представления задач",
"members_invite": "Приглашения",
"members_manage": "Участники",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "Задачи",
"dashboards": "Дашборды",
+ "documents": "Docs",
"notes": "Заметки",
"ai": "AI",
"configuration": "Настройки",
diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.json
index 473d2d0f..92756db0 100644
--- a/apps/web/messages/ru/settings.json
+++ b/apps/web/messages/ru/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "Что агент может делать в проекте",
"searchActions": "Поиск действий",
"actionGroup": {
+ "documents": "Docs",
"issues": "Задачи",
"initiatives": "Инициативы",
"cycles": "Циклы",
@@ -396,6 +397,7 @@
"features": "Разделы",
"featuresHint": "Разделы, которые показывает этот проект. Выключение скрывает раздел и сохраняет его содержимое.",
"featureHints": {
+ "documents": "Общая документация проекта в Docs.",
"dashboards": "Графики и метрики на сохранённых дашбордах.",
"initiatives": "Группы задач, которые ведутся как одна работа.",
"cycles": "Ограниченные по времени периоды работы, в которые планируются задачи.",
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index 8afbef76..71c43367 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -149,6 +149,7 @@
"initiatives": "Ініціативи",
"cycles": "Цикли",
"dashboards": "Дашборди",
+ "documents": "Docs",
"notes": "Нотатки",
"subtasks": "Підзадачі",
"checklists": "Чеклісти",
diff --git a/apps/web/messages/uk/documents.json b/apps/web/messages/uk/documents.json
new file mode 100644
index 00000000..16be4722
--- /dev/null
+++ b/apps/web/messages/uk/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "Нова сторінка",
+ "favoritePages": "Обрані",
+ "newSubpage": "Додати сторінку до {title}",
+ "addSubpage": "Додати підсторінку",
+ "untitled": "Без назви",
+ "titlePlaceholder": "Без назви",
+ "contentPlaceholder": "Почніть писати або натисніть / для команд…",
+ "search": "Пошук у Docs…",
+ "sort": "Сортувати сторінки",
+ "manualOrder": "Вручну",
+ "nameOrder": "За назвою",
+ "updatedOrder": "За оновленням",
+ "createdOrder": "За створенням",
+ "sortAscending": "За зростанням",
+ "sortDescending": "За спаданням",
+ "filters": "Фільтри",
+ "createdBy": "Автор",
+ "createdDate": "Дата створення",
+ "anyone": "Будь-хто",
+ "all": "За весь час",
+ "today": "За 24 години",
+ "week": "За 7 днів",
+ "month": "За 30 днів",
+ "clearFilters": "Скинути фільтри",
+ "noResults": "Сторінок не знайдено.",
+ "noAccess": "У вас немає доступу до Docs проєкту.",
+ "treeLabel": "Docs проєкту",
+ "expand": "Розгорнути сторінку",
+ "collapse": "Згорнути сторінку",
+ "backToDocuments": "Назад до Docs",
+ "documentActions": "Дії зі сторінкою",
+ "pageIcon": "Іконка сторінки",
+ "pageTitle": "Назва сторінки",
+ "saved": "Збережено",
+ "saving": "Зберігаємо…",
+ "saveFailed": "Не вдалося зберегти",
+ "retrySave": "Повторити збереження",
+ "loadFailed": "Не вдалося завантажити Docs",
+ "conflict": "Існує новіша версія",
+ "reload": "Оновити",
+ "reviewConflict": "Переглянути",
+ "discardTitle": "Відкинути локальну чернетку?",
+ "discardDescription": "Після оновлення незбережений текст буде замінено останньою версією із сервера. Цю дію неможливо скасувати.",
+ "discardAndReload": "Відкинути й оновити",
+ "updatedBy": "Оновив(ла) {name} {time}",
+ "updated": "Оновлено {time}",
+ "delete": "Видалити",
+ "deleteTitle": "Видалити сторінку",
+ "deleteDescription": "Видалити цю сторінку? Її підсторінки перейдуть на верхній рівень. Дію неможливо скасувати.",
+ "emptyTitle": "Сторінок ще немає",
+ "emptyDescription": "Створіть першу сторінку для рішень, інструкцій, нотаток і контексту проєкту.",
+ "copyTitle": "Копія — {title}",
+ "fullWidth": "На всю ширину",
+ "stickyToolbar": "Закріпити панель",
+ "copyMarkdown": "Копіювати Markdown",
+ "markdownCopied": "Markdown скопійовано",
+ "copyLink": "Копіювати посилання",
+ "linkCopied": "Посилання скопійовано",
+ "versionHistory": "Історія версій",
+ "versionHistoryDescription": "Поточна збережена версія сторінки.",
+ "currentVersion": "Поточна версія · v{version}",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "Попередні версії з’являться після підтримки історії документів на сервері.",
+ "makeCopy": "Створити копію",
+ "privacy": "Доступ",
+ "projectAccess": "Проєкт",
+ "archive": "Архівувати",
+ "apiRequired": "Потрібен API",
+ "export": "Експорт",
+ "exportTitle": "Експорт сторінки",
+ "exportDescription": "Завантажте переносну копію поточної сторінки.",
+ "exportFormat": "Формат експорту",
+ "markdown": "Markdown",
+ "markdownExportHint": "Завантажується як .md. Якщо сторінка містить захищені файли, їх буде запаковано разом із нею в .zip.",
+ "html": "HTML",
+ "download": "Завантажити",
+ "exporting": "Підготовка…",
+ "exportFailed": "Не вдалося додати до експорту всі захищені файли. Спробуйте ще раз.",
+ "exportTooLarge": "На сторінці забагато захищених файлів або вони завеликі для одного експорту (максимум 50 файлів і 100 МБ).",
+ "cancel": "Скасувати",
+ "publicPages": "Спільні",
+ "privatePages": "Особисті",
+ "archivedPages": "Архів",
+ "changeIcon": "Змінити іконку сторінки",
+ "removeIcon": "Видалити іконку сторінки",
+ "searchIcons": "Пошук іконок…",
+ "customIcon": "Вставте емодзі",
+ "setIcon": "Вибрати",
+ "frequentIcons": "Часті",
+ "objectIcons": "Об’єкти",
+ "symbolIcons": "Символи",
+ "lockedReadOnly": "Заблоковано",
+ "archivedReadOnly": "В архіві",
+ "addFavorite": "Додати до обраного",
+ "removeFavorite": "Прибрати з обраного",
+ "lock": "Заблокувати сторінку",
+ "unlock": "Розблокувати сторінку",
+ "savedVersion": "Версія {version}",
+ "historyLoadFailed": "Не вдалося завантажити історію версій.",
+ "restoreVersion": "Відновити",
+ "noHistory": "Збережених версій ще немає.",
+ "selectVersion": "Оберіть версію для перегляду.",
+ "unknownAuthor": "Автор невідомий",
+ "privatePage": "Особиста сторінка",
+ "restore": "Відновити",
+ "deletePermanently": "Видалити назавжди",
+ "details": "Відомості про сторінку",
+ "detailsDescription": "Структура, відомості та файли цієї сторінки.",
+ "openDetails": "Відкрити відомості про сторінку",
+ "closeDetails": "Закрити відомості про сторінку",
+ "close": "Закрити",
+ "outline": "Структура",
+ "info": "Відомості",
+ "assets": "Файли",
+ "outlineEmpty": "Додайте заголовки, щоб з’явилася структура.",
+ "untitledHeading": "Заголовок без назви",
+ "owner": "Власник",
+ "createdAt": "Створено",
+ "updatedAt": "Оновлено",
+ "version": "Версія",
+ "assetsDescription": "Файли цієї сторінки",
+ "upload": "Завантажити",
+ "uploadAsset": "Завантажити файл",
+ "assetsLoadFailed": "Не вдалося завантажити файли.",
+ "noAssets": "Файлів ще немає.",
+ "insertAsset": "Вставити {name}",
+ "copyAssetLink": "Копіювати посилання на {name}",
+ "assetLinkCopied": "Посилання на файл скопійовано",
+ "deleteAsset": "Видалити {name}",
+ "deleteAssetConfirm": "Видалити {name}? Наявні посилання та вставки перестануть працювати.",
+ "movePage": "Перемістити {title}",
+ "dragInstructions": "Натисніть пробіл, щоб підняти сторінку. Переміщуйте її стрілками, потім натисніть пробіл для підтвердження або Escape для скасування.",
+ "dragStarted": "Сторінку {title} піднято.",
+ "dragOver": "Переміщення над {title}.",
+ "dragEnded": "Переміщено поруч із {title}.",
+ "dragCanceled": "Переміщення скасовано.",
+ "linkWorkItem": {
+ "tab": "Задачі",
+ "description": "Задачі, для яких ця сторінка слугує контекстом.",
+ "add": "Пов’язати",
+ "selectIssue": "Пов’язати задачу",
+ "searchIssues": "Пошук задач…",
+ "empty": "Пов’язаних задач ще немає.",
+ "loadFailed": "Не вдалося завантажити пов’язані задачі. Натисніть, щоб повторити.",
+ "remove": "Відв’язати {identifier}",
+ "selectDocument": "Пов’язати сторінку Docs",
+ "searchDocuments": "Пошук у Docs…",
+ "loading": "Завантаження Docs…",
+ "noDocuments": "Немає доступних сторінок для зв’язку."
+ },
+ "toolbar": {
+ "underline": "Підкреслений",
+ "textColor": "Колір тексту",
+ "backgroundColor": "Колір тла",
+ "noBackground": "Без тла",
+ "defaultColor": "Типовий колір",
+ "colorNumber": "Колір {number}",
+ "todoList": "Список завдань",
+ "table": "Таблиця",
+ "image": "Зображення",
+ "imageUrl": "URL зображення",
+ "imageLibrary": "Бібліотека",
+ "externalImage": "Зовнішній URL",
+ "uploadImage": "Завантажити зображення",
+ "insertImage": "Вставити {name}",
+ "noImages": "Завантажених зображень ще немає.",
+ "insert": "Вставити",
+ "alignLeft": "Вирівняти ліворуч",
+ "alignCenter": "Вирівняти по центру",
+ "alignRight": "Вирівняти праворуч",
+ "label": "Панель форматування",
+ "text": "Текст",
+ "heading1": "Заголовок 1",
+ "heading2": "Заголовок 2",
+ "heading3": "Заголовок 3",
+ "heading4": "Заголовок 4",
+ "heading5": "Заголовок 5",
+ "heading6": "Заголовок 6",
+ "bold": "Напівжирний",
+ "italic": "Курсив",
+ "strike": "Закреслений",
+ "inlineCode": "Код у рядку",
+ "bulletList": "Маркований список",
+ "numberedList": "Нумерований список",
+ "quote": "Цитата",
+ "codeBlock": "Блок коду",
+ "divider": "Роздільник",
+ "undo": "Скасувати",
+ "redo": "Повторити"
+ }
+}
diff --git a/apps/web/messages/uk/issue.json b/apps/web/messages/uk/issue.json
index 7162a496..0e42b9b7 100644
--- a/apps/web/messages/uk/issue.json
+++ b/apps/web/messages/uk/issue.json
@@ -345,6 +345,14 @@
"skipped": "Пропущено"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "Пов’язати сторінку Docs",
+ "empty": "Пов’язаних сторінок Docs ще немає.",
+ "loadFailed": "Не вдалося завантажити пов’язані сторінки. Натисніть, щоб повторити.",
+ "remove": "Відв’язати {title}",
+ "untitled": "Без назви"
+ },
"archived": "Архівовано",
"activityHeading": "Активність",
"feedFlat": "Списком",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "Стежити",
- "unwatch": "Не стежити"
+ "unwatch": "Не стежити",
+ "manage": "Керувати спостерігачами",
+ "search": "Знайти учасника проєкту…",
+ "empty": "Учасників не знайдено.",
+ "you": "{name} (ви)",
+ "add": "Додати {name} до спостерігачів",
+ "remove": "Прибрати {name} зі спостерігачів",
+ "watchingCount": "{count, plural, =0 {Ніхто не стежить} one {# спостерігач} few {# спостерігачі} many {# спостерігачів} other {# спостерігача}}"
},
"effects": {
"cleared": "Очищено",
diff --git a/apps/web/messages/uk/nav.json b/apps/web/messages/uk/nav.json
index ed0522b9..179fc55a 100644
--- a/apps/web/messages/uk/nav.json
+++ b/apps/web/messages/uk/nav.json
@@ -6,6 +6,7 @@
"initiatives": "Ініціативи",
"cycles": "Цикли",
"notes": "Нотатки",
+ "documents": "Docs",
"aiTeam": "AI-команда",
"configure": "Налаштувати",
"aiAgents": "AI-агенти",
diff --git a/apps/web/messages/uk/newProject.json b/apps/web/messages/uk/newProject.json
index 55f1736b..94de49cb 100644
--- a/apps/web/messages/uk/newProject.json
+++ b/apps/web/messages/uk/newProject.json
@@ -26,7 +26,8 @@
"automation": "Автоматизація",
"project": "Проєкт",
"views": "Подання",
- "aiTeam": "AI-команда"
+ "aiTeam": "AI-команда",
+ "knowledge": "Знання"
},
"copyItems": {
"states": "Статуси",
@@ -35,6 +36,7 @@
"customFields": "Власні поля",
"views": "Подання",
"dashboards": "Дашборди",
+ "documents": "Docs",
"actions": "Дії",
"configuration": "Конфігурація",
"roles": "Ролі",
diff --git a/apps/web/messages/uk/permissions.json b/apps/web/messages/uk/permissions.json
index 4bd4dced..ea1ec334 100644
--- a/apps/web/messages/uk/permissions.json
+++ b/apps/web/messages/uk/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "Ініціативи",
"cycles": "Цикли",
"dashboards": "Дашборди",
+ "documents": "Docs",
"views": "Подання задач",
"members_invite": "Запрошення",
"members_manage": "Учасники",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "Задачі",
"dashboards": "Дашборди",
+ "documents": "Docs",
"notes": "Нотатки",
"ai": "AI",
"configuration": "Налаштування",
diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.json
index 0c14b3fb..d04f31c7 100644
--- a/apps/web/messages/uk/settings.json
+++ b/apps/web/messages/uk/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "Що агент може робити в проєкті",
"searchActions": "Пошук дій",
"actionGroup": {
+ "documents": "Docs",
"issues": "Задачі",
"initiatives": "Ініціативи",
"cycles": "Цикли",
@@ -396,6 +397,7 @@
"features": "Розділи",
"featuresHint": "Розділи, які показує цей проєкт. Вимкнений розділ ховається, а його вміст залишається.",
"featureHints": {
+ "documents": "Спільна документація проєкту в Docs.",
"dashboards": "Графіки та метрики на збережених дашбордах.",
"initiatives": "Групи задач, які ведуться як одна робота.",
"cycles": "Обмежені в часі періоди роботи, у які плануються задачі.",
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index 74de2643..969e9f63 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -149,6 +149,7 @@
"initiatives": "计划",
"cycles": "周期",
"dashboards": "仪表盘",
+ "documents": "Docs",
"notes": "便签",
"subtasks": "子任务",
"checklists": "检查清单",
diff --git a/apps/web/messages/zh-CN/documents.json b/apps/web/messages/zh-CN/documents.json
new file mode 100644
index 00000000..9ce09976
--- /dev/null
+++ b/apps/web/messages/zh-CN/documents.json
@@ -0,0 +1,193 @@
+{
+ "title": "Docs",
+ "newDocument": "新建页面",
+ "favoritePages": "收藏",
+ "newSubpage": "在 {title} 下添加页面",
+ "addSubpage": "添加子页面",
+ "untitled": "无标题",
+ "titlePlaceholder": "无标题",
+ "contentPlaceholder": "开始输入,或按 / 打开命令…",
+ "search": "搜索 Docs…",
+ "sort": "页面排序",
+ "manualOrder": "手动排序",
+ "nameOrder": "名称",
+ "updatedOrder": "最近更新",
+ "createdOrder": "创建时间",
+ "sortAscending": "升序排列",
+ "sortDescending": "降序排列",
+ "filters": "筛选",
+ "createdBy": "创建者",
+ "createdDate": "创建日期",
+ "anyone": "任何人",
+ "all": "不限时间",
+ "today": "过去 24 小时",
+ "week": "过去 7 天",
+ "month": "过去 30 天",
+ "clearFilters": "清除筛选",
+ "noResults": "未找到页面。",
+ "noAccess": "你无权访问项目 Docs。",
+ "treeLabel": "项目 Docs",
+ "expand": "展开页面",
+ "collapse": "收起页面",
+ "backToDocuments": "返回 Docs",
+ "documentActions": "页面操作",
+ "pageIcon": "页面图标",
+ "pageTitle": "页面标题",
+ "saved": "已保存",
+ "saving": "正在保存…",
+ "saveFailed": "保存失败",
+ "retrySave": "重试保存",
+ "loadFailed": "无法加载 Docs",
+ "conflict": "存在更新版本",
+ "reload": "重新加载",
+ "reviewConflict": "查看",
+ "discardTitle": "放弃本地草稿?",
+ "discardDescription": "重新加载会使用服务器上的最新版本替换未保存的文本,且无法撤销。",
+ "discardAndReload": "放弃并重新加载",
+ "updatedBy": "{name} 更新于 {time}",
+ "updated": "更新于 {time}",
+ "delete": "删除",
+ "deleteTitle": "删除页面",
+ "deleteDescription": "删除此页面?其子页面将移至顶层。此操作无法撤销。",
+ "emptyTitle": "还没有页面",
+ "emptyDescription": "创建第一个页面来记录决策、指南、笔记和项目背景。",
+ "copyTitle": "{title} 的副本",
+ "fullWidth": "全宽",
+ "stickyToolbar": "固定工具栏",
+ "copyMarkdown": "复制 Markdown",
+ "markdownCopied": "Markdown 已复制",
+ "copyLink": "复制链接",
+ "linkCopied": "链接已复制",
+ "versionHistory": "版本历史",
+ "versionHistoryDescription": "此页面当前保存的版本。",
+ "currentVersion": "当前版本 · v{version}",
+ "versionBy": "{name} · {time}",
+ "historyApiNotice": "服务器支持文档历史后,将显示更早的版本。",
+ "makeCopy": "创建副本",
+ "privacy": "访问权限",
+ "projectAccess": "项目",
+ "archive": "归档",
+ "apiRequired": "需要 API",
+ "export": "导出",
+ "exportTitle": "导出页面",
+ "exportDescription": "下载当前页面的便携副本。",
+ "exportFormat": "导出格式",
+ "markdown": "Markdown",
+ "markdownExportHint": "下载为 .md。如果页面包含受保护的文件,它们会一起打包为 .zip。",
+ "html": "HTML",
+ "download": "下载",
+ "exporting": "正在准备…",
+ "exportFailed": "无法在导出中包含所有受保护的文件。请重试。",
+ "exportTooLarge": "此页面的受保护文件过多或过大,无法一次导出(最多 50 个文件和 100 MB)。",
+ "cancel": "取消",
+ "publicPages": "公开",
+ "privatePages": "私人",
+ "archivedPages": "已归档",
+ "changeIcon": "更改页面图标",
+ "removeIcon": "移除页面图标",
+ "searchIcons": "搜索图标…",
+ "customIcon": "粘贴表情符号",
+ "setIcon": "设置",
+ "frequentIcons": "常用",
+ "objectIcons": "物品",
+ "symbolIcons": "符号",
+ "lockedReadOnly": "已锁定",
+ "archivedReadOnly": "已归档",
+ "addFavorite": "添加到收藏",
+ "removeFavorite": "从收藏中移除",
+ "lock": "锁定页面",
+ "unlock": "解锁页面",
+ "savedVersion": "版本 {version}",
+ "historyLoadFailed": "无法加载版本历史。",
+ "restoreVersion": "恢复",
+ "noHistory": "尚无保存的版本。",
+ "selectVersion": "选择一个版本进行预览。",
+ "unknownAuthor": "未知作者",
+ "privatePage": "私人页面",
+ "restore": "恢复",
+ "deletePermanently": "永久删除",
+ "details": "页面详情",
+ "detailsDescription": "此页面的大纲、信息和附件。",
+ "openDetails": "打开页面详情",
+ "closeDetails": "关闭页面详情",
+ "close": "关闭",
+ "outline": "大纲",
+ "info": "信息",
+ "assets": "附件",
+ "outlineEmpty": "添加标题后即可生成大纲。",
+ "untitledHeading": "无标题标题",
+ "owner": "所有者",
+ "createdAt": "创建时间",
+ "updatedAt": "更新时间",
+ "version": "版本",
+ "assetsDescription": "附加到此页面的文件",
+ "upload": "上传",
+ "uploadAsset": "上传附件",
+ "assetsLoadFailed": "无法加载附件。",
+ "noAssets": "暂无附件。",
+ "insertAsset": "插入 {name}",
+ "copyAssetLink": "复制 {name} 的链接",
+ "assetLinkCopied": "附件链接已复制",
+ "deleteAsset": "删除 {name}",
+ "deleteAssetConfirm": "删除 {name}?现有链接和嵌入内容将无法使用。",
+ "movePage": "移动 {title}",
+ "dragInstructions": "按空格键拾取页面,使用方向键移动,再按空格键放下,或按 Escape 取消。",
+ "dragStarted": "已拾取 {title}。",
+ "dragOver": "正在移至 {title}。",
+ "dragEnded": "已移至 {title} 附近。",
+ "dragCanceled": "已取消移动。",
+ "linkWorkItem": {
+ "tab": "工作项",
+ "description": "将此页面用作上下文的工作项。",
+ "add": "关联",
+ "selectIssue": "关联工作项",
+ "searchIssues": "搜索工作项…",
+ "empty": "暂无关联的工作项。",
+ "loadFailed": "无法加载关联的工作项。点击重试。",
+ "remove": "取消关联 {identifier}",
+ "selectDocument": "关联 Docs 页面",
+ "searchDocuments": "搜索 Docs…",
+ "loading": "正在加载 Docs…",
+ "noDocuments": "没有可关联的页面。"
+ },
+ "toolbar": {
+ "underline": "下划线",
+ "textColor": "文本颜色",
+ "backgroundColor": "背景颜色",
+ "noBackground": "无背景",
+ "defaultColor": "默认颜色",
+ "colorNumber": "颜色 {number}",
+ "todoList": "待办列表",
+ "table": "表格",
+ "image": "图片",
+ "imageUrl": "图片 URL",
+ "imageLibrary": "图片库",
+ "externalImage": "外部 URL",
+ "uploadImage": "上传图片",
+ "insertImage": "插入 {name}",
+ "noImages": "暂无已上传图片。",
+ "insert": "插入",
+ "alignLeft": "左对齐",
+ "alignCenter": "居中对齐",
+ "alignRight": "右对齐",
+ "label": "格式工具栏",
+ "text": "文本",
+ "heading1": "标题 1",
+ "heading2": "标题 2",
+ "heading3": "标题 3",
+ "heading4": "标题 4",
+ "heading5": "标题 5",
+ "heading6": "标题 6",
+ "bold": "粗体",
+ "italic": "斜体",
+ "strike": "删除线",
+ "inlineCode": "行内代码",
+ "bulletList": "项目符号列表",
+ "numberedList": "编号列表",
+ "quote": "引用",
+ "codeBlock": "代码块",
+ "divider": "分隔线",
+ "undo": "撤销",
+ "redo": "重做"
+ }
+}
diff --git a/apps/web/messages/zh-CN/issue.json b/apps/web/messages/zh-CN/issue.json
index 47241787..b3bcba45 100644
--- a/apps/web/messages/zh-CN/issue.json
+++ b/apps/web/messages/zh-CN/issue.json
@@ -345,6 +345,14 @@
"skipped": "已跳过"
}
},
+ "documents": {
+ "title": "Docs",
+ "add": "关联 Docs 页面",
+ "empty": "暂无关联的 Docs 页面。",
+ "loadFailed": "无法加载关联页面。点击重试。",
+ "remove": "取消关联 {title}",
+ "untitled": "无标题"
+ },
"archived": "已归档",
"activityHeading": "活动记录",
"feedFlat": "平铺",
@@ -376,7 +384,14 @@
},
"watchers": {
"watch": "关注",
- "unwatch": "取消关注"
+ "unwatch": "取消关注",
+ "manage": "管理关注者",
+ "search": "搜索项目成员…",
+ "empty": "未找到成员。",
+ "you": "{name}(你)",
+ "add": "将 {name} 添加为关注者",
+ "remove": "从关注者中移除 {name}",
+ "watchingCount": "{count} 位关注者"
},
"effects": {
"cleared": "已清除",
diff --git a/apps/web/messages/zh-CN/nav.json b/apps/web/messages/zh-CN/nav.json
index 41b520b6..e69bc89d 100644
--- a/apps/web/messages/zh-CN/nav.json
+++ b/apps/web/messages/zh-CN/nav.json
@@ -6,6 +6,7 @@
"initiatives": "计划",
"cycles": "周期",
"notes": "便签",
+ "documents": "Docs",
"aiTeam": "AI 团队",
"configure": "配置",
"aiAgents": "AI 代理",
diff --git a/apps/web/messages/zh-CN/newProject.json b/apps/web/messages/zh-CN/newProject.json
index 4000127a..5d1cbc09 100644
--- a/apps/web/messages/zh-CN/newProject.json
+++ b/apps/web/messages/zh-CN/newProject.json
@@ -26,7 +26,8 @@
"automation": "自动化",
"project": "项目",
"views": "视图",
- "aiTeam": "AI 团队"
+ "aiTeam": "AI 团队",
+ "knowledge": "知识"
},
"copyItems": {
"states": "状态",
@@ -35,6 +36,7 @@
"customFields": "自定义字段",
"views": "视图",
"dashboards": "仪表盘",
+ "documents": "Docs",
"actions": "操作",
"configuration": "配置",
"roles": "角色",
diff --git a/apps/web/messages/zh-CN/permissions.json b/apps/web/messages/zh-CN/permissions.json
index f3bbb131..0b09acf8 100644
--- a/apps/web/messages/zh-CN/permissions.json
+++ b/apps/web/messages/zh-CN/permissions.json
@@ -7,6 +7,7 @@
"initiatives": "计划",
"cycles": "周期",
"dashboards": "仪表盘",
+ "documents": "Docs",
"views": "工作项视图",
"members_invite": "邀请",
"members_manage": "成员",
@@ -34,6 +35,7 @@
"groups": {
"workItems": "工作项",
"dashboards": "仪表盘",
+ "documents": "Docs",
"notes": "便签",
"ai": "AI",
"configuration": "配置",
diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.json
index 530d1076..b2d08e1e 100644
--- a/apps/web/messages/zh-CN/settings.json
+++ b/apps/web/messages/zh-CN/settings.json
@@ -187,6 +187,7 @@
"actionsHint": "代理在项目中可以执行的操作",
"searchActions": "搜索操作",
"actionGroup": {
+ "documents": "Docs",
"issues": "任务",
"initiatives": "举措",
"cycles": "周期",
@@ -396,6 +397,7 @@
"features": "功能",
"featuresHint": "选择此项目显示的功能区。关闭功能只会隐藏入口,不会删除内容。",
"featureHints": {
+ "documents": "在 Docs 中组织共享项目文档。",
"dashboards": "在已保存的仪表盘中显示图表和指标。",
"initiatives": "将相关工作项作为同一计划跟踪。",
"cycles": "按固定时间段规划工作项。",
diff --git a/apps/web/package.json b/apps/web/package.json
index 1c951712..3cf870e8 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -35,7 +35,9 @@
"@tanstack/react-virtual": "^3.14.9",
"@tiptap/core": "^3.30.0",
"@tiptap/extension-code-block-lowlight": "^3.30.0",
+ "@tiptap/extension-color": "3.30.0",
"@tiptap/extension-hard-break": "^3.30.0",
+ "@tiptap/extension-highlight": "3.30.0",
"@tiptap/extension-image": "^3.30.0",
"@tiptap/extension-link": "^3.30.0",
"@tiptap/extension-placeholder": "^3.30.0",
@@ -43,6 +45,8 @@
"@tiptap/extension-task-item": "^3.30.0",
"@tiptap/extension-task-list": "^3.30.0",
"@tiptap/extension-text": "^3.30.0",
+ "@tiptap/extension-text-align": "3.30.0",
+ "@tiptap/extension-text-style": "3.30.0",
"@tiptap/pm": "^3.30.0",
"@tiptap/react": "^3.30.0",
"@tiptap/starter-kit": "^3.30.0",
@@ -57,6 +61,7 @@
"highlight.js": "~11.11.0",
"inter-ui": "^4.1.1",
"isomorphic-dompurify": "^3.22.0",
+ "jszip": "^3.10.1",
"lowlight": "^3.3.0",
"lucide-react": "^1.31.0",
"marked": "^18.0.9",
diff --git a/apps/web/src/app/project/[projectKey]/docs/[documentId]/page.tsx b/apps/web/src/app/project/[projectKey]/docs/[documentId]/page.tsx
new file mode 100644
index 00000000..1b7473a1
--- /dev/null
+++ b/apps/web/src/app/project/[projectKey]/docs/[documentId]/page.tsx
@@ -0,0 +1,10 @@
+import RequireFeature from '@/components/common/permissions/RequireFeature';
+import DocumentsPage from '@/features/documents/DocumentsPage';
+
+export default function Page() {
+ return (
+ <RequireFeature feature="documents">
+ <DocumentsPage />
+ </RequireFeature>
+ );
+}
diff --git a/apps/web/src/app/project/[projectKey]/docs/page.tsx b/apps/web/src/app/project/[projectKey]/docs/page.tsx
new file mode 100644
index 00000000..1b7473a1
--- /dev/null
+++ b/apps/web/src/app/project/[projectKey]/docs/page.tsx
@@ -0,0 +1,10 @@
+import RequireFeature from '@/components/common/permissions/RequireFeature';
+import DocumentsPage from '@/features/documents/DocumentsPage';
+
+export default function Page() {
+ return (
+ <RequireFeature feature="documents">
+ <DocumentsPage />
+ </RequireFeature>
+ );
+}
diff --git a/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.test.ts b/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.test.ts
new file mode 100644
index 00000000..b86b0a07
--- /dev/null
+++ b/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.test.ts
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict';
+import { afterEach, describe, it } from 'node:test';
+import { GET } from './route';
+
+const originalFetch = globalThis.fetch;
+const originalOrigin = process.env.SERVICE_URL_API;
+const params = Promise.resolve({
+ projectKey: 'SEKTA',
+ documentId: '42',
+ publicId: '123e4567-e89b-42d3-a456-426614174000',
+});
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+ if (originalOrigin === undefined) delete process.env.SERVICE_URL_API;
+ else process.env.SERVICE_URL_API = originalOrigin;
+});
+
+describe('protected document asset proxy', () => {
+ it('requires a session cookie before contacting the API', async () => {
+ let called = false;
+ globalThis.fetch = (async () => {
+ called = true;
+ return new Response();
+ }) as typeof fetch;
+ const response = await GET(new Request('https://plan.test/protected-media/example'), {
+ params,
+ });
+ assert.equal(response.status, 401);
+ assert.equal(called, false);
+ });
+
+ it('forwards only the session and cache validator to the exact asset endpoint', async () => {
+ process.env.SERVICE_URL_API = 'http://api:3000';
+ let capturedInput = '';
+ let capturedInit: RequestInit | undefined;
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ capturedInput = String(input);
+ capturedInit = init;
+ return new Response('image', {
+ headers: { 'content-type': 'image/png', etag: 'asset-v1', 'x-private': 'drop-me' },
+ });
+ }) as typeof fetch;
+ const response = await GET(
+ new Request('https://plan.test/protected-media/example', {
+ headers: { cookie: 'session=value', 'if-none-match': 'asset-v0', authorization: 'drop-me' },
+ }),
+ { params },
+ );
+ assert.equal(
+ capturedInput,
+ 'http://api:3000/projects/SEKTA/documents/42/assets/123e4567-e89b-42d3-a456-426614174000/raw',
+ );
+ assert.deepEqual(capturedInit?.headers, {
+ cookie: 'session=value',
+ 'if-none-match': 'asset-v0',
+ });
+ assert.equal(response.headers.get('content-type'), 'image/png');
+ assert.equal(response.headers.get('x-private'), null);
+ });
+});
diff --git a/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.ts b/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.ts
new file mode 100644
index 00000000..564aa2d7
--- /dev/null
+++ b/apps/web/src/app/protected-media/projects/[projectKey]/documents/[documentId]/assets/[publicId]/raw/route.ts
@@ -0,0 +1,71 @@
+import { serverRuntimeEnv } from '@/utils/runtimeEnv';
+
+// This route deliberately has a fixed shape. Unlike the public /media proxy it
+// forwards the session cookie, so accepting an arbitrary upstream path here would
+// turn the web application into an authenticated API proxy.
+const DOCUMENT_ID = /^[1-9]\d*$/;
+const PUBLIC_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+const PASSTHROUGH_HEADERS = [
+ 'content-type',
+ 'content-length',
+ 'content-disposition',
+ 'cache-control',
+ 'etag',
+ 'x-content-type-options',
+ 'content-security-policy',
+];
+
+type RouteParams = {
+ projectKey: string;
+ documentId: string;
+ publicId: string;
+};
+
+export async function GET(request: Request, { params }: { params: Promise<RouteParams> }) {
+ const { projectKey, documentId, publicId } = await params;
+ if (!validProjectKey(projectKey) || !DOCUMENT_ID.test(documentId) || !PUBLIC_ID.test(publicId)) {
+ return new Response(null, { status: 404 });
+ }
+
+ const cookie = request.headers.get('cookie');
+ if (!cookie) return new Response(null, { status: 401 });
+
+ const origin = process.env.SERVICE_URL_API || serverRuntimeEnv().apiUrl;
+ const upstream = await fetch(
+ `${origin}/projects/${encodeURIComponent(projectKey)}/documents/${documentId}/assets/${publicId}/raw`,
+ {
+ headers: forwardedHeaders(request, cookie),
+ cache: 'no-store',
+ redirect: 'error',
+ },
+ );
+
+ const headers = new Headers();
+ for (const name of PASSTHROUGH_HEADERS) {
+ const value = upstream.headers.get(name);
+ if (value) headers.set(name, value);
+ }
+ return new Response(upstream.body, { status: upstream.status, headers });
+}
+
+function validProjectKey(value: string): boolean {
+ const hasUnsafeCharacter = [...value].some((character) => {
+ const codePoint = character.codePointAt(0) ?? 0;
+ return character === '/' || codePoint <= 0x1f || codePoint === 0x7f;
+ });
+ return (
+ value.length > 0 &&
+ value.length <= 128 &&
+ value !== '.' &&
+ value !== '..' &&
+ !hasUnsafeCharacter
+ );
+}
+
+function forwardedHeaders(request: Request, cookie: string): HeadersInit {
+ const headers: Record<string, string> = { cookie };
+ const ifNoneMatch = request.headers.get('if-none-match');
+ if (ifNoneMatch) headers['if-none-match'] = ifNoneMatch;
+ return headers;
+}
diff --git a/apps/web/src/features/issue/components/editor/EditorResizableImage.tsx b/apps/web/src/components/common/editor/EditorResizableImage.tsx
similarity index 100%
rename from apps/web/src/features/issue/components/editor/EditorResizableImage.tsx
rename to apps/web/src/components/common/editor/EditorResizableImage.tsx
diff --git a/apps/web/src/features/issue/utils/tiptap-image.ts b/apps/web/src/components/common/editor/tiptap-image.ts
similarity index 97%
rename from apps/web/src/features/issue/utils/tiptap-image.ts
rename to apps/web/src/components/common/editor/tiptap-image.ts
index f9c3a68e..16c56e2e 100644
--- a/apps/web/src/features/issue/utils/tiptap-image.ts
+++ b/apps/web/src/components/common/editor/tiptap-image.ts
@@ -1,6 +1,6 @@
import Image from '@tiptap/extension-image';
import { ReactNodeViewRenderer } from '@tiptap/react';
-import EditorResizableImage from '../components/editor/EditorResizableImage';
+import EditorResizableImage from './EditorResizableImage';
// Safe inside a double-quoted HTML attribute: a filename may hold any of these.
const escapeAttribute = (value: string) =>
diff --git a/apps/web/src/features/issue/utils/tiptap-table.ts b/apps/web/src/components/common/editor/tiptap-table.ts
similarity index 100%
rename from apps/web/src/features/issue/utils/tiptap-table.ts
rename to apps/web/src/components/common/editor/tiptap-table.ts
diff --git a/apps/web/src/components/layout/CopyProjectOptions.tsx b/apps/web/src/components/layout/CopyProjectOptions.tsx
index 0e9530e4..a634d749 100644
--- a/apps/web/src/components/layout/CopyProjectOptions.tsx
+++ b/apps/web/src/components/layout/CopyProjectOptions.tsx
@@ -15,6 +15,7 @@ const REQUIRES: Record<CopyProjectIncludeKey, CopyProjectIncludeKey[]> = {
customFields: ['issueTypes'],
views: ['states', 'issueTypes', 'labels', 'customFields'],
dashboards: [],
+ documents: [],
actions: ['states', 'issueTypes', 'labels'],
configuration: [],
roles: [],
@@ -29,7 +30,7 @@ const REQUIRES: Record<CopyProjectIncludeKey, CopyProjectIncludeKey[]> = {
// The name of a group, and of each entity, are messages under `newProject`.
type Group = {
- title: 'workflow' | 'automation' | 'aiTeam' | 'project' | 'views';
+ title: 'workflow' | 'automation' | 'aiTeam' | 'project' | 'views' | 'knowledge';
keys: CopyProjectIncludeKey[];
};
@@ -47,6 +48,7 @@ const COLUMNS: Group[][] = [
[
{ title: 'project', keys: ['roles', 'notificationProviders'] },
{ title: 'views', keys: ['views', 'dashboards'] },
+ { title: 'knowledge', keys: ['documents'] },
],
];
diff --git a/apps/web/src/components/layout/SidebarWorkNav.tsx b/apps/web/src/components/layout/SidebarWorkNav.tsx
index 4684ff7a..005cee53 100644
--- a/apps/web/src/components/layout/SidebarWorkNav.tsx
+++ b/apps/web/src/components/layout/SidebarWorkNav.tsx
@@ -1,9 +1,18 @@
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';
-import { Inbox, LayoutDashboard, RefreshCw, SquareKanban, StickyNote, Target } from 'lucide-react';
+import {
+ BookOpenText,
+ Inbox,
+ LayoutDashboard,
+ RefreshCw,
+ SquareKanban,
+ StickyNote,
+ Target,
+} from 'lucide-react';
import {
cyclesPath,
dashboardsPath,
+ documentsPath,
inboxPath,
initiativesPath,
notesPath,
@@ -123,6 +132,15 @@ export default function SidebarWorkNav({
disabled={disabled}
/>
)}
+ {features.documents && can('documents', 'read') && (
+ <SidebarNavItem
+ href={projectKey ? documentsPath(projectKey) : '#'}
+ icon={BookOpenText}
+ label={t('documents')}
+ active={pathname.includes('/docs')}
+ disabled={disabled}
+ />
+ )}
{features.notes && can('note_boards', 'read') && (
<SidebarNavItem
href={projectKey ? notesPath(projectKey) : '#'}
diff --git a/apps/web/src/features/documents/DocumentsPage.tsx b/apps/web/src/features/documents/DocumentsPage.tsx
new file mode 100644
index 00000000..824d557e
--- /dev/null
+++ b/apps/web/src/features/documents/DocumentsPage.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import { useDeferredValue, useEffect, useState } from 'react';
+import { useParams, useRouter } from 'next/navigation';
+import { useShell } from '@/context/shellContext';
+import { usePermissions } from '@/hooks/usePermissions';
+import { useLiveRefresh } from '@/hooks/useLiveRefresh';
+import { revScope } from '@/utils/revScopes';
+import { qk } from '@/services/queryKeys';
+import { documentsPath, documentPath } from '@/utils/paths';
+import { Skeleton } from '@/components/ui/skeleton';
+import { ApiError } from '@/lib/api';
+import {
+ useCreateDocument,
+ useDeleteDocument,
+ useDuplicateDocument,
+ useDocumentQuery,
+ useDocumentsQuery,
+} from './services/documents.service';
+import DocumentEditor from './components/DocumentEditor';
+import DocumentLoadError from './components/DocumentLoadError';
+import DocumentLoadingState from './components/DocumentLoadingState';
+import DocumentsIndex from './components/DocumentsIndex';
+import { documentBelongsToTab, type DocumentListTab } from './utils/documentList';
+import { documentAncestors } from './utils/documentTree';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentsPage() {
+ const { project } = useShell();
+ const params = useParams<{ projectKey: string; documentId?: string }>();
+ const router = useRouter();
+ const t = useTranslations('documents');
+ const { can, isOwner } = usePermissions();
+ const projectKey = params.projectKey;
+ const routeId = params.documentId ? Number(params.documentId) : null;
+ const documentId = routeId && Number.isFinite(routeId) ? routeId : null;
+ const [search, setSearch] = useState('');
+ const [listTab, setListTab] = useState<DocumentListTab>('public');
+ const deferredSearch = useDeferredValue(search.trim());
+ const allDocumentsQuery = useDocumentsQuery(projectKey);
+ const allArchivedDocumentsQuery = useDocumentsQuery(projectKey, '', true);
+ const activeDocumentsQuery = useDocumentsQuery(projectKey, deferredSearch);
+ const archivedDocumentsQuery = useDocumentsQuery(projectKey, deferredSearch, true);
+ const visibleDocumentsQuery =
+ listTab === 'archived' ? archivedDocumentsQuery : activeDocumentsQuery;
+ const filteredDocuments = (visibleDocumentsQuery.data ?? []).filter((document) =>
+ documentBelongsToTab(document, listTab),
+ );
+ const visibleIds = new Set(filteredDocuments.map((document) => document.id));
+ const reorderSafe = filteredDocuments.every(
+ (document) => document.parentId === null || visibleIds.has(document.parentId),
+ );
+ const visibleDocuments = filteredDocuments.map((document) =>
+ document.parentId !== null && !visibleIds.has(document.parentId)
+ ? { ...document, parentId: null }
+ : document,
+ );
+ const documentQuery = useDocumentQuery(projectKey, documentId);
+ const createDocument = useCreateDocument(projectKey);
+ const deleteDocument = useDeleteDocument(projectKey);
+ const duplicateDocument = useDuplicateDocument(projectKey);
+ const canRead = can('documents', 'read');
+ const canCreate = can('documents', 'create');
+ const canEdit = can('documents', 'edit');
+ const canDelete = can('documents', 'delete');
+ const canReadWorkItems = can('work_items', 'read');
+ const canLinkWorkItems = canEdit && can('work_items', 'edit');
+
+ useLiveRefresh({
+ scope: project ? revScope.documents(project.project.id) : null,
+ targets: [
+ qk.documentListsForProject(projectKey),
+ ...(documentId === null
+ ? []
+ : [
+ qk.document(projectKey, documentId),
+ qk.documentRevisions(projectKey, documentId),
+ qk.documentAssets(projectKey, documentId),
+ qk.documentIssueLinks(projectKey, documentId),
+ ]),
+ ],
+ });
+
+ useEffect(() => {
+ if (documentQuery.error instanceof ApiError && documentQuery.error.status === 404) {
+ router.replace(documentsPath(projectKey));
+ }
+ }, [documentQuery.error, projectKey, router]);
+
+ if (!project) {
+ return (
+ <div className="flex flex-1 gap-0 overflow-hidden">
+ <Skeleton className="m-4 w-72" />
+ <Skeleton className="m-4 flex-1" />
+ </div>
+ );
+ }
+
+ if (!canRead) {
+ return (
+ <div className="flex flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">
+ {t('noAccess')}
+ </div>
+ );
+ }
+
+ const create = async (parentId: number | null, isPrivate = false) => {
+ try {
+ setSearch('');
+ const newDocument = await createDocument.mutateAsync({ parentId, isPrivate });
+ router.push(documentPath(projectKey, newDocument.id));
+ } catch {
+ // Mutation errors are reported by the shared query client.
+ }
+ };
+
+ const remove = async (version: number) => {
+ if (documentId === null) return;
+ await deleteDocument.mutateAsync({ documentId, version });
+ router.push(documentsPath(projectKey));
+ };
+
+ const duplicate = async (title: string, version: number) => {
+ if (!activeDocument) return;
+ try {
+ const copy = await duplicateDocument.mutateAsync({
+ documentId: activeDocument.id,
+ version,
+ title: t('copyTitle', { title: title.trim() || t('untitled') }),
+ parentId: activeDocument.parentId,
+ });
+ router.push(documentPath(projectKey, copy.id));
+ } catch {
+ // Mutation errors are reported by the shared query client.
+ }
+ };
+
+ const activeDocument = documentQuery.data;
+ const author = activeDocument?.updatedByUserId
+ ? project.assignees.find((candidate) => candidate.userId === activeDocument.updatedByUserId)
+ : null;
+ const ancestors = activeDocument
+ ? documentAncestors(activeDocument, [
+ ...(allDocumentsQuery.data ?? []),
+ ...(allArchivedDocumentsQuery.data ?? []),
+ ])
+ : [];
+ const detailFailed =
+ documentId !== null &&
+ documentQuery.isError &&
+ !(documentQuery.error instanceof ApiError && documentQuery.error.status === 404);
+
+ if (documentId === null) {
+ return (
+ <DocumentsIndex
+ projectKey={projectKey}
+ documents={visibleDocuments}
+ tab={listTab}
+ search={search}
+ searching={deferredSearch.length > 0}
+ loading={visibleDocumentsQuery.isLoading}
+ failed={visibleDocumentsQuery.isError}
+ canCreate={canCreate}
+ canEdit={canEdit}
+ authorNames={Object.fromEntries(
+ project.assignees.map((candidate) => [candidate.userId, candidate.name]),
+ )}
+ reorderSafe={reorderSafe}
+ creating={createDocument.isPending}
+ onSearchChange={setSearch}
+ onTabChange={setListTab}
+ onCreate={(parentId) => void create(parentId, listTab === 'private')}
+ onRetry={() => void visibleDocumentsQuery.refetch()}
+ />
+ );
+ }
+
+ if (detailFailed) return <DocumentLoadError onRetry={() => void documentQuery.refetch()} />;
+ if (!activeDocument) return <DocumentLoadingState />;
+
+ return (
+ <DocumentEditor
+ key={activeDocument.id}
+ projectKey={projectKey}
+ projectName={project.project.name}
+ document={activeDocument}
+ ancestors={ancestors}
+ authorName={author?.name ?? null}
+ authorNames={Object.fromEntries(
+ project.assignees.map((candidate) => [candidate.userId, candidate.name]),
+ )}
+ canEdit={canEdit}
+ canReadWorkItems={canReadWorkItems}
+ canLinkWorkItems={canLinkWorkItems}
+ isProjectOwner={isOwner}
+ canCreate={canCreate}
+ canDelete={canDelete}
+ onBack={() => router.push(documentsPath(projectKey))}
+ onCreateChild={() => void create(activeDocument.id, activeDocument.isPrivate)}
+ onDuplicate={duplicate}
+ onDelete={remove}
+ onReload={async () => {
+ const result = await documentQuery.refetch();
+ if (result.isError) throw result.error;
+ return result.data ?? null;
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentBlockTypeMenu.tsx b/apps/web/src/features/documents/components/DocumentBlockTypeMenu.tsx
new file mode 100644
index 00000000..ea1bd397
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentBlockTypeMenu.tsx
@@ -0,0 +1,78 @@
+'use client';
+
+import type { Editor } from '@tiptap/react';
+import { Check, ChevronDown, Pilcrow } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+
+const BLOCKS = [
+ { key: 'text', level: null, preview: 'Aa' },
+ { key: 'heading1', level: 1, preview: 'H1' },
+ { key: 'heading2', level: 2, preview: 'H2' },
+ { key: 'heading3', level: 3, preview: 'H3' },
+ { key: 'heading4', level: 4, preview: 'H4' },
+ { key: 'heading5', level: 5, preview: 'H5' },
+ { key: 'heading6', level: 6, preview: 'H6' },
+] as const;
+
+type Block = (typeof BLOCKS)[number];
+
+function activeBlock(editor: Editor): Block {
+ return (
+ BLOCKS.find(
+ (block) => block.level !== null && editor.isActive('heading', { level: block.level }),
+ ) ?? BLOCKS[0]
+ );
+}
+
+export default function DocumentBlockTypeMenu({ editor }: { editor: Editor }) {
+ const t = useTranslations('documents.toolbar');
+ const active = activeBlock(editor);
+
+ const select = (block: Block) => {
+ const chain = editor.chain().focus();
+ if (block.level === null) chain.setParagraph().run();
+ else chain.toggleHeading({ level: block.level }).run();
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-8 min-w-[7.75rem] justify-between gap-2 rounded-lg px-2.5 text-xs font-medium text-foreground hover:bg-muted data-[state=open]:bg-muted"
+ aria-label={t(active.key)}
+ >
+ <span className="flex min-w-0 items-center gap-2">
+ <Pilcrow className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t(active.key)}</span>
+ </span>
+ <ChevronDown className="size-3 shrink-0 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-56 p-1.5">
+ {BLOCKS.map((block) => (
+ <DropdownMenuItem
+ key={block.key}
+ className="h-9 gap-3 rounded-md px-2.5"
+ onSelect={() => select(block)}
+ >
+ <span className="w-7 shrink-0 font-mono text-[11px] font-semibold text-muted-foreground">
+ {block.preview}
+ </span>
+ <span className="flex-1">{t(block.key)}</span>
+ {active.key === block.key && <Check className="size-3.5 text-primary" />}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx b/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx
new file mode 100644
index 00000000..ac07b454
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx
@@ -0,0 +1,76 @@
+import { ChevronRight } from 'lucide-react';
+import Link from 'next/link';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { cn } from '@/lib/utils';
+import { documentPath, documentsPath } from '@/utils/paths';
+
+export default function DocumentBreadcrumbs({
+ projectKey,
+ projectName,
+ ancestors,
+ document,
+}: {
+ projectKey: string;
+ projectName: string;
+ ancestors: ProjectDocumentSummary[];
+ document: ProjectDocumentSummary;
+}) {
+ const t = useTranslations('documents');
+
+ return (
+ <nav
+ className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-[12px] text-muted-foreground"
+ aria-label={t('treeLabel')}
+ >
+ <span
+ className="hidden max-w-28 shrink-0 truncate font-medium lg:inline"
+ dir="auto"
+ title={projectName}
+ >
+ {projectName}
+ </span>
+ <ChevronRight className="hidden size-3 shrink-0 lg:block rtl:rotate-180" />
+ <Link
+ href={documentsPath(projectKey)}
+ className="shrink-0 rounded-sm px-1 py-0.5 font-medium transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ {t('title')}
+ </Link>
+
+ {ancestors.map((ancestor, index) => {
+ const nearest = index === ancestors.length - 1;
+ const ancestorTitle = ancestor.title.trim() || t('untitled');
+ return (
+ <span
+ key={ancestor.id}
+ className={cn(
+ 'min-w-0 items-center gap-1',
+ nearest ? 'hidden sm:flex' : 'hidden xl:flex',
+ )}
+ >
+ <ChevronRight className="size-3 shrink-0 rtl:rotate-180" />
+ <Link
+ href={documentPath(projectKey, ancestor.id)}
+ className="max-w-32 truncate rounded-sm px-1 py-0.5 transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ dir="auto"
+ title={ancestorTitle}
+ >
+ {ancestorTitle}
+ </Link>
+ </span>
+ );
+ })}
+
+ <ChevronRight className="size-3 shrink-0 rtl:rotate-180" />
+ <span
+ className="min-w-8 truncate rounded-sm px-1 py-0.5 font-medium text-foreground"
+ dir="auto"
+ title={document.title.trim() || t('untitled')}
+ aria-current="page"
+ >
+ {document.title.trim() || t('untitled')}
+ </span>
+ </nav>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentConflictBanner.tsx b/apps/web/src/features/documents/components/DocumentConflictBanner.tsx
new file mode 100644
index 00000000..c7bded29
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentConflictBanner.tsx
@@ -0,0 +1,20 @@
+import { RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentConflictBanner({ onReload }: { onReload: () => void }) {
+ const t = useTranslations('documents');
+
+ return (
+ <div
+ className="flex shrink-0 items-center justify-between gap-3 border-b border-amber-500/25 bg-amber-500/10 px-4 py-2 text-xs text-amber-800 dark:text-amber-200"
+ role="alert"
+ >
+ <span>{t('conflict')}</span>
+ <Button type="button" variant="ghost" size="sm" onClick={onReload}>
+ <RefreshCw />
+ {t('reviewConflict')}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentCopyLinkButton.tsx b/apps/web/src/features/documents/components/DocumentCopyLinkButton.tsx
new file mode 100644
index 00000000..983f11bb
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentCopyLinkButton.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import { Link2 } from 'lucide-react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentCopyLinkButton() {
+ const t = useTranslations('documents');
+
+ const copy = async () => {
+ await navigator.clipboard.writeText(window.location.href);
+ toast.success(t('linkCopied'));
+ };
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('copyLink')}
+ onClick={() => void copy()}
+ >
+ <Link2 />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t('copyLink')}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentDeleteDialog.tsx b/apps/web/src/features/documents/components/DocumentDeleteDialog.tsx
new file mode 100644
index 00000000..7fb427d0
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentDeleteDialog.tsx
@@ -0,0 +1,23 @@
+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentDeleteDialog({
+ onClose,
+ onDelete,
+}: {
+ onClose: () => void;
+ onDelete: () => Promise<void>;
+}) {
+ const t = useTranslations('documents');
+
+ return (
+ <ConfirmDialog
+ title={t('deleteTitle')}
+ confirmLabel={t('delete')}
+ onClose={onClose}
+ onConfirm={onDelete}
+ >
+ <p className="text-sm text-muted-foreground">{t('deleteDescription')}</p>
+ </ConfirmDialog>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentDiscardDraftDialog.tsx b/apps/web/src/features/documents/components/DocumentDiscardDraftDialog.tsx
new file mode 100644
index 00000000..565ed18e
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentDiscardDraftDialog.tsx
@@ -0,0 +1,23 @@
+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentDiscardDraftDialog({
+ onClose,
+ onDiscard,
+}: {
+ onClose: () => void;
+ onDiscard: () => Promise<void>;
+}) {
+ const t = useTranslations('documents');
+
+ return (
+ <ConfirmDialog
+ title={t('discardTitle')}
+ confirmLabel={t('discardAndReload')}
+ onClose={onClose}
+ onConfirm={onDiscard}
+ >
+ <p className="text-sm text-muted-foreground">{t('discardDescription')}</p>
+ </ConfirmDialog>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentEditor.tsx b/apps/web/src/features/documents/components/DocumentEditor.tsx
new file mode 100644
index 00000000..d362adae
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentEditor.tsx
@@ -0,0 +1,315 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import type { ProjectDocument, ProjectDocumentSummary } from '@/lib/api';
+import { useRelativeTime } from '@/context/relativeTimeContext';
+import { useSession } from '@/lib/auth-client';
+import { useTranslations } from 'next-intl';
+import { useDocumentDraft } from '../hooks/useDocumentDraft';
+import { useDocumentActionGate } from '../hooks/useDocumentActionGate';
+import { useDocumentEditorPreferences } from '../hooks/useDocumentEditorPreferences';
+import {
+ useArchiveDocument,
+ useRestoreDocument,
+ useSetDocumentAccess,
+ useSetDocumentFavorite,
+ useSetDocumentLocked,
+ useUploadDocumentAsset,
+ useUpdateDocument,
+} from '../services/documents.service';
+import DocumentConflictBanner from './DocumentConflictBanner';
+import DocumentDeleteDialog from './DocumentDeleteDialog';
+import DocumentDiscardDraftDialog from './DocumentDiscardDraftDialog';
+import DocumentEditorCanvas from './DocumentEditorCanvas';
+import DocumentEditorHeader from './DocumentEditorHeader';
+import DocumentEditorInspector from './DocumentEditorInspector';
+import DocumentHistoryDialog from './DocumentHistoryDialog';
+
+export default function DocumentEditor({
+ projectKey,
+ projectName,
+ document,
+ ancestors,
+ authorName,
+ authorNames,
+ canEdit,
+ canReadWorkItems,
+ canLinkWorkItems,
+ isProjectOwner,
+ canCreate,
+ canDelete,
+ onBack,
+ onCreateChild,
+ onDuplicate,
+ onDelete,
+ onReload,
+}: {
+ projectKey: string;
+ projectName: string;
+ document: ProjectDocument;
+ ancestors: ProjectDocumentSummary[];
+ authorName: string | null;
+ authorNames: Record<string, string>;
+ canEdit: boolean;
+ canReadWorkItems: boolean;
+ canLinkWorkItems: boolean;
+ isProjectOwner: boolean;
+ canCreate: boolean;
+ canDelete: boolean;
+ onBack: () => void;
+ onCreateChild: () => void;
+ onDuplicate: (title: string, version: number) => Promise<void>;
+ onDelete: (version: number) => Promise<void>;
+ onReload: () => Promise<ProjectDocument | null>;
+}) {
+ const t = useTranslations('documents');
+ const { data: session } = useSession();
+ const relativeTime = useRelativeTime();
+ const titleRef = useRef<HTMLTextAreaElement>(null);
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [discardOpen, setDiscardOpen] = useState(false);
+ const [historyOpen, setHistoryOpen] = useState(false);
+ const [inspectorOpen, setInspectorOpen] = useState(false);
+ const documentAction = useDocumentActionGate();
+ const currentUserId = session?.user.id ?? null;
+ const editable =
+ canEdit && currentUserId !== null && !document.isLocked && document.archivedAt === null;
+ const editorEditable = editable && !documentAction.pending;
+ const canManage =
+ canEdit && currentUserId !== null && (isProjectOwner || document.ownerUserId === currentUserId);
+ const canManageLifecycle =
+ canDelete &&
+ currentUserId !== null &&
+ (isProjectOwner || document.ownerUserId === currentUserId);
+ const { stickyToolbar, setStickyToolbar } = useDocumentEditorPreferences();
+ const updateDocument = useUpdateDocument(projectKey);
+ const setDocumentAccess = useSetDocumentAccess(projectKey);
+ const setDocumentLocked = useSetDocumentLocked(projectKey);
+ const archiveDocument = useArchiveDocument(projectKey);
+ const restoreDocument = useRestoreDocument(projectKey);
+ const setDocumentFavorite = useSetDocumentFavorite(projectKey);
+ const uploadDocumentAsset = useUploadDocumentAsset(projectKey, document.id);
+ const {
+ title,
+ content,
+ contentJson,
+ dirty,
+ saveState,
+ version,
+ editorRevision,
+ setTitle,
+ setContent,
+ save,
+ replaceWith,
+ adoptServerDocument,
+ } = useDocumentDraft({ projectKey, document, editable: editorEditable, userId: currentUserId });
+ const providerActionPending =
+ updateDocument.isPending ||
+ setDocumentAccess.isPending ||
+ setDocumentLocked.isPending ||
+ archiveDocument.isPending ||
+ restoreDocument.isPending ||
+ setDocumentFavorite.isPending;
+ const actionPending = documentAction.pending || providerActionPending;
+ const busy = actionPending || saveState === 'saving';
+
+ useEffect(() => {
+ const element = titleRef.current;
+ if (!element) return;
+ element.style.height = 'auto';
+ element.style.height = `${element.scrollHeight}px`;
+ }, [title]);
+
+ const reload = async () => {
+ const latest = await onReload();
+ if (latest) replaceWith(latest);
+ };
+
+ const prepareVersion = async () => {
+ if (providerActionPending || saveState === 'conflict' || saveState === 'error') return null;
+ const updatedDraft = await save();
+ if (dirty && !updatedDraft) return null;
+ return updatedDraft?.version ?? version;
+ };
+
+ const runVersioned = async (
+ action: (baseVersion: number) => Promise<ProjectDocument>,
+ replace = false,
+ ) =>
+ documentAction.run(async () => {
+ const baseVersion = await prepareVersion();
+ if (baseVersion === null) return null;
+ try {
+ const changed = await action(baseVersion);
+ if (replace) replaceWith(changed);
+ else adoptServerDocument(changed);
+ return changed;
+ } catch {
+ // The shared mutation error handler reports the failure. Keeping the
+ // current document intact lets the user retry without losing their draft.
+ return null;
+ }
+ });
+
+ const updateLabel = authorName
+ ? t('updatedBy', { name: authorName, time: relativeTime(document.updatedAt) })
+ : t('updated', { time: relativeTime(document.updatedAt) });
+
+ return (
+ <main className="relative flex min-w-0 flex-1 overflow-hidden bg-background">
+ <section className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ <DocumentEditorHeader
+ projectKey={projectKey}
+ projectName={projectName}
+ document={document}
+ ancestors={ancestors}
+ title={title}
+ content={content}
+ richHtml={editor?.getHTML() ?? ''}
+ saveState={saveState}
+ dirty={dirty}
+ stickyToolbar={stickyToolbar}
+ canCreate={canCreate}
+ canUpdate={editable}
+ canManage={canManage}
+ canManageLifecycle={canManageLifecycle}
+ canDelete={canManageLifecycle}
+ busy={busy}
+ onBack={onBack}
+ onRetrySave={() => void save()}
+ onFullWidthChange={(fullWidth) => {
+ void runVersioned((baseVersion) =>
+ updateDocument.mutateAsync({
+ documentId: document.id,
+ patch: { version: baseVersion, fullWidth },
+ }),
+ );
+ }}
+ onStickyToolbarChange={setStickyToolbar}
+ onCreateChild={onCreateChild}
+ onDuplicate={() => {
+ void documentAction.run(async () => {
+ const baseVersion = await prepareVersion();
+ if (baseVersion !== null) await onDuplicate(title, baseVersion);
+ });
+ }}
+ onFavoriteChange={(isFavorite) => {
+ void setDocumentFavorite
+ .mutateAsync({ documentId: document.id, isFavorite })
+ .catch(() => undefined);
+ }}
+ onLockChange={(locked) => {
+ void runVersioned((baseVersion) =>
+ setDocumentLocked.mutateAsync({
+ documentId: document.id,
+ version: baseVersion,
+ locked,
+ }),
+ );
+ }}
+ onPrivacyChange={(isPrivate) => {
+ void runVersioned((baseVersion) =>
+ setDocumentAccess.mutateAsync({
+ documentId: document.id,
+ version: baseVersion,
+ isPrivate,
+ }),
+ );
+ }}
+ onArchive={() => {
+ void runVersioned((baseVersion) =>
+ archiveDocument.mutateAsync({ documentId: document.id, version: baseVersion }),
+ ).then((changed) => {
+ if (changed) onBack();
+ });
+ }}
+ onRestore={() => {
+ void runVersioned((baseVersion) =>
+ restoreDocument.mutateAsync({ documentId: document.id, version: baseVersion }),
+ );
+ }}
+ onDelete={() => setDeleteOpen(true)}
+ inspectorOpen={inspectorOpen}
+ onInspectorOpenChange={setInspectorOpen}
+ onOpenHistory={() => setHistoryOpen(true)}
+ />
+
+ {saveState === 'conflict' && (
+ <DocumentConflictBanner onReload={() => setDiscardOpen(true)} />
+ )}
+ <DocumentEditorCanvas
+ projectKey={projectKey}
+ document={document}
+ title={title}
+ content={content}
+ contentJson={contentJson}
+ editorRevision={editorRevision}
+ editor={editor}
+ titleRef={titleRef}
+ editable={editorEditable}
+ stickyToolbar={stickyToolbar}
+ updateLabel={updateLabel}
+ onEditorReady={setEditor}
+ onTitleChange={setTitle}
+ onTitleSave={() => void save()}
+ onIconChange={(icon) => {
+ void runVersioned((baseVersion) =>
+ updateDocument.mutateAsync({
+ documentId: document.id,
+ patch: { version: baseVersion, icon },
+ }),
+ );
+ }}
+ onContentChange={({ markdown, json }) => setContent(markdown, json)}
+ onContentBlur={() => void save()}
+ onUploadImage={(file) => uploadDocumentAsset.mutateAsync(file)}
+ />
+ </section>
+
+ <DocumentEditorInspector
+ open={inspectorOpen}
+ projectKey={projectKey}
+ document={{ ...document, title, content, contentJson, version }}
+ editor={editor}
+ authorNames={authorNames}
+ canUpload={editorEditable}
+ canDeleteAssets={canManageLifecycle && editorEditable}
+ canReadWorkItems={canReadWorkItems}
+ canLinkWorkItems={canLinkWorkItems && document.archivedAt === null}
+ onOpenChange={setInspectorOpen}
+ onOpenHistory={() => setHistoryOpen(true)}
+ />
+
+ {deleteOpen && (
+ <DocumentDeleteDialog
+ onClose={() => setDeleteOpen(false)}
+ onDelete={async () => {
+ await onDelete(version);
+ setDeleteOpen(false);
+ }}
+ />
+ )}
+ {discardOpen && (
+ <DocumentDiscardDraftDialog
+ onClose={() => setDiscardOpen(false)}
+ onDiscard={async () => {
+ await reload();
+ setDiscardOpen(false);
+ }}
+ />
+ )}
+ <DocumentHistoryDialog
+ open={historyOpen}
+ projectKey={projectKey}
+ documentId={document.id}
+ version={version}
+ authorNames={authorNames}
+ canRestore={editorEditable && !dirty && !busy}
+ onOpenChange={setHistoryOpen}
+ onRestored={(changed) => replaceWith(changed)}
+ />
+ </main>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentEditorCanvas.test.ts b/apps/web/src/features/documents/components/DocumentEditorCanvas.test.ts
new file mode 100644
index 00000000..4105181a
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentEditorCanvas.test.ts
@@ -0,0 +1,13 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { documentToolbarPosition } from './DocumentEditorCanvas';
+
+describe('DocumentEditorCanvas toolbar position', () => {
+ it('pins the toolbar inside the editor scroll container', () => {
+ assert.equal(documentToolbarPosition(true), 'sticky top-0');
+ });
+
+ it('keeps the toolbar in the document flow when disabled', () => {
+ assert.equal(documentToolbarPosition(false), 'relative');
+ });
+});
diff --git a/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx b/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx
new file mode 100644
index 00000000..2ca12dc1
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx
@@ -0,0 +1,142 @@
+'use client';
+
+import { useRef, type RefObject } from 'react';
+import type { Editor } from '@tiptap/react';
+import type { ProjectDocument } from '@/lib/api';
+import { cn } from '@/lib/utils';
+import { useTranslations } from 'next-intl';
+import DocumentMarkdownEditor, { insertDocumentImage } from './DocumentMarkdownEditor';
+import DocumentPageTitle from './DocumentPageTitle';
+import DocumentToolbar from './DocumentToolbar';
+
+export function documentToolbarPosition(stickyToolbar: boolean) {
+ return stickyToolbar ? 'sticky top-0' : 'relative';
+}
+
+export default function DocumentEditorCanvas({
+ projectKey,
+ document,
+ title,
+ content,
+ contentJson,
+ editorRevision,
+ editor,
+ titleRef,
+ editable,
+ stickyToolbar,
+ updateLabel,
+ onEditorReady,
+ onTitleChange,
+ onTitleSave,
+ onIconChange,
+ onContentChange,
+ onContentBlur,
+ onUploadImage,
+}: {
+ projectKey: string;
+ document: ProjectDocument;
+ title: string;
+ content: string;
+ contentJson: ProjectDocument['contentJson'];
+ editorRevision: number;
+ editor: Editor | null;
+ titleRef: RefObject<HTMLTextAreaElement | null>;
+ editable: boolean;
+ stickyToolbar: boolean;
+ updateLabel: string;
+ onEditorReady: (editor: Editor | null) => void;
+ onTitleChange: (title: string) => void;
+ onTitleSave: () => void;
+ onIconChange: (icon: string | null) => void;
+ onContentChange: (value: {
+ markdown: string;
+ json: NonNullable<ProjectDocument['contentJson']>;
+ }) => void;
+ onContentBlur: () => void;
+ onUploadImage: (file: File) => Promise<{ url: string; filename: string }>;
+}) {
+ const t = useTranslations('documents');
+ const imageInput = useRef<HTMLInputElement>(null);
+ const editableRef = useRef(editable);
+ editableRef.current = editable;
+
+ const toolbar = editable ? (
+ <div
+ className={cn(
+ 'z-10 border-b bg-background/92 px-3 py-1.5 backdrop-blur-xl supports-[backdrop-filter]:bg-background/78 md:px-5',
+ documentToolbarPosition(stickyToolbar),
+ )}
+ >
+ <div className="mx-auto w-full max-w-[920px]">
+ <DocumentToolbar
+ editor={editor}
+ projectKey={projectKey}
+ documentId={document.id}
+ canUpload={editable}
+ />
+ </div>
+ </div>
+ ) : null;
+
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain scroll-smooth">
+ {stickyToolbar && toolbar}
+ <article
+ className={cn(
+ 'mx-auto flex min-h-full w-full max-w-[860px] animate-in flex-col px-5 pt-10 pb-24 duration-300 fade-in slide-in-from-bottom-1 sm:px-8 md:pt-14 lg:px-14',
+ document.fullWidth && 'max-w-[1280px] lg:px-20',
+ )}
+ >
+ {!stickyToolbar && <div className="-mx-3 mb-8 sm:-mx-5">{toolbar}</div>}
+ {editable && (
+ <input
+ ref={imageInput}
+ className="sr-only"
+ type="file"
+ accept="image/*"
+ aria-label={t('toolbar.uploadImage')}
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.currentTarget.value = '';
+ if (!file) return;
+ void onUploadImage(file)
+ .then((asset) => {
+ insertDocumentImage(editor, editableRef.current, asset.url, asset.filename);
+ })
+ .catch(() => undefined);
+ }}
+ />
+ )}
+
+ <header className="mb-9 border-b border-border/55 pb-8">
+ <DocumentPageTitle
+ ref={titleRef}
+ title={title}
+ icon={document.icon}
+ editable={editable}
+ onChange={onTitleChange}
+ onSave={onTitleSave}
+ onIconChange={onIconChange}
+ />
+ <p className="mt-3 text-xs text-muted-foreground/80" dir="auto">
+ {updateLabel}
+ </p>
+ </header>
+
+ <DocumentMarkdownEditor
+ key={`${document.id}:${editorRevision}`}
+ defaultValue={content}
+ defaultJson={contentJson}
+ editable={editable}
+ placeholder={t('contentPlaceholder')}
+ className="min-h-[58vh] flex-1 text-[15px] leading-7 md:text-base md:leading-7"
+ onReady={onEditorReady}
+ onChange={onContentChange}
+ onBlur={onContentBlur}
+ onPickImage={editable ? () => imageInput.current?.click() : undefined}
+ onUploadImage={editable ? onUploadImage : undefined}
+ />
+ </article>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentEditorHeader.tsx b/apps/web/src/features/documents/components/DocumentEditorHeader.tsx
new file mode 100644
index 00000000..0844cce2
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentEditorHeader.tsx
@@ -0,0 +1,203 @@
+import { ArrowLeft, Check, CircleAlert, LoaderCircle, PanelRight, RefreshCw } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocument, ProjectDocumentSummary } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import type { DocumentSaveState } from '../hooks/useDocumentDraft';
+import DocumentBreadcrumbs from './DocumentBreadcrumbs';
+import DocumentCopyLinkButton from './DocumentCopyLinkButton';
+import DocumentFavoriteButton from './DocumentFavoriteButton';
+import DocumentLockButton from './DocumentLockButton';
+import DocumentOptionsMenu from './DocumentOptionsMenu';
+
+export default function DocumentEditorHeader({
+ projectKey,
+ projectName,
+ document,
+ ancestors,
+ title,
+ content,
+ richHtml,
+ saveState,
+ dirty,
+ stickyToolbar,
+ canCreate,
+ canUpdate,
+ canManage,
+ canManageLifecycle,
+ canDelete,
+ busy,
+ onBack,
+ onRetrySave,
+ onFullWidthChange,
+ onStickyToolbarChange,
+ onCreateChild,
+ onDuplicate,
+ onFavoriteChange,
+ onLockChange,
+ onPrivacyChange,
+ onArchive,
+ onRestore,
+ onDelete,
+ inspectorOpen,
+ onInspectorOpenChange,
+ onOpenHistory,
+}: {
+ projectKey: string;
+ projectName: string;
+ document: ProjectDocument;
+ ancestors: ProjectDocumentSummary[];
+ title: string;
+ content: string;
+ richHtml: string;
+ saveState: DocumentSaveState;
+ dirty: boolean;
+ stickyToolbar: boolean;
+ canCreate: boolean;
+ canUpdate: boolean;
+ canManage: boolean;
+ canManageLifecycle: boolean;
+ canDelete: boolean;
+ busy: boolean;
+ onBack: () => void;
+ onRetrySave: () => void;
+ onFullWidthChange: (value: boolean) => void;
+ onStickyToolbarChange: (value: boolean) => void;
+ onCreateChild: () => void;
+ onDuplicate: () => void;
+ onFavoriteChange: (favorite: boolean) => void;
+ onLockChange: (locked: boolean) => void;
+ onPrivacyChange: (isPrivate: boolean) => void;
+ onArchive: () => void;
+ onRestore: () => void;
+ onDelete: () => void;
+ inspectorOpen: boolean;
+ onInspectorOpenChange: (open: boolean) => void;
+ onOpenHistory: () => void;
+}) {
+ const t = useTranslations('documents');
+ const readOnlyReason =
+ document.archivedAt !== null
+ ? t('archivedReadOnly')
+ : document.isLocked
+ ? t('lockedReadOnly')
+ : null;
+ const statusText = readOnlyReason
+ ? readOnlyReason
+ : saveState === 'conflict'
+ ? t('conflict')
+ : saveState === 'error'
+ ? t('saveFailed')
+ : saveState === 'saving' || dirty
+ ? t('saving')
+ : t('saved');
+ const statusTone =
+ saveState === 'error'
+ ? 'text-destructive'
+ : saveState === 'conflict'
+ ? 'text-amber-600 dark:text-amber-400'
+ : 'text-muted-foreground';
+
+ return (
+ <header className="flex h-12 shrink-0 items-center gap-2 border-b bg-background/90 px-2.5 backdrop-blur-md md:px-4">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="shrink-0 md:hidden"
+ aria-label={t('backToDocuments')}
+ onClick={onBack}
+ >
+ <ArrowLeft className="rtl:rotate-180" />
+ </Button>
+
+ <DocumentBreadcrumbs
+ projectKey={projectKey}
+ projectName={projectName}
+ ancestors={ancestors}
+ document={document}
+ />
+
+ <div className="ms-auto flex shrink-0 items-center gap-0.5">
+ <div
+ className={cn(
+ 'me-1 flex h-7 items-center gap-1.5 px-1 text-[11px] tabular-nums',
+ statusTone,
+ )}
+ role="status"
+ aria-live="polite"
+ title={statusText}
+ >
+ {saveState === 'error' || saveState === 'conflict' ? (
+ <CircleAlert className="size-3" />
+ ) : !readOnlyReason && (saveState === 'saving' || dirty) ? (
+ <LoaderCircle className="size-3 animate-spin" />
+ ) : (
+ <Check className="size-3" />
+ )}
+ <span className="hidden lg:inline">{statusText}</span>
+ </div>
+
+ {saveState === 'error' && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('retrySave')}
+ title={t('retrySave')}
+ onClick={onRetrySave}
+ >
+ <RefreshCw />
+ </Button>
+ )}
+
+ <DocumentFavoriteButton
+ favorite={document.isFavorite}
+ disabled={busy}
+ onChange={onFavoriteChange}
+ />
+ <DocumentLockButton
+ locked={document.isLocked}
+ disabled={!canManage || document.archivedAt !== null || busy}
+ onChange={onLockChange}
+ />
+ <DocumentCopyLinkButton />
+ <div className="mx-1 hidden h-4 w-px bg-border sm:block" aria-hidden />
+ <Button
+ type="button"
+ variant={inspectorOpen ? 'secondary' : 'ghost'}
+ size="icon-sm"
+ aria-label={inspectorOpen ? t('closeDetails') : t('openDetails')}
+ aria-pressed={inspectorOpen}
+ title={inspectorOpen ? t('closeDetails') : t('openDetails')}
+ onClick={() => onInspectorOpenChange(!inspectorOpen)}
+ >
+ <PanelRight />
+ </Button>
+ <DocumentOptionsMenu
+ projectKey={projectKey}
+ document={document}
+ title={title}
+ content={content}
+ richHtml={richHtml}
+ stickyToolbar={stickyToolbar}
+ canCreate={canCreate}
+ canUpdate={canUpdate}
+ canManage={canManage}
+ canManageLifecycle={canManageLifecycle}
+ canDelete={canDelete}
+ busy={busy}
+ onFullWidthChange={onFullWidthChange}
+ onStickyToolbarChange={onStickyToolbarChange}
+ onPrivacyChange={onPrivacyChange}
+ onCreateChild={onCreateChild}
+ onDuplicate={onDuplicate}
+ onArchive={onArchive}
+ onRestore={onRestore}
+ onDelete={onDelete}
+ onOpenHistory={onOpenHistory}
+ />
+ </div>
+ </header>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentEditorInspector.tsx b/apps/web/src/features/documents/components/DocumentEditorInspector.tsx
new file mode 100644
index 00000000..7846c6ac
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentEditorInspector.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import type { Editor } from '@tiptap/react';
+import type { ProjectDocument } from '@/lib/api';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { useIsMobile } from '@/hooks/use-mobile';
+import { useLocale, useTranslations } from 'next-intl';
+import DocumentSidePanel from './DocumentSidePanel';
+
+export default function DocumentEditorInspector({
+ open,
+ projectKey,
+ document,
+ editor,
+ authorNames,
+ canUpload,
+ canDeleteAssets,
+ canReadWorkItems,
+ canLinkWorkItems,
+ onOpenChange,
+ onOpenHistory,
+}: {
+ open: boolean;
+ projectKey: string;
+ document: ProjectDocument;
+ editor: Editor | null;
+ authorNames: Record<string, string>;
+ canUpload: boolean;
+ canDeleteAssets: boolean;
+ canReadWorkItems: boolean;
+ canLinkWorkItems: boolean;
+ onOpenChange: (open: boolean) => void;
+ onOpenHistory: () => void;
+}) {
+ const t = useTranslations('documents');
+ const locale = useLocale();
+ const isMobile = useIsMobile();
+
+ if (!open) return null;
+
+ const panel = (
+ <DocumentSidePanel
+ projectKey={projectKey}
+ document={document}
+ editor={editor}
+ authorNames={authorNames}
+ canUpload={canUpload}
+ canDeleteAssets={canDeleteAssets}
+ canReadWorkItems={canReadWorkItems}
+ canLinkWorkItems={canLinkWorkItems}
+ onOpenHistory={onOpenHistory}
+ />
+ );
+
+ if (isMobile) {
+ return (
+ <Sheet open onOpenChange={onOpenChange}>
+ <SheetContent
+ side={locale === 'ar' ? 'left' : 'right'}
+ className="w-[min(94vw,380px)] gap-0 sm:max-w-[380px]"
+ >
+ <SheetHeader className="shrink-0 border-b pe-12">
+ <SheetTitle>{t('details')}</SheetTitle>
+ <SheetDescription className="sr-only">{t('detailsDescription')}</SheetDescription>
+ </SheetHeader>
+ {panel}
+ </SheetContent>
+ </Sheet>
+ );
+ }
+
+ return (
+ <aside
+ className="flex w-[21rem] shrink-0 animate-in flex-col border-s bg-muted/10 duration-200 slide-in-from-right"
+ aria-label={t('details')}
+ >
+ {panel}
+ </aside>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentExportDialog.tsx b/apps/web/src/features/documents/components/DocumentExportDialog.tsx
new file mode 100644
index 00000000..8837871c
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentExportDialog.tsx
@@ -0,0 +1,184 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { Check, Download, FileCode2, FileText, Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { cn } from '@/lib/utils';
+import { useTranslations } from 'next-intl';
+import {
+ createPortableDocumentExport,
+ DocumentExportLimitError,
+ type DocumentExportFormat,
+} from '../utils/documentExport';
+
+const formats = [
+ { key: 'markdown', icon: FileText },
+ { key: 'html', icon: FileCode2 },
+] as const;
+
+export default function DocumentExportDialog({
+ open,
+ projectKey,
+ documentId,
+ title,
+ content,
+ richHtml,
+ onOpenChange,
+}: {
+ open: boolean;
+ projectKey: string;
+ documentId: number;
+ title: string;
+ content: string;
+ richHtml: string;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations('documents');
+ const [format, setFormat] = useState<DocumentExportFormat>('markdown');
+ const [pending, setPending] = useState(false);
+ const [failure, setFailure] = useState<'generic' | 'limit' | null>(null);
+ const downloadLock = useRef(false);
+
+ useEffect(() => {
+ if (open) setFailure(null);
+ }, [open]);
+
+ const changeOpen = (nextOpen: boolean) => {
+ if (downloadLock.current) return;
+ onOpenChange(nextOpen);
+ };
+
+ const download = async () => {
+ if (downloadLock.current) return;
+ downloadLock.current = true;
+ setPending(true);
+ setFailure(null);
+
+ try {
+ const result = await createPortableDocumentExport({
+ title,
+ content,
+ richHtml,
+ format,
+ projectKey,
+ documentId,
+ baseUrl: window.location.origin,
+ });
+ const url = URL.createObjectURL(result.blob);
+ const anchor = window.document.createElement('a');
+ anchor.href = url;
+ anchor.download = result.filename;
+ anchor.hidden = true;
+ try {
+ window.document.body.append(anchor);
+ anchor.click();
+ } finally {
+ anchor.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+ onOpenChange(false);
+ } catch (error) {
+ setFailure(error instanceof DocumentExportLimitError ? 'limit' : 'generic');
+ } finally {
+ downloadLock.current = false;
+ setPending(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={changeOpen}>
+ <DialogContent
+ className="sm:max-w-lg"
+ showCloseButton={!pending}
+ aria-busy={pending}
+ onEscapeKeyDown={(event) => {
+ if (pending) event.preventDefault();
+ }}
+ onPointerDownOutside={(event) => {
+ if (pending) event.preventDefault();
+ }}
+ >
+ <DialogHeader className="text-start">
+ <DialogTitle>{t('exportTitle')}</DialogTitle>
+ <DialogDescription>{t('exportDescription')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="grid gap-2" role="radiogroup" aria-label={t('exportFormat')}>
+ {formats.map(({ key, icon: Icon }) => {
+ const selected = format === key;
+ return (
+ <button
+ key={key}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={pending}
+ className={cn(
+ 'group flex min-h-16 items-center gap-3 rounded-lg border px-3 text-start transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',
+ selected ? 'border-foreground/25 bg-muted/50' : 'hover:bg-muted/30',
+ )}
+ onClick={() => {
+ setFormat(key);
+ setFailure(null);
+ }}
+ >
+ <span className="grid size-9 shrink-0 place-items-center rounded-md bg-background shadow-xs ring-1 ring-border">
+ <Icon className="size-4 text-muted-foreground" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium">{t(key)}</span>
+ {key === 'markdown' && (
+ <span className="mt-0.5 block text-xs leading-4 text-muted-foreground">
+ {t('markdownExportHint')}
+ </span>
+ )}
+ </span>
+ <span
+ className={cn(
+ 'grid size-5 shrink-0 place-items-center rounded-full border',
+ selected && 'border-primary bg-primary text-primary-foreground',
+ )}
+ aria-hidden
+ >
+ {selected && <Check className="size-3" />}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+
+ {failure && (
+ <p
+ className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive"
+ role="alert"
+ >
+ {t(failure === 'limit' ? 'exportTooLarge' : 'exportFailed')}
+ </p>
+ )}
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={pending}
+ onClick={() => changeOpen(false)}
+ >
+ {t('cancel')}
+ </Button>
+ <Button type="button" disabled={pending} onClick={() => void download()}>
+ {pending ? <Loader2 className="animate-spin" /> : <Download />}
+ {pending ? t('exporting') : t('download')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentFavoriteButton.tsx b/apps/web/src/features/documents/components/DocumentFavoriteButton.tsx
new file mode 100644
index 00000000..7f75f2a2
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentFavoriteButton.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { Star } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+
+export default function DocumentFavoriteButton({
+ favorite,
+ disabled,
+ onChange,
+}: {
+ favorite: boolean;
+ disabled: boolean;
+ onChange: (favorite: boolean) => void;
+}) {
+ const t = useTranslations('documents');
+ const label = favorite ? t('removeFavorite') : t('addFavorite');
+
+ return (
+ <Button
+ type="button"
+ variant={favorite ? 'secondary' : 'ghost'}
+ size="icon-sm"
+ disabled={disabled}
+ className={cn(
+ favorite && 'bg-amber-500/10 text-amber-600 hover:bg-amber-500/15 dark:text-amber-400',
+ )}
+ aria-label={label}
+ aria-pressed={favorite}
+ title={label}
+ onClick={() => onChange(!favorite)}
+ >
+ <Star className={cn(favorite && 'fill-current')} />
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentHistoryDialog.test.ts b/apps/web/src/features/documents/components/DocumentHistoryDialog.test.ts
new file mode 100644
index 00000000..b9c59241
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentHistoryDialog.test.ts
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import {
+ canApplyDocumentHistoryRestore,
+ canInteractWithDocumentHistory,
+} from './DocumentHistoryDialog';
+
+describe('DocumentHistoryDialog restore guard', () => {
+ it('allows interaction only when no restore owns the dialog', () => {
+ assert.equal(canInteractWithDocumentHistory(null), true);
+ assert.equal(canInteractWithDocumentHistory(0), false);
+ assert.equal(canInteractWithDocumentHistory(42), false);
+ });
+
+ it('accepts the active restore while the dialog is mounted and open', () => {
+ assert.equal(
+ canApplyDocumentHistoryRestore({
+ attempt: 2,
+ currentAttempt: 2,
+ open: true,
+ mounted: true,
+ }),
+ true,
+ );
+ });
+
+ it('rejects restore results after the dialog closes', () => {
+ assert.equal(
+ canApplyDocumentHistoryRestore({
+ attempt: 2,
+ currentAttempt: 2,
+ open: false,
+ mounted: true,
+ }),
+ false,
+ );
+ });
+
+ it('rejects an older result after a new attempt starts', () => {
+ assert.equal(
+ canApplyDocumentHistoryRestore({
+ attempt: 2,
+ currentAttempt: 3,
+ open: true,
+ mounted: true,
+ }),
+ false,
+ );
+ });
+
+ it('rejects restore results after unmount', () => {
+ assert.equal(
+ canApplyDocumentHistoryRestore({
+ attempt: 2,
+ currentAttempt: 2,
+ open: true,
+ mounted: false,
+ }),
+ false,
+ );
+ });
+});
diff --git a/apps/web/src/features/documents/components/DocumentHistoryDialog.tsx b/apps/web/src/features/documents/components/DocumentHistoryDialog.tsx
new file mode 100644
index 00000000..52735604
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentHistoryDialog.tsx
@@ -0,0 +1,338 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { Check, History, Loader2, RefreshCw, RotateCcw } from 'lucide-react';
+import { api, type ProjectDocument } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useRelativeTime } from '@/context/relativeTimeContext';
+import { cn } from '@/lib/utils';
+import { useTranslations } from 'next-intl';
+import {
+ useDocumentRevisionsQuery,
+ useRestoreDocumentRevision,
+} from '../services/documents.service';
+import DocumentMarkdownEditor from './DocumentMarkdownEditor';
+
+const noop = () => undefined;
+
+export default function DocumentHistoryDialog({
+ open,
+ projectKey,
+ documentId,
+ version,
+ authorNames,
+ canRestore,
+ onOpenChange,
+ onRestored,
+}: {
+ open: boolean;
+ projectKey: string;
+ documentId: number;
+ version: number;
+ authorNames: Record<string, string>;
+ canRestore: boolean;
+ onOpenChange: (open: boolean) => void;
+ onRestored: (document: ProjectDocument) => void;
+}) {
+ const t = useTranslations('documents');
+ const relativeTime = useRelativeTime();
+ const revisions = useDocumentRevisionsQuery(projectKey, documentId, open);
+ const restore = useRestoreDocumentRevision(projectKey);
+ const [selectedRevisionId, setSelectedRevisionId] = useState<number | null>(null);
+ const [restoringRevisionId, setRestoringRevisionId] = useState<number | null>(null);
+ const [restoreFailed, setRestoreFailed] = useState(false);
+ const mountedRef = useRef(false);
+ const openRef = useRef(open);
+ const restoreLockRef = useRef(false);
+ const restoreAttemptRef = useRef(0);
+ openRef.current = open;
+
+ const canInteract = canInteractWithDocumentHistory(restoringRevisionId);
+ const selectedRevision = useQuery({
+ queryKey: ['documents', projectKey, 'document', documentId, 'revision', selectedRevisionId],
+ queryFn: () => api.getDocumentRevision(projectKey, documentId, selectedRevisionId!),
+ enabled: open && selectedRevisionId !== null,
+ });
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ restoreAttemptRef.current += 1;
+ };
+ }, []);
+
+ useEffect(() => {
+ restoreAttemptRef.current += 1;
+ setSelectedRevisionId(null);
+ setRestoreFailed(false);
+ }, [documentId]);
+
+ useEffect(() => {
+ if (!open) {
+ restoreAttemptRef.current += 1;
+ setSelectedRevisionId(null);
+ setRestoreFailed(false);
+ return;
+ }
+
+ const selectionExists = revisions.data?.some((item) => item.id === selectedRevisionId);
+ if (!selectionExists) setSelectedRevisionId(revisions.data?.[0]?.id ?? null);
+ }, [open, revisions.data, selectedRevisionId]);
+
+ const restoreRevision = async (revisionId: number) => {
+ if (restoreLockRef.current) return;
+ restoreLockRef.current = true;
+ const attempt = ++restoreAttemptRef.current;
+ setRestoringRevisionId(revisionId);
+ setRestoreFailed(false);
+
+ try {
+ const updated = await restore.mutateAsync({ documentId, revisionId, version });
+ if (
+ canApplyDocumentHistoryRestore({
+ attempt,
+ currentAttempt: restoreAttemptRef.current,
+ open: openRef.current,
+ mounted: mountedRef.current,
+ })
+ ) {
+ onRestored(updated);
+ onOpenChange(false);
+ }
+ } catch {
+ if (mountedRef.current && openRef.current && attempt === restoreAttemptRef.current) {
+ setRestoreFailed(true);
+ }
+ } finally {
+ restoreLockRef.current = false;
+ if (mountedRef.current) setRestoringRevisionId(null);
+ }
+ };
+
+ const changeOpen = (nextOpen: boolean) => {
+ if (!nextOpen && !canInteractWithDocumentHistory(restoringRevisionId)) return;
+ onOpenChange(nextOpen);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={changeOpen}>
+ <DialogContent
+ className="max-h-[min(86vh,760px)] overflow-hidden p-0 sm:max-w-5xl"
+ showCloseButton={canInteract}
+ aria-busy={!canInteract}
+ onEscapeKeyDown={(event) => {
+ if (!canInteract) event.preventDefault();
+ }}
+ onPointerDownOutside={(event) => {
+ if (!canInteract) event.preventDefault();
+ }}
+ >
+ <DialogHeader className="border-b px-5 py-4 pe-12 text-start">
+ <DialogTitle className="flex items-center gap-2">
+ <History className="size-4 text-muted-foreground" />
+ {t('versionHistory')}
+ </DialogTitle>
+ <DialogDescription>{t('versionHistoryDescription')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="grid min-h-72 overflow-hidden md:grid-cols-[19rem_minmax(0,1fr)]">
+ <aside className="max-h-[min(72vh,640px)] overflow-y-auto border-b bg-muted/15 p-2 md:border-e md:border-b-0">
+ {revisions.isLoading ? (
+ <div className="space-y-1.5 p-1" aria-hidden>
+ <Skeleton className="h-16 w-full" />
+ <Skeleton className="h-16 w-full" />
+ <Skeleton className="h-16 w-full" />
+ </div>
+ ) : revisions.isError ? (
+ <div className="grid min-h-48 place-items-center px-4 text-center">
+ <div>
+ <p className="text-sm text-muted-foreground">{t('historyLoadFailed')}</p>
+ <Button
+ type="button"
+ className="mt-3"
+ variant="outline"
+ size="sm"
+ disabled={!canInteract}
+ onClick={() => void revisions.refetch()}
+ >
+ <RefreshCw />
+ {t('reload')}
+ </Button>
+ </div>
+ </div>
+ ) : revisions.data?.length ? (
+ <ol aria-label={t('versionHistory')}>
+ {revisions.data.map((revision) => {
+ const current = revision.version === version;
+ const selected = selectedRevisionId === revision.id;
+ const author = revision.createdByUserId
+ ? (authorNames[revision.createdByUserId] ?? t('unknownAuthor'))
+ : t('unknownAuthor');
+
+ return (
+ <li key={revision.id}>
+ <button
+ type="button"
+ className={cn(
+ 'group flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-start transition-colors outline-none hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
+ selected && 'bg-accent text-accent-foreground',
+ )}
+ aria-current={selected ? 'true' : undefined}
+ disabled={!canInteract}
+ onClick={() => {
+ setRestoreFailed(false);
+ setSelectedRevisionId(revision.id);
+ }}
+ >
+ <span
+ className={cn(
+ 'mt-1.5 size-2 shrink-0 rounded-full border border-muted-foreground/40',
+ selected && 'border-primary bg-primary',
+ )}
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center justify-between gap-2">
+ <span className="text-sm font-medium">
+ {current
+ ? t('currentVersion', { version: revision.version })
+ : t('savedVersion', { version: revision.version })}
+ </span>
+ {current && <Check className="size-3.5 text-primary" aria-hidden />}
+ </span>
+ <span
+ className="mt-1 block truncate text-xs text-muted-foreground"
+ dir="auto"
+ >
+ {revision.title.trim() || t('untitled')}
+ </span>
+ <span className="mt-1 block truncate text-[11px] text-muted-foreground">
+ {t('versionBy', {
+ name: author,
+ time: relativeTime(revision.createdAt),
+ })}
+ </span>
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ ) : (
+ <div className="grid min-h-48 place-items-center px-4 text-center text-sm text-muted-foreground">
+ {t('noHistory')}
+ </div>
+ )}
+ </aside>
+
+ <section className="max-h-[min(72vh,640px)] overflow-y-auto">
+ {selectedRevision.isLoading ? (
+ <div className="space-y-3 p-6" aria-hidden>
+ <Skeleton className="h-8 w-2/3" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-5/6" />
+ </div>
+ ) : selectedRevision.isError ? (
+ <div className="grid min-h-72 place-items-center px-6 text-center">
+ <div>
+ <p className="text-sm text-muted-foreground">{t('historyLoadFailed')}</p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="mt-3"
+ disabled={!canInteract}
+ onClick={() => void selectedRevision.refetch()}
+ >
+ <RefreshCw />
+ {t('reload')}
+ </Button>
+ </div>
+ </div>
+ ) : selectedRevision.data ? (
+ <article className="mx-auto max-w-3xl px-6 py-7">
+ <header className="mb-6 flex items-start justify-between gap-4 border-b pb-4">
+ <div className="min-w-0">
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('savedVersion', { version: selectedRevision.data.version })}
+ </p>
+ <h3 className="mt-1 truncate text-xl font-semibold" dir="auto">
+ {selectedRevision.data.title.trim() || t('untitled')}
+ </h3>
+ </div>
+ {canRestore && selectedRevision.data.version !== version && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!canInteract}
+ onClick={() => void restoreRevision(selectedRevision.data.id)}
+ >
+ {restoringRevisionId === selectedRevision.data.id ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <RotateCcw />
+ )}
+ {t('restoreVersion')}
+ </Button>
+ )}
+ </header>
+ {restoreFailed && (
+ <p
+ className="mb-5 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive"
+ role="alert"
+ >
+ {t('saveFailed')}
+ </p>
+ )}
+ <DocumentMarkdownEditor
+ key={selectedRevision.data.id}
+ defaultValue={selectedRevision.data.content}
+ defaultJson={selectedRevision.data.contentJson}
+ editable={false}
+ placeholder=""
+ className="text-sm leading-6"
+ onReady={noop}
+ onChange={noop}
+ onBlur={noop}
+ />
+ </article>
+ ) : (
+ <div className="grid min-h-72 place-items-center px-6 text-sm text-muted-foreground">
+ {t('selectVersion')}
+ </div>
+ )}
+ </section>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function canInteractWithDocumentHistory(restoringRevisionId: number | null): boolean {
+ return restoringRevisionId === null;
+}
+
+export function canApplyDocumentHistoryRestore({
+ attempt,
+ currentAttempt,
+ open,
+ mounted,
+}: {
+ attempt: number;
+ currentAttempt: number;
+ open: boolean;
+ mounted: boolean;
+}): boolean {
+ return mounted && open && attempt === currentAttempt;
+}
diff --git a/apps/web/src/features/documents/components/DocumentIconPicker.tsx b/apps/web/src/features/documents/components/DocumentIconPicker.tsx
new file mode 100644
index 00000000..336e2aaf
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentIconPicker.tsx
@@ -0,0 +1,208 @@
+'use client';
+
+import { useState } from 'react';
+import { FileText, Search, X } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+
+const ICON_SECTIONS = [
+ {
+ label: 'frequentIcons',
+ values: ['📄', '✍️', '📘', '💭', '🧩', '🚀', '✅', '📍', '🎯', '🧪', '🗓️', '📊'],
+ },
+ {
+ label: 'objectIcons',
+ values: [
+ '📣',
+ '🗃️',
+ '📎',
+ '🔗',
+ '🔐',
+ '🗝️',
+ '⚙️',
+ '🧰',
+ '💻',
+ '📱',
+ '🎨',
+ '🗺️',
+ '🔬',
+ '🧬',
+ '📝',
+ '📐',
+ ],
+ },
+ {
+ label: 'symbolIcons',
+ values: [
+ '⭐',
+ '❤️',
+ '🔥',
+ '⚡',
+ '✨',
+ '🎉',
+ '🏁',
+ '🚧',
+ '⚠️',
+ '❓',
+ '💬',
+ '👀',
+ '👍',
+ '🌱',
+ '🌍',
+ '💎',
+ ],
+ },
+] as const;
+
+export default function DocumentIconPicker({
+ icon,
+ editable,
+ onChange,
+}: {
+ icon: string | null;
+ editable: boolean;
+ onChange: (icon: string | null) => void;
+}) {
+ const t = useTranslations('documents');
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [customIcon, setCustomIcon] = useState('');
+ const normalizedQuery = query.trim().toLocaleLowerCase();
+ const sections = ICON_SECTIONS.map((section) => ({
+ ...section,
+ values:
+ normalizedQuery.length === 0 || t(section.label).toLocaleLowerCase().includes(normalizedQuery)
+ ? section.values
+ : section.values.filter((value) => value.includes(query.trim())),
+ })).filter((section) => section.values.length > 0);
+ const iconContent = icon ? (
+ <span className="text-[1.65rem] leading-none" aria-hidden>
+ {icon}
+ </span>
+ ) : (
+ <FileText className="size-5" />
+ );
+
+ if (!editable) {
+ return (
+ <div
+ className="grid size-11 shrink-0 place-items-center text-muted-foreground"
+ aria-label={t('pageIcon')}
+ >
+ {iconContent}
+ </div>
+ );
+ }
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(nextOpen) => {
+ setOpen(nextOpen);
+ if (!nextOpen) setQuery('');
+ }}
+ >
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-11 shrink-0 rounded-lg text-muted-foreground hover:bg-muted"
+ aria-label={t('changeIcon')}
+ title={t('changeIcon')}
+ >
+ {iconContent}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" sideOffset={8} className="w-76 p-2 shadow-xl">
+ <div className="relative mb-2">
+ <Search className="pointer-events-none absolute start-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ className="h-8 border-transparent bg-muted/60 ps-8 text-xs shadow-none focus-visible:bg-background"
+ placeholder={t('searchIcons')}
+ aria-label={t('searchIcons')}
+ autoFocus
+ onChange={(event) => setQuery(event.target.value)}
+ />
+ </div>
+
+ <div
+ className="max-h-64 overflow-y-auto overscroll-contain pe-1"
+ aria-label={t('pageIcon')}
+ >
+ {sections.map((section) => (
+ <section key={section.label} className="mb-2 last:mb-0">
+ <h2 className="px-1.5 py-1 text-[10px] font-semibold tracking-wide text-muted-foreground uppercase">
+ {t(section.label)}
+ </h2>
+ <div className="grid grid-cols-8 gap-0.5">
+ {section.values.map((candidate) => (
+ <button
+ key={candidate}
+ type="button"
+ className={cn(
+ 'grid size-8 place-items-center rounded-md text-lg transition-colors outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring',
+ icon === candidate && 'bg-accent ring-1 ring-border',
+ )}
+ aria-label={candidate}
+ aria-pressed={icon === candidate}
+ onClick={() => {
+ onChange(candidate);
+ setOpen(false);
+ }}
+ >
+ {candidate}
+ </button>
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+
+ <form
+ className="mt-2 flex gap-1.5 border-t pt-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const nextIcon = customIcon.trim();
+ if (!nextIcon) return;
+ onChange(nextIcon);
+ setCustomIcon('');
+ setOpen(false);
+ }}
+ >
+ <Input
+ value={customIcon}
+ className="h-8 min-w-0 text-xs shadow-none"
+ maxLength={8}
+ placeholder={t('customIcon')}
+ aria-label={t('customIcon')}
+ onChange={(event) => setCustomIcon(event.target.value)}
+ />
+ <Button type="submit" variant="secondary" size="sm" disabled={!customIcon.trim()}>
+ {t('setIcon')}
+ </Button>
+ </form>
+
+ {icon && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="mt-1.5 w-full justify-start text-muted-foreground"
+ onClick={() => {
+ onChange(null);
+ setOpen(false);
+ }}
+ >
+ <X />
+ {t('removeIcon')}
+ </Button>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentImageMenu.tsx b/apps/web/src/features/documents/components/DocumentImageMenu.tsx
new file mode 100644
index 00000000..fda2d893
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentImageMenu.tsx
@@ -0,0 +1,158 @@
+'use client';
+
+import { useRef, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import { ImagePlus, Loader2, Upload } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { useDocumentAssetsQuery, useUploadDocumentAsset } from '../services/documents.service';
+import { insertDocumentImage } from './DocumentMarkdownEditor';
+
+export default function DocumentImageMenu({
+ editor,
+ projectKey,
+ documentId,
+ canUpload,
+}: {
+ editor: Editor;
+ projectKey: string;
+ documentId: number;
+ canUpload: boolean;
+}) {
+ const t = useTranslations('documents.toolbar');
+ const [open, setOpen] = useState(false);
+ const [url, setUrl] = useState('');
+ const fileInput = useRef<HTMLInputElement>(null);
+ const editableRef = useRef(canUpload);
+ editableRef.current = canUpload;
+ const assets = useDocumentAssetsQuery(open ? projectKey : null, open ? documentId : null);
+ const upload = useUploadDocumentAsset(projectKey, documentId);
+ const images = assets.data?.filter((asset) => asset.contentType.startsWith('image/')) ?? [];
+
+ const insert = (source: string, alt?: string) => {
+ if (!insertDocumentImage(editor, editableRef.current, source, alt)) return;
+ setUrl('');
+ setOpen(false);
+ };
+
+ const chooseFile = (file: File | undefined) => {
+ if (!file || !editableRef.current || !file.type.startsWith('image/')) return;
+ upload.mutate(file, { onSuccess: (asset) => insert(asset.url, asset.filename) });
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-8 rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground"
+ aria-label={t('image')}
+ >
+ <ImagePlus className="size-4 stroke-[1.75]" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[21rem] overflow-hidden rounded-xl p-0 shadow-xl">
+ <Tabs defaultValue="library" className="gap-0">
+ <TabsList variant="line" className="h-11 w-full justify-start gap-4 px-4">
+ <TabsTrigger value="library" className="px-0 text-xs">
+ {t('imageLibrary')}
+ </TabsTrigger>
+ <TabsTrigger value="external" className="px-0 text-xs">
+ {t('externalImage')}
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="library" className="p-3">
+ {canUpload && (
+ <>
+ <input
+ ref={fileInput}
+ className="sr-only"
+ type="file"
+ accept="image/*"
+ aria-label={t('uploadImage')}
+ onChange={(event) => {
+ chooseFile(event.target.files?.[0]);
+ event.currentTarget.value = '';
+ }}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="mb-3 h-9 w-full justify-center rounded-lg border-dashed bg-muted/20 text-xs shadow-none"
+ disabled={upload.isPending}
+ onClick={() => fileInput.current?.click()}
+ >
+ {upload.isPending ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : (
+ <Upload className="size-4" />
+ )}
+ {t('uploadImage')}
+ </Button>
+ </>
+ )}
+
+ {assets.isLoading ? (
+ <div className="grid grid-cols-3 gap-2" aria-hidden>
+ {Array.from({ length: 6 }, (_, index) => (
+ <div key={index} className="aspect-square animate-pulse rounded-lg bg-muted/60" />
+ ))}
+ </div>
+ ) : images.length > 0 ? (
+ <div className="grid max-h-56 grid-cols-3 gap-2 overflow-y-auto pe-1" role="list">
+ {images.map((asset) => (
+ <button
+ key={asset.id}
+ type="button"
+ className="group relative aspect-square overflow-hidden rounded-lg bg-muted ring-offset-2 ring-offset-popover transition-[opacity,transform] outline-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98]"
+ title={asset.filename}
+ aria-label={t('insertImage', { name: asset.filename })}
+ onClick={() => insert(asset.url, asset.filename)}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element -- private media uses the session-gated proxy. */}
+ <img src={asset.url} alt="" className="size-full object-cover" />
+ <span className="absolute inset-x-0 bottom-0 truncate bg-black/55 px-1.5 py-1 text-start text-[10px] text-white opacity-0 backdrop-blur-sm transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100">
+ {asset.filename}
+ </span>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="py-8 text-center text-xs text-muted-foreground">{t('noImages')}</p>
+ )}
+ </TabsContent>
+
+ <TabsContent value="external" className="p-4">
+ <form
+ className="flex items-center gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ insert(url);
+ }}
+ >
+ <Input
+ value={url}
+ type="url"
+ dir="ltr"
+ className="h-9 rounded-lg text-xs"
+ placeholder={t('imageUrl')}
+ aria-label={t('imageUrl')}
+ onChange={(event) => setUrl(event.target.value)}
+ />
+ <Button type="submit" size="sm" className="h-9 rounded-lg" disabled={!url.trim()}>
+ {t('insert')}
+ </Button>
+ </form>
+ </TabsContent>
+ </Tabs>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentLoadError.tsx b/apps/web/src/features/documents/components/DocumentLoadError.tsx
new file mode 100644
index 00000000..025c6e25
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentLoadError.tsx
@@ -0,0 +1,19 @@
+import { RefreshCw } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { useTranslations } from 'next-intl';
+
+export default function DocumentLoadError({ onRetry }: { onRetry: () => void }) {
+ const t = useTranslations('documents');
+
+ return (
+ <main className="flex min-w-0 flex-1 items-center justify-center px-6 text-center">
+ <div>
+ <p className="text-sm text-muted-foreground">{t('loadFailed')}</p>
+ <Button className="mt-3" variant="outline" size="sm" onClick={onRetry}>
+ <RefreshCw />
+ {t('reload')}
+ </Button>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentLoadingState.tsx b/apps/web/src/features/documents/components/DocumentLoadingState.tsx
new file mode 100644
index 00000000..3c77dc43
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentLoadingState.tsx
@@ -0,0 +1,20 @@
+import { Skeleton } from '@/components/ui/skeleton';
+
+export default function DocumentLoadingState() {
+ return (
+ <main className="flex min-w-0 flex-1 flex-col">
+ <div className="h-12 border-b px-4 py-4">
+ <Skeleton className="h-3 w-48" />
+ </div>
+ <div className="h-11 border-b px-4 py-2">
+ <Skeleton className="h-7 w-80 max-w-full" />
+ </div>
+ <div className="mx-auto w-full max-w-[800px] px-6 py-12 md:px-12">
+ <Skeleton className="mb-4 size-10 rounded-lg" />
+ <Skeleton className="h-11 w-2/3 max-w-xl" />
+ <Skeleton className="mt-4 h-3 w-48" />
+ <Skeleton className="mt-10 h-72 w-full" />
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentLockButton.tsx b/apps/web/src/features/documents/components/DocumentLockButton.tsx
new file mode 100644
index 00000000..73af1096
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentLockButton.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import { LockKeyhole, LockKeyholeOpen } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+
+export default function DocumentLockButton({
+ locked,
+ disabled,
+ onChange,
+}: {
+ locked: boolean;
+ disabled: boolean;
+ onChange: (locked: boolean) => void;
+}) {
+ const t = useTranslations('documents');
+ const label = locked ? t('unlock') : t('lock');
+
+ return (
+ <Button
+ type="button"
+ variant={locked ? 'secondary' : 'ghost'}
+ size="icon-sm"
+ disabled={disabled}
+ aria-label={label}
+ aria-pressed={locked}
+ title={label}
+ onClick={() => onChange(!locked)}
+ >
+ {locked ? <LockKeyhole /> : <LockKeyholeOpen />}
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts b/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts
new file mode 100644
index 00000000..9ab4cee4
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts
@@ -0,0 +1,287 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { Editor, type JSONContent } from '@tiptap/core';
+import { JSDOM } from 'jsdom';
+import {
+ documentEditorExtensions,
+ firstImageFile,
+ insertDocumentImage,
+ safeDocumentImageSource,
+ uploadAndInsertImage,
+ syncDocumentEditorEditable,
+} from './DocumentMarkdownEditor';
+
+const richDocument: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ attrs: { textAlign: 'center' },
+ content: [
+ {
+ type: 'text',
+ text: 'Rich text',
+ marks: [
+ { type: 'underline' },
+ { type: 'textStyle', attrs: { color: '#dc2626' } },
+ { type: 'highlight', attrs: { color: '#fde047' } },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'taskList',
+ content: [
+ {
+ type: 'taskItem',
+ attrs: { checked: true },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Done' }] }],
+ },
+ ],
+ },
+ {
+ type: 'table',
+ content: [
+ {
+ type: 'tableRow',
+ content: [
+ {
+ type: 'tableHeader',
+ attrs: { colspan: 1, rowspan: 1, colwidth: null },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Column' }] }],
+ },
+ ],
+ },
+ ],
+ },
+ { type: 'image', attrs: { src: 'https://example.test/image.png', alt: 'Example' } },
+ ],
+};
+
+const protectedImage =
+ '/protected-media/projects/MKT/documents/1/assets/123e4567-e89b-12d3-a456-426614174000/raw';
+
+let dom: JSDOM;
+let previousWindow: PropertyDescriptor | undefined;
+let previousDocument: PropertyDescriptor | undefined;
+let previousNavigator: PropertyDescriptor | undefined;
+let previousAnimationFrame: PropertyDescriptor | undefined;
+
+beforeEach(() => {
+ previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
+ previousDocument = Object.getOwnPropertyDescriptor(globalThis, 'document');
+ previousNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
+ previousAnimationFrame = Object.getOwnPropertyDescriptor(globalThis, 'requestAnimationFrame');
+ dom = new JSDOM('<!doctype html><div id="one"></div><div id="two"></div>');
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ requestAnimationFrame: {
+ configurable: true,
+ value: (callback: FrameRequestCallback) => setTimeout(callback, 0),
+ },
+ });
+});
+
+afterEach(() => {
+ dom.window.close();
+ for (const [name, descriptor] of [
+ ['window', previousWindow],
+ ['document', previousDocument],
+ ['navigator', previousNavigator],
+ ['requestAnimationFrame', previousAnimationFrame],
+ ] as const) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('DocumentMarkdownEditor JSON persistence', () => {
+ it('registers one complete rich-text extension surface', () => {
+ const extensions = documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ image: { label: 'Image', onPick: () => undefined },
+ });
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions,
+ });
+ const names = editor.extensionManager.extensions.map((extension) => extension.name);
+
+ for (const name of [
+ 'codeBlock',
+ 'link',
+ 'image',
+ 'table',
+ 'tableRow',
+ 'tableHeader',
+ 'tableCell',
+ 'taskList',
+ 'taskItem',
+ 'highlight',
+ 'textAlign',
+ 'slashCommand',
+ 'markdown',
+ ]) {
+ assert.equal(names.filter((extensionName) => extensionName === name).length, 1, name);
+ }
+ editor.destroy();
+ });
+
+ it('preserves rich-only nodes and marks across an editor remount', () => {
+ const extensions = documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ });
+ const first = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions,
+ content: richDocument,
+ });
+ const persisted = first.getJSON();
+ first.destroy();
+
+ const second = new Editor({
+ element: document.querySelector('#two') as HTMLElement,
+ extensions,
+ content: persisted,
+ });
+ assert.deepEqual(second.getJSON(), persisted);
+ second.destroy();
+ });
+
+ it('selects image files for paste/drop without consuming unrelated files', () => {
+ const text = new window.File(['notes'], 'notes.txt', { type: 'text/plain' });
+ const image = new window.File(['image'], 'photo.png', { type: 'image/png' });
+ assert.equal(firstImageFile([text]), null);
+ assert.equal(firstImageFile([text, image]), image);
+ });
+
+ it('updates a mounted editor when the editable prop changes', () => {
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions: documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ }),
+ editable: true,
+ });
+
+ syncDocumentEditorEditable(editor, false);
+ assert.equal(editor.isEditable, false);
+
+ syncDocumentEditorEditable(editor, true);
+ assert.equal(editor.isEditable, true);
+ editor.destroy();
+ });
+
+ it('keeps links openable in the read-only editor', () => {
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions: documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ }),
+ editable: false,
+ });
+ const link = editor.extensionManager.extensions.find((extension) => extension.name === 'link');
+ assert.ok(link);
+ assert.equal(link.options.openOnClick, true);
+ editor.destroy();
+ });
+
+ it('keeps unsafe link protocols out of the document', () => {
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions: documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ }),
+ content: {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Docs' }] }],
+ },
+ });
+
+ assert.equal(
+ editor.chain().selectAll().setLink({ href: 'ftp://example.test/file' }).run(),
+ false,
+ );
+ assert.equal(editor.getAttributes('link').href, undefined);
+ assert.equal(editor.chain().selectAll().setLink({ href: '/docs/start' }).run(), true);
+ assert.equal(editor.getAttributes('link').href, '/docs/start');
+ editor.destroy();
+ });
+
+ it('inserts trimmed image sources only while the editor is editable', () => {
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions: documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ }),
+ editable: true,
+ });
+
+ assert.equal(insertDocumentImage(editor, true, ' '), false);
+ assert.equal(insertDocumentImage(editor, true, ` ${protectedImage} `, 'Photo'), true);
+ assert.equal(editor.getAttributes('image').src, protectedImage);
+
+ syncDocumentEditorEditable(editor, false);
+ assert.equal(insertDocumentImage(editor, true, '/protected-media/second.png'), false);
+ editor.destroy();
+ });
+
+ it('accepts only server-compatible image sources', () => {
+ assert.equal(safeDocumentImageSource(protectedImage), protectedImage);
+ assert.equal(
+ safeDocumentImageSource('https://images.example.test/photo.png'),
+ 'https://images.example.test/photo.png',
+ );
+ assert.equal(safeDocumentImageSource('javascript:alert(1)'), null);
+ assert.equal(safeDocumentImageSource('//images.example.test/photo.png'), null);
+ assert.equal(safeDocumentImageSource('https://user:[email protected]/photo.png'), null);
+ assert.equal(safeDocumentImageSource('https://example.test/image with space.png'), null);
+ });
+
+ it('does not insert a completed image upload after the editor becomes read-only', async () => {
+ const editor = new Editor({
+ element: document.querySelector('#one') as HTMLElement,
+ extensions: documentEditorExtensions({
+ placeholder: '',
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ }),
+ editable: true,
+ });
+ let resolveUpload!: (asset: { url: string; filename: string }) => void;
+ const upload = new Promise<{ url: string; filename: string }>((resolve) => {
+ resolveUpload = resolve;
+ });
+ let currentEditable = true;
+ const image = new window.File(['image'], 'photo.png', { type: 'image/png' });
+ const insertion = uploadAndInsertImage(
+ editor,
+ image,
+ () => upload,
+ 0,
+ () => currentEditable,
+ );
+
+ currentEditable = false;
+ syncDocumentEditorEditable(editor, false);
+ resolveUpload({ url: protectedImage, filename: 'photo.png' });
+
+ assert.equal(await insertion, false);
+ assert.equal(editor.getJSON().content?.some((node) => node.type === 'image') ?? false, false);
+ editor.destroy();
+ });
+});
diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
new file mode 100644
index 00000000..8189090e
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx
@@ -0,0 +1,293 @@
+'use client';
+
+import { useEffect, useLayoutEffect, useRef } from 'react';
+import type { JSONContent } from '@tiptap/core';
+import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
+import Color from '@tiptap/extension-color';
+import Highlight from '@tiptap/extension-highlight';
+import Link from '@tiptap/extension-link';
+import Placeholder from '@tiptap/extension-placeholder';
+import { TableKit } from '@tiptap/extension-table';
+import TaskItem from '@tiptap/extension-task-item';
+import TaskList from '@tiptap/extension-task-list';
+import TextAlign from '@tiptap/extension-text-align';
+import { TextStyle } from '@tiptap/extension-text-style';
+import { type Editor, EditorContent, useEditor } from '@tiptap/react';
+import StarterKit from '@tiptap/starter-kit';
+import { common, createLowlight } from 'lowlight';
+import { useTranslations } from 'next-intl';
+import { Markdown } from 'tiptap-markdown';
+import EditorSelectionMenu from '@/components/common/editor/EditorSelectionMenu';
+import EditorTableMenu from '@/components/common/editor/EditorTableMenu';
+import { ResizableImage } from '@/components/common/editor/tiptap-image';
+import { MarkdownTable } from '@/components/common/editor/tiptap-table';
+import { SlashCommand } from '@/lib/tiptap-slash-command';
+
+const lowlight = createLowlight(common);
+const DOCUMENT_ASSET_PATH =
+ /^\/(?:protected-media\/)?projects\/[A-Za-z0-9._~%+-]+\/documents\/[1-9]\d*\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/raw$/i;
+
+function safeDocumentLinkHref(href: string): boolean {
+ if (
+ href.length === 0 ||
+ href.length > 2048 ||
+ [...href].some(
+ (character) => character === '\\' || /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(character),
+ )
+ ) {
+ return false;
+ }
+ if (href.startsWith('#')) return true;
+ if (href.startsWith('/') && !href.startsWith('//')) return true;
+ if (/^(mailto:|tel:).+/i.test(href)) return true;
+ try {
+ const url = new URL(href);
+ return (
+ (url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password
+ );
+ } catch {
+ return false;
+ }
+}
+
+type EditorLabels = {
+ placeholder: string;
+ codeBlockLabel: string;
+ tableLabel: string;
+ blocks?: {
+ paragraph: string;
+ headings: [string, string, string, string, string, string];
+ bulletList: string;
+ orderedList: string;
+ taskList: string;
+ quote: string;
+ divider: string;
+ };
+ image?: { label: string; onPick: () => void };
+};
+
+type EditorValue = { markdown: string; json: JSONContent };
+
+export function documentEditorExtensions(labels: EditorLabels) {
+ return [
+ StarterKit.configure({
+ codeBlock: false,
+ link: false,
+ heading: { levels: [1, 2, 3, 4, 5, 6] },
+ }),
+ CodeBlockLowlight.configure({ lowlight }),
+ Placeholder.configure({ placeholder: labels.placeholder }),
+ Link.configure({
+ autolink: true,
+ defaultProtocol: 'https',
+ openOnClick: true,
+ isAllowedUri: safeDocumentLinkHref,
+ }),
+ ResizableImage,
+ TableKit.configure({ table: false }),
+ MarkdownTable.configure({ resizable: false }),
+ TaskList,
+ TaskItem.configure({ nested: true }),
+ TextStyle,
+ Color,
+ Highlight.configure({ multicolor: true }),
+ TextAlign.configure({ types: ['heading', 'paragraph'] }),
+ SlashCommand.configure({
+ codeBlockLabel: labels.codeBlockLabel,
+ tableLabel: labels.tableLabel,
+ blocks: labels.blocks,
+ image: labels.image,
+ }),
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ];
+}
+
+function editorValue(editor: Editor): EditorValue {
+ return { markdown: editor.storage.markdown.getMarkdown(), json: editor.getJSON() };
+}
+
+export default function DocumentMarkdownEditor({
+ defaultValue,
+ defaultJson,
+ editable,
+ placeholder,
+ className,
+ onReady,
+ onChange,
+ onBlur,
+ onPickImage,
+ onUploadImage,
+}: {
+ defaultValue: string;
+ defaultJson: Record<string, unknown> | null;
+ editable: boolean;
+ placeholder: string;
+ className?: string;
+ onReady: (editor: Editor | null) => void;
+ onChange: (value: EditorValue) => void;
+ onBlur: (value: EditorValue) => void;
+ onPickImage?: () => void;
+ onUploadImage?: (file: File) => Promise<{ url: string; filename: string }>;
+}) {
+ const t = useTranslations('documents.toolbar');
+ const editorRef = useRef<Editor | null>(null);
+ const editableRef = useRef(editable);
+ editableRef.current = editable;
+
+ const editor = useEditor({
+ editable,
+ extensions: documentEditorExtensions({
+ placeholder,
+ codeBlockLabel: t('codeBlock'),
+ tableLabel: t('table'),
+ blocks: {
+ paragraph: t('text'),
+ headings: [
+ t('heading1'),
+ t('heading2'),
+ t('heading3'),
+ t('heading4'),
+ t('heading5'),
+ t('heading6'),
+ ],
+ bulletList: t('bulletList'),
+ orderedList: t('numberedList'),
+ taskList: t('todoList'),
+ quote: t('quote'),
+ divider: t('divider'),
+ },
+ image: onPickImage ? { label: t('uploadImage'), onPick: onPickImage } : undefined,
+ }),
+ content: defaultJson ?? defaultValue,
+ editorProps: {
+ attributes: {
+ class: 'md-content flex-1 focus:outline-none selection:bg-primary/15',
+ },
+ handlePaste: (_view, event) => {
+ const file = firstImageFile(event.clipboardData?.files);
+ const currentEditor = editorRef.current;
+ if (!file || !onUploadImage || !currentEditor || !editableRef.current) return false;
+ event.preventDefault();
+ void uploadAndInsertImage(
+ currentEditor,
+ file,
+ onUploadImage,
+ currentEditor.state.selection.from,
+ () => editableRef.current,
+ );
+ return true;
+ },
+ handleDrop: (view, event, _slice, moved) => {
+ const file = firstImageFile(event.dataTransfer?.files);
+ const currentEditor = editorRef.current;
+ if (moved || !file || !onUploadImage || !currentEditor || !editableRef.current)
+ return false;
+ const dropPoint = view.posAtCoords({ left: event.clientX, top: event.clientY });
+ if (!dropPoint) return false;
+ event.preventDefault();
+ void uploadAndInsertImage(currentEditor, file, onUploadImage, dropPoint.pos, () =>
+ Boolean(editableRef.current),
+ );
+ return true;
+ },
+ },
+ onCreate: ({ editor: currentEditor }) => {
+ editorRef.current = currentEditor;
+ },
+ onUpdate: ({ editor: currentEditor }) => onChange(editorValue(currentEditor)),
+ onBlur: ({ editor: currentEditor }) => onBlur(editorValue(currentEditor)),
+ onDestroy: () => {
+ editorRef.current = null;
+ },
+ });
+
+ useEffect(() => {
+ editorRef.current = editor;
+ onReady(editor);
+ return () => onReady(null);
+ }, [editor, onReady]);
+
+ useLayoutEffect(() => {
+ syncDocumentEditorEditable(editor, editable);
+ }, [editable, editor]);
+
+ if (!editor) return null;
+
+ return (
+ <div className={className} data-document-editor="">
+ {editable && <EditorSelectionMenu editor={editor} />}
+ {editable && <EditorTableMenu editor={editor} />}
+ <EditorContent editor={editor} className="flex min-h-full flex-col" />
+ </div>
+ );
+}
+
+export function syncDocumentEditorEditable(editor: Editor | null, editable: boolean) {
+ if (editor && editor.isEditable !== editable) editor.setEditable(editable);
+}
+
+export function insertDocumentImage(
+ editor: Editor | null,
+ editable: boolean,
+ src: string,
+ alt?: string,
+): boolean {
+ const normalizedSource = safeDocumentImageSource(src);
+ if (!normalizedSource || !editable || !editor || editor.isDestroyed || !editor.isEditable) {
+ return false;
+ }
+ return editor.chain().focus().setImage({ src: normalizedSource, alt }).run();
+}
+
+export function safeDocumentImageSource(source: string): string | null {
+ const normalized = source.trim();
+ if (
+ normalized.length === 0 ||
+ normalized.length > 4096 ||
+ [...normalized].some(
+ (character) => character === '\\' || /[\p{White_Space}\p{Cc}\p{Cf}]/u.test(character),
+ )
+ ) {
+ return null;
+ }
+ if (DOCUMENT_ASSET_PATH.test(normalized)) return normalized;
+ try {
+ const url = new URL(normalized);
+ if ((url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password) {
+ return normalized;
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+export function firstImageFile(files: ArrayLike<File> | null | undefined): File | null {
+ return Array.from(files ?? []).find((file) => file.type.startsWith('image/')) ?? null;
+}
+
+export async function uploadAndInsertImage(
+ editor: Editor,
+ file: File,
+ upload: (file: File) => Promise<{ url: string; filename: string }>,
+ position: number,
+ isEditable: () => boolean = () => editor.isEditable,
+): Promise<boolean> {
+ try {
+ const asset = await upload(file);
+ if (editor.isDestroyed || !editor.isEditable || !isEditable()) return false;
+ const source = safeDocumentImageSource(asset.url);
+ if (!source) return false;
+ const safePosition = Math.max(0, Math.min(position, editor.state.doc.content.size));
+ return editor
+ .chain()
+ .focus()
+ .insertContentAt(safePosition, {
+ type: 'image',
+ attrs: { src: source, alt: asset.filename },
+ })
+ .run();
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/web/src/features/documents/components/DocumentOptionsMenu.tsx b/apps/web/src/features/documents/components/DocumentOptionsMenu.tsx
new file mode 100644
index 00000000..a547aea7
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentOptionsMenu.tsx
@@ -0,0 +1,220 @@
+'use client';
+
+import { useCallback, useState } from 'react';
+import {
+ Archive,
+ Check,
+ Clipboard,
+ Copy,
+ Download,
+ Expand,
+ History,
+ LockKeyhole,
+ MoreHorizontal,
+ PanelTop,
+ Plus,
+ RotateCcw,
+ Trash2,
+} from 'lucide-react';
+import { toast } from 'sonner';
+import type { ProjectDocument } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useTranslations } from 'next-intl';
+import DocumentExportDialog from './DocumentExportDialog';
+
+export default function DocumentOptionsMenu({
+ projectKey,
+ document,
+ title,
+ content,
+ richHtml,
+ stickyToolbar,
+ canCreate,
+ canUpdate,
+ canManage,
+ canManageLifecycle,
+ canDelete,
+ busy,
+ onFullWidthChange,
+ onStickyToolbarChange,
+ onPrivacyChange,
+ onCreateChild,
+ onDuplicate,
+ onArchive,
+ onRestore,
+ onDelete,
+ onOpenHistory,
+}: {
+ projectKey: string;
+ document: ProjectDocument;
+ title: string;
+ content: string;
+ richHtml: string;
+ stickyToolbar: boolean;
+ canCreate: boolean;
+ canUpdate: boolean;
+ canManage: boolean;
+ canManageLifecycle: boolean;
+ canDelete: boolean;
+ busy: boolean;
+ onFullWidthChange: (value: boolean) => void;
+ onStickyToolbarChange: (value: boolean) => void;
+ onPrivacyChange: (value: boolean) => void;
+ onCreateChild: () => void;
+ onDuplicate: () => void;
+ onArchive: () => void;
+ onRestore: () => void;
+ onDelete: () => void;
+ onOpenHistory: () => void;
+}) {
+ const t = useTranslations('documents');
+ const [exportOpen, setExportOpen] = useState(false);
+ const archived = document.archivedAt !== null;
+
+ const copyMarkdown = useCallback(async () => {
+ try {
+ await navigator.clipboard.writeText(content);
+ } catch {
+ const input = window.document.createElement('textarea');
+ input.value = content;
+ input.style.position = 'fixed';
+ input.style.opacity = '0';
+ try {
+ window.document.body.append(input);
+ input.select();
+ if (!window.document.execCommand('copy')) return;
+ } catch {
+ return;
+ } finally {
+ input.remove();
+ }
+ }
+ toast.success(t('markdownCopied'));
+ }, [content, t]);
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('documentActions')}
+ aria-busy={busy}
+ >
+ <MoreHorizontal />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-60">
+ {canUpdate && (
+ <DropdownMenuItem
+ disabled={busy}
+ onSelect={(event) => {
+ event.preventDefault();
+ onFullWidthChange(!document.fullWidth);
+ }}
+ >
+ <Expand />
+ <span className="flex-1">{t('fullWidth')}</span>
+ {document.fullWidth && <Check className="text-primary" aria-hidden />}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ onStickyToolbarChange(!stickyToolbar);
+ }}
+ >
+ <PanelTop />
+ <span className="flex-1">{t('stickyToolbar')}</span>
+ {stickyToolbar && <Check className="text-primary" aria-hidden />}
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => void copyMarkdown()}>
+ <Clipboard />
+ {t('copyMarkdown')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onOpenHistory}>
+ <History />
+ {t('versionHistory')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setExportOpen(true)}>
+ <Download />
+ {t('export')}
+ </DropdownMenuItem>
+
+ {canCreate && (
+ <>
+ <DropdownMenuSeparator />
+ {!archived && (
+ <DropdownMenuItem onSelect={onCreateChild}>
+ <Plus />
+ {t('addSubpage')}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem disabled={busy} onSelect={onDuplicate}>
+ <Copy />
+ {t('makeCopy')}
+ </DropdownMenuItem>
+ </>
+ )}
+
+ {(canManage || canManageLifecycle || canDelete) && <DropdownMenuSeparator />}
+ {canManage && !archived && (
+ <DropdownMenuItem
+ disabled={busy}
+ onSelect={(event) => {
+ event.preventDefault();
+ onPrivacyChange(!document.isPrivate);
+ }}
+ >
+ <LockKeyhole />
+ <span className="flex-1">{t('privatePage')}</span>
+ {document.isPrivate && <Check className="text-primary" aria-hidden />}
+ </DropdownMenuItem>
+ )}
+ {canManageLifecycle && !archived && (
+ <DropdownMenuItem disabled={busy || document.isLocked} onSelect={onArchive}>
+ <Archive />
+ {t('archive')}
+ </DropdownMenuItem>
+ )}
+ {canManageLifecycle && archived && (
+ <DropdownMenuItem disabled={busy} onSelect={onRestore}>
+ <RotateCcw />
+ {t('restore')}
+ </DropdownMenuItem>
+ )}
+ {canDelete && archived && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" disabled={busy} onSelect={onDelete}>
+ <Trash2 />
+ {t('deletePermanently')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <DocumentExportDialog
+ open={exportOpen}
+ projectKey={projectKey}
+ documentId={document.id}
+ title={title}
+ content={content}
+ richHtml={richHtml}
+ onOpenChange={setExportOpen}
+ />
+ </>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentPageTitle.tsx b/apps/web/src/features/documents/components/DocumentPageTitle.tsx
new file mode 100644
index 00000000..6fbc5204
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentPageTitle.tsx
@@ -0,0 +1,41 @@
+import { forwardRef } from 'react';
+import { useTranslations } from 'next-intl';
+import DocumentIconPicker from './DocumentIconPicker';
+
+const DocumentPageTitle = forwardRef<
+ HTMLTextAreaElement,
+ {
+ title: string;
+ icon: string | null;
+ editable: boolean;
+ onChange: (title: string) => void;
+ onSave: () => void;
+ onIconChange: (icon: string | null) => void;
+ }
+>(function DocumentPageTitle({ title, icon, editable, onChange, onSave, onIconChange }, ref) {
+ const t = useTranslations('documents');
+
+ return (
+ <div className="-ms-2 flex items-start gap-1.5">
+ <DocumentIconPicker icon={icon} editable={editable} onChange={onIconChange} />
+ <textarea
+ ref={ref}
+ value={title}
+ readOnly={!editable}
+ rows={1}
+ maxLength={255}
+ placeholder={t('titlePlaceholder')}
+ aria-label={t('pageTitle')}
+ dir="auto"
+ className="[field-sizing:content] min-h-11 min-w-0 flex-1 resize-none overflow-hidden bg-transparent pt-0.5 text-[2rem] leading-[1.12] font-semibold tracking-[-0.035em] text-balance outline-none placeholder:text-muted-foreground/35 md:text-[2.5rem]"
+ onChange={(event) => onChange(event.target.value.replace(/[\r\n]+/g, ''))}
+ onBlur={onSave}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing) event.preventDefault();
+ }}
+ />
+ </div>
+ );
+});
+
+export default DocumentPageTitle;
diff --git a/apps/web/src/features/documents/components/DocumentPickerDialog.tsx b/apps/web/src/features/documents/components/DocumentPickerDialog.tsx
new file mode 100644
index 00000000..bacb8b2b
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentPickerDialog.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { useState } from 'react';
+import { FileText, Lock } from 'lucide-react';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { useDebouncedValue } from '@/hooks/useDebouncedValue';
+import {
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@/components/ui/command';
+import { useTranslations } from 'next-intl';
+import { useDocumentsQuery } from '../services/documents.service';
+
+export default function DocumentPickerDialog({
+ projectKey,
+ linkedDocumentIds,
+ onPick,
+ onClose,
+}: {
+ projectKey: string;
+ linkedDocumentIds: Set<number>;
+ onPick: (document: ProjectDocumentSummary) => void;
+ onClose: () => void;
+}) {
+ const t = useTranslations('documents');
+ const [query, setQuery] = useState('');
+ const debounced = useDebouncedValue(query.trim(), 250);
+ const documents = useDocumentsQuery(projectKey, debounced);
+ const choices = (documents.data ?? []).filter((document) => !linkedDocumentIds.has(document.id));
+
+ return (
+ <CommandDialog
+ open
+ onOpenChange={onClose}
+ shouldFilter={false}
+ title={t('linkWorkItem.selectDocument')}
+ description={t('linkWorkItem.searchDocuments')}
+ >
+ <CommandInput
+ value={query}
+ onValueChange={setQuery}
+ placeholder={t('linkWorkItem.searchDocuments')}
+ />
+ <CommandList>
+ <CommandEmpty>
+ {documents.isLoading ? t('linkWorkItem.loading') : t('linkWorkItem.noDocuments')}
+ </CommandEmpty>
+ <CommandGroup>
+ {choices.map((document) => (
+ <CommandItem
+ key={document.id}
+ value={String(document.id)}
+ onSelect={() => onPick(document)}
+ >
+ <span className="grid size-7 shrink-0 place-items-center rounded-md border bg-muted/30 text-sm">
+ {document.icon || <FileText className="size-3.5" />}
+ </span>
+ <span className="min-w-0 flex-1 truncate" dir="auto">
+ {document.title.trim() || t('untitled')}
+ </span>
+ {document.isPrivate && <Lock className="size-3.5" aria-label={t('privatePage')} />}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </CommandDialog>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentSidePanel.tsx b/apps/web/src/features/documents/components/DocumentSidePanel.tsx
new file mode 100644
index 00000000..feabb8a7
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentSidePanel.tsx
@@ -0,0 +1,470 @@
+'use client';
+
+import Link from 'next/link';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import {
+ Clipboard,
+ File,
+ FileImage,
+ History,
+ Hash,
+ Loader2,
+ Link2,
+ Plus,
+ RefreshCw,
+ Trash2,
+ Upload,
+ X,
+} from 'lucide-react';
+import { toast } from 'sonner';
+import type { ProjectDocument } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { formatDateTime } from '@/utils/dates';
+import { issuePath } from '@/utils/paths';
+import IssuePickerDialog from '@/components/common/overlay/IssuePickerDialog';
+import ArchivedBadge from '@/components/common/ArchivedBadge';
+import { useTranslations } from 'next-intl';
+import {
+ useDeleteDocumentAsset,
+ useDocumentAssetsQuery,
+ useDocumentIssueLinksQuery,
+ useLinkDocumentIssue,
+ useUnlinkDocumentIssue,
+ useUploadDocumentAsset,
+} from '../services/documents.service';
+
+type OutlineItem = { level: number; position: number; text: string };
+
+export default function DocumentSidePanel({
+ projectKey,
+ document,
+ editor,
+ authorNames,
+ canUpload,
+ canDeleteAssets,
+ canReadWorkItems,
+ canLinkWorkItems,
+ onOpenHistory,
+}: {
+ projectKey: string;
+ document: ProjectDocument;
+ editor: Editor | null;
+ authorNames: Record<string, string>;
+ canUpload: boolean;
+ canDeleteAssets: boolean;
+ canReadWorkItems: boolean;
+ canLinkWorkItems: boolean;
+ onOpenHistory: () => void;
+}) {
+ const t = useTranslations('documents');
+ const fileInput = useRef<HTMLInputElement>(null);
+ const [outlineRevision, setOutlineRevision] = useState(0);
+ const [issuePickerOpen, setIssuePickerOpen] = useState(false);
+ const assets = useDocumentAssetsQuery(projectKey, document.id);
+ const issueLinks = useDocumentIssueLinksQuery(projectKey, document.id, canReadWorkItems);
+ const upload = useUploadDocumentAsset(projectKey, document.id);
+ const remove = useDeleteDocumentAsset(projectKey, document.id);
+ const linkIssue = useLinkDocumentIssue(projectKey);
+ const unlinkIssue = useUnlinkDocumentIssue(projectKey);
+ const linkedIssueIds = new Set((issueLinks.data ?? []).map((link) => link.issueId));
+
+ useEffect(() => {
+ if (!editor) return;
+ const refreshOutline = () => setOutlineRevision((value) => value + 1);
+ editor.on('transaction', refreshOutline);
+ return () => {
+ editor.off('transaction', refreshOutline);
+ };
+ }, [editor]);
+
+ const outline = useMemo(() => {
+ void outlineRevision;
+ const items: OutlineItem[] = [];
+ editor?.state.doc.descendants((node, position) => {
+ if (node.type.name !== 'heading') return;
+ items.push({
+ level: Number(node.attrs.level) || 1,
+ position: position + 1,
+ text: node.textContent.trim(),
+ });
+ });
+ return items;
+ }, [editor, outlineRevision]);
+
+ const jumpToHeading = (position: number) => {
+ if (!editor || editor.isDestroyed) return;
+ const chain = editor.chain().setTextSelection(position).scrollIntoView();
+ if (editor.isEditable) chain.focus();
+ chain.run();
+ };
+
+ const insertAsset = (asset: { contentType: string; filename: string; url: string }) => {
+ if (!canUpload || !editor || editor.isDestroyed || !editor.isEditable) return;
+ if (asset.contentType.startsWith('image/')) {
+ editor.chain().focus().setImage({ src: asset.url, alt: asset.filename }).run();
+ return;
+ }
+ editor
+ .chain()
+ .focus()
+ .insertContent({
+ type: 'text',
+ text: asset.filename,
+ marks: [{ type: 'link', attrs: { href: asset.url } }],
+ })
+ .run();
+ };
+
+ const copyAsset = async (url: string) => {
+ const copied = await copyText(new URL(url, window.location.origin).toString());
+ if (copied) toast.success(t('assetLinkCopied'));
+ };
+
+ return (
+ <Tabs defaultValue="outline" className="min-h-0 flex-1 gap-0">
+ <TabsList variant="line" className="h-11 w-full shrink-0 justify-start overflow-x-auto px-3">
+ <TabsTrigger value="outline">{t('outline')}</TabsTrigger>
+ <TabsTrigger value="info">{t('info')}</TabsTrigger>
+ {canReadWorkItems && (
+ <TabsTrigger value="workItems">
+ {t('linkWorkItem.tab')}
+ {linkedIssueIds.size > 0 && (
+ <span className="ms-1 text-muted-foreground tabular-nums">{linkedIssueIds.size}</span>
+ )}
+ </TabsTrigger>
+ )}
+ <TabsTrigger value="assets">{t('assets')}</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="outline" className="min-h-0 overflow-y-auto p-3">
+ {outline.length === 0 ? (
+ <p className="px-4 py-10 text-center text-xs leading-5 text-muted-foreground">
+ {t('outlineEmpty')}
+ </p>
+ ) : (
+ <nav aria-label={t('outline')}>
+ <ol className="space-y-0.5">
+ {outline.map((item) => (
+ <li key={item.position}>
+ <button
+ type="button"
+ className="w-full truncate rounded-md py-1.5 pe-2 text-start text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ style={{ paddingInlineStart: `${8 + (item.level - 1) * 12}px` }}
+ dir="auto"
+ onClick={() => jumpToHeading(item.position)}
+ >
+ {item.text || t('untitledHeading')}
+ </button>
+ </li>
+ ))}
+ </ol>
+ </nav>
+ )}
+ </TabsContent>
+
+ <TabsContent value="info" className="min-h-0 overflow-y-auto px-4 py-5">
+ <dl className="divide-y text-xs">
+ <div className="flex items-start justify-between gap-4 py-3 first:pt-0">
+ <dt className="text-muted-foreground">{t('owner')}</dt>
+ <dd className="max-w-[60%] truncate text-end font-medium" dir="auto">
+ {document.ownerUserId
+ ? (authorNames[document.ownerUserId] ?? t('unknownAuthor'))
+ : t('unknownAuthor')}
+ </dd>
+ </div>
+ <div className="flex items-start justify-between gap-4 py-3">
+ <dt className="text-muted-foreground">{t('privacy')}</dt>
+ <dd className="font-medium">
+ {document.isPrivate ? t('privatePage') : t('projectAccess')}
+ </dd>
+ </div>
+ <div className="flex items-start justify-between gap-4 py-3">
+ <dt className="text-muted-foreground">{t('createdAt')}</dt>
+ <dd className="text-end font-medium">
+ <time dateTime={document.createdAt}>{formatDateTime(document.createdAt)}</time>
+ </dd>
+ </div>
+ <div className="flex items-start justify-between gap-4 py-3">
+ <dt className="text-muted-foreground">{t('updatedAt')}</dt>
+ <dd className="text-end font-medium">
+ <time dateTime={document.updatedAt}>{formatDateTime(document.updatedAt)}</time>
+ </dd>
+ </div>
+ <div className="flex items-start justify-between gap-4 py-3">
+ <dt className="text-muted-foreground">{t('version')}</dt>
+ <dd className="font-mono font-medium">{document.version}</dd>
+ </div>
+ </dl>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="mt-5 w-full"
+ onClick={onOpenHistory}
+ >
+ <History />
+ {t('versionHistory')}
+ </Button>
+ </TabsContent>
+
+ {canReadWorkItems && (
+ <TabsContent value="workItems" className="min-h-0 overflow-y-auto p-3">
+ <div className="mb-3 flex items-center justify-between gap-3 px-1">
+ <p className="text-xs leading-4 text-muted-foreground">
+ {t('linkWorkItem.description')}
+ </p>
+ {canLinkWorkItems && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={linkIssue.isPending}
+ onClick={() => setIssuePickerOpen(true)}
+ >
+ <Plus />
+ {t('linkWorkItem.add')}
+ </Button>
+ )}
+ </div>
+
+ {issueLinks.isLoading ? (
+ <div className="space-y-1.5" aria-hidden>
+ <Skeleton className="h-14 w-full" />
+ <Skeleton className="h-14 w-full" />
+ </div>
+ ) : issueLinks.isError ? (
+ <button
+ type="button"
+ className="w-full rounded-md border border-dashed px-3 py-6 text-xs text-muted-foreground hover:text-foreground"
+ onClick={() => void issueLinks.refetch()}
+ >
+ {t('linkWorkItem.loadFailed')}
+ </button>
+ ) : issueLinks.data?.length ? (
+ <ul className="space-y-1.5">
+ {issueLinks.data.map((link) => {
+ const removing =
+ unlinkIssue.isPending && unlinkIssue.variables?.issueId === link.issueId;
+ return (
+ <li
+ key={link.issueId}
+ className="group flex items-center gap-2 rounded-lg border bg-card/40 px-2.5 py-2"
+ >
+ <Link
+ href={issuePath(projectKey, link.sequenceNumber)}
+ className="flex min-w-0 flex-1 items-center gap-2 rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <span className="grid size-7 shrink-0 place-items-center rounded-md border bg-muted/30">
+ <Hash className="size-3.5" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium" dir="auto">
+ {link.title}
+ </span>
+ <span className="mt-0.5 block font-mono text-[11px] text-muted-foreground">
+ {link.identifier}
+ </span>
+ </span>
+ {link.archived && <ArchivedBadge />}
+ </Link>
+ {canLinkWorkItems && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground opacity-100 hover:text-destructive sm:opacity-0 sm:group-focus-within:opacity-100 sm:group-hover:opacity-100"
+ aria-label={t('linkWorkItem.remove', { identifier: link.identifier })}
+ disabled={unlinkIssue.isPending}
+ onClick={() =>
+ unlinkIssue.mutate({ documentId: document.id, issueId: link.issueId })
+ }
+ >
+ {removing ? <Loader2 className="animate-spin" /> : <X />}
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <div className="rounded-lg border border-dashed px-4 py-8 text-center">
+ <Link2 className="mx-auto size-5 text-muted-foreground" />
+ <p className="mt-2 text-xs text-muted-foreground">{t('linkWorkItem.empty')}</p>
+ </div>
+ )}
+ </TabsContent>
+ )}
+
+ <TabsContent value="assets" className="min-h-0 overflow-y-auto p-3">
+ <div className="mb-3 flex items-center justify-between gap-3 px-1">
+ <p className="text-xs leading-4 text-muted-foreground">{t('assetsDescription')}</p>
+ {canUpload && (
+ <>
+ <input
+ ref={fileInput}
+ className="sr-only"
+ type="file"
+ aria-label={t('uploadAsset')}
+ disabled={upload.isPending}
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.currentTarget.value = '';
+ if (file) upload.mutate(file);
+ }}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={upload.isPending}
+ onClick={() => fileInput.current?.click()}
+ >
+ {upload.isPending ? <Loader2 className="animate-spin" /> : <Upload />}
+ {t('upload')}
+ </Button>
+ </>
+ )}
+ </div>
+
+ {assets.isLoading ? (
+ <div className="space-y-1.5" aria-hidden>
+ <Skeleton className="h-14 w-full" />
+ <Skeleton className="h-14 w-full" />
+ </div>
+ ) : assets.isError ? (
+ <div className="py-10 text-center" role="alert">
+ <p className="text-xs text-muted-foreground">{t('assetsLoadFailed')}</p>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="mt-2"
+ onClick={() => void assets.refetch()}
+ >
+ <RefreshCw />
+ {t('reload')}
+ </Button>
+ </div>
+ ) : assets.data?.length ? (
+ <ul className="divide-y">
+ {assets.data.map((asset) => {
+ const isImage = asset.contentType.startsWith('image/');
+ const deleting = remove.isPending && remove.variables === asset.id;
+ return (
+ <li key={asset.id} className="group flex items-center gap-2 py-2 first:pt-0">
+ {isImage ? (
+ // eslint-disable-next-line @next/next/no-img-element -- authenticated assets cannot use Next's public image optimizer.
+ <img
+ src={asset.url}
+ alt=""
+ className="size-9 shrink-0 rounded-md border object-cover"
+ />
+ ) : (
+ <span className="grid size-9 shrink-0 place-items-center rounded-md border bg-muted/30">
+ <File className="size-4 text-muted-foreground" />
+ </span>
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium" dir="auto">
+ {asset.filename}
+ </span>
+ <span className="mt-0.5 block text-[11px] text-muted-foreground">
+ {formatBytes(asset.sizeBytes)}
+ </span>
+ </span>
+ <span className="flex shrink-0 opacity-100 sm:opacity-0 sm:group-focus-within:opacity-100 sm:group-hover:opacity-100">
+ {editor?.isEditable && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('insertAsset', { name: asset.filename })}
+ onClick={() => insertAsset(asset)}
+ >
+ {isImage ? <FileImage /> : <Plus />}
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('copyAssetLink', { name: asset.filename })}
+ onClick={() => void copyAsset(asset.url)}
+ >
+ <Clipboard />
+ </Button>
+ {canDeleteAssets && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="text-destructive"
+ disabled={remove.isPending}
+ aria-label={t('deleteAsset', { name: asset.filename })}
+ onClick={() => {
+ if (window.confirm(t('deleteAssetConfirm', { name: asset.filename }))) {
+ remove.mutate(asset.id);
+ }
+ }}
+ >
+ {deleting ? <Loader2 className="animate-spin" /> : <Trash2 />}
+ </Button>
+ )}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="px-4 py-10 text-center text-xs text-muted-foreground">{t('noAssets')}</p>
+ )}
+ </TabsContent>
+
+ {issuePickerOpen && (
+ <IssuePickerDialog
+ projectKey={projectKey}
+ title={t('linkWorkItem.selectIssue')}
+ prompt={t('linkWorkItem.searchIssues')}
+ exclude={(hit) => linkedIssueIds.has(hit.id)}
+ onClose={() => setIssuePickerOpen(false)}
+ onPick={(hit) => {
+ void linkIssue
+ .mutateAsync({ documentId: document.id, issueId: hit.id })
+ .then(() => setIssuePickerOpen(false))
+ .catch(() => undefined);
+ }}
+ />
+ )}
+ </Tabs>
+ );
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+async function copyText(value: string): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(value);
+ return true;
+ } catch {
+ const input = window.document.createElement('textarea');
+ input.value = value;
+ input.style.position = 'fixed';
+ input.style.opacity = '0';
+ try {
+ window.document.body.append(input);
+ input.select();
+ return window.document.execCommand('copy');
+ } catch {
+ return false;
+ } finally {
+ input.remove();
+ }
+ }
+}
diff --git a/apps/web/src/features/documents/components/DocumentTextColorMenu.tsx b/apps/web/src/features/documents/components/DocumentTextColorMenu.tsx
new file mode 100644
index 00000000..da3d4480
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentTextColorMenu.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import type { Editor } from '@tiptap/react';
+import { Check, Palette } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+
+const COLORS = [
+ { value: null, surface: 'bg-foreground', ink: 'text-background' },
+ { value: '#dc2626', surface: 'bg-red-600', ink: 'text-white' },
+ { value: '#ea580c', surface: 'bg-orange-600', ink: 'text-white' },
+ { value: '#ca8a04', surface: 'bg-yellow-600', ink: 'text-white' },
+ { value: '#16a34a', surface: 'bg-green-600', ink: 'text-white' },
+ { value: '#2563eb', surface: 'bg-blue-600', ink: 'text-white' },
+ { value: '#7c3aed', surface: 'bg-violet-600', ink: 'text-white' },
+ { value: '#db2777', surface: 'bg-pink-600', ink: 'text-white' },
+] as const;
+
+export default function DocumentTextColorMenu({ editor }: { editor: Editor }) {
+ const t = useTranslations('documents.toolbar');
+ const textColor =
+ (editor.getAttributes('textStyle').color as string | undefined)?.toLowerCase() ?? null;
+ const highlightColor =
+ (editor.getAttributes('highlight').color as string | undefined)?.toLowerCase() ?? null;
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="relative size-8 rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground"
+ aria-label={t('textColor')}
+ >
+ <Palette className="size-4 stroke-[1.75]" />
+ <span
+ className="absolute inset-x-2 bottom-1 h-0.5 rounded-full bg-current"
+ style={textColor ? { backgroundColor: textColor } : undefined}
+ />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-56 space-y-3 rounded-xl p-3 shadow-xl">
+ <div>
+ <p className="mb-2 text-[11px] font-medium tracking-wide text-muted-foreground">
+ {t('textColor')}
+ </p>
+ <div className="grid grid-cols-8 gap-1" aria-label={t('textColor')}>
+ {COLORS.map((color, index) => (
+ <button
+ key={color.value ?? 'default'}
+ type="button"
+ className={cn(
+ 'grid size-6 place-items-center rounded-full border border-black/10 ring-offset-2 ring-offset-popover transition-transform outline-none hover:scale-110 focus-visible:ring-2 focus-visible:ring-ring',
+ color.surface,
+ color.ink,
+ )}
+ aria-label={color.value ? t('colorNumber', { number: index }) : t('defaultColor')}
+ aria-pressed={textColor === color.value}
+ onClick={() => {
+ if (color.value) editor.chain().focus().setColor(color.value).run();
+ else editor.chain().focus().unsetColor().run();
+ }}
+ >
+ {textColor === color.value && <Check className="size-3.5 stroke-[2.5]" />}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="border-t pt-3">
+ <p className="mb-2 text-[11px] font-medium tracking-wide text-muted-foreground">
+ {t('backgroundColor')}
+ </p>
+ <div className="grid grid-cols-8 gap-1" aria-label={t('backgroundColor')}>
+ {COLORS.map((color, index) => (
+ <button
+ key={color.value ?? 'default'}
+ type="button"
+ className="grid size-6 place-items-center rounded-md border border-border/70 bg-background p-0.5 ring-offset-2 ring-offset-popover transition-transform outline-none hover:scale-110 focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={color.value ? t('colorNumber', { number: index }) : t('noBackground')}
+ aria-pressed={highlightColor === color.value}
+ onClick={() => {
+ if (color.value)
+ editor.chain().focus().setHighlight({ color: color.value }).run();
+ else editor.chain().focus().unsetHighlight().run();
+ }}
+ >
+ <span
+ className={cn(
+ 'grid size-full place-items-center rounded-[3px] opacity-55',
+ color.surface,
+ color.ink,
+ )}
+ >
+ {highlightColor === color.value && <Check className="size-3 stroke-[2.5]" />}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentToolbar.tsx b/apps/web/src/features/documents/components/DocumentToolbar.tsx
new file mode 100644
index 00000000..04e8330d
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentToolbar.tsx
@@ -0,0 +1,245 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import type { Editor } from '@tiptap/react';
+import {
+ AlignCenter,
+ AlignLeft,
+ AlignRight,
+ Bold,
+ CheckSquare2,
+ Code,
+ Italic,
+ List,
+ ListOrdered,
+ Minus,
+ Quote,
+ Redo2,
+ SquareCode,
+ Strikethrough,
+ Table2,
+ Underline,
+ Undo2,
+} from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import DocumentBlockTypeMenu from './DocumentBlockTypeMenu';
+import DocumentImageMenu from './DocumentImageMenu';
+import DocumentTextColorMenu from './DocumentTextColorMenu';
+import DocumentToolbarButton from './DocumentToolbarButton';
+
+export default function DocumentToolbar({
+ editor,
+ projectKey,
+ documentId,
+ canUpload,
+}: {
+ editor: Editor | null;
+ projectKey: string;
+ documentId: number;
+ canUpload: boolean;
+}) {
+ const t = useTranslations('documents.toolbar');
+ const [, renderSelection] = useState(0);
+
+ useEffect(() => {
+ if (!editor) return;
+ const refresh = () => renderSelection((revision) => revision + 1);
+ editor.on('transaction', refresh);
+ editor.on('selectionUpdate', refresh);
+ return () => {
+ editor.off('transaction', refresh);
+ editor.off('selectionUpdate', refresh);
+ };
+ }, [editor]);
+
+ if (!editor) {
+ return (
+ <div className="flex h-12 items-center gap-2 px-3 md:px-5" aria-hidden>
+ <div className="h-8 w-28 animate-pulse rounded-lg bg-muted/60" />
+ <div className="h-8 w-48 animate-pulse rounded-lg bg-muted/40" />
+ </div>
+ );
+ }
+
+ const textActions = [
+ {
+ label: t('bold'),
+ active: editor.isActive('bold'),
+ icon: Bold,
+ run: () => editor.chain().focus().toggleBold().run(),
+ },
+ {
+ label: t('italic'),
+ active: editor.isActive('italic'),
+ icon: Italic,
+ run: () => editor.chain().focus().toggleItalic().run(),
+ },
+ {
+ label: t('underline'),
+ active: editor.isActive('underline'),
+ icon: Underline,
+ run: () => editor.chain().focus().toggleUnderline().run(),
+ },
+ {
+ label: t('strike'),
+ active: editor.isActive('strike'),
+ icon: Strikethrough,
+ run: () => editor.chain().focus().toggleStrike().run(),
+ },
+ {
+ label: t('inlineCode'),
+ active: editor.isActive('code'),
+ icon: Code,
+ run: () => editor.chain().focus().toggleCode().run(),
+ },
+ ];
+
+ const blockActions = [
+ {
+ label: t('bulletList'),
+ active: editor.isActive('bulletList'),
+ icon: List,
+ run: () => editor.chain().focus().toggleBulletList().run(),
+ },
+ {
+ label: t('numberedList'),
+ active: editor.isActive('orderedList'),
+ icon: ListOrdered,
+ run: () => editor.chain().focus().toggleOrderedList().run(),
+ },
+ {
+ label: t('todoList'),
+ active: editor.isActive('taskList'),
+ icon: CheckSquare2,
+ run: () => editor.chain().focus().toggleTaskList().run(),
+ },
+ {
+ label: t('quote'),
+ active: editor.isActive('blockquote'),
+ icon: Quote,
+ run: () => editor.chain().focus().toggleBlockquote().run(),
+ },
+ {
+ label: t('codeBlock'),
+ active: editor.isActive('codeBlock'),
+ icon: SquareCode,
+ run: () => editor.chain().focus().toggleCodeBlock().run(),
+ },
+ ];
+
+ const alignmentActions = [
+ {
+ label: t('alignLeft'),
+ active: editor.isActive({ textAlign: 'left' }),
+ icon: AlignLeft,
+ run: () => editor.chain().focus().setTextAlign('left').run(),
+ },
+ {
+ label: t('alignCenter'),
+ active: editor.isActive({ textAlign: 'center' }),
+ icon: AlignCenter,
+ run: () => editor.chain().focus().setTextAlign('center').run(),
+ },
+ {
+ label: t('alignRight'),
+ active: editor.isActive({ textAlign: 'right' }),
+ icon: AlignRight,
+ run: () => editor.chain().focus().setTextAlign('right').run(),
+ },
+ ];
+
+ return (
+ <div
+ className="flex h-12 min-w-0 [scrollbar-width:none] items-center gap-1 overflow-x-auto px-3 md:px-5 [&::-webkit-scrollbar]:hidden"
+ role="toolbar"
+ aria-label={t('label')}
+ >
+ <div className="me-1 flex shrink-0 items-center border-e pe-2">
+ <DocumentBlockTypeMenu editor={editor} />
+ </div>
+
+ <div className="flex shrink-0 items-center gap-0.5">
+ {textActions.map((action) => (
+ <DocumentToolbarButton
+ key={action.label}
+ label={action.label}
+ active={action.active}
+ onPress={action.run}
+ >
+ <action.icon />
+ </DocumentToolbarButton>
+ ))}
+ <DocumentTextColorMenu editor={editor} />
+ </div>
+
+ <div className="mx-1 flex shrink-0 items-center gap-0.5 border-s ps-2">
+ {blockActions.map((action) => (
+ <DocumentToolbarButton
+ key={action.label}
+ label={action.label}
+ active={action.active}
+ onPress={action.run}
+ >
+ <action.icon />
+ </DocumentToolbarButton>
+ ))}
+ <DocumentToolbarButton
+ label={t('divider')}
+ onPress={() => editor.chain().focus().setHorizontalRule().run()}
+ >
+ <Minus />
+ </DocumentToolbarButton>
+ </div>
+
+ <div className="me-1 flex shrink-0 items-center gap-0.5 border-e pe-2">
+ <DocumentToolbarButton
+ label={t('table')}
+ active={editor.isActive('table')}
+ onPress={() => {
+ if (editor.isActive('table')) editor.chain().focus().deleteTable().run();
+ else
+ editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();
+ }}
+ >
+ <Table2 />
+ </DocumentToolbarButton>
+ <DocumentImageMenu
+ editor={editor}
+ projectKey={projectKey}
+ documentId={documentId}
+ canUpload={canUpload}
+ />
+ </div>
+
+ <div className="flex shrink-0 items-center gap-0.5">
+ {alignmentActions.map((action) => (
+ <DocumentToolbarButton
+ key={action.label}
+ label={action.label}
+ active={action.active}
+ onPress={action.run}
+ >
+ <action.icon />
+ </DocumentToolbarButton>
+ ))}
+ </div>
+
+ <div className="ms-auto flex shrink-0 items-center gap-0.5 border-s ps-2">
+ <DocumentToolbarButton
+ label={t('undo')}
+ disabled={!editor.can().chain().focus().undo().run()}
+ onPress={() => editor.chain().focus().undo().run()}
+ >
+ <Undo2 />
+ </DocumentToolbarButton>
+ <DocumentToolbarButton
+ label={t('redo')}
+ disabled={!editor.can().chain().focus().redo().run()}
+ onPress={() => editor.chain().focus().redo().run()}
+ >
+ <Redo2 />
+ </DocumentToolbarButton>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentToolbarButton.tsx b/apps/web/src/features/documents/components/DocumentToolbarButton.tsx
new file mode 100644
index 00000000..1b3609c3
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentToolbarButton.tsx
@@ -0,0 +1,40 @@
+import type { ReactNode } from 'react';
+import { cn } from '@/lib/utils';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+
+export default function DocumentToolbarButton({
+ label,
+ active = false,
+ disabled = false,
+ onPress,
+ children,
+}: {
+ label: string;
+ active?: boolean;
+ disabled?: boolean;
+ onPress: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label={label}
+ aria-pressed={active}
+ className={cn(
+ 'relative grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground transition-[background-color,color,transform] duration-150 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background active:scale-[0.96] disabled:pointer-events-none disabled:opacity-30 [&_svg]:size-4 [&_svg]:stroke-[1.75]',
+ active &&
+ 'bg-primary/10 text-primary after:absolute after:inset-x-2 after:bottom-0.5 after:h-px after:rounded-full after:bg-primary/70 hover:bg-primary/15 hover:text-primary',
+ )}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={onPress}
+ >
+ {children}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentTree.tsx b/apps/web/src/features/documents/components/DocumentTree.tsx
new file mode 100644
index 00000000..fb663247
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentTree.tsx
@@ -0,0 +1,239 @@
+'use client';
+
+import { useMemo, useState } from 'react';
+import {
+ closestCenter,
+ DndContext,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ type DragEndEvent,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { FilePlus2, Plus } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import { projectedDocumentMove } from '../utils/documentMove';
+import SortableDocumentRow from './SortableDocumentRow';
+
+export type DocumentSort = 'position' | 'title' | 'created' | 'updated';
+
+export default function DocumentTree({
+ projectKey,
+ documents,
+ activeId,
+ searching,
+ sortBy,
+ sortDirection,
+ canCreate,
+ reorderEnabled,
+ favoritePending,
+ onCreate,
+ onMove,
+ onFavoriteChange,
+}: {
+ projectKey: string;
+ documents: ProjectDocumentSummary[];
+ activeId: number | null;
+ searching: boolean;
+ sortBy: DocumentSort;
+ sortDirection: 'asc' | 'desc';
+ canCreate: boolean;
+ reorderEnabled: boolean;
+ favoritePending: boolean;
+ onCreate: (parentId: number | null) => void;
+ onMove: (input: {
+ documentId: number;
+ version: number;
+ parentId: number | null;
+ position: number;
+ previousSiblingId: number | null;
+ nextSiblingId: number | null;
+ }) => void;
+ onFavoriteChange: (documentId: number, isFavorite: boolean) => void;
+}) {
+ const t = useTranslations('documents');
+ const [collapsed, setCollapsed] = useState<Set<number>>(new Set());
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+ const byId = useMemo(() => new Map(documents.map((item) => [item.id, item])), [documents]);
+ const byParent = useMemo(() => {
+ const groups = new Map<number | null, ProjectDocumentSummary[]>();
+ for (const item of documents) {
+ const parentId = item.parentId !== null && byId.has(item.parentId) ? item.parentId : null;
+ const siblings = groups.get(parentId) ?? [];
+ siblings.push(item);
+ groups.set(parentId, siblings);
+ }
+
+ for (const siblings of groups.values()) {
+ siblings.sort((a, b) => {
+ let result = a.position - b.position || a.id - b.id;
+ if (sortBy === 'title') result = a.title.localeCompare(b.title) || a.id - b.id;
+ if (sortBy === 'created') {
+ result = Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id - b.id;
+ }
+ if (sortBy === 'updated') {
+ result = Date.parse(a.updatedAt) - Date.parse(b.updatedAt) || a.id - b.id;
+ }
+ return sortBy !== 'position' && sortDirection === 'desc' ? -result : result;
+ });
+ }
+ return groups;
+ }, [byId, documents, sortBy, sortDirection]);
+ const ordered = useMemo(() => {
+ const result: ProjectDocumentSummary[] = [];
+ const visited = new Set<number>();
+ const visit = (parentId: number | null) => {
+ for (const item of byParent.get(parentId) ?? []) {
+ if (visited.has(item.id)) continue;
+ visited.add(item.id);
+ result.push(item);
+ visit(item.id);
+ }
+ };
+ visit(null);
+ for (const item of documents) {
+ if (!visited.has(item.id)) result.push(item);
+ }
+ return result;
+ }, [byParent, documents]);
+ const visibleIds = useMemo(() => {
+ if (searching) return ordered.map((item) => item.id);
+ const result: number[] = [];
+ const visit = (parentId: number | null) => {
+ for (const item of byParent.get(parentId) ?? []) {
+ result.push(item.id);
+ if (!collapsed.has(item.id)) visit(item.id);
+ }
+ };
+ visit(null);
+ return result;
+ }, [byParent, collapsed, ordered, searching]);
+
+ const toggle = (documentId: number) => {
+ setCollapsed((current) => {
+ const next = new Set(current);
+ if (next.has(documentId)) next.delete(documentId);
+ else next.add(documentId);
+ return next;
+ });
+ };
+
+ function renderDocument(item: ProjectDocumentSummary, depth: number, nested: boolean) {
+ const children = byParent.get(item.id) ?? [];
+ const isCollapsed = collapsed.has(item.id);
+ return (
+ <SortableDocumentRow
+ key={item.id}
+ projectKey={projectKey}
+ document={item}
+ depth={depth}
+ nested={nested}
+ active={activeId === item.id}
+ collapsed={isCollapsed}
+ hasChildren={children.length > 0}
+ canCreate={canCreate}
+ reorderEnabled={reorderEnabled}
+ favoritePending={favoritePending}
+ onToggle={() => toggle(item.id)}
+ onCreate={() => onCreate(item.id)}
+ onFavoriteChange={() => onFavoriteChange(item.id, !item.isFavorite)}
+ >
+ {nested && !isCollapsed && children.length > 0 && renderRows(item.id, depth + 1)}
+ </SortableDocumentRow>
+ );
+ }
+
+ function renderRows(parentId: number | null, depth: number) {
+ return (
+ <ul role={depth === 0 ? 'tree' : 'group'} className={depth === 0 ? 'space-y-px' : undefined}>
+ {(byParent.get(parentId) ?? []).map((item) => renderDocument(item, depth, true))}
+ </ul>
+ );
+ }
+
+ if (documents.length === 0) {
+ return (
+ <div className="flex min-h-64 flex-col items-center justify-center px-4 text-center">
+ <div className="mb-3 grid size-10 place-items-center rounded-full bg-muted text-muted-foreground">
+ <FilePlus2 className="size-4" />
+ </div>
+ <p className="text-sm font-medium">{t('noResults')}</p>
+ {canCreate && !searching && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="mt-2"
+ onClick={() => onCreate(null)}
+ >
+ <Plus />
+ {t('newDocument')}
+ </Button>
+ )}
+ </div>
+ );
+ }
+
+ const dragEnd = ({ active, over, delta }: DragEndEvent) => {
+ if (!reorderEnabled || !over || active.id === over.id) return;
+ const source = byId.get(Number(active.id));
+ const target = byId.get(Number(over.id));
+ if (!source || !target) return;
+ const projected = projectedDocumentMove({
+ source,
+ target,
+ deltaX:
+ typeof document !== 'undefined' && document.documentElement.dir === 'rtl'
+ ? -delta.x
+ : delta.x,
+ ordered,
+ byParent,
+ byId,
+ });
+ if (projected) onMove({ documentId: source.id, version: source.version, ...projected });
+ };
+
+ return (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={dragEnd}
+ accessibility={{
+ screenReaderInstructions: { draggable: t('dragInstructions') },
+ announcements: {
+ onDragStart: ({ active }) =>
+ t('dragStarted', { title: byId.get(Number(active.id))?.title ?? '' }),
+ onDragOver: ({ over }) =>
+ over ? t('dragOver', { title: byId.get(Number(over.id))?.title ?? '' }) : undefined,
+ onDragEnd: ({ over }) =>
+ over
+ ? t('dragEnded', { title: byId.get(Number(over.id))?.title ?? '' })
+ : t('dragCanceled'),
+ onDragCancel: () => t('dragCanceled'),
+ },
+ }}
+ >
+ <SortableContext items={visibleIds} strategy={verticalListSortingStrategy}>
+ <nav aria-label={t('treeLabel')}>
+ {searching ? (
+ <ul role="tree" className="space-y-px">
+ {ordered.map((item) => renderDocument(item, 0, false))}
+ </ul>
+ ) : (
+ renderRows(null, 0)
+ )}
+ </nav>
+ </SortableContext>
+ </DndContext>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentsIndex.tsx b/apps/web/src/features/documents/components/DocumentsIndex.tsx
new file mode 100644
index 00000000..844b64eb
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentsIndex.tsx
@@ -0,0 +1,352 @@
+'use client';
+
+import { useState } from 'react';
+import {
+ ArrowDown,
+ ArrowUp,
+ ArrowUpDown,
+ BookOpenText,
+ Check,
+ LoaderCircle,
+ Plus,
+ RefreshCw,
+ Search,
+ SlidersHorizontal,
+} from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Input } from '@/components/ui/input';
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+import { useMoveDocument, useSetDocumentFavorite } from '../services/documents.service';
+import { DOCUMENT_LIST_TABS, type DocumentListTab } from '../utils/documentList';
+import DocumentTree, { type DocumentSort } from './DocumentTree';
+
+const SORTS = [
+ 'position',
+ 'title',
+ 'created',
+ 'updated',
+] as const satisfies readonly DocumentSort[];
+export type { DocumentListTab } from '../utils/documentList';
+
+export default function DocumentsIndex({
+ projectKey,
+ documents,
+ tab,
+ search,
+ searching,
+ loading,
+ failed,
+ canCreate,
+ canEdit,
+ authorNames,
+ reorderSafe,
+ creating,
+ onSearchChange,
+ onTabChange,
+ onCreate,
+ onRetry,
+}: {
+ projectKey: string;
+ documents: ProjectDocumentSummary[];
+ tab: DocumentListTab;
+ search: string;
+ searching: boolean;
+ loading: boolean;
+ failed: boolean;
+ canCreate: boolean;
+ canEdit: boolean;
+ authorNames: Record<string, string>;
+ reorderSafe: boolean;
+ creating: boolean;
+ onSearchChange: (value: string) => void;
+ onTabChange: (tab: DocumentListTab) => void;
+ onCreate: (parentId: number | null) => void;
+ onRetry: () => void;
+}) {
+ const t = useTranslations('documents');
+ const move = useMoveDocument(projectKey);
+ const favorite = useSetDocumentFavorite(projectKey);
+ const [sort, setSort] = useState<DocumentSort>('position');
+ const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
+ const [creatorId, setCreatorId] = useState<string | null>(null);
+ const [createdRange, setCreatedRange] = useState<'all' | 'today' | 'week' | 'month'>('all');
+
+ const creatorIds = Array.from(
+ new Set(
+ documents.flatMap((document) => (document.createdByUserId ? [document.createdByUserId] : [])),
+ ),
+ ).sort((a, b) => (authorNames[a] ?? a).localeCompare(authorNames[b] ?? b));
+ const now = Date.now();
+ const filteredDocuments = documents.filter((document) => {
+ if (creatorId !== null && document.createdByUserId !== creatorId) return false;
+ if (createdRange === 'all') return true;
+
+ const age = now - Date.parse(document.createdAt);
+ const limit =
+ createdRange === 'today'
+ ? 24 * 60 * 60 * 1000
+ : createdRange === 'week'
+ ? 7 * 24 * 60 * 60 * 1000
+ : 30 * 24 * 60 * 60 * 1000;
+ return age >= 0 && age <= limit;
+ });
+ const filteredIds = new Set(filteredDocuments.map((document) => document.id));
+ const displayDocuments = filteredDocuments.map((document) =>
+ document.parentId !== null && !filteredIds.has(document.parentId)
+ ? { ...document, parentId: null }
+ : document,
+ );
+ const filterCount = Number(creatorId !== null) + Number(createdRange !== 'all');
+ const sortLabel = {
+ position: t('manualOrder'),
+ title: t('nameOrder'),
+ updated: t('updatedOrder'),
+ created: t('createdOrder'),
+ }[sort];
+ const tabLabel = (value: DocumentListTab) =>
+ value === 'favorites'
+ ? t('favoritePages')
+ : value === 'public'
+ ? t('publicPages')
+ : value === 'private'
+ ? t('privatePages')
+ : t('archivedPages');
+
+ return (
+ <main className="flex min-w-0 flex-1 flex-col overflow-hidden bg-background">
+ <header className="shrink-0 border-b bg-background/95 px-4 backdrop-blur md:px-6">
+ <div className="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-4">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <div className="grid size-7 shrink-0 place-items-center rounded-md bg-foreground text-background">
+ <BookOpenText className="size-3.5" />
+ </div>
+ <div className="flex min-w-0 items-baseline gap-2">
+ <h1 className="truncate text-sm font-semibold tracking-[-0.01em]">{t('title')}</h1>
+ {!loading && (
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {documents.length}
+ </span>
+ )}
+ </div>
+ </div>
+ {canCreate && (
+ <Button
+ type="button"
+ size="sm"
+ className="h-8 px-2.5 shadow-none"
+ disabled={creating}
+ onClick={() => onCreate(null)}
+ >
+ {creating ? <LoaderCircle className="animate-spin" /> : <Plus />}
+ <span className="hidden sm:inline">{t('newDocument')}</span>
+ </Button>
+ )}
+ </div>
+ </header>
+
+ <div className="shrink-0 border-b px-4 md:px-6">
+ <div
+ className="mx-auto flex w-full max-w-6xl items-center gap-6 overflow-x-auto"
+ role="tablist"
+ >
+ {DOCUMENT_LIST_TABS.map((option) => (
+ <button
+ key={option}
+ type="button"
+ role="tab"
+ aria-selected={tab === option}
+ className={cn(
+ 'relative h-10 shrink-0 px-0.5 text-[13px] font-medium text-muted-foreground transition-colors outline-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:origin-center after:scale-x-0 after:bg-foreground after:transition-transform hover:text-foreground focus-visible:rounded-sm focus-visible:ring-2 focus-visible:ring-ring',
+ tab === option && 'text-foreground after:scale-x-100',
+ )}
+ onClick={() => onTabChange(option)}
+ >
+ {tabLabel(option)}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="shrink-0 px-4 py-3 md:px-6">
+ <div className="mx-auto flex w-full max-w-6xl items-center gap-1.5">
+ <div className="relative min-w-0 flex-1 sm:max-w-md">
+ <Search className="pointer-events-none absolute start-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ className="h-8 border-transparent bg-muted/55 ps-8 text-[13px] shadow-none hover:bg-muted focus-visible:bg-background"
+ placeholder={t('search')}
+ aria-label={t('search')}
+ onChange={(event) => onSearchChange(event.target.value)}
+ />
+ </div>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-8 px-2 text-muted-foreground"
+ aria-label={t('sort')}
+ >
+ <ArrowUpDown />
+ <span className="hidden md:inline">{sortLabel}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ {SORTS.map((option) => (
+ <DropdownMenuItem key={option} onSelect={() => setSort(option)}>
+ <Check className={cn('me-1', option !== sort && 'invisible')} />
+ {option === 'position'
+ ? t('manualOrder')
+ : option === 'title'
+ ? t('nameOrder')
+ : option === 'created'
+ ? t('createdOrder')
+ : t('updatedOrder')}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ disabled={sort === 'position'}
+ aria-label={sortDirection === 'asc' ? t('sortDescending') : t('sortAscending')}
+ onClick={() => setSortDirection((value) => (value === 'asc' ? 'desc' : 'asc'))}
+ >
+ {sortDirection === 'asc' ? <ArrowUp /> : <ArrowDown />}
+ </Button>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant={filterCount > 0 ? 'secondary' : 'ghost'}
+ size="sm"
+ className="h-8 px-2 text-muted-foreground"
+ aria-label={t('filters')}
+ >
+ <SlidersHorizontal />
+ <span className="hidden md:inline">{t('filters')}</span>
+ {filterCount > 0 && (
+ <span className="min-w-4 rounded-full bg-foreground px-1 text-center text-[10px] leading-4 text-background tabular-nums">
+ {filterCount}
+ </span>
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>{t('createdBy')}</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-56">
+ <DropdownMenuItem onSelect={() => setCreatorId(null)}>
+ <Check className={cn('me-1', creatorId !== null && 'invisible')} />
+ {t('anyone')}
+ </DropdownMenuItem>
+ {creatorIds.map((id) => (
+ <DropdownMenuItem key={id} onSelect={() => setCreatorId(id)}>
+ <Check className={cn('me-1', creatorId !== id && 'invisible')} />
+ <span className="truncate" dir="auto">
+ {authorNames[id] ?? t('unknownAuthor')}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>{t('createdDate')}</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ {(['all', 'today', 'week', 'month'] as const).map((range) => (
+ <DropdownMenuItem key={range} onSelect={() => setCreatedRange(range)}>
+ <Check className={cn('me-1', createdRange !== range && 'invisible')} />
+ {t(range)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ {filterCount > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ setCreatorId(null);
+ setCreatedRange('all');
+ }}
+ >
+ {t('clearFilters')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-10 md:px-6">
+ <div className="mx-auto w-full max-w-6xl">
+ {loading ? (
+ <div className="space-y-1 py-1" aria-hidden>
+ <Skeleton className="h-9 w-full rounded-md" />
+ <Skeleton className="h-9 w-[92%] rounded-md" />
+ <Skeleton className="h-9 w-[85%] rounded-md" />
+ </div>
+ ) : failed ? (
+ <div className="flex min-h-56 flex-col items-center justify-center text-center">
+ <div className="mb-3 grid size-9 place-items-center rounded-full bg-muted text-muted-foreground">
+ <RefreshCw className="size-4" />
+ </div>
+ <p className="text-sm font-medium">{t('loadFailed')}</p>
+ <Button className="mt-3" variant="outline" size="sm" onClick={onRetry}>
+ <RefreshCw />
+ {t('reload')}
+ </Button>
+ </div>
+ ) : (
+ <DocumentTree
+ projectKey={projectKey}
+ documents={displayDocuments}
+ activeId={null}
+ searching={searching}
+ sortBy={sort}
+ sortDirection={sortDirection}
+ canCreate={canCreate}
+ reorderEnabled={
+ canEdit &&
+ tab !== 'favorites' &&
+ tab !== 'archived' &&
+ !searching &&
+ sort === 'position' &&
+ filterCount === 0 &&
+ reorderSafe &&
+ !move.isPending
+ }
+ favoritePending={favorite.isPending}
+ onCreate={onCreate}
+ onMove={(input) => move.mutate(input)}
+ onFavoriteChange={(documentId, isFavorite) =>
+ favorite.mutate({ documentId, isFavorite })
+ }
+ />
+ )}
+ </div>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/documents/components/SortableDocumentRow.tsx b/apps/web/src/features/documents/components/SortableDocumentRow.tsx
new file mode 100644
index 00000000..647940c6
--- /dev/null
+++ b/apps/web/src/features/documents/components/SortableDocumentRow.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import type { ReactNode } from 'react';
+import { useSortable } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import { ChevronRight, FileText, GripVertical, LockKeyhole, Plus, Star } from 'lucide-react';
+import Link from 'next/link';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import { documentPath } from '@/utils/paths';
+
+export default function SortableDocumentRow({
+ projectKey,
+ document,
+ depth,
+ active,
+ collapsed,
+ hasChildren,
+ nested,
+ canCreate,
+ reorderEnabled,
+ favoritePending,
+ children,
+ onToggle,
+ onCreate,
+ onFavoriteChange,
+}: {
+ projectKey: string;
+ document: ProjectDocumentSummary;
+ depth: number;
+ active: boolean;
+ collapsed: boolean;
+ hasChildren: boolean;
+ nested: boolean;
+ canCreate: boolean;
+ reorderEnabled: boolean;
+ favoritePending: boolean;
+ children?: ReactNode;
+ onToggle: () => void;
+ onCreate: () => void;
+ onFavoriteChange: () => void;
+}) {
+ const t = useTranslations('documents');
+ const draggable = reorderEnabled && !document.isLocked;
+ const sortable = useSortable({ id: document.id, disabled: !draggable });
+ const title = document.title.trim() || t('untitled');
+ const style = {
+ transform: CSS.Translate.toString(sortable.transform),
+ transition: sortable.transition,
+ paddingInlineStart: `${Math.min(depth, 12) * 18}px`,
+ };
+
+ return (
+ <li
+ ref={sortable.setNodeRef}
+ style={{ transform: style.transform, transition: style.transition }}
+ role="treeitem"
+ aria-level={depth + 1}
+ aria-selected={active}
+ aria-expanded={nested && hasChildren ? !collapsed : undefined}
+ className={cn(sortable.isDragging && 'relative z-20')}
+ >
+ <div style={{ paddingInlineStart: style.paddingInlineStart }}>
+ <div
+ className={cn(
+ 'group/row relative flex h-9 items-center rounded-md pe-1 text-[13px] transition-[background-color,box-shadow,opacity] duration-150 outline-none',
+ active
+ ? 'bg-accent font-medium text-accent-foreground'
+ : 'text-foreground focus-within:bg-muted/65 hover:bg-muted/65',
+ sortable.isDragging && 'bg-background opacity-90 shadow-lg ring-1 ring-border',
+ )}
+ >
+ <div className="grid size-6 shrink-0 place-items-center">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ disabled={!draggable}
+ className={cn(
+ 'size-6 cursor-grab touch-none text-muted-foreground opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100 active:cursor-grabbing',
+ !draggable && 'invisible',
+ )}
+ aria-label={t('movePage', { title })}
+ {...sortable.attributes}
+ {...sortable.listeners}
+ >
+ <GripVertical className="size-3.5" />
+ </Button>
+ </div>
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className={cn(
+ 'size-6 shrink-0 text-muted-foreground',
+ (!nested || !hasChildren) && 'invisible',
+ )}
+ aria-label={collapsed ? t('expand') : t('collapse')}
+ aria-expanded={hasChildren ? !collapsed : undefined}
+ onClick={onToggle}
+ >
+ <ChevronRight
+ className={cn(
+ 'size-3.5 transition-transform duration-150 rtl:rotate-180',
+ !collapsed && 'rotate-90 rtl:rotate-90',
+ )}
+ />
+ </Button>
+
+ <Link
+ href={documentPath(projectKey, document.id)}
+ className="flex min-w-0 flex-1 items-center gap-2 self-stretch rounded-sm pe-2 outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
+ aria-current={active ? 'page' : undefined}
+ >
+ <span
+ className="grid size-5 shrink-0 place-items-center text-sm text-muted-foreground"
+ aria-hidden
+ >
+ {document.icon ? document.icon : <FileText className="size-3.5" />}
+ </span>
+ <span className="min-w-0 flex-1 truncate" dir="auto">
+ {title}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5 text-muted-foreground">
+ {document.isPrivate && <LockKeyhole className="size-3" />}
+ </span>
+ </Link>
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ disabled={favoritePending}
+ className={cn(
+ 'size-6 shrink-0 text-muted-foreground opacity-0 transition-[color,opacity] group-focus-within/row:opacity-100 group-hover/row:opacity-100',
+ document.isFavorite &&
+ 'text-amber-500 opacity-100 hover:bg-amber-500/10 hover:text-amber-600 dark:text-amber-400 dark:hover:text-amber-300',
+ )}
+ aria-label={document.isFavorite ? t('removeFavorite') : t('addFavorite')}
+ aria-pressed={document.isFavorite}
+ onClick={onFavoriteChange}
+ >
+ <Star className={cn('size-3.5', document.isFavorite && 'fill-current')} />
+ </Button>
+
+ {canCreate && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="size-6 shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100"
+ aria-label={t('newSubpage', { title })}
+ onClick={onCreate}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ )}
+ </div>
+ </div>
+ {children}
+ </li>
+ );
+}
diff --git a/apps/web/src/features/documents/hooks/useDocumentActionGate.test.tsx b/apps/web/src/features/documents/hooks/useDocumentActionGate.test.tsx
new file mode 100644
index 00000000..f9324748
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentActionGate.test.tsx
@@ -0,0 +1,81 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { JSDOM } from 'jsdom';
+import { useDocumentActionGate } from './useDocumentActionGate';
+
+type Gate = ReturnType<typeof useDocumentActionGate>;
+
+let dom: JSDOM;
+let root: Root;
+let gate: Gate | null;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+
+function Probe() {
+ gate = useDocumentActionGate();
+ return null;
+}
+
+beforeEach(async () => {
+ originalGlobalDescriptors = new Map(
+ ['window', 'document', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'].map((name) => [
+ name,
+ Object.getOwnPropertyDescriptor(globalThis, name),
+ ]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>');
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ const { createRoot } = await import('react-dom/client');
+ const element = document.querySelector('#root');
+ assert.ok(element);
+ root = createRoot(element);
+ gate = null;
+ act(() => root.render(<Probe />));
+ assert.ok(gate);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originalGlobalDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('useDocumentActionGate', () => {
+ it('freezes editing for the whole versioned action and rejects a concurrent action', async () => {
+ let resolve!: () => void;
+ const deferred = new Promise<void>((done) => {
+ resolve = done;
+ });
+ let actionPromise!: Promise<string | null>;
+ act(() => {
+ actionPromise = gate!.run(async () => {
+ await deferred;
+ return 'done';
+ });
+ });
+ assert.equal(gate!.pending, true);
+
+ let concurrentRan = false;
+ const concurrent = await gate!.run(async () => {
+ concurrentRan = true;
+ return 'unexpected';
+ });
+ assert.equal(concurrent, null);
+ assert.equal(concurrentRan, false);
+
+ await act(async () => {
+ resolve();
+ assert.equal(await actionPromise, 'done');
+ });
+ assert.equal(gate!.pending, false);
+ });
+});
diff --git a/apps/web/src/features/documents/hooks/useDocumentActionGate.ts b/apps/web/src/features/documents/hooks/useDocumentActionGate.ts
new file mode 100644
index 00000000..38acb9ef
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentActionGate.ts
@@ -0,0 +1,24 @@
+import { useCallback, useRef, useState } from 'react';
+
+// A document lifecycle mutation is a two-step optimistic-concurrency operation:
+// flush the editor draft, then mutate the returned version. This gate is both a
+// synchronous mutex (for two clicks before React rerenders) and a render signal
+// used to make the title/editor read-only for the complete sequence.
+export function useDocumentActionGate() {
+ const runningRef = useRef(false);
+ const [pending, setPending] = useState(false);
+
+ const run = useCallback(async <T>(action: () => Promise<T>): Promise<T | null> => {
+ if (runningRef.current) return null;
+ runningRef.current = true;
+ setPending(true);
+ try {
+ return await action();
+ } finally {
+ runningRef.current = false;
+ setPending(false);
+ }
+ }, []);
+
+ return { pending, run };
+}
diff --git a/apps/web/src/features/documents/hooks/useDocumentDraft.test.tsx b/apps/web/src/features/documents/hooks/useDocumentDraft.test.tsx
new file mode 100644
index 00000000..9116a37c
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentDraft.test.tsx
@@ -0,0 +1,310 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { JSDOM } from 'jsdom';
+import type { ProjectDocument } from '@/lib/api';
+
+type UseDocumentDraft = (typeof import('./useDocumentDraft'))['useDocumentDraft'];
+type DocumentDraftController = ReturnType<UseDocumentDraft>;
+type Api = (typeof import('@/lib/api'))['api'];
+
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'HTMLElement',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let queryClient: QueryClient;
+let useDocumentDraft: UseDocumentDraft;
+let api: Api;
+let originalUpdateDocument: Api['updateDocument'];
+let controller: DocumentDraftController | null;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+
+function projectDocument(version: number, content: string): ProjectDocument {
+ return {
+ id: 42,
+ projectId: 7,
+ parentId: null,
+ title: 'Runbook',
+ content,
+ contentJson: null,
+ icon: null,
+ metadata: {},
+ fullWidth: false,
+ isPrivate: false,
+ isLocked: false,
+ isFavorite: false,
+ archivedAt: null,
+ position: 0,
+ version,
+ ownerUserId: 'user-1',
+ createdByUserId: 'user-1',
+ updatedByUserId: 'user-1',
+ createdAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ };
+}
+
+function Probe({
+ document,
+ editable,
+ onController = (value) => {
+ controller = value;
+ },
+}: {
+ document: ProjectDocument;
+ editable: boolean;
+ onController?: (value: DocumentDraftController) => void;
+}) {
+ const value = useDocumentDraft({
+ projectKey: 'SEKTA',
+ document,
+ editable,
+ userId: 'user-1',
+ });
+ onController(value);
+ return null;
+}
+
+function renderInto(
+ targetRoot: Root,
+ document: ProjectDocument,
+ editable: boolean,
+ onController?: (value: DocumentDraftController) => void,
+) {
+ act(() =>
+ targetRoot.render(
+ <QueryClientProvider client={queryClient}>
+ <Probe document={document} editable={editable} onController={onController} />
+ </QueryClientProvider>,
+ ),
+ );
+}
+
+function render(document: ProjectDocument, editable = true) {
+ renderInto(root, document, editable);
+ assert.ok(controller);
+}
+
+beforeEach(async () => {
+ originalGlobalDescriptors = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://plan.example.test' });
+ dom.window.__ITSAPLAN_ENV__ = {
+ apiUrl: 'https://api.example.test',
+ privacyUrl: '',
+ termsUrl: '',
+ };
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+
+ ({ useDocumentDraft } = await import('./useDocumentDraft'));
+ ({ api } = await import('@/lib/api'));
+ originalUpdateDocument = api.updateDocument;
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ controller = null;
+
+ const { createRoot } = await import('react-dom/client');
+ const rootElement = document.querySelector('#root');
+ assert.ok(rootElement);
+ root = createRoot(rootElement);
+});
+
+afterEach(() => {
+ api.updateDocument = originalUpdateDocument;
+ act(() => root.unmount());
+ queryClient.clear();
+ dom.window.close();
+ for (const [name, descriptor] of originalGlobalDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('useDocumentDraft', () => {
+ it('adopts a newer remote version when the editor is clean', () => {
+ render(projectDocument(1, 'Initial'));
+ const previousRevision = controller!.editorRevision;
+
+ render(projectDocument(2, 'Changed elsewhere'));
+
+ assert.equal(controller!.content, 'Changed elsewhere');
+ assert.equal(controller!.version, 2);
+ assert.equal(controller!.saveState, 'saved');
+ assert.equal(controller!.editorRevision, previousRevision + 1);
+ });
+
+ it('preserves a local draft and enters conflict on a newer remote version', () => {
+ render(projectDocument(1, 'Initial'));
+ act(() => controller!.setContent('Local draft', { type: 'doc', content: [] }));
+
+ render(projectDocument(2, 'Changed elsewhere'));
+
+ assert.equal(controller!.content, 'Local draft');
+ assert.equal(controller!.version, 1);
+ assert.equal(controller!.dirty, true);
+ assert.equal(controller!.saveState, 'conflict');
+ });
+
+ it('refreshes a read-only view without requiring an editor save', () => {
+ render(projectDocument(1, 'Initial'), false);
+
+ render(projectDocument(2, 'Read-only refresh'), false);
+
+ assert.equal(controller!.content, 'Read-only refresh');
+ assert.equal(controller!.version, 2);
+ assert.equal(controller!.saveState, 'saved');
+ });
+
+ it('rebases edits made during an in-flight save before a remount', async () => {
+ const first = projectDocument(1, 'Server copy');
+ render(first);
+
+ let resolveUpdate!: (document: ProjectDocument) => void;
+ const update = new Promise<ProjectDocument>((resolve) => {
+ resolveUpdate = resolve;
+ });
+ api.updateDocument = () => update;
+
+ act(() => controller!.setContent('Snapshot A', { type: 'doc', content: [] }));
+ let savePromise!: Promise<ProjectDocument | null>;
+ act(() => {
+ savePromise = controller!.save();
+ });
+ act(() => controller!.setContent('Newer draft B', { type: 'doc', content: [] }));
+
+ const storageKey = 'itsaplan:document-draft:user-1:SEKTA:42';
+ assert.equal(JSON.parse(window.localStorage.getItem(storageKey)!).baseVersion, 1);
+
+ // Navigation may unmount the editor while its request is still in flight.
+ // The success path must rebase the recovery draft without relying on a
+ // mounted component or a follow-up React effect.
+ act(() => root.unmount());
+ resolveUpdate(projectDocument(2, 'Snapshot A'));
+ await savePromise;
+
+ const rebased = JSON.parse(window.localStorage.getItem(storageKey)!);
+ assert.deepEqual(
+ { title: rebased.title, content: rebased.content, baseVersion: rebased.baseVersion },
+ { title: 'Runbook', content: 'Newer draft B', baseVersion: 2 },
+ );
+ assert.equal(typeof rebased.writerId, 'string');
+
+ const { createRoot } = await import('react-dom/client');
+ const rootElement = document.querySelector('#root');
+ assert.ok(rootElement);
+ root = createRoot(rootElement);
+ controller = null;
+ render(projectDocument(2, 'Snapshot A'));
+
+ assert.equal(controller!.content, 'Newer draft B');
+ assert.equal(controller!.dirty, true);
+ assert.equal(controller!.saveState, 'saved');
+ });
+
+ it("does not rebase another tab's recovery draft", async () => {
+ render(projectDocument(1, 'Server copy'));
+
+ let resolveUpdate!: (document: ProjectDocument) => void;
+ const update = new Promise<ProjectDocument>((resolve) => {
+ resolveUpdate = resolve;
+ });
+ api.updateDocument = () => update;
+
+ act(() => controller!.setContent('Saved by tab A', { type: 'doc', content: [] }));
+ let savePromise!: Promise<ProjectDocument | null>;
+ act(() => {
+ savePromise = controller!.save();
+ });
+
+ const storageKey = 'itsaplan:document-draft:user-1:SEKTA:42';
+ window.localStorage.setItem(
+ storageKey,
+ JSON.stringify({
+ title: 'Runbook',
+ content: 'Draft from tab B',
+ baseVersion: 1,
+ writerId: 'tab-b',
+ }),
+ );
+
+ act(() => root.unmount());
+ resolveUpdate(projectDocument(2, 'Saved by tab A'));
+ await savePromise;
+
+ assert.deepEqual(JSON.parse(window.localStorage.getItem(storageKey)!), {
+ title: 'Runbook',
+ content: 'Draft from tab B',
+ baseVersion: 1,
+ writerId: 'tab-b',
+ });
+
+ const { createRoot } = await import('react-dom/client');
+ const rootElement = document.querySelector('#root');
+ assert.ok(rootElement);
+ root = createRoot(rootElement);
+ });
+
+ it("does not delete another mounted tab's recovery draft after saving", async () => {
+ render(projectDocument(1, 'Server copy'));
+ const tabA = controller!;
+
+ const tabBElement = document.createElement('div');
+ document.body.appendChild(tabBElement);
+ const { createRoot } = await import('react-dom/client');
+ const tabBRoot = createRoot(tabBElement);
+ const tabB: { current: DocumentDraftController | null } = { current: null };
+ renderInto(tabBRoot, projectDocument(1, 'Server copy'), true, (value) => {
+ tabB.current = value;
+ });
+ assert.ok(tabB.current);
+
+ let resolveUpdate!: (document: ProjectDocument) => void;
+ const update = new Promise<ProjectDocument>((resolve) => {
+ resolveUpdate = resolve;
+ });
+ api.updateDocument = () => update;
+
+ act(() => tabA.setContent('Saved by tab A', { type: 'doc', content: [] }));
+ let savePromise!: Promise<ProjectDocument | null>;
+ act(() => {
+ savePromise = tabA.save();
+ });
+ act(() => tabB.current!.setContent('Newer draft from tab B', { type: 'doc', content: [] }));
+
+ const storageKey = 'itsaplan:document-draft:user-1:SEKTA:42';
+ const tabBDraft = JSON.parse(window.localStorage.getItem(storageKey)!);
+ assert.equal(tabBDraft.content, 'Newer draft from tab B');
+ assert.equal(typeof tabBDraft.writerId, 'string');
+
+ await act(async () => {
+ resolveUpdate(projectDocument(2, 'Saved by tab A'));
+ await savePromise;
+ });
+
+ assert.deepEqual(JSON.parse(window.localStorage.getItem(storageKey)!), tabBDraft);
+
+ renderInto(tabBRoot, projectDocument(2, 'Saved by tab A'), true, (value) => {
+ tabB.current = value;
+ });
+ assert.equal(tabB.current!.content, 'Newer draft from tab B');
+ assert.equal(tabB.current!.dirty, true);
+ assert.equal(tabB.current!.saveState, 'conflict');
+
+ act(() => tabBRoot.unmount());
+ tabBElement.remove();
+ });
+});
diff --git a/apps/web/src/features/documents/hooks/useDocumentDraft.ts b/apps/web/src/features/documents/hooks/useDocumentDraft.ts
new file mode 100644
index 00000000..e43af3cc
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentDraft.ts
@@ -0,0 +1,309 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { ProjectDocument } from '@/lib/api';
+import { ApiError } from '@/lib/api';
+import { uuid } from '@/utils/uuid';
+import { useUpdateDocument } from '../services/documents.service';
+
+export type DocumentSaveState = 'saved' | 'saving' | 'conflict' | 'error';
+
+const AUTOSAVE_DELAY_MS = 700;
+
+interface StoredDocumentDraft {
+ title: string;
+ content: string;
+ contentJson?: Record<string, unknown> | null;
+ baseVersion: number;
+ writerId?: string;
+}
+
+function draftStorageKey(projectKey: string, documentId: number, userId: string) {
+ return `itsaplan:document-draft:${userId}:${projectKey}:${documentId}`;
+}
+
+function storedDraft(value: string | null): StoredDocumentDraft | null {
+ if (!value) return null;
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (
+ !parsed ||
+ typeof parsed !== 'object' ||
+ typeof (parsed as StoredDocumentDraft).title !== 'string' ||
+ typeof (parsed as StoredDocumentDraft).content !== 'string' ||
+ ((parsed as StoredDocumentDraft).contentJson !== undefined &&
+ (parsed as StoredDocumentDraft).contentJson !== null &&
+ typeof (parsed as StoredDocumentDraft).contentJson !== 'object') ||
+ !Number.isInteger((parsed as StoredDocumentDraft).baseVersion) ||
+ ((parsed as StoredDocumentDraft).writerId !== undefined &&
+ typeof (parsed as StoredDocumentDraft).writerId !== 'string')
+ ) {
+ return null;
+ }
+ return parsed as StoredDocumentDraft;
+ } catch {
+ return null;
+ }
+}
+
+function rebaseStoredDraft(
+ storageKey: string | null,
+ writerId: string,
+ fromVersion: number,
+ toVersion: number,
+) {
+ if (!storageKey) return;
+ try {
+ const local = storedDraft(window.localStorage.getItem(storageKey));
+ // Do not overwrite a draft already rebased by another save/tab. Keeping the
+ // text unchanged is important: it may contain edits newer than this request.
+ if (!local || local.writerId !== writerId || local.baseVersion !== fromVersion) return;
+ window.localStorage.setItem(storageKey, JSON.stringify({ ...local, baseVersion: toVersion }));
+ } catch {
+ // Recovery storage is best effort; the server save still succeeded.
+ }
+}
+
+function removeOwnedStoredDraft(storageKey: string | null, writerId: string) {
+ if (!storageKey) return;
+ const rawStoredDraft = window.localStorage.getItem(storageKey);
+ const local = storedDraft(rawStoredDraft);
+ // The recovery key is shared by every tab for this account and page. A clean
+ // tab must not delete a newer draft written by another mounted tab. Legacy
+ // drafts have no writer id, so preserve them until a tab restores and rewrites
+ // them as its own.
+ if (rawStoredDraft !== null && local?.writerId === writerId) {
+ window.localStorage.removeItem(storageKey);
+ }
+}
+
+export function useDocumentDraft({
+ projectKey,
+ document,
+ editable,
+ userId,
+}: {
+ projectKey: string;
+ document: ProjectDocument;
+ editable: boolean;
+ userId: string | null;
+}) {
+ const { mutateAsync } = useUpdateDocument(projectKey);
+ const versionRef = useRef(document.version);
+ const savingRef = useRef(false);
+ const writerIdRef = useRef(uuid());
+ const [version, setVersion] = useState(document.version);
+ const [title, setTitleState] = useState(document.title);
+ const [content, setContentState] = useState(document.content);
+ const [contentJson, setContentJsonState] = useState(document.contentJson);
+ const [saved, setSaved] = useState({
+ title: document.title,
+ content: document.content,
+ contentJson: JSON.stringify(document.contentJson),
+ });
+ const [draftBaseVersion, setDraftBaseVersion] = useState(document.version);
+ const [saveState, setSaveState] = useState<DocumentSaveState>('saved');
+ const [editorRevision, setEditorRevision] = useState(0);
+ const [restoredStorageKey, setRestoredStorageKey] = useState<string | null>(null);
+ const dirty =
+ title !== saved.title ||
+ content !== saved.content ||
+ JSON.stringify(contentJson) !== saved.contentJson;
+ const storageKey = userId ? draftStorageKey(projectKey, document.id, userId) : null;
+
+ // Keep an on-device recovery copy. Unlike beforeunload, this also survives
+ // App Router links and browser Back/Forward, where React can unmount the editor
+ // before an unsuccessful autosave reports its error.
+ useEffect(() => {
+ if (!storageKey || restoredStorageKey === storageKey) return;
+ let local: StoredDocumentDraft | null = null;
+ try {
+ local = storedDraft(window.localStorage.getItem(storageKey));
+ } catch {
+ // Private browsing policies may make even reading storage throw.
+ }
+ versionRef.current = document.version;
+ setDraftBaseVersion(local?.baseVersion ?? document.version);
+ setSaved({
+ title: document.title,
+ content: document.content,
+ contentJson: JSON.stringify(document.contentJson),
+ });
+ setTitleState(local?.title ?? document.title);
+ setContentState(local?.content ?? document.content);
+ setContentJsonState(local ? (local.contentJson ?? null) : document.contentJson);
+ setSaveState(local && local.baseVersion !== document.version ? 'conflict' : 'saved');
+ setEditorRevision((revision) => revision + 1);
+ setRestoredStorageKey(storageKey);
+ }, [
+ document.content,
+ document.contentJson,
+ document.title,
+ document.version,
+ restoredStorageKey,
+ storageKey,
+ ]);
+
+ // A scope refresh can replace the query data while this editor stays mounted.
+ // Own writes update versionRef before their query result settles, so equality is
+ // also what prevents a successful autosave from remounting Tiptap and moving the
+ // cursor. A genuinely newer remote version is adopted only when there is no local
+ // work to protect; otherwise the existing conflict flow lets the user review it.
+ useEffect(() => {
+ if (document.version <= versionRef.current) return;
+ if (dirty || savingRef.current) {
+ setSaveState('conflict');
+ return;
+ }
+ versionRef.current = document.version;
+ setVersion(document.version);
+ setDraftBaseVersion(document.version);
+ setTitleState(document.title);
+ setContentState(document.content);
+ setContentJsonState(document.contentJson);
+ setSaved({
+ title: document.title,
+ content: document.content,
+ contentJson: JSON.stringify(document.contentJson),
+ });
+ setSaveState('saved');
+ setEditorRevision((revision) => revision + 1);
+ }, [dirty, document.content, document.contentJson, document.title, document.version]);
+
+ useEffect(() => {
+ if (!storageKey || restoredStorageKey !== storageKey) return;
+ try {
+ if (dirty) {
+ window.localStorage.setItem(
+ storageKey,
+ JSON.stringify({
+ title,
+ content,
+ contentJson,
+ baseVersion: draftBaseVersion,
+ writerId: writerIdRef.current,
+ }),
+ );
+ } else {
+ removeOwnedStoredDraft(storageKey, writerIdRef.current);
+ }
+ } catch {
+ // A full or disabled storage must not prevent editing or autosave.
+ }
+ }, [content, contentJson, dirty, draftBaseVersion, restoredStorageKey, storageKey, title]);
+
+ const save = useCallback(async (): Promise<ProjectDocument | null> => {
+ if (!editable || !dirty || savingRef.current || saveState === 'conflict') return null;
+
+ const snapshot = { title, content, contentJson };
+ const baseVersion = versionRef.current;
+ savingRef.current = true;
+ setSaveState('saving');
+ try {
+ const updated = await mutateAsync({
+ documentId: document.id,
+ patch: {
+ version: baseVersion,
+ title: snapshot.title,
+ content: snapshot.content,
+ contentJson: snapshot.contentJson,
+ },
+ });
+ versionRef.current = updated.version;
+ setVersion(updated.version);
+ // This direct write also runs when navigation unmounted the editor while
+ // the request was in flight, where a React state/effect update cannot.
+ rebaseStoredDraft(storageKey, writerIdRef.current, baseVersion, updated.version);
+ // A user may keep typing while this request is in flight. Advancing the
+ // recovery draft's base version keeps those newer edits saveable after a
+ // navigation or remount, even before the next autosave fires.
+ setDraftBaseVersion(updated.version);
+ setSaved({ ...snapshot, contentJson: JSON.stringify(snapshot.contentJson) });
+ setSaveState('saved');
+ return updated;
+ } catch (error) {
+ setSaveState(error instanceof ApiError && error.status === 409 ? 'conflict' : 'error');
+ return null;
+ } finally {
+ savingRef.current = false;
+ }
+ }, [
+ content,
+ contentJson,
+ dirty,
+ document.id,
+ editable,
+ mutateAsync,
+ saveState,
+ storageKey,
+ title,
+ ]);
+
+ useEffect(() => {
+ if (!editable || !dirty || saveState === 'conflict' || saveState === 'error') return;
+ const timer = window.setTimeout(() => void save(), AUTOSAVE_DELAY_MS);
+ return () => window.clearTimeout(timer);
+ }, [dirty, editable, save, saveState]);
+
+ useEffect(() => {
+ if (!dirty) return;
+ const warnBeforeLeaving = (event: BeforeUnloadEvent) => event.preventDefault();
+ window.addEventListener('beforeunload', warnBeforeLeaving);
+ return () => window.removeEventListener('beforeunload', warnBeforeLeaving);
+ }, [dirty]);
+
+ const setTitle = (value: string) => {
+ setTitleState(value);
+ setSaveState((state) => (state === 'error' ? 'saved' : state));
+ };
+
+ const setContent = (value: string, json: Record<string, unknown>) => {
+ setContentState(value);
+ setContentJsonState(json);
+ setSaveState((state) => (state === 'error' ? 'saved' : state));
+ };
+
+ const replaceWith = (latest: ProjectDocument) => {
+ try {
+ removeOwnedStoredDraft(storageKey, writerIdRef.current);
+ } catch {
+ // Reloading from the server still works when storage is unavailable.
+ }
+ versionRef.current = latest.version;
+ setVersion(latest.version);
+ setDraftBaseVersion(latest.version);
+ setTitleState(latest.title);
+ setContentState(latest.content);
+ setContentJsonState(latest.contentJson);
+ setSaved({
+ title: latest.title,
+ content: latest.content,
+ contentJson: JSON.stringify(latest.contentJson),
+ });
+ setSaveState('saved');
+ // Tiptap owns its document after mount. Remounting is the reliable way to
+ // replace it after resolving an optimistic-concurrency conflict.
+ setEditorRevision((revision) => revision + 1);
+ };
+
+ const adoptServerDocument = (latest: ProjectDocument) => {
+ const previousVersion = versionRef.current;
+ versionRef.current = latest.version;
+ setVersion(latest.version);
+ setDraftBaseVersion(latest.version);
+ rebaseStoredDraft(storageKey, writerIdRef.current, previousVersion, latest.version);
+ };
+
+ return {
+ title,
+ content,
+ contentJson,
+ dirty,
+ saveState,
+ version,
+ editorRevision,
+ setTitle,
+ setContent,
+ save,
+ replaceWith,
+ adoptServerDocument,
+ };
+}
diff --git a/apps/web/src/features/documents/hooks/useDocumentEditorPreferences.ts b/apps/web/src/features/documents/hooks/useDocumentEditorPreferences.ts
new file mode 100644
index 00000000..f7a06003
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentEditorPreferences.ts
@@ -0,0 +1,66 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+
+const STORAGE_KEY = 'itsaplan:docs:editor-preferences:v1';
+
+interface DocumentEditorPreferences {
+ stickyToolbar: boolean;
+}
+
+const DEFAULT_PREFERENCES: DocumentEditorPreferences = {
+ stickyToolbar: true,
+};
+
+function parsePreferences(value: string | null): DocumentEditorPreferences {
+ if (!value) return DEFAULT_PREFERENCES;
+ try {
+ const parsed = JSON.parse(value) as Partial<DocumentEditorPreferences>;
+ return { stickyToolbar: parsed.stickyToolbar !== false };
+ } catch {
+ return DEFAULT_PREFERENCES;
+ }
+}
+
+function readPreferences(): DocumentEditorPreferences {
+ try {
+ return parsePreferences(window.localStorage.getItem(STORAGE_KEY));
+ } catch {
+ return DEFAULT_PREFERENCES;
+ }
+}
+
+export function useDocumentEditorPreferences() {
+ const [preferences, setPreferences] = useState(DEFAULT_PREFERENCES);
+ const [restored, setRestored] = useState(false);
+
+ useEffect(() => {
+ setPreferences(readPreferences());
+ setRestored(true);
+
+ const syncPreferences = (event: StorageEvent) => {
+ if (event.key !== STORAGE_KEY) return;
+ const next = parsePreferences(event.newValue);
+ setPreferences((current) => (current.stickyToolbar === next.stickyToolbar ? current : next));
+ };
+ window.addEventListener('storage', syncPreferences);
+ return () => window.removeEventListener('storage', syncPreferences);
+ }, []);
+
+ useEffect(() => {
+ if (!restored) return;
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
+ } catch {
+ return;
+ }
+ }, [preferences, restored]);
+
+ const setStickyToolbar = useCallback((stickyToolbar: boolean) => {
+ setPreferences((current) =>
+ current.stickyToolbar === stickyToolbar ? current : { ...current, stickyToolbar },
+ );
+ }, []);
+
+ return { ...preferences, setStickyToolbar };
+}
diff --git a/apps/web/src/features/documents/services/documents.service.ts b/apps/web/src/features/documents/services/documents.service.ts
new file mode 100644
index 00000000..196d195c
--- /dev/null
+++ b/apps/web/src/features/documents/services/documents.service.ts
@@ -0,0 +1,379 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import {
+ api,
+ type DocumentIssueLink,
+ type DocumentAsset,
+ type IssueDocumentLink,
+ type NewProjectDocumentInput,
+ type ProjectDocument,
+ type ProjectDocumentPatch,
+ type ProjectDocumentRevisionSummary,
+ type ProjectDocumentSummary,
+} from '@/lib/api';
+import { qk } from '@/services/queryKeys';
+import { applyOptimisticDocumentMove } from '../utils/documentMove';
+
+function summaryOf(document: ProjectDocument): ProjectDocumentSummary {
+ const { content: _content, contentJson: _contentJson, ...summary } = document;
+ return summary;
+}
+
+function invalidateLists(qc: ReturnType<typeof useQueryClient>, projectKey: string) {
+ void qc.invalidateQueries({ queryKey: qk.documentListsForProject(projectKey) });
+}
+
+export function useDocumentsQuery(projectKey: string | null, q = '', archived = false) {
+ return useQuery({
+ queryKey: qk.documents(projectKey ?? '', q, archived),
+ queryFn: () => api.listDocuments(projectKey!, q || undefined, archived),
+ enabled: projectKey != null,
+ });
+}
+
+export function useDocumentQuery(projectKey: string | null, documentId: number | null) {
+ return useQuery({
+ queryKey: qk.document(projectKey ?? '', documentId ?? 0),
+ queryFn: () => api.getDocument(projectKey!, documentId!),
+ enabled: projectKey != null && documentId != null,
+ refetchOnMount: 'always',
+ });
+}
+
+export function useDocumentIssueLinksQuery(
+ projectKey: string | null,
+ documentId: number | null,
+ enabled = true,
+) {
+ return useQuery<DocumentIssueLink[]>({
+ queryKey: qk.documentIssueLinks(projectKey ?? '', documentId ?? 0),
+ queryFn: () => api.listDocumentIssueLinks(projectKey!, documentId!),
+ enabled: enabled && projectKey != null && documentId != null,
+ });
+}
+
+export function useIssueDocumentLinksQuery(
+ projectKey: string | null,
+ issueId: number | null,
+ enabled = true,
+) {
+ return useQuery<IssueDocumentLink[]>({
+ queryKey: qk.issueDocumentLinks(projectKey ?? '', issueId ?? 0),
+ queryFn: () => api.listIssueDocumentLinks(projectKey!, issueId!),
+ enabled: enabled && projectKey != null && issueId != null,
+ });
+}
+
+export function useLinkDocumentIssue(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ documentId, issueId }: { documentId: number; issueId: number }) =>
+ api.linkDocumentIssue(projectKey!, documentId, issueId),
+ onSuccess: (_link, { documentId, issueId }) => {
+ if (!projectKey) return;
+ void qc.invalidateQueries({ queryKey: qk.documentIssueLinks(projectKey, documentId) });
+ void qc.invalidateQueries({ queryKey: qk.issueDocumentLinks(projectKey, issueId) });
+ },
+ });
+}
+
+export function useUnlinkDocumentIssue(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ documentId, issueId }: { documentId: number; issueId: number }) =>
+ api.unlinkDocumentIssue(projectKey!, documentId, issueId),
+ onSuccess: (_result, { documentId, issueId }) => {
+ if (!projectKey) return;
+ void qc.invalidateQueries({ queryKey: qk.documentIssueLinks(projectKey, documentId) });
+ void qc.invalidateQueries({ queryKey: qk.issueDocumentLinks(projectKey, issueId) });
+ },
+ });
+}
+
+export function useCreateDocument(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: NewProjectDocumentInput) => api.createDocument(projectKey!, input),
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, document.id), document);
+ invalidateLists(qc, projectKey);
+ },
+ });
+}
+
+export function useDuplicateDocument(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ documentId,
+ version,
+ title,
+ parentId,
+ }: {
+ documentId: number;
+ version: number;
+ title: string;
+ parentId: number | null;
+ }) => api.duplicateDocument(projectKey!, documentId, { version, title, parentId }),
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, document.id), document);
+ invalidateLists(qc, projectKey);
+ },
+ });
+}
+
+function cacheDocument(
+ qc: ReturnType<typeof useQueryClient>,
+ projectKey: string,
+ document: ProjectDocument,
+) {
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, document.id), document);
+ invalidateLists(qc, projectKey);
+}
+
+function useDocumentMutation<TInput>(
+ projectKey: string | null,
+ mutationFn: (input: TInput) => Promise<ProjectDocument>,
+) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn,
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ cacheDocument(qc, projectKey, document);
+ },
+ });
+}
+
+export function useSetDocumentAccess(projectKey: string | null) {
+ return useDocumentMutation(
+ projectKey,
+ ({
+ documentId,
+ version,
+ isPrivate,
+ }: {
+ documentId: number;
+ version: number;
+ isPrivate: boolean;
+ }) => api.setDocumentAccess(projectKey!, documentId, { version, isPrivate }),
+ );
+}
+
+export function useSetDocumentLocked(projectKey: string | null) {
+ return useDocumentMutation(
+ projectKey,
+ ({ documentId, version, locked }: { documentId: number; version: number; locked: boolean }) =>
+ api.setDocumentLocked(projectKey!, documentId, version, locked),
+ );
+}
+
+export function useArchiveDocument(projectKey: string | null) {
+ return useDocumentMutation(
+ projectKey,
+ ({ documentId, version }: { documentId: number; version: number }) =>
+ api.archiveDocument(projectKey!, documentId, version),
+ );
+}
+
+export function useRestoreDocument(projectKey: string | null) {
+ return useDocumentMutation(
+ projectKey,
+ ({ documentId, version }: { documentId: number; version: number }) =>
+ api.restoreDocument(projectKey!, documentId, version),
+ );
+}
+
+export function useSetDocumentFavorite(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ documentId, isFavorite }: { documentId: number; isFavorite: boolean }) =>
+ api.setDocumentFavorite(projectKey!, documentId, isFavorite),
+ onMutate: async ({ documentId, isFavorite }) => {
+ if (!projectKey) return;
+ await qc.cancelQueries({ queryKey: qk.documentListsForProject(projectKey) });
+ await qc.cancelQueries({ queryKey: qk.document(projectKey, documentId) });
+ const previousDocument = qc.getQueryData<ProjectDocument>(
+ qk.document(projectKey, documentId),
+ );
+ const previousLists = qc.getQueriesData<ProjectDocumentSummary[]>({
+ queryKey: qk.documentListsForProject(projectKey),
+ });
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, documentId), (previous) =>
+ previous ? { ...previous, isFavorite } : previous,
+ );
+ qc.setQueriesData<ProjectDocumentSummary[]>(
+ { queryKey: qk.documentListsForProject(projectKey) },
+ (previous) =>
+ previous?.map((item) => (item.id === documentId ? { ...item, isFavorite } : item)),
+ );
+ return { previousDocument, previousLists };
+ },
+ onError: (_error, { documentId }, context) => {
+ if (!projectKey || !context) return;
+ qc.setQueryData(qk.document(projectKey, documentId), context.previousDocument);
+ for (const [queryKey, data] of context.previousLists) qc.setQueryData(queryKey, data);
+ },
+ onSettled: (_result, _error, { documentId }) => {
+ if (!projectKey) return;
+ void qc.invalidateQueries({ queryKey: qk.document(projectKey, documentId) });
+ invalidateLists(qc, projectKey);
+ },
+ });
+}
+
+export function useDocumentRevisionsQuery(
+ projectKey: string | null,
+ documentId: number | null,
+ enabled: boolean,
+) {
+ return useQuery<ProjectDocumentRevisionSummary[]>({
+ queryKey: qk.documentRevisions(projectKey ?? '', documentId ?? 0),
+ queryFn: () => api.listDocumentRevisions(projectKey!, documentId!),
+ enabled: enabled && projectKey != null && documentId != null,
+ });
+}
+
+export function useDocumentAssetsQuery(projectKey: string | null, documentId: number | null) {
+ return useQuery<DocumentAsset[]>({
+ queryKey: qk.documentAssets(projectKey ?? '', documentId ?? 0),
+ queryFn: () => api.listDocumentAssets(projectKey!, documentId!),
+ enabled: projectKey != null && documentId != null,
+ });
+}
+
+export function useUploadDocumentAsset(projectKey: string | null, documentId: number | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (file: File) => api.uploadDocumentAsset(projectKey!, documentId!, file),
+ onSuccess: (asset) => {
+ if (!projectKey || documentId === null) return;
+ qc.setQueryData<DocumentAsset[]>(qk.documentAssets(projectKey, documentId), (previous) => [
+ asset,
+ ...(previous ?? []),
+ ]);
+ },
+ });
+}
+
+export function useDeleteDocumentAsset(projectKey: string | null, documentId: number | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (publicId: string) => api.deleteDocumentAsset(projectKey!, documentId!, publicId),
+ onSuccess: (_result, publicId) => {
+ if (!projectKey || documentId === null) return;
+ qc.setQueryData<DocumentAsset[]>(qk.documentAssets(projectKey, documentId), (previous) =>
+ previous?.filter((asset) => asset.id !== publicId),
+ );
+ },
+ });
+}
+
+export function useRestoreDocumentRevision(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ documentId,
+ revisionId,
+ version,
+ }: {
+ documentId: number;
+ revisionId: number;
+ version: number;
+ }) => api.restoreDocumentRevision(projectKey!, documentId, revisionId, version),
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ cacheDocument(qc, projectKey, document);
+ void qc.invalidateQueries({ queryKey: qk.documentRevisions(projectKey, document.id) });
+ },
+ });
+}
+
+export function useUpdateDocument(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ documentId, patch }: { documentId: number; patch: ProjectDocumentPatch }) =>
+ api.updateDocument(projectKey!, documentId, patch),
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, document.id), document);
+ qc.setQueriesData<ProjectDocumentSummary[]>(
+ { queryKey: qk.documentListsForProject(projectKey) },
+ (previous) =>
+ previous?.map((item) => (item.id === document.id ? summaryOf(document) : item)),
+ );
+ // Search membership can change when either title or content changes. The
+ // immediate replacement keeps visible summaries fresh; the refetch adds or
+ // removes the page from every cached search result as needed.
+ invalidateLists(qc, projectKey);
+ },
+ });
+}
+
+export function useMoveDocument(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ documentId,
+ version,
+ parentId,
+ position,
+ previousSiblingId,
+ nextSiblingId,
+ }: {
+ documentId: number;
+ version: number;
+ parentId: number | null;
+ position: number;
+ previousSiblingId: number | null;
+ nextSiblingId: number | null;
+ }) =>
+ api.updateDocument(projectKey!, documentId, {
+ version,
+ parentId,
+ position,
+ previousSiblingId,
+ nextSiblingId,
+ }),
+ onMutate: async (move) => {
+ if (!projectKey) return { snapshots: [] };
+ await qc.cancelQueries({ queryKey: qk.documentListsForProject(projectKey) });
+ const snapshots = qc.getQueriesData<ProjectDocumentSummary[]>({
+ queryKey: qk.documentListsForProject(projectKey),
+ });
+ qc.setQueriesData<ProjectDocumentSummary[]>(
+ { queryKey: qk.documentListsForProject(projectKey) },
+ (previous) => (previous ? applyOptimisticDocumentMove(previous, move) : previous),
+ );
+ return { snapshots };
+ },
+ onError: (_error, _variables, context) => {
+ for (const [queryKey, data] of context?.snapshots ?? []) qc.setQueryData(queryKey, data);
+ },
+ onSuccess: (document) => {
+ if (!projectKey) return;
+ qc.setQueryData<ProjectDocument>(qk.document(projectKey, document.id), document);
+ },
+ onSettled: (_document, error) => {
+ // Keep the complete optimistic sibling projection while the canonical
+ // list refetches. A failed refetch therefore cannot reintroduce stale
+ // sibling positions, while mutation failures still use the snapshot
+ // rollback above.
+ if (projectKey && !error) invalidateLists(qc, projectKey);
+ },
+ });
+}
+
+export function useDeleteDocument(projectKey: string | null) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({ documentId, version }: { documentId: number; version: number }) =>
+ api.deleteDocument(projectKey!, documentId, version),
+ onSuccess: (_result, { documentId }) => {
+ if (!projectKey) return;
+ qc.removeQueries({ queryKey: qk.document(projectKey, documentId) });
+ invalidateLists(qc, projectKey);
+ },
+ });
+}
diff --git a/apps/web/src/features/documents/utils/documentExport.test.ts b/apps/web/src/features/documents/utils/documentExport.test.ts
new file mode 100644
index 00000000..ffe81ebd
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentExport.test.ts
@@ -0,0 +1,213 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import JSZip from 'jszip';
+import {
+ createPortableDocumentExport,
+ DocumentExportLimitError,
+ documentExportArchiveFilename,
+ documentExportBody,
+ documentExportFilename,
+ MAX_DOCUMENT_EXPORT_ASSETS,
+ MAX_DOCUMENT_EXPORT_BYTES,
+} from './documentExport';
+
+const protectedAsset =
+ '/protected-media/projects/SEKTA/documents/42/assets/123e4567-e89b-12d3-a456-426614174000/raw';
+
+function assertSanitizedHtml(html: string): void {
+ const normalized = html.toLowerCase();
+ assert.equal(normalized.includes('<script'), false);
+ assert.equal(normalized.includes('javascript:'), false);
+ assert.equal(normalized.includes('onerror='), false);
+ assert.equal(normalized.includes('onload='), false);
+}
+
+describe('document export', () => {
+ it('creates a stable filename for either format', () => {
+ assert.equal(
+ documentExportFilename(' Release notes 2026 ', 'markdown'),
+ 'release-notes-2026.md',
+ );
+ assert.equal(documentExportFilename('', 'html'), 'untitled.html');
+ assert.equal(documentExportArchiveFilename('Release notes 2026'), 'release-notes-2026.zip');
+ });
+
+ it('includes the page title in markdown exports', () => {
+ assert.equal(documentExportBody('Guide', 'Start here.', 'markdown'), '# Guide\n\nStart here.');
+ });
+
+ it('escapes the title and sanitizes exported HTML', () => {
+ const html = documentExportBody(
+ '<Guide>',
+ '<SCRIPT>alert(1)</SCRIPT><img src="x" onerror="alert(2)"><a href="JaVaScRiPt:alert(3)">Unsafe</a><svg onload="alert(4)"></svg>Safe',
+ 'html',
+ );
+ assert.match(html, /<h1>&lt;Guide&gt;<\/h1>/);
+ assertSanitizedHtml(html);
+ assert.match(html, /Safe/);
+ });
+
+ it('preserves rich editor alignment and highlight while removing scripts', () => {
+ const html = documentExportBody(
+ 'Guide',
+ 'Fallback',
+ 'html',
+ '<p style="text-align: center"><mark data-color="#fde047" style="background-color: #fde047">Important</mark><ScRiPt>alert(1)</ScRiPt><img src="x" onerror="alert(2)"></p>',
+ );
+ assert.match(html, /text-align: center/);
+ assert.match(html, /background-color: #fde047/);
+ assert.match(html, /Important/);
+ assertSanitizedHtml(html);
+ });
+
+ it('inlines only this document protected assets in portable HTML', async () => {
+ const calls: Array<{ url: string; credentials: RequestCredentials | undefined }> = [];
+ const result = await createPortableDocumentExport({
+ title: 'Guide',
+ content: '',
+ richHtml: `<p><img src="${protectedAsset}"><a href="${protectedAsset}">Download</a><img src="/protected-media/projects/SEKTA/documents/99/assets/123e4567-e89b-12d3-a456-426614174000/raw"><img src="https://evil.example${protectedAsset}"><a href="https://example.test/public.png">External</a></p>`,
+ format: 'html',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async (input, init) => {
+ calls.push({ url: String(input), credentials: init?.credentials });
+ return new Response(new Uint8Array([137, 80, 78, 71]), {
+ headers: {
+ 'content-type': 'image/png',
+ 'content-disposition': 'inline; filename="diagram.png"',
+ },
+ });
+ },
+ });
+
+ const html = await result.blob.text();
+ assert.equal(result.filename, 'guide.html');
+ assert.deepEqual(calls, [
+ {
+ url: `https://plan.example.test${protectedAsset}`,
+ credentials: 'same-origin',
+ },
+ ]);
+ assert.equal(html.match(/data:image\/png;base64,iVBORw==/g)?.length, 2);
+ assert.match(html, /documents\/99\/assets\/123e4567/);
+ assert.match(html, /https:\/\/evil\.example\/protected-media\/projects\/SEKTA/);
+ assert.match(html, /https:\/\/example\.test\/public\.png/);
+ });
+
+ it('does not preserve active asset MIME types in portable HTML', async () => {
+ const result = await createPortableDocumentExport({
+ title: 'Guide',
+ content: '',
+ richHtml: `<a href="${protectedAsset}">Download diagram</a>`,
+ format: 'html',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async () =>
+ new Response('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>', {
+ headers: { 'content-type': 'image/svg+xml' },
+ }),
+ });
+
+ const html = await result.blob.text();
+ assert.equal(html.includes('data:image/svg+xml'), false);
+ assert.match(html, /data:application\/octet-stream;base64,/);
+ });
+
+ it('packages Markdown with local protected assets and preserves external links', async () => {
+ let calls = 0;
+ const result = await createPortableDocumentExport({
+ title: 'Guide',
+ content: `![Diagram](${protectedAsset})\n\n[Download](${protectedAsset})\n\n[External](https://example.test/public.pdf)`,
+ format: 'markdown',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async () => {
+ calls += 1;
+ return new Response(new Uint8Array([1, 2, 3]), {
+ headers: {
+ 'content-type': 'image/png',
+ 'content-disposition': "attachment; filename*=UTF-8''diagram.png",
+ },
+ });
+ },
+ });
+
+ assert.equal(result.filename, 'guide.zip');
+ assert.equal(calls, 1);
+ const zip = await JSZip.loadAsync(await result.blob.arrayBuffer());
+ const markdown = await zip.file('guide.md')!.async('string');
+ assert.equal(markdown.match(/assets\/diagram\.png/g)?.length, 2);
+ assert.match(markdown, /https:\/\/example\.test\/public\.pdf/);
+ assert.deepEqual([...(await zip.file('assets/diagram.png')!.async('uint8array'))], [1, 2, 3]);
+ });
+
+ it('downloads Markdown without protected assets as a plain .md file', async () => {
+ let calls = 0;
+ const result = await createPortableDocumentExport({
+ title: 'Guide',
+ content: '[External](https://example.test/public.pdf)',
+ format: 'markdown',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async () => {
+ calls += 1;
+ throw new Error('External assets must not be fetched');
+ },
+ });
+
+ assert.equal(result.filename, 'guide.md');
+ assert.equal(result.blob.type, 'text/markdown;charset=utf-8');
+ assert.equal(calls, 0);
+ assert.equal(
+ await result.blob.text(),
+ '# Guide\n\n[External](https://example.test/public.pdf)',
+ );
+ });
+
+ it('rejects exports with more protected assets than the hard cap before fetching', async () => {
+ let calls = 0;
+ const content = Array.from({ length: MAX_DOCUMENT_EXPORT_ASSETS + 1 }, (_, index) => {
+ const publicId = `123e4567-e89b-12d3-a456-${index.toString(16).padStart(12, '0')}`;
+ return `![Asset ${index}](/protected-media/projects/SEKTA/documents/42/assets/${publicId}/raw)`;
+ }).join('\n');
+
+ await assert.rejects(
+ createPortableDocumentExport({
+ title: 'Guide',
+ content,
+ format: 'markdown',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async () => {
+ calls += 1;
+ return new Response();
+ },
+ }),
+ DocumentExportLimitError,
+ );
+ assert.equal(calls, 0);
+ });
+
+ it('rejects a declared protected asset size beyond the total byte cap', async () => {
+ await assert.rejects(
+ createPortableDocumentExport({
+ title: 'Guide',
+ content: `![Diagram](${protectedAsset})`,
+ format: 'markdown',
+ projectKey: 'SEKTA',
+ documentId: 42,
+ baseUrl: 'https://plan.example.test',
+ fetchImpl: async () =>
+ new Response(new Uint8Array([1]), {
+ headers: { 'content-length': String(MAX_DOCUMENT_EXPORT_BYTES + 1) },
+ }),
+ }),
+ DocumentExportLimitError,
+ );
+ });
+});
diff --git a/apps/web/src/features/documents/utils/documentExport.ts b/apps/web/src/features/documents/utils/documentExport.ts
new file mode 100644
index 00000000..94f7b570
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentExport.ts
@@ -0,0 +1,430 @@
+import { marked } from 'marked';
+import DOMPurify from 'isomorphic-dompurify';
+import JSZip from 'jszip';
+
+export type DocumentExportFormat = 'markdown' | 'html';
+
+export interface PortableDocumentExportInput {
+ title: string;
+ content: string;
+ richHtml?: string;
+ format: DocumentExportFormat;
+ projectKey: string;
+ documentId: number;
+ baseUrl: string;
+ fetchImpl?: typeof fetch;
+}
+
+export interface PortableDocumentExport {
+ blob: Blob;
+ filename: string;
+}
+
+export const MAX_DOCUMENT_EXPORT_ASSETS = 50;
+export const MAX_DOCUMENT_EXPORT_BYTES = 100 * 1024 * 1024;
+const DOCUMENT_EXPORT_FETCH_CONCURRENCY = 4;
+const SAFE_INLINE_IMAGE_CONTENT_TYPES = new Set([
+ 'image/gif',
+ 'image/jpeg',
+ 'image/png',
+ 'image/webp',
+]);
+
+export class DocumentExportLimitError extends Error {
+ constructor() {
+ super('The document export exceeds the protected asset limit.');
+ this.name = 'DocumentExportLimitError';
+ }
+}
+
+interface ExportAsset {
+ references: string[];
+ bytes: Uint8Array;
+ contentType: string;
+ filename: string;
+}
+
+const PUBLIC_ID = '[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
+
+function renderExportMarkdown(value: string): string {
+ const html = marked.parse(value, { async: false, breaks: true }) as string;
+ return DOMPurify.sanitize(html);
+}
+
+function escapeHtml(value: string): string {
+ return value
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;');
+}
+
+export function documentExportFilename(title: string, extension: DocumentExportFormat): string {
+ const base = title
+ .trim()
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80);
+ return `${base || 'untitled'}.${extension === 'markdown' ? 'md' : 'html'}`;
+}
+
+export function documentExportBody(
+ title: string,
+ content: string,
+ format: DocumentExportFormat,
+ richHtml?: string,
+): string {
+ if (format === 'markdown') {
+ return `${title.trim() ? `# ${title.trim()}\n\n` : ''}${content}`;
+ }
+
+ const heading = title.trim() ? `<h1>${escapeHtml(title.trim())}</h1>` : '';
+ return `<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>${escapeHtml(title.trim() || 'Untitled')}</title>
+ <style>body{max-width:760px;margin:64px auto;padding:0 24px;color:#171717;font:16px/1.65 system-ui,sans-serif}h1,h2,h3{line-height:1.2}pre{overflow:auto;padding:16px;background:#f5f5f5;border-radius:8px}code{font-family:ui-monospace,monospace}img{max-width:100%}blockquote{margin-inline:0;padding-inline-start:16px;border-inline-start:3px solid #d4d4d4;color:#525252}</style>
+</head>
+<body>${heading}${richHtml ? DOMPurify.sanitize(richHtml) : renderExportMarkdown(content)}</body>
+</html>`;
+}
+
+export async function createPortableDocumentExport({
+ title,
+ content,
+ richHtml,
+ format,
+ projectKey,
+ documentId,
+ baseUrl,
+ fetchImpl = fetch,
+}: PortableDocumentExportInput): Promise<PortableDocumentExport> {
+ const body = documentExportBody(title, content, format, richHtml);
+ const assets = await fetchDocumentExportAssets({
+ body,
+ projectKey,
+ documentId,
+ baseUrl,
+ fetchImpl,
+ });
+
+ if (format === 'html') {
+ const replacements = new Map<string, string>();
+ for (const asset of assets) {
+ const inlineContentType = SAFE_INLINE_IMAGE_CONTENT_TYPES.has(asset.contentType)
+ ? asset.contentType
+ : 'application/octet-stream';
+ const dataUrl = `data:${inlineContentType};base64,${bytesToBase64(asset.bytes)}`;
+ for (const reference of asset.references) replacements.set(reference, dataUrl);
+ }
+ return {
+ blob: new Blob([replaceExportReferences(body, replacements)], {
+ type: 'text/html;charset=utf-8',
+ }),
+ filename: documentExportFilename(title, 'html'),
+ };
+ }
+
+ if (assets.length === 0) {
+ return {
+ blob: new Blob([body], { type: 'text/markdown;charset=utf-8' }),
+ filename: documentExportFilename(title, 'markdown'),
+ };
+ }
+
+ const zip = new JSZip();
+ const replacements = new Map<string, string>();
+ for (const asset of assets) {
+ const assetPath = `assets/${asset.filename}`;
+ zip.file(assetPath, asset.bytes);
+ for (const reference of asset.references) replacements.set(reference, assetPath);
+ }
+ zip.file(documentExportFilename(title, 'markdown'), replaceExportReferences(body, replacements));
+ return {
+ blob: await zip.generateAsync({ type: 'blob', compression: 'DEFLATE' }),
+ filename: documentExportArchiveFilename(title),
+ };
+}
+
+export function documentExportArchiveFilename(title: string): string {
+ return documentExportFilename(title, 'markdown').replace(/\.md$/, '.zip');
+}
+
+async function fetchDocumentExportAssets({
+ body,
+ projectKey,
+ documentId,
+ baseUrl,
+ fetchImpl,
+}: {
+ body: string;
+ projectKey: string;
+ documentId: number;
+ baseUrl: string;
+ fetchImpl: typeof fetch;
+}): Promise<ExportAsset[]> {
+ const base = new URL(baseUrl);
+ const referencesByUrl = new Map<string, { url: URL; references: Set<string> }>();
+ for (const reference of extractExportReferences(body)) {
+ const url = protectedDocumentAssetUrl(reference, { projectKey, documentId, base });
+ if (!url) continue;
+ const existing = referencesByUrl.get(url.href);
+ if (existing) existing.references.add(reference);
+ else referencesByUrl.set(url.href, { url, references: new Set([reference]) });
+ }
+
+ if (referencesByUrl.size > MAX_DOCUMENT_EXPORT_ASSETS) {
+ throw new DocumentExportLimitError();
+ }
+
+ const usedFilenames = new Set<string>();
+ const entries = [...referencesByUrl.values()];
+ const results = new Array<ExportAsset>(entries.length);
+ const controller = new AbortController();
+ const byteBudget = new ExportByteBudget(MAX_DOCUMENT_EXPORT_BYTES);
+ let cursor = 0;
+ let primaryError: unknown;
+
+ const worker = async () => {
+ while (cursor < entries.length && !controller.signal.aborted) {
+ const index = cursor++;
+ const entry = entries[index];
+ if (!entry) return;
+ try {
+ const response = await fetchImpl(entry.url.href, {
+ credentials: 'same-origin',
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ throw new Error(`Unable to export document asset (${response.status})`);
+ }
+ const contentType = safeContentType(response.headers.get('content-type'));
+ const publicId = entry.url.pathname.match(
+ new RegExp(`/assets/(${PUBLIC_ID})/raw$`, 'i'),
+ )?.[1];
+ const preferredFilename = contentDispositionFilename(
+ response.headers.get('content-disposition'),
+ );
+ const filename = uniqueAssetFilename(
+ preferredFilename || `${publicId ?? 'asset'}${extensionForContentType(contentType)}`,
+ usedFilenames,
+ );
+ results[index] = {
+ references: [...entry.references],
+ bytes: await readExportAssetBytes(response, byteBudget),
+ contentType,
+ filename,
+ };
+ } catch (error) {
+ if (primaryError === undefined) {
+ primaryError = error;
+ controller.abort();
+ }
+ throw primaryError;
+ }
+ }
+ };
+
+ await Promise.all(
+ Array.from({ length: Math.min(DOCUMENT_EXPORT_FETCH_CONCURRENCY, entries.length) }, worker),
+ );
+ return results;
+}
+
+class ExportByteBudget {
+ private actualBytes = 0;
+ private reservedBytes = 0;
+
+ constructor(private readonly limit: number) {}
+
+ reserve(declaredBytes: number | null) {
+ let remaining = declaredBytes ?? 0;
+ if (this.actualBytes + this.reservedBytes + remaining > this.limit) {
+ throw new DocumentExportLimitError();
+ }
+ this.reservedBytes += remaining;
+ let released = false;
+ return {
+ record: (bytes: number) => {
+ const covered = Math.min(bytes, remaining);
+ remaining -= covered;
+ this.reservedBytes -= covered;
+ this.actualBytes += bytes;
+ if (this.actualBytes + this.reservedBytes > this.limit) {
+ throw new DocumentExportLimitError();
+ }
+ },
+ release: () => {
+ if (released) return;
+ released = true;
+ this.reservedBytes -= remaining;
+ remaining = 0;
+ },
+ };
+ }
+}
+
+async function readExportAssetBytes(
+ response: Response,
+ byteBudget: ExportByteBudget,
+): Promise<Uint8Array> {
+ const reservation = byteBudget.reserve(contentLength(response.headers.get('content-length')));
+ try {
+ if (!response.body) {
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ reservation.record(bytes.byteLength);
+ return bytes;
+ }
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let length = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ reservation.record(value.byteLength);
+ chunks.push(value);
+ length += value.byteLength;
+ }
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes;
+ } finally {
+ reservation.release();
+ }
+}
+
+function contentLength(value: string | null): number | null {
+ if (!value || !/^\d+$/.test(value)) return null;
+ const parsed = Number(value);
+ return Number.isSafeInteger(parsed) ? parsed : null;
+}
+
+function extractExportReferences(body: string): Set<string> {
+ const references = new Set<string>();
+ for (const match of body.matchAll(/\b(?:src|href)\s*=\s*["']([^"']+)["']/gi)) {
+ if (match[1]) references.add(match[1]);
+ }
+ for (const match of body.matchAll(/!?\[[^\]]*\]\(\s*(?:<([^>]+)>|([^\s)]+))/g)) {
+ const value = match[1] ?? match[2];
+ if (value) references.add(value);
+ }
+ return references;
+}
+
+function protectedDocumentAssetUrl(
+ reference: string,
+ { projectKey, documentId, base }: { projectKey: string; documentId: number; base: URL },
+): URL | null {
+ let url: URL;
+ try {
+ url = new URL(reference, base);
+ } catch {
+ return null;
+ }
+ if (url.origin !== base.origin || url.search || url.hash) return null;
+ const expected = new RegExp(
+ `^/protected-media/projects/${escapeRegExp(encodeURIComponent(projectKey))}/documents/${documentId}/assets/${PUBLIC_ID}/raw$`,
+ 'i',
+ );
+ return expected.test(url.pathname) ? url : null;
+}
+
+function replaceExportReferences(body: string, replacements: Map<string, string>): string {
+ const htmlRewritten = body.replace(
+ /\b(src|href)(\s*=\s*)(["'])([^"']+)\3/gi,
+ (match, attribute: string, separator: string, quote: string, reference: string) => {
+ const replacement = replacements.get(reference);
+ return replacement ? `${attribute}${separator}${quote}${replacement}${quote}` : match;
+ },
+ );
+ return htmlRewritten.replace(
+ /(!?\[[^\]]*\]\(\s*)(?:<([^>]+)>|([^\s)]+))(?=[\s)])/g,
+ (
+ match,
+ prefix: string,
+ wrappedReference: string | undefined,
+ reference: string | undefined,
+ ) => {
+ const replacement = replacements.get(wrappedReference ?? reference ?? '');
+ return replacement ? `${prefix}${replacement}` : match;
+ },
+ );
+}
+
+function safeContentType(value: string | null): string {
+ const contentType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
+ return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)
+ ? contentType
+ : 'application/octet-stream';
+}
+
+function contentDispositionFilename(value: string | null): string | null {
+ if (!value) return null;
+ const encoded = value.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
+ const plain = value.match(/filename="?([^";]+)"?/i)?.[1];
+ const candidate = encoded ? safeDecodeURIComponent(encoded) : plain;
+ return candidate ? sanitizeAssetFilename(candidate) : null;
+}
+
+function sanitizeAssetFilename(value: string): string {
+ const basename = value.replaceAll('\\', '/').split('/').pop() ?? '';
+ const sanitized = basename
+ .normalize('NFKC')
+ .replace(/[^\p{Letter}\p{Number}._-]+/gu, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 100);
+ return sanitized && sanitized !== '.' && sanitized !== '..' ? sanitized : 'asset';
+}
+
+function uniqueAssetFilename(value: string, used: Set<string>): string {
+ const safe = sanitizeAssetFilename(value);
+ const dot = safe.lastIndexOf('.');
+ const base = dot > 0 ? safe.slice(0, dot) : safe;
+ const extension = dot > 0 ? safe.slice(dot) : '';
+ let candidate = safe;
+ let suffix = 2;
+ while (used.has(candidate.toLowerCase())) candidate = `${base}-${suffix++}${extension}`;
+ used.add(candidate.toLowerCase());
+ return candidate;
+}
+
+function extensionForContentType(contentType: string): string {
+ return (
+ {
+ 'image/jpeg': '.jpg',
+ 'image/png': '.png',
+ 'image/gif': '.gif',
+ 'image/webp': '.webp',
+ 'image/svg+xml': '.svg',
+ 'application/pdf': '.pdf',
+ }[contentType] ?? ''
+ );
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ }
+ return btoa(binary);
+}
+
+function safeDecodeURIComponent(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/apps/web/src/features/documents/utils/documentList.test.ts b/apps/web/src/features/documents/utils/documentList.test.ts
new file mode 100644
index 00000000..14056bdd
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentList.test.ts
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict';
+import { describe, test } from 'node:test';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { documentBelongsToTab } from './documentList';
+
+const document = {
+ isFavorite: true,
+ isPrivate: true,
+} as ProjectDocumentSummary;
+
+describe('documentBelongsToTab', () => {
+ test('includes private pages in personal favorites', () => {
+ assert.equal(documentBelongsToTab(document, 'favorites'), true);
+ });
+
+ test('keeps private pages out of the public tab', () => {
+ assert.equal(documentBelongsToTab(document, 'public'), false);
+ assert.equal(documentBelongsToTab(document, 'private'), true);
+ });
+
+ test('lets the archived query define archived membership', () => {
+ assert.equal(documentBelongsToTab(document, 'archived'), true);
+ });
+});
diff --git a/apps/web/src/features/documents/utils/documentList.ts b/apps/web/src/features/documents/utils/documentList.ts
new file mode 100644
index 00000000..f66f8ebc
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentList.ts
@@ -0,0 +1,11 @@
+import type { ProjectDocumentSummary } from '@/lib/api';
+
+export const DOCUMENT_LIST_TABS = ['favorites', 'public', 'private', 'archived'] as const;
+
+export type DocumentListTab = (typeof DOCUMENT_LIST_TABS)[number];
+
+export function documentBelongsToTab(document: ProjectDocumentSummary, tab: DocumentListTab) {
+ if (tab === 'archived') return true;
+ if (tab === 'favorites') return document.isFavorite;
+ return tab === 'private' ? document.isPrivate : !document.isPrivate;
+}
diff --git a/apps/web/src/features/documents/utils/documentMove.test.ts b/apps/web/src/features/documents/utils/documentMove.test.ts
new file mode 100644
index 00000000..1c6ce0b2
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentMove.test.ts
@@ -0,0 +1,184 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { applyOptimisticDocumentMove, projectedDocumentMove } from './documentMove';
+
+const page = (id: number, parentId: number | null, position: number): ProjectDocumentSummary =>
+ ({ id, parentId, position, version: 1, title: `Page ${id}` }) as ProjectDocumentSummary;
+
+describe('projectedDocumentMove', () => {
+ it('indents a page below the target when dragged toward the content', () => {
+ const one = page(1, null, 0);
+ const two = page(2, null, 1);
+ const byParent = new Map<number | null, ProjectDocumentSummary[]>([[null, [one, two]]]);
+ assert.deepEqual(
+ projectedDocumentMove({
+ source: two,
+ target: one,
+ deltaX: 32,
+ ordered: [one, two],
+ byParent,
+ byId: new Map([
+ [1, one],
+ [2, two],
+ ]),
+ }),
+ { parentId: 1, position: 1, previousSiblingId: null, nextSiblingId: null },
+ );
+ });
+
+ it('refuses to move a page below one of its descendants', () => {
+ const parent = page(1, null, 0);
+ const child = page(2, 1, 0);
+ assert.equal(
+ projectedDocumentMove({
+ source: parent,
+ target: child,
+ deltaX: 32,
+ ordered: [parent, child],
+ byParent: new Map([
+ [null, [parent]],
+ [1, [child]],
+ ]),
+ byId: new Map([
+ [1, parent],
+ [2, child],
+ ]),
+ }),
+ null,
+ );
+ });
+
+ it('outdents beside the parent in logical tree order', () => {
+ const parent = page(1, null, 2);
+ const first = page(2, 1, 0);
+ const second = page(3, 1, 1);
+ const next = page(4, null, 4);
+ assert.deepEqual(
+ projectedDocumentMove({
+ source: second,
+ target: first,
+ deltaX: -32,
+ ordered: [parent, first, second, next],
+ byParent: new Map([
+ [null, [parent, next]],
+ [1, [first, second]],
+ ]),
+ byId: new Map([
+ [1, parent],
+ [2, first],
+ [3, second],
+ [4, next],
+ ]),
+ }),
+ { parentId: null, position: 3, previousSiblingId: 1, nextSiblingId: 4 },
+ );
+ });
+
+ it('refuses a self-target even when called outside the drag handler', () => {
+ const source = page(1, null, 1);
+ assert.equal(
+ projectedDocumentMove({
+ source,
+ target: source,
+ deltaX: 0,
+ ordered: [source],
+ byParent: new Map([[null, [source]]]),
+ byId: new Map([[source.id, source]]),
+ }),
+ null,
+ );
+ });
+
+ it('uses the sibling anchors when numeric positions no longer have a midpoint', () => {
+ const source = page(1, 9, 1);
+ const target = page(2, null, 10_000_000_000_000_000);
+ const next = page(3, null, 10_000_000_000_000_002);
+ const result = projectedDocumentMove({
+ source,
+ target,
+ deltaX: 0,
+ ordered: [source, target, next],
+ byParent: new Map([
+ [null, [target, next]],
+ [9, [source]],
+ ]),
+ byId: new Map([
+ [source.id, source],
+ [target.id, target],
+ [next.id, next],
+ ]),
+ });
+
+ assert.deepEqual(result, {
+ parentId: null,
+ position: 2048,
+ previousSiblingId: target.id,
+ nextSiblingId: next.id,
+ });
+ });
+});
+
+describe('applyOptimisticDocumentMove', () => {
+ it('projects the complete target sibling order without duplicate positions', () => {
+ const one = page(1, null, 1024);
+ const two = page(2, null, 2048);
+ const three = page(3, null, 3072);
+
+ const result = applyOptimisticDocumentMove([one, two, three], {
+ documentId: 3,
+ parentId: null,
+ position: 1536,
+ previousSiblingId: 1,
+ nextSiblingId: 2,
+ });
+
+ assert.deepEqual(
+ result
+ .filter((document) => document.parentId === null)
+ .sort((left, right) => left.position - right.position)
+ .map(({ id, position, version }) => ({ id, position, version })),
+ [
+ { id: 1, position: 1024, version: 1 },
+ { id: 3, position: 2048, version: 2 },
+ { id: 2, position: 3072, version: 1 },
+ ],
+ );
+ });
+
+ it('normalizes only the destination siblings for a nested move', () => {
+ const parent = page(1, null, 1024);
+ const source = page(2, null, 2048);
+ const child = page(3, 1, 4096);
+
+ const result = applyOptimisticDocumentMove([parent, source, child], {
+ documentId: 2,
+ parentId: 1,
+ position: 5120,
+ previousSiblingId: 3,
+ nextSiblingId: null,
+ });
+
+ assert.deepEqual(
+ result.map(({ id, parentId, position, version }) => ({ id, parentId, position, version })),
+ [
+ { id: 1, parentId: null, position: 1024, version: 1 },
+ { id: 2, parentId: 1, position: 2048, version: 2 },
+ { id: 3, parentId: 1, position: 1024, version: 1 },
+ ],
+ );
+ });
+
+ it('keeps the cache unchanged when an anchor is absent', () => {
+ const documents = [page(1, null, 1024), page(2, null, 2048)];
+ const result = applyOptimisticDocumentMove(documents, {
+ documentId: 2,
+ parentId: null,
+ position: 1,
+ previousSiblingId: 999,
+ nextSiblingId: null,
+ });
+
+ assert.equal(result, documents);
+ });
+});
diff --git a/apps/web/src/features/documents/utils/documentMove.ts b/apps/web/src/features/documents/utils/documentMove.ts
new file mode 100644
index 00000000..80f81695
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentMove.ts
@@ -0,0 +1,175 @@
+import type { ProjectDocumentSummary } from '@/lib/api';
+
+export interface OptimisticDocumentMove {
+ documentId: number;
+ parentId: number | null;
+ position: number;
+ previousSiblingId: number | null;
+ nextSiblingId: number | null;
+}
+
+export function applyOptimisticDocumentMove(
+ documents: ProjectDocumentSummary[],
+ move: OptimisticDocumentMove,
+): ProjectDocumentSummary[] {
+ const source = documents.find((document) => document.id === move.documentId);
+ if (!source) return documents;
+
+ const siblings = documents
+ .filter((document) => document.id !== move.documentId && document.parentId === move.parentId)
+ .sort(comparePosition);
+ const insertionIndex = insertionIndexFromAnchors(siblings, move);
+ if (insertionIndex === null) return documents;
+
+ siblings.splice(insertionIndex, 0, {
+ ...source,
+ parentId: move.parentId,
+ position: move.position,
+ version: source.version + 1,
+ });
+
+ const normalizedPositions = new Map(
+ siblings.map((document, index) => [document.id, (index + 1) * 1024]),
+ );
+ return documents.map((document) => {
+ const position = normalizedPositions.get(document.id);
+ if (position === undefined) return document;
+ if (document.id === move.documentId) {
+ return {
+ ...document,
+ parentId: move.parentId,
+ position,
+ version: document.version + 1,
+ };
+ }
+ return { ...document, position };
+ });
+}
+
+export function projectedDocumentMove({
+ source,
+ target,
+ deltaX,
+ ordered,
+ byParent,
+ byId,
+}: {
+ source: ProjectDocumentSummary;
+ target: ProjectDocumentSummary;
+ deltaX: number;
+ ordered: ProjectDocumentSummary[];
+ byParent: Map<number | null, ProjectDocumentSummary[]>;
+ byId: Map<number, ProjectDocumentSummary>;
+}): Omit<OptimisticDocumentMove, 'documentId'> | null {
+ if (source.id === target.id) return null;
+
+ const descendants = descendantIds(source.id, byParent);
+ let parentId = target.parentId;
+ let anchor = target;
+ let placeAfterAnchor = false;
+
+ if (deltaX > 24) {
+ if (descendants.has(target.id)) return null;
+ parentId = target.id;
+ } else if (deltaX < -24 && target.parentId !== null) {
+ const parent = byId.get(target.parentId);
+ if (!parent) return null;
+ parentId = parent.parentId;
+ anchor = parent;
+ placeAfterAnchor = true;
+ } else {
+ const sourceIndex = ordered.findIndex((document) => document.id === source.id);
+ const targetIndex = ordered.findIndex((document) => document.id === target.id);
+ if (sourceIndex < 0 || targetIndex < 0) return null;
+ placeAfterAnchor = sourceIndex < targetIndex;
+ }
+
+ if (parentId === source.id || (parentId !== null && descendants.has(parentId))) return null;
+
+ const siblings = [...(byParent.get(parentId) ?? [])]
+ .filter((document) => document.id !== source.id)
+ .sort(comparePosition);
+ if (parentId === target.id) {
+ const previous = siblings.at(-1);
+ return {
+ parentId,
+ position: positionForRequest(previous, undefined, siblings.length),
+ previousSiblingId: previous?.id ?? null,
+ nextSiblingId: null,
+ };
+ }
+
+ const anchorIndex = siblings.findIndex((document) => document.id === anchor.id);
+ if (anchorIndex < 0) return null;
+ const insertionIndex = anchorIndex + (placeAfterAnchor ? 1 : 0);
+ const previous = siblings[insertionIndex - 1];
+ const next = siblings[insertionIndex];
+ return {
+ parentId,
+ position: positionForRequest(previous, next, insertionIndex),
+ previousSiblingId: previous?.id ?? null,
+ nextSiblingId: next?.id ?? null,
+ };
+}
+
+function insertionIndexFromAnchors(
+ siblings: ProjectDocumentSummary[],
+ move: Pick<OptimisticDocumentMove, 'previousSiblingId' | 'nextSiblingId'>,
+): number | null {
+ const previousIndex =
+ move.previousSiblingId === null
+ ? -1
+ : siblings.findIndex((document) => document.id === move.previousSiblingId);
+ const nextIndex =
+ move.nextSiblingId === null
+ ? siblings.length
+ : siblings.findIndex((document) => document.id === move.nextSiblingId);
+
+ if (move.previousSiblingId !== null && previousIndex < 0) return null;
+ if (move.nextSiblingId !== null && nextIndex < 0) return null;
+ if (
+ move.previousSiblingId !== null &&
+ move.nextSiblingId !== null &&
+ previousIndex >= nextIndex
+ ) {
+ return null;
+ }
+ if (move.previousSiblingId !== null) return previousIndex + 1;
+ if (move.nextSiblingId !== null) return nextIndex;
+ return 0;
+}
+
+function descendantIds(
+ documentId: number,
+ byParent: Map<number | null, ProjectDocumentSummary[]>,
+): Set<number> {
+ const descendants = new Set<number>();
+ const pending = [...(byParent.get(documentId) ?? [])];
+ while (pending.length > 0) {
+ const document = pending.pop()!;
+ if (document.id === documentId || descendants.has(document.id)) continue;
+ descendants.add(document.id);
+ pending.push(...(byParent.get(document.id) ?? []));
+ }
+ return descendants;
+}
+
+function positionForRequest(
+ previous: ProjectDocumentSummary | undefined,
+ next: ProjectDocumentSummary | undefined,
+ insertionIndex: number,
+): number {
+ if (!previous && !next) return 1;
+ if (!previous) return next!.position - 1;
+ if (!next) return previous.position + 1;
+
+ const midpoint = previous.position + (next.position - previous.position) / 2;
+ if (Number.isFinite(midpoint) && midpoint > previous.position && midpoint < next.position) {
+ return midpoint;
+ }
+ return (insertionIndex + 1) * 1024;
+}
+
+function comparePosition(left: ProjectDocumentSummary, right: ProjectDocumentSummary): number {
+ return left.position - right.position || left.id - right.id;
+}
diff --git a/apps/web/src/features/documents/utils/documentTree.test.ts b/apps/web/src/features/documents/utils/documentTree.test.ts
new file mode 100644
index 00000000..61d25bdf
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentTree.test.ts
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import type { ProjectDocumentSummary } from '@/lib/api';
+import { documentAncestors } from './documentTree';
+
+function document(id: number, parentId: number | null, title: string): ProjectDocumentSummary {
+ return {
+ id,
+ projectId: 1,
+ parentId,
+ title,
+ icon: null,
+ metadata: {},
+ fullWidth: false,
+ isPrivate: false,
+ isLocked: false,
+ isFavorite: false,
+ archivedAt: null,
+ position: id,
+ version: 1,
+ ownerUserId: null,
+ createdByUserId: null,
+ updatedByUserId: null,
+ createdAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ };
+}
+
+describe('documentAncestors', () => {
+ it('returns the root-first path for a nested document', () => {
+ const root = document(1, null, 'Root');
+ const section = document(2, 1, 'Section');
+ const page = document(3, 2, 'Page');
+
+ assert.deepEqual(documentAncestors(page, [page, root, section]), [root, section]);
+ });
+
+ it('stops safely when malformed data contains a cycle', () => {
+ const first = document(1, 2, 'First');
+ const second = document(2, 1, 'Second');
+
+ assert.deepEqual(documentAncestors(first, [first, second]), [second]);
+ });
+});
diff --git a/apps/web/src/features/documents/utils/documentTree.ts b/apps/web/src/features/documents/utils/documentTree.ts
new file mode 100644
index 00000000..65022959
--- /dev/null
+++ b/apps/web/src/features/documents/utils/documentTree.ts
@@ -0,0 +1,21 @@
+import type { ProjectDocumentSummary } from '@/lib/api';
+
+export function documentAncestors(
+ document: ProjectDocumentSummary,
+ documents: ProjectDocumentSummary[],
+): ProjectDocumentSummary[] {
+ const byId = new Map(documents.map((item) => [item.id, item]));
+ const seen = new Set<number>([document.id]);
+ const ancestors: ProjectDocumentSummary[] = [];
+ let parentId = document.parentId;
+
+ while (parentId !== null && !seen.has(parentId)) {
+ seen.add(parentId);
+ const parent = byId.get(parentId);
+ if (!parent) break;
+ ancestors.unshift(parent);
+ parentId = parent.parentId;
+ }
+
+ return ancestors;
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
index 099d68ae..de002e3a 100644
--- a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx
@@ -12,6 +12,7 @@ import IssueAttachmentsPanel from './IssueAttachmentsPanel';
import IssueChecklistsPanel from './IssueChecklistsPanel';
import IssueLinksPanel from './IssueLinksPanel';
import IssueDevelopmentPanel from './IssueDevelopmentPanel';
+import IssueDocumentsPanel from './IssueDocumentsPanel';
import IssueWorklogPanel from './IssueWorklogPanel';
import IssueSubtasksPanel from './IssueSubtasksPanel';
import IssueActivityFeed from './IssueActivityFeed';
@@ -72,7 +73,10 @@ export default function IssueDetailContent({
imageAttachments,
setDescEditor,
} = useIssueDetail(project, issueId, onIssueLoaded);
- const canEdit = usePermissions(project).can('work_items', 'edit');
+ const permissions = usePermissions(project);
+ const canEdit = permissions.can('work_items', 'edit');
+ const canReadDocuments = permissions.can('documents', 'read');
+ const canLinkDocuments = canEdit && permissions.can('documents', 'edit');
const features = useProjectFeatures();
useFilePaste(canEdit && issue ? (files) => void attachFiles(files) : null);
const properties = usePersistedOpen('issue-properties-open');
@@ -185,6 +189,15 @@ export default function IssueDetailContent({
<IssueDevelopmentPanel issueId={issue.id} links={issue.development ?? []} canEdit={canEdit} />
+ {features.documents && (
+ <IssueDocumentsPanel
+ projectKey={project.project.key}
+ issueId={issue.id}
+ canRead={canReadDocuments}
+ canLink={canLinkDocuments}
+ />
+ )}
+
<IssueLinksPanel project={project} issue={issue} />
</>
);
diff --git a/apps/web/src/features/issue/components/detail/IssueDocumentsPanel.tsx b/apps/web/src/features/issue/components/detail/IssueDocumentsPanel.tsx
new file mode 100644
index 00000000..6225efb1
--- /dev/null
+++ b/apps/web/src/features/issue/components/detail/IssueDocumentsPanel.tsx
@@ -0,0 +1,145 @@
+'use client';
+
+import Link from 'next/link';
+import { useState } from 'react';
+import { FileText, Loader2, Lock, Plus, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import ArchivedBadge from '@/components/common/ArchivedBadge';
+import { documentPath } from '@/utils/paths';
+import DocumentPickerDialog from '@/features/documents/components/DocumentPickerDialog';
+import {
+ useIssueDocumentLinksQuery,
+ useLinkDocumentIssue,
+ useUnlinkDocumentIssue,
+} from '@/features/documents/services/documents.service';
+import { useTranslations } from 'next-intl';
+import { usePersistedOpen } from '../../hooks/usePersistedOpen';
+import IssueSectionHeading from './IssueSectionHeading';
+
+export default function IssueDocumentsPanel({
+ projectKey,
+ issueId,
+ canRead,
+ canLink,
+}: {
+ projectKey: string;
+ issueId: number;
+ canRead: boolean;
+ canLink: boolean;
+}) {
+ const t = useTranslations('issue.documents');
+ const { open, toggle } = usePersistedOpen('issue-documents-open');
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const links = useIssueDocumentLinksQuery(projectKey, issueId, canRead);
+ const linkDocument = useLinkDocumentIssue(projectKey);
+ const unlinkDocument = useUnlinkDocumentIssue(projectKey);
+ const linkedIds = new Set((links.data ?? []).map((link) => link.documentId));
+
+ if (!canRead || (!links.isLoading && !links.isError && linkedIds.size === 0 && !canLink)) {
+ return null;
+ }
+
+ return (
+ <div className={`mt-6 border-t pt-5 ${open ? '' : '-mb-2'}`}>
+ <div className={`flex h-7 items-center gap-2 ${open ? 'mb-3' : ''}`}>
+ <IssueSectionHeading
+ label={t('title')}
+ tally={linkedIds.size > 0 ? String(linkedIds.size) : undefined}
+ open={open}
+ onToggle={toggle}
+ />
+ {canLink && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="ms-auto"
+ aria-label={t('add')}
+ title={t('add')}
+ disabled={linkDocument.isPending}
+ onClick={() => setPickerOpen(true)}
+ >
+ <Plus />
+ </Button>
+ )}
+ </div>
+
+ {open && (
+ <div className="space-y-1.5">
+ {links.isLoading ? (
+ <div className="flex h-12 items-center justify-center text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ ) : links.isError ? (
+ <button
+ type="button"
+ className="w-full rounded-md border border-dashed px-3 py-4 text-xs text-muted-foreground hover:text-foreground"
+ onClick={() => void links.refetch()}
+ >
+ {t('loadFailed')}
+ </button>
+ ) : links.data?.length ? (
+ links.data.map((link) => {
+ const removing =
+ unlinkDocument.isPending &&
+ unlinkDocument.variables?.documentId === link.documentId;
+ return (
+ <div
+ key={link.documentId}
+ className="group flex items-center gap-2 rounded-lg border bg-card/40 px-2.5 py-2"
+ >
+ <Link
+ href={documentPath(projectKey, link.documentId)}
+ className="flex min-w-0 flex-1 items-center gap-2 rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <span className="grid size-7 shrink-0 place-items-center rounded-md border bg-muted/30 text-sm">
+ {link.icon || <FileText className="size-3.5" />}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-sm" dir="auto">
+ {link.title.trim() || t('untitled')}
+ </span>
+ {link.isPrivate && <Lock className="size-3.5 text-muted-foreground" />}
+ {link.archived && <ArchivedBadge />}
+ </Link>
+ {canLink && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground opacity-100 hover:text-destructive sm:opacity-0 sm:group-focus-within:opacity-100 sm:group-hover:opacity-100"
+ aria-label={t('remove', { title: link.title || t('untitled') })}
+ disabled={unlinkDocument.isPending}
+ onClick={() =>
+ unlinkDocument.mutate({ documentId: link.documentId, issueId })
+ }
+ >
+ {removing ? <Loader2 className="animate-spin" /> : <X />}
+ </Button>
+ )}
+ </div>
+ );
+ })
+ ) : (
+ <p className="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
+ {t('empty')}
+ </p>
+ )}
+ </div>
+ )}
+
+ {pickerOpen && (
+ <DocumentPickerDialog
+ projectKey={projectKey}
+ linkedDocumentIds={linkedIds}
+ onClose={() => setPickerOpen(false)}
+ onPick={(document) => {
+ void linkDocument
+ .mutateAsync({ documentId: document.id, issueId })
+ .then(() => setPickerOpen(false))
+ .catch(() => undefined);
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/issue/components/detail/IssueProperties.tsx b/apps/web/src/features/issue/components/detail/IssueProperties.tsx
index c84549a0..fded3252 100644
--- a/apps/web/src/features/issue/components/detail/IssueProperties.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueProperties.tsx
@@ -143,7 +143,14 @@ export default function IssueProperties({
watchers && (
<IssuePropertyRow key="watching" label={t('watching')}>
- <IssueWatchers issueId={issue.id} watchers={watchers} />
+ <IssueWatchers
+ issueId={issue.id}
+ watchers={watchers}
+ members={project.assignees.filter(
+ (assignee) => assignee.kind === 'member' && assignee.canReadWorkItems,
+ )}
+ canManage={!readOnly}
+ />
</IssuePropertyRow>
),
],
diff --git a/apps/web/src/features/issue/components/detail/IssueWatchers.tsx b/apps/web/src/features/issue/components/detail/IssueWatchers.tsx
index fc3c5ef6..4424ec64 100644
--- a/apps/web/src/features/issue/components/detail/IssueWatchers.tsx
+++ b/apps/web/src/features/issue/components/detail/IssueWatchers.tsx
@@ -1,28 +1,77 @@
-import { Eye, EyeOff } from 'lucide-react';
-import { type IssueWatcher } from '@/lib/api';
+import { Check, Eye, EyeOff, LoaderCircle, UserPlus } from 'lucide-react';
+import { useIsMutating } from '@tanstack/react-query';
+import { type Assignee, type IssueWatcher } from '@/lib/api';
import { useSession } from '@/lib/auth-client';
import Avatar from '@/components/common/Avatar';
import { Pill } from '@/components/common/fields/Pill';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { useSetIssueWatching } from '../../services/watchers.service';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@/components/ui/command';
+import {
+ useSetIssueWatcher,
+ useSetIssueWatching,
+ watcherMutationKey,
+} from '../../services/watchers.service';
import { useTranslations } from 'next-intl';
-// Who follows the issue, and the button the signed-in member subscribes and
-// unsubscribes themselves with. Members subscribe only themselves, so the stack is
-// a display, not a picker — the signed-in member is in it too, marked in their
-// tooltip.
+// Who follows the issue. Everyone can subscribe themselves; members who may edit
+// the issue can also curate the watcher list from the avatar-stack picker.
export default function IssueWatchers({
issueId,
watchers,
+ members,
+ canManage = false,
}: {
issueId: number;
watchers: IssueWatcher[];
+ members: Assignee[];
+ canManage?: boolean;
}) {
const t = useTranslations('issue.watchers');
const { data: session } = useSession();
const currentUserId = session?.user.id ?? null;
const watching = watchers.some((w) => w.userId === currentUserId);
- const setWatching = useSetIssueWatching();
+ const setWatching = useSetIssueWatching(issueId);
+ const setWatcher = useSetIssueWatcher(issueId);
+ const watcherWrites = useIsMutating({ mutationKey: watcherMutationKey(issueId) });
+ const writePending = watcherWrites > 0;
+ const watcherIds = new Set(watchers.map((watcher) => watcher.userId));
+
+ const toggleWatcher = (userId: string) => {
+ setWatcher.mutate({ userId, watching: !watcherIds.has(userId) });
+ };
+
+ const watcherStack = watchers.length > 0 && (
+ <span className="flex items-center -space-x-1.5 rtl:space-x-reverse">
+ {watchers.slice(0, 4).map((watcher) => (
+ <Tooltip key={watcher.userId}>
+ <TooltipTrigger asChild>
+ <Avatar
+ name={watcher.name}
+ image={watcher.image}
+ className="size-5 ring-2 ring-card transition-transform hover:z-10 hover:scale-110"
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ {watcher.userId === currentUserId ? t('you', { name: watcher.name }) : watcher.name}
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ {watchers.length > 4 && (
+ <span className="relative z-10 flex size-5 items-center justify-center rounded-full bg-muted text-[10px] ring-2 ring-card">
+ +{watchers.length - 4}
+ </span>
+ )}
+ </span>
+ );
return (
<div className="flex flex-wrap items-center gap-1.5">
@@ -31,30 +80,87 @@ export default function IssueWatchers({
the stack of watchers next to it shows. */}
<Pill
active={watching}
- disabled={setWatching.isPending}
- onClick={() => setWatching.mutate({ issueId, watching: !watching })}
+ disabled={!currentUserId || writePending}
+ onClick={() => setWatching.mutate({ watching: !watching })}
>
{watching ? <EyeOff /> : <Eye />}
{watching ? t('unwatch') : t('watch')}
</Pill>
- {/* Negative spacing so the avatars overlap; the ring in the card color keeps
- them separated. */}
- <div className="flex items-center -space-x-1.5">
- {watchers.map((watcher) => (
- <Tooltip key={watcher.userId}>
- <TooltipTrigger asChild>
- <Avatar
- name={watcher.name}
- image={watcher.image}
- className="ring-2 ring-card transition-transform hover:z-10 hover:scale-110"
- />
- </TooltipTrigger>
- <TooltipContent>
- {watcher.userId === currentUserId ? `${watcher.name} (you)` : watcher.name}
- </TooltipContent>
- </Tooltip>
- ))}
- </div>
+ {canManage ? (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-7 min-w-7 gap-1 px-1.5 hover:bg-muted"
+ aria-label={t('manage')}
+ title={t('manage')}
+ >
+ {watcherStack}
+ {writePending ? (
+ <LoaderCircle className="size-3.5 animate-spin text-muted-foreground" />
+ ) : (
+ <UserPlus className="size-3.5 text-muted-foreground" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-72 p-0">
+ <Command>
+ <CommandInput aria-label={t('search')} placeholder={t('search')} />
+ <CommandList>
+ <CommandEmpty>{t('empty')}</CommandEmpty>
+ <CommandGroup heading={t('manage')}>
+ {members.map((member) => {
+ const selected = watcherIds.has(member.userId);
+ return (
+ <CommandItem
+ key={member.userId}
+ value={`${member.name} ${member.email}`}
+ aria-label={
+ selected
+ ? t('remove', { name: `${member.name} (${member.email})` })
+ : t('add', { name: `${member.name} (${member.email})` })
+ }
+ disabled={writePending}
+ onSelect={() => toggleWatcher(member.userId)}
+ >
+ <Avatar name={member.name} image={member.image} className="size-6" />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate" dir="auto">
+ {member.name}
+ </span>
+ <span className="truncate text-xs text-muted-foreground" dir="ltr">
+ {member.email}
+ </span>
+ </span>
+ {setWatcher.isPending && setWatcher.variables?.userId === member.userId ? (
+ <LoaderCircle className="animate-spin" />
+ ) : (
+ <Check className={selected ? 'opacity-100' : 'opacity-0'} />
+ )}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ ) : watchers.length > 0 ? (
+ <span
+ className="flex h-7 items-center px-1"
+ role="group"
+ aria-label={t('watchingCount', { count: watchers.length })}
+ >
+ {watcherStack}
+ <span className="sr-only">{watchers.map((watcher) => watcher.name).join(', ')}</span>
+ </span>
+ ) : (
+ <span className="text-xs text-muted-foreground">
+ {t('watchingCount', { count: watchers.length })}
+ </span>
+ )}
</div>
);
}
diff --git a/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx b/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
index e3724656..a5839580 100644
--- a/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
+++ b/apps/web/src/features/issue/components/editor/IssueMarkdownEditor.tsx
@@ -7,10 +7,10 @@ import Placeholder from '@tiptap/extension-placeholder';
import Link from '@tiptap/extension-link';
import { common, createLowlight } from 'lowlight';
import { Markdown } from 'tiptap-markdown';
-import { ResizableImage } from '../../utils/tiptap-image';
+import { ResizableImage } from '@/components/common/editor/tiptap-image';
import { Mention } from '@/lib/tiptap-mention';
import { SlashCommand } from '@/lib/tiptap-slash-command';
-import { MarkdownTable } from '../../utils/tiptap-table';
+import { MarkdownTable } from '@/components/common/editor/tiptap-table';
import { Video } from '../../utils/tiptap-video';
import { attachmentHtml, type Embeddable } from '../../utils/attachmentEmbed';
import { openLinkOnModifierClick } from '../../utils/modifierClickLink';
diff --git a/apps/web/src/features/issue/hooks/useIssueDetail.ts b/apps/web/src/features/issue/hooks/useIssueDetail.ts
index 81963313..b0615001 100644
--- a/apps/web/src/features/issue/hooks/useIssueDetail.ts
+++ b/apps/web/src/features/issue/hooks/useIssueDetail.ts
@@ -54,7 +54,11 @@ export function useIssueDetail(
// comments (including an agent's reply to a mention) show without a manual reload.
useLiveRefresh({
scope: revScope.issue(issueId),
- targets: [qk.issue(issueId), qk.feed(issueId)],
+ targets: [
+ qk.issue(issueId),
+ qk.feed(issueId),
+ qk.issueDocumentLinks(project.project.key, issueId),
+ ],
});
// Upload a file dropped onto a markdown editor. Returns the attachment so the
diff --git a/apps/web/src/features/issue/services/watchers.service.ts b/apps/web/src/features/issue/services/watchers.service.ts
index a9120f75..ccf9b8e9 100644
--- a/apps/web/src/features/issue/services/watchers.service.ts
+++ b/apps/web/src/features/issue/services/watchers.service.ts
@@ -6,15 +6,41 @@ import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api, type IssueWithWatchers } from '@/lib/api';
import { qk } from '@/services/queryKeys';
-export function useSetIssueWatching() {
+export const watcherMutationKey = (issueId: number) => ['issue-watchers', issueId] as const;
+
+function updateWatchers(
+ qc: ReturnType<typeof useQueryClient>,
+ issueId: number,
+ watchers: IssueWithWatchers['watchers'],
+) {
+ qc.setQueryData<IssueWithWatchers>(qk.issue(issueId), (prev) =>
+ prev ? { ...prev, watchers } : prev,
+ );
+}
+
+// All watcher writes for one issue share a TanStack mutation scope. That makes
+// self-service and editor changes run serially even if the responsive detail has
+// two mounted property panes while crossing a breakpoint.
+export function useSetIssueWatching(issueId: number) {
const qc = useQueryClient();
return useMutation({
- mutationFn: ({ issueId, watching }: { issueId: number; watching: boolean }) =>
+ mutationKey: watcherMutationKey(issueId),
+ mutationFn: ({ watching }: { watching: boolean }) =>
watching ? api.watchIssue(issueId) : api.unwatchIssue(issueId),
- onSuccess: (watchers, { issueId }) => {
- qc.setQueryData<IssueWithWatchers>(qk.issue(issueId), (prev) =>
- prev ? { ...prev, watchers } : prev,
- );
- },
+ scope: { id: `issue-watchers-${issueId}` },
+ onSuccess: (watchers) => updateWatchers(qc, issueId, watchers),
+ onSettled: () => void qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
+ });
+}
+
+export function useSetIssueWatcher(issueId: number) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationKey: watcherMutationKey(issueId),
+ mutationFn: ({ userId, watching }: { userId: string; watching: boolean }) =>
+ watching ? api.addIssueWatcher(issueId, userId) : api.removeIssueWatcher(issueId, userId),
+ scope: { id: `issue-watchers-${issueId}` },
+ onSuccess: (watchers) => updateWatchers(qc, issueId, watchers),
+ onSettled: () => void qc.invalidateQueries({ queryKey: qk.issue(issueId) }),
});
}
diff --git a/apps/web/src/features/settings/components/general/SettingsFeatures.tsx b/apps/web/src/features/settings/components/general/SettingsFeatures.tsx
index df9dcdf2..61c6c6f3 100644
--- a/apps/web/src/features/settings/components/general/SettingsFeatures.tsx
+++ b/apps/web/src/features/settings/components/general/SettingsFeatures.tsx
@@ -13,6 +13,7 @@ const FEATURES = [
'dashboards',
'initiatives',
'cycles',
+ 'documents',
'notes',
'subtasks',
'checklists',
diff --git a/apps/web/src/hooks/useNavigationCommands.tsx b/apps/web/src/hooks/useNavigationCommands.tsx
index b17a6f67..5b2bc10a 100644
--- a/apps/web/src/hooks/useNavigationCommands.tsx
+++ b/apps/web/src/hooks/useNavigationCommands.tsx
@@ -1,6 +1,7 @@
import { useRouter } from 'next/navigation';
import {
Bell,
+ BookOpenText,
Braces,
FolderKanban,
Inbox,
@@ -18,6 +19,7 @@ import {
aiTeamPath,
apiDocsPath,
dashboardsPath,
+ documentsPath,
godPath,
inboxPath,
initiativesPath,
@@ -78,6 +80,14 @@ export function useNavigationCommands(projectKey: string | null): CommandSection
);
if (features.initiatives && can('initiatives', 'read'))
add('nav.initiatives', t('initiatives'), <Target />, initiativesPath(key), 'epics');
+ if (features.documents && can('documents', 'read'))
+ add(
+ 'nav.documents',
+ t('documents'),
+ <BookOpenText />,
+ documentsPath(key),
+ 'docs pages documentation',
+ );
for (const s of AI_TEAM_SECTIONS) {
if (can(s.resource, 'read'))
add(
diff --git a/apps/web/src/i18n/messages.ts b/apps/web/src/i18n/messages.ts
index 8875e62f..3a2bbb19 100644
--- a/apps/web/src/i18n/messages.ts
+++ b/apps/web/src/i18n/messages.ts
@@ -6,6 +6,7 @@ import common from '../../messages/en/common.json';
import cycles from '../../messages/en/cycles.json';
import dashboards from '../../messages/en/dashboards.json';
import display from '../../messages/en/display.json';
+import documents from '../../messages/en/documents.json';
import filters from '../../messages/en/filters.json';
import god from '../../messages/en/god.json';
import inbox from '../../messages/en/inbox.json';
@@ -44,6 +45,7 @@ const defaultMessages = {
issueLinks,
issue,
display,
+ documents,
filters,
workItems,
apiKeys,
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index b06d846a..d149671d 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -118,6 +118,7 @@ export interface Project {
// useProjectFeatures, which hides the navigation and the section itself.
initiativesEnabled: boolean;
dashboardsEnabled: boolean;
+ documentsEnabled: boolean;
notesEnabled: boolean;
cyclesEnabled: boolean;
subtasksEnabled: boolean;
@@ -151,6 +152,7 @@ export type CopyProjectIncludeKey =
| 'customFields'
| 'views'
| 'dashboards'
+ | 'documents'
| 'actions'
| 'configuration'
| 'roles'
@@ -221,6 +223,9 @@ export interface Assignee {
// The user an 'owner'-scoped agent works for: delegating it to anyone else queues a
// run its runner never receives. Null for members and project-scoped agents.
restrictedToUserId: string | null;
+ // Whether this person may read issues and can therefore receive watcher
+ // notifications without leaking work-item content.
+ canReadWorkItems: boolean;
}
// One member custom field an agent reacts to, with the seconds its run waits.
@@ -1047,6 +1052,7 @@ export interface ProjectFeatures {
initiatives: boolean;
cycles: boolean;
dashboards: boolean;
+ documents: boolean;
notes: boolean;
subtasks: boolean;
checklists: boolean;
@@ -1623,6 +1629,143 @@ export interface NoteBoardListParams {
offset?: number;
}
+export interface ProjectDocumentSummary {
+ id: number;
+ projectId: number;
+ parentId: number | null;
+ title: string;
+ icon: string | null;
+ metadata: Record<string, unknown>;
+ fullWidth: boolean;
+ isPrivate: boolean;
+ isLocked: boolean;
+ isFavorite: boolean;
+ archivedAt: string | null;
+ position: number;
+ version: number;
+ ownerUserId: string | null;
+ createdByUserId: string | null;
+ updatedByUserId: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface ProjectDocument extends ProjectDocumentSummary {
+ content: string;
+ contentJson: Record<string, unknown> | null;
+}
+
+export interface DocumentIssueLink {
+ issueId: number;
+ sequenceNumber: number;
+ identifier: string;
+ title: string;
+ archived: boolean;
+ createdAt: string;
+}
+
+export interface IssueDocumentLink {
+ documentId: number;
+ title: string;
+ icon: string | null;
+ isPrivate: boolean;
+ archived: boolean;
+ createdAt: string;
+}
+
+export interface NewProjectDocumentInput {
+ title?: string;
+ content?: string;
+ contentJson?: Record<string, unknown> | null;
+ icon?: string | null;
+ metadata?: Record<string, unknown>;
+ fullWidth?: boolean;
+ isPrivate?: boolean;
+ parentId?: number | null;
+}
+
+export interface ProjectDocumentPatch {
+ version: number;
+ title?: string;
+ content?: string;
+ contentJson?: Record<string, unknown> | null;
+ icon?: string | null;
+ metadata?: Record<string, unknown>;
+ fullWidth?: boolean;
+ parentId?: number | null;
+ position?: number;
+ previousSiblingId?: number | null;
+ nextSiblingId?: number | null;
+}
+
+export interface ProjectDocumentRevisionSummary {
+ id: number;
+ documentId: number;
+ version: number;
+ title: string;
+ createdByUserId: string | null;
+ createdAt: string;
+}
+
+export interface ProjectDocumentRevision extends ProjectDocumentRevisionSummary {
+ parentId: number | null;
+ content: string;
+ contentJson: Record<string, unknown> | null;
+ icon: string | null;
+ metadata: Record<string, unknown>;
+ fullWidth: boolean;
+ isPrivate: boolean;
+ isLocked: boolean;
+ archivedAt: string | null;
+ position: number;
+}
+
+export interface ProjectDocumentExport {
+ filename: string;
+ mimeType: 'text/markdown';
+ content: string;
+ version: number;
+ exportedAt: string;
+}
+
+export interface DocumentAsset {
+ id: string;
+ filename: string;
+ contentType: string;
+ sizeBytes: number;
+ uploadedByUserId: string | null;
+ createdAt: string;
+ url: string;
+}
+
+function withDocumentAssetUrl(asset: DocumentAsset): DocumentAsset {
+ const match = asset.url.match(
+ /^\/projects\/([^/]+)\/documents\/(\d+)\/assets\/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\/raw$/i,
+ );
+ if (!match) throw new Error('The document asset URL returned by the API is invalid');
+ const [, encodedProjectKey, documentId, publicId] = match;
+ return {
+ ...asset,
+ url: `/protected-media/projects/${encodeURIComponent(decodeURIComponent(encodedProjectKey))}/documents/${documentId}/assets/${publicId}/raw`,
+ };
+}
+
+async function sendDocumentAssetFile(
+ projectKey: string,
+ documentId: number,
+ file: File,
+): Promise<DocumentAsset> {
+ const form = new FormData();
+ form.append('file', file);
+ const res = await fetch(`${API_URL}/projects/${projectKey}/documents/${documentId}/assets`, {
+ method: 'POST',
+ credentials: 'include',
+ body: form,
+ });
+ if (!res.ok) throw await apiFailure(res);
+ return withDocumentAssetUrl(await res.json());
+}
+
// --- Analytics DTOs (project metrics behind the dashboard widgets) ---------------
export interface AnalyticsStats {
@@ -2206,7 +2349,7 @@ export interface IssueWithWatchers extends IssueRelations {
// The scaffold mirrors ProjectScaffold minus the caller's viewer/permissions and
// member emails and handles (a public page shows names and avatars only).
export type PublicScaffold = Omit<ProjectScaffold, 'viewer' | 'permissions' | 'assignees'> & {
- assignees: Omit<Assignee, 'email' | 'username'>[];
+ assignees: Omit<Assignee, 'email' | 'username' | 'canReadWorkItems'>[];
};
export interface SharedIssueBundle {
@@ -2502,6 +2645,7 @@ export type PermissionResource =
| 'initiatives'
| 'cycles'
| 'dashboards'
+ | 'documents'
| 'views'
| 'members_invite'
| 'members_manage'
@@ -2940,12 +3084,17 @@ export const api = {
unlinkIssues: (issueId: number, linkId: number) =>
request<void>(`/issues/${issueId}/links/${linkId}`, { method: 'DELETE' }),
- // Following an issue, for the signed-in user only. Both return the resulting
- // watcher list.
+ // Following an issue. The singular routes act on the signed-in user; the
+ // watcher routes let an editor curate other project members. Every route
+ // returns the resulting watcher list.
watchIssue: (issueId: number) =>
request<IssueWatcher[]>(`/issues/${issueId}/watch`, { method: 'POST' }),
unwatchIssue: (issueId: number) =>
request<IssueWatcher[]>(`/issues/${issueId}/watch`, { method: 'DELETE' }),
+ addIssueWatcher: (issueId: number, userId: string) =>
+ request<IssueWatcher[]>(`/issues/${issueId}/watchers/${userId}`, { method: 'PUT' }),
+ removeIssueWatcher: (issueId: number, userId: string) =>
+ request<IssueWatcher[]>(`/issues/${issueId}/watchers/${userId}`, { method: 'DELETE' }),
setFieldValue: (issueId: number, fieldId: number, input: IssueFieldValueInput) =>
request<{ ok: boolean }>(`/issues/${issueId}/fields/${fieldId}`, {
@@ -3172,6 +3321,112 @@ export const api = {
deleteNoteBoard: (projectKey: string, boardId: number) =>
request<void>(`/projects/${projectKey}/note-boards/${boardId}`, { method: 'DELETE' }),
+ listDocuments: (projectKey: string, q?: string, archived = false) => {
+ const params = new URLSearchParams();
+ if (q) params.set('q', q);
+ if (archived) params.set('archived', 'true');
+ const suffix = params.size > 0 ? `?${params}` : '';
+ return request<ProjectDocumentSummary[]>(`/projects/${projectKey}/documents${suffix}`);
+ },
+ getDocument: (projectKey: string, documentId: number) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}`),
+ listDocumentIssueLinks: (projectKey: string, documentId: number) =>
+ request<DocumentIssueLink[]>(`/projects/${projectKey}/documents/${documentId}/issues`),
+ listIssueDocumentLinks: (projectKey: string, issueId: number) =>
+ request<IssueDocumentLink[]>(`/projects/${projectKey}/documents/for-issue/${issueId}`),
+ linkDocumentIssue: (projectKey: string, documentId: number, issueId: number) =>
+ request<DocumentIssueLink>(`/projects/${projectKey}/documents/${documentId}/issues`, {
+ method: 'POST',
+ body: JSON.stringify({ issueId }),
+ }),
+ unlinkDocumentIssue: (projectKey: string, documentId: number, issueId: number) =>
+ request<void>(`/projects/${projectKey}/documents/${documentId}/issues/${issueId}`, {
+ method: 'DELETE',
+ }),
+ createDocument: (projectKey: string, input: NewProjectDocumentInput) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
+ updateDocument: (projectKey: string, documentId: number, patch: ProjectDocumentPatch) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ }),
+ deleteDocument: (projectKey: string, documentId: number, version: number) =>
+ request<void>(`/projects/${projectKey}/documents/${documentId}?version=${version}`, {
+ method: 'DELETE',
+ }),
+ setDocumentAccess: (
+ projectKey: string,
+ documentId: number,
+ input: { version: number; isPrivate: boolean },
+ ) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}/access`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
+ setDocumentLocked: (projectKey: string, documentId: number, version: number, locked: boolean) =>
+ request<ProjectDocument>(
+ `/projects/${projectKey}/documents/${documentId}/${locked ? 'lock' : 'unlock'}`,
+ { method: 'POST', body: JSON.stringify({ version }) },
+ ),
+ archiveDocument: (projectKey: string, documentId: number, version: number) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}/archive`, {
+ method: 'POST',
+ body: JSON.stringify({ version }),
+ }),
+ restoreDocument: (projectKey: string, documentId: number, version: number) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}/restore`, {
+ method: 'POST',
+ body: JSON.stringify({ version }),
+ }),
+ duplicateDocument: (
+ projectKey: string,
+ documentId: number,
+ input: { version: number; title?: string; parentId?: number | null },
+ ) =>
+ request<ProjectDocument>(`/projects/${projectKey}/documents/${documentId}/duplicate`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
+ setDocumentFavorite: (projectKey: string, documentId: number, isFavorite: boolean) =>
+ request<{ isFavorite: boolean }>(
+ `/projects/${projectKey}/documents/${documentId}/preferences`,
+ { method: 'PATCH', body: JSON.stringify({ isFavorite }) },
+ ),
+ listDocumentRevisions: (projectKey: string, documentId: number) =>
+ request<ProjectDocumentRevisionSummary[]>(
+ `/projects/${projectKey}/documents/${documentId}/revisions`,
+ ),
+ getDocumentRevision: (projectKey: string, documentId: number, revisionId: number) =>
+ request<ProjectDocumentRevision>(
+ `/projects/${projectKey}/documents/${documentId}/revisions/${revisionId}`,
+ ),
+ restoreDocumentRevision: (
+ projectKey: string,
+ documentId: number,
+ revisionId: number,
+ version: number,
+ ) =>
+ request<ProjectDocument>(
+ `/projects/${projectKey}/documents/${documentId}/revisions/${revisionId}/restore`,
+ { method: 'POST', body: JSON.stringify({ version }) },
+ ),
+ exportDocument: (projectKey: string, documentId: number) =>
+ request<ProjectDocumentExport>(`/projects/${projectKey}/documents/${documentId}/export`),
+ listDocumentAssets: (projectKey: string, documentId: number) =>
+ request<DocumentAsset[]>(`/projects/${projectKey}/documents/${documentId}/assets`).then(
+ (assets) => assets.map(withDocumentAssetUrl),
+ ),
+ uploadDocumentAsset: (projectKey: string, documentId: number, file: File) =>
+ sendDocumentAssetFile(projectKey, documentId, file),
+ deleteDocumentAsset: (projectKey: string, documentId: number, publicId: string) =>
+ request<void>(
+ `/projects/${projectKey}/documents/${documentId}/assets/${encodeURIComponent(publicId)}`,
+ { method: 'DELETE' },
+ ),
+
// Analytics — read-only project metrics behind the dashboard widgets.
getStats: (projectKey: string) =>
request<AnalyticsStats>(`/projects/${projectKey}/analytics/stats`),
diff --git a/apps/web/src/lib/tiptap-slash-command.test.ts b/apps/web/src/lib/tiptap-slash-command.test.ts
new file mode 100644
index 00000000..96218163
--- /dev/null
+++ b/apps/web/src/lib/tiptap-slash-command.test.ts
@@ -0,0 +1,48 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { buildSlashItems } from './tiptap-slash-command';
+
+describe('buildSlashItems', () => {
+ it('exposes the complete Docs block surface without changing compact editors', () => {
+ const compact = buildSlashItems({ codeBlockLabel: 'Code' });
+ assert.deepEqual(
+ compact.map((item) => item.title),
+ ['Code'],
+ );
+
+ const docs = buildSlashItems({
+ codeBlockLabel: 'Code',
+ tableLabel: 'Table',
+ image: { label: 'Image', onPick: () => undefined },
+ blocks: {
+ paragraph: 'Text',
+ headings: ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'],
+ bulletList: 'Bullets',
+ orderedList: 'Numbers',
+ taskList: 'Tasks',
+ quote: 'Quote',
+ divider: 'Divider',
+ },
+ });
+ assert.deepEqual(
+ docs.map((item) => item.title),
+ [
+ 'Text',
+ 'H1',
+ 'H2',
+ 'H3',
+ 'H4',
+ 'H5',
+ 'H6',
+ 'Bullets',
+ 'Numbers',
+ 'Tasks',
+ 'Quote',
+ 'Code',
+ 'Divider',
+ 'Table',
+ 'Image',
+ ],
+ );
+ });
+});
diff --git a/apps/web/src/lib/tiptap-slash-command.ts b/apps/web/src/lib/tiptap-slash-command.ts
index 57ffb134..b160b795 100644
--- a/apps/web/src/lib/tiptap-slash-command.ts
+++ b/apps/web/src/lib/tiptap-slash-command.ts
@@ -1,7 +1,21 @@
import { Extension, type Editor, type Range } from '@tiptap/core';
import { ReactRenderer } from '@tiptap/react';
import Suggestion from '@tiptap/suggestion';
-import { Image as ImageIcon, SquareCode, Table, type LucideIcon } from 'lucide-react';
+import {
+ CheckSquare2,
+ Heading1,
+ Heading2,
+ Heading3,
+ Image as ImageIcon,
+ List,
+ ListOrdered,
+ Minus,
+ Pilcrow,
+ Quote,
+ SquareCode,
+ Table,
+ type LucideIcon,
+} from 'lucide-react';
import EditorSlashMenu, { type SlashMenuRef } from '@/components/common/editor/EditorSlashMenu';
export type SlashItem = {
@@ -22,15 +36,110 @@ export type SlashCommandOptions = {
tableLabel?: string;
// Omitted where there is nothing to pick from, which drops the Image item.
image?: { label: string; onPick: () => void };
+ // Editors that expose a richer block schema opt into these commands. Keeping
+ // this optional preserves the compact Issue and agent-instruction menus.
+ blocks?: {
+ paragraph: string;
+ headings: [string, string, string, string, string, string];
+ bulletList: string;
+ orderedList: string;
+ taskList: string;
+ quote: string;
+ divider: string;
+ };
};
+export function buildSlashItems(options: SlashCommandOptions): SlashItem[] {
+ const items: SlashItem[] = [];
+ if (options.blocks) {
+ items.push({
+ title: options.blocks.paragraph,
+ icon: Pilcrow,
+ run: ({ editor, range }) => editor.chain().focus().deleteRange(range).setParagraph().run(),
+ });
+ const headingIcons = [Heading1, Heading2, Heading3, Heading3, Heading3, Heading3];
+ options.blocks.headings.forEach((title, index) => {
+ const level = (index + 1) as 1 | 2 | 3 | 4 | 5 | 6;
+ items.push({
+ title,
+ icon: headingIcons[index] ?? Heading3,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).setHeading({ level }).run(),
+ });
+ });
+ items.push(
+ {
+ title: options.blocks.bulletList,
+ icon: List,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).toggleBulletList().run(),
+ },
+ {
+ title: options.blocks.orderedList,
+ icon: ListOrdered,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).toggleOrderedList().run(),
+ },
+ {
+ title: options.blocks.taskList,
+ icon: CheckSquare2,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).toggleTaskList().run(),
+ },
+ {
+ title: options.blocks.quote,
+ icon: Quote,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).toggleBlockquote().run(),
+ },
+ );
+ }
+ items.push({
+ title: options.codeBlockLabel,
+ icon: SquareCode,
+ run: ({ editor, range }) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
+ });
+ if (options.blocks) {
+ items.push({
+ title: options.blocks.divider,
+ icon: Minus,
+ run: ({ editor, range }) =>
+ editor.chain().focus().deleteRange(range).setHorizontalRule().run(),
+ });
+ }
+ if (options.tableLabel) {
+ items.push({
+ title: options.tableLabel,
+ icon: Table,
+ run: ({ editor, range }) =>
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertTable({ rows: 3, cols: 3, withHeaderRow: true })
+ .run(),
+ });
+ }
+ if (options.image) {
+ items.push({
+ title: options.image.label,
+ icon: ImageIcon,
+ run: ({ editor, range }) => {
+ editor.chain().focus().deleteRange(range).run();
+ options.image?.onPick();
+ },
+ });
+ }
+ return items;
+}
+
// Typing "/" opens a list of blocks to insert — how they are reached with nothing
// selected, where the bubble menu has nothing to hang off.
export const SlashCommand = Extension.create<SlashCommandOptions>({
name: 'slashCommand',
addProseMirrorPlugins() {
- const { codeBlockLabel, tableLabel, image, container } = this.options;
+ const { container } = this.options;
return [
Suggestion<SlashItem, SlashItem>({
@@ -38,37 +147,7 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({
char: '/',
container: container ?? '[data-slot="dialog-content"]',
items: ({ query }) => {
- const items: SlashItem[] = [
- {
- title: codeBlockLabel,
- icon: SquareCode,
- run: ({ editor, range }) =>
- editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
- },
- ];
- if (tableLabel) {
- items.push({
- title: tableLabel,
- icon: Table,
- run: ({ editor, range }) =>
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertTable({ rows: 3, cols: 3, withHeaderRow: true })
- .run(),
- });
- }
- if (image) {
- items.push({
- title: image.label,
- icon: ImageIcon,
- run: ({ editor, range }) => {
- editor.chain().focus().deleteRange(range).run();
- image.onPick();
- },
- });
- }
+ const items = buildSlashItems(this.options);
const needle = query.toLowerCase();
return items.filter((item) => item.title.toLowerCase().includes(needle));
},
diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts
index 81e9f5ee..639543b2 100644
--- a/apps/web/src/proxy.ts
+++ b/apps/web/src/proxy.ts
@@ -13,6 +13,8 @@ const PUBLIC_PATHS = ['/login', '/register'];
// anyone with the link, signed in or not.
// `/media` streams avatars and attachments from the api, which serves them without
// a session — a share page opened by a logged-out visitor shows them too.
+// `/protected-media` is intentionally absent: document assets carry private project
+// content and must pass this session gate before their route forwards the cookie.
const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media'];
// Gate the whole app behind a session. This is an optimistic check: it only looks
@@ -46,5 +48,7 @@ export function proxy(request: NextRequest) {
export const config = {
// Run on every route except Next internals and static assets.
- matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.).*)'],
+ // Protected media is listed first so a valid project key containing a dot is
+ // still session-gated instead of falling through the static-file exclusion.
+ matcher: ['/protected-media/:path*', '/((?!_next/static|_next/image|favicon.ico|.*\\.).*)'],
};
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 97ad7d8a..d63157f2 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -33,6 +33,19 @@ export const qk = {
// widgets. `kind` names the metric (stats/pulse/throughput/breakdown/...) and
// `params` scopes it to the widget's query (window, filters).
dashboards: (projectKey: string) => ['dashboards', projectKey] as const,
+ documents: (projectKey: string, q = '', archived = false) =>
+ ['documents', projectKey, 'list', archived ? 'archived' : 'active', q] as const,
+ documentListsForProject: (projectKey: string) => ['documents', projectKey, 'list'] as const,
+ document: (projectKey: string, documentId: number) =>
+ ['documents', projectKey, 'document', documentId] as const,
+ documentRevisions: (projectKey: string, documentId: number) =>
+ ['documents', projectKey, 'document', documentId, 'revisions'] as const,
+ documentAssets: (projectKey: string, documentId: number) =>
+ ['documents', projectKey, 'document', documentId, 'assets'] as const,
+ documentIssueLinks: (projectKey: string, documentId: number) =>
+ ['documents', projectKey, 'document', documentId, 'issues'] as const,
+ issueDocumentLinks: (projectKey: string, issueId: number) =>
+ ['documents', projectKey, 'issue', issueId] as const,
// Note boards (the notes canvases). `noteBoardsForProject` is the invalidation
// base for every list/search variant; `noteBoardsSearch` is one paged switcher
// query (scoped by search text); `noteBoard` is a single board with its canvas.
diff --git a/apps/web/src/utils/paths.ts b/apps/web/src/utils/paths.ts
index db49ce48..0cddb873 100644
--- a/apps/web/src/utils/paths.ts
+++ b/apps/web/src/utils/paths.ts
@@ -25,6 +25,11 @@ export const notesPath = (key: string) => `${projectPath(key)}/notes`;
export const notePath = (key: string, boardId: number) => `${notesPath(key)}/${boardId}`;
+export const documentsPath = (key: string) => `${projectPath(key)}/docs`;
+
+export const documentPath = (key: string, documentId: number) =>
+ `${documentsPath(key)}/${documentId}`;
+
export const settingsPath = (key: string, section: string) =>
`${projectPath(key)}/settings/${section}`;
diff --git a/apps/web/src/utils/permissions.ts b/apps/web/src/utils/permissions.ts
index c85ec385..ce6d9eed 100644
--- a/apps/web/src/utils/permissions.ts
+++ b/apps/web/src/utils/permissions.ts
@@ -22,6 +22,7 @@ export interface PermissionGroup {
const GROUP_DEFS: PermissionGroup[] = [
{ key: 'workItems', resources: ['work_items', 'initiatives', 'cycles', 'views'] },
{ key: 'dashboards', resources: ['dashboards'] },
+ { key: 'documents', resources: ['documents'] },
{ key: 'notes', resources: ['note_boards'] },
{ key: 'ai', resources: ['ai_agents', 'integrations', 'agent_skills', 'agent_tools'] },
{
diff --git a/apps/web/src/utils/projectFeatures.ts b/apps/web/src/utils/projectFeatures.ts
index 955403ed..b2fa7260 100644
--- a/apps/web/src/utils/projectFeatures.ts
+++ b/apps/web/src/utils/projectFeatures.ts
@@ -16,6 +16,7 @@ export function projectFeatures(project: Project | null): ProjectFeatureSet {
initiatives: project?.initiativesEnabled ?? false,
cycles: project?.cyclesEnabled ?? false,
dashboards: project?.dashboardsEnabled ?? false,
+ documents: project?.documentsEnabled ?? false,
notes: project?.notesEnabled ?? false,
subtasks: project?.subtasksEnabled ?? false,
checklists: project?.checklistsEnabled ?? false,
diff --git a/apps/web/src/utils/publicProject.ts b/apps/web/src/utils/publicProject.ts
index 6a85a6a2..aecfae79 100644
--- a/apps/web/src/utils/publicProject.ts
+++ b/apps/web/src/utils/publicProject.ts
@@ -16,7 +16,12 @@ export function toPublicProjectDetail(
issueTypes: scaffold.issueTypes,
labels: scaffold.labels,
labelGroups: scaffold.labelGroups,
- assignees: scaffold.assignees.map((a) => ({ ...a, email: '', username: null })),
+ assignees: scaffold.assignees.map((a) => ({
+ ...a,
+ email: '',
+ username: null,
+ canReadWorkItems: false,
+ })),
customFields: scaffold.customFields,
// A public page creates nothing, so it needs no templates.
issueTemplates: [],
diff --git a/apps/web/src/utils/revScopes.ts b/apps/web/src/utils/revScopes.ts
index d0815ff1..dc2a340b 100644
--- a/apps/web/src/utils/revScopes.ts
+++ b/apps/web/src/utils/revScopes.ts
@@ -6,4 +6,5 @@ export const revScope = {
issue: (issueId: number) => `issue:${issueId}`,
initiative: (initiativeId: number) => `initiative:${initiativeId}`,
inbox: (projectId: number) => `inbox:${projectId}`,
+ documents: (projectId: number) => `documents:${projectId}`,
};
diff --git a/bun.lock b/bun.lock
index d0679f73..460ba28a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -87,7 +87,9 @@
"@tanstack/react-virtual": "^3.14.9",
"@tiptap/core": "^3.30.0",
"@tiptap/extension-code-block-lowlight": "^3.30.0",
+ "@tiptap/extension-color": "3.30.0",
"@tiptap/extension-hard-break": "^3.30.0",
+ "@tiptap/extension-highlight": "3.30.0",
"@tiptap/extension-image": "^3.30.0",
"@tiptap/extension-link": "^3.30.0",
"@tiptap/extension-placeholder": "^3.30.0",
@@ -95,6 +97,8 @@
"@tiptap/extension-task-item": "^3.30.0",
"@tiptap/extension-task-list": "^3.30.0",
"@tiptap/extension-text": "^3.30.0",
+ "@tiptap/extension-text-align": "3.30.0",
+ "@tiptap/extension-text-style": "3.30.0",
"@tiptap/pm": "^3.30.0",
"@tiptap/react": "^3.30.0",
"@tiptap/starter-kit": "^3.30.0",
@@ -109,6 +113,7 @@
"highlight.js": "~11.11.0",
"inter-ui": "^4.1.1",
"isomorphic-dompurify": "^3.22.0",
+ "jszip": "^3.10.1",
"lowlight": "^3.3.0",
"lucide-react": "^1.31.0",
"marked": "^18.0.9",
@@ -1078,6 +1083,8 @@
"@tiptap/extension-code-block-lowlight": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0", "@tiptap/extension-code-block": "3.30.0", "@tiptap/pm": "3.30.0", "highlight.js": "^11", "lowlight": "^2 || ^3" } }, "sha512-SDWMmqBe38o1ORmpx2rEzuxjbmUr50/XqMtwzaE/k6jHQ8tovIcTpAEbXEBj0hSDFdeZaFZnuOGVX85Y6SHQyQ=="],
+ "@tiptap/extension-color": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extension-text-style": "3.30.0" } }, "sha512-7uZErSu6KFkBAUmJEEFO38xh7I/1d/ehWWu277soSTA2aXwyDTIn2b4J50u1Zap9x9UePNIeuZ+o1DwHJlOMZw=="],
+
"@tiptap/extension-document": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-gSXVcISMkK9IXa2YUc0TM+lkyCWaK6KgcsIoePnCWWdUGs0wtcktz3XK9mmcVu5xntg7AR7AT9B6gvl1k+MKYA=="],
"@tiptap/extension-dropcursor": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extensions": "3.30.0" } }, "sha512-RjTRfPH/fMaXYeRRp1etivWrH5vhrPEhEEY+34IrEXglp11svTp3heK1G2eIhppUKPRhsczWffSpUYEgEcEYsw=="],
@@ -1090,6 +1097,8 @@
"@tiptap/extension-heading": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-PqUZP/dPFtBtETYXkQrybfdMRntxEY9ZQv2b+8vC0U3JCE+6IUEnJaFZgAimIyN3++ZLh3gCVvI/LfqFh3UHRQ=="],
+ "@tiptap/extension-highlight": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-pdkslqEO3SOrmLjztDThHXsENFA+vVMkw1RbmBdVQl4/eNYiyz3ffx06uJhp5NahqUDoJg7BKj5Y+fFg6GRp8g=="],
+
"@tiptap/extension-horizontal-rule": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0", "@tiptap/pm": "3.30.0" } }, "sha512-SD/udnQ6aAEbyi0DSf48Yh/LAPMulgvaX83MwVhzMb/qgV7eCUbJxLsqQvaaNnVFZZyl5GHbCwTbPEdEymEIRA=="],
"@tiptap/extension-image": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-7KfGfbMv4Ak99fybGmpaUyhIKmfV7aZGl1YMrlj+uA2RQjzO597DGnLCEvdv2zfvwHi7WZODC8DVxJe8bKYNFw=="],
@@ -1120,6 +1129,10 @@
"@tiptap/extension-text": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-NjsZzbuCkDth/XIpXQbcdoDpXQarQlISBARdwVEEXq2Cv8YEJRERblO8PHUdaP7AxuxPru5ZfgbnAkbopy/fwQ=="],
+ "@tiptap/extension-text-align": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-JThXRqQzhLjZk1bi7fHd9BcCiymK2D/l108JXmnsM3wXNPS+cdRf+a511gDAXABcGBuh8rUBJer5TDfD2rLf/w=="],
+
+ "@tiptap/extension-text-style": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-6XM3KAxEI8zWLDsKA1/91TaZP06qRvaZc3qnEKUo78q0R0r0kthThREFIgt6NBf+fb35zNypueTS2H4XMKLXpw=="],
+
"@tiptap/extension-underline": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0" } }, "sha512-EJ7NF3CP96gJVmdaXUJ9GaaFKpC92flftT6/PtINK4oCBPYbyWRI8nOdeBPijm12yXGbzcPS3oyIjc2FIzkdHA=="],
"@tiptap/extensions": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.30.0", "@tiptap/pm": "3.30.0" } }, "sha512-dCevnLGpISgrMqnEse3BeZPpaPtYBdIWONIiVSl4ODDCMUthcs8QqM5qi192f0fT+jnYikD7UP3zn+hdCFOtaw=="],
diff --git a/packages/db/drizzle/0118_left_titanium_man.sql b/packages/db/drizzle/0118_left_titanium_man.sql
new file mode 100644
index 00000000..f0dbe635
--- /dev/null
+++ b/packages/db/drizzle/0118_left_titanium_man.sql
@@ -0,0 +1,411 @@
+CREATE TABLE "document_asset" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "public_id" uuid DEFAULT gen_random_uuid() NOT NULL,
+ "document_id" integer NOT NULL,
+ "uploaded_by_user_id" text,
+ "s3_key" text NOT NULL,
+ "filename" text NOT NULL,
+ "content_type" text NOT NULL,
+ "size_bytes" bigint NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "document_asset_public_id_unique" UNIQUE("public_id")
+);
+--> statement-breakpoint
+CREATE TABLE "project_document" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "project_id" integer NOT NULL,
+ "parent_id" integer,
+ "title" text DEFAULT '' NOT NULL,
+ "content" text DEFAULT '' NOT NULL,
+ "content_json" jsonb,
+ "icon" text,
+ "metadata" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "full_width" boolean DEFAULT false NOT NULL,
+ "is_private" boolean DEFAULT false NOT NULL,
+ "is_locked" boolean DEFAULT false NOT NULL,
+ "archived_at" timestamp with time zone,
+ "archived_by_ancestor_id" integer,
+ "position" double precision DEFAULT 0 NOT NULL,
+ "version" integer DEFAULT 1 NOT NULL,
+ "owner_user_id" text,
+ "created_by_user_id" text,
+ "updated_by_user_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "project_document_version_check" CHECK ("project_document"."version" > 0)
+);
+--> statement-breakpoint
+CREATE TABLE "project_document_issue" (
+ "document_id" integer NOT NULL,
+ "issue_id" integer NOT NULL,
+ "created_by_user_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "project_document_issue_document_id_issue_id_pk" PRIMARY KEY("document_id","issue_id")
+);
+--> statement-breakpoint
+CREATE TABLE "project_document_preference" (
+ "document_id" integer NOT NULL,
+ "user_id" text NOT NULL,
+ "is_favorite" boolean DEFAULT false NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "project_document_preference_document_id_user_id_pk" PRIMARY KEY("document_id","user_id")
+);
+--> statement-breakpoint
+CREATE TABLE "project_document_revision" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "document_id" integer NOT NULL,
+ "version" integer NOT NULL,
+ "parent_id" integer,
+ "title" text NOT NULL,
+ "content" text NOT NULL,
+ "content_json" jsonb,
+ "icon" text,
+ "metadata" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "full_width" boolean DEFAULT false NOT NULL,
+ "is_private" boolean DEFAULT false NOT NULL,
+ "is_locked" boolean DEFAULT false NOT NULL,
+ "archived_at" timestamp with time zone,
+ "position" double precision NOT NULL,
+ "owner_user_id" text,
+ "created_by_user_id" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "project_document_revision_document_version_unique" UNIQUE("document_id","version")
+);
+--> statement-breakpoint
+ALTER TABLE "project" ADD COLUMN "documents_enabled" boolean DEFAULT true NOT NULL;--> statement-breakpoint
+ALTER TABLE "document_asset" ADD CONSTRAINT "document_asset_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "document_asset" ADD CONSTRAINT "document_asset_uploaded_by_user_id_user_id_fk" FOREIGN KEY ("uploaded_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_parent_id_project_document_id_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."project_document"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_archived_by_ancestor_id_project_document_id_fk" FOREIGN KEY ("archived_by_ancestor_id") REFERENCES "public"."project_document"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_owner_user_id_user_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document" ADD CONSTRAINT "project_document_updated_by_user_id_user_id_fk" FOREIGN KEY ("updated_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_issue" ADD CONSTRAINT "project_document_issue_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_issue" ADD CONSTRAINT "project_document_issue_issue_id_issue_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issue"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_issue" ADD CONSTRAINT "project_document_issue_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_preference" ADD CONSTRAINT "project_document_preference_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_preference" ADD CONSTRAINT "project_document_preference_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_revision" ADD CONSTRAINT "project_document_revision_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_revision" ADD CONSTRAINT "project_document_revision_owner_user_id_user_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "project_document_revision" ADD CONSTRAINT "project_document_revision_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX "document_asset_document_idx" ON "document_asset" USING btree ("document_id","created_at");--> statement-breakpoint
+CREATE INDEX "project_document_project_tree_idx" ON "project_document" USING btree ("project_id","parent_id","position","id");--> statement-breakpoint
+CREATE INDEX "project_document_owner_idx" ON "project_document" USING btree ("owner_user_id");--> statement-breakpoint
+CREATE INDEX "project_document_project_archive_idx" ON "project_document" USING btree ("project_id","archived_at");--> statement-breakpoint
+CREATE INDEX "project_document_issue_issue_idx" ON "project_document_issue" USING btree ("issue_id","document_id");--> statement-breakpoint
+CREATE INDEX "project_document_preference_user_idx" ON "project_document_preference" USING btree ("user_id");--> statement-breakpoint
+CREATE INDEX "project_document_revision_document_idx" ON "project_document_revision" USING btree ("document_id","version");--> statement-breakpoint
+
+-- New pages receive the creator as their explicit owner unless an internal
+-- writer has already selected another owner.
+CREATE OR REPLACE FUNCTION default_project_document_owner()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW."owner_user_id" IS NULL THEN
+ NEW."owner_user_id" := NEW."created_by_user_id";
+ END IF;
+ RETURN NEW;
+END;
+$$;
+--> statement-breakpoint
+
+CREATE TRIGGER "project_document_owner_default"
+BEFORE INSERT ON "project_document"
+FOR EACH ROW
+EXECUTE FUNCTION default_project_document_owner();
+--> statement-breakpoint
+
+-- Capture persisted page states atomically. Consecutive content edits by the
+-- same actor within ten minutes replace the immediately preceding snapshot so
+-- autosave does not make version history noisy. Structural and access changes
+-- remain explicit checkpoints, and only the newest twenty snapshots are kept.
+CREATE OR REPLACE FUNCTION capture_project_document_revision()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ actor_id text := COALESCE(NEW."updated_by_user_id", NEW."created_by_user_id");
+ previous_revision "project_document_revision"%ROWTYPE;
+ preceding_revision "project_document_revision"%ROWTYPE;
+ coalesce_edit boolean := false;
+ previous_is_content_edit boolean := false;
+BEGIN
+ IF current_setting('app.document_rebalance', true) = 'true' THEN
+ RETURN NEW;
+ END IF;
+
+ -- Ignore same-version physical maintenance only when the snapshot payload is
+ -- unchanged. Project copy deliberately rewrites parent/content at version 1,
+ -- and those updates must still replace the seeded revision.
+ IF TG_OP = 'UPDATE'
+ AND NEW."version" = OLD."version"
+ AND ROW(
+ NEW."parent_id", NEW."title", NEW."content", NEW."content_json",
+ NEW."icon", NEW."metadata", NEW."full_width", NEW."is_private",
+ NEW."is_locked", NEW."archived_at", NEW."position", NEW."owner_user_id"
+ ) IS NOT DISTINCT FROM ROW(
+ OLD."parent_id", OLD."title", OLD."content", OLD."content_json",
+ OLD."icon", OLD."metadata", OLD."full_width", OLD."is_private",
+ OLD."is_locked", OLD."archived_at", OLD."position", OLD."owner_user_id"
+ )
+ THEN
+ RETURN NEW;
+ END IF;
+
+ SELECT * INTO previous_revision
+ FROM "project_document_revision"
+ WHERE "document_id" = NEW."id"
+ ORDER BY "version" DESC
+ LIMIT 1;
+
+ SELECT * INTO preceding_revision
+ FROM "project_document_revision"
+ WHERE "document_id" = NEW."id"
+ ORDER BY "version" DESC
+ OFFSET 1
+ LIMIT 1;
+
+ IF TG_OP = 'UPDATE' THEN
+ coalesce_edit :=
+ OLD."parent_id" IS NOT DISTINCT FROM NEW."parent_id"
+ AND OLD."icon" IS NOT DISTINCT FROM NEW."icon"
+ AND OLD."metadata" IS NOT DISTINCT FROM NEW."metadata"
+ AND OLD."full_width" IS NOT DISTINCT FROM NEW."full_width"
+ AND OLD."is_private" IS NOT DISTINCT FROM NEW."is_private"
+ AND OLD."is_locked" IS NOT DISTINCT FROM NEW."is_locked"
+ AND OLD."archived_at" IS NOT DISTINCT FROM NEW."archived_at"
+ AND OLD."position" IS NOT DISTINCT FROM NEW."position"
+ AND OLD."owner_user_id" IS NOT DISTINCT FROM NEW."owner_user_id"
+ AND (
+ OLD."title" IS DISTINCT FROM NEW."title"
+ OR OLD."content" IS DISTINCT FROM NEW."content"
+ OR OLD."content_json" IS DISTINCT FROM NEW."content_json"
+ );
+ END IF;
+
+ IF previous_revision."id" IS NOT NULL AND preceding_revision."id" IS NOT NULL THEN
+ previous_is_content_edit :=
+ previous_revision."parent_id" IS NOT DISTINCT FROM preceding_revision."parent_id"
+ AND previous_revision."icon" IS NOT DISTINCT FROM preceding_revision."icon"
+ AND previous_revision."metadata" IS NOT DISTINCT FROM preceding_revision."metadata"
+ AND previous_revision."full_width" IS NOT DISTINCT FROM preceding_revision."full_width"
+ AND previous_revision."is_private" IS NOT DISTINCT FROM preceding_revision."is_private"
+ AND previous_revision."is_locked" IS NOT DISTINCT FROM preceding_revision."is_locked"
+ AND previous_revision."archived_at" IS NOT DISTINCT FROM preceding_revision."archived_at"
+ AND previous_revision."position" IS NOT DISTINCT FROM preceding_revision."position"
+ AND previous_revision."owner_user_id" IS NOT DISTINCT FROM preceding_revision."owner_user_id"
+ AND (
+ previous_revision."title" IS DISTINCT FROM preceding_revision."title"
+ OR previous_revision."content" IS DISTINCT FROM preceding_revision."content"
+ OR previous_revision."content_json" IS DISTINCT FROM preceding_revision."content_json"
+ );
+ END IF;
+
+ IF coalesce_edit
+ AND previous_is_content_edit
+ AND current_setting('app.document_checkpoint', true) IS DISTINCT FROM 'true'
+ AND previous_revision."id" IS NOT NULL
+ AND previous_revision."created_by_user_id" IS NOT DISTINCT FROM actor_id
+ AND previous_revision."created_at" BETWEEN NEW."updated_at" - interval '10 minutes' AND NEW."updated_at"
+ THEN
+ UPDATE "project_document_revision" SET
+ "version" = NEW."version",
+ "parent_id" = NEW."parent_id",
+ "title" = NEW."title",
+ "content" = NEW."content",
+ "content_json" = NEW."content_json",
+ "icon" = NEW."icon",
+ "metadata" = NEW."metadata",
+ "full_width" = NEW."full_width",
+ "is_private" = NEW."is_private",
+ "is_locked" = NEW."is_locked",
+ "archived_at" = NEW."archived_at",
+ "position" = NEW."position",
+ "owner_user_id" = NEW."owner_user_id",
+ "created_by_user_id" = actor_id,
+ "created_at" = NEW."updated_at"
+ WHERE "id" = previous_revision."id";
+ ELSE
+ INSERT INTO "project_document_revision" (
+ "document_id",
+ "version",
+ "parent_id",
+ "title",
+ "content",
+ "content_json",
+ "icon",
+ "metadata",
+ "full_width",
+ "is_private",
+ "is_locked",
+ "archived_at",
+ "position",
+ "owner_user_id",
+ "created_by_user_id",
+ "created_at"
+ ) VALUES (
+ NEW."id",
+ NEW."version",
+ NEW."parent_id",
+ NEW."title",
+ NEW."content",
+ NEW."content_json",
+ NEW."icon",
+ NEW."metadata",
+ NEW."full_width",
+ NEW."is_private",
+ NEW."is_locked",
+ NEW."archived_at",
+ NEW."position",
+ NEW."owner_user_id",
+ actor_id,
+ NEW."updated_at"
+ )
+ ON CONFLICT ("document_id", "version") DO UPDATE SET
+ "parent_id" = EXCLUDED."parent_id",
+ "title" = EXCLUDED."title",
+ "content" = EXCLUDED."content",
+ "content_json" = EXCLUDED."content_json",
+ "icon" = EXCLUDED."icon",
+ "metadata" = EXCLUDED."metadata",
+ "full_width" = EXCLUDED."full_width",
+ "is_private" = EXCLUDED."is_private",
+ "is_locked" = EXCLUDED."is_locked",
+ "archived_at" = EXCLUDED."archived_at",
+ "position" = EXCLUDED."position",
+ "owner_user_id" = EXCLUDED."owner_user_id",
+ "created_by_user_id" = EXCLUDED."created_by_user_id",
+ "created_at" = EXCLUDED."created_at";
+ END IF;
+
+ DELETE FROM "project_document_revision"
+ WHERE "id" IN (
+ SELECT "id"
+ FROM "project_document_revision"
+ WHERE "document_id" = NEW."id"
+ ORDER BY "version" DESC
+ OFFSET 20
+ );
+ RETURN NEW;
+END;
+$$;
+--> statement-breakpoint
+
+CREATE TRIGGER "project_document_revision_capture"
+AFTER INSERT OR UPDATE ON "project_document"
+FOR EACH ROW
+EXECUTE FUNCTION capture_project_document_revision();
+--> statement-breakpoint
+
+CREATE OR REPLACE FUNCTION rev_document()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ row_project_id integer;
+BEGIN
+ IF current_setting('app.document_rebalance', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ IF TG_OP = 'DELETE' THEN
+ row_project_id := OLD."project_id";
+ ELSE
+ row_project_id := NEW."project_id";
+ END IF;
+ PERFORM bump_rev('documents:' || row_project_id, row_project_id);
+ RETURN NULL;
+END;
+$$;
+--> statement-breakpoint
+
+CREATE OR REPLACE FUNCTION rev_document_child()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ document_id integer;
+ row_project_id integer;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ document_id := OLD."document_id";
+ ELSE
+ document_id := NEW."document_id";
+ END IF;
+ SELECT "project_id" INTO row_project_id
+ FROM "project_document"
+ WHERE "id" = document_id;
+ IF row_project_id IS NOT NULL THEN
+ PERFORM bump_rev('documents:' || row_project_id, row_project_id);
+ END IF;
+ RETURN NULL;
+END;
+$$;
+--> statement-breakpoint
+
+CREATE TRIGGER "project_document_rev"
+AFTER INSERT OR UPDATE OR DELETE ON "project_document"
+FOR EACH ROW
+EXECUTE FUNCTION rev_document();
+--> statement-breakpoint
+
+CREATE TRIGGER "document_asset_rev"
+AFTER INSERT OR UPDATE OR DELETE ON "document_asset"
+FOR EACH ROW
+EXECUTE FUNCTION rev_document_child();
+--> statement-breakpoint
+
+CREATE TRIGGER "project_document_preference_rev"
+AFTER INSERT OR UPDATE OR DELETE ON "project_document_preference"
+FOR EACH ROW
+EXECUTE FUNCTION rev_document_child();
+
+--> statement-breakpoint
+CREATE FUNCTION project_document_issue_validate_project() RETURNS trigger AS $$
+DECLARE
+ document_project_id integer;
+ issue_project_id integer;
+BEGIN
+ SELECT project_id INTO document_project_id FROM project_document WHERE id = NEW.document_id;
+ SELECT project_id INTO issue_project_id FROM issue WHERE id = NEW.issue_id;
+ IF document_project_id IS NULL OR issue_project_id IS NULL OR document_project_id <> issue_project_id THEN
+ RAISE EXCEPTION 'A document and work item link must stay inside one project'
+ USING ERRCODE = '23514';
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+--> statement-breakpoint
+CREATE TRIGGER project_document_issue_validate_project
+BEFORE INSERT OR UPDATE ON project_document_issue
+FOR EACH ROW EXECUTE FUNCTION project_document_issue_validate_project();
+--> statement-breakpoint
+CREATE FUNCTION project_document_issue_rev() RETURNS trigger AS $$
+DECLARE
+ row_document_id integer;
+ row_issue_id integer;
+ row_project_id integer;
+BEGIN
+ row_document_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.document_id ELSE NEW.document_id END;
+ row_issue_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.issue_id ELSE NEW.issue_id END;
+ SELECT project_id INTO row_project_id FROM project_document WHERE id = row_document_id;
+ IF row_project_id IS NULL THEN
+ SELECT project_id INTO row_project_id FROM issue WHERE id = row_issue_id;
+ END IF;
+ IF row_project_id IS NOT NULL THEN
+ PERFORM bump_rev('documents:' || row_project_id, row_project_id);
+ PERFORM bump_rev('issue:' || row_issue_id, row_project_id);
+ END IF;
+ IF TG_OP = 'DELETE' THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+--> statement-breakpoint
+CREATE TRIGGER project_document_issue_rev
+AFTER INSERT OR DELETE ON project_document_issue
+FOR EACH ROW EXECUTE FUNCTION project_document_issue_rev();
diff --git a/packages/db/drizzle/meta/0118_snapshot.json b/packages/db/drizzle/meta/0118_snapshot.json
new file mode 100644
index 00000000..934ed878
--- /dev/null
+++ b/packages/db/drizzle/meta/0118_snapshot.json
@@ -0,0 +1,9814 @@
+{
+ "id": "65e7d6c1-e7c5-406c-bb22-fa4d8508ff25",
+ "prevId": "88bbde94-fcee-4f7a-84aa-c24e4e8a3c7e",
+ "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
+ },
+ "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": {}
+ }
+ },
+ "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_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
+ },
+ "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": {}
+ }
+ },
+ "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"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_schedule_agent_id_name_unique": {
+ "name": "agent_schedule_agent_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "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
+ },
+ "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": "''"
+ },
+ "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_project_idx": {
+ "name": "agent_skill_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skill_project_id_project_id_fk": {
+ "name": "agent_skill_project_id_project_id_fk",
+ "tableFrom": "agent_skill",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_skill_project_id_name_unique": {
+ "name": "agent_skill_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_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
+ },
+ "project_id": {
+ "name": "project_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_project_idx": {
+ "name": "agent_tool_project_idx",
+ "columns": [
+ {
+ "expression": "project_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_project_id_project_id_fk": {
+ "name": "agent_tool_project_id_project_id_fk",
+ "tableFrom": "agent_tool",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_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_project_id_tool_key_credential_id_unique": {
+ "name": "agent_tool_project_id_tool_key_credential_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_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
+ },
+ "project_id": {
+ "name": "project_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
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "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": "'project'"
+ },
+ "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_project_username_uq": {
+ "name": "ai_agent_project_username_uq",
+ "columns": [
+ {
+ "expression": "project_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_project_idx": {
+ "name": "ai_agent_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_agent_project_id_project_id_fk": {
+ "name": "ai_agent_project_id_project_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_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_role_id_project_role_id_fk": {
+ "name": "ai_agent_role_id_project_role_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_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', 'project')"
+ },
+ "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.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.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_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
+ },
+ "project_id": {
+ "name": "project_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_project_idx": {
+ "name": "integration_credential_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_credential_project_id_project_id_fk": {
+ "name": "integration_credential_project_id_project_id_fk",
+ "tableFrom": "integration_credential",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_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"
+ },
+ "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
+ },
+ "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": {},
+ "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_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_invite": {
+ "name": "project_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()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "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
+ },
+ "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": {
+ "project_invite_pending_uq": {
+ "name": "project_invite_pending_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_invite\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_invite_project_idx": {
+ "name": "project_invite_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_invite_project_id_project_id_fk": {
+ "name": "project_invite_project_id_project_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invite_role_id_project_role_id_fk": {
+ "name": "project_invite_role_id_project_role_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_invited_by_user_id_user_id_fk": {
+ "name": "project_invite_invited_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invited_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_accepted_by_user_id_user_id_fk": {
+ "name": "project_invite_accepted_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "accepted_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_invite_token_unique": {
+ "name": "project_invite_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "project_invite_role_check": {
+ "name": "project_invite_role_check",
+ "value": "\"project_invite\".\"role\" IN ('owner', 'member')"
+ },
+ "project_invite_status_check": {
+ "name": "project_invite_status_check",
+ "value": "\"project_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"
+ }
+ },
+ "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'"
+ },
+ "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_project_role_id_fk": {
+ "name": "project_member_role_id_project_role_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "project_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_notification_setting": {
+ "name": "project_notification_setting",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_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": {
+ "project_notification_setting_project_id_project_id_fk": {
+ "name": "project_notification_setting_project_id_project_id_fk",
+ "tableFrom": "project_notification_setting",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_role": {
+ "name": "project_role",
+ "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
+ },
+ "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": {
+ "project_role_default_uq": {
+ "name": "project_role_default_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_role\".\"is_default\"",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_role_project_idx": {
+ "name": "project_role_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_role_project_id_project_id_fk": {
+ "name": "project_role_project_id_project_id_fk",
+ "tableFrom": "project_role",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_role_project_id_name_unique": {
+ "name": "project_role_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "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.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
+ },
+ "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_project_role_id_fk": {
+ "name": "scim_group_mapping_role_id_project_role_id_fk",
+ "tableFrom": "scim_group_mapping",
+ "tableTo": "project_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 e5a672e0..1045afcc 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -827,6 +827,13 @@
"when": 1788539930251,
"tag": "0117_backfill_issue_templates_permission",
"breakpoints": true
+ },
+ {
+ "idx": 118,
+ "version": "7",
+ "when": 1788542845903,
+ "tag": "0118_left_titanium_man",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.ts
index 5f4ac66d..1a4475f4 100644
--- a/packages/db/src/schema/app.ts
+++ b/packages/db/src/schema/app.ts
@@ -67,6 +67,7 @@ export const project = pgTable('project', {
// come back with it.
initiativesEnabled: boolean('initiatives_enabled').notNull().default(true),
dashboardsEnabled: boolean('dashboards_enabled').notNull().default(true),
+ documentsEnabled: boolean('documents_enabled').notNull().default(true),
notesEnabled: boolean('notes_enabled').notNull().default(true),
cyclesEnabled: boolean('cycles_enabled').notNull().default(true),
subtasksEnabled: boolean('subtasks_enabled').notNull().default(true),
@@ -1726,6 +1727,157 @@ export const projectDashboard = pgTable(
(t) => [index('project_dashboard_project_idx').on(t.projectId, t.position)],
);
+// Shared Markdown pages arranged as a tree. Version rejects stale autosaves.
+// Private pages are visible only to their owner; project permissions still gate
+// access before that page-level rule is applied.
+export const projectDocument = pgTable(
+ 'project_document',
+ {
+ id: serial('id').primaryKey(),
+ projectId: integer('project_id')
+ .notNull()
+ .references(() => project.id, { onDelete: 'cascade' }),
+ parentId: integer('parent_id').references((): AnyPgColumn => projectDocument.id, {
+ onDelete: 'set null',
+ }),
+ title: text('title').notNull().default(''),
+ content: text('content').notNull().default(''),
+ contentJson: jsonb('content_json').$type<Record<string, unknown>>(),
+ icon: text('icon'),
+ metadata: jsonb('metadata').$type<Record<string, unknown>>().notNull().default({}),
+ fullWidth: boolean('full_width').notNull().default(false),
+ isPrivate: boolean('is_private').notNull().default(false),
+ isLocked: boolean('is_locked').notNull().default(false),
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
+ archivedByAncestorId: integer('archived_by_ancestor_id').references(
+ (): AnyPgColumn => projectDocument.id,
+ { onDelete: 'set null' },
+ ),
+ position: doublePrecision('position').notNull().default(0),
+ version: integer('version').notNull().default(1),
+ ownerUserId: text('owner_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ createdByUserId: text('created_by_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ updatedByUserId: text('updated_by_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ index('project_document_project_tree_idx').on(t.projectId, t.parentId, t.position, t.id),
+ index('project_document_owner_idx').on(t.ownerUserId),
+ index('project_document_project_archive_idx').on(t.projectId, t.archivedAt),
+ check('project_document_version_check', sql`${t.version} > 0`),
+ ],
+);
+
+// Immutable snapshots of every persisted document version. A database trigger
+// fills this table so project copies and bulk tree operations receive the same
+// history guarantees as writes made through the Documents API.
+export const projectDocumentRevision = pgTable(
+ 'project_document_revision',
+ {
+ id: serial('id').primaryKey(),
+ documentId: integer('document_id')
+ .notNull()
+ .references(() => projectDocument.id, { onDelete: 'cascade' }),
+ version: integer('version').notNull(),
+ parentId: integer('parent_id'),
+ title: text('title').notNull(),
+ content: text('content').notNull(),
+ contentJson: jsonb('content_json').$type<Record<string, unknown>>(),
+ icon: text('icon'),
+ metadata: jsonb('metadata').$type<Record<string, unknown>>().notNull().default({}),
+ fullWidth: boolean('full_width').notNull().default(false),
+ isPrivate: boolean('is_private').notNull().default(false),
+ isLocked: boolean('is_locked').notNull().default(false),
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
+ position: doublePrecision('position').notNull(),
+ ownerUserId: text('owner_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ createdByUserId: text('created_by_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ unique('project_document_revision_document_version_unique').on(t.documentId, t.version),
+ index('project_document_revision_document_idx').on(t.documentId, t.version),
+ ],
+);
+
+// Per-user page preferences. Keeping favorites outside the shared page row means
+// one person's sidebar choices never affect another project member.
+export const projectDocumentPreference = pgTable(
+ 'project_document_preference',
+ {
+ documentId: integer('document_id')
+ .notNull()
+ .references(() => projectDocument.id, { onDelete: 'cascade' }),
+ userId: text('user_id')
+ .notNull()
+ .references(() => user.id, { onDelete: 'cascade' }),
+ isFavorite: boolean('is_favorite').notNull().default(false),
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ primaryKey({ columns: [t.documentId, t.userId] }),
+ index('project_document_preference_user_idx').on(t.userId),
+ ],
+);
+
+// Explicit links between Docs pages and work items. The relation is intentionally
+// separate from page content: renaming either side keeps the link intact, one page
+// can provide context for several work items, and one work item can collect several
+// specs or runbooks. The API verifies that both ends belong to the same project.
+export const projectDocumentIssue = pgTable(
+ 'project_document_issue',
+ {
+ documentId: integer('document_id')
+ .notNull()
+ .references(() => projectDocument.id, { onDelete: 'cascade' }),
+ issueId: integer('issue_id')
+ .notNull()
+ .references(() => issue.id, { onDelete: 'cascade' }),
+ createdByUserId: text('created_by_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ primaryKey({ columns: [t.documentId, t.issueId] }),
+ index('project_document_issue_issue_idx').on(t.issueId, t.documentId),
+ ],
+);
+
+// Files embedded in Docs pages. Bytes use the same S3-compatible object store as
+// issue/chat attachments; only authenticated document routes expose them, so a
+// private page's unguessable asset id never acts as a public capability URL.
+export const documentAsset = pgTable(
+ 'document_asset',
+ {
+ id: serial('id').primaryKey(),
+ publicId: uuid('public_id').notNull().defaultRandom().unique(),
+ documentId: integer('document_id')
+ .notNull()
+ .references(() => projectDocument.id, { onDelete: 'cascade' }),
+ uploadedByUserId: text('uploaded_by_user_id').references(() => user.id, {
+ onDelete: 'set null',
+ }),
+ s3Key: text('s3_key').notNull(),
+ filename: text('filename').notNull(),
+ contentType: text('content_type').notNull(),
+ sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [index('document_asset_document_idx').on(t.documentId, t.createdAt)],
+);
+
// Note boards: a freeform canvas of sticky notes. canvas is a jsonb blob owned by
// the UI (React Flow nodes + edges + viewport), stored and returned verbatim.
// owner_user_id NULL means a public board visible to every project member; a set