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.

refactor(api): move every remaining feature to the modules/ layout (#197)

Croffbf46c5b9c62e
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 33a0f625..7e9a8b1b 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -22,9 +22,9 @@ Rules and invariants for this package below; read the code for the walkthrough.
- `model.ts`: the `t` schemas of the feature's requests and responses. An update body
is `t.Partial(<create body>)` where it accepts the same fields.
- `service.ts`: plain async functions, no Elysia/HTTP types, returns DTOs never rows.
-- The features still sitting in `src/<feature>/` as `routes.ts` + `store.ts` predate
- this layout. Move one to `src/modules/` when you next change it; do not add a new
- feature in the old shape.
+- Every feature lives under `src/modules/`. A feature that needs more than the three
+ files adds one per concern next to them (`emit.ts`, `internal-routes.ts`), it does
+ not grow a `routes.ts` + `store.ts` pair.
- Imports inside a module are relative (`./model`); everything it reaches outside
itself goes through the subpath aliases in `apps/api/package.json` — `#shared/*`,
`#mcp/*`, `#modules/*`, `#tests/*`. They map to a `.ts` file (`"#shared/*":
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 6fd66e9a..16d2d99a 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -9,12 +9,11 @@ import { cors } from '@elysiajs/cors';
import { swagger } from '@elysiajs/swagger';
import { Elysia } from 'elysia';
import { planner } from './planner';
-import { webhookTestRoutes } from './webhook-test/routes';
import { mountMcp } from './mcp/mount';
import { setMcpApp } from './mcp/app-ref';
import { internalAgentRunRoutes } from './modules/agents/core/internal-routes';
import { internalNotificationRoutes } from './modules/notifications/internal-routes';
-import { internalTelegramRoutes } from './telegram/internal-routes';
+import { internalTelegramRoutes } from './modules/telegram/internal-routes';
import { gitWebhookRoutes } from './modules/git/webhook';
// The assembled Elysia app, without `.listen()`. `index.ts` imports this and
@@ -199,8 +198,6 @@ export const app = new Elysia()
.use(internalAgentRunRoutes)
.use(internalNotificationRoutes)
.use(internalTelegramRoutes)
- // Test receiver for inspecting webhook deliveries (unauthenticated, dev aid).
- .use(webhookTestRoutes)
// Inbound repository webhook receiver (authenticated by its per-project secret).
.use(gitWebhookRoutes)
// Planner API: projects, issues, and their dependent entities.
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
index 0e1970bb..97cdcbe3 100644
--- a/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
@@ -5,7 +5,7 @@ import { authedApi, type Api } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { addProjectMember } from '#tests/helpers/members';
-import { createComment } from '../../../../../issues/activity';
+import { createComment } from '#modules/issues/activity';
import { claimDueRuns } from '../../run-queue';
// Mentioning an agent in a comment queues an agent_run so the agent can reply. The
diff --git a/apps/api/src/modules/agents/core/run-activity.ts b/apps/api/src/modules/agents/core/run-activity.ts
index d44ba247..13838e8f 100644
--- a/apps/api/src/modules/agents/core/run-activity.ts
+++ b/apps/api/src/modules/agents/core/run-activity.ts
@@ -1,4 +1,4 @@
-import { recordActivity } from '../../../issues/activity';
+import { recordActivity } from '#modules/issues/activity';
// Records that an agent took a queued run of the issue. Only the first claim is
// logged: a re-claim after an expired lease is the same task handed out again.
diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.ts
index a930d0fd..63a94950 100644
--- a/apps/api/src/modules/attachments/index.ts
+++ b/apps/api/src/modules/attachments/index.ts
@@ -8,8 +8,13 @@ import { putObject, getObject, deleteObject } from '#shared/s3';
import { assertPublicHttpUrl } from '#shared/net';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors, errors } from '#shared/responses';
-import { getIssueProjectId } from '../../issues/store';
-import { getStorageSettings, mimeAllowed, MB, type StorageSettings } from '../../settings/storage';
+import { getIssueProjectId } from '#modules/issues/service';
+import {
+ getStorageSettings,
+ mimeAllowed,
+ MB,
+ type StorageSettings,
+} from '#modules/settings/service';
import {
AttachmentResponse,
AttachmentListResponse,
@@ -29,7 +34,7 @@ import {
type AttachmentRow,
} from './service';
-// The upload limits are instance settings (see ../../settings/storage.ts), read per
+// 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,
diff --git a/apps/api/src/modules/avatars/service.ts b/apps/api/src/modules/avatars/service.ts
index 5d6be088..24d27d95 100644
--- a/apps/api/src/modules/avatars/service.ts
+++ b/apps/api/src/modules/avatars/service.ts
@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';
import { randomUUID } from 'node:crypto';
import { HttpError } from '#shared/lib';
import { putObject, getObject, deleteObject } from '#shared/s3';
-import { getStorageSettings, MB } from '../../settings/storage';
+import { getStorageSettings, MB } from '#modules/settings/service';
// Avatar images for the signed-in user. The bytes live in the S3-compatible
// object store under `avatars/<uuid>`; the user's `image` column (managed by
@@ -43,7 +43,7 @@ async function deletePreviousAvatar(image: string | null | undefined): Promise<v
});
}
-// The size limit is an instance setting (see ../../settings/storage.ts), read per
+// The size limit is an instance setting (see modules/settings/service.ts), read per
// call so a change in god mode takes effect without a restart.
export async function replaceAvatar(
userId: string,
diff --git a/apps/api/src/modules/columns/service.ts b/apps/api/src/modules/columns/service.ts
index ea4640d2..905c57d2 100644
--- a/apps/api/src/modules/columns/service.ts
+++ b/apps/api/src/modules/columns/service.ts
@@ -2,7 +2,7 @@ import { db, projectColumn, issue, issueLabel, issueFieldValue, issueFieldOption
import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
import { HttpError } from '#shared/lib';
import { getMembership } from '#modules/members/service';
-import { recordActivityForIssues } from '../../issues/activity';
+import { recordActivityForIssues } from '#modules/issues/activity';
export interface ColumnRow {
id: number;
diff --git a/apps/api/src/modules/cycles/index.ts b/apps/api/src/modules/cycles/index.ts
index b0fb07ab..5ba4b964 100644
--- a/apps/api/src/modules/cycles/index.ts
+++ b/apps/api/src/modules/cycles/index.ts
@@ -6,7 +6,7 @@ import { authContext } from '#shared/auth-context';
import { requireUser } from '#shared/access';
import { HttpError } from '#shared/lib';
import { accessErrors, commonErrors } from '#shared/responses';
-import { transferCycleIssues } from '../../issues/store';
+import { transferCycleIssues } from '#modules/issues/service';
import {
CycleListResponse,
CycleOptionListResponse,
diff --git a/apps/api/src/modules/git/handler.ts b/apps/api/src/modules/git/handler.ts
index 4bf24a58..abe67f21 100644
--- a/apps/api/src/modules/git/handler.ts
+++ b/apps/api/src/modules/git/handler.ts
@@ -1,5 +1,5 @@
-import { getIssueBySequence, updateIssue } from '../../issues/store';
-import { recordActivity, type ActivityActor } from '../../issues/activity';
+import { getIssueBySequence, updateIssue } from '#modules/issues/service';
+import { recordActivity, type ActivityActor } from '#modules/issues/activity';
import { parseMagicWords, type IssueRef } from './magic-words';
import type { PullRequestEvent } from './providers';
import { columnStateTypes, firstCompletedColumnId, type GitSettings } from './service';
diff --git a/apps/api/src/modules/git/service.ts b/apps/api/src/modules/git/service.ts
index f0dd5d95..bd32dd2b 100644
--- a/apps/api/src/modules/git/service.ts
+++ b/apps/api/src/modules/git/service.ts
@@ -3,7 +3,7 @@ import { db, projectColumn, projectSetting } from '@repo/db';
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
import { decryptSecret, encryptSecret, type EncryptedSecret } from '@repo/crypto';
import { HttpError } from '#shared/lib';
-import { getProjectSetting } from '../../settings/store';
+import { getProjectSetting } from '#shared/project-settings';
// The shared secret a project hands to its repository host.
const newSecret = () => `whs_${randomBytes(24).toString('hex')}`;
diff --git a/apps/api/src/god/__tests__/helpers.ts b/apps/api/src/modules/god/__tests__/helpers.ts
similarity index 91%
rename from apps/api/src/god/__tests__/helpers.ts
rename to apps/api/src/modules/god/__tests__/helpers.ts
index 7c2c444f..71525662 100644
--- a/apps/api/src/god/__tests__/helpers.ts
+++ b/apps/api/src/modules/god/__tests__/helpers.ts
@@ -1,5 +1,5 @@
-import { authedApi, type Api } from '../../__tests__/helpers/app';
-import { signUpTestUser } from '../../__tests__/helpers/auth';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
// Actors and the flows both god directory tests need. The first user in a reset
// database gets the "god" role, so `setup` registers the instance owner first and
diff --git a/apps/api/src/god/__tests__/integration/god-projects.test.ts b/apps/api/src/modules/god/__tests__/integration/god-projects.test.ts
similarity index 99%
rename from apps/api/src/god/__tests__/integration/god-projects.test.ts
rename to apps/api/src/modules/god/__tests__/integration/god-projects.test.ts
index f1581d2a..42729013 100644
--- a/apps/api/src/god/__tests__/integration/god-projects.test.ts
+++ b/apps/api/src/modules/god/__tests__/integration/god-projects.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { resetDb } from '#tests/helpers/db';
import { addUser, createAgentUser, joinProject, setup } from '../helpers';
// The instance project directory under god mode: listing every project on the
diff --git a/apps/api/src/god/__tests__/integration/god-updates.test.ts b/apps/api/src/modules/god/__tests__/integration/god-updates.test.ts
similarity index 97%
rename from apps/api/src/god/__tests__/integration/god-updates.test.ts
rename to apps/api/src/modules/god/__tests__/integration/god-updates.test.ts
index 43343e17..feda7a50 100644
--- a/apps/api/src/god/__tests__/integration/god-updates.test.ts
+++ b/apps/api/src/modules/god/__tests__/integration/god-updates.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { resetDb } from '#tests/helpers/db';
import { addUser, setup } from '../helpers';
// The update check under god mode. Only the instance owner may read it — they are
diff --git a/apps/api/src/god/__tests__/integration/god-users.test.ts b/apps/api/src/modules/god/__tests__/integration/god-users.test.ts
similarity index 99%
rename from apps/api/src/god/__tests__/integration/god-users.test.ts
rename to apps/api/src/modules/god/__tests__/integration/god-users.test.ts
index 3375c42e..da20ff9c 100644
--- a/apps/api/src/god/__tests__/integration/god-users.test.ts
+++ b/apps/api/src/modules/god/__tests__/integration/god-users.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { resetDb } from '#tests/helpers/db';
import { addUser, createAgentUser, joinProject, setup } from '../helpers';
// The instance user directory under god mode: listing every account on the instance,
diff --git a/apps/api/src/god/routes.ts b/apps/api/src/modules/god/index.ts
similarity index 64%
rename from apps/api/src/god/routes.ts
rename to apps/api/src/modules/god/index.ts
index 03907876..05a36e60 100644
--- a/apps/api/src/god/routes.ts
+++ b/apps/api/src/modules/god/index.ts
@@ -1,6 +1,5 @@
import { Elysia, t } from 'elysia';
import {
- REGISTRATION_MODES,
GOOGLE_REDIRECT_URI,
getAuthSettings,
setAuthSettings,
@@ -10,25 +9,53 @@ import {
getGoogleSettings,
setGoogleSettings,
} from '@repo/auth';
-import { authContext } from '../shared/auth-context';
-import { requireGod } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { accessErrors, commonErrors, errors } from '../shared/responses';
-import { noContent } from '../shared/http';
+import { authContext } from '#shared/auth-context';
+import { requireGod } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { noContent } from '#shared/http';
import { deleteProject } from '#modules/projects/service';
import {
- USER_KINDS,
deleteInstanceUser,
getInstanceProject,
getInstanceUser,
listInstanceProjects,
listInstanceUsers,
verifyInstanceUserEmail,
-} from './store';
-import { getInstanceBotSettings, setInstanceBotSettings } from '../telegram/store';
-import { getStorageSettings, setStorageSettings, StorageSettingsSchema } from '../settings/storage';
-import { getHotkeySettings, setHotkeySettings, HotkeyCombosSchema } from '../settings/hotkeys';
-import { getUpdateStatus, UpdateStatusSchema } from '../settings/updates';
+} from './service';
+import {
+ AuthSettingsBody,
+ AuthSettingsResponse,
+ EmailSettingsBody,
+ EmailSettingsResponse,
+ GoogleSettingsBody,
+ GoogleSettingsResponse,
+ InstanceProjectDetailResponse,
+ InstanceProjectListResponse,
+ InstanceUserDetailResponse,
+ InstanceUserListResponse,
+ StorageSettingsBody,
+ TelegramSettingsBody,
+ TelegramSettingsResponse,
+ deleteUserQuery,
+ listProjectsQuery,
+ listUsersQuery,
+ projectParams,
+ userParams,
+} from './model';
+import { getInstanceBotSettings, setInstanceBotSettings } from '#modules/telegram/service';
+import {
+ getStorageSettings,
+ setStorageSettings,
+ getHotkeySettings,
+ setHotkeySettings,
+} from '#modules/settings/service';
+import { getUpdateStatus } from '#modules/settings/updates';
+import {
+ HotkeyCombosSchema,
+ StorageSettingsSchema,
+ UpdateStatusSchema,
+} from '#modules/settings/model';
// God mode: instance-wide administration, open only to the "god" user (the first
// registered account). It covers how people may register, the mail provider that
@@ -40,172 +67,6 @@ import { getUpdateStatus, UpdateStatusSchema } from '../settings/updates';
// when sending mail; these routes only expose them over HTTP. Secrets are never
// returned — each is replaced by a boolean telling whether a value is stored.
-const encryption = t.UnionEnum(['none', 'ssl', 'tls']);
-
-const AuthSettingsResponse = t.Object({
- registration: t.UnionEnum([...REGISTRATION_MODES]),
- requireEmailVerification: t.Boolean(),
- magicLink: t.Boolean(),
- // Whether a mail provider is configured. The settings that depend on outbound
- // email cannot be turned on without one, and the UI explains why.
- hasEmailProvider: t.Boolean(),
-});
-
-const AuthSettingsBody = t.Object({
- registration: t.Optional(t.UnionEnum([...REGISTRATION_MODES])),
- requireEmailVerification: t.Optional(t.Boolean()),
- magicLink: t.Optional(t.Boolean()),
-});
-
-const EmailSettingsResponse = t.Object({
- smtp: t.Object({
- enabled: t.Boolean(),
- host: t.String(),
- port: t.Nullable(t.Number()),
- encryption,
- username: t.String(),
- hasPassword: t.Boolean(),
- timeout: t.Nullable(t.Number()),
- }),
- resend: t.Object({ enabled: t.Boolean(), hasApiKey: t.Boolean() }),
- from: t.String(),
- // Whether projects may deliver their notifications through this provider instead
- // of configuring one of their own.
- allowProjects: t.Boolean(),
-});
-
-const EmailSettingsBody = t.Object({
- smtp: t.Optional(
- t.Object({
- enabled: t.Boolean(),
- host: t.String(),
- port: t.Nullable(t.Integer({ minimum: 1, maximum: 65535 })),
- encryption,
- username: t.String(),
- password: t.Optional(t.String()),
- timeout: t.Nullable(t.Integer({ minimum: 1 })),
- }),
- ),
- resend: t.Optional(t.Object({ enabled: t.Boolean(), apiKey: t.Optional(t.String()) })),
- from: t.Optional(t.String()),
- allowProjects: t.Optional(t.Boolean()),
-});
-
-const GoogleSettingsResponse = t.Object({
- enabled: t.Boolean(),
- clientId: t.String(),
- hasClientSecret: t.Boolean(),
- // The value to register in the Google Cloud console. Derived from the API origin,
- // so the UI shows it rather than asking the owner to assemble it.
- redirectUri: t.String(),
-});
-
-const GoogleSettingsBody = t.Object({
- enabled: t.Optional(t.Boolean()),
- clientId: t.Optional(t.String()),
- clientSecret: t.Optional(t.String()),
-});
-
-const StorageSettingsBody = t.Object({
- maxAttachmentMb: t.Optional(t.Integer({ minimum: 1, maximum: 10240 })),
- maxAvatarMb: t.Optional(t.Integer({ minimum: 1, maximum: 1024 })),
- attachmentMimeTypes: t.Optional(t.Array(t.String({ minLength: 1 }))),
- projectQuotaMb: t.Optional(t.Integer({ minimum: 0 })),
-});
-
-const TelegramSettingsResponse = t.Object({
- enabled: t.Boolean(),
- // Resolved from Telegram when the token is saved. Shown so the administrator can
- // confirm which bot the token belongs to, and used to build the link deep link.
- botUsername: t.String(),
- hasBotToken: t.Boolean(),
-});
-
-const TelegramSettingsBody = t.Object({
- enabled: t.Optional(t.Boolean()),
- botToken: t.Optional(t.String()),
-});
-
-// One account in the instance user directory.
-const InstanceUserResponse = t.Object({
- id: t.String(),
- name: t.String(),
- email: t.String(),
- image: t.Nullable(t.String()),
- emailVerified: t.Boolean(),
- role: t.String(),
- isAgent: t.Boolean(),
- providers: t.Array(t.String()),
- projectCount: t.Number(),
- lastSeenAt: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-// The permission matrix as returned: for each resource, the create/edit/read/
-// delete flags. Same shape as the roles API returns.
-const PermissionMatrix = t.Record(t.String(), t.Record(t.String(), t.Boolean()));
-
-const InstanceUserDetailResponse = t.Composite([
- InstanceUserResponse,
- t.Object({
- projects: t.Array(
- t.Object({
- projectId: t.Number(),
- projectKey: t.String(),
- projectName: t.String(),
- role: t.UnionEnum(['owner', 'member']),
- roleId: t.Nullable(t.Number()),
- roleName: t.Nullable(t.String()),
- permissions: PermissionMatrix,
- ownerCount: t.Number(),
- joinedAt: t.String(),
- }),
- ),
- }),
-]);
-
-// One project in the instance project directory, with what it holds counted across
-// its dependent tables.
-const InstanceProjectResponse = t.Object({
- id: t.Number(),
- key: t.String(),
- name: t.String(),
- description: t.String(),
- mcpEnabled: t.Boolean(),
- memberCount: t.Number(),
- issueCount: t.Number(),
- archivedIssueCount: t.Number(),
- initiativeCount: t.Number(),
- dashboardCount: t.Number(),
- viewCount: t.Number(),
- agentCount: t.Number(),
- skillCount: t.Number(),
- toolCount: t.Number(),
- integrationCount: t.Number(),
- lastActivityAt: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-const InstanceProjectDetailResponse = t.Composite([
- InstanceProjectResponse,
- t.Object({
- members: t.Array(
- t.Object({
- userId: t.String(),
- name: t.String(),
- email: t.String(),
- image: t.Nullable(t.String()),
- isAgent: t.Boolean(),
- role: t.UnionEnum(['owner', 'member']),
- roleId: t.Nullable(t.Number()),
- roleName: t.Nullable(t.String()),
- permissions: PermissionMatrix,
- joinedAt: t.String(),
- }),
- ),
- }),
-]);
-
export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
.use(authContext)
// Every route in this plugin is instance administration, so the role check runs
@@ -410,18 +271,8 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
offset: query.offset ?? 0,
}),
{
- query: t.Object({
- search: t.Optional(t.String()),
- // Agent bot users are accounts too, but they are managed on a project's AI
- // Agents screen, so the directory lists people unless asked otherwise.
- kind: t.Optional(t.UnionEnum([...USER_KINDS])),
- limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200 })),
- offset: t.Optional(t.Numeric({ minimum: 0 })),
- }),
- response: {
- 200: t.Object({ items: t.Array(InstanceUserResponse), total: t.Number() }),
- ...errors(400, 401, 403),
- },
+ query: listUsersQuery,
+ response: { 200: InstanceUserListResponse, ...errors(400, 401, 403) },
detail: {
summary: 'List instance users',
description:
@@ -438,7 +289,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
return found;
},
{
- params: t.Object({ userId: t.String() }),
+ params: userParams,
response: { 200: InstanceUserDetailResponse, ...accessErrors },
detail: {
summary: 'Get an instance user',
@@ -456,7 +307,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
return updated;
},
{
- params: t.Object({ userId: t.String() }),
+ params: userParams,
response: { 200: InstanceUserDetailResponse, ...accessErrors },
detail: {
summary: 'Confirm a user email address',
@@ -496,12 +347,8 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
return noContent();
},
{
- params: t.Object({ userId: t.String() }),
- query: t.Object({
- // Delete the projects this user owns alone along with the account. Every
- // issue, comment and attachment in them goes too.
- withProjects: t.Optional(t.Boolean()),
- }),
+ params: userParams,
+ query: deleteUserQuery,
response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a user',
@@ -520,15 +367,8 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
offset: query.offset ?? 0,
}),
{
- query: t.Object({
- search: t.Optional(t.String()),
- limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200 })),
- offset: t.Optional(t.Numeric({ minimum: 0 })),
- }),
- response: {
- 200: t.Object({ items: t.Array(InstanceProjectResponse), total: t.Number() }),
- ...errors(400, 401, 403),
- },
+ query: listProjectsQuery,
+ response: { 200: InstanceProjectListResponse, ...errors(400, 401, 403) },
detail: {
summary: 'List instance projects',
description:
@@ -545,7 +385,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
return found;
},
{
- params: t.Object({ projectId: t.Numeric() }),
+ params: projectParams,
response: { 200: InstanceProjectDetailResponse, ...commonErrors },
detail: {
summary: 'Get an instance project',
diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.ts
new file mode 100644
index 00000000..7666236a
--- /dev/null
+++ b/apps/api/src/modules/god/model.ts
@@ -0,0 +1,198 @@
+import { t } from 'elysia';
+import { REGISTRATION_MODES } from '@repo/auth';
+import { PermissionMatrixSchema } from '#shared/permissions';
+import { USER_KINDS } from './service';
+
+const encryption = t.UnionEnum(['none', 'ssl', 'tls']);
+
+export const userParams = t.Object({ userId: t.String() });
+
+export const projectParams = t.Object({ projectId: t.Numeric() });
+
+export const listUsersQuery = t.Object({
+ search: t.Optional(t.String()),
+ // Agent bot users are accounts too, but they are managed on a project's AI
+ // Agents screen, so the directory lists people unless asked otherwise.
+ kind: t.Optional(t.UnionEnum([...USER_KINDS])),
+ limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200 })),
+ offset: t.Optional(t.Numeric({ minimum: 0 })),
+});
+
+export const listProjectsQuery = t.Object({
+ search: t.Optional(t.String()),
+ limit: t.Optional(t.Numeric({ minimum: 1, maximum: 200 })),
+ offset: t.Optional(t.Numeric({ minimum: 0 })),
+});
+
+export const deleteUserQuery = t.Object({
+ // Delete the projects this user owns alone along with the account. Every
+ // issue, comment and attachment in them goes too.
+ withProjects: t.Optional(t.Boolean()),
+});
+
+export const AuthSettingsResponse = t.Object({
+ registration: t.UnionEnum([...REGISTRATION_MODES]),
+ requireEmailVerification: t.Boolean(),
+ magicLink: t.Boolean(),
+ // The settings that depend on outbound email cannot be turned on without a mail
+ // provider, and the UI explains why.
+ hasEmailProvider: t.Boolean(),
+});
+
+export const AuthSettingsBody = t.Object({
+ registration: t.Optional(t.UnionEnum([...REGISTRATION_MODES])),
+ requireEmailVerification: t.Optional(t.Boolean()),
+ magicLink: t.Optional(t.Boolean()),
+});
+
+export const EmailSettingsResponse = t.Object({
+ smtp: t.Object({
+ enabled: t.Boolean(),
+ host: t.String(),
+ port: t.Nullable(t.Number()),
+ encryption,
+ username: t.String(),
+ hasPassword: t.Boolean(),
+ timeout: t.Nullable(t.Number()),
+ }),
+ resend: t.Object({ enabled: t.Boolean(), hasApiKey: t.Boolean() }),
+ from: t.String(),
+ // Whether projects may deliver their notifications through this provider instead
+ // of configuring one of their own.
+ allowProjects: t.Boolean(),
+});
+
+export const EmailSettingsBody = t.Object({
+ smtp: t.Optional(
+ t.Object({
+ enabled: t.Boolean(),
+ host: t.String(),
+ port: t.Nullable(t.Integer({ minimum: 1, maximum: 65535 })),
+ encryption,
+ username: t.String(),
+ password: t.Optional(t.String()),
+ timeout: t.Nullable(t.Integer({ minimum: 1 })),
+ }),
+ ),
+ resend: t.Optional(t.Object({ enabled: t.Boolean(), apiKey: t.Optional(t.String()) })),
+ from: t.Optional(t.String()),
+ allowProjects: t.Optional(t.Boolean()),
+});
+
+export const GoogleSettingsResponse = t.Object({
+ enabled: t.Boolean(),
+ clientId: t.String(),
+ hasClientSecret: t.Boolean(),
+ // The value to register in the Google Cloud console. Derived from the API origin,
+ // so the UI shows it rather than asking the owner to assemble it.
+ redirectUri: t.String(),
+});
+
+export const GoogleSettingsBody = t.Object({
+ enabled: t.Optional(t.Boolean()),
+ clientId: t.Optional(t.String()),
+ clientSecret: t.Optional(t.String()),
+});
+
+export const StorageSettingsBody = t.Object({
+ maxAttachmentMb: t.Optional(t.Integer({ minimum: 1, maximum: 10240 })),
+ maxAvatarMb: t.Optional(t.Integer({ minimum: 1, maximum: 1024 })),
+ attachmentMimeTypes: t.Optional(t.Array(t.String({ minLength: 1 }))),
+ projectQuotaMb: t.Optional(t.Integer({ minimum: 0 })),
+});
+
+export const TelegramSettingsResponse = t.Object({
+ enabled: t.Boolean(),
+ // Resolved from Telegram when the token is saved. Shown so the administrator can
+ // confirm which bot the token belongs to, and used to build the link deep link.
+ botUsername: t.String(),
+ hasBotToken: t.Boolean(),
+});
+
+export const TelegramSettingsBody = t.Object({
+ enabled: t.Optional(t.Boolean()),
+ botToken: t.Optional(t.String()),
+});
+
+const InstanceUserResponse = t.Object({
+ id: t.String(),
+ name: t.String(),
+ email: t.String(),
+ image: t.Nullable(t.String()),
+ emailVerified: t.Boolean(),
+ role: t.String(),
+ isAgent: t.Boolean(),
+ providers: t.Array(t.String()),
+ projectCount: t.Number(),
+ lastSeenAt: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const InstanceUserDetailResponse = t.Composite([
+ InstanceUserResponse,
+ t.Object({
+ projects: t.Array(
+ t.Object({
+ projectId: t.Number(),
+ projectKey: t.String(),
+ projectName: t.String(),
+ role: t.UnionEnum(['owner', 'member']),
+ roleId: t.Nullable(t.Number()),
+ roleName: t.Nullable(t.String()),
+ permissions: PermissionMatrixSchema,
+ ownerCount: t.Number(),
+ joinedAt: t.String(),
+ }),
+ ),
+ }),
+]);
+
+export const InstanceUserListResponse = t.Object({
+ items: t.Array(InstanceUserResponse),
+ total: t.Number(),
+});
+
+const InstanceProjectResponse = t.Object({
+ id: t.Number(),
+ key: t.String(),
+ name: t.String(),
+ description: t.String(),
+ mcpEnabled: t.Boolean(),
+ memberCount: t.Number(),
+ issueCount: t.Number(),
+ archivedIssueCount: t.Number(),
+ initiativeCount: t.Number(),
+ dashboardCount: t.Number(),
+ viewCount: t.Number(),
+ agentCount: t.Number(),
+ skillCount: t.Number(),
+ toolCount: t.Number(),
+ integrationCount: t.Number(),
+ lastActivityAt: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const InstanceProjectDetailResponse = t.Composite([
+ InstanceProjectResponse,
+ t.Object({
+ members: t.Array(
+ t.Object({
+ userId: t.String(),
+ name: t.String(),
+ email: t.String(),
+ image: t.Nullable(t.String()),
+ isAgent: t.Boolean(),
+ role: t.UnionEnum(['owner', 'member']),
+ roleId: t.Nullable(t.Number()),
+ roleName: t.Nullable(t.String()),
+ permissions: PermissionMatrixSchema,
+ joinedAt: t.String(),
+ }),
+ ),
+ }),
+]);
+
+export const InstanceProjectListResponse = t.Object({
+ items: t.Array(InstanceProjectResponse),
+ total: t.Number(),
+});
diff --git a/apps/api/src/god/store.ts b/apps/api/src/modules/god/service.ts
similarity index 99%
rename from apps/api/src/god/store.ts
rename to apps/api/src/modules/god/service.ts
index 20e98a28..9c89aa82 100644
--- a/apps/api/src/god/store.ts
+++ b/apps/api/src/modules/god/service.ts
@@ -31,13 +31,13 @@ import {
type SQL,
} from 'drizzle-orm';
import type { AnyPgColumn, PgTable } from 'drizzle-orm/pg-core';
-import { iso } from '../shared/lib';
+import { iso } from '#shared/lib';
import {
defaultMemberPermissions,
fullPermissions,
normalizePermissions,
type Permissions,
-} from '../shared/permissions';
+} from '#shared/permissions';
// Data access for the instance directories (god mode): every account and every
// project on this instance. It reads across the better-auth tables (user, session,
diff --git a/apps/api/src/modules/initiatives/service.ts b/apps/api/src/modules/initiatives/service.ts
index ee721ebe..8d395ad8 100644
--- a/apps/api/src/modules/initiatives/service.ts
+++ b/apps/api/src/modules/initiatives/service.ts
@@ -1,6 +1,6 @@
import { db, initiative, initiativeLabel, issue, label, projectColumn, user } from '@repo/db';
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
-import { labelNames } from '../../issues/activity';
+import { labelNames } from '#modules/issues/activity';
import { getMembership } from '#modules/members/service';
import { HttpError, iso, num } from '#shared/lib';
import { computeHealth, type Health } from './health';
diff --git a/apps/api/src/modules/invites/index.ts b/apps/api/src/modules/invites/index.ts
index 982f2a90..7f32d811 100644
--- a/apps/api/src/modules/invites/index.ts
+++ b/apps/api/src/modules/invites/index.ts
@@ -6,7 +6,7 @@ import { guards } from '#shared/guards';
import { requireUser, type AuthUser } from '#shared/access';
import { HttpError } from '#shared/lib';
import { accessErrors, commonErrors, errors } from '#shared/responses';
-import { getRole } from '../../roles/store';
+import { getRole } from '#modules/roles/service';
import {
AcceptInviteResponse,
InviteRowListResponse,
diff --git a/apps/api/src/issues/__tests__/integration/activity.test.ts b/apps/api/src/modules/issues/__tests__/integration/activity.test.ts
similarity index 99%
rename from apps/api/src/issues/__tests__/integration/activity.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/activity.test.ts
index da13901e..cf05df3b 100644
--- a/apps/api/src/issues/__tests__/integration/activity.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/activity.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser, type TestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser, type TestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// An issue's timeline (issue_activity): comments (POST /issues/:issueId/comments)
// and change-log entries recorded by the issue mutation routes, merged and paged
diff --git a/apps/api/src/issues/__tests__/integration/checklists.test.ts b/apps/api/src/modules/issues/__tests__/integration/checklists.test.ts
similarity index 98%
rename from apps/api/src/issues/__tests__/integration/checklists.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/checklists.test.ts
index 54d6a278..a3a38571 100644
--- a/apps/api/src/issues/__tests__/integration/checklists.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/checklists.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Checklists: an issue holds several checklists, each holding checkbox items. Both
// are ordered by position within their parent and come back with the issue read
diff --git a/apps/api/src/issues/__tests__/integration/issues.test.ts b/apps/api/src/modules/issues/__tests__/integration/issues.test.ts
similarity index 99%
rename from apps/api/src/issues/__tests__/integration/issues.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/issues.test.ts
index 9eca4d26..fa4e4c50 100644
--- a/apps/api/src/issues/__tests__/integration/issues.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/issues.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Issues live under a project. Create is /projects/:projectKey/issues (permission
// guard on :projectKey); the other routes address the issue by its own id
@@ -637,7 +637,7 @@ describe('issues', () => {
.put({ value: 8 });
expect(put.status).toBe(200);
- // The number column stores a string; the store coerces it back to a number.
+ // The number column stores a string. The service coerces it back to a number.
expect((await fieldValue(asOwner, issue.id, field.id))?.value).toBe(8);
});
diff --git a/apps/api/src/issues/__tests__/integration/links.test.ts b/apps/api/src/modules/issues/__tests__/integration/links.test.ts
similarity index 98%
rename from apps/api/src/issues/__tests__/integration/links.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/links.test.ts
index 958263b7..c185d54a 100644
--- a/apps/api/src/issues/__tests__/integration/links.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/links.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
import { type IssueLinkInputKind } from '../../links';
// Relations between issues. A relation is one row and shows on both issues, each
diff --git a/apps/api/src/issues/__tests__/integration/subtasks.test.ts b/apps/api/src/modules/issues/__tests__/integration/subtasks.test.ts
similarity index 99%
rename from apps/api/src/issues/__tests__/integration/subtasks.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/subtasks.test.ts
index 253e50fa..21bdce06 100644
--- a/apps/api/src/issues/__tests__/integration/subtasks.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/subtasks.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Subtasks: an issue carries the id of the issue it hangs under (parentId), set on
// create or through an update. The hierarchy is one level deep and stays inside one
diff --git a/apps/api/src/issues/__tests__/integration/watchers.test.ts b/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
similarity index 97%
rename from apps/api/src/issues/__tests__/integration/watchers.test.ts
rename to apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
index 7be98c94..5617e316 100644
--- a/apps/api/src/issues/__tests__/integration/watchers.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/watchers.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+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
diff --git a/apps/api/src/issues/activity.ts b/apps/api/src/modules/issues/activity.ts
similarity index 99%
rename from apps/api/src/issues/activity.ts
rename to apps/api/src/modules/issues/activity.ts
index e0838c0c..fd64ccfe 100644
--- a/apps/api/src/issues/activity.ts
+++ b/apps/api/src/modules/issues/activity.ts
@@ -10,8 +10,8 @@ import {
cycle,
} from '@repo/db';
import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
-import { HttpError, iso } from '../shared/lib';
-import { emitWebhookEvent } from '../webhooks/emit';
+import { HttpError, iso } from '#shared/lib';
+import { emitWebhookEvent } from '#modules/webhooks/emit';
import { parseMentionHandles, resolveMentionHandles } from '#shared/mentions';
import { isAgentUser, listMentionTriggerAgents } from '#modules/agents/core/service';
import { enqueueAgentRun } from '#modules/agents/core/run-queue';
diff --git a/apps/api/src/issues/automation.ts b/apps/api/src/modules/issues/automation.ts
similarity index 98%
rename from apps/api/src/issues/automation.ts
rename to apps/api/src/modules/issues/automation.ts
index 380ff1dd..562689cc 100644
--- a/apps/api/src/issues/automation.ts
+++ b/apps/api/src/modules/issues/automation.ts
@@ -2,7 +2,7 @@ import { db, issue, projectColumn } from '@repo/db';
import { and, eq, inArray, isNull } from 'drizzle-orm';
import { getSubtaskAutomationSettings } from '#modules/projects/service';
import { listSubtasks } from './subtasks';
-import { updateIssue, type IssueRow } from './store';
+import { updateIssue, type IssueRow } from './service';
import type { ActivityActor } from './activity';
// The subtask automations a column change triggers, both off unless the project
diff --git a/apps/api/src/issues/checklists.ts b/apps/api/src/modules/issues/checklists.ts
similarity index 99%
rename from apps/api/src/issues/checklists.ts
rename to apps/api/src/modules/issues/checklists.ts
index eecf1aae..454be666 100644
--- a/apps/api/src/issues/checklists.ts
+++ b/apps/api/src/modules/issues/checklists.ts
@@ -1,6 +1,6 @@
import { db, issueChecklist, issueChecklistItem } from '@repo/db';
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
-import { HttpError } from '../shared/lib';
+import { HttpError } from '#shared/lib';
import { recordActivity } from './activity';
// Checklists on an issue: a list of steps too small to be subtasks of their own.
diff --git a/apps/api/src/issues/routes.ts b/apps/api/src/modules/issues/index.ts
similarity index 56%
rename from apps/api/src/issues/routes.ts
rename to apps/api/src/modules/issues/index.ts
index b72a57bf..37a99f9c 100644
--- a/apps/api/src/issues/routes.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -1,14 +1,14 @@
import { Elysia, t } from 'elysia';
-import { mcpTool } from '../mcp/generate';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { assertPermission, assertMcpEnabled, requireUser } from '../shared/access';
-import { isMcpRequest } from '../shared/mcp-request';
+import { mcpTool } from '#mcp/generate';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { assertPermission, assertMcpEnabled, requireUser } from '#shared/access';
+import { isMcpRequest } from '#shared/mcp-request';
import { getProjectById } from '#modules/projects/service';
-import { HttpError } from '../shared/lib';
-import { accessErrors, commonErrors, errors } from '../shared/responses';
-import { deleteObject } from '../shared/s3';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { deleteObject } from '#shared/s3';
import {
createIssue,
searchIssues,
@@ -28,7 +28,7 @@ import {
setIssueLabels,
setIssueFieldValue,
getIssueFieldValues,
-} from './store';
+} from './service';
import {
listFeed,
listFeedRange,
@@ -62,9 +62,50 @@ import {
updateChecklistItem,
} from './checklists';
-// Numeric path params are validated (and coerced string -> number) with t.Numeric,
-// so a non-numeric id is rejected with a 400 before reaching the store.
-const issueParams = t.Object({ issueId: t.Numeric() });
+import {
+ issueParams,
+ IssueResponse,
+ IssueLinkResponse,
+ IssueWatcherResponse,
+ ChecklistItemResponse,
+ ChecklistResponse,
+ OrderedIdsSchema,
+ checklistParams,
+ checklistItemParams,
+ IssueWithFieldsResponse,
+ IssueSearchHitResponse,
+ FeedItemResponse,
+ FeedPageResponse,
+ GroupedFeedPageResponse,
+ feedPageQuery,
+ TimelineSegmentResponse,
+ projectKeyParams,
+ createIssueBody,
+ bulkUpdateIssuesBody,
+ bulkAddLabelsBody,
+ bulkArchiveIssuesBody,
+ bulkDeleteIssuesBody,
+ searchIssuesQuery,
+ listIssuesQuery,
+ issueSequenceParams,
+ updateIssueBody,
+ subtaskDispositionQuery,
+ setIssueFieldValueBody,
+ issueFieldParams,
+ addIssueLinkBody,
+ issueLinkParams,
+ checklistTitleBody,
+ createChecklistItemBody,
+ updateChecklistItemBody,
+ feedRangeQuery,
+ createCommentBody,
+ archiveIssueBody,
+ BulkUpdatedResponse,
+ BulkArchivedResponse,
+ BulkDeletedResponse,
+ BoardResponse,
+ WatchStateResponse,
+} from './model';
// The subtask choice a delete or archive request carries, or undefined when it
// carries none.
@@ -90,265 +131,7 @@ async function purgeObjects(attachments: { s3Key: string }[]): Promise<void> {
);
}
-// --- Response DTO schemas (mirror the store interfaces the handlers return) -------
-
-// IssueFieldValueEntry from the store: a compact custom field value carried on an
-// issue (scalar value, the end of a datetime_range, and selected option ids).
-const IssueFieldValueEntry = t.Object({
- fieldId: t.Number(),
- value: t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()])),
- valueEnd: t.Nullable(t.String()),
- optionIds: t.Array(t.Number()),
-});
-
-// IssueRow from the store.
-const IssueResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- sequenceNumber: t.Number(),
- identifier: t.String(),
- typeId: t.Nullable(t.Number()),
- // The linked initiative expanded to id + title for rendering and status for
- // ordering the lanes of a board grouped by initiative, or null. Set through
- // create/update by initiativeId.
- initiative: t.Nullable(t.Object({ id: t.Number(), title: t.String(), status: t.String() })),
- // The cycle this issue is planned into, expanded to id + name for rendering and
- // status for filtering by the running or the upcoming ones, or null. Set through
- // create/update by cycleId.
- cycle: t.Nullable(t.Object({ id: t.Number(), name: t.String(), status: t.String() })),
- assigneeUserId: t.Nullable(t.String()),
- delegateUserId: t.Nullable(t.String()),
- columnId: t.Number(),
- // The issue this one is a subtask of, or null. Set through create/update.
- parentId: t.Nullable(t.Number()),
- title: t.String(),
- description: t.String(),
- priority: t.Nullable(t.String()),
- startDate: t.Nullable(t.String()),
- dueDate: t.Nullable(t.String()),
- position: t.Number(),
- createdAt: t.String(),
- updatedAt: t.String(),
- archivedAt: t.Nullable(t.String()),
- statusSince: t.String(),
- shareToken: t.Nullable(t.String()),
- shareExtended: t.Boolean(),
- labelIds: t.Array(t.Number()),
- fieldValues: t.Array(IssueFieldValueEntry),
-});
-
-// IssueFieldValueRow from the store: one applicable custom field joined with its
-// value on the issue. fieldType is the CustomFieldType union (a string).
-const IssueFieldValueRow = t.Object({
- fieldId: t.Number(),
- name: t.String(),
- fieldType: t.String(),
- value: t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()])),
- valueEnd: t.Nullable(t.String()),
- optionIds: t.Array(t.Number()),
-});
-
-// IssueRef from subtasks.ts: another issue named with the state it is in — an
-// issue's parent, one of its subtasks, or the other end of a relation.
-const IssueRefResponse = t.Object({
- id: t.Number(),
- sequenceNumber: t.Number(),
- identifier: t.String(),
- title: t.String(),
- columnId: t.Number(),
- typeId: t.Nullable(t.Number()),
- archived: t.Boolean(),
-});
-
-// The kinds a relation is stored under (IssueLinkKind in links.ts).
-const StoredLinkKind = t.Union([
- t.Literal('blocks'),
- t.Literal('relates'),
- t.Literal('duplicates'),
-]);
-
-// IssueLinkRow from links.ts: one relation to another issue, as it reads from the
-// issue it was loaded for.
-const IssueLinkResponse = t.Object({
- id: t.Number(),
- kind: StoredLinkKind,
- direction: t.Union([t.Literal('outward'), t.Literal('inward')]),
- issue: IssueRefResponse,
-});
-
-// A relation as one of its two issues reads it (IssueLinkInputKind in links.ts):
-// what a caller states when creating one, and what a board issue carries.
-const IssueLinkKindSchema = t.Union(
- [
- t.Literal('blocks'),
- t.Literal('blocked_by'),
- t.Literal('relates'),
- t.Literal('duplicates'),
- t.Literal('duplicated_by'),
- ],
- {
- description:
- 'How one issue relates to the other: blocks, blocked_by, relates, duplicates, or duplicated_by.',
- },
-);
-
-// BoardIssueLink from links.ts: one relation on the issue carrying it, with the
-// other end as an id.
-const BoardIssueLinkResponse = t.Object({
- id: t.Number(),
- relation: IssueLinkKindSchema,
- issueId: t.Number(),
-});
-
-// What a delete or an archive does with the issue's subtasks. Required when it has
-// any, ignored when it has none.
-const SubtaskModeSchema = t.Union(
- [t.Literal('cascade'), t.Literal('detach'), t.Literal('reassign')],
- {
- description:
- "What happens to the issue's subtasks: 'cascade' removes them with it, 'detach' turns them into ordinary issues, 'reassign' moves them to newParentId.",
- },
-);
-
-const NewParentIdSchema = t.Integer({
- description: "Numeric id of the issue the subtasks move to. Required by 'reassign'.",
-});
-
-// IssueWatcherRow from watchers.ts: one member following the issue.
-const IssueWatcherResponse = t.Object({
- userId: t.String(),
- name: t.String(),
- image: t.Nullable(t.String()),
-});
-
-// ChecklistItemRow / ChecklistRow from checklists.ts.
-const ChecklistItemResponse = t.Object({
- id: t.Number(),
- content: t.String(),
- done: t.Boolean(),
- position: t.Number(),
-});
-
-const ChecklistResponse = t.Object({
- id: t.Number(),
- title: t.String(),
- position: t.Number(),
- items: t.Array(ChecklistItemResponse),
-});
-
-const ChecklistTitleSchema = t.String({
- minLength: 1,
- maxLength: 200,
- description: 'Title of the checklist.',
-});
-
-const ChecklistItemContentSchema = t.String({
- minLength: 1,
- maxLength: 500,
- description: 'Text of the checklist item.',
-});
-
-// A reorder sends the ids in their new order. Ids outside the parent in the path
-// are ignored, and ones left out keep their position after the listed ones.
-const OrderedIdsSchema = t.Object({
- orderedIds: t.Array(t.Integer(), { minItems: 1 }),
-});
-
-const checklistParams = t.Object({ checklistId: t.Numeric() });
-const checklistItemParams = t.Object({ itemId: t.Numeric() });
-
-// GET /issues/:issueId returns the full issue plus its custom field values, its
-// relations to other issues, the members watching it, and its checklists.
-const IssueWithFieldsResponse = t.Composite([
- IssueResponse,
- t.Object({
- fields: t.Array(IssueFieldValueRow),
- links: t.Array(IssueLinkResponse),
- watchers: t.Array(IssueWatcherResponse),
- parent: t.Nullable(IssueRefResponse),
- subtasks: t.Array(IssueRefResponse),
- checklists: t.Array(ChecklistResponse),
- }),
-]);
-
-// The board carries each issue's relations on the issue itself.
-const BoardIssueResponse = t.Composite([
- IssueResponse,
- t.Object({
- links: t.Array(BoardIssueLinkResponse),
- // How many subtasks the issue has, archived ones included — the board lists
- // only active issues, so it cannot count them from the payload itself.
- subtaskCount: t.Number(),
- }),
-]);
-
-// IssueSearchHit from the store: a light search result (no description/field values).
-const IssueSearchHitResponse = t.Object({
- id: t.Number(),
- sequenceNumber: t.Number(),
- identifier: t.String(),
- title: t.String(),
- columnId: t.Number(),
- typeId: t.Nullable(t.Number()),
- initiativeId: t.Nullable(t.Number()),
- cycleId: t.Nullable(t.Number()),
- parentId: t.Nullable(t.Number()),
- assigneeUserId: t.Nullable(t.String()),
- delegateUserId: t.Nullable(t.String()),
- priority: t.Nullable(t.String()),
- dueDate: t.Nullable(t.String()),
- labelIds: t.Array(t.Number()),
- archived: t.Boolean(),
-});
-
-// FeedItemRow from activity.ts: one timeline entry (comment or change-log).
-// kind is the FeedKind union (a string).
-const FeedItemResponse = t.Object({
- id: t.Number(),
- issueId: t.Number(),
- kind: t.String(),
- replyToId: t.Nullable(t.Number()),
- actorUserId: t.Nullable(t.String()),
- actorName: t.Nullable(t.String()),
- body: t.Nullable(t.String()),
- action: t.Nullable(t.String()),
- subject: t.Nullable(t.String()),
- fromText: t.Nullable(t.String()),
- toText: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-const FeedCursorResponse = t.Nullable(t.Object({ ts: t.String(), id: t.Number() }));
-
-// FeedPage from activity.ts: one page of the feed with the keyset cursor.
-const FeedPageResponse = t.Object({
- items: t.Array(FeedItemResponse),
- nextCursor: FeedCursorResponse,
-});
-
-// GroupedFeedPage from activity.ts: the same page, split into the stretches the issue
-// spent in one column.
-const GroupedFeedPageResponse = t.Object({
- groups: t.Array(
- t.Object({
- status: t.Nullable(t.String()),
- from: t.String(),
- to: t.Nullable(t.String()),
- durationMs: t.Number(),
- repeat: t.Boolean(),
- items: t.Array(FeedItemResponse),
- }),
- ),
- nextCursor: FeedCursorResponse,
-});
-
-// Both feed routes are paged the same way: a limit and the previous page's cursor.
-const feedPageQuery = t.Object({
- limit: t.Optional(t.Numeric({ description: 'Max items per page (1-100). Default 25.' })),
- cursor: t.Optional(t.String({ description: 'nextCursor from the previous page, for paging.' })),
-});
-
-// The cursor travels as JSON in the query string. A malformed one is ignored, which
+// The cursor travels as JSON in the query string. A malformed one gives null, which
// serves the first page.
function feedCursor(raw?: string): FeedCursor | null {
if (!raw) return null;
@@ -359,20 +142,12 @@ function feedCursor(raw?: string): FeedCursor | null {
}
}
-// TimelineSegment from activity.ts: one stretch the issue spent in a column.
-const TimelineSegmentResponse = t.Object({
- status: t.Nullable(t.String()),
- from: t.String(),
- to: t.Nullable(t.String()),
- durationMs: t.Number(),
-});
-
export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues'] } })
.use(authContext)
.use(guards)
// Guards for routes that address an entity by its own id (no :projectKey in the
// path). Set `workItem` / `checklist` / `checklistItem` to the action in the
- // route options. A checklist and its items are part of the issue they hang on,
+ // route options. A checklist and its items belong to the issue that carries them,
// so all three resolve to the same work_items permission.
.macro({
workItem: entityGuard('work_items', 'Issue not found', (p) =>
@@ -394,67 +169,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return createIssue(project, body, requireUser(user).id);
},
{
- body: t.Object({
- typeId: t.Optional(
- t.Nullable(t.Integer({ description: 'Issue type id, or null. From get_project.' })),
- ),
- initiativeId: t.Optional(
- t.Nullable(
- t.Integer({
- description: 'Initiative id to link this issue to, or null. From list_initiatives.',
- }),
- ),
- ),
- cycleId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Cycle id to plan this issue into, or null. From list_cycles; a completed cycle is rejected.',
- }),
- ),
- ),
- assigneeUserId: t.Optional(
- t.Nullable(
- t.String({
- description:
- "Assignee user id (a project member), or null. From get_project.assignees where kind is 'member'.",
- }),
- ),
- ),
- delegateUserId: t.Optional(
- t.Nullable(
- t.String({
- description:
- "Delegate user id (an AI agent), or null. From get_project.assignees where kind is 'agent'.",
- }),
- ),
- ),
- columnId: t.Integer({ description: 'Target column (state) id. From get_project.columns.' }),
- parentId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Numeric id of the issue this one is a subtask of, or null. The parent must be in this project and must not be a subtask itself.',
- }),
- ),
- ),
- title: t.String({ minLength: 1, description: 'Issue title.' }),
- description: t.Optional(
- t.String({ description: 'Issue description (plain text or markdown).' }),
- ),
- priority: t.Optional(
- t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
- ),
- startDate: t.Optional(
- t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." })),
- ),
- dueDate: t.Optional(
- t.Nullable(t.String({ description: "Due date 'YYYY-MM-DD', or null." })),
- ),
- labelIds: t.Optional(
- t.Array(t.Integer(), { description: 'Label ids to attach. From get_project.labels.' }),
- ),
- }),
+ body: createIssueBody,
permission: ['work_items', 'create'],
response: { 201: IssueResponse, ...commonErrors, ...errors(409) },
detail: {
@@ -468,9 +183,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
)
// --- Bulk actions (board multi-select) -----------------------------------------
- // Project-scoped so the `permission` guard resolves the project and asserts
- // access once; the store filters the ids to this project, so a bulk action can
- // never touch another project's issues.
+ // Project-scoped, so the `permission` guard resolves the project and asserts access
+ // once. The service filters the ids to this project, so a bulk action can never
+ // touch another project's issues.
// Applies one patch to every listed issue.
.patch(
@@ -485,23 +200,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { updated };
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to update.' }),
- patch: t.Object({
- columnId: t.Optional(t.Integer()),
- typeId: t.Optional(t.Nullable(t.Integer())),
- initiativeId: t.Optional(t.Nullable(t.Integer())),
- cycleId: t.Optional(t.Nullable(t.Integer())),
- assigneeUserId: t.Optional(t.Nullable(t.String())),
- delegateUserId: t.Optional(t.Nullable(t.String())),
- priority: t.Optional(t.Nullable(t.String())),
- startDate: t.Optional(t.Nullable(t.String())),
- dueDate: t.Optional(t.Nullable(t.String())),
- }),
- }),
+ params: projectKeyParams,
+ body: bulkUpdateIssuesBody,
permission: ['work_items', 'edit'],
- response: { 200: t.Object({ updated: t.Number() }), ...commonErrors, ...errors(409) },
+ response: { 200: BulkUpdatedResponse, ...commonErrors, ...errors(409) },
detail: { summary: 'Bulk update issues' },
},
)
@@ -514,13 +216,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { updated };
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to label.' }),
- add: t.Array(t.Integer(), { minItems: 1, description: 'Label ids to add.' }),
- }),
+ params: projectKeyParams,
+ body: bulkAddLabelsBody,
permission: ['work_items', 'edit'],
- response: { 200: t.Object({ updated: t.Number() }), ...commonErrors },
+ response: { 200: BulkUpdatedResponse, ...commonErrors },
detail: { summary: 'Bulk add labels to issues' },
},
)
@@ -535,14 +234,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { archived };
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to archive.' }),
- subtasks: t.Optional(SubtaskModeSchema),
- newParentId: t.Optional(NewParentIdSchema),
- }),
+ params: projectKeyParams,
+ body: bulkArchiveIssuesBody,
permission: ['work_items', 'edit'],
- response: { 200: t.Object({ archived: t.Number() }), ...commonErrors, ...errors(409) },
+ response: { 200: BulkArchivedResponse, ...commonErrors, ...errors(409) },
detail: { summary: 'Bulk archive issues' },
},
)
@@ -563,23 +258,19 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { deleted };
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to delete.' }),
- subtasks: t.Optional(SubtaskModeSchema),
- newParentId: t.Optional(NewParentIdSchema),
- }),
+ params: projectKeyParams,
+ body: bulkDeleteIssuesBody,
permission: ['work_items', 'delete'],
- response: { 200: t.Object({ deleted: t.Number() }), ...commonErrors, ...errors(409) },
+ response: { 200: BulkDeletedResponse, ...commonErrors, ...errors(409) },
detail: { summary: 'Bulk delete issues' },
},
)
// Text search: matches q (case-insensitive substring) against the title,
// description, issue number, and custom field text. Always searches every issue,
- // archived included (each hit carries an 'archived' flag); filtering by fields is
- // a separate concern (see list_issues). Declared before /issues/:sequenceNumber so
- // the static "search" segment wins over the numeric param.
+ // archived included, and each hit carries an 'archived' flag. Filtering by fields is
+ // a separate concern (see list_issues). This route comes before
+ // /issues/:sequenceNumber so the static "search" segment wins over the numeric param.
.get(
'/projects/:projectKey/issues/search',
async ({ project, query }) => {
@@ -587,16 +278,8 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return searchIssues(project, { query: query.q, limit }, { includeArchived: true });
},
{
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- q: t.Optional(
- t.String({
- description:
- 'Case-insensitive substring, matched against the title, description, issue number, and custom field text.',
- }),
- ),
- limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
- }),
+ params: projectKeyParams,
+ query: searchIssuesQuery,
permission: ['work_items', 'read'],
response: { 200: t.Array(IssueSearchHitResponse), ...commonErrors },
detail: {
@@ -607,9 +290,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // Filtered list: no text query, only exact field filters. Every filter is optional
- // and all supplied ones must match; with no filters this lists the project's active
- // issues. Archived are excluded unless includeArchived is 'true'.
+ // Filtered list: no text query, only exact field filters. Every filter is optional,
+ // and every filter the caller sets must match. With no filters this lists the
+ // project's active issues. It leaves out archived issues unless includeArchived is
+ // 'true'.
.get(
'/projects/:projectKey/issues',
async ({ project, query }) => {
@@ -644,28 +328,8 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
);
},
{
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- columnId: t.Optional(t.Numeric({ description: 'Exact column (state) id.' })),
- typeId: t.Optional(t.Numeric({ description: 'Exact issue type id.' })),
- initiativeId: t.Optional(t.Numeric({ description: 'Exact initiative id.' })),
- cycleId: t.Optional(t.Numeric({ description: 'Exact cycle id.' })),
- parentId: t.Optional(
- t.Numeric({ description: 'Parent issue id, to list that issue’s subtasks.' }),
- ),
- assigneeUserId: t.Optional(t.String({ description: 'Exact assignee user id.' })),
- delegateUserId: t.Optional(t.String({ description: 'Exact delegate agent id.' })),
- priority: t.Optional(t.String({ description: 'Exact priority value.' })),
- labelIds: t.Optional(
- t.String({ description: 'CSV of label ids; the issue must carry all.' }),
- ),
- dueFrom: t.Optional(t.String({ description: "Inclusive earliest due date 'YYYY-MM-DD'." })),
- dueTo: t.Optional(t.String({ description: "Inclusive latest due date 'YYYY-MM-DD'." })),
- includeArchived: t.Optional(
- t.String({ description: "'true' to include archived issues. Default false." }),
- ),
- limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
- }),
+ params: projectKeyParams,
+ query: listIssuesQuery,
permission: ['work_items', 'read'],
response: { 200: t.Array(IssueSearchHitResponse), ...commonErrors },
detail: {
@@ -690,9 +354,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
),
}),
{
- params: t.Object({ projectKey: t.String() }),
+ params: projectKeyParams,
permission: ['work_items', 'read'],
- response: { 200: t.Object({ issues: t.Array(BoardIssueResponse) }), ...accessErrors },
+ response: { 200: BoardResponse, ...accessErrors },
detail: { summary: 'Get board issues' },
},
)
@@ -703,7 +367,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
'/projects/:projectKey/issues/archived',
async ({ project }) => listArchivedIssues(project),
{
- params: t.Object({ projectKey: t.String() }),
+ params: projectKeyParams,
permission: ['work_items', 'read'],
response: { 200: t.Array(IssueResponse), ...accessErrors },
detail: { summary: 'List archived issues' },
@@ -727,7 +391,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { ...issue, fields, links, watchers, parent, subtasks, checklists };
},
{
- params: t.Object({ projectKey: t.String(), sequenceNumber: t.Numeric() }),
+ params: issueSequenceParams,
permission: ['work_items', 'read'],
response: { 200: IssueWithFieldsResponse, ...commonErrors },
detail: {
@@ -739,9 +403,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // Reads the full issue including its custom field values. The issue is fetched
- // for the response, so access is asserted on the fetched row rather than
- // through the workItem guard (which would re-resolve the project id).
+ // Reads the full issue including its custom field values. The handler fetches the
+ // issue for the response, so it asserts access on that row instead of using the
+ // workItem guard, which would resolve the project id a second time.
.get(
'/issues/:issueId',
async ({ params, user, request }) => {
@@ -790,59 +454,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return issue;
},
{
- body: t.Object({
- columnId: t.Optional(
- t.Integer({ description: 'Move the issue to this column (state) id.' }),
- ),
- position: t.Optional(t.Number({ description: 'Ordering position within the column.' })),
- typeId: t.Optional(t.Nullable(t.Integer({ description: 'New issue type id, or null.' }))),
- parentId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Make this issue a subtask of that issue id, or null to detach it. The parent must be in this project and must not be a subtask itself; an issue that has subtasks cannot become one.',
- }),
- ),
- ),
- initiativeId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Link this issue to an initiative id, or null to unlink. From list_initiatives.',
- }),
- ),
- ),
- cycleId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Plan this issue into a cycle id, or null to unplan it. From list_cycles; a completed cycle is rejected.',
- }),
- ),
- ),
- assigneeUserId: t.Optional(
- t.Nullable(
- t.String({ description: 'New assignee user id (a project member), or null.' }),
- ),
- ),
- delegateUserId: t.Optional(
- t.Nullable(t.String({ description: 'New delegate user id (an AI agent), or null.' })),
- ),
- title: t.Optional(t.String({ minLength: 1, description: 'New title.' })),
- description: t.Optional(t.String({ description: 'New description.' })),
- priority: t.Optional(
- t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
- ),
- startDate: t.Optional(
- t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." })),
- ),
- dueDate: t.Optional(
- t.Nullable(t.String({ description: "Due date 'YYYY-MM-DD', or null." })),
- ),
- labelIds: t.Optional(
- t.Array(t.Integer(), { description: "Replace the issue's labels with these ids." }),
- ),
- }),
+ body: updateIssueBody,
params: issueParams,
workItem: 'edit',
response: { 200: IssueResponse, ...commonErrors, ...errors(409) },
@@ -856,10 +468,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // Deletes an issue. Its custom field values, labels, attachments, comments and
- // activity are removed with it. Attachment objects are then deleted from the
- // object store; a failed object delete only orphans bytes, so it does not fail
- // the request.
+ // Deletes an issue, together with its custom field values, labels, attachments,
+ // comments and activity. It then deletes the attachment objects from the object
+ // store. A failed object delete only orphans bytes, so it does not fail the
+ // request.
.delete(
'/issues/:issueId',
async ({ params, query, user, projectId }) => {
@@ -877,10 +489,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
{
params: issueParams,
- query: t.Object({
- subtasks: t.Optional(SubtaskModeSchema),
- newParentId: t.Optional(t.Numeric(NewParentIdSchema)),
- }),
+ query: subtaskDispositionQuery,
workItem: 'delete',
response: { 204: t.Void(), ...commonErrors, ...errors(409) },
detail: {
@@ -912,12 +521,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
{
params: issueParams,
- body: t.Optional(
- t.Object({
- subtasks: t.Optional(SubtaskModeSchema),
- newParentId: t.Optional(NewParentIdSchema),
- }),
- ),
+ body: archiveIssueBody,
workItem: 'edit',
response: { 200: IssueResponse, ...commonErrors, ...errors(409) },
detail: {
@@ -953,11 +557,11 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // Sets one custom field's value on one issue. For select/multi_select fields,
- // body.optionIds replaces the full selection; for every other field type,
- // body.value must match the field's type (text/number/boolean/date/datetime,
- // and the user id of a project member for a member field). A datetime_range takes
- // its end in body.valueEnd.
+ // Sets one custom field's value on one issue. For a select or multi_select field,
+ // body.optionIds replaces the full selection. For every other field type, body.value
+ // must match the field's type (text/number/boolean/date/datetime, and the user id of
+ // a project member for a member field). A datetime_range takes its end in
+ // body.valueEnd.
.put(
'/issues/:issueId/fields/:fieldId',
async ({ params, body, user, projectId }) => {
@@ -971,14 +575,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return { ok: true };
},
{
- body: t.Object({
- value: t.Optional(t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()]))),
- valueEnd: t.Optional(t.Nullable(t.String())),
- optionIds: t.Optional(t.Array(t.Integer())),
- }),
- params: t.Object({ issueId: t.Numeric(), fieldId: t.Numeric() }),
+ body: setIssueFieldValueBody,
+ params: issueFieldParams,
workItem: 'edit',
- response: { 200: t.Object({ ok: t.Boolean() }), ...commonErrors },
+ response: { 200: WatchStateResponse, ...commonErrors },
detail: {
summary: 'Set a custom field value',
description:
@@ -1000,12 +600,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return addIssueLink(params.issueId, body.targetIssueId, body.kind, requireUser(user).id);
},
{
- body: t.Object({
- targetIssueId: t.Integer({
- description: 'Numeric id of the issue on the other end of the relation.',
- }),
- kind: IssueLinkKindSchema,
- }),
+ body: addIssueLinkBody,
params: issueParams,
workItem: 'edit',
response: { 201: IssueLinkResponse, ...commonErrors, ...errors(409) },
@@ -1028,7 +623,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return noContent();
},
{
- params: t.Object({ issueId: t.Numeric(), linkId: t.Numeric() }),
+ params: issueLinkParams,
workItem: 'edit',
response: { 204: t.Void(), ...commonErrors },
detail: {
@@ -1059,7 +654,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return createChecklist(params.issueId, body.title, requireUser(user).id);
},
{
- body: t.Object({ title: ChecklistTitleSchema }),
+ body: checklistTitleBody,
params: issueParams,
workItem: 'edit',
response: { 201: ChecklistResponse, ...commonErrors },
@@ -1092,7 +687,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
async ({ params, body, user }) =>
renameChecklist(params.checklistId, body.title, requireUser(user).id),
{
- body: t.Object({ title: ChecklistTitleSchema }),
+ body: checklistTitleBody,
params: checklistParams,
checklist: 'edit',
response: { 200: ChecklistResponse, ...commonErrors },
@@ -1126,7 +721,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
return createChecklistItem(params.checklistId, body.content, requireUser(user).id);
},
{
- body: t.Object({ content: ChecklistItemContentSchema }),
+ body: createChecklistItemBody,
params: checklistParams,
checklist: 'edit',
response: { 201: ChecklistItemResponse, ...commonErrors },
@@ -1153,15 +748,12 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
)
// Edits the text, the checked state, or both. Checking a box is the most
- // frequent write here, so it is deliberately not written to the activity feed.
+ // frequent write here, so it deliberately does not reach the activity feed.
.patch(
'/checklists/items/:itemId',
async ({ params, body }) => updateChecklistItem(params.itemId, body),
{
- body: t.Object({
- content: t.Optional(ChecklistItemContentSchema),
- done: t.Optional(t.Boolean({ description: 'Whether the item is checked off.' })),
- }),
+ body: updateChecklistItemBody,
params: checklistItemParams,
checklistItem: 'edit',
response: { 200: ChecklistItemResponse, ...commonErrors },
@@ -1211,8 +803,9 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
- // Stops following the issue. The unsubscription is recorded rather than
- // forgotten, so commenting on the issue again does not silently re-subscribe.
+ // Stops following the issue. The route records the unsubscription instead of
+ // forgetting it, so a later comment on the issue does not silently re-subscribe
+ // the caller.
.delete(
'/issues/:issueId/watch',
async ({ params, projectId, user }) => {
@@ -1233,7 +826,8 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
// 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
- // pagination; the response is { items, nextCursor }, nextCursor null at the end.
+ // pagination. The response is { items, nextCursor }, and nextCursor is null on the
+ // last page.
.get(
'/issues/:issueId/feed',
async ({ params, query }) =>
@@ -1275,7 +869,8 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
// The stretches the issue spent in one column, oldest first, with the duration of
// each. Entry-free and unpaged: the change log holds a handful of status entries,
- // and what happened inside a stretch is read separately when it is opened.
+ // and a client reads the entries of one stretch separately when it opens that
+ // stretch.
.get('/issues/:issueId/timeline', async ({ params }) => listStatusTimeline(params.issueId), {
params: issueParams,
workItem: 'read',
@@ -1293,12 +888,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
async ({ params, query }) => listFeedRange(params.issueId, query.from, query.to),
{
params: issueParams,
- query: t.Object({
- from: t.String({ description: 'Start of the stretch (ISO datetime), inclusive.' }),
- to: t.Optional(
- t.String({ description: 'End of the stretch (ISO datetime), exclusive. Open-ended.' }),
- ),
- }),
+ query: feedRangeQuery,
workItem: 'read',
response: { 200: t.Array(FeedItemResponse), ...commonErrors },
detail: {
@@ -1322,12 +912,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
});
},
{
- body: t.Object({
- body: t.String({ minLength: 1, description: 'Comment text.' }),
- replyToId: t.Optional(
- t.Number({ description: 'Reply to this comment of the same issue.' }),
- ),
- }),
+ body: createCommentBody,
params: issueParams,
workItem: 'create',
response: { 201: FeedItemResponse, ...commonErrors },
diff --git a/apps/api/src/issues/links.ts b/apps/api/src/modules/issues/links.ts
similarity index 98%
rename from apps/api/src/issues/links.ts
rename to apps/api/src/modules/issues/links.ts
index efd2a024..c37b15a2 100644
--- a/apps/api/src/issues/links.ts
+++ b/apps/api/src/modules/issues/links.ts
@@ -1,10 +1,10 @@
import { db, issue, issueLink, project as projectTable } from '@repo/db';
import { and, eq, isNull, or, sql } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
-import { HttpError } from '../shared/lib';
+import { HttpError } from '#shared/lib';
import { recordActivityEntries, type ActivityInput } from './activity';
-import { emitWebhookEvents } from '../webhooks/emit';
-import { getIssues } from './store';
+import { emitWebhookEvents } from '#modules/webhooks/emit';
+import { getIssues } from './service';
// Relations between issues of one project. A relation is one row (issue_link);
// which side of it an issue sits on decides how the relation reads for that
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
new file mode 100644
index 00000000..caf38ceb
--- /dev/null
+++ b/apps/api/src/modules/issues/model.ts
@@ -0,0 +1,505 @@
+import { t } from 'elysia';
+
+// t.Numeric validates a numeric path param and coerces the string to a number. A
+// non-numeric id gets a 400 before it reaches the service.
+export const issueParams = t.Object({ issueId: t.Numeric() });
+
+// --- Response DTO schemas (mirror the service interfaces the handlers return) -----
+
+// IssueFieldValueEntry from the service: a compact custom field value on an issue. It
+// holds the scalar value, the end of a datetime_range, and the selected option ids.
+export const IssueFieldValueEntry = t.Object({
+ fieldId: t.Number(),
+ value: t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()])),
+ valueEnd: t.Nullable(t.String()),
+ optionIds: t.Array(t.Number()),
+});
+
+// IssueRow from the service.
+export const IssueResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ sequenceNumber: t.Number(),
+ identifier: t.String(),
+ typeId: t.Nullable(t.Number()),
+ // The linked initiative, or null. It carries id + title for rendering, and status
+ // to order the lanes of a board grouped by initiative. Create and update set it
+ // through initiativeId.
+ initiative: t.Nullable(t.Object({ id: t.Number(), title: t.String(), status: t.String() })),
+ // The cycle this issue is planned into, or null. It carries id + name for rendering,
+ // and status to filter by the running or the upcoming ones. Create and update set it
+ // through cycleId.
+ cycle: t.Nullable(t.Object({ id: t.Number(), name: t.String(), status: t.String() })),
+ assigneeUserId: t.Nullable(t.String()),
+ delegateUserId: t.Nullable(t.String()),
+ columnId: t.Number(),
+ // The issue this one is a subtask of, or null. Create and update set it.
+ parentId: t.Nullable(t.Number()),
+ title: t.String(),
+ description: t.String(),
+ priority: t.Nullable(t.String()),
+ startDate: t.Nullable(t.String()),
+ dueDate: t.Nullable(t.String()),
+ position: t.Number(),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+ archivedAt: t.Nullable(t.String()),
+ statusSince: t.String(),
+ shareToken: t.Nullable(t.String()),
+ shareExtended: t.Boolean(),
+ labelIds: t.Array(t.Number()),
+ fieldValues: t.Array(IssueFieldValueEntry),
+});
+
+// IssueFieldValueRow from the service: one applicable custom field with its value on
+// the issue. fieldType is the CustomFieldType union (a string).
+export const IssueFieldValueRow = t.Object({
+ fieldId: t.Number(),
+ name: t.String(),
+ fieldType: t.String(),
+ value: t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()])),
+ valueEnd: t.Nullable(t.String()),
+ optionIds: t.Array(t.Number()),
+});
+
+// IssueRef from subtasks.ts: another issue named with the state it is in — an
+// issue's parent, one of its subtasks, or the other end of a relation.
+export const IssueRefResponse = t.Object({
+ id: t.Number(),
+ sequenceNumber: t.Number(),
+ identifier: t.String(),
+ title: t.String(),
+ columnId: t.Number(),
+ typeId: t.Nullable(t.Number()),
+ archived: t.Boolean(),
+});
+
+// The kinds a relation is stored under (IssueLinkKind in links.ts).
+export const StoredLinkKind = t.Union([
+ t.Literal('blocks'),
+ t.Literal('relates'),
+ t.Literal('duplicates'),
+]);
+
+// IssueLinkRow from links.ts: one relation to another issue, as the issue that owns
+// the relation reads it.
+export const IssueLinkResponse = t.Object({
+ id: t.Number(),
+ kind: StoredLinkKind,
+ direction: t.Union([t.Literal('outward'), t.Literal('inward')]),
+ issue: IssueRefResponse,
+});
+
+// A relation as one of its two issues reads it (IssueLinkInputKind in links.ts). A
+// caller states this kind on create, and a board issue carries it.
+export const IssueLinkKindSchema = t.Union(
+ [
+ t.Literal('blocks'),
+ t.Literal('blocked_by'),
+ t.Literal('relates'),
+ t.Literal('duplicates'),
+ t.Literal('duplicated_by'),
+ ],
+ {
+ description:
+ 'How one issue relates to the other: blocks, blocked_by, relates, duplicates, or duplicated_by.',
+ },
+);
+
+// BoardIssueLink from links.ts: one relation on the issue carrying it, with the
+// other end as an id.
+export const BoardIssueLinkResponse = t.Object({
+ id: t.Number(),
+ relation: IssueLinkKindSchema,
+ issueId: t.Number(),
+});
+
+// What a delete or an archive does with the issue's subtasks. The request must set it
+// when the issue has subtasks. The route ignores it when the issue has none.
+export const SubtaskModeSchema = t.Union(
+ [t.Literal('cascade'), t.Literal('detach'), t.Literal('reassign')],
+ {
+ description:
+ "What happens to the issue's subtasks: 'cascade' removes them with it, 'detach' turns them into ordinary issues, 'reassign' moves them to newParentId.",
+ },
+);
+
+export const NewParentIdSchema = t.Integer({
+ description: "Numeric id of the issue the subtasks move to. Required by 'reassign'.",
+});
+
+// IssueWatcherRow from watchers.ts: one member following the issue.
+export const IssueWatcherResponse = t.Object({
+ userId: t.String(),
+ name: t.String(),
+ image: t.Nullable(t.String()),
+});
+
+// ChecklistItemRow / ChecklistRow from checklists.ts.
+export const ChecklistItemResponse = t.Object({
+ id: t.Number(),
+ content: t.String(),
+ done: t.Boolean(),
+ position: t.Number(),
+});
+
+export const ChecklistResponse = t.Object({
+ id: t.Number(),
+ title: t.String(),
+ position: t.Number(),
+ items: t.Array(ChecklistItemResponse),
+});
+
+export const ChecklistTitleSchema = t.String({
+ minLength: 1,
+ maxLength: 200,
+ description: 'Title of the checklist.',
+});
+
+export const ChecklistItemContentSchema = t.String({
+ minLength: 1,
+ maxLength: 500,
+ description: 'Text of the checklist item.',
+});
+
+// A reorder sends the ids in their new order. The route ignores an id outside the
+// parent in the path. An id the caller omits keeps its position after the listed ones.
+export const OrderedIdsSchema = t.Object({
+ orderedIds: t.Array(t.Integer(), { minItems: 1 }),
+});
+
+export const checklistParams = t.Object({ checklistId: t.Numeric() });
+export const checklistItemParams = t.Object({ itemId: t.Numeric() });
+
+// GET /issues/:issueId returns the full issue plus its custom field values, its
+// relations to other issues, the members watching it, and its checklists.
+export const IssueWithFieldsResponse = t.Composite([
+ IssueResponse,
+ t.Object({
+ fields: t.Array(IssueFieldValueRow),
+ links: t.Array(IssueLinkResponse),
+ watchers: t.Array(IssueWatcherResponse),
+ parent: t.Nullable(IssueRefResponse),
+ subtasks: t.Array(IssueRefResponse),
+ checklists: t.Array(ChecklistResponse),
+ }),
+]);
+
+// The board carries each issue's relations on the issue itself.
+export const BoardIssueResponse = t.Composite([
+ IssueResponse,
+ t.Object({
+ links: t.Array(BoardIssueLinkResponse),
+ // How many subtasks the issue has, archived ones included — the board lists
+ // only active issues, so it cannot count them from the payload itself.
+ subtaskCount: t.Number(),
+ }),
+]);
+
+// IssueSearchHit from the service: a light search result. It carries no description
+// and no field values.
+export const IssueSearchHitResponse = t.Object({
+ id: t.Number(),
+ sequenceNumber: t.Number(),
+ identifier: t.String(),
+ title: t.String(),
+ columnId: t.Number(),
+ typeId: t.Nullable(t.Number()),
+ initiativeId: t.Nullable(t.Number()),
+ cycleId: t.Nullable(t.Number()),
+ parentId: t.Nullable(t.Number()),
+ assigneeUserId: t.Nullable(t.String()),
+ delegateUserId: t.Nullable(t.String()),
+ priority: t.Nullable(t.String()),
+ dueDate: t.Nullable(t.String()),
+ labelIds: t.Array(t.Number()),
+ archived: t.Boolean(),
+});
+
+// FeedItemRow from activity.ts: one timeline entry (comment or change-log).
+// kind is the FeedKind union (a string).
+export const FeedItemResponse = t.Object({
+ id: t.Number(),
+ issueId: t.Number(),
+ kind: t.String(),
+ replyToId: t.Nullable(t.Number()),
+ actorUserId: t.Nullable(t.String()),
+ actorName: t.Nullable(t.String()),
+ body: t.Nullable(t.String()),
+ action: t.Nullable(t.String()),
+ subject: t.Nullable(t.String()),
+ fromText: t.Nullable(t.String()),
+ toText: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const FeedCursorResponse = t.Nullable(t.Object({ ts: t.String(), id: t.Number() }));
+
+// FeedPage from activity.ts: one page of the feed with the keyset cursor.
+export const FeedPageResponse = t.Object({
+ items: t.Array(FeedItemResponse),
+ nextCursor: FeedCursorResponse,
+});
+
+// GroupedFeedPage from activity.ts: the same page, split into the stretches the issue
+// spent in one column.
+export const GroupedFeedPageResponse = t.Object({
+ groups: t.Array(
+ t.Object({
+ status: t.Nullable(t.String()),
+ from: t.String(),
+ to: t.Nullable(t.String()),
+ durationMs: t.Number(),
+ repeat: t.Boolean(),
+ items: t.Array(FeedItemResponse),
+ }),
+ ),
+ nextCursor: FeedCursorResponse,
+});
+
+// Both feed routes page the same way: a limit and the previous page's cursor.
+export const feedPageQuery = t.Object({
+ limit: t.Optional(t.Numeric({ description: 'Max items per page (1-100). Default 25.' })),
+ cursor: t.Optional(t.String({ description: 'nextCursor from the previous page, for paging.' })),
+});
+
+// TimelineSegment from activity.ts: one stretch the issue spent in a column.
+export const TimelineSegmentResponse = t.Object({
+ status: t.Nullable(t.String()),
+ from: t.String(),
+ to: t.Nullable(t.String()),
+ durationMs: t.Number(),
+});
+
+// --- Request schemas -------------------------------------------------------------
+
+export const projectKeyParams = t.Object({ projectKey: t.String() });
+
+export const createIssueBody = t.Object({
+ typeId: t.Optional(
+ t.Nullable(t.Integer({ description: 'Issue type id, or null. From get_project.' })),
+ ),
+ initiativeId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description: 'Initiative id to link this issue to, or null. From list_initiatives.',
+ }),
+ ),
+ ),
+ cycleId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Cycle id to plan this issue into, or null. From list_cycles; a completed cycle is rejected.',
+ }),
+ ),
+ ),
+ assigneeUserId: t.Optional(
+ t.Nullable(
+ t.String({
+ description:
+ "Assignee user id (a project member), or null. From get_project.assignees where kind is 'member'.",
+ }),
+ ),
+ ),
+ delegateUserId: t.Optional(
+ t.Nullable(
+ t.String({
+ description:
+ "Delegate user id (an AI agent), or null. From get_project.assignees where kind is 'agent'.",
+ }),
+ ),
+ ),
+ columnId: t.Integer({ description: 'Target column (state) id. From get_project.columns.' }),
+ parentId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Numeric id of the issue this one is a subtask of, or null. The parent must be in this project and must not be a subtask itself.',
+ }),
+ ),
+ ),
+ title: t.String({ minLength: 1, description: 'Issue title.' }),
+ description: t.Optional(t.String({ description: 'Issue description (plain text or markdown).' })),
+ priority: t.Optional(
+ t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
+ ),
+ startDate: t.Optional(t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." }))),
+ dueDate: t.Optional(t.Nullable(t.String({ description: "Due date 'YYYY-MM-DD', or null." }))),
+ labelIds: t.Optional(
+ t.Array(t.Integer(), { description: 'Label ids to attach. From get_project.labels.' }),
+ ),
+});
+
+export const bulkUpdateIssuesBody = t.Object({
+ ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to update.' }),
+ patch: t.Object({
+ columnId: t.Optional(t.Integer()),
+ typeId: t.Optional(t.Nullable(t.Integer())),
+ initiativeId: t.Optional(t.Nullable(t.Integer())),
+ cycleId: t.Optional(t.Nullable(t.Integer())),
+ assigneeUserId: t.Optional(t.Nullable(t.String())),
+ delegateUserId: t.Optional(t.Nullable(t.String())),
+ priority: t.Optional(t.Nullable(t.String())),
+ startDate: t.Optional(t.Nullable(t.String())),
+ dueDate: t.Optional(t.Nullable(t.String())),
+ }),
+});
+
+export const bulkAddLabelsBody = t.Object({
+ ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to label.' }),
+ add: t.Array(t.Integer(), { minItems: 1, description: 'Label ids to add.' }),
+});
+
+export const bulkArchiveIssuesBody = t.Object({
+ ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to archive.' }),
+ subtasks: t.Optional(SubtaskModeSchema),
+ newParentId: t.Optional(NewParentIdSchema),
+});
+
+export const bulkDeleteIssuesBody = t.Object({
+ ids: t.Array(t.Integer(), { minItems: 1, description: 'Issue ids to delete.' }),
+ subtasks: t.Optional(SubtaskModeSchema),
+ newParentId: t.Optional(NewParentIdSchema),
+});
+
+export const searchIssuesQuery = t.Object({
+ q: t.Optional(
+ t.String({
+ description:
+ 'Case-insensitive substring, matched against the title, description, issue number, and custom field text.',
+ }),
+ ),
+ limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
+});
+
+export const listIssuesQuery = t.Object({
+ columnId: t.Optional(t.Numeric({ description: 'Exact column (state) id.' })),
+ typeId: t.Optional(t.Numeric({ description: 'Exact issue type id.' })),
+ initiativeId: t.Optional(t.Numeric({ description: 'Exact initiative id.' })),
+ cycleId: t.Optional(t.Numeric({ description: 'Exact cycle id.' })),
+ parentId: t.Optional(
+ t.Numeric({ description: 'Parent issue id, to list that issue’s subtasks.' }),
+ ),
+ assigneeUserId: t.Optional(t.String({ description: 'Exact assignee user id.' })),
+ delegateUserId: t.Optional(t.String({ description: 'Exact delegate agent id.' })),
+ priority: t.Optional(t.String({ description: 'Exact priority value.' })),
+ labelIds: t.Optional(t.String({ description: 'CSV of label ids; the issue must carry all.' })),
+ dueFrom: t.Optional(t.String({ description: "Inclusive earliest due date 'YYYY-MM-DD'." })),
+ dueTo: t.Optional(t.String({ description: "Inclusive latest due date 'YYYY-MM-DD'." })),
+ includeArchived: t.Optional(
+ t.String({ description: "'true' to include archived issues. Default false." }),
+ ),
+ limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
+});
+
+export const issueSequenceParams = t.Object({
+ projectKey: t.String(),
+ sequenceNumber: t.Numeric(),
+});
+
+export const updateIssueBody = t.Object({
+ columnId: t.Optional(t.Integer({ description: 'Move the issue to this column (state) id.' })),
+ position: t.Optional(t.Number({ description: 'Ordering position within the column.' })),
+ typeId: t.Optional(t.Nullable(t.Integer({ description: 'New issue type id, or null.' }))),
+ parentId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Make this issue a subtask of that issue id, or null to detach it. The parent must be in this project and must not be a subtask itself; an issue that has subtasks cannot become one.',
+ }),
+ ),
+ ),
+ initiativeId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Link this issue to an initiative id, or null to unlink. From list_initiatives.',
+ }),
+ ),
+ ),
+ cycleId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Plan this issue into a cycle id, or null to unplan it. From list_cycles; a completed cycle is rejected.',
+ }),
+ ),
+ ),
+ assigneeUserId: t.Optional(
+ t.Nullable(t.String({ description: 'New assignee user id (a project member), or null.' })),
+ ),
+ delegateUserId: t.Optional(
+ t.Nullable(t.String({ description: 'New delegate user id (an AI agent), or null.' })),
+ ),
+ title: t.Optional(t.String({ minLength: 1, description: 'New title.' })),
+ description: t.Optional(t.String({ description: 'New description.' })),
+ priority: t.Optional(
+ t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
+ ),
+ startDate: t.Optional(t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." }))),
+ dueDate: t.Optional(t.Nullable(t.String({ description: "Due date 'YYYY-MM-DD', or null." }))),
+ labelIds: t.Optional(
+ t.Array(t.Integer(), { description: "Replace the issue's labels with these ids." }),
+ ),
+});
+
+export const subtaskDispositionQuery = t.Object({
+ subtasks: t.Optional(SubtaskModeSchema),
+ newParentId: t.Optional(t.Numeric(NewParentIdSchema)),
+});
+
+export const setIssueFieldValueBody = t.Object({
+ value: t.Optional(t.Nullable(t.Union([t.String(), t.Number(), t.Boolean()]))),
+ valueEnd: t.Optional(t.Nullable(t.String())),
+ optionIds: t.Optional(t.Array(t.Integer())),
+});
+
+export const issueFieldParams = t.Object({ issueId: t.Numeric(), fieldId: t.Numeric() });
+
+export const addIssueLinkBody = t.Object({
+ targetIssueId: t.Integer({
+ description: 'Numeric id of the issue on the other end of the relation.',
+ }),
+ kind: IssueLinkKindSchema,
+});
+
+export const issueLinkParams = t.Object({ issueId: t.Numeric(), linkId: t.Numeric() });
+
+export const checklistTitleBody = t.Object({ title: ChecklistTitleSchema });
+
+export const createChecklistItemBody = t.Object({ content: ChecklistItemContentSchema });
+
+export const updateChecklistItemBody = t.Object({
+ content: t.Optional(ChecklistItemContentSchema),
+ done: t.Optional(t.Boolean({ description: 'Whether the item is checked off.' })),
+});
+
+export const feedRangeQuery = t.Object({
+ from: t.String({ description: 'Start of the stretch (ISO datetime), inclusive.' }),
+ to: t.Optional(
+ t.String({ description: 'End of the stretch (ISO datetime), exclusive. Open-ended.' }),
+ ),
+});
+
+export const createCommentBody = t.Object({
+ body: t.String({ minLength: 1, description: 'Comment text.' }),
+ replyToId: t.Optional(t.Number({ description: 'Reply to this comment of the same issue.' })),
+});
+
+export const archiveIssueBody = t.Optional(
+ t.Object({
+ subtasks: t.Optional(SubtaskModeSchema),
+ newParentId: t.Optional(NewParentIdSchema),
+ }),
+);
+
+export const BulkUpdatedResponse = t.Object({ updated: t.Number() });
+
+export const BulkArchivedResponse = t.Object({ archived: t.Number() });
+
+export const BulkDeletedResponse = t.Object({ deleted: t.Number() });
+
+export const BoardResponse = t.Object({ issues: t.Array(BoardIssueResponse) });
+
+export const WatchStateResponse = t.Object({ ok: t.Boolean() });
diff --git a/apps/api/src/issues/store.ts b/apps/api/src/modules/issues/service.ts
similarity index 99%
rename from apps/api/src/issues/store.ts
rename to apps/api/src/modules/issues/service.ts
index 038acc2c..8b13434c 100644
--- a/apps/api/src/issues/store.ts
+++ b/apps/api/src/modules/issues/service.ts
@@ -32,7 +32,7 @@ import {
type SQL,
} from 'drizzle-orm';
import type { IssueQuery } from '#modules/agents/core/issue-query';
-import { iso, num, HttpError } from '../shared/lib';
+import { iso, num, HttpError } from '#shared/lib';
import type { ProjectRow } from '#modules/projects/service';
import {
getCustomFieldById,
@@ -54,7 +54,7 @@ import {
import { autoWatchIssue } from './watchers';
import { mapAttachment, type AttachmentRow } from '#modules/attachments/service';
import { notifyIssueChange, notifyTextMentions } from '#modules/notifications/service';
-import { emitWebhookEvent } from '../webhooks/emit';
+import { emitWebhookEvent } from '#modules/webhooks/emit';
import {
getAssignTriggerAgent,
getFieldTriggerAgent,
diff --git a/apps/api/src/issues/subtasks.ts b/apps/api/src/modules/issues/subtasks.ts
similarity index 98%
rename from apps/api/src/issues/subtasks.ts
rename to apps/api/src/modules/issues/subtasks.ts
index 19d457b2..cf3743cd 100644
--- a/apps/api/src/issues/subtasks.ts
+++ b/apps/api/src/modules/issues/subtasks.ts
@@ -1,12 +1,12 @@
import { db, issue, project as projectTable } from '@repo/db';
import { and, eq, inArray, sql, type SQL } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
-import { HttpError } from '../shared/lib';
-import { archiveIssue, deleteIssue, restoreIssue, updateIssue } from './store';
+import { HttpError } from '#shared/lib';
+import { archiveIssue, deleteIssue, restoreIssue, updateIssue } from './service';
import type { AttachmentRow } from '#modules/attachments/service';
// An issue's subtasks: issues carrying its id in parent_id. The hierarchy is one
-// level deep (see assertParent in store.ts), so a subtask has no subtasks of its
+// level deep (see assertParent in service.ts), so a subtask has no subtasks of its
// own and every issue is either a parent, a subtask, or neither.
// A subtask or a parent as the issue page renders it: enough to name the issue and
diff --git a/apps/api/src/issues/watchers.ts b/apps/api/src/modules/issues/watchers.ts
similarity index 100%
rename from apps/api/src/issues/watchers.ts
rename to apps/api/src/modules/issues/watchers.ts
diff --git a/apps/api/src/modules/members/index.ts b/apps/api/src/modules/members/index.ts
index c2af9ca2..f124a737 100644
--- a/apps/api/src/modules/members/index.ts
+++ b/apps/api/src/modules/members/index.ts
@@ -6,7 +6,7 @@ import { guards } from '#shared/guards';
import { assertPermission, requireUser } from '#shared/access';
import { HttpError } from '#shared/lib';
import { accessErrors, commonErrors } from '#shared/responses';
-import { getRole } from '../../roles/store';
+import { getRole } from '#modules/roles/service';
import {
MemberListResponse,
memberParams,
diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.ts
index c10868d8..20b15718 100644
--- a/apps/api/src/modules/notifications/outbound.ts
+++ b/apps/api/src/modules/notifications/outbound.ts
@@ -3,7 +3,7 @@ import { eq, inArray } from 'drizzle-orm';
import { getProjectEmailConfig } from '@repo/auth';
import { emailSource, readRedactedSettings } from '#modules/notification-settings/service';
import { getPreferencesForUsers } from '#modules/notification-preferences/service';
-import { getTelegramChatIds, hasUsableInstanceBot } from '../../telegram/store';
+import { getTelegramChatIds, hasUsableInstanceBot } from '#modules/telegram/service';
import { escapeHtml } from '#shared/lib';
import type { NotificationType, NewNotificationRow } from './service';
diff --git a/apps/api/src/modules/notifications/send.ts b/apps/api/src/modules/notifications/send.ts
index 1f2279e9..c65ca156 100644
--- a/apps/api/src/modules/notifications/send.ts
+++ b/apps/api/src/modules/notifications/send.ts
@@ -2,7 +2,7 @@ import { sendEmail, emailBody, type EmailConfig, type SendResult } from '@repo/m
import { getProjectEmailConfig } from '@repo/auth';
import { emailSource, type NotificationConfig } from '#modules/notification-settings/service';
import type { DeliveryPayload } from './outbound';
-import { getInstanceBotConfig, isInstanceBotUsable } from '../../telegram/store';
+import { getInstanceBotConfig, isInstanceBotUsable } from '#modules/telegram/service';
// Sends one composed notification over the requested channel using the project's
// decrypted config. Email transport lives in @repo/mailer (shared with the
diff --git a/apps/api/src/modules/notifications/service.ts b/apps/api/src/modules/notifications/service.ts
index 889fe058..1eddc670 100644
--- a/apps/api/src/modules/notifications/service.ts
+++ b/apps/api/src/modules/notifications/service.ts
@@ -10,13 +10,13 @@ import {
} from '@repo/db';
import { and, desc, eq, inArray, lt, or, sql, isNull } from 'drizzle-orm';
import { addedMentionHandles, resolveMentionHandles, type MentionedUsers } from '#shared/mentions';
-import { autoWatchIssue, watcherUserIds } from '../../issues/watchers';
+import { autoWatchIssue, watcherUserIds } from '#modules/issues/watchers';
import { iso } from '#shared/lib';
import { enqueueOutbound } from './outbound';
// Inbox notifications. A notification is one (recipient, event) row: a user is told
// about an issue they are involved in. What happens on the issue ('commented',
-// 'state_changed') goes to its watchers (issue_watcher, see issues/watchers.ts);
+// 'state_changed') goes to its watchers (issue_watcher, see modules/issues/watchers.ts);
// what is addressed to one person ('assigned', 'mentioned') goes to them whether
// they watch the issue or not, and subscribes them to it. The actor is never
// notified about their own action, and only project members receive notifications,
diff --git a/apps/api/src/modules/projects/model.ts b/apps/api/src/modules/projects/model.ts
index c741d5d5..206e11ed 100644
--- a/apps/api/src/modules/projects/model.ts
+++ b/apps/api/src/modules/projects/model.ts
@@ -3,6 +3,7 @@ import { ColumnResponse } from '#modules/columns/model';
import { CustomFieldResponse } from '#modules/custom-fields/model';
import { IssueTypeResponse } from '#modules/issue-types/model';
import { LabelGroupResponse, LabelResponse } from '#modules/labels/model';
+import { PermissionMatrixSchema } from '#shared/permissions';
import { ISSUE_TYPE_PRESET_KEYS } from './service';
import { COPY_INCLUDE_KEYS } from './copy';
@@ -70,10 +71,6 @@ export const ProjectResponse = t.Object({
createdAt: t.String(),
});
-// The permission matrix as resolved for a member: for each resource, the
-// create/edit/read/delete flags.
-const PermissionMatrix = t.Record(t.String(), t.Record(t.String(), t.Boolean()));
-
// A project in the caller's list (ProjectListItem): ProjectRow plus the caller's
// own role in it, and the caller's permission matrix when requested with
// ?permissions=true.
@@ -82,7 +79,7 @@ export const ProjectListResponse = t.Array(
ProjectResponse,
t.Object({
role: t.Union([t.Literal('owner'), t.Literal('member')]),
- permissions: t.Optional(PermissionMatrix),
+ permissions: t.Optional(PermissionMatrixSchema),
}),
]),
);
@@ -120,7 +117,7 @@ export const ProjectBoardResponse = t.Object({
customFields: t.Array(CustomFieldResponse),
viewer: ViewerResponse,
// The caller's resolved permission matrix (owners get every flag).
- permissions: PermissionMatrix,
+ permissions: PermissionMatrixSchema,
});
// Which optional sections the project shows (ProjectFeatures from the service).
diff --git a/apps/api/src/modules/projects/service.ts b/apps/api/src/modules/projects/service.ts
index 7481a7f0..3b2b50c5 100644
--- a/apps/api/src/modules/projects/service.ts
+++ b/apps/api/src/modules/projects/service.ts
@@ -15,7 +15,7 @@ import {
normalizePermissions,
type Permissions,
} from '#shared/permissions';
-import { getProjectSetting, setProjectSetting } from '../../settings/store';
+import { getProjectSetting, setProjectSetting } from '#shared/project-settings';
import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';
// Data access for projects: the top-level container that groups its own columns,
@@ -376,7 +376,7 @@ export async function setAutoArchiveSettings(
// completeParent moves a parent into the column of its last closed subtask once
// every subtask is closed; closeSubtasks moves the still-open subtasks of an issue
// into the column the issue was closed in. Both off unless a project turns them on:
-// they rewrite states nobody asked to change. Applied in issues/automation.ts.
+// they rewrite states nobody asked to change. Applied in modules/issues/automation.ts.
const SUBTASK_AUTOMATION_KEY = 'subtask_automation';
export interface SubtaskAutomationSettings {
diff --git a/apps/api/src/roles/__tests__/integration/roles.test.ts b/apps/api/src/modules/roles/__tests__/integration/roles.test.ts
similarity index 98%
rename from apps/api/src/roles/__tests__/integration/roles.test.ts
rename to apps/api/src/modules/roles/__tests__/integration/roles.test.ts
index 033ac79e..9d6d6d67 100644
--- a/apps/api/src/roles/__tests__/integration/roles.test.ts
+++ b/apps/api/src/modules/roles/__tests__/integration/roles.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { api, authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser, type TestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { PERMISSION_RESOURCES, PERMISSION_ACTIONS } from '../../../shared/permissions';
+import { api, authedApi } from '#tests/helpers/app';
+import { signUpTestUser, type TestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { PERMISSION_RESOURCES, PERMISSION_ACTIONS } from '#shared/permissions';
// Integration coverage for the roles feature: the static permission catalog,
// listing a project's roles (any member), and creating, updating, and deleting a
diff --git a/apps/api/src/roles/routes.ts b/apps/api/src/modules/roles/index.ts
similarity index 57%
rename from apps/api/src/roles/routes.ts
rename to apps/api/src/modules/roles/index.ts
index a213e171..5a107411 100644
--- a/apps/api/src/roles/routes.ts
+++ b/apps/api/src/modules/roles/index.ts
@@ -1,37 +1,19 @@
import { Elysia, t } from 'elysia';
-import { mcpTool } from '../mcp/generate';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { HttpError, rethrowDuplicate } from '../shared/lib';
-import { PERMISSION_RESOURCES, PERMISSION_ACTIONS } from '../shared/permissions';
-import { accessErrors, commonErrors, errors } from '../shared/responses';
-import { listRoles, getRole, createRole, updateRole, deleteRole } from './store';
-
-const roleParams = t.Object({ projectKey: t.String(), roleId: t.Numeric() });
-
-// Permission matrix carried on create/update. Kept loose (a jsonb blob) and
-// sanitized by normalizePermissions in the store: unknown keys are dropped,
-// values coerced to booleans, missing entries defaulted to false.
-const permissions = t.Any();
-
-// The permission matrix as returned: for each resource, the create/edit/read/
-// delete flags. normalizePermissions always fills every resource and action.
-const PermissionMatrix = t.Record(t.String(), t.Record(t.String(), t.Boolean()));
-
-// A role DTO (RoleRow from the store).
-const RoleResponse = t.Object({
- id: t.Number(),
- name: t.String(),
- isDefault: t.Boolean(),
- permissions: PermissionMatrix,
- createdAt: t.String(),
-});
-
-// The catalog of resources and actions a role's matrix is built from.
-const PermissionCatalogResponse = t.Object({
- resources: t.Array(t.String()),
- actions: t.Array(t.String()),
-});
+import { mcpTool } from '#mcp/generate';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { HttpError, rethrowDuplicate } from '#shared/lib';
+import { PERMISSION_RESOURCES, PERMISSION_ACTIONS } from '#shared/permissions';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { listRoles, getRole, createRole, updateRole, deleteRole } from './service';
+import {
+ PermissionCatalogResponse,
+ RoleResponse,
+ createRoleBody,
+ projectKeyParams,
+ roleParams,
+ updateRoleBody,
+} from './model';
// Roles CRUD. Listing is open to any member; creating, editing, and deleting a
// role are owner-only. Role management is deliberately not delegated through the
@@ -40,8 +22,7 @@ const PermissionCatalogResponse = t.Object({
export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles'] } })
.use(guards)
- // The catalog of resources and actions a role's permission matrix is built
- // from. Static; any authenticated user may read it to render a role editor.
+ // Static; any authenticated user may read it to render a role editor.
.get(
'/permission-catalog',
() => ({ resources: [...PERMISSION_RESOURCES], actions: [...PERMISSION_ACTIONS] }),
@@ -55,18 +36,12 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
},
)
- .get(
- '/projects/:projectKey/roles',
- async ({ project }) => {
- return listRoles(project.id);
- },
- {
- params: t.Object({ projectKey: t.String() }),
- projectMember: true,
- response: { 200: t.Array(RoleResponse), ...accessErrors },
- detail: { summary: "List a project's roles", ...mcpTool('list_roles') },
- },
- )
+ .get('/projects/:projectKey/roles', ({ project }) => listRoles(project.id), {
+ params: projectKeyParams,
+ projectMember: true,
+ response: { 200: t.Array(RoleResponse), ...accessErrors },
+ detail: { summary: "List a project's roles", ...mcpTool('list_roles') },
+ })
.post(
'/projects/:projectKey/roles',
@@ -79,8 +54,8 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
}
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({ name: t.String({ minLength: 1 }), permissions }),
+ params: projectKeyParams,
+ body: createRoleBody,
projectOwner: true,
response: { 201: RoleResponse, ...commonErrors, ...errors(409) },
detail: { summary: 'Create a role', ...mcpTool('create_role') },
@@ -101,10 +76,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
},
{
params: roleParams,
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- permissions: t.Optional(permissions),
- }),
+ body: updateRoleBody,
projectOwner: true,
response: { 200: RoleResponse, ...commonErrors, ...errors(409) },
detail: {
diff --git a/apps/api/src/modules/roles/model.ts b/apps/api/src/modules/roles/model.ts
new file mode 100644
index 00000000..3ba73f9d
--- /dev/null
+++ b/apps/api/src/modules/roles/model.ts
@@ -0,0 +1,35 @@
+import { t } from 'elysia';
+import { PermissionMatrixSchema } from '#shared/permissions';
+
+export const projectKeyParams = t.Object({ projectKey: t.String() });
+
+export const roleParams = t.Object({ projectKey: t.String(), roleId: t.Numeric() });
+
+// Permission matrix carried on create/update. Kept loose (a jsonb blob) and
+// sanitized by normalizePermissions in the service: unknown keys are dropped,
+// values coerced to booleans, missing entries defaulted to false.
+const permissions = t.Any();
+
+export const createRoleBody = t.Object({
+ name: t.String({ minLength: 1 }),
+ permissions,
+});
+
+export const updateRoleBody = t.Object({
+ name: t.Optional(t.String({ minLength: 1 })),
+ permissions: t.Optional(permissions),
+});
+
+// A role DTO (RoleRow from the service).
+export const RoleResponse = t.Object({
+ id: t.Number(),
+ name: t.String(),
+ isDefault: t.Boolean(),
+ permissions: PermissionMatrixSchema,
+ createdAt: t.String(),
+});
+
+export const PermissionCatalogResponse = t.Object({
+ resources: t.Array(t.String()),
+ actions: t.Array(t.String()),
+});
diff --git a/apps/api/src/roles/store.ts b/apps/api/src/modules/roles/service.ts
similarity index 96%
rename from apps/api/src/roles/store.ts
rename to apps/api/src/modules/roles/service.ts
index 4ff4054b..5d3cb311 100644
--- a/apps/api/src/roles/store.ts
+++ b/apps/api/src/modules/roles/service.ts
@@ -1,7 +1,7 @@
import { db, projectRole, projectMember } from '@repo/db';
import { and, asc, eq } from 'drizzle-orm';
-import { iso } from '../shared/lib';
-import { normalizePermissions, type Permissions } from '../shared/permissions';
+import { iso } from '#shared/lib';
+import { normalizePermissions, type Permissions } from '#shared/permissions';
// Data access for project roles: the per-project permission matrices assigned to
// members. Owners bypass roles. Exactly one role per project is the default
diff --git a/apps/api/src/settings/__tests__/unit/updates.test.ts b/apps/api/src/modules/settings/__tests__/unit/updates.test.ts
similarity index 100%
rename from apps/api/src/settings/__tests__/unit/updates.test.ts
rename to apps/api/src/modules/settings/__tests__/unit/updates.test.ts
diff --git a/apps/api/src/settings/routes.ts b/apps/api/src/modules/settings/index.ts
similarity index 82%
rename from apps/api/src/settings/routes.ts
rename to apps/api/src/modules/settings/index.ts
index a71e0cec..03c4a400 100644
--- a/apps/api/src/settings/routes.ts
+++ b/apps/api/src/modules/settings/index.ts
@@ -1,9 +1,9 @@
-import { Elysia, t } from 'elysia';
-import { authContext } from '../shared/auth-context';
-import { errors } from '../shared/responses';
-import { getStorageSettings, StorageSettingsSchema } from './storage';
-import { getHotkeySettings, HotkeyCombosSchema } from './hotkeys';
+import { Elysia } from 'elysia';
+import { authContext } from '#shared/auth-context';
+import { errors } from '#shared/responses';
+import { getStorageSettings, getHotkeySettings } from './service';
import { getAppVersion } from './updates';
+import { HotkeyCombosSchema, StorageSettingsSchema, VersionResponse } from './model';
// Routes for global instance settings (app_setting): a key-value store not scoped
// to a project. The MCP toggle is per-project (see modules/projects), not here.
@@ -37,7 +37,7 @@ export const settingsRoutes = new Elysia({
// required: the version tells an anonymous visitor which release to look up
// vulnerabilities for.
.get('/settings/version', () => ({ version: getAppVersion() }), {
- response: { 200: t.Object({ version: t.String() }), ...errors(401) },
+ response: { 200: VersionResponse, ...errors(401) },
detail: {
summary: 'Get the running version',
description: 'Get the version of the app this instance runs.',
diff --git a/apps/api/src/modules/settings/model.ts b/apps/api/src/modules/settings/model.ts
new file mode 100644
index 00000000..7f519f4f
--- /dev/null
+++ b/apps/api/src/modules/settings/model.ts
@@ -0,0 +1,35 @@
+import { t } from 'elysia';
+
+export const StorageSettingsSchema = t.Object({
+ maxAttachmentMb: t.Number(),
+ maxAvatarMb: t.Number(),
+ attachmentMimeTypes: t.Array(t.String()),
+ projectQuotaMb: t.Number(),
+});
+
+// A command id bound to a combination written as modifier tokens plus a key
+// ('mod+k', 'n'). The set of commands lives in the web app (its lib/hotkeys), so
+// the API checks the shape and stores the map as given.
+export const HotkeyCombosSchema = t.Record(
+ t.String({ pattern: '^[a-z][a-z0-9.-]{0,63}$' }),
+ t.String({ pattern: '^(mod\\+|shift\\+|alt\\+)*[a-z0-9]{1,10}$' }),
+);
+
+const ReleaseSchema = t.Object({
+ tag: t.String(),
+ version: t.String(),
+ publishedAt: t.String(),
+ url: t.Nullable(t.String()),
+ notes: t.String(),
+ notesFormat: t.UnionEnum(['html', 'markdown']),
+});
+
+export const UpdateStatusSchema = t.Object({
+ currentVersion: t.String(),
+ latestVersion: t.Nullable(t.String()),
+ updateAvailable: t.Boolean(),
+ checkedAt: t.Nullable(t.String()),
+ releases: t.Array(ReleaseSchema),
+});
+
+export const VersionResponse = t.Object({ version: t.String() });
diff --git a/apps/api/src/settings/storage.ts b/apps/api/src/modules/settings/service.ts
similarity index 77%
rename from apps/api/src/settings/storage.ts
rename to apps/api/src/modules/settings/service.ts
index 8c3fd9a6..dce83b22 100644
--- a/apps/api/src/settings/storage.ts
+++ b/apps/api/src/modules/settings/service.ts
@@ -1,6 +1,8 @@
-import { t } from 'elysia';
import { getSetting, setSetting } from '@repo/db';
+// The instance settings kept in app_setting: the upload limits and the keyboard
+// shortcuts.
+
// Instance-wide upload limits (app_setting key 'storage'). They apply to every
// upload path in the api and are read by the web app before a file is picked, so
// the limit is visible in the UI instead of only surfacing as a 413.
@@ -27,14 +29,6 @@ export interface StorageSettings {
projectQuotaMb: number;
}
-// Served by GET /settings/storage (any signed-in user) and the god routes.
-export const StorageSettingsSchema = t.Object({
- maxAttachmentMb: t.Number(),
- maxAvatarMb: t.Number(),
- attachmentMimeTypes: t.Array(t.String()),
- projectQuotaMb: t.Number(),
-});
-
// Images, video, PDF, office documents and plain text formats. Executables,
// archives and anything else are refused until an admin adds them.
const DEFAULT_ATTACHMENT_MIME_TYPES = [
@@ -92,3 +86,23 @@ export function mimeAllowed(contentType: string, allowed: string[]): boolean {
pattern.endsWith('/*') ? ct.startsWith(pattern.slice(0, -1)) : ct === pattern,
);
}
+
+// The instance keyboard shortcuts (app_setting key 'hotkeys'): the combination
+// each command is bound to for everyone on this instance. Only the bindings
+// changed in god mode are stored; the web app fills the rest from its built-in
+// defaults, then applies the user's own overrides on top (user_preference.hotkeys).
+
+const HOTKEYS_SETTING_KEY = 'hotkeys';
+
+export type HotkeyCombos = Record<string, string>;
+
+export async function getHotkeySettings(): Promise<HotkeyCombos> {
+ return (await getSetting<HotkeyCombos>(HOTKEYS_SETTING_KEY)) ?? {};
+}
+
+// Replaces the stored map. The god screen sends the full set of overrides, so an
+// unbound command is one left out rather than one written as empty.
+export async function setHotkeySettings(combos: HotkeyCombos): Promise<HotkeyCombos> {
+ await setSetting(HOTKEYS_SETTING_KEY, combos);
+ return combos;
+}
diff --git a/apps/api/src/settings/updates.ts b/apps/api/src/modules/settings/updates.ts
similarity index 90%
rename from apps/api/src/settings/updates.ts
rename to apps/api/src/modules/settings/updates.ts
index 42d07ac4..efea59ff 100644
--- a/apps/api/src/settings/updates.ts
+++ b/apps/api/src/modules/settings/updates.ts
@@ -1,5 +1,4 @@
-import { t } from 'elysia';
-import pkg from '../../../../package.json';
+import pkg from '../../../../../package.json';
// Whether a newer release is published, plus the notes to show. The repository's
// releases atom feed is the source of the history; the CHANGELOG.md of this build
@@ -7,7 +6,8 @@ import pkg from '../../../../package.json';
// cannot be read.
//
// The feed is github.com web content, not the REST API, so no token and no
-// 60/hour limit (agent-skills/skill-format.ts reads github.com atom the same way).
+// 60/hour limit (modules/agents/skills/skill-format.ts reads github.com atom the
+// same way).
// The result is not stored on the server: every read fetches the feed, and the
// browser holds it behind a stale time (web services/updates.service.ts).
// A failed check leaves the local history intact.
@@ -18,7 +18,7 @@ const FETCH_TIMEOUT_MS = 10_000;
// configure.
const FEED_URL = 'https://github.com/croffasia/itsaplan/releases.atom';
-const CHANGELOG_PATH = `${import.meta.dir}/../../../../CHANGELOG.md`;
+const CHANGELOG_PATH = `${import.meta.dir}/../../../../../CHANGELOG.md`;
export interface Release {
tag: string;
@@ -42,23 +42,6 @@ export interface UpdateStatus {
releases: Release[];
}
-const ReleaseSchema = t.Object({
- tag: t.String(),
- version: t.String(),
- publishedAt: t.String(),
- url: t.Nullable(t.String()),
- notes: t.String(),
- notesFormat: t.UnionEnum(['html', 'markdown']),
-});
-
-export const UpdateStatusSchema = t.Object({
- currentVersion: t.String(),
- latestVersion: t.Nullable(t.String()),
- updateAvailable: t.Boolean(),
- checkedAt: t.Nullable(t.String()),
- releases: t.Array(ReleaseSchema),
-});
-
export function getAppVersion(): string {
return pkg.version;
}
diff --git a/apps/api/src/modules/share/index.ts b/apps/api/src/modules/share/index.ts
index a55c0db7..ce0dc18f 100644
--- a/apps/api/src/modules/share/index.ts
+++ b/apps/api/src/modules/share/index.ts
@@ -4,8 +4,8 @@ import { guards, entityGuard } from '#shared/guards';
import { authContext } from '#shared/auth-context';
import { HttpError } from '#shared/lib';
import { commonErrors, errors } from '#shared/responses';
-import { getIssueProjectId } from '../../issues/store';
-import { getView } from '../../views/store';
+import { getIssueProjectId } from '#modules/issues/service';
+import { getView } from '#modules/views/service';
import {
BundleResponse,
ShareTokenResponse,
diff --git a/apps/api/src/modules/share/service.ts b/apps/api/src/modules/share/service.ts
index c6743c36..8a896b36 100644
--- a/apps/api/src/modules/share/service.ts
+++ b/apps/api/src/modules/share/service.ts
@@ -7,16 +7,16 @@ import { listIssueTypes } from '#modules/issue-types/service';
import { listLabels, listLabelGroups } from '#modules/labels/service';
import { listCustomFields } from '#modules/custom-fields/service';
import { listAssigneeCandidates } from '#modules/members/service';
-import { getIssue, getIssueFieldValues, listIssues, type IssueRow } from '../../issues/store';
-import { listFeed, type FeedItemRow } from '../../issues/activity';
+import { getIssue, getIssueFieldValues, listIssues, type IssueRow } from '#modules/issues/service';
+import { listFeed, type FeedItemRow } from '#modules/issues/activity';
import {
attachBoardLinks,
listIssueLinks,
type BoardIssueLink,
type IssueLinkRow,
-} from '../../issues/links';
-import { getParentRef, listSubtasks, type IssueRef } from '../../issues/subtasks';
-import { applyFilters } from '../../views/filters';
+} from '#modules/issues/links';
+import { getParentRef, listSubtasks, type IssueRef } from '#modules/issues/subtasks';
+import { applyFilters } from '#modules/views/filters';
// Public read-only sharing: an issue or a saved view carries an unguessable
// share_token that, when set, makes it readable without a session through the
diff --git a/apps/api/src/sync/__tests__/integration/sync.test.ts b/apps/api/src/modules/sync/__tests__/integration/sync.test.ts
similarity index 98%
rename from apps/api/src/sync/__tests__/integration/sync.test.ts
rename to apps/api/src/modules/sync/__tests__/integration/sync.test.ts
index ca0dc5b6..232c9029 100644
--- a/apps/api/src/sync/__tests__/integration/sync.test.ts
+++ b/apps/api/src/modules/sync/__tests__/integration/sync.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { api, authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { api, authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// GET /sync/rev is the one poll behind live refresh: it answers with the change
// marker of every scope a client watches. The markers are written by database
diff --git a/apps/api/src/sync/routes.ts b/apps/api/src/modules/sync/index.ts
similarity index 79%
rename from apps/api/src/sync/routes.ts
rename to apps/api/src/modules/sync/index.ts
index 176718bd..f4e2cda1 100644
--- a/apps/api/src/sync/routes.ts
+++ b/apps/api/src/modules/sync/index.ts
@@ -1,9 +1,10 @@
-import { Elysia, t } from 'elysia';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { errors } from '../shared/responses';
-import { NO_REV, readRevs, scopeKind, type ScopeRead } from './store';
+import { Elysia } from 'elysia';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { errors } from '#shared/responses';
+import { NO_REV, readRevs, scopeKind, type ScopeRead } from './service';
+import { RevResponse, revQuery } from './model';
const MAX_SCOPES = 20;
@@ -48,13 +49,8 @@ export const syncRoutes = new Elysia({ name: 'sync', detail: { tags: ['Sync'] }
};
},
{
- query: t.Object({
- scopes: t.String({
- description:
- "Comma-separated scopes to read, each '<kind>:<id>' — board, issue, initiative, or inbox (by project id).",
- }),
- }),
- response: { 200: t.Object({ revs: t.Record(t.String(), t.String()) }), ...errors(400, 401) },
+ query: revQuery,
+ response: { 200: RevResponse, ...errors(400, 401) },
detail: {
summary: 'Get change markers',
description:
diff --git a/apps/api/src/modules/sync/model.ts b/apps/api/src/modules/sync/model.ts
new file mode 100644
index 00000000..867d3f3a
--- /dev/null
+++ b/apps/api/src/modules/sync/model.ts
@@ -0,0 +1,10 @@
+import { t } from 'elysia';
+
+export const revQuery = t.Object({
+ scopes: t.String({
+ description:
+ "Comma-separated scopes to read, each '<kind>:<id>' — board, issue, initiative, or inbox (by project id).",
+ }),
+});
+
+export const RevResponse = t.Object({ revs: t.Record(t.String(), t.String()) });
diff --git a/apps/api/src/sync/store.ts b/apps/api/src/modules/sync/service.ts
similarity index 97%
rename from apps/api/src/sync/store.ts
rename to apps/api/src/modules/sync/service.ts
index 3c0ebfb7..37393ccc 100644
--- a/apps/api/src/sync/store.ts
+++ b/apps/api/src/modules/sync/service.ts
@@ -1,7 +1,7 @@
import { db, projectMember, projectRole, revision } from '@repo/db';
import { and, eq, inArray } from 'drizzle-orm';
import { toMemberContext, type MemberRole } from '#modules/members/service';
-import { hasPermission, type PermissionResource } from '../shared/permissions';
+import { hasPermission, type PermissionResource } from '#shared/permissions';
// The revision engine's read side. The counters themselves are written by the
// triggers in migration 0070 — no application code bumps them, so a write moves
diff --git a/apps/api/src/telegram/routes.ts b/apps/api/src/modules/telegram/index.ts
similarity index 80%
rename from apps/api/src/telegram/routes.ts
rename to apps/api/src/modules/telegram/index.ts
index 23f42d8c..fa2f38e1 100644
--- a/apps/api/src/telegram/routes.ts
+++ b/apps/api/src/modules/telegram/index.ts
@@ -1,16 +1,17 @@
import { Elysia, t } from 'elysia';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { errors } from '../shared/responses';
-import { noContent } from '../shared/http';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { errors } from '#shared/responses';
+import { noContent } from '#shared/http';
+import { TelegramAccountResponse, TelegramLinkStartResponse } from './model';
import {
getInstanceBotConfig,
getTelegramLink,
isInstanceBotUsable,
startTelegramLink,
unlinkTelegram,
-} from './store';
+} from './service';
// The session user's own Telegram account link. Linking runs through the instance
// bot: this mints a one-time code and returns the deep link that opens the bot with
@@ -20,22 +21,6 @@ import {
// `botUsername` is null when no instance bot is configured, which is how the UI
// knows not to offer Telegram at all.
-const TelegramAccountResponse = t.Object({
- botUsername: t.Nullable(t.String()),
- link: t.Nullable(
- t.Object({
- username: t.Nullable(t.String()),
- firstName: t.Nullable(t.String()),
- linkedAt: t.String(),
- }),
- ),
-});
-
-const TelegramLinkStartResponse = t.Object({
- url: t.String(),
- expiresAt: t.String(),
-});
-
export const telegramRoutes = new Elysia({ name: 'telegram', detail: { tags: ['Telegram'] } })
.use(authContext)
diff --git a/apps/api/src/telegram/internal-routes.ts b/apps/api/src/modules/telegram/internal-routes.ts
similarity index 88%
rename from apps/api/src/telegram/internal-routes.ts
rename to apps/api/src/modules/telegram/internal-routes.ts
index 2d9feca2..e5a57b66 100644
--- a/apps/api/src/telegram/internal-routes.ts
+++ b/apps/api/src/modules/telegram/internal-routes.ts
@@ -1,5 +1,6 @@
-import { Elysia, t } from 'elysia';
-import { confirmTelegramLink, getInstanceBotConfig, isInstanceBotUsable } from './store';
+import { Elysia } from 'elysia';
+import { confirmLinkBody } from './model';
+import { confirmTelegramLink, getInstanceBotConfig, isInstanceBotUsable } from './service';
// Internal endpoints the bot service calls. The bot holds no database connection and
// no encryption key: it asks for its token here and posts back the `/start` codes it
@@ -10,13 +11,6 @@ import { confirmTelegramLink, getInstanceBotConfig, isInstanceBotUsable } from '
// The config endpoint returns the bot token in plaintext. It is reachable only with
// that token, on the internal network, and the bot cannot work without it.
-const linkBody = t.Object({
- code: t.String({ minLength: 1, maxLength: 64 }),
- chatId: t.String({ minLength: 1, maxLength: 128 }),
- username: t.Nullable(t.String()),
- firstName: t.Nullable(t.String()),
-});
-
function authorized(headers: Record<string, string | undefined>): boolean {
const expected = process.env.WORKER_INTERNAL_TOKEN;
return Boolean(expected) && headers['x-worker-token'] === expected;
@@ -59,7 +53,7 @@ export const internalTelegramRoutes = new Elysia({
return confirmTelegramLink(body);
},
{
- body: linkBody,
+ body: confirmLinkBody,
detail: {
summary: 'Confirm a Telegram link code',
description:
diff --git a/apps/api/src/modules/telegram/model.ts b/apps/api/src/modules/telegram/model.ts
new file mode 100644
index 00000000..ac1f7f0c
--- /dev/null
+++ b/apps/api/src/modules/telegram/model.ts
@@ -0,0 +1,24 @@
+import { t } from 'elysia';
+
+export const TelegramAccountResponse = t.Object({
+ botUsername: t.Nullable(t.String()),
+ link: t.Nullable(
+ t.Object({
+ username: t.Nullable(t.String()),
+ firstName: t.Nullable(t.String()),
+ linkedAt: t.String(),
+ }),
+ ),
+});
+
+export const TelegramLinkStartResponse = t.Object({
+ url: t.String(),
+ expiresAt: t.String(),
+});
+
+export const confirmLinkBody = t.Object({
+ code: t.String({ minLength: 1, maxLength: 64 }),
+ chatId: t.String({ minLength: 1, maxLength: 128 }),
+ username: t.Nullable(t.String()),
+ firstName: t.Nullable(t.String()),
+});
diff --git a/apps/api/src/telegram/store.ts b/apps/api/src/modules/telegram/service.ts
similarity index 100%
rename from apps/api/src/telegram/store.ts
rename to apps/api/src/modules/telegram/service.ts
diff --git a/apps/api/src/modules/user-preferences/model.ts b/apps/api/src/modules/user-preferences/model.ts
index 43175930..83fdc218 100644
--- a/apps/api/src/modules/user-preferences/model.ts
+++ b/apps/api/src/modules/user-preferences/model.ts
@@ -1,5 +1,5 @@
import { t } from 'elysia';
-import { HotkeyCombosSchema } from '../../settings/hotkeys';
+import { HotkeyCombosSchema } from '#modules/settings/model';
const Locale = t.Union([
t.Literal('en'),
diff --git a/apps/api/src/views/__tests__/integration/views.test.ts b/apps/api/src/modules/views/__tests__/integration/views.test.ts
similarity index 95%
rename from apps/api/src/views/__tests__/integration/views.test.ts
rename to apps/api/src/modules/views/__tests__/integration/views.test.ts
index 9758a6ce..5e39ff4f 100644
--- a/apps/api/src/views/__tests__/integration/views.test.ts
+++ b/apps/api/src/modules/views/__tests__/integration/views.test.ts
@@ -1,13 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-
-// Saved views are the tabs above a project's work items view. List and create are
-// project-scoped (/projects/:projectKey/views), reorder is project-scoped, but
-// patch and delete address a view by its own id (/views/:viewId) and resolve the
-// owning project through the savedView guard. filters/display are jsonb blobs the
-// store keeps verbatim; icon is nullable; position orders the tabs, first is 0.
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
async function setupOwnerProject() {
const owner = await signUpTestUser();
diff --git a/apps/api/src/views/filters.ts b/apps/api/src/modules/views/filters.ts
similarity index 95%
rename from apps/api/src/views/filters.ts
rename to apps/api/src/modules/views/filters.ts
index de546310..095678de 100644
--- a/apps/api/src/views/filters.ts
+++ b/apps/api/src/modules/views/filters.ts
@@ -1,4 +1,4 @@
-import type { IssueRow } from '../issues/store';
+import type { IssueRow } from '#modules/issues/service';
import type { ColumnRow } from '#modules/columns/service';
// Server-side copy of the view filter engine. The web app (utils/filters.ts) stores
@@ -57,7 +57,6 @@ function isEffectiveCondition(cond: FilterCondition): boolean {
return cond.values.length > 0;
}
-// Coerces the persisted jsonb into a FilterSet, dropping anything malformed.
function toFilterSet(raw: unknown): FilterSet {
if (!raw || typeof raw !== 'object') return { conditions: [] };
const conditions = (raw as { conditions?: unknown }).conditions;
@@ -170,7 +169,6 @@ function matchCondition(
return cond.op === 'contains' ? has : !has;
}
- // is / is_not — set membership.
const issueValues =
cfId != null
? customFieldValues(issue, cfId)
@@ -179,8 +177,6 @@ function matchCondition(
return cond.op === 'is' ? overlaps : !overlaps;
}
-// The issues that satisfy every effective condition. An empty or all-empty set
-// returns the input unchanged.
export function applyFilters(
issues: IssueRow[],
rawFilters: unknown,
diff --git a/apps/api/src/views/routes.ts b/apps/api/src/modules/views/index.ts
similarity index 70%
rename from apps/api/src/views/routes.ts
rename to apps/api/src/modules/views/index.ts
index 30282a58..6145e591 100644
--- a/apps/api/src/views/routes.ts
+++ b/apps/api/src/modules/views/index.ts
@@ -1,11 +1,18 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { accessErrors, commonErrors } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
+import {
+ ViewResponse,
+ createViewBody,
+ reorderViewsBody,
+ updateViewBody,
+ viewParams,
+} from './model';
import {
listViews,
createView,
@@ -16,32 +23,11 @@ import {
isFavoriteView,
addFavoriteView,
removeFavoriteView,
-} from './store';
-
-const viewParams = t.Object({ viewId: t.Numeric() });
-
-// A saved view DTO (ViewRow from the store). filters and display are jsonb blobs
-// owned by the UI, returned as-is (t.Any()).
-const ViewResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- icon: t.Nullable(t.String()),
- filters: t.Any(),
- display: t.Any(),
- position: t.Number(),
- shareToken: t.Nullable(t.String()),
- shareExtended: t.Boolean(),
- // Personal to the caller, not shared with the other project members.
- favorite: t.Boolean(),
- createdAt: t.String(),
-});
+} from './service';
export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views'] } })
.use(authContext)
.use(guards)
- // Guard for routes that address a view by its own id (no :projectKey in the
- // path). Set `savedView: "<action>"` in the route options.
.macro({
savedView: entityGuard(
'views',
@@ -72,12 +58,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
return { ...(await createView({ projectId: project.id, ...body })), favorite: false };
},
{
- body: t.Object({
- name: t.String({ minLength: 1 }),
- icon: t.Optional(t.Nullable(t.String())),
- filters: t.Optional(t.Any()),
- display: t.Optional(t.Any()),
- }),
+ body: createViewBody,
permission: ['views', 'create'],
response: { 201: ViewResponse, ...commonErrors },
detail: {
@@ -88,14 +69,13 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
},
)
- // Sets the tab order to orderedIds.
.put(
'/projects/:projectKey/views/reorder',
async ({ project, body, user }) => {
return reorderViews(project.id, body.orderedIds, requireUser(user).id);
},
{
- body: t.Object({ orderedIds: t.Array(t.Integer(), { minItems: 1 }) }),
+ body: reorderViewsBody,
permission: ['views', 'edit'],
response: { 200: t.Array(ViewResponse), ...commonErrors },
detail: {
@@ -114,12 +94,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
return { ...view, favorite: await isFavoriteView(view.id, requireUser(user).id) };
},
{
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- icon: t.Optional(t.Nullable(t.String())),
- filters: t.Optional(t.Any()),
- display: t.Optional(t.Any()),
- }),
+ body: updateViewBody,
params: viewParams,
savedView: 'edit',
response: { 200: ViewResponse, ...commonErrors },
diff --git a/apps/api/src/modules/views/model.ts b/apps/api/src/modules/views/model.ts
new file mode 100644
index 00000000..38dcce3a
--- /dev/null
+++ b/apps/api/src/modules/views/model.ts
@@ -0,0 +1,30 @@
+import { t } from 'elysia';
+
+export const viewParams = t.Object({ viewId: t.Numeric() });
+
+export const createViewBody = t.Object({
+ name: t.String({ minLength: 1 }),
+ icon: t.Optional(t.Nullable(t.String())),
+ filters: t.Optional(t.Any()),
+ display: t.Optional(t.Any()),
+});
+
+export const updateViewBody = t.Partial(createViewBody);
+
+export const reorderViewsBody = t.Object({
+ orderedIds: t.Array(t.Integer(), { minItems: 1 }),
+});
+
+export const ViewResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ icon: t.Nullable(t.String()),
+ filters: t.Any(),
+ display: t.Any(),
+ position: t.Number(),
+ shareToken: t.Nullable(t.String()),
+ shareExtended: t.Boolean(),
+ favorite: t.Boolean(),
+ createdAt: t.String(),
+});
diff --git a/apps/api/src/views/store.ts b/apps/api/src/modules/views/service.ts
similarity index 85%
rename from apps/api/src/views/store.ts
rename to apps/api/src/modules/views/service.ts
index 9ebaac36..67a9a8c7 100644
--- a/apps/api/src/views/store.ts
+++ b/apps/api/src/modules/views/service.ts
@@ -1,10 +1,6 @@
import { db, projectView, projectViewFavorite } from '@repo/db';
import { and, eq, sql } from 'drizzle-orm';
-import { iso, num } from '../shared/lib';
-
-// Saved views: the tabs above a project's work items view. filters and display are jsonb
-// blobs owned by the UI; this layer stores and returns them without inspecting
-// their shape. position orders the tabs.
+import { iso, num } from '#shared/lib';
export interface ViewRow {
id: number;
@@ -39,7 +35,6 @@ function mapView(row: typeof projectView.$inferSelect): ViewRow {
};
}
-// A view as one user sees it: the favorite flag is personal.
export interface UserViewRow extends ViewRow {
favorite: boolean;
}
@@ -78,8 +73,6 @@ export async function removeFavoriteView(viewId: number, userId: string): Promis
.where(and(eq(projectViewFavorite.viewId, viewId), eq(projectViewFavorite.userId, userId)));
}
-// New views go to the end of the tab row (max position + 1). filters/display are
-// stored verbatim in the jsonb columns.
export async function createView(input: {
projectId: number;
name: string;
@@ -110,8 +103,6 @@ export async function getView(id: number): Promise<ViewRow | null> {
return rows[0] ? mapView(rows[0]) : null;
}
-// Updates only the provided fields. filters/display are replaced wholesale (not
-// merged), since the UI always sends the full blob.
export async function updateView(
id: number,
patch: { name?: string; icon?: string | null; filters?: unknown; display?: unknown },
@@ -130,8 +121,6 @@ export async function deleteView(id: number): Promise<void> {
await db.delete(projectView).where(eq(projectView.id, id));
}
-// Sets each view's position to its index in orderedIds, in one transaction, so
-// the tab order the UI sends is stored exactly. Ids not on the project are ignored.
export async function reorderViews(
projectId: number,
orderedIds: number[],
diff --git a/apps/api/src/webhooks/__tests__/integration/webhooks.test.ts b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts
similarity index 98%
rename from apps/api/src/webhooks/__tests__/integration/webhooks.test.ts
rename to apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts
index a7c38eb4..37aff0f2 100644
--- a/apps/api/src/webhooks/__tests__/integration/webhooks.test.ts
+++ b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import type { WebhookEventType } from '../../store';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import type { WebhookEventType } from '../../service';
async function setupOwnerProject() {
const owner = await signUpTestUser();
diff --git a/apps/api/src/webhooks/emit.ts b/apps/api/src/modules/webhooks/emit.ts
similarity index 61%
rename from apps/api/src/webhooks/emit.ts
rename to apps/api/src/modules/webhooks/emit.ts
index 6cba6085..45f2b365 100644
--- a/apps/api/src/webhooks/emit.ts
+++ b/apps/api/src/modules/webhooks/emit.ts
@@ -1,13 +1,13 @@
import { randomUUID } from 'node:crypto';
import { db, webhook, webhookDelivery } from '@repo/db';
import { and, eq, sql } from 'drizzle-orm';
-import type { WebhookEventType } from './store';
+import type { WebhookEventType } from './service';
// Maps our granular event type to the Linear-style envelope's action + resource
-// type. action is create | update | remove; type is the PascalCase resource.
-// Linear's action/type pair cannot distinguish our assigned / state_changed /
-// label_changed variants (all of them are an issue update), so the granular event
-// is kept in the payload's `event` field.
+// type. action is create | update | remove. type is the PascalCase resource.
+// Linear's action/type pair cannot distinguish our assigned, state_changed, and
+// label_changed variants, because all of them are an issue update. The payload keeps
+// the granular event in its own `event` field.
const EVENT_SHAPE: Record<WebhookEventType, { action: string; type: string }> = {
'issue.created': { action: 'create', type: 'Issue' },
'issue.updated': { action: 'update', type: 'Issue' },
@@ -19,18 +19,18 @@ const EVENT_SHAPE: Record<WebhookEventType, { action: string; type: string }> =
'comment.created': { action: 'create', type: 'Comment' },
};
-// Fan-out for outgoing webhooks: queues one delivery per active webhook of the
-// project that is subscribed to eventType, all sharing a single eventId (stable
-// across retries so receivers can deduplicate). Called right after a domain
-// mutation, next to the activity log, following the same post-write side-effect
-// pattern the issue store already uses. No-op when no webhook matches, so it costs
-// one indexed SELECT on projects with no webhooks.
+// Fan-out for outgoing webhooks. Queues one delivery per active webhook of the
+// project that subscribes to eventType. The deliveries share one eventId, which stays
+// the same across retries so a receiver can deduplicate. Call it right after a domain
+// mutation, next to the activity log, the same way the issue service handles its other
+// post-write side effects. It does nothing when no webhook matches, so a project with
+// no webhooks pays one indexed SELECT.
//
// The body follows Linear's webhook envelope: top-level action, type, data, plus
-// createdAt and webhookTimestamp (epoch ms). `event` is our extension carrying the
-// granular event type. organizationId and url are omitted (there is no organization
-// concept, and issues have no public URL). The shared dedup id rides on the wire in
-// the X-Itsaplan-Event-Id header, not the body.
+// createdAt and webhookTimestamp (epoch ms). `event` is our extension, and it carries
+// the granular event type. We omit organizationId and url, because there is no
+// organization concept and issues have no public URL. The shared dedup id goes in the
+// X-Itsaplan-Event-Id header, not in the body.
export async function emitWebhookEvent(
projectId: number,
eventType: WebhookEventType,
@@ -39,11 +39,11 @@ export async function emitWebhookEvent(
await emitWebhookEvents(projectId, eventType, () => Promise.resolve([data]));
}
-// Several events of one type at once, with the payloads assembled only once a
-// webhook turns out to be subscribed. For the writes whose payload costs its own
-// queries to build — linking two issues has to load both of them — so a project
-// with no webhook pays one indexed SELECT and nothing else. Each event gets its
-// own eventId; the deliveries go in as one insert.
+// Several events of one type at once. It builds the payloads only after it finds a
+// subscribed webhook. Use it for a write whose payload costs its own queries to
+// build: linking two issues has to load both of them. A project with no webhook then
+// pays one indexed SELECT and nothing else. Each event gets its own eventId. The
+// deliveries go in as one insert.
export async function emitWebhookEvents(
projectId: number,
eventType: WebhookEventType,
@@ -56,7 +56,7 @@ export async function emitWebhookEvents(
and(
eq(webhook.projectId, projectId),
eq(webhook.isActive, true),
- // events is a jsonb array of event-type strings; @> tests membership.
+ // events is a jsonb array of event-type strings. @> tests membership.
sql`${webhook.events} @> ${JSON.stringify([eventType])}::jsonb`,
),
);
diff --git a/apps/api/src/webhooks/routes.ts b/apps/api/src/modules/webhooks/index.ts
similarity index 61%
rename from apps/api/src/webhooks/routes.ts
rename to apps/api/src/modules/webhooks/index.ts
index 388b1f71..4e787842 100644
--- a/apps/api/src/webhooks/routes.ts
+++ b/apps/api/src/modules/webhooks/index.ts
@@ -1,56 +1,26 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { mcpTool } from '../mcp/generate';
-import { accessErrors, commonErrors } from '../shared/responses';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { mcpTool } from '#mcp/generate';
+import { accessErrors, commonErrors } from '#shared/responses';
+import {
+ WebhookDeliveryPageResponse,
+ WebhookResponse,
+ createWebhookBody,
+ listDeliveriesQuery,
+ updateWebhookBody,
+ webhookParams,
+} from './model';
import {
- WEBHOOK_EVENT_TYPES,
listWebhooks,
createWebhook,
getWebhook,
updateWebhook,
deleteWebhook,
listWebhookDeliveries,
-} from './store';
-
-const webhookParams = t.Object({ webhookId: t.Numeric() });
-
-const eventType = t.UnionEnum([...WEBHOOK_EVENT_TYPES]);
-const eventsSchema = t.Array(eventType, { minItems: 1 });
-
-// A webhook subscription DTO (WebhookRow from the store).
-const WebhookResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- url: t.String(),
- secret: t.String(),
- events: t.Array(eventType),
- isActive: t.Boolean(),
- createdAt: t.String(),
-});
-
-// A webhook delivery attempt DTO (WebhookDeliveryRow from the store).
-const WebhookDeliveryResponse = t.Object({
- id: t.Number(),
- eventId: t.String(),
- eventType: t.String(),
- status: t.String(),
- attempts: t.Number(),
- payload: t.Any(),
- responseStatus: t.Nullable(t.Number()),
- responseBody: t.Nullable(t.String()),
- lastError: t.Nullable(t.String()),
- nextAttemptAt: t.String(),
- createdAt: t.String(),
-});
-
-// One page of deliveries (WebhookDeliveryPage from the store).
-const WebhookDeliveryPageResponse = t.Object({
- items: t.Array(WebhookDeliveryResponse),
- nextCursor: t.Nullable(t.Number()),
-});
+} from './service';
// A local, loopback, or private-range host — the SSRF-sensitive targets.
function isLocalHost(host: string): boolean {
@@ -73,14 +43,13 @@ function isIpLiteral(host: string): boolean {
return /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(':');
}
-// Rejects urls that are not https or that point at a local/private address, so a
-// subscription cannot be pointed at internal services (SSRF). The DNS-level check
-// belongs to the delivery side; this is the syntactic guard at registration time.
+// Rejects a url that is not https, or that targets a local or private address. This
+// stops a subscription from reaching internal services (SSRF). The check is syntactic
+// and runs at registration time. The delivery side runs the DNS-level check.
//
-// Exception for local development (NODE_ENV neither production nor test): a
-// localhost / 0.0.0.0 / IP-literal target is allowed over http, so a local test
-// receiver (e.g. http://localhost:3000/webhook-test/sink) can be registered.
-// Production and the test suite stay strict.
+// Local development is the exception (NODE_ENV is neither production nor test): a
+// localhost, 0.0.0.0, or IP-literal target passes over http, so an operator can
+// register a local test receiver. Production and the test suite stay strict.
function validateWebhookUrl(raw: string): string {
let url: URL;
try {
@@ -108,8 +77,6 @@ function validateWebhookUrl(raw: string): string {
export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['Webhooks'] } })
.use(authContext)
.use(guards)
- // Guard for routes that address a webhook by its own id (no :projectKey in the
- // path). Set `webhook: "<action>"` in the route options.
.macro({
webhook: entityGuard(
'webhooks',
@@ -141,11 +108,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
});
},
{
- body: t.Object({
- url: t.String({ minLength: 1 }),
- events: eventsSchema,
- isActive: t.Optional(t.Boolean()),
- }),
+ body: createWebhookBody,
permission: ['webhooks', 'create'],
response: { 201: WebhookResponse, ...commonErrors },
detail: { summary: 'Create a webhook', ...mcpTool('create_webhook') },
@@ -164,11 +127,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
return updated;
},
{
- body: t.Object({
- url: t.Optional(t.String({ minLength: 1 })),
- events: t.Optional(eventsSchema),
- isActive: t.Optional(t.Boolean()),
- }),
+ body: updateWebhookBody,
params: webhookParams,
webhook: 'edit',
response: { 200: WebhookResponse, ...commonErrors },
@@ -197,10 +156,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
},
{
params: webhookParams,
- query: t.Object({
- before: t.Optional(t.Numeric()),
- limit: t.Optional(t.Numeric()),
- }),
+ query: listDeliveriesQuery,
webhook: 'read',
response: { 200: WebhookDeliveryPageResponse, ...commonErrors },
detail: {
diff --git a/apps/api/src/modules/webhooks/model.ts b/apps/api/src/modules/webhooks/model.ts
new file mode 100644
index 00000000..cd0fe3d7
--- /dev/null
+++ b/apps/api/src/modules/webhooks/model.ts
@@ -0,0 +1,48 @@
+import { t } from 'elysia';
+import { WEBHOOK_EVENT_TYPES } from './service';
+
+export const webhookParams = t.Object({ webhookId: t.Numeric() });
+
+const eventType = t.UnionEnum([...WEBHOOK_EVENT_TYPES]);
+
+export const createWebhookBody = t.Object({
+ url: t.String({ minLength: 1 }),
+ events: t.Array(eventType, { minItems: 1 }),
+ isActive: t.Optional(t.Boolean()),
+});
+
+export const updateWebhookBody = t.Partial(createWebhookBody);
+
+export const listDeliveriesQuery = t.Object({
+ before: t.Optional(t.Numeric()),
+ limit: t.Optional(t.Numeric()),
+});
+
+export const WebhookResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ url: t.String(),
+ secret: t.String(),
+ events: t.Array(eventType),
+ isActive: t.Boolean(),
+ createdAt: t.String(),
+});
+
+export const WebhookDeliveryResponse = t.Object({
+ id: t.Number(),
+ eventId: t.String(),
+ eventType: t.String(),
+ status: t.String(),
+ attempts: t.Number(),
+ payload: t.Any(),
+ responseStatus: t.Nullable(t.Number()),
+ responseBody: t.Nullable(t.String()),
+ lastError: t.Nullable(t.String()),
+ nextAttemptAt: t.String(),
+ createdAt: t.String(),
+});
+
+export const WebhookDeliveryPageResponse = t.Object({
+ items: t.Array(WebhookDeliveryResponse),
+ nextCursor: t.Nullable(t.Number()),
+});
diff --git a/apps/api/src/webhooks/store.ts b/apps/api/src/modules/webhooks/service.ts
similarity index 75%
rename from apps/api/src/webhooks/store.ts
rename to apps/api/src/modules/webhooks/service.ts
index 86028d37..8e5fec64 100644
--- a/apps/api/src/webhooks/store.ts
+++ b/apps/api/src/modules/webhooks/service.ts
@@ -1,21 +1,23 @@
import { randomBytes } from 'node:crypto';
import { db, webhook, webhookDelivery } from '@repo/db';
import { and, desc, eq, lt } from 'drizzle-orm';
-import { iso } from '../shared/lib';
+import { iso } from '#shared/lib';
-// Outgoing webhook subscriptions on a project. A subscription targets a `url`,
-// carries a per-subscription `secret` used to sign delivered payloads, and lists
-// the event types it wants. Delivery is handled separately; this layer only
-// stores and returns the subscription.
+// Outgoing webhook subscriptions on a project. A subscription targets a `url` and
+// lists the event types it wants. It carries its own `secret`, which signs the
+// payloads sent to that url. This layer only stores and returns the subscription.
+// The delivery side is separate.
-// The event types a subscription can listen to. Keep in sync with the events the
-// delivery side emits (issues/store.ts, issues/activity.ts, issues/links.ts) and
-// the frontend list (apps/web src/lib/api.ts). issue.updated fires on any field
-// change; the granular issue.assigned / issue.state_changed / issue.label_changed
-// fire in addition, only when that specific field changes on an existing issue.
-// issue.state_changed fires when the issue moves to a different state (column).
-// issue.link_changed fires for both issues of an added or removed relation, and
-// without issue.updated: no field of either issue changed.
+// The event types a subscription can select. Keep this list in sync with the events
+// the delivery side emits (modules/issues/service.ts, activity.ts, links.ts) and
+// with the frontend list (apps/web src/lib/api.ts).
+//
+// issue.updated fires on any field change. The granular issue.assigned,
+// issue.state_changed, and issue.label_changed fire in addition, and only when that
+// specific field changes on an existing issue. issue.state_changed fires when the
+// issue moves to a different state (column). issue.link_changed fires for both issues
+// of an added or removed relation, and without issue.updated: no field of either
+// issue changed.
export const WEBHOOK_EVENT_TYPES = [
'issue.created',
'issue.updated',
@@ -50,8 +52,8 @@ function mapWebhook(row: typeof webhook.$inferSelect): WebhookRow {
};
}
-// A signing secret for a new subscription. Shown to the client so it can verify
-// delivered payloads; generated server-side and never derived from user input.
+// A signing secret for a new subscription. The client gets it back so it can verify
+// delivered payloads. The server generates it, and never derives it from user input.
function generateSecret(): string {
return `whsec_${randomBytes(24).toString('hex')}`;
}
@@ -89,7 +91,7 @@ export async function getWebhook(id: number): Promise<WebhookRow | null> {
return rows[0] ? mapWebhook(rows[0]) : null;
}
-// Updates only the provided fields. The secret is not user-editable here.
+// Updates only the fields the patch provides. A caller cannot change the secret.
export async function updateWebhook(
id: number,
patch: { url?: string; events?: WebhookEventType[]; isActive?: boolean },
@@ -126,7 +128,7 @@ export interface WebhookDeliveryRow {
export interface WebhookDeliveryPage {
items: WebhookDeliveryRow[];
- // The id to pass as `before` to load the next page, or null when at the end.
+ // The id to pass as `before` to load the next page, or null on the last page.
nextCursor: number | null;
}
@@ -146,9 +148,9 @@ function mapDelivery(row: typeof webhookDelivery.$inferSelect): WebhookDeliveryR
};
}
-// One page of the webhook's deliveries, newest first. Keyset pagination by id
-// (deliveries are id-monotonic): pass the previous page's nextCursor as `before`
-// to get the next page. limit is clamped to 1..50.
+// One page of the webhook's deliveries, newest first. Keyset pagination by id, which
+// works because delivery ids only grow: pass the previous page's nextCursor as
+// `before` to get the next page. This clamps limit to 1..50.
export async function listWebhookDeliveries(
webhookId: number,
opts: { before?: number; limit?: number } = {},
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 0a77fc12..e3c9bb5c 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -3,7 +3,7 @@ import { HttpError, pgErrorCode } from './shared/lib';
import { authContext } from './shared/auth-context';
import { projectRoutes } from './modules/projects';
import { memberRoutes } from './modules/members';
-import { roleRoutes } from './roles/routes';
+import { roleRoutes } from './modules/roles';
import { inviteRoutes } from './modules/invites';
import { columnRoutes } from './modules/columns';
import { issueTypeRoutes } from './modules/issue-types';
@@ -13,22 +13,22 @@ import { integrationRoutes } from './modules/agents/integrations';
import { agentSkillRoutes } from './modules/agents/skills';
import { agentToolRoutes } from './modules/agents/tools';
import { customFieldRoutes } from './modules/custom-fields';
-import { issueRoutes } from './issues/routes';
+import { issueRoutes } from './modules/issues';
import { initiativeRoutes } from './modules/initiatives';
import { cycleRoutes } from './modules/cycles';
import { attachmentRoutes } from './modules/attachments';
import { avatarRoutes } from './modules/avatars';
-import { viewRoutes } from './views/routes';
+import { viewRoutes } from './modules/views';
import { shareRoutes } from './modules/share';
import { actionRoutes } from './modules/actions';
-import { webhookRoutes } from './webhooks/routes';
+import { webhookRoutes } from './modules/webhooks';
import { gitSettingsRoutes } from './modules/git';
import { dashboardRoutes } from './modules/dashboards';
import { noteBoardRoutes } from './modules/note-boards';
import { analyticsRoutes } from './modules/analytics';
import { chartRoutes } from './modules/charts';
-import { settingsRoutes } from './settings/routes';
-import { godRoutes } from './god/routes';
+import { settingsRoutes } from './modules/settings';
+import { godRoutes } from './modules/god';
import { agentScheduleRoutes } from './modules/agents/schedules';
import { agentRunnerRoutes } from './modules/agents/runner';
import { agentChatRoutes } from './modules/agents/chat';
@@ -36,8 +36,8 @@ import { notificationRoutes } from './modules/notifications';
import { notificationSettingsRoutes } from './modules/notification-settings';
import { notificationPreferenceRoutes } from './modules/notification-preferences';
import { userPreferenceRoutes } from './modules/user-preferences';
-import { telegramRoutes } from './telegram/routes';
-import { syncRoutes } from './sync/routes';
+import { telegramRoutes } from './modules/telegram';
+import { syncRoutes } from './modules/sync';
// The planner API: projects and their columns, issue types, labels, AI agents,
// custom fields, issues, attachments, saved views, and actions. Mounted on the
diff --git a/apps/api/src/settings/hotkeys.ts b/apps/api/src/settings/hotkeys.ts
deleted file mode 100644
index 9aa71617..00000000
--- a/apps/api/src/settings/hotkeys.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { t } from 'elysia';
-import { getSetting, setSetting } from '@repo/db';
-
-// The instance keyboard shortcuts (app_setting key 'hotkeys'): the combination
-// each command is bound to for everyone on this instance. Only the bindings
-// changed in god mode are stored; the web app fills the rest from its built-in
-// defaults, then applies the user's own overrides on top (user_preference.hotkeys).
-//
-// The set of commands lives in the web app (its lib/hotkeys), so the API stores the
-// map as given and only checks the shape: a command id and a combination written as
-// modifier tokens plus a key ('mod+k', 'n').
-
-const HOTKEYS_SETTING_KEY = 'hotkeys';
-
-export type HotkeyCombos = Record<string, string>;
-
-export const HotkeyCombosSchema = t.Record(
- t.String({ pattern: '^[a-z][a-z0-9.-]{0,63}$' }),
- t.String({ pattern: '^(mod\\+|shift\\+|alt\\+)*[a-z0-9]{1,10}$' }),
-);
-
-export async function getHotkeySettings(): Promise<HotkeyCombos> {
- return (await getSetting<HotkeyCombos>(HOTKEYS_SETTING_KEY)) ?? {};
-}
-
-// Replaces the stored map. The god screen sends the full set of overrides, so an
-// unbound command is one left out rather than one written as empty.
-export async function setHotkeySettings(combos: HotkeyCombos): Promise<HotkeyCombos> {
- await setSetting(HOTKEYS_SETTING_KEY, combos);
- return combos;
-}
diff --git a/apps/api/src/shared/lib.ts b/apps/api/src/shared/lib.ts
index 6a04279b..fb0ae3a7 100644
--- a/apps/api/src/shared/lib.ts
+++ b/apps/api/src/shared/lib.ts
@@ -1,8 +1,8 @@
// Shared helpers for the planner API (projects, issues, and their dependent
-// entities). Each feature folder holds a store.ts (Drizzle data access) and a
-// routes.ts (Elysia routes) that exposes it over HTTP.
+// entities). Each feature folder under modules/ holds a service.ts (Drizzle data
+// access) and an index.ts (Elysia routes) that exposes it over HTTP.
-// An error carrying an HTTP status. Thrown from stores and routes; the planner
+// An error carrying an HTTP status. Services and routes throw it. The planner
// plugin's onError maps it to a { error } JSON response with that status.
//
// `code` names the failure for a caller that has to branch on it rather than show
diff --git a/apps/api/src/shared/permissions.ts b/apps/api/src/shared/permissions.ts
index 9438d075..c936e835 100644
--- a/apps/api/src/shared/permissions.ts
+++ b/apps/api/src/shared/permissions.ts
@@ -1,3 +1,5 @@
+import { t } from 'elysia';
+
// Permission model for project roles. A role carries a matrix: for each resource
// the create/edit/read/delete flags. The matrix is stored as jsonb on
// project_role and enforced here and in shared/access.ts. Owners bypass the
@@ -33,6 +35,11 @@ export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
export type ResourcePermissions = Record<PermissionAction, boolean>;
export type Permissions = Record<PermissionResource, ResourcePermissions>;
+// The matrix as it crosses the API. Kept as an open record rather than a schema
+// per resource: normalizePermissions is what guarantees the keys, and pinning
+// them here would mean a schema change for every resource added.
+export const PermissionMatrixSchema = t.Record(t.String(), t.Record(t.String(), t.Boolean()));
+
function fill(value: boolean): ResourcePermissions {
return { create: value, edit: value, read: value, delete: value };
}
diff --git a/apps/api/src/settings/store.ts b/apps/api/src/shared/project-settings.ts
similarity index 100%
rename from apps/api/src/settings/store.ts
rename to apps/api/src/shared/project-settings.ts
diff --git a/apps/api/src/shared/s3.ts b/apps/api/src/shared/s3.ts
index a711b261..58a551fe 100644
--- a/apps/api/src/shared/s3.ts
+++ b/apps/api/src/shared/s3.ts
@@ -7,7 +7,7 @@ import {
// S3-compatible object store (MinIO) for issue attachments. Only the file
// bytes live here; the metadata and object key are rows in issue_attachment
-// (see ../attachments/store.ts).
+// (see modules/attachments/service.ts).
//
// Config comes from env. forcePathStyle is required for MinIO (and most
// self-hosted S3 gateways) because they do not serve virtual-host-style buckets;
@@ -49,7 +49,7 @@ export async function putObject(key: string, body: Buffer, contentType: string):
// Returns a web ReadableStream of the object body so a route can stream it to
// the client without buffering the whole file (matters for video). contentType
-// and contentLength fall back to sensible defaults when the store omits them.
+// and contentLength fall back to sensible defaults when the object store omits them.
export async function getObject(
key: string,
): Promise<{ body: ReadableStream; contentType: string; contentLength?: number }> {
diff --git a/apps/api/src/webhook-test/routes.ts b/apps/api/src/webhook-test/routes.ts
deleted file mode 100644
index e63a142d..00000000
--- a/apps/api/src/webhook-test/routes.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { Elysia, t } from 'elysia';
-
-// One recorded request as returned over HTTP (the in-memory Received entry).
-const ReceivedResponse = t.Object({
- at: t.String(),
- method: t.String(),
- headers: t.Record(t.String(), t.String()),
- body: t.Any(),
-});
-
-// Test receiver for webhooks — a dev aid, not part of the product API. Register
-// its URL as a webhook to see exactly what the delivery worker sends:
-// POST /webhook-test/sink records the request and echoes it back
-// GET /webhook-test/sink lists the most recent requests it received
-// DELETE /webhook-test/sink clears the log
-// Unauthenticated (a webhook sender carries no session). Stored in memory only,
-// bounded to the last MAX requests. Remove this route once real testing is done.
-
-interface Received {
- at: string;
- method: string;
- headers: Record<string, string>;
- body: unknown;
-}
-
-const MAX = 50;
-const log: Received[] = [];
-
-export const webhookTestRoutes = new Elysia({
- name: 'webhook-test',
- detail: { tags: ['Webhook test'] },
-})
- .post(
- '/webhook-test/sink',
- ({ request, body }) => {
- const entry: Received = {
- at: new Date().toISOString(),
- method: request.method,
- headers: Object.fromEntries(request.headers),
- body: body ?? null,
- };
- log.unshift(entry);
- if (log.length > MAX) log.length = MAX;
- // Echo back what arrived (the worker sees this as the delivery response).
- return { received: entry };
- },
- {
- response: { 200: t.Object({ received: ReceivedResponse }) },
- detail: {
- summary: 'Receive a test webhook',
- description: 'Receive a webhook and echo what arrived',
- },
- },
- )
- .get('/webhook-test/sink', () => ({ count: log.length, requests: log }), {
- response: { 200: t.Object({ count: t.Number(), requests: t.Array(ReceivedResponse) }) },
- detail: {
- summary: 'List test webhook deliveries',
- description: 'List the received webhook requests',
- },
- })
- .delete(
- '/webhook-test/sink',
- () => {
- log.length = 0;
- return { cleared: true };
- },
- {
- response: { 200: t.Object({ cleared: t.Boolean() }) },
- detail: {
- summary: 'Clear test webhook deliveries',
- description: 'Clear the received webhook log',
- },
- },
- );
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 3bfdb9ee..38396a56 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1486,7 +1486,7 @@ export interface ActionPatch {
effect?: ActionEffect;
}
-// Outgoing webhook subscription (mirrors apps/api webhooks/store.ts). The event
+// Outgoing webhook subscription (mirrors apps/api modules/webhooks/service.ts). The event
// types must stay in sync with WEBHOOK_EVENT_TYPES on the server.
export type WebhookEventType =
| 'issue.created'
@@ -1754,7 +1754,7 @@ export interface IssueDetail extends Issue {
fields: IssueFieldValue[];
}
-// A relation between two issues (mirrors apps/api issues/links.ts). 'blocks' and
+// A relation between two issues (mirrors apps/api modules/issues/links.ts). 'blocks' and
// 'duplicates' are directional and read differently on each end, which direction
// selects: 'outward' is the side that blocks/duplicates, 'inward' the side that is
// blocked/duplicated. On a symmetric 'relates' relation direction means nothing.