⭐️⭐️⭐️ 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
improvement(api): list cycles across all readable projects (#766)
Ken3086ff0a8de2
diff --git a/apps/api/src/modules/cycles/__tests__/integration/cycles-all.test.ts b/apps/api/src/modules/cycles/__tests__/integration/cycles-all.test.tsnew file mode 100644index 00000000..511c9e6f--- /dev/null+++ b/apps/api/src/modules/cycles/__tests__/integration/cycles-all.test.ts@@ -0,0 +1,157 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { auth } from '@repo/auth';+import { app, authedApi, type Api, createProject } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { addProjectMember } from '#tests/helpers/members';+import { createRole } from '#tests/helpers/roles';++// GET /cycles: the cycles of every project the caller may read cycles in.++function day(offset: number): string {+ const d = new Date();+ d.setUTCDate(d.getUTCDate() + offset);+ return d.toISOString().slice(0, 10);+}++async function setup() {+ await signUpTestUser();+ const user = await signUpTestUser();+ const api = authedApi(user.cookie);+ await createProject(api, { key: 'MKT', name: 'Marketing' });+ await createProject(api, { key: 'OPS', name: 'Operations' });+ return { user, api };+}++function createCycle(api: Api, projectKey: string, name: string, start: number, end: number) {+ return api+ .projects({ projectKey })+ .cycles.post({ name, startDate: day(start), endDate: day(end) });+}++const projectId = async (api: Api, projectKey: string) =>+ (await api.projects({ projectKey }).get()).data!.project.id;++const names = (res: Awaited<ReturnType<Api['cycles']['get']>>) => res.data?.map((c) => c.name);++describe('cross-project cycle list', () => {+ beforeEach(resetDb);++ it('lists the cycles of every project oldest first, each with its project', async () => {+ const { api } = await setup();+ await createCycle(api, 'MKT', 'MKT current', 0, 6);+ await createCycle(api, 'OPS', 'OPS past', -20, -14);+ await createCycle(api, 'OPS', 'OPS next', 7, 13);++ const res = await api.cycles.get();+ const [ownTeam] = (await api.teams.get()).data!;+ expect(res.status).toBe(200);+ expect(names(res)).toEqual(['OPS past', 'MKT current', 'OPS next']);+ expect(res.data![1]).toMatchObject({+ status: 'active',+ projectId: await projectId(api, 'MKT'),+ projectKey: 'MKT',+ projectName: 'Marketing',+ projectRef: expect.stringMatching(/\.MKT$/),+ teamName: ownTeam!.name,+ progress: { completed: 0, canceled: 0, total: 0 },+ });+ expect(names(await api.cycles.get({ query: { status: 'planned' } }))).toEqual([+ 'MKT current',+ 'OPS next',+ ]);+ });++ it("leaves out another person's projects", async () => {+ const { api } = await setup();+ await createCycle(api, 'MKT', 'Secret', 0, 6);+ const other = authedApi((await signUpTestUser()).cookie);++ const res = await other.cycles.get();+ expect(res.status).toBe(200);+ expect(res.data).toEqual([]);+ });++ it('leaves out a project whose role may not read cycles', async () => {+ const { api } = await setup();+ await createCycle(api, 'MKT', 'MKT cycle', 0, 6);+ const reader = await createRole(api, 'MKT', {+ name: 'Reader',+ permissions: { cycles: { read: true } },+ });+ const blind = await createRole(api, 'MKT', { name: 'Blind', permissions: {} });++ expect(names(await (await addProjectMember(api, 'MKT', reader.data!.id)).cycles.get())).toEqual(+ ['MKT cycle'],+ );+ expect(names(await (await addProjectMember(api, 'MKT', blind.data!.id)).cycles.get())).toEqual(+ [],+ );+ });++ it('leaves out a project with cycles turned off', async () => {+ const { api } = await setup();+ await createCycle(api, 'MKT', 'MKT cycle', 0, 6);+ await createCycle(api, 'OPS', 'OPS cycle', 0, 6);+ await api.projects({ projectKey: 'OPS' }).settings.patch({ features: { cycles: false } });++ expect(names(await api.cycles.get())).toEqual(['MKT cycle']);+ });++ it('lists only the project an agent run is bound to', async () => {+ const { user, api } = await setup();+ await createCycle(api, 'MKT', 'MKT cycle', 0, 6);+ await createCycle(api, 'OPS', 'OPS cycle', 0, 6);+ const other = authedApi((await signUpTestUser()).cookie);+ await createProject(other, { key: 'HR', name: 'People' });+ const bound = (id: number) => authedApi(user.cookie, { 'x-agent-project': String(id) });++ expect(names(await bound(await projectId(api, 'MKT')).cycles.get())).toEqual(['MKT cycle']);+ expect(names(await bound(await projectId(other, 'HR')).cycles.get())).toEqual([]);+ });++ it('rejects an unknown status', async () => {+ const { user } = await setup();+ const res = await app.handle(+ new Request('http://localhost/cycles?status=done', { headers: { cookie: user.cookie } }),+ );+ expect(res.status).toBe(400);+ });++ it('serves the list_cycles_all_projects MCP tool over the MCP-enabled projects', async () => {+ const { user, api } = await setup();+ await createCycle(api, 'MKT', 'Visible', 0, 6);+ await createCycle(api, 'OPS', 'Hidden', 0, 6);+ const ops = (await api.projects({ projectKey: 'OPS' }).get()).data!.project;+ await api.teams({ teamId: ops.teamId }).mcp.patch({+ projects: [{ projectId: ops.id, enabled: false }],+ });+ const key = await auth.api.createApiKey({ body: { userId: user.userId, name: 'cycles' } });++ const response = await app.handle(+ new Request('http://localhost/mcp', {+ method: 'POST',+ headers: {+ authorization: `Bearer ${key.key}`,+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'list_cycles_all_projects', arguments: {} },+ }),+ }),+ );+ const text = await response.text();+ const { result } = JSON.parse(text.slice(text.indexOf('data: ') + 6)) as {+ result: { structuredContent: { ok: boolean; data: { name: string }[] } };+ };+ expect(result.structuredContent).toMatchObject({+ ok: true,+ data: [expect.objectContaining({ name: 'Visible', projectKey: 'MKT' })],+ });+ expect(result.structuredContent.data).toHaveLength(1);+ });+});diff --git a/apps/api/src/modules/cycles/index.ts b/apps/api/src/modules/cycles/index.tsindex cba8aedc..ba09ca6f 100644--- a/apps/api/src/modules/cycles/index.ts+++ b/apps/api/src/modules/cycles/index.ts@@ -1,14 +1,16 @@import { Elysia, t } from 'elysia';import { mcpTool } from '#mcp/generate';import { noContent } from '#shared/http';-import { guards, entityGuard } from '#shared/guards';+import { guards, entityGuard, requiresPermission } from '#shared/guards';import { authContext } from '#shared/auth-context';-import { requireUser } from '#shared/access';+import { readableProjectIds, requireUser } from '#shared/access';+import { boundProjectId, isMcpRequest } from '#shared/mcp-request';import { HttpError } from '#shared/lib';-import { accessErrors, commonErrors } from '#shared/responses';+import { accessErrors, commonErrors, errors } from '#shared/responses';import { paginate } from '#shared/pagination';import { transferCycleIssues } from '#modules/issues/service';import {+ CrossProjectCycleListResponse,CycleListResponse,CycleOptionListResponse,CyclePageResponse,@@ -24,6 +26,7 @@ import {} from './model';import {listCycles,+ listCyclesInProjects,listPlannedCycles,listCompletedCycles,getCycle,@@ -124,6 +127,33 @@ export const cycleRoutes = new Elysia({},)+ .get(+ '/cycles',+ async ({ user, query, request }) => {+ const ids = await readableProjectIds(requireUser(user).id, [['cycles', 'read']], {+ mcpOnly: isMcpRequest(request.headers),+ });+ const bound = boundProjectId(request.headers);+ return listCyclesInProjects(+ ids.filter((id) => bound == null || id === bound),+ query.status === 'planned',+ );+ },+ {+ query: listCyclesQuery,+ response: { 200: CrossProjectCycleListResponse, ...errors(400, 401) },+ detail: {+ summary: 'List cycles in all projects',+ description:+ 'The cycles of every project you can read cycles in, oldest first. Each cycle names ' ++ 'its project (projectKey, projectRef, projectName, teamName); use list_cycles for one ' ++ 'project. An agent run lists only the project it works in.',+ ...requiresPermission(['cycles', 'read']),+ ...mcpTool('list_cycles_all_projects'),+ },+ },+ )+.get('/cycles/:cycleId',async ({ params }) => {diff --git a/apps/api/src/modules/cycles/model.ts b/apps/api/src/modules/cycles/model.tsindex 1accd8fc..33155552 100644--- a/apps/api/src/modules/cycles/model.ts+++ b/apps/api/src/modules/cycles/model.ts@@ -35,6 +35,18 @@ export const CycleResponse = t.Object({export const CycleListResponse = t.Array(CycleResponse);+export const CrossProjectCycleListResponse = t.Array(+ t.Composite([+ CycleResponse,+ t.Object({+ projectRef: t.String(),+ projectKey: t.String(),+ projectName: t.String(),+ teamName: t.String(),+ }),+ ]),+);+export const CyclePageResponse = pageResponse(CycleResponse);export const CycleOptionListResponse = t.Array(diff --git a/apps/api/src/modules/cycles/service.ts b/apps/api/src/modules/cycles/service.tsindex 0ff297c6..9e9fef8b 100644--- a/apps/api/src/modules/cycles/service.ts+++ b/apps/api/src/modules/cycles/service.ts@@ -1,6 +1,7 @@-import { db, cycle, issue, projectColumn } from '@repo/db';-import { and, asc, desc, eq, isNull, ne, sql, type SQL } from 'drizzle-orm';+import { db, cycle, issue, project, projectColumn, team } from '@repo/db';+import { and, asc, desc, eq, inArray, isNull, ne, sql, type SQL } from 'drizzle-orm';import { HttpError, iso } from '#shared/lib';+import { projectRefSql } from '#modules/teams/ref';// Data access for cycles: a time-boxed period of work inside a project (a sprint).// Issues link to a cycle through issue.cycle_id. The status is derived from the@@ -125,6 +126,48 @@ export async function listPlannedCycles(projectId: number): Promise<CycleRow[]>return rows.map(mapCycle);}+export interface CrossProjectCycleRow extends CycleRow {+ projectRef: string;+ projectKey: string;+ projectName: string;+ teamName: string;+}++// The cycles of the given projects that have cycles turned on, oldest first, each+// with its project. planned keeps only the active and upcoming ones.+export async function listCyclesInProjects(+ projectIds: number[],+ planned: boolean,+): Promise<CrossProjectCycleRow[]> {+ if (projectIds.length === 0) return [];+ const projects = await db+ .select({+ id: project.id,+ ref: projectRefSql,+ key: project.key,+ name: project.name,+ teamName: team.name,+ })+ .from(project)+ .innerJoin(team, eq(team.id, project.teamId))+ .where(and(inArray(project.id, projectIds), eq(project.cyclesEnabled, true)));+ if (projects.length === 0) return [];+ const byId = new Map(projects.map((p) => [p.id, p]));+ const rows = await selectCycles(+ and(inArray(cycle.projectId, [...byId.keys()]), planned ? sql`not ${FINISHED}` : undefined),+ ).orderBy(asc(cycle.startDate), asc(cycle.id));+ return rows.map((r) => {+ const p = byId.get(r.row.projectId)!;+ return {+ ...mapCycle(r),+ projectRef: p.ref,+ projectKey: p.key,+ projectName: p.name,+ teamName: p.teamName,+ };+ });+}+export interface CyclePage {items: CycleRow[];total: number;