⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
refactor(api): restructure the api into feature modules (part 2) (#167)
Croff63d2f9caed4f
diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 38a17d22..021cc91e 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -13,7 +13,7 @@ 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 './notifications/internal-routes';+import { internalNotificationRoutes } from './modules/notifications/internal-routes';import { internalTelegramRoutes } from './telegram/internal-routes';import { githubWebhookRoutes } from './modules/github/webhook';diff --git a/apps/api/src/god/routes.ts b/apps/api/src/god/routes.tsindex b60c3ce7..03907876 100644--- a/apps/api/src/god/routes.ts+++ b/apps/api/src/god/routes.ts@@ -15,7 +15,7 @@ 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 '../projects/store';+import { deleteProject } from '#modules/projects/service';import {USER_KINDS,deleteInstanceUser,diff --git a/apps/api/src/issues/activity.ts b/apps/api/src/issues/activity.tsindex 9c8adb7a..2de5f47e 100644--- a/apps/api/src/issues/activity.ts+++ b/apps/api/src/issues/activity.ts@@ -15,7 +15,7 @@ import { emitWebhookEvent } from '../webhooks/emit';import { parseMentions } from '#modules/agents/core/mentions';import { isAgentUser, listMentionTriggerAgents } from '#modules/agents/core/service';import { enqueueAgentRun } from '#modules/agents/core/run-queue';-import { notifyComment, notifyIssueChange } from '../notifications/store';+import { notifyComment, notifyIssueChange } from '#modules/notifications/service';// Issue timeline: comments and change-log activity in one table (issue_activity).// kind selects which payload columns a row uses. The author is the session userdiff --git a/apps/api/src/issues/automation.ts b/apps/api/src/issues/automation.tsindex ca484262..380ff1dd 100644--- a/apps/api/src/issues/automation.ts+++ b/apps/api/src/issues/automation.ts@@ -1,13 +1,13 @@import { db, issue, projectColumn } from '@repo/db';import { and, eq, inArray, isNull } from 'drizzle-orm';-import { getSubtaskAutomationSettings } from '../projects/store';+import { getSubtaskAutomationSettings } from '#modules/projects/service';import { listSubtasks } from './subtasks';import { updateIssue, type IssueRow } from './store';import type { ActivityActor } from './activity';// The subtask automations a column change triggers, both off unless the project-// turns them on (projects/store.ts). A closed issue is one sitting in a column-// whose stateType is 'completed' or 'canceled'.+// turns them on (modules/projects/service.ts). A closed issue is one sitting in a+// column whose stateType is 'completed' or 'canceled'.//// The hierarchy is one level deep, so an issue is either a subtask or a parent and// only one of the two rules applies to it. Each rule writes through updateIssue, sodiff --git a/apps/api/src/issues/routes.ts b/apps/api/src/issues/routes.tsindex bff18100..7dddf55e 100644--- a/apps/api/src/issues/routes.ts+++ b/apps/api/src/issues/routes.ts@@ -5,7 +5,7 @@ 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 '../projects/store';+import { getProjectById } from '#modules/projects/service';import { HttpError } from '../shared/lib';import { accessErrors, commonErrors, errors } from '../shared/responses';import { deleteObject } from '../shared/s3';diff --git a/apps/api/src/issues/store.ts b/apps/api/src/issues/store.tsindex bb2034fb..bb0a1e72 100644--- a/apps/api/src/issues/store.ts+++ b/apps/api/src/issues/store.ts@@ -33,7 +33,7 @@ import {} from 'drizzle-orm';import type { IssueQuery } from '#modules/agents/core/issue-query';import { iso, num, HttpError } from '../shared/lib';-import type { ProjectRow } from '../projects/store';+import type { ProjectRow } from '#modules/projects/service';import { getCustomFieldById, type CustomFieldType } from '#modules/custom-fields/service';import {recordActivity,@@ -47,13 +47,13 @@ import {} from './activity';import { autoWatchIssue } from './watchers';import { mapAttachment, type AttachmentRow } from '#modules/attachments/service';-import { notifyIssueChange } from '../notifications/store';+import { notifyIssueChange } from '#modules/notifications/service';import { emitWebhookEvent } from '../webhooks/emit';import { getAssignTriggerAgent, isProjectAgent } from '#modules/agents/core/service';import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';import { getInitiativeProjectId } from '#modules/initiatives/service';import { cycleStatus, getCycleRef, type CycleStatus } from '#modules/cycles/service';-import { getMembership } from '../members/store';+import { getMembership } from '#modules/members/service';import { enqueueAgentRun } from '#modules/agents/core/run-queue';import { applySubtaskAutomation } from './automation';import { assertWipLimit, wipLimitBreach } from '#modules/columns/service';diff --git a/apps/api/src/issues/watchers.ts b/apps/api/src/issues/watchers.tsindex e17a52c9..704fefa6 100644--- a/apps/api/src/issues/watchers.ts+++ b/apps/api/src/issues/watchers.ts@@ -2,7 +2,7 @@ import { db, issueWatcher, projectMember, user, userPreference } from '@repo/db'import { and, asc, eq, inArray, isNull, or } from 'drizzle-orm';// Who follows an issue. A watcher receives every notification the issue produces-// (see notifications/store.ts); the assignment and mention notifications are+// (see modules/notifications/service.ts); the assignment and mention notifications are// addressed to one person and reach them whether they watch the issue or not.//// A member subscribes either by hand or through the auto-subscribe rules below.diff --git a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.tsindex 7c889bd7..de2c1475 100644--- a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts@@ -4,7 +4,7 @@ import { eq } from 'drizzle-orm';import { authedApi, type Api } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';-import { getProjectByKey } from '../../../../../projects/store';+import { getProjectByKey } from '#modules/projects/service';import { getAgentById, getInternalAgentApiKey } from '../../service';import { buildRouteTools } from '../../runtime/tools/route-tools';import { AGENT_ACTIONS, ALWAYS_ON_ACTIONS } from '../../runtime/tools/catalog';diff --git a/apps/api/src/modules/agents/core/runtime/index.ts b/apps/api/src/modules/agents/core/runtime/index.tsindex bbde8174..68f54519 100644--- a/apps/api/src/modules/agents/core/runtime/index.ts+++ b/apps/api/src/modules/agents/core/runtime/index.ts@@ -1,6 +1,6 @@import { Agent } from '@mastra/core/agent';import { getAgentById, getInternalAgentApiKey, type AiAgentRow } from '../service';-import { getProjectById } from '../../../../projects/store';+import { getProjectById } from '#modules/projects/service';import { getCredentialSecret } from '../../integrations/service';import { listAgentSkills } from '../../skills/service';import { listAgentToolsForRun } from '../../tools/service';diff --git a/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts b/apps/api/src/modules/agents/core/runtime/tools/route-tools.tsindex 2f693827..14a493fe 100644--- a/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts+++ b/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts@@ -1,6 +1,6 @@import { createTool } from '@mastra/core/tools';import type { z } from 'zod';-import type { ProjectRow } from '../../../../../projects/store';+import type { ProjectRow } from '#modules/projects/service';import { routeTools, type McpInputSchema, type McpRouteTool } from '#mcp/generate';import { dispatchTool } from '#mcp/dispatch';import { getMcpApp } from '#mcp/app-ref';diff --git a/apps/api/src/modules/custom-fields/service.ts b/apps/api/src/modules/custom-fields/service.tsindex 5d79a7e4..27f6d528 100644--- a/apps/api/src/modules/custom-fields/service.ts+++ b/apps/api/src/modules/custom-fields/service.ts@@ -1,7 +1,7 @@import { db, customField, customFieldOption } from '@repo/db';import { and, asc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm';import { HttpError } from '#shared/lib';-import { getIssueTypeById } from '../../issue-types/store';+import { getIssueTypeById } from '#modules/issue-types/service';// Data access for custom fields and their options. Every field belongs to a// project. A field with issue_type_id NULL is project-wide (applies to everydiff --git a/apps/api/src/modules/github/webhook.ts b/apps/api/src/modules/github/webhook.tsindex 3a5d8afd..2c51f538 100644--- a/apps/api/src/modules/github/webhook.ts+++ b/apps/api/src/modules/github/webhook.ts@@ -2,7 +2,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto';import { Elysia } from 'elysia';import { HttpError } from '#shared/lib';import { errors } from '#shared/responses';-import { getProjectById } from '../../projects/store';+import { getProjectById } from '#modules/projects/service';import { handlePullRequestEvent, type PullRequestPayload } from './handler';import { WebhookAckResponse, webhookBody, webhookParams } from './model';import { claimGithubDelivery, findProjectByGithubWebhookId, recordGithubEvent } from './service';diff --git a/apps/api/src/modules/initiatives/service.ts b/apps/api/src/modules/initiatives/service.tsindex 7355bf5d..ee721ebe 100644--- a/apps/api/src/modules/initiatives/service.ts+++ b/apps/api/src/modules/initiatives/service.ts@@ -1,7 +1,7 @@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 { getMembership } from '../../members/store';+import { getMembership } from '#modules/members/service';import { HttpError, iso, num } from '#shared/lib';import { computeHealth, type Health } from './health';import { recordActivity, logInitiativeUpdate, type InitiativeSnapshot } from './activity';diff --git a/apps/api/src/invites/__tests__/integration/invites.test.ts b/apps/api/src/modules/invites/__tests__/integration/invites.test.tssimilarity index 98%rename from apps/api/src/invites/__tests__/integration/invites.test.tsrename to apps/api/src/modules/invites/__tests__/integration/invites.test.tsindex 3fd56e20..d8fce128 100644--- a/apps/api/src/invites/__tests__/integration/invites.test.ts+++ b/apps/api/src/modules/invites/__tests__/integration/invites.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach } from 'bun:test';-import { authedApi } from '../../../__tests__/helpers/app';-import { signUpTestUser, type TestUser } from '../../../__tests__/helpers/auth';-import { resetDb } from '../../../__tests__/helpers/db';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser, type TestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';// Integration coverage for the invites feature: the owner-side routes that// create/list/revoke invites and the invitee-side routes that read, accept, ordiff --git a/apps/api/src/invites/routes.ts b/apps/api/src/modules/invites/index.tssimilarity index 58%rename from apps/api/src/invites/routes.tsrename to apps/api/src/modules/invites/index.tsindex 7f38af13..982f2a90 100644--- a/apps/api/src/invites/routes.ts+++ b/apps/api/src/modules/invites/index.ts@@ -1,12 +1,21 @@import { Elysia, t } from 'elysia';-import { mcpTool } from '../mcp/generate';-import { noContent } from '../shared/http';-import { authContext } from '../shared/auth-context';-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 { mcpTool } from '#mcp/generate';+import { noContent } from '#shared/http';+import { authContext } from '#shared/auth-context';+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 {+ AcceptInviteResponse,+ InviteRowListResponse,+ InviteRowResponse,+ InviteViewResponse,+ createInviteBody,+ inviteParams,+ tokenParams,+} from './model';import {createInvite,listInvites,@@ -15,56 +24,10 @@ import {getInviteRowByToken,acceptInvite,rejectInvite,-} from './store';--const inviteRole = t.Union([t.Literal('owner'), t.Literal('member')]);--// The token is a UUID column. Validating its format here turns a malformed token-// into a 400 instead of letting it reach Postgres and surface as a 500.-const tokenParams = t.Object({ token: t.String({ format: 'uuid' }) });--// An invite's lifecycle status.-const inviteStatus = t.Union([t.Literal('pending'), t.Literal('accepted'), t.Literal('rejected')]);--// The owner-facing invite row (InviteRow from the store).-const InviteRowResponse = t.Object({- id: t.Number(),- token: t.String(),- email: t.String(),- role: inviteRole,- roleId: t.Nullable(t.Number()),- roleName: t.Nullable(t.String()),- status: inviteStatus,- createdAt: t.String(),- respondedAt: t.Nullable(t.String()),- invitedByName: t.Nullable(t.String()),- invitedByEmail: t.Nullable(t.String()),-});+} from './service';-// The invitee-facing invite view (InviteView from the store).-const InviteViewResponse = t.Object({- token: t.String(),- projectKey: t.String(),- projectName: t.String(),- email: t.String(),- role: inviteRole,- roleId: t.Nullable(t.Number()),- roleName: t.Nullable(t.String()),- status: inviteStatus,- createdAt: t.String(),- hasAccount: t.Boolean(),-});--// The result of accepting an invite: the joined project's context.-const AcceptInviteResponse = t.Object({- projectKey: t.String(),- projectName: t.String(),- role: inviteRole,-});--// Loads the invite named by the token and asserts the caller may act on it: it-// must exist, still be pending, and be addressed to the session email-// (case-insensitive). Shared by accept and reject.+// Shared by accept and reject: an invite is actionable only by the account whose+// email it names, and only while it is still pending.async function loadActionableInvite(token: string, user: AuthUser | undefined | null) {const current = requireUser(user);const invite = await getInviteRowByToken(token);@@ -80,10 +43,6 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi.use(authContext).use(guards)- // --- Owner-side: manage a project's invites ----- // Create an invite link for an email + role. Owner only. A second pending- // invite for the same email in the same project is a 409..post('/projects/:projectKey/invites',async ({ project, body, user, set }) => {@@ -106,12 +65,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invireturn invite;},{- params: t.Object({ projectKey: t.String() }),- body: t.Object({- email: t.String({ format: 'email' }),- role: inviteRole,- roleId: t.Optional(t.Nullable(t.Integer())),- }),+ body: createInviteBody,permission: ['members_invite', 'create'],response: { 201: InviteRowResponse, ...commonErrors, ...errors(409) },detail: {@@ -130,14 +84,12 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invireturn listInvites(project.id);},{- params: t.Object({ projectKey: t.String() }),permission: ['members_invite', 'read'],- response: { 200: t.Array(InviteRowResponse), ...accessErrors },+ response: { 200: InviteRowListResponse, ...accessErrors },detail: { summary: "List a project's invites", ...mcpTool('list_invites') },},)- // Revoke a pending invite (or remove a resolved one). Owner only..delete('/projects/:projectKey/invites/:inviteId',async ({ project, params }) => {@@ -146,7 +98,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invireturn noContent();},{- params: t.Object({ projectKey: t.String(), inviteId: t.Numeric() }),+ params: inviteParams,permission: ['members_invite', 'delete'],response: { 204: t.Void(), ...commonErrors },detail: {@@ -157,11 +109,8 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi},)- // --- Invitee-side: open, accept, or reject a link ----- // Look up an invite by its token to render the accept/reject screen. Any- // authenticated user may read it (the token is unguessable); only the matching- // email may accept.+ // Unguarded by project membership: the invitee is not a member yet. The token+ // is unguessable, so any authenticated caller holding one may read the invite..get('/invites/:token',async ({ params }) => {@@ -184,9 +133,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi'/invites/:token/accept',async ({ params, user }) => {const { invite, current } = await loadActionableInvite(params.token, user);- await acceptInvite(invite, current.id);- const view = await getInviteByToken(params.token);- return { projectKey: view!.projectKey, projectName: view!.projectName, role: view!.role };+ return acceptInvite(invite, current.id);},{params: tokenParams,diff --git a/apps/api/src/modules/invites/model.ts b/apps/api/src/modules/invites/model.tsnew file mode 100644index 00000000..a51d7af2--- /dev/null+++ b/apps/api/src/modules/invites/model.ts@@ -0,0 +1,54 @@+import { t } from 'elysia';++const inviteRole = t.Union([t.Literal('owner'), t.Literal('member')]);++const inviteStatus = t.Union([t.Literal('pending'), t.Literal('accepted'), t.Literal('rejected')]);++export const inviteParams = t.Object({ projectKey: t.String(), inviteId: t.Numeric() });++// The token is a UUID column. Validating its format here turns a malformed token+// into a 400 instead of letting it reach Postgres and surface as a 500.+export const tokenParams = t.Object({ token: t.String({ format: 'uuid' }) });++export const createInviteBody = t.Object({+ email: t.String({ format: 'email' }),+ role: inviteRole,+ roleId: t.Optional(t.Nullable(t.Integer())),+});++// The owner-facing invite row (InviteRow from the service).+export const InviteRowResponse = t.Object({+ id: t.Number(),+ token: t.String(),+ email: t.String(),+ role: inviteRole,+ roleId: t.Nullable(t.Number()),+ roleName: t.Nullable(t.String()),+ status: inviteStatus,+ createdAt: t.String(),+ respondedAt: t.Nullable(t.String()),+ invitedByName: t.Nullable(t.String()),+ invitedByEmail: t.Nullable(t.String()),+});++export const InviteRowListResponse = t.Array(InviteRowResponse);++// The invitee-facing invite view (InviteView from the service).+export const InviteViewResponse = t.Object({+ token: t.String(),+ projectKey: t.String(),+ projectName: t.String(),+ email: t.String(),+ role: inviteRole,+ roleId: t.Nullable(t.Number()),+ roleName: t.Nullable(t.String()),+ status: inviteStatus,+ createdAt: t.String(),+ hasAccount: t.Boolean(),+});++export const AcceptInviteResponse = t.Object({+ projectKey: t.String(),+ projectName: t.String(),+ role: inviteRole,+});diff --git a/apps/api/src/invites/store.ts b/apps/api/src/modules/invites/service.tssimilarity index 93%rename from apps/api/src/invites/store.tsrename to apps/api/src/modules/invites/service.tsindex 1b7895ff..fcee4515 100644--- a/apps/api/src/invites/store.ts+++ b/apps/api/src/modules/invites/service.ts@@ -1,7 +1,7 @@import { db, projectInvite, projectMember, projectRole, project, user } from '@repo/db';import { and, desc, eq, sql } from 'drizzle-orm';-import { HttpError, iso, pgErrorCode } from '../shared/lib';-import type { MemberRole } from '../members/store';+import { HttpError, iso, pgErrorCode } from '#shared/lib';+import type { MemberRole } from '#modules/members/service';// Data access for project invites. An invite is a token-addressed grant of a// role to an email in a project. Creating one requires the project owner;@@ -46,6 +46,13 @@ export interface InviteView {hasAccount: boolean;}+// The project context an invitee lands in once the invite is accepted.+export interface AcceptedInvite {+ projectKey: string;+ projectName: string;+ role: MemberRole;+}+const normalizeEmail = (email: string) => email.trim().toLowerCase();export async function createInvite(input: {@@ -224,8 +231,8 @@ export async function getInviteRowByToken(token: string) {export async function acceptInvite(invite: { id: number; projectId: number; role: string; roleId: number | null },userId: string,-): Promise<void> {- await db.transaction(async (tx) => {+): Promise<AcceptedInvite> {+ return db.transaction(async (tx) => {// A member joins on the invite's chosen role, falling back to the project's// default role when none was set; an owner bypasses roles.let roleId: number | null = null;@@ -251,6 +258,11 @@ export async function acceptInvite(.update(projectInvite).set({ status: 'accepted', acceptedByUserId: userId, respondedAt: new Date() }).where(eq(projectInvite.id, invite.id));+ const [joined] = await tx+ .select({ projectKey: project.key, projectName: project.name })+ .from(project)+ .where(eq(project.id, invite.projectId));+ return { ...joined, role: invite.role as MemberRole };});}diff --git a/apps/api/src/issue-types/__tests__/integration/issue-types.test.ts b/apps/api/src/modules/issue-types/__tests__/integration/issue-types.test.tssimilarity index 94%rename from apps/api/src/issue-types/__tests__/integration/issue-types.test.tsrename to apps/api/src/modules/issue-types/__tests__/integration/issue-types.test.tsindex 89169af8..3d6b2f17 100644--- a/apps/api/src/issue-types/__tests__/integration/issue-types.test.ts+++ b/apps/api/src/modules/issue-types/__tests__/integration/issue-types.test.ts@@ -1,13 +1,13 @@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';// Issue types belong to one project. There is no GET /issue-types route — a type// is read back through the project view (GET /projects/:projectKey), whose// `issueTypes` field is listIssueTypes() ordered by position. A new project seeds-// no types, so the list starts empty. Names are unique within a project (a UNIQUE-// (project_id, name) constraint → 409 on a duplicate).+// one default "Task" type at position 0, so the list starts with it. Names are unique+// within a project (a UNIQUE (project_id, name) constraint → 409 on a duplicate).async function setupProject() {const owner = await signUpTestUser();@@ -202,7 +202,7 @@ describe('issue-types', () => {expect(types.map((t) => t.id)).not.toContain(type.id);});- // The store deletes by (id, projectId) with no existence check, so a missing+ // The service deletes by (id, projectId) with no existence check, so a missing// id is a no-op that still returns 204.it('returns 204 for a missing type', async () => {const { asOwner } = await setupProject();@@ -215,8 +215,8 @@ describe('issue-types', () => {});// A type is addressed as /projects/:projectKey/issue-types/:typeId. The- // permission guard runs on :projectKey, so the store must scope the type to that- // project — otherwise a request under one project could edit or delete another+ // permission guard runs on :projectKey, so the service must scope the type to+ // that project — otherwise a request under one project could edit or delete another// project's type by passing its id. delete has no existence check (always 204),// so the isolation is asserted by the foreign type surviving, not by the status.describe('cross-project isolation', () => {diff --git a/apps/api/src/issue-types/routes.ts b/apps/api/src/modules/issue-types/index.tssimilarity index 64%rename from apps/api/src/issue-types/routes.tsrename to apps/api/src/modules/issue-types/index.tsindex da46103d..7f500201 100644--- a/apps/api/src/issue-types/routes.ts+++ b/apps/api/src/modules/issue-types/index.ts@@ -1,23 +1,16 @@import { Elysia, t } from 'elysia';-import { mcpTool } from '../mcp/generate';-import { noContent } from '../shared/http';-import { guards } from '../shared/guards';-import { HttpError } from '../shared/lib';-import { commonErrors } from '../shared/responses';-import { createIssueType, updateIssueType, deleteIssueType } from './store';--const typeParams = t.Object({ projectKey: t.String(), typeId: t.Numeric() });--// An issue type DTO (IssueTypeRow from the store).-const IssueTypeResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- name: t.String(),- icon: t.String(),- color: t.String(),- isDefault: t.Boolean(),- position: t.Number(),-});+import { mcpTool } from '#mcp/generate';+import { noContent } from '#shared/http';+import { guards } from '#shared/guards';+import { HttpError } from '#shared/lib';+import { commonErrors } from '#shared/responses';+import {+ IssueTypeResponse,+ createIssueTypeBody,+ issueTypeParams,+ updateIssueTypeBody,+} from './model';+import { createIssueType, updateIssueType, deleteIssueType } from './service';export const issueTypeRoutes = new Elysia({name: 'issue-types',@@ -31,12 +24,7 @@ export const issueTypeRoutes = new Elysia({return createIssueType({ projectId: project.id, ...body });},{- body: t.Object({- name: t.String({ minLength: 1 }),- icon: t.Optional(t.String()),- color: t.Optional(t.String()),- isDefault: t.Optional(t.Boolean()),- }),+ body: createIssueTypeBody,permission: ['issue_types', 'create'],response: { 201: IssueTypeResponse, ...commonErrors },detail: {@@ -56,12 +44,8 @@ export const issueTypeRoutes = new Elysia({return type;},{- body: t.Object({- name: t.Optional(t.String({ minLength: 1 })),- color: t.Optional(t.String()),- isDefault: t.Optional(t.Boolean()),- }),- params: typeParams,+ body: updateIssueTypeBody,+ params: issueTypeParams,permission: ['issue_types', 'edit'],response: { 200: IssueTypeResponse, ...commonErrors },detail: {@@ -79,7 +63,7 @@ export const issueTypeRoutes = new Elysia({return noContent();},{- params: typeParams,+ params: issueTypeParams,permission: ['issue_types', 'delete'],response: { 204: t.Void(), ...commonErrors },detail: {diff --git a/apps/api/src/modules/issue-types/model.ts b/apps/api/src/modules/issue-types/model.tsnew file mode 100644index 00000000..10949bec--- /dev/null+++ b/apps/api/src/modules/issue-types/model.ts@@ -0,0 +1,27 @@+import { t } from 'elysia';++export const issueTypeParams = t.Object({ projectKey: t.String(), typeId: t.Numeric() });++export const IssueTypeResponse = t.Object({+ id: t.Number(),+ projectId: t.Number(),+ name: t.String(),+ icon: t.String(),+ color: t.String(),+ isDefault: t.Boolean(),+ position: t.Number(),+});++export const createIssueTypeBody = t.Object({+ name: t.String({ minLength: 1 }),+ icon: t.Optional(t.String()),+ color: t.Optional(t.String()),+ isDefault: t.Optional(t.Boolean()),+});++// The icon is fixed at creation, so it is not part of the patch.+export const updateIssueTypeBody = t.Object({+ name: t.Optional(t.String({ minLength: 1 })),+ color: t.Optional(t.String()),+ isDefault: t.Optional(t.Boolean()),+});diff --git a/apps/api/src/issue-types/store.ts b/apps/api/src/modules/issue-types/service.tssimilarity index 100%rename from apps/api/src/issue-types/store.tsrename to apps/api/src/modules/issue-types/service.tsdiff --git a/apps/api/src/labels/__tests__/integration/labels.test.ts b/apps/api/src/modules/labels/__tests__/integration/labels.test.tssimilarity index 98%rename from apps/api/src/labels/__tests__/integration/labels.test.tsrename to apps/api/src/modules/labels/__tests__/integration/labels.test.tsindex 4b57b4bf..fe851c31 100644--- a/apps/api/src/labels/__tests__/integration/labels.test.ts+++ b/apps/api/src/modules/labels/__tests__/integration/labels.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';// Labels and label groups belong to one project. There are no GET routes — both// are read back through the project view (GET /projects/:projectKey), whosediff --git a/apps/api/src/labels/routes.ts b/apps/api/src/modules/labels/index.tssimilarity index 70%rename from apps/api/src/labels/routes.tsrename to apps/api/src/modules/labels/index.tsindex 55ac9987..e4d3a686 100644--- a/apps/api/src/labels/routes.ts+++ b/apps/api/src/modules/labels/index.ts@@ -1,9 +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 { commonErrors, errors } from '../shared/responses';+import { mcpTool } from '#mcp/generate';+import { noContent } from '#shared/http';+import { guards } from '#shared/guards';+import { HttpError, rethrowDuplicate } from '#shared/lib';+import { commonErrors, errors } from '#shared/responses';+import {+ LabelGroupResponse,+ LabelResponse,+ createLabelBody,+ createLabelGroupBody,+ labelGroupParams,+ labelParams,+ updateLabelBody,+ updateLabelGroupBody,+} from './model';import {createLabel,updateLabel,@@ -11,31 +21,10 @@ import {createLabelGroup,updateLabelGroup,deleteLabelGroup,-} from './store';--const labelParams = t.Object({ projectKey: t.String(), labelId: t.Numeric() });-const groupParams = t.Object({ projectKey: t.String(), groupId: t.Numeric() });--// A label DTO (LabelRow from the store).-const LabelResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- groupId: t.Nullable(t.Number()),- name: t.String(),- color: t.String(),-});--// A label group DTO (LabelGroupRow from the store).-const LabelGroupResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- name: t.String(),- color: t.String(),-});+} from './service';export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels'] } }).use(guards)- // --- Labels ------------------------------------------------------------------.post('/projects/:projectKey/labels',async ({ project, body, set }) => {@@ -47,11 +36,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels}},{- body: t.Object({- name: t.String({ minLength: 1 }),- color: t.Optional(t.String()),- groupId: t.Optional(t.Nullable(t.Integer())),- }),+ body: createLabelBody,permission: ['labels', 'create'],response: { 201: LabelResponse, ...commonErrors, ...errors(409) },detail: {@@ -75,11 +60,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labelsreturn label;},{- body: t.Object({- name: t.Optional(t.String({ minLength: 1 })),- color: t.Optional(t.String()),- groupId: t.Optional(t.Nullable(t.Integer())),- }),+ body: updateLabelBody,params: labelParams,permission: ['labels', 'edit'],response: { 200: LabelResponse, ...commonErrors, ...errors(409) },@@ -110,7 +91,6 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels},)- // --- Label groups ------------------------------------------------------------.post('/projects/:projectKey/label-groups',async ({ project, body, set }) => {@@ -122,7 +102,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels}},{- body: t.Object({ name: t.String({ minLength: 1 }), color: t.Optional(t.String()) }),+ body: createLabelGroupBody,permission: ['labels', 'create'],response: { 201: LabelGroupResponse, ...commonErrors, ...errors(409) },detail: {@@ -146,11 +126,8 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labelsreturn group;},{- body: t.Object({- name: t.Optional(t.String({ minLength: 1 })),- color: t.Optional(t.String()),- }),- params: groupParams,+ body: updateLabelGroupBody,+ params: labelGroupParams,permission: ['labels', 'edit'],response: { 200: LabelGroupResponse, ...commonErrors, ...errors(409) },detail: {@@ -168,7 +145,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labelsreturn noContent();},{- params: groupParams,+ params: labelGroupParams,permission: ['labels', 'delete'],response: { 204: t.Void(), ...commonErrors },detail: {diff --git a/apps/api/src/modules/labels/model.ts b/apps/api/src/modules/labels/model.tsnew file mode 100644index 00000000..7412ab65--- /dev/null+++ b/apps/api/src/modules/labels/model.ts@@ -0,0 +1,36 @@+import { t } from 'elysia';++export const labelParams = t.Object({ projectKey: t.String(), labelId: t.Numeric() });+export const labelGroupParams = t.Object({ projectKey: t.String(), groupId: t.Numeric() });++// A label DTO (LabelRow from the service).+export const LabelResponse = t.Object({+ id: t.Number(),+ projectId: t.Number(),+ groupId: t.Nullable(t.Number()),+ name: t.String(),+ color: t.String(),+});++// A label group DTO (LabelGroupRow from the service).+export const LabelGroupResponse = t.Object({+ id: t.Number(),+ projectId: t.Number(),+ name: t.String(),+ color: t.String(),+});++export const createLabelBody = t.Object({+ name: t.String({ minLength: 1 }),+ color: t.Optional(t.String()),+ groupId: t.Optional(t.Nullable(t.Integer())),+});++export const updateLabelBody = t.Partial(createLabelBody);++export const createLabelGroupBody = t.Object({+ name: t.String({ minLength: 1 }),+ color: t.Optional(t.String()),+});++export const updateLabelGroupBody = t.Partial(createLabelGroupBody);diff --git a/apps/api/src/labels/store.ts b/apps/api/src/modules/labels/service.tssimilarity index 100%rename from apps/api/src/labels/store.tsrename to apps/api/src/modules/labels/service.tsdiff --git a/apps/api/src/members/__tests__/integration/members.test.ts b/apps/api/src/modules/members/__tests__/integration/members.test.tssimilarity index 98%rename from apps/api/src/members/__tests__/integration/members.test.tsrename to apps/api/src/modules/members/__tests__/integration/members.test.tsindex 889ae905..387b4114 100644--- a/apps/api/src/members/__tests__/integration/members.test.ts+++ b/apps/api/src/modules/members/__tests__/integration/members.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach } from 'bun:test';-import { authedApi } from '../../../__tests__/helpers/app';-import { signUpTestUser, type TestUser } from '../../../__tests__/helpers/auth';-import { resetDb } from '../../../__tests__/helpers/db';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser, type TestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';// Integration coverage for the members feature: listing a project's members,// assigning a custom role to a member (owner only), and removing a member ordiff --git a/apps/api/src/members/routes.ts b/apps/api/src/modules/members/index.tssimilarity index 67%rename from apps/api/src/members/routes.tsrename to apps/api/src/modules/members/index.tsindex b0f1e69a..c2af9ca2 100644--- a/apps/api/src/members/routes.ts+++ b/apps/api/src/modules/members/index.ts@@ -1,11 +1,18 @@import { Elysia, t } from 'elysia';-import { mcpTool } from '../mcp/generate';-import { noContent } from '../shared/http';-import { authContext } from '../shared/auth-context';-import { guards } from '../shared/guards';-import { assertPermission, 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 { authContext } from '#shared/auth-context';+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 {+ MemberListResponse,+ memberParams,+ setMemberDescriptionBody,+ setMemberRoleBody,+} from './model';import {listMembers,getMembership,@@ -13,46 +20,23 @@ import {setMembership,setMemberDescription,countOwners,-} from './store';-import { getRole } from '../roles/store';--const memberParams = t.Object({ projectKey: t.String(), userId: t.String() });-const memberRole = t.Union([t.Literal('owner'), t.Literal('member')]);--// A member DTO (MemberRow from the store).-const MemberResponse = t.Object({- userId: t.String(),- name: t.String(),- email: t.String(),- image: t.Nullable(t.String()),- role: memberRole,- roleId: t.Nullable(t.Number()),- roleName: t.Nullable(t.String()),- description: t.String(),- isAgent: t.Boolean(),- createdAt: t.String(),-});+} from './service';export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Members'] } }).use(authContext).use(guards)- // Members with members_manage read may see who else is on the project..get('/projects/:projectKey/members',async ({ project }) => {return listMembers(project.id);},{- params: t.Object({ projectKey: t.String() }),permission: ['members_manage', 'read'],- response: { 200: t.Array(MemberResponse), ...accessErrors },+ response: { 200: MemberListResponse, ...accessErrors },detail: { summary: 'List project members', ...mcpTool('list_members') },},)- // Set a member's role. Owner only. role "owner" promotes them to owner (owners- // bypass roles); role "member" assigns a custom role by roleId (null falls back- // to the default role). Demoting the last owner is refused..patch('/projects/:projectKey/members/:userId',async ({ project, params, body, user }) => {@@ -83,7 +67,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb},{params: memberParams,- body: t.Object({ role: memberRole, roleId: t.Optional(t.Nullable(t.Integer())) }),+ body: setMemberRoleBody,projectOwner: true,response: { 204: t.Void(), ...commonErrors },detail: {@@ -96,9 +80,8 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb},)- // Set a member's project description (what they do). A member may edit their own;- // an owner may edit anyone's. The description is shown on the members page and- // given to agents so they can pick who to tag on an unassigned issue.+ // The description is shown on the members page and given to agents so they can+ // pick who to tag on an unassigned issue..patch('/projects/:projectKey/members/:userId/description',async ({ project, params, body, user }) => {@@ -115,7 +98,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb},{params: memberParams,- body: t.Object({ description: t.String({ maxLength: 500 }) }),+ body: setMemberDescriptionBody,projectMember: true,response: { 204: t.Void(), ...commonErrors },detail: {@@ -127,10 +110,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb},)- // Revoke a member's access, or leave the project yourself. Removing someone- // else requires members_manage delete (owners bypass); a member may always- // remove themselves. The last owner cannot be removed. New members join through- // invites, so there is no direct add here.+ // New members join through invites, so there is no direct add here..delete('/projects/:projectKey/members/:userId',async ({ project, params, user }) => {diff --git a/apps/api/src/modules/members/model.ts b/apps/api/src/modules/members/model.tsnew file mode 100644index 00000000..4cd2fd1f--- /dev/null+++ b/apps/api/src/modules/members/model.ts@@ -0,0 +1,30 @@+import { t } from 'elysia';++const memberRole = t.Union([t.Literal('owner'), t.Literal('member')]);++export const memberParams = t.Object({ projectKey: t.String(), userId: t.String() });++// A member DTO (MemberRow from the service).+const MemberResponse = t.Object({+ userId: t.String(),+ name: t.String(),+ email: t.String(),+ image: t.Nullable(t.String()),+ role: memberRole,+ roleId: t.Nullable(t.Number()),+ roleName: t.Nullable(t.String()),+ description: t.String(),+ isAgent: t.Boolean(),+ createdAt: t.String(),+});++export const MemberListResponse = t.Array(MemberResponse);++export const setMemberRoleBody = t.Object({+ role: memberRole,+ roleId: t.Optional(t.Nullable(t.Integer())),+});++export const setMemberDescriptionBody = t.Object({+ description: t.String({ maxLength: 500 }),+});diff --git a/apps/api/src/members/store.ts b/apps/api/src/modules/members/service.tssimilarity index 99%rename from apps/api/src/members/store.tsrename to apps/api/src/modules/members/service.tsindex 3317b135..3cab3327 100644--- a/apps/api/src/members/store.ts+++ b/apps/api/src/modules/members/service.ts@@ -1,12 +1,12 @@import { db, projectMember, projectRole, user, aiAgent } from '@repo/db';import { and, eq, isNull, sql } from 'drizzle-orm';-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 project membership: which users can reach a project and their// role in it ("owner" or "member"). Access checks resolve the owning project ofdiff --git a/apps/api/src/note-boards/__tests__/integration/note-boards.test.ts b/apps/api/src/modules/note-boards/__tests__/integration/note-boards.test.tssimilarity index 98%rename from apps/api/src/note-boards/__tests__/integration/note-boards.test.tsrename to apps/api/src/modules/note-boards/__tests__/integration/note-boards.test.tsindex 1f55143b..eb1bbd25 100644--- a/apps/api/src/note-boards/__tests__/integration/note-boards.test.ts+++ b/apps/api/src/modules/note-boards/__tests__/integration/note-boards.test.ts@@ -1,7 +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';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';type Client = ReturnType<typeof authedApi>;diff --git a/apps/api/src/note-boards/routes.ts b/apps/api/src/modules/note-boards/index.tssimilarity index 77%rename from apps/api/src/note-boards/routes.tsrename to apps/api/src/modules/note-boards/index.tsindex c13af329..5a0db875 100644--- a/apps/api/src/note-boards/routes.ts+++ b/apps/api/src/modules/note-boards/index.ts@@ -1,11 +1,20 @@import { Elysia, t } from 'elysia';-import { noContent } from '../shared/http';-import { guards } from '../shared/guards';-import { authContext } from '../shared/auth-context';-import { requireUser } from '../shared/access';-import { HttpError } from '../shared/lib';-import { mcpTool } from '../mcp/generate';-import { accessErrors, commonErrors } from '../shared/responses';+import { noContent } from '#shared/http';+import { guards } from '#shared/guards';+import { authContext } from '#shared/auth-context';+import { requireUser } from '#shared/access';+import { HttpError } from '#shared/lib';+import { mcpTool } from '#mcp/generate';+import { accessErrors, commonErrors } from '#shared/responses';+import {+ NoteBoardAccessCandidateListResponse,+ NoteBoardResponse,+ NoteBoardSummaryListResponse,+ createNoteBoardBody,+ listNoteBoardsQuery,+ noteBoardParams,+ updateNoteBoardBody,+} from './model';import {listNoteBoards,createNoteBoard,@@ -14,37 +23,7 @@ import {deleteNoteBoard,listNoteBoardAccessCandidates,type NoteBoardRow,-} from './store';--const boardParams = t.Object({ projectKey: t.String(), boardId: t.Numeric() });--const Visibility = t.Union([t.Literal('public'), t.Literal('private'), t.Literal('restricted')]);--// A note board DTO (NoteBoardRow from the store). canvas is a jsonb blob owned by-// the UI (React Flow nodes/edges) and returned verbatim, so it is typed t.Any().-const NoteBoardResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- ownerUserId: t.Nullable(t.String()),- createdByUserId: t.Nullable(t.String()),- visibility: Visibility,- memberIds: t.Array(t.String()),- name: t.String(),- canvas: t.Any(),- createdAt: t.String(),- updatedAt: t.String(),-});--// The list/switcher DTO: the board without its canvas or member list.-const NoteBoardSummaryResponse = t.Omit(NoteBoardResponse, ['canvas', 'memberIds']);--const NoteBoardAccessCandidateResponse = t.Object({- userId: t.String(),- name: t.String(),- image: t.Nullable(t.String()),- kind: t.Union([t.Literal('member'), t.Literal('agent')]),- canAccess: t.Boolean(),-});+} from './service';// Load a board that belongs to this project and that the user may access: a// public board is open to any member; a private one to its owner and the members@@ -103,13 +82,8 @@ export const noteBoardRoutes = new Elysia({},{permission: ['note_boards', 'read'],- // Paged for the board switcher.- query: t.Object({- q: t.Optional(t.String()),- limit: t.Optional(t.Numeric({ minimum: 1, maximum: 50 })),- offset: t.Optional(t.Numeric({ minimum: 0 })),- }),- response: { 200: t.Array(NoteBoardSummaryResponse), ...accessErrors },+ query: listNoteBoardsQuery,+ response: { 200: NoteBoardSummaryListResponse, ...accessErrors },detail: {summary: "List a project's note boards",description:@@ -124,7 +98,7 @@ export const noteBoardRoutes = new Elysia({async ({ project }) => listNoteBoardAccessCandidates(project.id),{permission: ['note_boards', 'edit'],- response: { 200: t.Array(NoteBoardAccessCandidateResponse), ...accessErrors },+ response: { 200: NoteBoardAccessCandidateListResponse, ...accessErrors },detail: {summary: 'List who a board can be shared with',description:@@ -140,7 +114,7 @@ export const noteBoardRoutes = new Elysia({},{permission: ['note_boards', 'read'],- params: boardParams,+ params: noteBoardParams,response: { 200: NoteBoardResponse, ...accessErrors },detail: {summary: 'Get a note board with its canvas',@@ -166,11 +140,7 @@ export const noteBoardRoutes = new Elysia({},{permission: ['note_boards', 'create'],- body: t.Object({- name: t.String({ minLength: 1 }),- visibility: t.Optional(t.Union([t.Literal('public'), t.Literal('private')])),- canvas: t.Optional(t.Any()),- }),+ body: createNoteBoardBody,response: { 201: NoteBoardResponse, ...commonErrors },detail: {summary: 'Create a note board',@@ -218,13 +188,8 @@ export const noteBoardRoutes = new Elysia({},{permission: ['note_boards', 'edit'],- params: boardParams,- body: t.Object({- name: t.Optional(t.String({ minLength: 1 })),- canvas: t.Optional(t.Any()),- visibility: t.Optional(Visibility),- memberIds: t.Optional(t.Array(t.String())),- }),+ params: noteBoardParams,+ body: updateNoteBoardBody,response: { 200: NoteBoardResponse, ...commonErrors },detail: {summary: 'Update a note board',@@ -244,7 +209,7 @@ export const noteBoardRoutes = new Elysia({},{permission: ['note_boards', 'delete'],- params: boardParams,+ params: noteBoardParams,response: { 204: t.Void(), ...accessErrors },detail: {summary: 'Delete a note board',diff --git a/apps/api/src/modules/note-boards/model.ts b/apps/api/src/modules/note-boards/model.tsnew file mode 100644index 00000000..55f9e75a--- /dev/null+++ b/apps/api/src/modules/note-boards/model.ts@@ -0,0 +1,56 @@+import { t } from 'elysia';++const visibility = t.Union([t.Literal('public'), t.Literal('private'), t.Literal('restricted')]);++export const noteBoardParams = t.Object({ projectKey: t.String(), boardId: t.Numeric() });++// A note board DTO (NoteBoardRow from the service). canvas is a jsonb blob owned by+// the UI (React Flow nodes/edges) and returned verbatim, so it is typed t.Any().+export const NoteBoardResponse = t.Object({+ id: t.Number(),+ projectId: t.Number(),+ ownerUserId: t.Nullable(t.String()),+ createdByUserId: t.Nullable(t.String()),+ visibility,+ memberIds: t.Array(t.String()),+ name: t.String(),+ canvas: t.Any(),+ createdAt: t.String(),+ updatedAt: t.String(),+});++// What the board switcher lists (NoteBoardSummary from the service).+export const NoteBoardSummaryListResponse = t.Array(+ t.Omit(NoteBoardResponse, ['canvas', 'memberIds']),+);++export const NoteBoardAccessCandidateListResponse = t.Array(+ t.Object({+ userId: t.String(),+ name: t.String(),+ image: t.Nullable(t.String()),+ kind: t.Union([t.Literal('member'), t.Literal('agent')]),+ canAccess: t.Boolean(),+ }),+);++export const listNoteBoardsQuery = t.Object({+ q: t.Optional(t.String()),+ limit: t.Optional(t.Numeric({ minimum: 1, maximum: 50 })),+ offset: t.Optional(t.Numeric({ minimum: 0 })),+});++// A board is created public or private; it turns restricted by granting members,+// which only the update route does.+export const createNoteBoardBody = t.Object({+ name: t.String({ minLength: 1 }),+ visibility: t.Optional(t.Union([t.Literal('public'), t.Literal('private')])),+ canvas: t.Optional(t.Any()),+});++export const updateNoteBoardBody = t.Object({+ name: t.Optional(t.String({ minLength: 1 })),+ canvas: t.Optional(t.Any()),+ visibility: t.Optional(visibility),+ memberIds: t.Optional(t.Array(t.String())),+});diff --git a/apps/api/src/note-boards/store.ts b/apps/api/src/modules/note-boards/service.tssimilarity index 96%rename from apps/api/src/note-boards/store.tsrename to apps/api/src/modules/note-boards/service.tsindex 8f15527d..a05e7c6d 100644--- a/apps/api/src/note-boards/store.ts+++ b/apps/api/src/modules/note-boards/service.ts@@ -1,8 +1,8 @@import { db, noteBoard, noteBoardMember } from '@repo/db';import { and, desc, eq, exists, ilike, inArray, isNull, or, sql } from 'drizzle-orm';-import { iso } from '../shared/lib';-import { hasPermission } from '../shared/permissions';-import { listAssigneeCandidates, listMemberContexts } from '../members/store';+import { iso } from '#shared/lib';+import { hasPermission } from '#shared/permissions';+import { listAssigneeCandidates, listMemberContexts } from '#modules/members/service';// Note boards: a freeform canvas of sticky notes. canvas is a jsonb blob owned by// the UI (React Flow nodes + edges + viewport); this layer stores and returns it@@ -12,7 +12,7 @@ import { listAssigneeCandidates, listMemberContexts } from '../members/store';// The three states the UI offers, derived from the two columns above: a board with// an owner and no granted members is private, one with granted members restricted.-export type NoteBoardVisibility = 'public' | 'private' | 'restricted';+type NoteBoardVisibility = 'public' | 'private' | 'restricted';export interface NoteBoardRow {id: number;diff --git a/apps/api/src/notification-preferences/routes.ts b/apps/api/src/modules/notification-preferences/index.tssimilarity index 66%rename from apps/api/src/notification-preferences/routes.tsrename to apps/api/src/modules/notification-preferences/index.tsindex 65b5bce1..14f6380a 100644--- a/apps/api/src/notification-preferences/routes.ts+++ b/apps/api/src/modules/notification-preferences/index.ts@@ -1,21 +1,10 @@-import { Elysia, t } from 'elysia';-import { guards } from '../shared/guards';-import { authContext } from '../shared/auth-context';-import { requireUser } from '../shared/access';-import { accessErrors, commonErrors } from '../shared/responses';-import { getPreferences, setPreferences } from './store';--const EventToggles = t.Object({- assigned: t.Boolean(),- mentioned: t.Boolean(),- commented: t.Boolean(),- state_changed: t.Boolean(),-});--const PreferenceBody = t.Object({- emailEvents: EventToggles,- telegramEvents: EventToggles,-});+import { Elysia } from 'elysia';+import { guards } from '#shared/guards';+import { authContext } from '#shared/auth-context';+import { requireUser } from '#shared/access';+import { accessErrors, commonErrors } from '#shared/responses';+import { NotificationPreferenceBody } from './model';+import { getPreferences, setPreferences } from './service';// A member's own notification preferences for a project: which issue events they want// by email and/or Telegram. Every route is self-scoped to the session user, so bare@@ -35,7 +24,7 @@ export const notificationPreferenceRoutes = new Elysia({({ project, user }) => getPreferences(requireUser(user).id, project.id),{projectMember: true,- response: { 200: PreferenceBody, ...accessErrors },+ response: { 200: NotificationPreferenceBody, ...accessErrors },detail: {summary: 'Get notification preferences',description: "Get the current user's notification preferences for a project.",@@ -47,9 +36,9 @@ export const notificationPreferenceRoutes = new Elysia({'/projects/:projectKey/notification-preferences',({ project, user, body }) => setPreferences(requireUser(user).id, project.id, body),{- body: PreferenceBody,+ body: NotificationPreferenceBody,projectMember: true,- response: { 200: PreferenceBody, ...commonErrors },+ response: { 200: NotificationPreferenceBody, ...commonErrors },detail: {summary: 'Update notification preferences',description: "Update the current user's notification preferences for a project.",diff --git a/apps/api/src/modules/notification-preferences/model.ts b/apps/api/src/modules/notification-preferences/model.tsnew file mode 100644index 00000000..5af4d2c2--- /dev/null+++ b/apps/api/src/modules/notification-preferences/model.ts@@ -0,0 +1,14 @@+import { t } from 'elysia';++const EventToggles = t.Object({+ assigned: t.Boolean(),+ mentioned: t.Boolean(),+ commented: t.Boolean(),+ state_changed: t.Boolean(),+});++// Request body of the PUT and the response of both routes.+export const NotificationPreferenceBody = t.Object({+ emailEvents: EventToggles,+ telegramEvents: EventToggles,+});diff --git a/apps/api/src/notification-preferences/store.ts b/apps/api/src/modules/notification-preferences/service.tssimilarity index 89%rename from apps/api/src/notification-preferences/store.tsrename to apps/api/src/modules/notification-preferences/service.tsindex 1a9ea1c6..04f6ab2f 100644--- a/apps/api/src/notification-preferences/store.ts+++ b/apps/api/src/modules/notification-preferences/service.ts@@ -4,14 +4,9 @@ import { and, eq, inArray, sql } from 'drizzle-orm';// A member's own notification preferences for one project: for each issue event// type, whether they want it by email and/or Telegram. One row per (user, project);// absent means the member has not opted in and receives nothing (opt-in default).-// The project's provider credentials live separately in notification-settings, and-// which Telegram chat the member is reached at comes from the account they linked-// (telegram/store.ts), which is instance-wide. Here is only the per-user choice of-// events and channels.// The issue events a member can subscribe to, matching the inbox notification types.-export const EVENT_KEYS = ['assigned', 'mentioned', 'commented', 'state_changed'] as const;-export type EventKey = (typeof EVENT_KEYS)[number];+export type EventKey = 'assigned' | 'mentioned' | 'commented' | 'state_changed';export type EventToggles = Record<EventKey, boolean>;export interface NotificationPreferenceDto {diff --git a/apps/api/src/modules/notification-settings/index.ts b/apps/api/src/modules/notification-settings/index.tsnew file mode 100644index 00000000..993a3665--- /dev/null+++ b/apps/api/src/modules/notification-settings/index.ts@@ -0,0 +1,57 @@+import { Elysia } from 'elysia';+import { guards } from '#shared/guards';+import { authContext } from '#shared/auth-context';+import { accessErrors, commonErrors } from '#shared/responses';+import { getProjectEmailConfig } from '@repo/auth';+import { NotificationSettingsBody, NotificationSettingsResponse } from './model';+import {+ getNotificationSettings,+ setNotificationSettings,+ type NotificationSettingsDto,+} from './service';++// Adds whether the instance provider is available to projects right now. It is an+// instance setting, so it is reported alongside the project's own settings rather+// than stored with them.+async function withSystemAvailability(settings: NotificationSettingsDto) {+ return { ...settings, systemAvailable: (await getProjectEmailConfig()) !== null };+}++// Notification provider credentials carry secrets (SMTP password, Resend key,+// Telegram bot token), so they are managed only through the session UI and not+// exposed as MCP tools. Gated under the danger_zone resource, the project-level+// settings gate. A member's own delivery preferences live in notification-preferences.+export const notificationSettingsRoutes = new Elysia({+ name: 'notification-settings',+ detail: { tags: ['Settings'] },+})+ .use(authContext)+ .use(guards)++ .get(+ '/projects/:projectKey/notification-settings',+ async ({ project }) => withSystemAvailability(await getNotificationSettings(project.id)),+ {+ permission: ['danger_zone', 'read'],+ response: { 200: NotificationSettingsResponse, ...accessErrors },+ detail: {+ summary: 'Get notification provider settings',+ description: "Get a project's notification provider settings (secrets redacted).",+ },+ },+ )++ .put(+ '/projects/:projectKey/notification-settings',+ async ({ project, body }) =>+ withSystemAvailability(await setNotificationSettings(project.id, body)),+ {+ body: NotificationSettingsBody,+ permission: ['danger_zone', 'edit'],+ response: { 200: NotificationSettingsResponse, ...commonErrors },+ detail: {+ summary: 'Update notification provider settings',+ description: "Update a project's notification provider settings.",+ },+ },+ );diff --git a/apps/api/src/modules/notification-settings/model.ts b/apps/api/src/modules/notification-settings/model.tsnew file mode 100644index 00000000..e27c0e1a--- /dev/null+++ b/apps/api/src/modules/notification-settings/model.ts@@ -0,0 +1,45 @@+import { t } from 'elysia';+import { ENCRYPTION_MODES } from './service';++const encryption = t.UnionEnum([...ENCRYPTION_MODES]);++// The redacted settings DTO (NotificationSettingsDto from the service): the+// project's provider credentials. Secrets are never returned; each is replaced by a+// boolean telling whether a value is stored.+export const NotificationSettingsResponse = t.Object({+ // Deliver email through the instance provider instead of the project's own.+ system: t.Object({ enabled: t.Boolean() }),+ // Whether that instance provider exists and is shared with projects right now.+ // The project cannot see or change it, so the UI states why sending is off.+ systemAvailable: t.Boolean(),+ 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() }),+ telegram: t.Object({ enabled: t.Boolean(), hasBotToken: t.Boolean() }),+});++// Every section optional so each provider card can save on its own. Secret fields+// are optional and, when omitted or empty, keep their stored value.+export const NotificationSettingsBody = t.Object({+ system: t.Optional(t.Object({ enabled: t.Boolean() })),+ 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()) })),+ telegram: t.Optional(t.Object({ enabled: t.Boolean(), botToken: t.Optional(t.String()) })),+});diff --git a/apps/api/src/notification-settings/store.ts b/apps/api/src/modules/notification-settings/service.tssimilarity index 97%rename from apps/api/src/notification-settings/store.tsrename to apps/api/src/modules/notification-settings/service.tsindex 855c4f43..0421b3f6 100644--- a/apps/api/src/notification-settings/store.ts+++ b/apps/api/src/modules/notification-settings/service.ts@@ -185,8 +185,8 @@ async function readConfig(projectId: number): Promise<NotificationConfig | null>return { ...defaultConfig(), ...(JSON.parse(decryptSecret(row)) as NotificationConfig) };}-// The redacted settings for a project. Defaults (all channels off, no secrets)-// when nothing has been saved.+// The redacted settings for a project. Defaults (no secrets, no provider of its own,+// delivery through the instance provider) when nothing has been saved.export async function getNotificationSettings(projectId: number): Promise<NotificationSettingsDto> {const config = (await readConfig(projectId)) ?? defaultConfig();return toDto(config);@@ -199,6 +199,7 @@ export async function setNotificationSettings(): Promise<NotificationSettingsDto> {const current = (await readConfig(projectId)) ?? defaultConfig();const next = applyPatch(current, patch);+ const redacted = toDto(next);const enc = encryptSecret(JSON.stringify(next));await db.insert(projectNotificationSetting)@@ -207,7 +208,7 @@ export async function setNotificationSettings(ciphertext: enc.ciphertext,iv: enc.iv,authTag: enc.authTag,- redacted: toDto(next),+ redacted,}).onConflictDoUpdate({target: projectNotificationSetting.projectId,@@ -215,11 +216,11 @@ export async function setNotificationSettings(ciphertext: enc.ciphertext,iv: enc.iv,authTag: enc.authTag,- redacted: toDto(next),+ redacted,updatedAt: sql`now()`,},});- return toDto(next);+ return redacted;}// The redacted settings read straight from the plaintext `redacted` column, withoutdiff --git a/apps/api/src/notifications/__tests__/integration/notifications.test.ts b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.tssimilarity index 96%rename from apps/api/src/notifications/__tests__/integration/notifications.test.tsrename to apps/api/src/modules/notifications/__tests__/integration/notifications.test.tsindex de382203..7d1a8700 100644--- a/apps/api/src/notifications/__tests__/integration/notifications.test.ts+++ b/apps/api/src/modules/notifications/__tests__/integration/notifications.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';// Notifications are fanned out when an issue changes and read back through the// session user's inbox. The actor is never notified about their own action, anddiff --git a/apps/api/src/notifications/routes.ts b/apps/api/src/modules/notifications/index.tssimilarity index 60%rename from apps/api/src/notifications/routes.tsrename to apps/api/src/modules/notifications/index.tsindex b123617c..1e54cecd 100644--- a/apps/api/src/notifications/routes.ts+++ b/apps/api/src/modules/notifications/index.ts@@ -1,9 +1,21 @@import { Elysia, t } from 'elysia';-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 { authContext } from '#shared/auth-context';+import { requireUser } from '#shared/access';+import { HttpError } from '#shared/lib';+import { errors } from '#shared/responses';+import {+ AffectedCountResponse,+ NotificationPageResponse,+ UnreadCountResponse,+ deleteNotificationsQuery,+ listNotificationsQuery,+ markAllReadBody,+ notificationParams,+ setNotificationReadBody,+ snoozeNotificationBody,+ unreadCountQuery,+} from './model';import {listNotifications,unreadCount,@@ -12,43 +24,11 @@ import {snoozeNotification,deleteNotification,deleteNotifications,+ NOTIFICATION_TYPES,type NotificationType,type NotificationFilters,type DeleteScope,-} from './store';--const NOTIFICATION_TYPES: NotificationType[] = [- 'assigned',- 'mentioned',- 'commented',- 'state_changed',-];--const NotificationResponse = t.Object({- id: t.Number(),- type: t.String(),- actorUserId: t.Nullable(t.String()),- actorName: t.Nullable(t.String()),- readAt: t.Nullable(t.String()),- snoozedUntil: t.Nullable(t.String()),- createdAt: t.String(),- issueId: t.Number(),- issueSeq: t.Number(),- issueTitle: t.String(),- issueStateType: t.String(),- projectId: t.Number(),- projectKey: t.String(),- projectName: t.String(),- fromState: t.Nullable(t.String()),- toState: t.Nullable(t.String()),-});--const NotificationPageResponse = t.Object({- items: t.Array(NotificationResponse),- nextCursor: t.Nullable(t.Object({ ts: t.String(), id: t.Number() })),-});--const idParams = t.Object({ id: t.Numeric() });+} from './service';// Inbox: the session user's own notifications across every project they are a// member of. Every route is scoped to that user (no project permission needed to@@ -77,7 +57,9 @@ export const notificationRoutes = new Elysia({if (query.types) {const types = query.types.split(',')- .filter((x): x is NotificationType => (NOTIFICATION_TYPES as string[]).includes(x));+ .filter((x): x is NotificationType =>+ (NOTIFICATION_TYPES as readonly string[]).includes(x),+ );if (types.length) filters.types = types;}if (query.from) filters.fromUserId = query.from;@@ -87,19 +69,7 @@ export const notificationRoutes = new Elysia({return listNotifications(userId, { before, limit, filters });},{- query: t.Object({- limit: t.Optional(t.String({ description: 'Max items per page (1-100). Default 30.' })),- cursor: t.Optional(t.String({ description: 'nextCursor from the previous page.' })),- types: t.Optional(- t.String({ description: 'Comma-separated notification types to include.' }),- ),- from: t.Optional(t.String({ description: 'Filter by actor user id.' })),- projectId: t.Optional(t.String({ description: 'Filter by project id.' })),- includeRead: t.Optional(t.String({ description: "'false' hides read. Default true." })),- includeSnoozed: t.Optional(- t.String({ description: "'true' shows snoozed. Default false." }),- ),- }),+ query: listNotificationsQuery,response: { 200: NotificationPageResponse, ...errors(401) },detail: { summary: 'List inbox notifications' },},@@ -114,10 +84,8 @@ export const notificationRoutes = new Elysia({return { unread: await unreadCount(userId, projectId) };},{- query: t.Object({- projectId: t.Optional(t.String({ description: 'Scope the count to one project.' })),- }),- response: { 200: t.Object({ unread: t.Number() }), ...errors(401) },+ query: unreadCountQuery,+ response: { 200: UnreadCountResponse, ...errors(401) },detail: { summary: 'Get unread notification count' },},)@@ -130,8 +98,8 @@ export const notificationRoutes = new Elysia({return { count };},{- body: t.Optional(t.Object({ projectId: t.Optional(t.Number()) })),- response: { 200: t.Object({ count: t.Number() }), ...errors(401) },+ body: markAllReadBody,+ response: { 200: AffectedCountResponse, ...errors(401) },detail: { summary: 'Mark all notifications read' },},)@@ -146,15 +114,8 @@ export const notificationRoutes = new Elysia({return { count };},{- query: t.Object({- scope: t.Optional(- t.Union([t.Literal('all'), t.Literal('read'), t.Literal('read-completed')], {- description: 'Which notifications to delete. Default read.',- }),- ),- projectId: t.Optional(t.String({ description: 'Scope the delete to one project.' })),- }),- response: { 200: t.Object({ count: t.Number() }), ...errors(401) },+ query: deleteNotificationsQuery,+ response: { 200: AffectedCountResponse, ...errors(401) },detail: { summary: 'Delete inbox notifications' },},)@@ -169,8 +130,8 @@ export const notificationRoutes = new Elysia({return noContent();},{- params: idParams,- body: t.Optional(t.Object({ read: t.Optional(t.Boolean()) })),+ params: notificationParams,+ body: setNotificationReadBody,response: { 204: t.Void(), ...errors(401, 404) },detail: { summary: 'Mark a notification read or unread' },},@@ -187,8 +148,8 @@ export const notificationRoutes = new Elysia({return noContent();},{- params: idParams,- body: t.Object({ until: t.Nullable(t.String()) }),+ params: notificationParams,+ body: snoozeNotificationBody,response: { 204: t.Void(), ...errors(400, 401, 404) },detail: {summary: 'Snooze a notification',@@ -206,7 +167,7 @@ export const notificationRoutes = new Elysia({return noContent();},{- params: idParams,+ params: notificationParams,response: { 204: t.Void(), ...errors(401, 404) },detail: { summary: 'Delete a notification' },},diff --git a/apps/api/src/notifications/internal-routes.ts b/apps/api/src/modules/notifications/internal-routes.tssimilarity index 70%rename from apps/api/src/notifications/internal-routes.tsrename to apps/api/src/modules/notifications/internal-routes.tsindex c8e1bdcd..fbb4c314 100644--- a/apps/api/src/notifications/internal-routes.ts+++ b/apps/api/src/modules/notifications/internal-routes.ts@@ -1,5 +1,6 @@-import { Elysia, t } from 'elysia';-import { getDeliveryConfig } from '../notification-settings/store';+import { Elysia } from 'elysia';+import { getDeliveryConfig } from '#modules/notification-settings/service';+import { sendDeliveryBody } from './model';import { sendDelivery } from './send';// Internal endpoint the worker calls to deliver one claimed notification_delivery@@ -8,21 +9,6 @@ import { sendDelivery } from './send';// in the worker, mirroring /internal/agent-runs/execute. Authenticated with the// shared WORKER_INTERNAL_TOKEN. Returns the SendResult so the worker records the// outcome and decides whether to retry.-const sendBody = t.Object({- projectId: t.Number(),- channel: t.UnionEnum(['email', 'telegram']),- recipient: t.Nullable(t.String()),- payload: t.Object({- subject: t.Optional(t.String()),- text: t.String(),- // The Telegram body. Elysia strips fields the schema does not declare, so- // leaving it out here would silently drop the formatted message and send the- // plain-text fallback instead.- html: t.Optional(t.String()),- url: t.Optional(t.String()),- }),-});-export const internalNotificationRoutes = new Elysia({name: 'internal-notification-deliveries',detail: { tags: ['Internal'] },@@ -43,7 +29,7 @@ export const internalNotificationRoutes = new Elysia({});},{- body: sendBody,+ body: sendDeliveryBody,detail: {summary: 'Send one notification delivery',description:diff --git a/apps/api/src/modules/notifications/model.ts b/apps/api/src/modules/notifications/model.tsnew file mode 100644index 00000000..c9d6d62e--- /dev/null+++ b/apps/api/src/modules/notifications/model.ts@@ -0,0 +1,76 @@+import { t } from 'elysia';++export const notificationParams = t.Object({ id: t.Numeric() });++const NotificationResponse = t.Object({+ id: t.Number(),+ type: t.String(),+ actorUserId: t.Nullable(t.String()),+ actorName: t.Nullable(t.String()),+ readAt: t.Nullable(t.String()),+ snoozedUntil: t.Nullable(t.String()),+ createdAt: t.String(),+ issueId: t.Number(),+ issueSeq: t.Number(),+ issueTitle: t.String(),+ issueStateType: t.String(),+ projectId: t.Number(),+ projectKey: t.String(),+ projectName: t.String(),+ fromState: t.Nullable(t.String()),+ toState: t.Nullable(t.String()),+});++export const NotificationPageResponse = t.Object({+ items: t.Array(NotificationResponse),+ nextCursor: t.Nullable(t.Object({ ts: t.String(), id: t.Number() })),+});++export const UnreadCountResponse = t.Object({ unread: t.Number() });++// How many rows the bulk read-all and delete routes touched.+export const AffectedCountResponse = t.Object({ count: t.Number() });++export const listNotificationsQuery = t.Object({+ limit: t.Optional(t.String({ description: 'Max items per page (1-100). Default 30.' })),+ cursor: t.Optional(t.String({ description: 'nextCursor from the previous page.' })),+ types: t.Optional(t.String({ description: 'Comma-separated notification types to include.' })),+ from: t.Optional(t.String({ description: 'Filter by actor user id.' })),+ projectId: t.Optional(t.String({ description: 'Filter by project id.' })),+ includeRead: t.Optional(t.String({ description: "'false' hides read. Default true." })),+ includeSnoozed: t.Optional(t.String({ description: "'true' shows snoozed. Default false." })),+});++export const unreadCountQuery = t.Object({+ projectId: t.Optional(t.String({ description: 'Scope the count to one project.' })),+});++export const markAllReadBody = t.Optional(t.Object({ projectId: t.Optional(t.Number()) }));++export const deleteNotificationsQuery = t.Object({+ scope: t.Optional(+ t.Union([t.Literal('all'), t.Literal('read'), t.Literal('read-completed')], {+ description: 'Which notifications to delete. Default read.',+ }),+ ),+ projectId: t.Optional(t.String({ description: 'Scope the delete to one project.' })),+});++export const setNotificationReadBody = t.Optional(t.Object({ read: t.Optional(t.Boolean()) }));++export const snoozeNotificationBody = t.Object({ until: t.Nullable(t.String()) });++export const sendDeliveryBody = t.Object({+ projectId: t.Number(),+ channel: t.UnionEnum(['email', 'telegram']),+ recipient: t.Nullable(t.String()),+ payload: t.Object({+ subject: t.Optional(t.String()),+ text: t.String(),+ // The Telegram body. Elysia strips fields the schema does not declare, so+ // leaving it out here would silently drop the formatted message and send the+ // plain-text fallback instead.+ html: t.Optional(t.String()),+ url: t.Optional(t.String()),+ }),+});diff --git a/apps/api/src/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.tssimilarity index 95%rename from apps/api/src/notifications/outbound.tsrename to apps/api/src/modules/notifications/outbound.tsindex ad8a2829..cee51ac0 100644--- a/apps/api/src/notifications/outbound.ts+++ b/apps/api/src/modules/notifications/outbound.ts@@ -1,11 +1,11 @@import { db, notificationDelivery, issue, issueActivity, project, user } from '@repo/db';import { eq, inArray } from 'drizzle-orm';import { getProjectEmailConfig } from '@repo/auth';-import { emailSource, readRedactedSettings } from '../notification-settings/store';-import { getPreferencesForUsers } from '../notification-preferences/store';-import { getTelegramChatIds, hasUsableInstanceBot } from '../telegram/store';-import { escapeHtml } from '../shared/lib';-import type { NotificationType, NewNotificationRow } from './store';+import { emailSource, readRedactedSettings } from '#modules/notification-settings/service';+import { getPreferencesForUsers } from '#modules/notification-preferences/service';+import { getTelegramChatIds, hasUsableInstanceBot } from '../../telegram/store';+import { escapeHtml } from '#shared/lib';+import type { NotificationType, NewNotificationRow } from './service';// Outbound notification delivery: turns the inbox notification rows produced by an// issue event into notification_delivery outbox rows. Delivery is per member and perdiff --git a/apps/api/src/notifications/send.ts b/apps/api/src/modules/notifications/send.tssimilarity index 96%rename from apps/api/src/notifications/send.tsrename to apps/api/src/modules/notifications/send.tsindex 50f15e20..1f2279e9 100644--- a/apps/api/src/notifications/send.ts+++ b/apps/api/src/modules/notifications/send.ts@@ -1,8 +1,8 @@import { sendEmail, emailBody, type EmailConfig, type SendResult } from '@repo/mailer';import { getProjectEmailConfig } from '@repo/auth';-import { emailSource, type NotificationConfig } from '../notification-settings/store';+import { emailSource, type NotificationConfig } from '#modules/notification-settings/service';import type { DeliveryPayload } from './outbound';-import { getInstanceBotConfig, isInstanceBotUsable } from '../telegram/store';+import { getInstanceBotConfig, isInstanceBotUsable } from '../../telegram/store';// Sends one composed notification over the requested channel using the project's// decrypted config. Email transport lives in @repo/mailer (shared with thediff --git a/apps/api/src/notifications/store.ts b/apps/api/src/modules/notifications/service.tssimilarity index 98%rename from apps/api/src/notifications/store.tsrename to apps/api/src/modules/notifications/service.tsindex b193694e..3334d76a 100644--- a/apps/api/src/notifications/store.ts+++ b/apps/api/src/modules/notifications/service.ts@@ -10,8 +10,8 @@ import {} from '@repo/db';import { and, desc, eq, inArray, lt, or, sql, isNull } from 'drizzle-orm';import { parseMentions } from '#modules/agents/core/mentions';-import { autoWatchIssue, watcherUserIds } from '../issues/watchers';-import { iso } from '../shared/lib';+import { autoWatchIssue, watcherUserIds } from '../../issues/watchers';+import { iso } from '#shared/lib';import { enqueueOutbound } from './outbound';// Inbox notifications. A notification is one (recipient, event) row: a user is told@@ -22,7 +22,8 @@ import { enqueueOutbound } from './outbound';// notified about their own action, and only project members receive notifications,// so agent bot users (assigned via delegate, not members) are excluded.-export type NotificationType = 'assigned' | 'mentioned' | 'commented' | 'state_changed';+export const NOTIFICATION_TYPES = ['assigned', 'mentioned', 'commented', 'state_changed'] as const;+export type NotificationType = (typeof NOTIFICATION_TYPES)[number];export interface NewNotificationRow {userId: string;diff --git a/apps/api/src/projects/__tests__/integration/projects.test.ts b/apps/api/src/modules/projects/__tests__/integration/projects.test.tssimilarity index 99%rename from apps/api/src/projects/__tests__/integration/projects.test.tsrename to apps/api/src/modules/projects/__tests__/integration/projects.test.tsindex 6077e622..e8f304bb 100644--- a/apps/api/src/projects/__tests__/integration/projects.test.ts+++ b/apps/api/src/modules/projects/__tests__/integration/projects.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 { addProjectMember } from '../../../__tests__/helpers/members';+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';// Full integration flow: a real session against the real (test) database.// Requires the test DB to be up and migrated:diff --git a/apps/api/src/projects/copy.ts b/apps/api/src/modules/projects/copy.tssimilarity index 98%rename from apps/api/src/projects/copy.tsrename to apps/api/src/modules/projects/copy.tsindex 3e6e08f3..bd2599db 100644--- a/apps/api/src/projects/copy.ts+++ b/apps/api/src/modules/projects/copy.ts@@ -19,9 +19,9 @@ import {projectSetting,} from '@repo/db';import { eq, inArray } from 'drizzle-orm';-import { iso } from '../shared/lib';-import { defaultMemberPermissions } from '../shared/permissions';-import { DEFAULT_COLUMNS, type ProjectRow } from './store';+import { iso } from '#shared/lib';+import { defaultMemberPermissions } from '#shared/permissions';+import { DEFAULT_COLUMNS, type ProjectRow } from './service';import { GITHUB_SETTING_KEY } from '#modules/github/service';import { listAgents, createAgent, type NewAgentInput } from '#modules/agents/core/service';import {@@ -34,7 +34,7 @@ import {import { listAgentToolLinks, setAgentTools } from '#modules/agents/tools/service';import { listAgentSchedules, createAgentSchedule } from '#modules/agents/schedules/service';import { nextCronRun } from '#modules/agents/schedules/cron';-import { getObject } from '../shared/s3';+import { getObject } from '#shared/s3';// Which parts of a source project the copy carries over. Each key mirrors a section// of the project settings menu. A key set false skips that entity. Some sections@@ -252,7 +252,7 @@ async function readObjectBytes(key: string): Promise<{ bytes: Buffer; contentTyp// and tools/agents reference are remapped to the copied entities. Entities with side// effects outside the database are copied after that transaction commits: skills copy// their object-store files, agents create their own bot user and API key, and both go-// through the same store functions the UI uses.+// through the same service functions the UI uses.export async function copyProject(sourceProjectId: number,input: { key: string; name: string; description?: string },@@ -633,7 +633,7 @@ export async function copyProject(});// Skills: copy each skill's object-store files into the new project's own prefix,- // then create the row through the same store the UI uses.+ // then create the row through the same service the UI uses.if (inc.skills) {for (const s of await listSkills(sourceProjectId)) {const markdown = await getSkillMarkdown(s.id, sourceProjectId);diff --git a/apps/api/src/projects/routes.ts b/apps/api/src/modules/projects/index.tssimilarity index 53%rename from apps/api/src/projects/routes.tsrename to apps/api/src/modules/projects/index.tsindex bc50a62a..aa5b7c68 100644--- a/apps/api/src/projects/routes.ts+++ b/apps/api/src/modules/projects/index.ts@@ -1,13 +1,32 @@import { Elysia, t } from 'elysia';-import { mcpTool } from '../mcp/generate';-import { noContent } from '../shared/http';-import { HttpError } from '../shared/lib';-import { authContext } from '../shared/auth-context';-import { guards } from '../shared/guards';-import { requireUser } from '../shared/access';-import { isMcpRequest } from '../shared/mcp-request';-import { accessErrors, commonErrors, errors } from '../shared/responses';-import { getMemberContext, listAssigneeCandidates } from '../members/store';+import { mcpTool } from '#mcp/generate';+import { noContent } from '#shared/http';+import { HttpError } from '#shared/lib';+import { authContext } from '#shared/auth-context';+import { guards } from '#shared/guards';+import { requireUser } from '#shared/access';+import { isMcpRequest } from '#shared/mcp-request';+import { accessErrors, commonErrors, errors } from '#shared/responses';+import { getMemberContext, listAssigneeCandidates } from '#modules/members/service';+import { listColumns } from '#modules/columns/service';+import { listIssueTypes } from '#modules/issue-types/service';+import { listLabels, listLabelGroups } from '#modules/labels/service';+import { listCustomFields } from '#modules/custom-fields/service';+import {+ AutoArchiveResponse,+ ProjectBoardResponse,+ ProjectListResponse,+ ProjectResponse,+ ProjectSettingsResponse,+ SubtaskAutomationResponse,+ copyProjectBody,+ createProjectBody,+ listProjectsQuery,+ updateAutoArchiveBody,+ updateProjectBody,+ updateProjectSettingsBody,+ updateSubtaskAutomationBody,+} from './model';import {listProjects,createProject,@@ -20,195 +39,8 @@ import {setAutoArchiveSettings,getSubtaskAutomationSettings,setSubtaskAutomationSettings,- ISSUE_TYPE_PRESET_KEYS,-} from './store';-import { copyProject, COPY_INCLUDE_KEYS } from './copy';-import { listColumns } from '#modules/columns/service';-import { ColumnResponse } from '#modules/columns/model';-import { listIssueTypes } from '../issue-types/store';-import { listLabels, listLabelGroups } from '../labels/store';-import { listCustomFields } from '#modules/custom-fields/service';--const projectBody = t.Object({- key: t.String({ minLength: 1 }),- name: t.String({ minLength: 1 }),- description: t.Optional(t.String()),-});--// Create adds the issue-type preset: which set of types the new project starts with.-// Omitted → "general" (a single Task). Copy takes its types from the source project,-// so the preset applies to create only.-const createProjectBody = t.Composite([- projectBody,- t.Object({- preset: t.Optional(- t.Union(- ISSUE_TYPE_PRESET_KEYS.map((k) => t.Literal(k)),- { description: `Issue-type preset: ${ISSUE_TYPE_PRESET_KEYS.join(', ')}.` },- ),- ),- }),-]);--// Copy adds an optional selection of which parts of the source project to carry over.-// Omitted → the source project's structure (states, types, labels, custom fields,-// views, dashboards, actions), matching the copy's original behavior. Each flag maps-// to a section of the project settings menu; the store force-enables dependencies.-const copyProjectBody = t.Composite([- projectBody,- t.Object({- include: t.Optional(- t.Object(Object.fromEntries(COPY_INCLUDE_KEYS.map((k) => [k, t.Optional(t.Boolean())]))),- ),- }),-]);--// A project DTO (ProjectRow from the store).-const ProjectResponse = t.Object({- id: t.Number(),- key: t.String(),- name: t.String(),- description: t.String(),- mcpEnabled: t.Boolean(),- // The optional sections, toggled in Settings -> General. All on by default; a- // disabled section is hidden in the web app and its rows are kept.- initiativesEnabled: t.Boolean(),- dashboardsEnabled: t.Boolean(),- notesEnabled: t.Boolean(),- cyclesEnabled: t.Boolean(),- subtasksEnabled: t.Boolean(),- checklistsEnabled: t.Boolean(),- issueStatsEnabled: t.Boolean(),- 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.-const ProjectListItemResponse = t.Composite([- ProjectResponse,- t.Object({- role: t.Union([t.Literal('owner'), t.Literal('member')]),- permissions: t.Optional(PermissionMatrix),- }),-]);--// An issue type (IssueTypeRow from issue-types/store).-const IssueTypeResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- name: t.String(),- icon: t.String(),- color: t.String(),- isDefault: t.Boolean(),- position: t.Number(),-});--// A label (LabelRow from labels/store).-const LabelResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- groupId: t.Nullable(t.Number()),- name: t.String(),- color: t.String(),-});--// A label group (LabelGroupRow from labels/store).-const LabelGroupResponse = t.Object({- id: t.Number(),- projectId: t.Number(),- name: t.String(),- color: t.String(),-});--// An assignable candidate (AssigneeCandidate from members/store): a project-// member or an AI agent's bot user.-const AssigneeCandidateResponse = t.Object({- userId: t.String(),- name: t.String(),- email: t.String(),- image: t.Nullable(t.String()),- kind: t.Union([t.Literal('member'), t.Literal('agent')]),- agentKind: t.Nullable(t.Union([t.Literal('external'), t.Literal('internal')])),- restrictedToUserId: t.Nullable(t.String()),-});--// A custom field option (CustomFieldOptionRow from custom-fields/store).-const CustomFieldOptionResponse = t.Object({- id: t.Number(),- value: t.String(),- color: t.String(),- position: t.Number(),-});--// A custom field (CustomFieldRow from custom-fields/store). The board carries every-// field of the project; the client filters by issueTypeId.-const CustomFieldResponse = t.Object({- id: t.Number(),- issueTypeId: t.Nullable(t.Number()),- name: t.String(),- fieldType: t.String(),- showInBody: t.Boolean(),- position: t.Number(),- options: t.Array(CustomFieldOptionResponse),-});--// Auto-archive thresholds (AutoArchiveSettings from the store): days of inactivity-// in a completed/canceled column before the worker archives an issue; null = off.-const AutoArchiveResponse = t.Object({- completedDays: t.Nullable(t.Number()),- canceledDays: t.Nullable(t.Number()),-});--// The subtask automations (SubtaskAutomationSettings from the store).-const SubtaskAutomationResponse = t.Object({- completeParent: t.Boolean(),- closeSubtasks: t.Boolean(),-});--// Which optional sections the project shows (ProjectFeatures from the store).-const FeaturesResponse = t.Object({- initiatives: t.Boolean(),- dashboards: t.Boolean(),- notes: t.Boolean(),- cycles: t.Boolean(),- subtasks: t.Boolean(),- checklists: t.Boolean(),- issueStats: t.Boolean(),-});--// The project's settings: MCP reachability and the enabled sections.-const ProjectSettingsResponse = t.Object({- mcpEnabled: t.Boolean(),- features: FeaturesResponse,-});--// The caller's own role in a project (from MemberContext in members/store). The-// resolved permission matrix is a sibling `permissions` key on the board payload.-const ViewerResponse = t.Object({- role: t.Union([t.Literal('owner'), t.Literal('member')]),-});--// The project board scaffold (GET /projects/:projectKey): the project plus its-// columns, issue types, labels, label groups, assignable users, custom fields, and-// the caller's own effective access. The issues themselves come from-// GET /projects/:projectKey/issues/board.-const ProjectBoardResponse = t.Object({- project: ProjectResponse,- columns: t.Array(ColumnResponse),- issueTypes: t.Array(IssueTypeResponse),- labels: t.Array(LabelResponse),- labelGroups: t.Array(LabelGroupResponse),- assignees: t.Array(AssigneeCandidateResponse),- customFields: t.Array(CustomFieldResponse),- viewer: ViewerResponse,- // The caller's resolved permission matrix (owners get every flag).- permissions: PermissionMatrix,-});+} from './service';+import { copyProject } from './copy';export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Projects'] } }).use(authContext)@@ -221,14 +53,8 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['PrwithPermissions: query.permissions === 'true',}),{- query: t.Object({- permissions: t.Optional(- t.String({- description: "'true' to include the caller's permission matrix per project.",- }),- ),- }),- response: { 200: t.Array(ProjectListItemResponse), ...errors(401) },+ query: listProjectsQuery,+ response: { 200: ProjectListResponse, ...errors(401) },detail: {summary: 'List projects',description:@@ -259,11 +85,6 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr},)- // Creates a new project copying the selected parts of the source project's- // configuration (states, issue types, labels, custom fields, views, dashboards,- // actions, roles, settings, notification providers, webhooks, integrations, tools,- // skills, agents, schedules) but none of its issues. `include` picks the sections;- // omitted, the project structure is copied as before..post('/projects/:projectKey/copy',async ({ project, body, user, set }) => {@@ -355,10 +176,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Prreturn updated;},{- body: t.Object({- name: t.Optional(t.String({ minLength: 1 })),- description: t.Optional(t.String()),- }),+ body: updateProjectBody,projectOwner: true,response: { 200: ProjectResponse, ...commonErrors },detail: {@@ -405,20 +223,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Prreturn { mcpEnabled: current.mcpEnabled, features: projectFeatures(current) };},{- body: t.Object({- mcpEnabled: t.Optional(t.Boolean()),- features: t.Optional(- t.Object({- initiatives: t.Optional(t.Boolean()),- dashboards: t.Optional(t.Boolean()),- notes: t.Optional(t.Boolean()),- cycles: t.Optional(t.Boolean()),- subtasks: t.Optional(t.Boolean()),- checklists: t.Optional(t.Boolean()),- issueStats: t.Optional(t.Boolean()),- }),- ),- }),+ body: updateProjectSettingsBody,projectOwner: true,response: { 200: ProjectSettingsResponse, ...commonErrors },detail: { summary: "Update a project's settings" },@@ -444,10 +249,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr'/projects/:projectKey/settings/auto-archive',({ project, body }) => setAutoArchiveSettings(project.id, body),{- body: t.Object({- completedDays: t.Nullable(t.Integer({ minimum: 1 })),- canceledDays: t.Nullable(t.Integer({ minimum: 1 })),- }),+ body: updateAutoArchiveBody,permission: ['workflow_config', 'edit'],response: { 200: AutoArchiveResponse, ...commonErrors },detail: { summary: "Update a project's auto-archive thresholds" },@@ -469,10 +271,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr'/projects/:projectKey/settings/subtasks',({ project, body }) => setSubtaskAutomationSettings(project.id, body),{- body: t.Object({- completeParent: t.Boolean(),- closeSubtasks: t.Boolean(),- }),+ body: updateSubtaskAutomationBody,permission: ['workflow_config', 'edit'],response: { 200: SubtaskAutomationResponse, ...commonErrors },detail: { summary: "Update a project's subtask automations" },diff --git a/apps/api/src/modules/projects/model.ts b/apps/api/src/modules/projects/model.tsnew file mode 100644index 00000000..c25914b0--- /dev/null+++ b/apps/api/src/modules/projects/model.ts@@ -0,0 +1,165 @@+import { t } from 'elysia';+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 { ISSUE_TYPE_PRESET_KEYS } from './service';+import { COPY_INCLUDE_KEYS } from './copy';++const projectBody = t.Object({+ key: t.String({ minLength: 1 }),+ name: t.String({ minLength: 1 }),+ description: t.Optional(t.String()),+});++// Create adds the issue-type preset: which set of types the new project starts with.+// Omitted → "general" (a single Task). Copy takes its types from the source project,+// so the preset applies to create only.+export const createProjectBody = t.Composite([+ projectBody,+ t.Object({+ preset: t.Optional(+ t.Union(+ ISSUE_TYPE_PRESET_KEYS.map((k) => t.Literal(k)),+ { description: `Issue-type preset: ${ISSUE_TYPE_PRESET_KEYS.join(', ')}.` },+ ),+ ),+ }),+]);++// Copy adds an optional selection of which parts of the source project to carry over.+// Omitted → the source project's structure (states, types, labels, custom fields,+// views, dashboards, actions). Each flag maps to a section of the project settings+// menu; the service force-enables dependencies.+export const copyProjectBody = t.Composite([+ projectBody,+ t.Object({+ include: t.Optional(+ t.Object(Object.fromEntries(COPY_INCLUDE_KEYS.map((k) => [k, t.Optional(t.Boolean())]))),+ ),+ }),+]);++export const updateProjectBody = t.Object({+ name: t.Optional(t.String({ minLength: 1 })),+ description: t.Optional(t.String()),+});++export const listProjectsQuery = t.Object({+ permissions: t.Optional(+ t.String({ description: "'true' to include the caller's permission matrix per project." }),+ ),+});++// A project DTO (ProjectRow from the service).+export const ProjectResponse = t.Object({+ id: t.Number(),+ key: t.String(),+ name: t.String(),+ description: t.String(),+ mcpEnabled: t.Boolean(),+ // The optional sections, toggled in Settings -> General. All on by default; a+ // disabled section is hidden in the web app and its rows are kept.+ initiativesEnabled: t.Boolean(),+ dashboardsEnabled: t.Boolean(),+ notesEnabled: t.Boolean(),+ cyclesEnabled: t.Boolean(),+ subtasksEnabled: t.Boolean(),+ checklistsEnabled: t.Boolean(),+ issueStatsEnabled: t.Boolean(),+ 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.+export const ProjectListResponse = t.Array(+ t.Composite([+ ProjectResponse,+ t.Object({+ role: t.Union([t.Literal('owner'), t.Literal('member')]),+ permissions: t.Optional(PermissionMatrix),+ }),+ ]),+);++// An assignable candidate (AssigneeCandidate from members/service): a project+// member or an AI agent's bot user.+const AssigneeCandidateResponse = t.Object({+ userId: t.String(),+ name: t.String(),+ email: t.String(),+ image: t.Nullable(t.String()),+ kind: t.Union([t.Literal('member'), t.Literal('agent')]),+ agentKind: t.Nullable(t.Union([t.Literal('external'), t.Literal('internal')])),+ restrictedToUserId: t.Nullable(t.String()),+});++// The caller's own role in a project (from MemberContext in members/service). The+// resolved permission matrix is a sibling `permissions` key on the board payload.+const ViewerResponse = t.Object({+ role: t.Union([t.Literal('owner'), t.Literal('member')]),+});++// The project board scaffold (GET /projects/:projectKey): the project plus its+// columns, issue types, labels, label groups, assignable users, custom fields, and+// the caller's own effective access. The issues themselves come from+// GET /projects/:projectKey/issues/board.+export const ProjectBoardResponse = t.Object({+ project: ProjectResponse,+ columns: t.Array(ColumnResponse),+ issueTypes: t.Array(IssueTypeResponse),+ labels: t.Array(LabelResponse),+ labelGroups: t.Array(LabelGroupResponse),+ assignees: t.Array(AssigneeCandidateResponse),+ customFields: t.Array(CustomFieldResponse),+ viewer: ViewerResponse,+ // The caller's resolved permission matrix (owners get every flag).+ permissions: PermissionMatrix,+});++// Which optional sections the project shows (ProjectFeatures from the service).+const FeaturesResponse = t.Object({+ initiatives: t.Boolean(),+ dashboards: t.Boolean(),+ notes: t.Boolean(),+ cycles: t.Boolean(),+ subtasks: t.Boolean(),+ checklists: t.Boolean(),+ issueStats: t.Boolean(),+});++// The project's settings: MCP reachability and the enabled sections.+export const ProjectSettingsResponse = t.Object({+ mcpEnabled: t.Boolean(),+ features: FeaturesResponse,+});++export const updateProjectSettingsBody = t.Object({+ mcpEnabled: t.Optional(t.Boolean()),+ features: t.Optional(t.Partial(FeaturesResponse)),+});++// Auto-archive thresholds (AutoArchiveSettings from the service): days of inactivity+// in a completed/canceled column before the worker archives an issue; null = off.+export const AutoArchiveResponse = t.Object({+ completedDays: t.Nullable(t.Number()),+ canceledDays: t.Nullable(t.Number()),+});++export const updateAutoArchiveBody = t.Object({+ completedDays: t.Nullable(t.Integer({ minimum: 1 })),+ canceledDays: t.Nullable(t.Integer({ minimum: 1 })),+});++// The subtask automations (SubtaskAutomationSettings from the service).+export const SubtaskAutomationResponse = t.Object({+ completeParent: t.Boolean(),+ closeSubtasks: t.Boolean(),+});++export const updateSubtaskAutomationBody = SubtaskAutomationResponse;diff --git a/apps/api/src/projects/store.ts b/apps/api/src/modules/projects/service.tssimilarity index 99%rename from apps/api/src/projects/store.tsrename to apps/api/src/modules/projects/service.tsindex b6e9b184..7481a7f0 100644--- a/apps/api/src/projects/store.ts+++ b/apps/api/src/modules/projects/service.ts@@ -8,14 +8,14 @@ import {projectSetting,} from '@repo/db';import { and, eq } from 'drizzle-orm';-import { iso } from '../shared/lib';+import { iso } from '#shared/lib';import {defaultMemberPermissions,fullPermissions,normalizePermissions,type Permissions,-} from '../shared/permissions';-import { getProjectSetting, setProjectSetting } from '../settings/store';+} from '#shared/permissions';+import { getProjectSetting, setProjectSetting } from '../../settings/store';import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';// Data access for projects: the top-level container that groups its own columns,diff --git a/apps/api/src/share/__tests__/integration/share.test.ts b/apps/api/src/modules/share/__tests__/integration/share.test.tssimilarity index 99%rename from apps/api/src/share/__tests__/integration/share.test.tsrename to apps/api/src/modules/share/__tests__/integration/share.test.tsindex 0305bed2..8410a926 100644--- a/apps/api/src/share/__tests__/integration/share.test.ts+++ b/apps/api/src/modules/share/__tests__/integration/share.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach } from 'bun:test';-import { api, authedApi } from '../../../__tests__/helpers/app';-import { signUpTestUser } from '../../../__tests__/helpers/auth';-import { resetDb } from '../../../__tests__/helpers/db';+import { api, authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';// Public read-only sharing. Enabling sharing on an issue or a saved view sets an// unguessable token; the /share/* GET routes then return a self-contained bundlediff --git a/apps/api/src/share/routes.ts b/apps/api/src/modules/share/index.tssimilarity index 63%rename from apps/api/src/share/routes.tsrename to apps/api/src/modules/share/index.tsindex 1744c0ee..a55c0db7 100644--- a/apps/api/src/share/routes.ts+++ b/apps/api/src/modules/share/index.ts@@ -1,11 +1,20 @@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 { commonErrors, errors } from '../shared/responses';-import { getIssueProjectId } from '../issues/store';-import { getView } from '../views/store';+import { noContent } from '#shared/http';+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 {+ BundleResponse,+ ShareTokenResponse,+ shareExtendedBody,+ shareIssueParams,+ shareTokenParams,+ shareViewParams,+ sharedViewIssueParams,+} from './model';import {enableIssueShare,disableIssueShare,@@ -14,34 +23,7 @@ import {getSharedIssue,getSharedView,getSharedViewIssue,-} from './store';--// The token is a UUID column; validating its format here turns a malformed token-// into a 400 rather than letting it reach Postgres as a 500.-const tokenParams = t.Object({ token: t.String({ format: 'uuid' }) });--// The share link's token, returned when sharing is enabled.-const ShareTokenResponse = t.Object({ token: t.String() });--// How much the link exposes, sent when enabling it. Enabling an already-shared-// entity keeps its token and only changes this; leaving the field out keeps that-// as it stands too, so fetching the link of a live share cannot downgrade it.-const ShareExtendedBody = t.Optional(- t.Object({- extended: t.Optional(- t.Boolean({- description:- 'Expose the full issues (assignees, labels, custom fields, activity) instead of their title, description, state, type, priority, dates, subtasks and links. Omit to leave it unchanged.',- }),- ),- }),-);--// The public read-only bundles mirror the store DTOs (project scaffold + entity),-// which the read-only web pages type themselves. They are self-contained reads,-// so the response is passed through rather than re-declaring the five feature DTOs-// they compose.-const BundleResponse = t.Any();+} from './service';export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share'] } }).use(authContext)@@ -69,8 +51,8 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return { token };},{- params: t.Object({ issueId: t.Numeric() }),- body: ShareExtendedBody,+ params: shareIssueParams,+ body: shareExtendedBody,workItem: 'edit',response: { 200: ShareTokenResponse, ...commonErrors },detail: { summary: 'Enable issue sharing' },@@ -85,7 +67,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return noContent();},{- params: t.Object({ issueId: t.Numeric() }),+ params: shareIssueParams,workItem: 'edit',response: { 204: t.Void(), ...commonErrors },detail: { summary: 'Revoke issue sharing' },@@ -100,8 +82,8 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return { token };},{- params: t.Object({ viewId: t.Numeric() }),- body: ShareExtendedBody,+ params: shareViewParams,+ body: shareExtendedBody,savedView: 'edit',response: { 200: ShareTokenResponse, ...commonErrors },detail: { summary: 'Enable view sharing' },@@ -116,7 +98,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return noContent();},{- params: t.Object({ viewId: t.Numeric() }),+ params: shareViewParams,savedView: 'edit',response: { 204: t.Void(), ...commonErrors },detail: { summary: 'Revoke view sharing' },@@ -133,7 +115,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return bundle;},{- params: tokenParams,+ params: shareTokenParams,response: { 200: BundleResponse, ...errors(400, 404) },detail: { summary: 'Get a shared issue' },},@@ -147,7 +129,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return bundle;},{- params: tokenParams,+ params: shareTokenParams,response: { 200: BundleResponse, ...errors(400, 404) },detail: { summary: 'Get a shared view' },},@@ -161,7 +143,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']return bundle;},{- params: t.Object({ token: t.String({ format: 'uuid' }), issueId: t.Numeric() }),+ params: sharedViewIssueParams,response: { 200: BundleResponse, ...errors(400, 404) },detail: { summary: 'Get an issue from a shared view' },},diff --git a/apps/api/src/modules/share/model.ts b/apps/api/src/modules/share/model.tsnew file mode 100644index 00000000..d8da778f--- /dev/null+++ b/apps/api/src/modules/share/model.ts@@ -0,0 +1,33 @@+import { t } from 'elysia';++// The token is a UUID column; validating its format here turns a malformed token+// into a 400 rather than letting it reach Postgres as a 500.+const token = t.String({ format: 'uuid' });++export const shareIssueParams = t.Object({ issueId: t.Numeric() });+export const shareViewParams = t.Object({ viewId: t.Numeric() });+export const shareTokenParams = t.Object({ token });+export const sharedViewIssueParams = t.Object({ token, issueId: t.Numeric() });++// The share link's token, returned when sharing is enabled.+export const ShareTokenResponse = t.Object({ token: t.String() });++// How much the link exposes, sent when enabling it. Enabling an already-shared+// entity keeps its token and only changes this; leaving the field out keeps that+// as it stands too, so fetching the link of a live share cannot downgrade it.+export const shareExtendedBody = t.Optional(+ t.Object({+ extended: t.Optional(+ t.Boolean({+ description:+ 'Expose the full issues (assignees, labels, custom fields, activity) instead of their title, description, state, type, priority, dates, subtasks and links. Omit to leave it unchanged.',+ }),+ ),+ }),+);++// The public read-only bundles mirror the service DTOs (project scaffold + entity),+// which the read-only web pages type themselves. They are self-contained reads,+// so the response is passed through rather than re-declaring the five feature DTOs+// they compose.+export const BundleResponse = t.Any();diff --git a/apps/api/src/share/store.ts b/apps/api/src/modules/share/service.tssimilarity index 94%rename from apps/api/src/share/store.tsrename to apps/api/src/modules/share/service.tsindex 7e32cba5..c6743c36 100644--- a/apps/api/src/share/store.ts+++ b/apps/api/src/modules/share/service.ts@@ -1,22 +1,22 @@import { randomUUID } from 'node:crypto';import { db, issue, projectView } from '@repo/db';import { eq } from 'drizzle-orm';-import { getProjectById, type ProjectRow } from '../projects/store';+import { getProjectById, type ProjectRow } from '#modules/projects/service';import { listColumns } from '#modules/columns/service';-import { listIssueTypes } from '../issue-types/store';-import { listLabels, listLabelGroups } from '../labels/store';+import { listIssueTypes } from '#modules/issue-types/service';+import { listLabels, listLabelGroups } from '#modules/labels/service';import { listCustomFields } from '#modules/custom-fields/service';-import { listAssigneeCandidates } from '../members/store';-import { getIssue, getIssueFieldValues, listIssues, type IssueRow } from '../issues/store';-import { listFeed, type FeedItemRow } from '../issues/activity';+import { listAssigneeCandidates } from '#modules/members/service';+import { getIssue, getIssueFieldValues, listIssues, type IssueRow } from '../../issues/store';+import { listFeed, type FeedItemRow } from '../../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 '../../issues/links';+import { getParentRef, listSubtasks, type IssueRef } from '../../issues/subtasks';+import { applyFilters } from '../../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@@ -114,7 +114,7 @@ function redactIssue<T extends IssueRow>(row: T): T {}// The read-only feed shows the newest activity; a public share never paginates,-// so it is capped at the store's max page (100). An issue with more than that+// so it is capped at listFeed's max page (100). An issue with more than that// shows its latest 100 entries.async function issueFeed(issueId: number): Promise<FeedItemRow[]> {const page = await listFeed(issueId, { limit: 100 });diff --git a/apps/api/src/modules/user-preferences/index.ts b/apps/api/src/modules/user-preferences/index.tsindex a23497e5..d4aeadbf 100644--- a/apps/api/src/modules/user-preferences/index.ts+++ b/apps/api/src/modules/user-preferences/index.ts@@ -3,7 +3,7 @@ import { requireUser } from '#shared/access';import { authContext } from '#shared/auth-context';import { HttpError } from '#shared/lib';import { errors } from '#shared/responses';-import { getMembership } from '../../members/store';+import { getMembership } from '#modules/members/service';import { PreferencePatch, PreferenceResponse } from './model';import { getPreferences, isValidTimezone, updatePreferences } from './service';import { localeFromAcceptLanguage } from './locale';diff --git a/apps/api/src/notification-settings/routes.ts b/apps/api/src/notification-settings/routes.tsdeleted file mode 100644index aaa7aef6..00000000--- a/apps/api/src/notification-settings/routes.ts+++ /dev/null@@ -1,100 +0,0 @@-import { Elysia, t } from 'elysia';-import { guards } from '../shared/guards';-import { authContext } from '../shared/auth-context';-import { accessErrors, commonErrors } from '../shared/responses';-import { getProjectEmailConfig } from '@repo/auth';-import {- ENCRYPTION_MODES,- getNotificationSettings,- setNotificationSettings,- type NotificationSettingsDto,-} from './store';--const encryption = t.UnionEnum([...ENCRYPTION_MODES]);--// The redacted settings DTO (NotificationSettingsDto): the project's provider-// credentials. Secrets are never returned; each is replaced by a boolean telling-// whether a value is stored.-const NotificationSettingsResponse = t.Object({- // Deliver email through the instance provider instead of the project's own.- system: t.Object({ enabled: t.Boolean() }),- // Whether that instance provider exists and is shared with projects right now.- // The project cannot see or change it, so the UI states why sending is off.- systemAvailable: t.Boolean(),- 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() }),- telegram: t.Object({ enabled: t.Boolean(), hasBotToken: t.Boolean() }),-});--// The write body: every section optional so each provider card can save on its own.-// Secret fields are optional and, when omitted or empty, keep their stored value.-const NotificationSettingsBody = t.Object({- system: t.Optional(t.Object({ enabled: t.Boolean() })),- 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()) })),- telegram: t.Optional(t.Object({ enabled: t.Boolean(), botToken: t.Optional(t.String()) })),-});--// Adds whether the instance provider is available to projects right now. It is an-// instance setting, so it is reported alongside the project's own settings rather-// than stored with them.-async function withSystemAvailability(settings: NotificationSettingsDto) {- return { ...settings, systemAvailable: (await getProjectEmailConfig()) !== null };-}--// Notification provider credentials carry secrets (SMTP password, Resend key,-// Telegram bot token), so they are managed only through the session UI and not-// exposed as MCP tools. Gated under the danger_zone resource, the project-level-// settings gate. A member's own delivery preferences live in notification-preferences.-export const notificationSettingsRoutes = new Elysia({- name: 'notification-settings',- detail: { tags: ['Settings'] },-})- .use(authContext)- .use(guards)-- .get(- '/projects/:projectKey/notification-settings',- async ({ project }) => withSystemAvailability(await getNotificationSettings(project.id)),- {- permission: ['danger_zone', 'read'],- response: { 200: NotificationSettingsResponse, ...accessErrors },- detail: {- summary: 'Get notification provider settings',- description: "Get a project's notification provider settings (secrets redacted).",- },- },- )-- .put(- '/projects/:projectKey/notification-settings',- async ({ project, body }) =>- withSystemAvailability(await setNotificationSettings(project.id, body)),- {- body: NotificationSettingsBody,- permission: ['danger_zone', 'edit'],- response: { 200: NotificationSettingsResponse, ...commonErrors },- detail: {- summary: 'Update notification provider settings',- description: "Update a project's notification provider settings.",- },- },- );diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.tsindex 6fea32c6..ef8cd792 100644--- a/apps/api/src/planner.ts+++ b/apps/api/src/planner.ts@@ -1,13 +1,13 @@import { Elysia } from 'elysia';import { HttpError, pgErrorCode } from './shared/lib';import { authContext } from './shared/auth-context';-import { projectRoutes } from './projects/routes';-import { memberRoutes } from './members/routes';+import { projectRoutes } from './modules/projects';+import { memberRoutes } from './modules/members';import { roleRoutes } from './roles/routes';-import { inviteRoutes } from './invites/routes';+import { inviteRoutes } from './modules/invites';import { columnRoutes } from './modules/columns';-import { issueTypeRoutes } from './issue-types/routes';-import { labelRoutes } from './labels/routes';+import { issueTypeRoutes } from './modules/issue-types';+import { labelRoutes } from './modules/labels';import { aiAgentRoutes } from './modules/agents/core';import { integrationRoutes } from './modules/agents/integrations';import { agentSkillRoutes } from './modules/agents/skills';@@ -19,21 +19,21 @@ import { cycleRoutes } from './modules/cycles';import { attachmentRoutes } from './modules/attachments';import { avatarRoutes } from './modules/avatars';import { viewRoutes } from './views/routes';-import { shareRoutes } from './share/routes';+import { shareRoutes } from './modules/share';import { actionRoutes } from './modules/actions';import { webhookRoutes } from './webhooks/routes';import { githubSettingsRoutes } from './modules/github';import { dashboardRoutes } from './modules/dashboards';-import { noteBoardRoutes } from './note-boards/routes';+import { noteBoardRoutes } from './modules/note-boards';import { analyticsRoutes } from './modules/analytics';import { settingsRoutes } from './settings/routes';import { godRoutes } from './god/routes';import { agentScheduleRoutes } from './modules/agents/schedules';import { agentRunnerRoutes } from './modules/agents/runner';import { agentChatRoutes } from './modules/agents/chat';-import { notificationRoutes } from './notifications/routes';-import { notificationSettingsRoutes } from './notification-settings/routes';-import { notificationPreferenceRoutes } from './notification-preferences/routes';+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';diff --git a/apps/api/src/settings/routes.ts b/apps/api/src/settings/routes.tsindex 94519bb5..a71e0cec 100644--- a/apps/api/src/settings/routes.ts+++ b/apps/api/src/settings/routes.ts@@ -6,7 +6,7 @@ import { getHotkeySettings, HotkeyCombosSchema } from './hotkeys';import { getAppVersion } from './updates';// Routes for global instance settings (app_setting): a key-value store not scoped-// to a project. The MCP toggle is per-project (see projects/routes.ts), not here.+// to a project. The MCP toggle is per-project (see modules/projects), not here.//// Storage limits are readable by any signed-in user, because the upload UI shows// them before a file is picked. Changing them is god mode (/god/storage-settings).diff --git a/apps/api/src/settings/store.ts b/apps/api/src/settings/store.tsindex b8405cdb..f17807ba 100644--- a/apps/api/src/settings/store.ts+++ b/apps/api/src/settings/store.ts@@ -6,7 +6,7 @@ import { and, eq, sql } from 'drizzle-orm';// Per-project settings (project_setting): the same key-value store scoped to a// project. Typed accessors per key live in the feature that owns the key (e.g.-// auto-archive in projects/store.ts).+// auto-archive in modules/projects/service.ts).export async function getProjectSetting<T>(projectId: number, key: string): Promise<T | null> {const rows = await dbdiff --git a/apps/api/src/shared/access.ts b/apps/api/src/shared/access.tsindex 5773882a..fe7cb42e 100644--- a/apps/api/src/shared/access.ts+++ b/apps/api/src/shared/access.ts@@ -1,6 +1,6 @@import { HttpError } from './lib';-import { getProjectByKey, type ProjectRow } from '../projects/store';-import { getMembership, getMemberContext } from '../members/store';+import { getProjectByKey, type ProjectRow } from '#modules/projects/service';+import { getMembership, getMemberContext } from '#modules/members/service';import { hasPermission, type PermissionAction, type PermissionResource } from './permissions';// The authenticated user carried on the request context. Populated by thediff --git a/apps/api/src/shared/guards.ts b/apps/api/src/shared/guards.tsindex 9df0f5c2..4681910d 100644--- a/apps/api/src/shared/guards.ts+++ b/apps/api/src/shared/guards.ts@@ -8,7 +8,7 @@ import {assertMcpEnabled,type AuthUser,} from './access';-import { getProjectById } from '../projects/store';+import { getProjectById } from '#modules/projects/service';import { isMcpRequest } from './mcp-request';import { HttpError } from './lib';import type { PermissionResource, PermissionAction } from './permissions';diff --git a/apps/api/src/sync/store.ts b/apps/api/src/sync/store.tsindex 14d7b906..3c0ebfb7 100644--- a/apps/api/src/sync/store.ts+++ b/apps/api/src/sync/store.ts@@ -1,6 +1,6 @@import { db, projectMember, projectRole, revision } from '@repo/db';import { and, eq, inArray } from 'drizzle-orm';-import { toMemberContext, type MemberRole } from '../members/store';+import { toMemberContext, type MemberRole } from '#modules/members/service';import { hasPermission, type PermissionResource } from '../shared/permissions';// The revision engine's read side. The counters themselves are written by thediff --git a/apps/web/src/utils/projectPresets.ts b/apps/web/src/utils/projectPresets.tsindex b8e3da3b..b5f091bb 100644--- a/apps/web/src/utils/projectPresets.ts+++ b/apps/web/src/utils/projectPresets.ts@@ -1,6 +1,7 @@// Issue-type presets offered when creating a project. Mirrors ISSUE_TYPE_PRESETS in-// the API (apps/api/src/projects/store.ts), which is what actually seeds the types;-// the copy here exists so the dialog can preview the result before the request.+// the API (apps/api/src/modules/projects/service.ts), which is what actually seeds+// the types; the copy here exists so the dialog can preview the result before the+// request.export type PresetKey =| 'general'| 'software'diff --git a/apps/worker/src/store.ts b/apps/worker/src/store.tsindex a2c4ed87..0239b63f 100644--- a/apps/worker/src/store.ts+++ b/apps/worker/src/store.ts@@ -148,12 +148,13 @@ export async function cleanupOldDeliveries(): Promise<number> {// threshold lives in project_setting under key 'auto_archive' as// { completedDays, canceledDays }; a positive day count enables archiving for that// state group, null/absent disables it (kept in sync with getAutoArchiveSettings in-// apps/api/src/projects/store.ts). Inactivity is measured by issue.updated_at:-// moving to a terminal column bumps it, and any later edit resets the clock, so an-// issue is archived only after the full period with no activity. The ->> is guarded-// by a numeric-string regex so a malformed or missing value is treated as disabled,-// never cast. Returns the ids archived, which the caller uses to drop the agent-// conversation threads of those issues. Idempotent (archived_at IS NULL filter).+// apps/api/src/modules/projects/service.ts). Inactivity is measured by+// issue.updated_at: moving to a terminal column bumps it, and any later edit resets+// the clock, so an issue is archived only after the full period with no activity.+// The ->> is guarded by a numeric-string regex so a malformed or missing value is+// treated as disabled, never cast. Returns the ids archived, which the caller uses+// to drop the agent conversation threads of those issues. Idempotent+// (archived_at IS NULL filter).export async function archiveStaleIssues(): Promise<number[]> {const rows = await db.execute(sql`UPDATE issue idiff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.tsindex 05006487..691e3a1b 100644--- a/packages/db/src/schema/app.ts+++ b/packages/db/src/schema/app.ts@@ -701,10 +701,10 @@ export const userTelegramAccount = pgTable(// Outbox for outbound notification delivery. One row per (recipient, channel,// message) to send for an issue event: an email or a Telegram message to one member.// Rows are enqueued when inbox notifications are created (see-// apps/api/src/notifications/outbound.ts) and drained by the worker following the-// same claim/retry pattern as webhook_delivery. The message text is composed at-// enqueue time and stored in `payload`; the channel credentials are read from-// project_notification_setting at send time. channel is 'email' | 'telegram'+// apps/api/src/modules/notifications/outbound.ts) and drained by the worker+// following the same claim/retry pattern as webhook_delivery. The message text is+// composed at enqueue time and stored in `payload`; the channel credentials are read+// from project_notification_setting at send time. channel is 'email' | 'telegram'// ('email' picks SMTP or Resend from the project config). recipient is the member's// email address for email rows, or their Telegram chat id for telegram rows.export const notificationDelivery = pgTable(