⭐️⭐️⭐️ 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
api (Elysia)
| Before you change | Read |
|---|---|
| roles, workspaces, invites, members, who may do what | docs/dev/access-model.md |
| agents, runs, traces, analytics, runner queue, MCP reach | docs/dev/agents.md |
| SCIM | docs/dev/scim.md |
| test setup, parallel workers | docs/dev/api-tests.md |
Structure
- One folder per domain under
src/modules/, three files:index.ts,model.ts,service.ts. Cross-cutting code is inshared/. index.ts:new Elysia({ name: "<feature>", detail: { tags: ["<Tag>"] } }), routes chained directly on it, each route setsdetail.summary, handlers only.model.ts: thetschemas. An update body ist.Partial(<create body>)where it accepts the same fields.service.ts: plain async functions, no Elysia/HTTP types, returns DTOs never rows.- A feature that needs more adds one file per concern next to them (
emit.ts,run-queue.ts), never a routes file plus a store file. Features nest only where they already call each other (modules/agents). - Imports inside a module are relative (
./model). Everything outside goes through the subpath aliases inapps/api/package.json:#shared/*,#mcp/*,#modules/*,#tests/*. src/app.tsexports the app, no.listen().src/index.tsbinds the port and startssrc/background.ts. Start background jobs fromindex.ts, never from the app, so importing the app in a test starts nothing. A background job must be safe with several api replicas.
Adding a route
- Chain on the same instance. A route added in a separate statement that drops the return value
is missing from Elysia's type inference and from
type App. - Validate all input with
t, from a schema declared in the feature'smodel.ts. Numeric path ids uset.Numeric(); neverNumber(params.x)in the handler. - Enforce access with a guard in the route options. Only a rule no guard can express stays in the
handler, such as a list across projects or a private view: see
requiresPermissionbelow. - Throw
HttpErrorfor failures; return the service DTO on success;noContent()for a delete with no body;set.status = 201on create. - New feature:
.use()it inplanner.tsand register its tag in the swaggerdocumentation.tagslist inapp.ts.
Error model
- Throw
HttpError(status, message)for expected failures. Never hand-build error bodies.onErrormaps it to{ error }, pluscodewhen theHttpErrorhas one. - Unique violation: wrap the insert in
rethrowDuplicate(err, "<what>")→ 409. - A route declares its failure statuses by spreading a map from
shared/responses.tsinto itsresponse:accessErrors(401/403/404) for a guarded read,commonErrors(+400) where it also validates input,errors(...)for anything else ({ ...commonErrors, ...errors(409) }). - Set that map per route. A
guard({ schema: "standalone", response })on the feature passes typecheck but drops the codes from the OpenAPI spec.
Data invariants
- DTOs, not rows.
timestamptz→iso()string;numeric→num();dateis already'YYYY-MM-DD'. - jsonb passes through as JS objects. Never
JSON.stringify; validate only ast.Any(). - Sequence numbers ("MKT-42") are issued under a row lock on
projectinside the transaction ofcreateIssueand ofmoveIssue. Keep the lock. A moved issue's old number goes toissue_key_alias, and the counter never goes back. - The
positionstep differs by table.issue,initiativeand checklists are sparse floats (MAX(position) + 1000). Columns, issue types, custom fields, views, dashboards and actions step by 1. Never assume contiguous values. - A delete relies on the FK actions. A row that cannot exist without its parent uses
cascade; an optional link (assignee, author, cycle, parent issue) usesset null.deleteIssuestill reads attachment rows first to purge objects. - Object-store deletes are best-effort: log a failed
deleteObject, do not fail the request. - A list route either pages or answers with the whole list, never both. A list a picker needs
entire gets an
/optionsroute returning a plain array. A whole-list read only the server needs is a service function of its own. - A paged route takes
...pageQueryFields, answers withpageResponse(...)and wraps its service inpaginate(shared/pagination.ts). The service takes a required{ limit, offset }and returns{ items, total }. - A feed pages by cursor:
limit+cursor/before→{ items, nextCursor }. Rows arrive at its head while a reader is paging. Everything else usespage/pageSize.
Auth and access
Enforced through macros in the route options.
:projectKeyroutes:.use(guards)and setpermission: ["<resource>", "<action>"],projectMember: trueorprojectOwner: true; readprojectfrom context.- Entity-by-id routes (
/issues/:issueId): define a local macro withentityGuard(resource, notFound, resolveProjectId)and set it in the route options (workItem: "edit"). - Team-owned resources (agents, skills, tools, integrations) are under
:teamIdwith theteamPermissionguard. What happens in one project (chat, runs, schedules) stays under:projectKey. - A route that resolves the project itself calls
assertProjectReachable, asentityGuarddoes.assertMcpAllowedalone neither refuses a write to an archived project nor checks the section. - A handler that checks a permission itself spreads
requiresPermission([...])into itsdetail, so the MCP tool table still reports what it requires. - A feature also
.use(authContext)when its handlers or macros referenceuser. Handlers that still needusercallrequireUser(user). Anx-api-keyheader resolves throughgetSession, so no route special-cases it. - Owners bypass the permission matrix; the global
user.role(god|user) does not. Keep at least one owner per project. - Whether the caller may reach something goes through
getProjectAccess/getTeamAccess. Whether someone else is a member (assignees, mentions, recipients, seats, last-owner) reads the rows, so a workspace manager is in no member list. - Member routes use
memberAdminormemberSelfOrAdmin. Grantingowner, or a role with aroleId, is capped:assertProjectAdmin,mayGrantInviteRanks,assertGrantablePermissions. - An invite is checked against its sender when made and again when accepted.
- An agent is never a project owner. An action on an agent that reaches every project it works in
takes
assertFullAgentAccess. There is no instance-level agent and no non-human flag onuser. - A
project_memberrow withsource: 'scim'is refused for edit or removal (409), because the next sync would undo the change. - A
team_memberrow is refused for removal or leaving only while itssourceis'scim'and its role ismember. Its rank can be changed, and the sync then leaves the row alone. GET /attachments/:publicId/rawis public. KeepX-Content-Type-Options: nosniff, forced download outside a strict media allowlist, and the locked-down CSP.GET /share/document/:token/assets/:publicId/rawserves a Docs asset without a session, only while the token is a live link to the page that holds it or to an ancestor that shares its subpages. It sends the same response as the route above.
Tests
bun test with Eden Treaty driving the app in memory against a real test Postgres and real
better-auth sessions. Nothing is mocked. Import app via the helpers, never src/index.ts.
- Tests are colocated under
__tests__/:integration/orunit/. Helpers are insrc/__tests__/helpers/:api,authedApi(cookie),signUpTestUser(),resetDb(). beforeEach(resetDb). Build every precondition through the API. Write to the DB only for a state the API cannot produce, such as a retry that is due now.- Assert through the API (status + DTO via
toMatchObject, side effects via a follow-up read). Read rows only for what no route returns, such as a queued run or a stored ciphertext. - Cover per route: happy path, one valid + one invalid per field rule, boundaries (empty, max/max+1, last-owner), each failure status, and the feature's own access wiring (owner succeeds, non-member 403). Do not re-test the no-session 401 or the permission matrix.
- Confirm each case goes red when the behavior is broken.
- Assert failures on the top-level
status, noterror.status: Treaty narrows it, soHttpErrorcodes fail typecheck there. Read the body fromerror.value. - A DTO date arrives as a
Date: Treaty revivesiso()strings. Assert the value. - The first
signUpTestUserin a test isgod. To act as a plain user, create the god user first and act as the second. - Do not hardcode ids or the "-42" sequence. Read them from the create response.
- A test that runs an internal agent against a model must flush its spans before it ends:
await getMastra().observability.flush(). Late spans count as the next test's runs.
Rules
- Auth logic is in
@repo/auth, DB access via@repo/db. Do not re-instantiate either. - A state-changing request with the session cookie must come from a trusted origin; the
onRequestguard inapp.tsrefuses the rest with 403CSRF_ORIGIN_REJECTED.