Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

docs: trim AGENTS.md to core rules and move the details to docs/dev (#808)

Croffbe165e8331b2
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 0d87c784..32d51368 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -25,7 +25,7 @@ behaviour made right (patch). See CONTRIBUTING.md.
- [ ] Tests added or updated for the changed behaviour
- [ ] Database schema changed: migration generated with `bun run db:generate` and committed
- [ ] New environment variables documented in `.env.example`
-- [ ] Docs updated (`README.md` or the relevant `AGENTS.md`)
+- [ ] Docs updated (`README.md` or `docs/`). `AGENTS.md` changed only as `docs/dev/agents-md.md` allows
## Screenshots
diff --git a/AGENTS.md b/AGENTS.md
index 9ace14cb..5e7e3330 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,249 +1,127 @@
# AGENTS.md
-Bun + Turborepo monorepo. Backend **Elysia**, frontend **Next.js (SSR)** + **shadcn/ui**,
-auth **better-auth**, ORM **Drizzle** + PostgreSQL. Self-hosted with Docker Compose or the
-Helm chart.
-
-The most specific `AGENTS.md` for the changed area overrides this file. Every app and some
-packages have one. Each `CLAUDE.md` only points to the `AGENTS.md` next to it.
-
-## Editing this file
-
-This file holds only the core rules that an agent needs on most tasks.
-
-- Do not add a fix, a feature description, or a detail that only one area needs. Put it in a
- code comment, in `docs/`, or in the `AGENTS.md` of that app or package.
-- Add a rule here only when the user asks.
-
-## Core Coding Principles
-
-- **IMPORTANT — always follow, no exceptions:** KISS and YAGNI. Write the simplest thing that
- works. Add an abstraction only when several concrete implementations need it. No
- overengineering.
-- Study the existing code first and follow its sound patterns and conventions. Reuse shared
- modules, components, and utilities. Extend them instead of adding a parallel solution.
-- Minimum comments. A comment explains why, the code explains what. Hide the comment and
- read the code: if the code tells the fact, delete the comment.
- - A comment longer than its code is too long.
- - A wrong comment is worse than none. Change or delete a comment in the same edit as its code.
- - Do not copy the comment density of nearby code. This rule wins.
- - Never comment layout or styling: positioning, sticky or overflow behaviour, spacing, why a
- class is set.
- - The full rules and the pass that removes stale comments are in the `tidy` skill.
+It's a Plan, a self-hosted project tracker. Bun + Turborepo monorepo: Elysia api, Next.js (SSR)
+web with shadcn/ui, better-auth, Drizzle + PostgreSQL.
+
+Before you change files in an app or package, read its `AGENTS.md`: `apps/api`, `apps/web`,
+`apps/worker`, `apps/bot`, `packages/auth`, `packages/db`. It overrides this file.
+
+## Rules
+
+- **KISS and YAGNI, no exceptions.** Write the simplest thing that works. Add an abstraction
+ only when several concrete implementations need it.
+- Study the existing code first and follow its patterns. Reuse shared modules, components and
+ utilities. Extend them instead of adding a parallel solution.
+- **Bun only.** `bun install`, `bun run`. Never npm, yarn, or pnpm. Run tasks from the repo root.
+- All code, comments and strings are in English.
+- Cross-package imports use the workspace protocol: `"@repo/db": "workspace:*"`. Packages export
+ raw `.ts` and have no build step. `packages/runner` is the exception: it is published to npm,
+ bundles to `dist/`, and its source uses no Bun APIs because the CLI runs on plain Node.
+- The web app never imports a package. It calls the API over HTTP. Dependencies run
+ `api → @repo/auth → @repo/db → @repo/crypto`.
+- A server-side fetch of a supplied URL goes through `@repo/net`, the SSRF guard.
+- Never skip the pre-commit hook with `--no-verify`. It runs `eslint --fix` and `prettier --write`.
+- Minimum comments. A comment says why; the code says what. No comment longer than its code, none
+ on layout or styling. Change or delete a comment in the same edit as its code. Full rules are
+ in the `tidy` skill.
## When the work is done
-Run on the new code, in this order, without being asked:
-
-1. `tidy`
-2. `code-review`
-3. `security-audit`
-
-Then propose a commit message in chat (format in [Commits](#commits)). Never run
-`git commit` or `git push` unless the user asks.
-
-## Writing style (docs, comments, chat)
-
-Applies to all prose: docs, code comments, commit messages, chat replies.
-
-- Write plainly and literally, in short, direct sentences.
-- No metaphors, personification, or figurative language. Bad: "the parser is the heart of the
- step", "data lives in Postgres", "self-healing queue", "the ticket flows through the
- pipeline". Good: "the parser is the main task of the step", "data is stored in Postgres",
- "a failed donor is retried on the next run".
-- No rhetorical flourishes or drama. Say what a thing does, not how important or elegant it is.
-- Standard terms that began as metaphors (watermark, backlog, queue, pipeline) are fine.
-
-**Write the final state, not the edit history.** When the user changes a decision, rewrite
-docs and comments to describe only the current design.
-
-- Do not write "not X, but Y", "now in the DB instead of in code", "decided", "moved from a
- separate step", "previously we planned". Write Y.
-- Do not explain why a choice replaced an earlier idea from the conversation.
-- Allowed: forward-looking rationale ("column `project_key` is added now so steps 3–4 need no
- migration") and cross-references between sections.
-- Mention a discarded idea only as a lasting "considered and rejected because…" that a future
- reader would otherwise propose again. State it once, plainly.
-
-## Golden rules
-
-- **Runtime is Bun.** Never npm, yarn, or pnpm. Use `bun install` and `bun run`.
-- **All code, comments, and strings are in English.**
-- Cross-package imports use the workspace protocol: `"@repo/db": "workspace:*"`. Packages
- export raw `.ts` (see each package's `exports`). Bun and Next transpile them. No build step.
-- Run tasks from the **repo root** through Turborepo: `bun run dev` / `build` / `typecheck`.
-- The pre-commit hook (`lefthook.yml`) runs `eslint --fix` and `prettier --write` on the
- staged files and stages the result again. Never skip it with `--no-verify`.
-
-## Layout
-
-```
-apps/api Elysia (Bun) — better-auth at /api/auth/*, agent runs :3000
-apps/web Next.js App Router, SSR (not SPA) + shadcn + TanStack Query :3001
-apps/worker webhook and notification delivery, agent schedules, imports
-apps/bot Telegram bot, long polling
-packages/db @repo/db — Drizzle client, schema, migrations, permission matrix, shared config readers
-packages/auth @repo/auth — better-auth server instance + instance auth settings
-packages/crypto @repo/crypto — AES-256-GCM encryption for secrets at rest
-packages/storage @repo/storage — S3 client (RustFS in Compose) for attachment bytes, used by api and worker
-packages/mailer @repo/mailer — SMTP/Resend transport for outbound email
-packages/net @repo/net — SSRF guard for server-side fetches of a supplied URL
-packages/agent-tools @repo/agent-tools — tool definitions for the AI agent runtime
-packages/runner @itsaplan/runner — CLI that runs an external agent's queued tasks on the operator's own machine
-packages/eslint-config @repo/eslint-config — shared ESLint config
-charts/itsaplan Helm chart
-scripts/ `bun run setup` and its tests
-dev-scripts/ dev-stack.sh (switch dev/PR backing services), permission-matrix.sh (permission → route table)
-docs/ see Docs below
-```
-
-Dependency graph: `api → @repo/auth → @repo/db → @repo/crypto`. **The web app never imports
-packages directly.** It talks to the API over HTTP (better-auth client + fetch).
+Run on the new code, in this order, without being asked: `tidy`, `code-review`, `security-audit`.
+Then propose a commit message in chat. Never run `git commit` or `git push` unless the user asks.
-## Docs
+## Writing style (docs, comments, commits, chat)
-| Doc | Read when the task touches |
-| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
-| `docs/development.md` | local setup, `bun run setup`, running tests, the Docker test gate |
-| `docs/self-hosting.md` | the self-hosting compose stack, `.env` for a domain, TLS proxy |
-| `docs/coolify.md` | `docker-compose.coolify*.yml` |
-| `docs/railway.md` | the Railway template |
-| `docs/helm.md`, `charts/itsaplan/README.md` | the Helm chart and its values |
-| `docs/runner.md` | `packages/runner` and its agent presets |
-| `docs/agent-endpoint.md` | external agents that receive tasks on their own HTTPS endpoint |
-| `docs/mcp-results.md` | the shape of MCP tool results (`structuredContent`) |
-| `docs/importing-from-linear.md`, `docs/dev/linear-import.md` | the Linear import: user guide, implementation |
-| `docs/importing-from-trello.md`, `docs/dev/trello-import.md` | the Trello import: user guide, implementation |
-| `docs/importing-from-plane.md`, `docs/dev/plane-import.md`, `docs/dev/plane-import-source-notes.md` | the Plane import: user guide, implementation, Plane API facts |
-| `docs/dev/revision-engine.md` | live updates: scopes, counters, refetch |
-| `docs/dev/i18n.md` | interface languages, the language cookie |
+- Plain, literal, short sentences. No metaphors, personification or drama. Bad: "data lives in
+ Postgres", "self-healing queue". Good: "data is stored in Postgres", "a failed donor is retried
+ on the next run". Standard terms (queue, pipeline, backlog, watermark) are fine.
+- Write the final state, not the edit history. Do not write "not X, but Y", "previously",
+ "moved from", "decided".
+- Forward-looking rationale is allowed ("column `project_key` is added now so steps 3–4 need no
+ migration"). A discarded idea appears only as a lasting "considered and rejected because…".
## Commands (from root)
-| Command | Purpose |
-| ------------------------- | ------------------------------------------------------------------ |
-| `bun run dev` | api, web, worker and bot in watch mode (turbo) |
-| `bun run build` | build all apps |
-| `bun run typecheck` | tsc in every workspace member, then at the root |
-| `bun run lint` | ESLint across the workspace |
-| `bun run format:check` | Prettier check (CI runs the same) |
-| `bun run test` | `scripts/` tests, then every member's suite (see Gotchas) |
-| `bun run db:generate` | generate SQL migrations from Drizzle schema |
-| `bun run db:migrate` | apply migrations |
-| `bun run db:migrate:test` | apply migrations to the test DB (`.env.test`) |
-| `bun run db:studio` | Drizzle Studio on the dev DB |
-| `bun run setup` | interactive local setup (see `docs/development.md`) |
-| `bun run auth:generate` | regenerate better-auth tables → `packages/db/src/schema/auth.ts` |
-
-One test file: `cd apps/api && bun test --env-file=../../.env.test <path>`. worker, bot and
-`packages/db` need the same flag. Packages without a database need no flag.
-
-CI (`.github/workflows/ci.yml`) runs on every pull request: `format:check`, `lint`,
-`typecheck`, an app build, and the Docker test gate (`docker-compose.test.yml`). Do not add a
-workflow for a job that an existing workflow already runs.
-
-## Environment
-
-- api, worker, bot, drizzle, and docker-compose read the root `.env` (a copy of
- `.env.example`). Bun apps load it with `--env-file=../../.env`. Drizzle loads it with `dotenv` in
- `drizzle.config.ts`.
-- `apps/web/.env` is **separate**: Next reads env only from its own folder. It holds
- `API_URL` (same value as the root one) and the legal document URLs. web reads them from its
- process at **startup**. Never use `NEXT_PUBLIC_*` for them: `next build` inlines those into
- the bundle, and the image then works for one instance only.
-- Add a new environment variable to `.env.example`. If a service needs it, also add it to the
- five deploy compose files and to the Helm chart: `values.yaml`,
- `templates/configmap.yaml` or `templates/secret.yaml`, and the values table in
- `charts/itsaplan/README.md`.
-
-## Deploy stack
-
-- `docker-compose.dev.yml` holds only the local backing services (Postgres + RustFS). The apps
- run on the host. The deploy composes do NOT publish the DB port.
-- A deploy stack change usually needs an edit in **all five** of `docker-compose.yml`,
- `docker-compose.pro.yml`, `docker-compose.coolify.yml`, `docker-compose.coolify-images.yml`,
- `docker-compose.coolify-pro.yml`, and in the Helm chart.
-- `docker-compose.pro.yml` and `docker-compose.coolify-pro.yml` run the published Pro
- images: migrate from `vendor/itsaplan/packages/db/src/migrate.ts`, start the api with
- `./pro-api`. The Helm chart does the same when `pro: true` (`values-pro.yaml`).
-- Never add `image:` to `docker-compose.coolify.yml`. With both `image:` and `build:` Coolify
+| Command | Purpose |
+| ------------------------- | --------------------------------------------------------- |
+| `bun run dev` | api, web, worker and bot in watch mode |
+| `bun run typecheck` | tsc in every workspace member, then at the root |
+| `bun run lint` | ESLint across the workspace |
+| `bun run format:check` | Prettier check (CI runs the same) |
+| `bun run test` | `scripts/` tests, then every member's suite |
+| `bun run db:generate` | generate SQL migrations from the Drizzle schema |
+| `bun run db:migrate` | apply migrations |
+| `bun run db:migrate:test` | apply migrations to the test DB (`.env.test`) |
+| `bun run auth:generate` | regenerate better-auth tables |
+
+- One test file: `cd apps/api && bun test --env-file=../../.env.test <path>`. worker, bot and
+ `packages/db` need the same flag. Packages without a database need no flag.
+- `bun --filter` needs the `=` form: `bun --filter='@repo/db' run <script>`.
+- Tests are integration tests against a real test Postgres, not mocks. api, bot, worker and
+ `@repo/db` share one test database, and the api suite empties every table before each test, so
+ those suites run one at a time.
+- Do not add a workflow for a job `.github/workflows/ci.yml` already runs.
+
+## Environment and deploy
+
+- api, worker, bot, drizzle and docker-compose read the root `.env`. `apps/web` has its own `.env`:
+ Next reads env only from its own folder.
+- web reads `API_URL` and the legal document URLs from its process at startup. Never use
+ `NEXT_PUBLIC_*` for them: `next build` inlines those, and the image then works for one instance.
+- A new environment variable goes in `.env.example`. If a service needs it, also add it to
+ `docker-compose.yml`, `docker-compose.pro.yml`, `docker-compose.coolify.yml`,
+ `docker-compose.coolify-images.yml` and `docker-compose.coolify-pro.yml`.
+- Add that variable to the Helm chart too: `values.yaml`, `templates/configmap.yaml` or
+ `templates/secret.yaml`, and the values table in `charts/itsaplan/README.md`.
+- A deploy stack change usually needs an edit in the same five compose files and the Helm chart.
+- Never add `image:` to `docker-compose.coolify.yml`: with both `image:` and `build:` Coolify
still builds and stops making rollback images.
-- Migrations run as a separate step before the apps start:
- - Compose: the one-shot `migrate` service. api, worker and bot wait for it.
- - Helm: the `migrate` init container of the api pods. Worker and bot pods wait in a
- `wait-for-migrations` init container.
- - Both run `migrate.ts` from the api image and override the api command, so the api
- container only starts the server.
-- The api image's own CMD also runs the migrations before the server starts. Deploy targets
- with no separate step (Railway, a plain `docker run`) need this.
-- `migrate.ts` first dumps the database into the `db-backups` volume. A failed dump stops the
- run, so no migration runs without a backup. Every run takes a Postgres advisory lock, so
- runs that start together apply each migration only once.
-- Run exactly one `bot` replica: it uses Telegram long polling.
+- Run exactly one `bot` replica. It uses Telegram long polling.
+- Migrations run as a separate step before the apps start. See `docs/dev/deploy-stack.md`.
## Commits
-Subject: Conventional Commit, `type(scope): summary`. PRs are squash-merged, so the PR title
-becomes the commit subject on `main` (`pr-title.yml` checks it). release-please reads the
-subjects to pick the next version and write `CHANGELOG.md`.
-
-Pick the type by what the change gives the user, not by how much code it touches:
-
-- **`feat:` — minor.** A capability that did not exist: a new entity, page, integration, or a
- setting that unlocks behaviour. Use it only for a change that earns a "Highlights" entry.
-- **`improvement:` — patch.** A visible change to something that exists: a redesign, a
- reworked layout, a theme, a better interaction. Not a bug fix, not a new capability.
-- **`fix:` — patch.** Behaviour that was wrong is now right.
-- **Every other type (`perf`, `refactor`, `docs`, `build`, `ci`, `test`, `chore`, `revert`) —
- patch.**
+`type(scope): summary`. PRs are squash-merged, so the PR title becomes the commit subject, and
+release-please reads it to pick the next version.
-Scope: the name of one app or package (`api`, `web`, `worker`, `bot`, `db`, `auth`, …). No
-scope when the change spans several.
+- `feat`: a capability that did not exist, one that earns a "Highlights" entry.
+- `improvement`: a visible change to something that exists. Not a bug fix.
+- `fix`: behaviour that was wrong is now right.
+- `perf`, `refactor`, `docs`, `build`, `ci`, `test`, `chore`, `revert`: everything else.
-While the version is `0.x`, `!` (e.g. `feat!:`) bumps the minor. The major never bumps
-automatically. To cut `1.0.0`, add a `Release-As: 1.0.0` footer to the squash commit body.
+Scope is the name of one app or package, none when the change spans several. Pick the type by what
+the change gives the user. Version bumps and release config traps: `docs/dev/releasing.md`.
-Release config traps:
+## Gotchas
-- Add a new commit type to both `pr-title.yml` and `changelog-sections` in
- `release-please-config.json`. release-please drops a type that is not in
- `changelog-sections` from the release notes.
-- Keep `"package-name": ""` in `release-please-config.json`. Without it, release-please skips
- every release and stops at `There are untagged, merged release PRs outstanding - aborting`.
+- A new workspace member needs `COPY <path>/package.json ./<path>/` in every Dockerfile that
+ installs deps (`apps/api`, `apps/web`, `apps/worker`, `apps/bot`). Without it the Docker build
+ fails while local dev still works.
+- A better-auth config change can change its tables. Run `bun run auth:generate`, then
+ `db:generate` and `db:migrate`.
+- Read the comments in `scripts/setup.ts` before you change it.
-## Gotchas
+## Docs
-- Shared packages have no build step. Their consumers import the source. The exception is
- `packages/runner`, the only member published to npm. It bundles to `dist/`
- (`bun build --target=node`), and its source uses no Bun APIs because the published CLI runs
- on plain Node. Publish it by hand (`npm publish` after a `version` bump). release-please
- versions the application, not this package.
-- New workspace member under `packages/*` or `apps/*`: add `COPY <path>/package.json ./<path>/`
- to every Dockerfile that installs deps (`apps/api`, `apps/web`, `apps/worker`, `apps/bot`).
- The install stage copies manifests from an explicit list. A missing line fails
- `bun install --frozen-lockfile` in the Docker build with
- `Workspace dependency "@repo/<name>" not found`, while local dev still works.
-- A better-auth config change in `packages/auth` can change its tables. Run
- `bun run auth:generate`, then `bun run db:generate` and `db:migrate`.
-- Frontend and backend on different domains in prod: adjust cookie `sameSite`/`secure` and
- `APP_URL` (see `packages/auth/AGENTS.md`).
-- Tests use `bun test`. They are integration tests against a real test Postgres
- (`.env.test`), not mocks. `apps/api` uses Eden Treaty. Its setup and test-writing rules are
- in `apps/api/AGENTS.md`. api, bot, worker and `@repo/db` share one test database, and the
- api suite empties every table before each test. So `bun run test` runs those suites one at
- a time (`test:database`), and the other suites alongside them (`test:standalone`).
-- `bun --filter` needs the `=` form: `bun --filter='@repo/db' run <script>`. With the space
- form, Bun reads `run` as the script name and fails.
-- Read the comments in `scripts/setup.ts` before you change it. They give the rules that keep
- the script safe to run again on a live instance.
-
-<!-- BEGIN:turborepo-agent-rules -->
-
-# This is NOT the Turborepo you know
-
-Turborepo configuration, task behavior, and CLI commands can vary between installed versions and may differ from your training data. Resolve the `turbo` package from this file's directory or relevant workspace; in monorepos, it may not be visible from the repository root. For example, run `node -p "require.resolve('turbo/package.json')"` from a workspace that depends on `turbo`.
-
-Read `docs/README.md` inside that installed package first, then read the relevant pages from its `docs/` directory before changing Turborepo configuration or commands. Heed deprecation notices. These bundled docs match the installed package version and are available without network access.
-
-This block is written and re-added by `turbo` before repository-scoped commands when an AI agent is detected. In the Turborepo source repository, its template is defined in `crates/turborepo-cli/src/cli/agent_guidance.rs`. Removing the managed block while updates are enabled means a later qualifying invocation will add it again. Set `"agentGuidance": false` in the root `turbo.json` or `turbo.jsonc` to opt out; this does not remove an existing block. Keep the block committed with your work to avoid an uncommitted change on the next agent invocation.
-<!-- END:turborepo-agent-rules -->
+Read the doc for what your task touches:
+
+| Task touches | Doc |
+| --------------------------------------------- | -------------------------------------------------------------------- |
+| local setup, running tests, the Docker gate | `docs/development.md` |
+| who may do what: roles, workspaces, invites | `docs/dev/access-model.md` |
+| AI agents, runs, traces, the runner queue | `docs/dev/agents.md` |
+| SCIM | `docs/dev/scim.md` |
+| sign-in methods, sessions, API keys, MCP OAuth | `docs/dev/auth.md` |
+| live updates: scopes, counters, refetch | `docs/dev/revision-engine.md` |
+| interface languages | `docs/dev/i18n.md` |
+| imports | `docs/dev/import-worker.md`, `docs/dev/{linear,trello,plane}-import.md` |
+| migrations in deploys, backups | `docs/dev/deploy-stack.md` |
+| commit types, versions, release config | `docs/dev/releasing.md` |
+| self-hosting, Coolify, Railway, Helm | `docs/self-hosting.md`, `docs/coolify.md`, `docs/railway.md`, `docs/helm.md` |
+| the runner, external agents, MCP results | `docs/runner.md`, `docs/agent-endpoint.md`, `docs/mcp-results.md` |
+
+## Changing an AGENTS.md
+
+Read `docs/dev/agents-md.md` first. A line belongs here only if an agent would otherwise break a
+rule it cannot see in the code. Do not add a line to record a fix or a feature. CI checks the
+size limit and the references.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index dd4fd88f..aead5bb8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -35,8 +35,11 @@ packages/mailer SMTP and Resend transport
Dependency direction is `api → @repo/auth → @repo/db`. The web app never imports the
packages directly, it talks to the API over HTTP.
-Each app and package has a `AGENTS.md` with the rules that apply inside it. Read the one
-for the area you are changing.
+Each app, plus `packages/auth` and `packages/db`, has an `AGENTS.md` with the rules that
+apply inside it. Read the one for the area you are changing.
+
+Do not add to an `AGENTS.md` to record a fix or a feature. `docs/dev/agents-md.md` says what
+belongs there.
## Code conventions
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index c7208b90..7a49c309 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -1,577 +1,140 @@
# api (Elysia)
-Elysia server on Bun, port 3000 (`API_PORT`). See root `AGENTS.md` for stack/env.
-Rules and invariants for this package below; read the code for the walkthrough.
+| 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
-- Feature-based: one folder per domain under `src/modules/`, three files —
- `index.ts` (controller), `model.ts` (schemas), `service.ts` (Drizzle). Cross-cutting
- code in `shared/`. See `src/modules/` for the current set.
-- Features nest one level deeper only where they already call each other:
- `modules/agents/{core,chat,runner,schedules,skills,tools}`, where `core` holds the
- agent itself and its runtime. A feature whose links to its neighbours run one way
- stays flat. A schema several of the nested features share sits in the parent's
- `model.ts` and is re-exported from each child's (`agentParams`).
-- `src/app.ts` assembles and exports the app (`export const app`, no `.listen()`);
- `src/index.ts` binds the port and starts `src/background.ts`.
- `export type App = typeof app` types the Eden Treaty client (web + tests).
-- **Background jobs are started from `index.ts`, never assembled into the app**, so
- importing the app in a test starts nothing. `background.ts` drains the `agent_run`
- queue in one loop and runs the auto-archive sweep in a loop of its own, so neither
- waits on the other. Several api replicas run them without overlapping: the queue is
- claimed with `FOR UPDATE SKIP LOCKED`, and the sweep only touches rows it has not
- archived yet. An agent run is built from the queue row alone — the project it works
- in and the bot user it acts as are read there, never handed in.
-- `index.ts`: `new Elysia({ name: "<feature>", detail: { tags: ["<Tag>"] } })` —
- routes chained directly on it, each route sets `detail.summary`. Handlers only;
- the schemas they reference come from `model.ts`.
-- `model.ts`: the `t` schemas of the feature's requests and responses. An update body
- is `t.Partial(<create body>)` where it accepts the same fields.
+- One folder per domain under `src/modules/`, three files: `index.ts`, `model.ts`, `service.ts`.
+ Cross-cutting code is in `shared/`.
+- `index.ts`: `new Elysia({ name: "<feature>", detail: { tags: ["<Tag>"] } })`, routes chained
+ directly on it, each route sets `detail.summary`, handlers only.
+- `model.ts`: the `t` schemas. An update body is `t.Partial(<create body>)` where it accepts the
+ same fields.
- `service.ts`: plain async functions, no Elysia/HTTP types, returns DTOs never rows.
-- Every feature lives under `src/modules/`. A feature that needs more than the three
- files adds one per concern next to them (`emit.ts`, `run-queue.ts`), it does
- not grow a `routes.ts` + `store.ts` pair.
-- Imports inside a module are relative (`./model`); everything it reaches outside
- itself goes through the subpath aliases in `apps/api/package.json` — `#shared/*`,
- `#mcp/*`, `#modules/*`, `#tests/*`. They map to a `.ts` file (`"#shared/*":
-"./src/shared/*.ts"`), which is what makes both `tsc` and Bun resolve them, and they
- resolve against the api's own `package.json`, so they hold in the Docker image where
- the process starts from the repo root. A tsconfig `paths` alias would not: there is
- no tsconfig.json at that root.
+- 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 in `apps/api/package.json`: `#shared/*`, `#mcp/*`, `#modules/*`, `#tests/*`.
+- `src/app.ts` exports the app, no `.listen()`. `src/index.ts` binds the port and starts
+ `src/background.ts`. Start background jobs from `index.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 — never reassign to an intermediate `const` (breaks
- Elysia type inference and `type App`).
-- Validate all input with `t`, from a schema declared in the feature's `model.ts`.
- Numeric path ids use `t.Numeric()`; never `Number(params.x)` in the handler.
-- Enforce access with a guard in the route options, never an imperative call in the
- handler (see Auth and access).
-- Throw `HttpError` for failures; return the service DTO on success; `noContent()` for a
- delete with no body; `set.status = 201` on create.
+- 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's `model.ts`. Numeric path
+ ids use `t.Numeric()`; never `Number(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 `requiresPermission` below.
+- Throw `HttpError` for failures; return the service DTO on success; `noContent()` for a delete
+ with no body; `set.status = 201` on create.
- New feature: `.use()` it in `planner.ts` and register its tag in the swagger
`documentation.tags` list in `app.ts`.
## Error model
-- Throw `HttpError(status, message)` for expected failures (400/404/409/413/502) —
- never hand-build error bodies. `onError` maps it to `{ error }`.
+- Throw `HttpError(status, message)` for expected failures. Never hand-build error bodies.
+ `onError` maps it to `{ error }`, plus `code` when the `HttpError` has one.
- Unique violation: wrap the insert in `rethrowDuplicate(err, "<what>")` → 409.
-- `onError` also maps `t`-schema rejection → 400, `NOT_FOUND` → 404, anything else →
- 500 logged with `[planner]`.
-- A route declares the statuses it can fail with by spreading a map from
- `shared/responses.ts` into its `response`: `accessErrors` (401/403/404) for a
- guarded read, `commonErrors` (+400) where it also validates input, `errors(...)` for
- anything else (`{ ...commonErrors, ...errors(409) }`). Listing the codes per route is
- what puts them in the OpenAPI docs — a `guard({ schema: "standalone", response })`
- on the feature passes typecheck but drops them from the spec.
+- A route declares its failure statuses by spreading a map from `shared/responses.ts` into its
+ `response`: `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()`; `date` is
- already `'YYYY-MM-DD'`.
-- **jsonb** (view `filters`/`display`, action `condition`/`effect`) passes through as
- JS objects — never `JSON.stringify`; validate only as `t.Any()`.
-- **Sequence numbers** ("MKT-42") are issued under a row lock on `project` inside
- the transaction of `createIssue` and of `moveIssue` (`issues/move.ts`) — keep the
- lock so concurrent writes don't collide. A moved issue's old number goes to
- `issue_key_alias`, and `getIssueBySequence` resolves it to the issue in its new
- project. The counter never goes back, so an alias never collides with an issue.
-- **`position` is a sparse float** (`MAX(position) + 1000`); do not assume contiguous
- integers.
-- **Deletes cascade in the DB** (every project/issue-scoped FK is `ON DELETE CASCADE`).
- `deleteIssue` still reads attachment rows first to purge their 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 paged
- route takes `...pageQueryFields` (`page`/`pageSize`, 25 by default), answers with
- `pageResponse(...)` and wraps its service in `paginate` (`shared/pagination.ts`); its
- service takes a required `{ limit, offset }` and returns `{ items, total }`, counted
- beside the window so a page past the end still reports how many there are. A list a
- picker needs entire gets an `/options` route of its own returning a plain array
- (`/teams/:teamId/agent-skills/options`), and a whole-list read only the server needs
- is a service function of its own (`listAllAgentSchedules`). A query flag that
- switches one route between the two makes every caller check which it got.
-- **A feed pages by cursor, not by offset**: `limit` + `cursor`/`before` →
- `{ items, nextCursor }`. Rows arrive at its head while a reader is paging, which
- makes an offset skip or repeat them. Everything else uses `page`/`pageSize`, whether
- the screen shows numbered pages or a "show more" button.
+- **DTOs, not rows.** `timestamptz` → `iso()` string; `numeric` → `num()`; `date` is already
+ `'YYYY-MM-DD'`.
+- **jsonb** passes through as JS objects. Never `JSON.stringify`; validate only as `t.Any()`.
+- **Sequence numbers** ("MKT-42") are issued under a row lock on `project` inside the transaction
+ of `createIssue` and of `moveIssue`. Keep the lock. A moved issue's old number goes to
+ `issue_key_alias`, and the counter never goes back.
+- **The `position` step differs by table.** `issue`, `initiative` and 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) uses `set null`. `deleteIssue` still
+ 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 `/options` route 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 with `pageResponse(...)` and wraps its service
+ in `paginate` (`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 uses `page`/`pageSize`.
## Auth and access
-Enforced declaratively through macros, never imperative calls in handlers.
-
-- **Session:** `authContext` (named plugin) reads the better-auth session once, puts
- `user` on context, throws 401 with none. `planner.ts` gates every planner route;
- a feature also `.use(authContext)` when its handlers/macros reference `user`. An
- `x-api-key` header resolves through `getSession` — no special-casing. A route outside
- the planner that answers without credentials (`/me`) reads the same account through
- `requestUser`, which also takes the MCP OAuth token of a tool call. `authContext`
- also writes `user.last_seen_at` for god's "Last seen", at most once an hour per
- account; `requestUser` alone does not.
-- **Membership:** access is by a `project_member` row (`owner` | `member`), raised by
- the caller's role in the workspace that holds the project. Owners bypass the
- permission matrix; the global `user.role` (`god` | `user`) does **not**. Keep at least
- one owner per project.
-- **Workspace roles reach every team and project of the workspace** without a membership
- row: the owner as an owner of each, an admin with a matrix that only reads. The table
- is `shared/workspace-roles.ts`; `setWorkspaceRoleGrant(role, grant)` changes what a role
- grants or adds a role, for a build that has more. `getProjectAccess` and
- `getTeamAccess` in `shared/access.ts` merge the membership with the grant, and every
- guard reads them. The lists that decide what the caller sees — `listProjects`, the
- team list, `readRevs` — take the reached teams the same way, and answer `via:
-'workspace'` for what the caller reaches only through the workspace. Everything that
- asks whether _someone else_ is a member — assignees, mentions, watchers, notification
- recipients, seats, the last-owner check, SCIM — still reads the rows, so a workspace
- manager is in none of the member lists, gets no notifications and takes no seat.
-- **`:projectKey` routes:** `.use(guards)` and set `permission: ["<resource>",
-"<action>"]` / `projectMember: true` / `projectOwner: true`; read the resolved
- `project` from context.
-- **Entity-by-id routes** (`/issues/:issueId`, `/views/:viewId`, …): define a local
- macro via `entityGuard(resource, notFound, resolveProjectId)` and set it in route
- options (e.g. `workItem: "edit"`). `GET /issues/:issueId` instead asserts
- `assertPermission` on the fetched row, and spreads `requiresPermission([...])` into its
- `detail` so the MCP tool table still reports what it requires. `GET
-/projects/:projectKey/issues/:sequenceNumber` does the same for an old number that
- resolved to an issue now in another project. `POST /issues/:issueId/move` checks the
- target project in the `moveTarget` macro, which reads `projectId` from the body.
- `entityGuard` calls `assertMcpAllowed`, and so does a route that resolves the project
- itself: it applies the per-project MCP toggle, and refuses an object outside
- the project an internal agent's run works in (`x-agent-project`, set by the run's tool
- dispatch).
-- Every guard publishes the pair it asserts as `x-permission` on the route's OpenAPI
- detail, which is where `mcp/generate.ts` reads it — Elysia deletes a macro's own key
- from the route once it expands the macro, so there is nothing else to read it from.
-- Guards/macros wrap the `shared/access.ts` primitives. Handlers that still need
- `user` (project create, invite accept/reject, self-removal) call `requireUser(user)`.
-- **The workspace decides who creates a team in it** (`POST /teams`, `createTeam` in
- `teams/service.ts`, `assertMayCreateTeam` in `workspaces/service.ts`): its owner by
- default, also its admins, or anyone in one of its teams, as its owner sets
- `teamCreation`. `workspaceId` in the body names the workspace and is required. Anyone
- else gets 403.
-- **Every person owns one workspace.** No route creates one: sign-up makes it
- (`@repo/auth`), and `authContext` makes it on the next request for an account that has
- none (`ensurePersonalWorkspace`): the instance owner always, anyone else while
- `personalWorkspaces` is on in the auth settings. There is no shared workspace; every
- team is in the workspace of its owner.
- A build that lets a person own more mounts its own route on `createOwnWorkspace` and
- `workspaceCreation` (`workspaces/service.ts`, which refuse an agent's bot user) and
- raises the number with `setOwnedWorkspaceLimit` (`shared/limits.ts`). When an account is deleted (`deleteAccount`), a workspace it
- owned goes with it while it holds no project and no AI agent; any other passes to the
- instance owner with what the account owned alone in it (`releaseOwnedWorkspaces` in
- `teams/service.ts`). God mode asks about sole-owned projects only outside the account's
- own workspaces. The owner deletes a workspace under the same rule
- (`DELETE /workspaces/:id`, `workspaceDeletion` in `workspaces/service.ts`). No core
- route hands a workspace over; `transferWorkspace` is there for a build that offers it.
- SCIM provisioning creates and attaches accounts across the instance, so it is set up in
- god mode (`/god/scim`); a hosted build also sets it up per workspace with
- `setWorkspaceScim()` from `@repo/auth`, whose routes (`workspaceScim` guard) are each
- workspace owner's (see SCIM below).
-- **A member of the team joins a project directly** (`POST /projects/:key/members`,
- from the candidate list); anyone else joins through an invite, which puts them in
- the team as well. A team invite (`/teams/:teamId/invites`) names no project, so its
- email cannot go through the notification outbox, which belongs to a project:
- `invites/email.ts` sends it at once, without the outbox's retries. One
- pending invite per (team, email) and per (project, email) — partial unique indexes →
- 409, and so is an address already in the team or in the project: accepting such an
- invite would rewrite the membership it already holds, demoting an owner past the
- last-owner check. An expired invite gives way: inviting the address again, or
- renewing it (`.../invites/:inviteId/renew`), replaces it with a new invite under a new
- link. A link is never reissued, and an expired one is neither accepted nor mailed.
- An address takes an invite only where the installed policy admits it
- (`invites/email-policy.ts`, 400 `EMAIL_DOMAIN_NOT_ALLOWED`): by default, one with an
- account always and one without only if it could register. A build that lets a
- workspace keep domains of its own calls `setInviteEmailPolicy` with a check against them.
- The invite dialog's suggestions (`.../invites/candidates`) leave out whom it refuses.
- `members/` removes (last owner protected).
-- The member list of a project is governed by its role matrix **or** by the team that
- owns it: `memberAdmin: ["members_manage", "<action>"]` passes an owner or manager of
- the team without a `project_member` row of their own, and every member route uses it
- — list, add, assign a role, describe, remove. The two that address one member by
- `:userId` use `memberSelfOrAdmin` instead: that member acts on their own row —
- leaving the project, saying what they do in it — with no member permission at all.
- The one standing the member permission does not carry is `owner`: an owner bypasses
- the matrix, so adding one, promoting to one and _inviting_ one all go through the
- same rule — an owner of the project, or an owner or manager of the team that owns it
- (`assertProjectAdmin`, and `mayGrantInviteRanks` for the invite). The team rank is
- stricter still: only a team owner grants, takes or invites `owner` and `manager`
- there. An invite is checked against its sender twice, once when it is made and again
- when it is accepted: the sender can be demoted or deleted while the link is out, and
- a link must not outlive the standing that issued it (409 on accept).
- A custom role is capped the same way: adding, re-roling, inviting or renewing an invite
- with a `roleId` goes through `assertGrantablePermissions`, which refuses a role that
- grants more than the granter holds, and the project's invite list hides the link of
- an invite whose role the viewer could not grant. A project owner, or an owner or
- manager of the team, is not capped. Demoting or removing an owner needs
- `assertProjectAdmin`.
-- `project_member.source` says which path a row came from: `modules/scim/reconcile.ts`
- only ever writes, re-roles or removes its own `'scim'` rows, and `members/` refuses to
- edit or remove one (409) because the next sync would undo the change. A project
- membership it grants comes with a `team_member` row in the owning team, added as a
- plain member — the same order an accepted invite follows. `team_member.source` marks
- that row the same way, and it is removed again once the sync holds no project
- membership of that team; a row someone else created, or one whose rank was raised
- afterwards, stays. `teams/` refuses to remove or leave such a row for the same reason
- `members/` refuses its project one: the rank is the team's to set, the membership
- itself is the identity provider's.
-
-## Team-owned agents
-
-Agents, the skill library, the configured tools and the integration credentials belong
-to the team; the routes are under `:teamId` and use the `teamPermission` guard. What
-stays under `:projectKey` is what happens in one project: an agent's chat, its runs and
-its schedules. `packages/db/AGENTS.md` has the schema side.
-
-Two decisions a reader would otherwise propose again:
-
-- **The team is the boundary.** There is no instance-level agent and no non-human-identity
- flag on the user. An agent is reachable through its team or not at all.
-- **The `ai_agents` permissions are administrative.** A role granting `create` or `edit`
- can make an agent, attach it to the projects the caller sees, and read its key — so
- granting either is granting everything an agent of those projects can reach. Rotating
- the key, editing or deleting the agent, setting its tools or skills, and reading,
- rotating or testing its invocation secret act on it in every project it works in, so
- they also take running the team or being a member of all of them
- (`assertFullAgentAccess`). The agent's `canManage` reports the same rule to the caller,
- so the web hides what the api would refuse. What the agents spent is a resource of its own,
- `agent_usage`, read only, so reading it administers nothing.
-- **An agent's role is its `project_member` row**, per project, set from the project's
- member list like a person's. Attaching an agent joins it on the default system role;
- `members/` refuses to make it an owner, since an owner bypasses the matrix.
-
-Runs of an internal agent are traced. `runtime/observability.ts` holds the one Mastra
-container of the process: an agent built for a run writes no spans on its own, so every
-one is registered with it, and its exporter writes the spans into Mastra's own table on
-the application database. A run names what it belongs to in the trace metadata — the
-agent, the team, the project, the issue and the schedule, and either the queued run with
-its trigger or, for a chat run, the person who asked — which is what `runtime/traces.ts`
-filters on, since the spans carry no foreign keys of ours. How long they are kept is the
-instance setting under god mode (`app_setting` key `agents`); `runtime/trace-retention.ts`
-applies it from the api's background loop. The window applies to whole runs: the sweep
-finds the root spans past it and deletes their traces whole, and the same sweep drops
-the traces of a deleted team.
-
-The same setting holds the longest one run may take (`maxRunSeconds`). An agent can set a
-shorter limit of its own (`ai_agent.run_timeout_sec`), and a workspace ceiling from
-`setLimitsProvider` lowers both. A run that reaches it is aborted and saved as failed with
-the text it had produced. A claim's lease is kept longer than the instance maximum, so the
-poller does not claim a run again while it is still running.
-
-The run traces also back the agent dashboard (`runtime/analytics.ts`) at
-`GET /teams/:teamId/agent-analytics`: runs, tokens and cost by model, agent, project and
-day, over a window and the same span before it. Its owner and managers read every project
-of the team; anyone else the projects where their role grants `agent_usage` `read`
-(`projectsWithPermission` in `shared/access.ts`), since a role is set per project and a
-team-wide figure would show the others. The response names those projects
-(`readableProjects`), and `projectId` narrows the dashboard to one of them.
-`GET /workspaces/:workspaceId/agent-analytics` reads it over every team of a workspace,
-with the teams compared, for its owner and its admins.
-
-Cost is applied in the api, not read from a span. Mastra computes it in a metrics
-pipeline that needs an analytics store its Postgres adapter does not implement, so the
-spans arrive with raw token counts and `runtime/model-pricing.ts` prices them from the
-table `@mastra/observability` bundles for that pipeline (`dist/metrics/pricing-data.json`).
-Its provider ids are the registry `AI_PROVIDERS` mirrors, so a credential's integration
-key matches it directly. The file is outside the package's exports map: a release that
-moves it leaves the table empty, an unpriced call reports no cost, and the dashboard shows
-the tokens without an amount.
-
-A workspace sets its own price for any model in `model_price`, which the dashboards of its
-teams read before the table (`ownPrices` in `analytics.ts`): a model the table lacks, such
-as one behind an OpenAI-compatible proxy, or one bought at another rate. The cost is
-worked out when a dashboard is read, so a price also recounts past calls.
-`modules/agents/prices` serves the list to the workspace's owner and its admins: the
-models it called in the last 90 days with those no price covers first, and the whole
-table, paged, each beside the workspace's own price.
-
-Over MCP the team is resolved from the API key rather than asked for (`mcp/server.ts`):
-an agent's key acts in its own team, a person with one team in theirs, and a person in
-several passes `teamId` after reading `list_teams`.
-
-MCP reach is the team's too. `team.mcp_enabled` opens the team to MCP clients, and
-`project.mcp_enabled` says which of its projects that reach covers; both are written
-from `PATCH /teams/:teamId/mcp`, never from the project. The project guards check both
-through `assertMcpEnabled`, which reads them off the resolved project row — `ProjectRow`
-carries `teamMcpEnabled` from the join it already makes. The team guards check the team
-switch through `assertTeamMcpAllowed`, which is what covers the resources no project
-flag reaches: the agents, the skills, the tools, the roles and the credentials.
-
-## Extension hooks
-
-A build that extends the api, such as the hosted edition, installs these at startup
-before `listen`. A self-hosted instance installs none and runs the defaults. The schedule
-and run setters put their default back when called with no argument, which is how a test
-undoes one.
-
-- `setLimitsProvider`, `setOwnedWorkspaceLimit` (`shared/limits.ts`): a workspace's
- ceilings.
-- `setScheduleTypes`, `setScheduleOptionsCheck`, `setScheduleIssueFilter`
- (`modules/agents/schedules/extension.ts`): schedule types of its own beside `cron` and
- `status`; the `options` it keeps on a schedule, checked on every write and, with the id
- maps, on a project copy; and which issues start a schedule's run. `queueScheduleRuns`
- (`issue-runs.ts`) queues the runs of its types on issues, with the trigger `event`. A
- schedule of a type or with options no installed extension reads (`isScheduleSupported`)
- stays as it is, so it works again once the extension is back, but starts no run and
- answers 409 to an update; only a delete goes through.
-- `setRunAdmission` (`modules/agents/core/run-admission.ts`): the seconds a claimed run
- waits before it starts, asked in the poller and in a runner's claim.
-- `setRunRefusal` (`modules/agents/core/run-refusal.ts`): whether an internal agent works
- at all, asked in the poller before a queued run starts and in `prepareRun` before a chat
- answer. A reason fails the run without a retry, and answers the chat with 403.
-- `onProjectEvent` (`modules/webhooks/emit.ts`): every event the webhooks get, inside the
- request or the run that caused it: the issues and comments, and `agent_run.finished`
- once a run ends, whose `emitRunsCanceled` (`modules/agents/core/run-finished.ts`)
- serves a build that cancels runs of its own.
-- `setRequestTracker` (`shared/request-tracker.ts`): every request, with its declared
- route, params and body, before the guards run; a request it follows gets its status,
- its account and the handler's value back after the handler, before the answer is sent,
- or the status of the error a guard or the handler refused or failed it with.
-
-Functions with no setter, for the routes such a build adds:
-
-- `getAgentAnalytics({ teamIds, projectIds }, days)`
- (`modules/agents/core/runtime/analytics.ts`): the agent dashboard over any set of
- teams, or some of their projects.
-- `tracedRuns(scope, from)`, `analyticsWindow(days)` (same file): the runs the dashboard
- is read from, with the whole trace metadata, and its window, for figures of the
- build's own.
-- `workspaceScope(workspaceId)`, `onlyProject(scope, projectId)` (same file): the scope
- of the workspace dashboard, and a scope narrowed to one project as the team dashboard
- does it.
-- `estimateCost(provider, model, usage, calls, own)` (`runtime/model-pricing.ts`): what
- model calls cost, with `own` from `ownPrices(scope)` (`analytics.ts`) so a workspace's
- prices count.
-- `projectsWithPermission` (`shared/access.ts`): the projects a member may read.
-- `createIssue(project, input, null)` (`modules/issues/service.ts`): an issue no account
- created, such as one a person files through a page the build serves to anyone.
-- `createComment({ issueId, body, authorName })` (`modules/issues/activity.ts`): a comment
- from someone without an account, named `authorName`. Its mentions reach nobody.
-
-## SCIM
-
-`modules/scim/` serves SCIM 2.0 (RFC 7643 / 7644) at `/scim/v2` for an identity provider
-to provision users and groups with. Three things make it unlike every other module:
-
-- **Mounted on the root app in `app.ts`, not under `planner`.** The planner's `authContext`
- answers 401 before the bearer check could run. Authentication is one `resolve` that hands
- the token to `verifyScimToken` from `@repo/auth`, which answers with the provider the
- token belongs to: the instance's (`workspaceId` null) or a workspace's. Every route acts
- for that provider, and every function in `service.ts` takes its `workspaceId`.
-- **Its own error document.** `onError` sits on a parent instance that `.use()`s the routes
- and answers only for paths under `/scim/v2`, handing everything else back to the planner's
- handler. Two reasons for that shape: an `onError` beside the routes widens the inferred
- response type of every one of them with the body it returns (which then reaches the Eden
- client as a success shape), and Elysia propagates the handler to the root app either way.
-- **Bodies are `t.Any()`.** SCIM defines its own schemas and clients send attributes this app
- ignores, so `resource.ts` validates instead and raises `ScimError`, which carries the
- `scimType` a provisioning client branches on. Responses are declared per route from
- `model.ts` — `scimErrors(...)` is the SCIM-shaped counterpart of `shared/responses.ts`.
-
-Filtering is `<attribute> eq "<value>"` only, over the attributes each resource lists in
-`service.ts`; that is what Okta, Entra and Authentik send, and `ServiceProviderConfig`
-advertises exactly that. A create inserts the `user` row directly, the way `createAgent`
-does, which deliberately skips the registration gate — with SCIM on, the identity provider
-brings people in, and that is what makes `registration: 'closed'` plus SSO work.
-
-An account is one `user` row across the instance. What a provider says about a person — its
-own id for them and whether they are active — is a `scim_user` row per (provider, user), where
-`workspace_id` is null for the instance's provider. Groups belong to a provider
-(`scim_group.workspace_id`, null for the instance's), their names are unique within it, and
-their members must be accounts it sees. A create for an address that has an account links
-it. The group mappings are in `scim/mappings.ts`; they and the settings are served from god
-mode (`/god/scim/...`) and, for a workspace, from `modules/workspaces/` (`/workspaces/:id/scim/...`).
-
-- **The instance's provider** is god's, set up in god mode, and every build has it. Its
- token reads `scim_<secret>`. The provider sees every account, PUT and PATCH write the name
- and address, a group maps to any project, and DELETE removes the account the way god mode
- does (409 for the only owner of a project outside the workspaces they own, whose projects
- pass to the instance owner).
- A deactivated account (`user.active` false, written alongside `scim_user.active`) keeps
- its teams and projects but cannot sign in, and `isAccountDeactivated` makes
- `authContext`, `/me` and the MCP key check refuse what it already holds.
- God mode writes `user.active` too (`POST /god/users/:userId/deactivate` and
- `/reactivate` in `modules/god/`) while the instance's provider does not manage accounts
- (`accountsManagedByScim` from `@repo/auth`), and answers 409 while it does. Deactivating
- there also deletes the account's sessions, its MCP OAuth tokens and the pending invites
- it created; its API keys are kept and answer 401 until it is reactivated. The instance
- owner and an agent's account are refused (403). The user list and detail carry
- `activeLock` (`owner`, `agent` or `scim`), the reason the switch is locked, or null.
-- **A workspace's provider**, where a hosted build turns `setWorkspaceScim()` on, decides
- who is in the workspace, not who has an account, so the same person can be linked by
- several workspaces. Its token reads `scim_<workspaceId>_<secret>`. It sees the accounts it
- linked and the people in the workspace's teams (`inWorkspace` in `service.ts`), a name or
- address it sends is accepted and the account keeps its own, and a group maps to projects
- of its workspace only. The instance's groups grant nothing in a workspace that set up
- SCIM of its own (`workspacesWithOwnScim`): `reconcile.ts` leaves them out there, the
- mapping picker leaves its projects out, and turning that workspace's SCIM on or off
- reconciles its mapped projects (`reconcileWorkspaceGrants` in `scim/mappings.ts`).
-
-A create first asks the installed policy whether the provider may provision the address
-(`email-policy.ts`, with `workspaceId` null for the instance's). By default it allows any
-address, since only god sets up the instance's provider; a hosted build calls
-`setScimEmailPolicy` with a check against the domains a workspace has verified, and a refused
-address answers 400 `invalidValue`.
-
-Set up per workspace, deactivation (`active: false`) and DELETE take the person out of every
-team of the workspace through `dropWorkspaceMemberships` in `teams/service.ts`, invite memberships
-included, and a team or project they owned alone passes to the workspace owner. Neither
-touches the account or its sessions. A deactivated person stays linked, so the provider can
-turn them back on, and `reconcile.ts` grants them nothing through the groups until then.
-
-The `god`-role account is refused (409), because nothing about the instance owner is
-provider-owned; set up per workspace, so is the workspace owner, who receives what a
-deprovisioned person owned alone. A create for an address the provider already linked
-with an `externalId` is refused the same way — it is a retry, not a new person, and must not
-overwrite the link the first create wrote.
-
-A group member removal arrives in two shapes: `path: 'members'` with the id(s) to drop in
-`value`, or RFC 7644 §3.5.2.2's path filter, `path: 'members[value eq "<id>"]'`, which Okta
-sends and which carries no `value` at all. `resource.ts`'s `memberFilterIds` reads the
-second shape; a `PATCH /Groups/:id` remove that only checked `value` would silently drop
-nothing for a provider that sends the filter form.
-
-The `scim_group` / `scim_group_member` tables have two writers, not one. A SCIM sync is
-the obvious one, but a group can also be embedded right on a resource instead of pushed on
-its own: `resource.ts`'s `groupDisplayNames` reads a SCIM User's `groups` attribute, and
-`oidc-sync.ts` reads an OIDC sign-in's `groups` claim off the ID token stored on the linked
-`account` row, decoded with no signature check since it already crossed a trusted, TLS
-channel and is read only for a claim, not for authentication. Both funnel into
-`syncEmbeddedGroups`, the same additive-only join a group pushed through `POST /Groups`
-gets — a name missing from a later sync is never removed by this path, only by an explicit
-`PATCH /Groups/:id` or an unmapping in the workspace settings.
-
-## Issue agent runs
-
-`GET /issues/:issueId/agent-runs` reads triggered runs with cursor pagination. Both
-`work_items read` and `ai_agents read` in the issue's current project are required.
-Runs keep their original project, so a moved issue does not expose its former project's
-prompts or traces. `/issues/:issueId/agent-runs/:runId/trace` reads the latest recorded
-attempt of that run, or the one named by `traceId`. Each trace links to the previous recorded
-attempt. A missing latest trace returns null; an unknown or unrelated `traceId` returns 404.
-Both permission checks and the read use the same resolved project id. Other people's chat
-traces stay private.
-External runners reporting run events also retain messages, tool inputs/results and a
-local Codex session link per attempt. `GET /agent-runs/:runId/trace?attempt=N` uses
-both read permissions in the original project and excludes moved issues. It also
-serves scheduled/manual runs without an issue. The latest recorded attempt is the default. `GET /agent-runs/:runId/internal-trace` is its counterpart for an internal run: the Mastra trace of the run, read by the run alone, with the same permissions. The runner queue lists active and past runs of internal and external agents; `runId` narrows it to one authorized run for the detail pane. External transcripts follow the instance trace retention window after the run finishes; pending runs and final results are retained.
-`POST /agent-runs/:runId/events` accepts only the calling agent's current executing,
-unexpired attempt. Event offsets deduplicate retries and reject gaps. Transcripts
-stop recording after 2,000 events or 1 MB; acknowledgements continue so the runner
-can report its final result. A Codex UUID forms the local `codex://threads/` link;
-no supplied URL is accepted. The event-capable runner also sends the attempt number
-on heartbeat and result calls, so a reclaimed attempt rejects the old process.
-Legacy clients may omit this field for compatibility.
-
-## Security
-
-- **`GET /attachments/:publicId/raw` is public and unauthenticated** (used in
- `<img>`/`<video>`). Preserve its defenses if you touch it: `X-Content-Type-Options:
-nosniff`, forced download outside a strict media allowlist, locked-down CSP.
+Enforced through macros in the route options.
+
+- **`:projectKey` routes:** `.use(guards)` and set `permission: ["<resource>", "<action>"]`,
+ `projectMember: true` or `projectOwner: true`; read `project` from context.
+- **Entity-by-id routes** (`/issues/:issueId`): define a local macro with
+ `entityGuard(resource, notFound, resolveProjectId)` and set it in the route options
+ (`workItem: "edit"`).
+- **Team-owned resources** (agents, skills, tools, integrations) are under `:teamId` with the
+ `teamPermission` guard. What happens in one project (chat, runs, schedules) stays under
+ `:projectKey`.
+- A route that resolves the project itself calls `assertProjectReachable`, as `entityGuard` does.
+ `assertMcpAllowed` alone neither refuses a write to an archived project nor checks the section.
+- A handler that checks a permission itself spreads `requiresPermission([...])` into its `detail`,
+ so the MCP tool table still reports what it requires.
+- A feature also `.use(authContext)` when its handlers or macros reference `user`. Handlers that
+ still need `user` call `requireUser(user)`. An `x-api-key` header resolves through `getSession`,
+ 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 `memberAdmin` or `memberSelfOrAdmin`. Granting `owner`, or a role with a
+ `roleId`, 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 on `user`.
+- A `project_member` row with `source: 'scim'` is refused for edit or removal (409), because the
+ next sync would undo the change.
+- A `team_member` row is refused for removal or leaving only while its `source` is `'scim'` and its
+ role is `member`. Its rank can be changed, and the sync then leaves the row alone.
+- `GET /attachments/:publicId/raw` is public. Keep `X-Content-Type-Options: nosniff`, forced
+ download outside a strict media allowlist, and the locked-down CSP.
## 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 (from
-`src/app.ts`), never `src/index.ts` (it binds the port).
-
-**Setup.** `bun run setup` at the repo root creates the `*_test` database next to the dev
-one, writes `.env.test`, and migrates it. To do it by hand instead:
-
-```bash
-cp .env.test.example .env.test # repo root; DATABASE_URL must name a *_test database
-bun run db:migrate:test # migrate it (repo root)
-bun run test # from apps/api, or at root via turbo
-```
-
-The `test` script loads `--env-file=../../.env.test` and runs the files in 5 workers. Each
-worker uses its own copy of the test database (`<name>_1` … `<name>_5`), which
-`src/__tests__/preload.ts` makes afresh when the worker starts, so nothing may be connected to
-the test database at that moment. A worker holds up to 20 Postgres connections (the
-`@repo/db` client and the Mastra store) and Postgres allows 100 by default, hence 5.
-`bun test <path>` without `--parallel` runs on the test database itself. The same preload
-hashes passwords with scrypt at its lowest cost. The attachments test also needs
-RustFS + `S3_*` in `.env.test` (`docker compose -f docker-compose.dev.yml up -d` creates
-the bucket); the Docker test gate starts its own throwaway RustFS.
-
-**Layout.** Tests colocated under `__tests__/`, `integration/` (Treaty vs running app +
-test DB, one file per feature) or `unit/` (pure functions, no session/HTTP/DB — import
-directly). Helpers in `src/__tests__/helpers/`: `api` (anonymous client), `authedApi(cookie)`,
-`signUpTestUser()` → `{ cookie, userId, email }`, `resetDb()`.
-
-**Rules.**
-
-- `beforeEach(resetDb)`. Build every precondition through the API, not raw inserts.
-- Assert through the API (status + DTO via `toMatchObject`, side effects via a
- follow-up read), never by reading rows.
-- Cover per route: happy path, one valid + one invalid per field rule, boundaries
- (empty, max/max+1, last-owner), each failure status (400/403/404/409), and the
- feature's own access wiring (owner succeeds, non-member 403). Don't re-test shared
- machinery — the no-session 401 and the permission matrix have their own tests in
- `shared/__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/` or `unit/`. Helpers are in
+ `src/__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.
-
-**Gotchas.**
-
-- Assert failures on the top-level `status`, not `error.status` — Treaty narrows
- `error.status` (e.g. `422`), so `HttpError` codes (400/401/403/404) fail typecheck
- there. Read the body from `error.value`.
-- A DTO date arrives as a `Date`, not a string — Treaty revives `iso()` strings on the
- client. Assert the value, not `typeof === "string"`.
-- The first `signUpTestUser` in a test is `god` (fresh DB per `resetDb`). To act as a
- plain user, create the god user first and act as the second.
-- Don't hardcode ids or the "-42" sequence — read them from the create response.
-- A test that runs an internal agent against a model leaves its spans in the trace
- exporter, which writes them in batches up to 5 s later. By then the next test has reset
- the database and reused the ids, so the late spans count as that test's runs. Flush them
- before the test ends, in `afterEach` or right after the run:
- `await getMastra().observability.flush()`.
+- Assert failures on the top-level `status`, not `error.status`: Treaty narrows it, so `HttpError`
+ codes fail typecheck there. Read the body from `error.value`.
+- A DTO date arrives as a `Date`: Treaty revives `iso()` strings. Assert the value.
+- The first `signUpTestUser` in a test is `god`. 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. The web app never imports these packages; it uses this API over HTTP.
-- CORS `origin` is the `trustedOrigins` list exported by `@repo/auth` — do not re-parse
- `APP_URL` here.
-- A state-changing request that carries the session cookie must come from a trusted
- origin or the api's own; the `onRequest` guard in `app.ts` refuses the rest with 403
- `CSRF_ORIGIN_REJECTED`. `/api/auth/*` is left to better-auth's own check, and requests
- authenticated by api key or bearer token are not checked.
-- swagger `/docs` (planner) is separate from better-auth's `/api/auth/reference`; both
- stay reachable without a session.
-- Dev: `bun run dev`. Prod: the Dockerfile migrates, then starts the server; the compose files and the Helm chart run the migrations as a separate step and start only the server.
-
-## Runner queue and execution state
-
-`GET /agent-runs/queue` pages the runs of internal and external agents across the
-caller's readable projects, including archived projects. Both `work_items read` and
-`ai_agents read` are required in each project. Moved issues do not expose their original
-project's prompt. The same queue is narrowed to one project
-(`/projects/:projectKey/agent-runs/queue`), a team (`/teams/:teamId/...`) or a workspace
-(`/workspaces/:workspaceId/...`). Whoever runs the team reads every run of its projects
-there and in the run traces without a role in the project; the team's queue is theirs and
-the workspace managers', the workspace's its owner's and admins'. Each scope also answers
-`.../agent-runs/in-flight`: the internal runs in flight in the workspace and the
-workspace's limit on them.
-
-Two limits hold the runs of internal agents in flight; an external agent's run counts
-against neither. The instance's (`maxConcurrentRuns` in the god mode agent settings, 5 by
-default, 0 for none) is applied in `claimDueRuns`, which claims under an advisory lock so
-api replicas take only the free slots between them. It counts only the runs the api has
-claimed (`claimed_at`): a deferred run and one in retry backoff leave their slot to the
-other workspaces. A workspace's (`workspace.max_concurrent_runs`, set by its owner, lowered
-by `setLimitsProvider`) is applied in the poller, which defers a claimed run past it; there
-a run in retry backoff keeps its slot, so the older runs keep their turn.
-
-The stored `status` keeps the runner protocol's `pending` value. `executionState`
-is `running` only after admission succeeds and while its lease is valid; it is
-`queued` during delays, retry backoff and after lease expiry. Terminal states retain
-their names. `execution_started_at` is cleared on claim, defer, retry and completion,
-and set before execution is handed out. A heartbeat can restore the marker for a
-claimed external run that was already in flight when this column was added.
-
-`runnerQueue:1` is a user-scoped sync marker. It combines the `runner-queue:` revisions
-of the projects a queue may list to the user, those of the teams they run included, with
-lease expiry, runner presence and the internal runs in flight in those projects'
-workspaces, so time-based state changes are visible without a write. The queue and issue run panel share this scope.
-A runner being online is separate from a run holding an execution lease.
+- 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
+ `onRequest` guard in `app.ts` refuses the rest with 403 `CSRF_ORIGIN_REJECTED`.
diff --git a/apps/bot/AGENTS.md b/apps/bot/AGENTS.md
index 479bf13f..5e2964e1 100644
--- a/apps/bot/AGENTS.md
+++ b/apps/bot/AGENTS.md
@@ -1,46 +1,6 @@
-# bot — rules
+# bot
-Telegram bot service: a standalone Bun process running grammY long polling for the
-instance bot. Its only job today is completing account links (`/start <code>`). See
-root `AGENTS.md`.
-
-## Invariants
-
-- **The bot talks to Postgres and Telegram, and to nothing else.** Its queries are in
- `src/db.ts`, over the schema of `@repo/db`, so it needs `DATABASE_URL` and
- `APP_ENCRYPTION_KEY`. It holds no api credential and makes no call to the api — a
- secret that never crosses the network cannot be read off it.
-- **The bot settings row is the api's.** The api writes `telegram.bot` in `app_secret`;
- the bot reads it through `@repo/db` (`domains/telegram-bot.ts`), which is also where
- a new field on that config goes.
-- **One replica only.** Telegram gives each `getUpdates` call to a single caller, so
- a second instance would steal updates from the first. Do not add replicas or run it
- alongside a webhook registration for the same bot.
-- **The token is not env configuration.** It is stored in the database and edited in
- god mode, so `supervisor.ts` polls it and starts/stops/replaces the bot when it
- changes. A new bot must work without a redeploy.
-- **An error must not stop polling.** `bot.catch` swallows update failures and the
- supervisor loop tolerates the database being unreachable.
-
-## Config
-
-`DATABASE_URL` and `APP_ENCRYPTION_KEY` are required — the same values the api uses.
-Optional tuning: `BOT_CONFIG_POLL_INTERVAL_MS`, `BOT_CONFIG_RETRY_INTERVAL_MS` (see
-`src/config.ts`).
-
-## Growing it
-
-grammY ships `webhookCallback(bot, 'elysia')`, so moving from polling to a webhook
-mounted on the api is a swap of the transport, not of the framework. Commands beyond
-`/start` go in `bot.ts`, the queries they need in `db.ts`.
-
-## Tests
-
-`src/db.test.ts` covers redeeming a `/start` code against the test database
-(`bun run test` loads `.env.test`; the Docker gate runs it after the api suite). It
-inserts the pending rows the api mints in production — there is no api to call.
-
-## Run
-
-- Dev: `bun run dev` at the repo root runs it under turbo alongside api + web + worker.
-- Prod: the `bot` service in `docker-compose.yml`.
+- Do not call the api or use an api credential. The bot connects only to Postgres and Telegram.
+ The Helm chart passes it the shared configmap and secret, including `API_URL` and
+ `BETTER_AUTH_SECRET`: the bot must not read them.
+- Do not register a webhook for this bot: `bot.start()` calls `deleteWebhook` on every start.
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 78f4d797..34f4970f 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -1,233 +1,100 @@
-# web (Next.js) — rules
+# web (Next.js)
-Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`.
+Next.js App Router. Pages server-render, API data loads in the browser. Tailwind v4 + shadcn/ui.
## Imports
-- A feature is a self-contained module: imports **within the same feature** use relative paths
- (`./`, `../`); imports of the **shared layer or another feature** use the `@/` alias.
+- Imports within the same feature are relative (`./`, `../`). The shared layer and other features
+ use the `@/` alias.
- A feature imports the shared layer (`@/utils`, `@/lib`, `@/hooks`, `@/context`, `@/services`,
- `@/components/*`), never another feature —
- one accepted one-way exception: `work-items` may compose `issue` presentational components. Keep it
- one-directional, no cycles; if a second such need appears, move the shared piece to
- `components/common`.
-- The shared layer never imports a feature. `app/` routes stay thin: mount the feature page and
- providers only.
-- **`@/cloud` is the seam for the hosted edition.** It resolves to `src/ce/index.ts`, which
- exports what a self-hosted instance runs. A cloud-only part is imported from there and
- nowhere else. `useWorkspaceSections(workspace, core)` returns a workspace's settings menu,
- shown by `WorkspaceSectionNav`: here the core's sections and previews of the
- dashboard, the AI budgets and the audit log, and for the owner of email domains, single
- sign-on, the requests portal and SCIM (`components/common/page/SectionPreview`), while the
- hosted build adds
- its own at any position or drops some. One it adds carries in `Component` the
- page `/workspaces/:id/:sectionId` opens; that page answers 404 only once the workspace and
- every query in flight have loaded, so a section that waits on a query of its own opens
- from a direct link. Every section names its group: an `overview` one sits at the top of
- the menu, a `settings` one in the folding Settings group below, a `history` one below that
- group, each in the order given.
- `/workspaces/:id` names no section and opens the first entry of the menu, so the order
- also decides the page a workspace opens on.
- `useProjectSettingsSections(project, core)` returns the project's sections: here the
- core's and, for the people who govern the project's settings, a preview of the forms after
- the webhooks, while the hosted build adds its own at any position or drops some. Those of the
- `ai-team` group are listed in the main sidebar's AI Team group, those naming the same `menu`
- as one entry that opens to them, named by the menu's `sections.settings` messages; the others
- in the settings sidebar, which lists the groups in the order their first section comes, each
- named in `nav.groups.<group>`, so a section can open a group of its own. One the build adds
- carries in `Component` the page `/:team/:projectKey/settings/<slug>` opens, or
- `/:team/:projectKey/agents/<slug>` in the AI Team group, which answers 404 only once the
- project and every query in flight have loaded.
- `NoTeamStart` is the start page of an account with no team and no workspace it owns,
- which happens while personal workspaces are off; here it says who adds them.
- `WorkspaceRailActions` sits below the workspace tiles of a rail; here it says where more
- than one workspace per person is available. `ShellNotice` is a strip under the top bar of
- the app shell, god mode and the teams pages; here it shows nothing, while the hosted
- build shows notices about the instance there. `AfterSignIn` is mounted over every page,
- beside the what's new screen; here it shows nothing, while the hosted build can show a
- screen there once a session starts. `BrandMark` is the product mark at the top
- and the bottom of both sidebars; here the core's `ItsAPlanMark`, which the hosted build can
- mark its edition on. `BrandPanel({ subtitle })` is the panel beside the form on the
- logged-out screens and the invite screen; here the core's, which the hosted build can
- replace. `godSections(core)` returns the god mode
- sections: here the core's and a preview of the audit log, in a `security` group, while
- the hosted build adds, replaces or drops some. One it adds carries in `Component` the
- page `/god/<slug>` opens, and may sit in a group of its own: the sidebar lists the groups
- in the order their first section comes, each named in `sections.godGroups`. The instance's
- SCIM is set up in god mode; the hosted build that also sets it up per workspace adds
- `WorkspaceScimSection` through `useWorkspaceSections`. `SignInExtras` sits among the sign-in methods, after the
- instance's own provider, on the sign-in screen and on the invite screen, where it gets the
- invited address as `email`; here it adds nothing, while the hosted build offers a sign-in
- through providers of its own. `SignInPage` is what `/login/<name>` shows, a sign-in page under a
- name of its own; here every name answers 404, while the hosted build can show the sign-in
- form there under a title of its own (`AuthLoginForm`'s `title`). `PublicPage({ path })` is what `/p/<path>` shows to
- anyone, signed in or not, never indexed; here every path answers 404, while the hosted build
- serves pages of its own there. Those pages and the share pages may be shown in a frame on
- the sites the instance owner trusts (god mode, General; `GET /embed-sites`), which
- `src/proxy.ts` writes into `frame-ancestors` beside the app itself; `next.config.ts` refuses a
- frame to every other page. A sign-in that comes back, or an auth form the server refuses, with
- a code the core does not know shows the text the build's messages give it under
- `auth.errors.codes.<code>`.
- `GodSectionExtras` renders at the end of every god section page, by its slug, for settings the hosted build adds to an existing section; `WorkspaceSectionExtras`
- does the same on a workspace's own settings pages (`general`, `managers`), with the
- workspace, and its controls save themselves. `ScheduleDialog` is the dialog that creates
- and edits an agent schedule: here the core's, while the hosted build opens its own with
- the same props, with the schedule types it adds and the `options` it keeps on a
- schedule. The schedule list names such a type by the message
- `settings.schedules.types.<id>`. `AgentAnalyticsExtras` renders below the panels of an
- agent dashboard, a team's or a workspace's, with the scope and the window it shows;
- here a preview of the panels a build adds, which folds to its title and
- description. `cloudMessages` is the
- hosted build's English, merged into the catalogue the keys are typed against (a god
- section's name and blurb go under `sections.god.<slug>` like the core ones), and
- `loadCloudMessages(locale)` returns its other languages. The i18n request config imports
- `@/cloud` on the server for the messages, so every component file it exports starts with
- `'use client'`.
- The hosted build points `CLOUD_UI_ENTRY` at its own module exporting the same names, and
- `WEB_TRACING_ROOT` at the root its workspace has; unset, both are what this repository needs.
+ `@/i18n`, `@/components/*`), never another feature. One accepted one-way exception: `work-items`
+ may compose `issue` components. A second such need moves the piece to `components/common`.
+- The shared layer never imports a feature. `app/` pages stay thin: mount the feature page and
+ providers, or redirect.
-## Feature structure & decomposition
+## Feature structure
-- **One component per file — no exceptions.** A file exports exactly one component, even when the
- extra one is three lines long. On finding a file with two, split it: each component moves to its
- own file named after it, and the imports are updated.
-- Keep components small and single-purpose. Split when one grows past ~120 lines or mixes concerns
- (layout + fetch + mutation + dialog). The entry component becomes a thin composition; each part
- is its own file. Push state to where it is used; the parent holds only what it coordinates.
-- A feature's own parts go in purpose folders: `components/`, `hooks/`, `context/`, `services/`,
- `utils/`. Split by purpose even when a folder holds one file. A React context and its `use*`
- reader go in `context/`, not `hooks/`. The feature root holds only the entry
- component (named after the feature) — no `pages/` folder (routing is `src/app/`).
-- **A feature with more than two pages groups its components by page.** `components/` gets one
- subfolder per page, named after that page (`components/profile/`, `components/security/`), and
- each page's parts go in its own folder. A component used by two or more of the feature's pages
- stays directly in `components/`. A feature with one or two pages keeps `components/` flat.
-- Types live next to the code that produces them (API-response type in its service, prop type in
- its component), not in a `types/` folder. Add a `types/` file only for a standalone shape shared
- by several modules with no single owner.
-- Shared vs local decides feature-folder vs `src/`: a part used by more than one feature goes to
- the shared layer (`src/utils`, `src/lib`, `src/hooks`, `src/context`, `src/services`,
- `components/{common,ui}`); a part used by one feature stays in it. Promote only when a second
- feature needs it (YAGNI) — don't pre-share.
-- The shared layer splits by what a module depends on: `src/lib` holds wrappers over external
- packages (`api.ts`, `auth-client.ts`, `markdown.ts`, `dnd.ts`) plus shadcn's `utils.ts` (`cn`,
- fixed by `components.json`); `src/utils` holds own helpers and constants with no external
- package behind them. `src/context` holds shared React contexts and their `use*` readers.
-- `components/common` groups by purpose: `agent-chat/`, `attachments/`, `chart/`, `editor/`,
- `fields/`, `hotkeys/`, `inputs/`, `overlay/`, `page/`, `permissions/`, `share/`, `skeleton/`,
- `timeline/`. A component that fits none of them stays at the `common/` root.
- Imports of a sibling in the same folder are relative; everything else uses `@/`.
-- Component files use the feature name as a PascalCase prefix, file name = exported name. Service
- files carry a `.service.ts` suffix (`passkeys.service.ts`). Other non-component files use plain
- descriptive names (the folder gives the context).
+- **One component per file, no exceptions.** On finding a file with two, split it. File name =
+ exported name, with the feature name as a PascalCase prefix.
+- Split a component past ~120 lines or one that mixes layout, fetch, mutation and dialog.
+- A feature's parts go in `components/`, `hooks/`, `context/`, `services/`, `utils/`, even when a
+ folder holds one file. A React context and its `use*` reader go in `context/`. The feature root
+ holds only entry components, one per page. No `pages/` folder.
+- A feature with more than two pages gets one `components/<page>/` subfolder per page that has
+ parts of its own. A part used by two pages goes in `components/` or `components/shared/`.
+- Types live next to the code that produces them. A `types/` file is only for a shape with no
+ single owner. Service files carry a `.service.ts` suffix.
+- A part used by one feature stays in it. Promote it to the shared layer only when a second
+ feature needs it.
+- `src/lib` holds wrappers over external packages and the API client. `src/utils` holds own
+ helpers with no external package behind them. `components/common` groups by purpose; imports of
+ a sibling in the same folder are relative.
## Translations
-next-intl, language from the `NEXT_LOCALE` cookie — no `[locale]` route segment.
-`messages/<locale>/<namespace>.json`, one file per namespace, namespaces are domains
-(`issue`, `settings`) not pages.
+next-intl, language from the `NEXT_LOCALE` cookie, then `Accept-Language`, no `[locale]` route
+segment. Files are `messages/<locale>/<namespace>.json`; namespaces are domains, not pages.
+`docs/dev/i18n.md` has the whole picture, including how to add a language.
-- English is the source: `src/i18n/messages.ts` imports it statically, merges the chosen
- language over it, and types every `t('…')`. A new key goes there first or typecheck fails;
- an untranslated one renders its English text.
- A new namespace needs its file in every language plus an entry in `coreMessages`.
-- A new language: `messages/<code>/`, `src/i18n/locales.ts`, `src/hooks/useDateFnsLocale.ts`,
- and `LOCALES`/`Locale` in `apps/api/src/modules/user-preferences/`. No migration — the `locale`
- column has no CHECK. One written right to left also goes in `RTL_LOCALES`.
-- Don't subset messages per route with `pick()`: a missing namespace then fails at runtime
- instead of at typecheck.
-- The layout mirrors for a right-to-left language, so position new components with the logical
- utilities — `ms`/`me`, `ps`/`pe`, `start`/`end`, `border-s`/`border-e`, `text-start`/`text-end`
- — not `ml-`, `left-` or `text-left`, which compile to physical CSS and ignore `dir`. A
- `left`/`translate-x` centring pair and an edge the caller names (`Sheet side="right"`) stay
- physical; content that is not prose (timelines, charts, code) sits in a `dir="ltr"` container,
- and user-written text gets `dir="auto"`. `docs/dev/i18n.md` has the whole picture.
-- `bun run lint` checks the message files themselves (`eslint-plugin-i18n-json`, wired in
- `eslint.config.mjs`): every language carries every namespace of `messages/en` with the same
- key set, and each message parses as ICU. A key added to English alone fails CI. Angle
- brackets in a message are rich-text tags to next-intl — write `owner/repo`, not
- `<owner>/<repo>`, or the message does not parse.
-
-`docs/dev/i18n.md` has the whole picture, including how a switch reaches the server render.
+- Do not subset messages with `pick()`: a missing namespace then fails at runtime.
+- Angle brackets in a message are rich-text tags. Write `owner/repo`, not `<owner>/<repo>`.
+- The layout mirrors for right-to-left languages. In new code use logical utilities (`ms`/`me`,
+ `ps`/`pe`, `start`/`end`, `border-s`/`border-e`, `text-start`/`text-end`), not `ml-`, `left-` or
+ `text-left`. A `left-1/2` centring pair stays physical: `translate-x` has no logical form.
+- Content that is not prose sits in a `dir="ltr"` container. User-written text gets `dir="auto"`.
## Rules
-- Prefer Server Components and server-side data fetching; reach for client components only for
- interactivity/hooks.
-- **A screen names itself in the browser tab with `useDocumentTitle`.** The shell names the
- section (`useShellTitle`), a detail page its entity, and an issue side panel its issue over
- both; `titlePath(...)` builds `Project › Section` and gives null while a part is missing. An
- entity read that failed passes null, so the tab never names what the screen cannot show.
- A server-rendered page renders `components/common/DocumentTitle`. Never set `metadata.title`
- per route: the hook owns `document.title`.
+- Read API data in the browser with the react-query hooks in `services/`. `lib/api` sends the
+ browser cookie, so a server render cannot read as the user.
+- A screen names itself in the browser tab with `useDocumentTitle`; a server-rendered page renders
+ `components/common/DocumentTitle`. Never set `metadata.title` per route.
- A screen that has to stay live calls `useLiveRefresh({ scope, targets })` with a scope from
- `@/utils/revScopes` — never its own polling. `SyncProvider` polls every registered scope in one
- request and invalidates the targets of the ones that moved.
-- **A paged list holds its window in `usePaging()` and renders `ListPager`.** The hook owns
- `page`/`pageSize`; a filter change calls its `reset()`, and `ListPager` pulls the page back
- when deleting rows leaves the reader past the end. Spread `paging.params` straight into the
- query — the API takes `page`/`pageSize` and answers `{ items, total, page, pageSize }`.
- A "show more" list reads the same route through `useInfiniteQuery` with
- `getNextPageParam: nextPageParam` (`useCompletedCyclesQuery` is the shape to copy); a feed
- reads a cursor route instead. A picker that needs every row calls the list's `/options`
- endpoint — never a paged one with a large `pageSize`.
-- **The API client is split by domain.** `lib/api/core/` holds the transport —
- `client.ts` (`API_URL`, `request()`, `uploadFile()`, `ApiError`, `apiFailure`, the
- 401 sign-out), `paging.ts` (`Page<T>`, `PageParams`, `pageQuery`, `nextPageParam`)
- and `media.ts` (`mediaUrl`). `lib/api/endpoints/` holds one flat file per domain,
- named after the module of `apps/api/src/modules` it calls: an endpoint on the API in
- `modules/cycles/` is reached from `lib/api/endpoints/cycles.ts`. A file keeps its
- DTOs next to the functions that return them, and exports both by name — there is no
- `index.ts` anywhere under `lib/api`, and no barrel re-exporting the domains. Types
- cross domains with `import type`, which the compiler erases, so a composite like
- `ProjectDetail` is assembled in the domain that owns the route without a runtime
- cycle. A moved type whose name matches a DOM global (`Permissions`, `Notification`,
- `Storage`) resolves to that global when its import is missing, so tsc stays silent
- while the type is wrong: import it explicitly.
-- Call the backend over HTTP at the API origin. `lib/api/core/client.ts` takes it from
- `utils/runtimeEnv`, which reads `API_URL` in the server process and hands it to the
- browser through the inline script in `components/runtime-env-script.tsx`. A per-instance
- value goes through there — never `process.env.NEXT_PUBLIC_*` in a component, which
- `next build` inlines and which pins the image to one instance.
-- Avatars and attachments render from `/media/...` on the web origin (`app/media`, which
- streams them from the api), not from an absolute api url. That keeps them local images
- for `next/image`: `images.remotePatterns` is frozen into the standalone build, so an
- api origin listed there would only be valid for the instance that built the image.
-- **Every write to the API tells the user how it went.** A failed mutation is toasted by the
- `MutationCache` in `components/providers.tsx`, so a call site adds nothing for the failure;
- it adds the `toast.success(...)` for the success, from the mutation's `onSuccess`, with a
- translated message naming what was saved. A write whose result the screen already shows —
- a row that appears, a field that fills in, a dialog that closes on the created entity — needs
- no success toast; one whose effect is invisible does. A mutation that renders its own error
- instead opts out with `meta: { suppressErrorToast: true }`.
-- **A reader gets values, not disabled controls.** When the current user may not change a
- setting, render its state — an icon plus a word, a plain row — instead of a switch, input,
- or button that is disabled. A disabled control reads the same whether it is off or merely
- locked. Say once, next to the setting, who can change it. And when a switch that gates a
- whole section is off, drop the section: the settings under it and the instructions that
- depend on them change nothing until it is on. One read-only state looks the same everywhere:
- the same icon and the same wording for on and off, in the row the control would have taken —
- reuse the component that already renders it rather than styling a second variant.
-- **A workspace's owner and admins reach its projects and teams without being members.**
- The API says so with `via: 'workspace'` on the project viewer (`usePermissions().isMember`
- is false), on a project in the list and on a team. What hangs on the membership itself
- is left out for them: starring and hiding a project, leaving it or the team, and the
- project's notification settings. Everything else follows `can()` as for a member.
-- Add shadcn components with `bunx shadcn@latest add <name>` (config in `components.json`).
-- **Don't edit `src/components/ui/`** — those files are generated and re-adding a component
- overwrites them. Style them from the outside instead: every primitive carries a `data-slot`
- attribute, so a rule in `globals.css` targeting `[data-slot='…']` survives the update (the
- overlay shadows and the right-to-left corrections both work this way). Such a rule has to sit
- outside `@layer`: Tailwind orders its layers `theme, base, components, utilities`, so anything
- in `@layer components` loses to the utility classes on the element. When the change is a prop
- the component already exposes (`Sidebar side`), pass it from the caller rather than writing CSS.
- One prop reaches neither the caller nor CSS and has to be re-applied after a re-add:
- `chart.tsx` passes `debounce` to recharts' `ResponsiveContainer`, without which a chart in a
- container that resizes itself loops until React reports "Maximum update depth exceeded".
-- Tailwind v4: no `tailwind.config`; tokens live in `src/app/globals.css` (`@theme`, CSS vars).
-- Nothing per-instance may reach the bundle: the image is published once and serves every
- instance. New config of that kind belongs in `utils/runtimeEnv`.
-- Don't remove `output: "standalone"` + `outputFileTracingRoot` from `next.config` — the Docker
+ `@/utils/revScopes`. Never its own polling.
+- A paged list holds its window in `usePaging()` and renders `ListPager`. A filter change calls
+ `reset()`.
+- A "show more" list over a `Page<T>` route uses `useInfiniteQuery` with
+ `getNextPageParam: nextPageParam` (`useCompletedCyclesQuery` is the shape to copy). A cursor
+ route passes its own `nextCursor` or `nextPage`.
+- A picker that needs every row calls a whole-list route (`/options` on a paged list), never a
+ paged one with a large `pageSize`.
+- The API client: `lib/api/core/` holds the transport, `mediaUrl` and the paging helpers,
+ `lib/api/endpoints/` one flat file per domain, named after the module or sub-resource of
+ `apps/api/src/modules` it calls, with its DTOs beside the functions.
+- No `index.ts` or barrel under `lib/api`. Types cross domains with `import type`.
+- A type named like a DOM global (`Permissions`, `Notification`) resolves to that global when its
+ import is missing, and tsc fails only on a DTO-only field, so import it explicitly.
+- Nothing per-instance may reach the bundle: the image serves every instance. New config of that
+ kind goes in `utils/runtimeEnv`. Never `process.env.NEXT_PUBLIC_*` in a component.
+- Avatars and attachments render from `/media/...` through `mediaUrl`, document assets from
+ `/protected-media/...`. Both are on the web origin, never an absolute api url.
+- **Every write tells the user how it went.** A failed `useMutation` is toasted by the
+ `MutationCache`, so its call site adds nothing for the failure. A plain request or a better-auth
+ call toasts its own.
+- A call site adds `toast.success(...)` from `onSuccess` or after `await mutateAsync`, with a
+ translated message, unless the screen already shows the result.
+- A mutation that renders its own error sets `meta: { suppressErrorToast: true }`.
+- **A reader gets values, not disabled controls.** When the user may not change a setting, render
+ its state (icon plus word) instead of a disabled switch, input or button, and say once who can
+ change it. Reuse `components/common/fields/OnOffStatus.tsx` for an on/off state.
+- When a switch that gates a section is off, drop the section.
+- A workspace's owner and admins reach its projects and teams without being members: the project
+ or team carries `via: 'workspace'`. In a project `usePermissions().isMember` is false; a team
+ screen reads `team.via`.
+- For those users, leave out starring and hiding a project, saving a private view, leaving the
+ project or the team, and notification settings. Everything else follows `can()`.
+- Add shadcn components with `bunx shadcn@latest add <name>`.
+- **Do not edit `src/components/ui/`.** Re-adding a component overwrites it. Style from outside:
+ a rule in `globals.css` on `[data-slot='…']`, outside `@layer`, since anything in
+ `@layer components` loses to utility classes. Prefer a prop the component exposes.
+- After a re-add, re-apply the local edits. `chart.tsx`: `debounce` on `ResponsiveContainer`, or a
+ chart in a resizing container loops until "Maximum update depth exceeded", and the `sized` gate.
+- Local edits in other components: `sidebar.tsx` (translated labels, `isTypingTarget` on Ctrl+B),
+ `calendar.tsx` (`useDateFnsLocale`), `command.tsx` and `message-scroller.tsx` (translated labels).
+- Tailwind v4: no `tailwind.config`. Tokens are in `src/app/globals.css`.
+- Do not remove `output: "standalone"` + `outputFileTracingRoot` from `next.config`: the Docker
image depends on them.
-- When touching `localStorage`/`window` in a render path (e.g. a `useState` initializer), guard
- with `typeof window === 'undefined'` — client components still server-render.
+- Guard `localStorage`/`window` in a render path with `typeof window === 'undefined'`. Client
+ components still server-render. Read a stored value that reaches the markup in an effect, or the
+ first client render does not match the server markup.
diff --git a/apps/worker/AGENTS.md b/apps/worker/AGENTS.md
index 0d7bb984..7e11bc8f 100644
--- a/apps/worker/AGENTS.md
+++ b/apps/worker/AGENTS.md
@@ -1,159 +1,45 @@
-# worker — rules
+# worker
-Standalone Bun process (own Dockerfile, separate from `apps/api`) that drains a
-few background queues: webhook delivery, notification delivery, agent
-scheduling, and source imports. See root `AGENTS.md`.
-
-## What it does
-
-- Polls `webhook_delivery` for due `pending` rows, claims a batch with
- `FOR UPDATE SKIP LOCKED`, posts each to its webhook URL, records the outcome.
-- Queues an `agent_run` row for every due `agent_schedule`.
-- Signs every request: `X-Itsaplan-Signature: t=<ts>,v1=<hmac-sha256>` over
- `${ts}.${body}` with the webhook's `secret`. Plus `X-Itsaplan-Event`,
- `X-Itsaplan-Delivery`, `X-Itsaplan-Event-Id` (stable across retries).
-- Retries transient failures (timeout, 429, 5xx) with equal-jitter exponential
- backoff up to `WEBHOOK_MAX_ATTEMPTS`; permanent 4xx fail immediately. After
- `WEBHOOK_DISABLE_THRESHOLD` consecutive failures the webhook is auto-disabled.
-- Drains `notification_delivery` and sends each row itself: email through
- `@repo/mailer`, Telegram through the Bot API. The provider credentials are read
- from the database and decrypted here (`notification-send.ts`), so the process
- needs `APP_ENCRYPTION_KEY`.
-- Drives `import_job` rows through Discover -> Create -> Link -> Rewrite ->
- Attachments -> Done. See "Source imports" below.
-
-## Source imports
-
-`import-worker.ts` polls `import_job` for a due `pending` row (`import-store.ts`,
-same claim-with-lease shape as `webhook_delivery`) and advances it by one bounded
-chunk of work per tick — a large import interleaves across many ticks rather than
-running to completion in one.
-
-- `canonical.ts` — the source-independent shape an adapter produces
- (`CanonicalIssue`, `CanonicalState`, ...). Plain types, no logic.
-- `reader.ts` — the `SourceReader` port a source adapter implements, and the
- `SourceRateLimitedError` an adapter throws when the source's rate limit is
- reached.
-- `import-sources.ts` — one entry per `import_job.source`: its credential and
- config types, how to build its reader, and its issue-key prefix for Rewrite. A
- new source adds an entry here; the phases do not change.
-- `import-retry.ts` — what a failed tick does: a rate limit is waited out and
- does not count toward the attempt limit (the claim's bump is undone), a job whose
- source has no registry entry fails at once, any other error retries with backoff
- until `MAX_ATTEMPTS` in a row.
-- `plane-adapter.ts` — the Plane implementation. HTTP against a Plane
- instance via `pinnedFetch`, using the credential decrypted from the job row
- (base URL, workspace slug, API key — never from env, since this has to work
- against any operator's self-hosted instance). `docs/dev/plane-import-source-notes.md`
- is the spec it follows for pagination, rate limiting, and Plane's actual wire
- shapes.
-- `linear-adapter.ts` and `linear-mapping.ts` — the Linear implementation: its
- GraphQL API at the fixed `https://api.linear.app/graphql` with the job's
- personal API key, and the pure mapping from Linear's shapes. Issues in
- Linear's trash are left out. Files uploaded into Linear text are attachments;
- `resolveAttachmentDownload` follows `uploads.linear.app`'s redirects itself
- and sends the key to that host only. `docs/dev/linear-import.md` has the
- queries, limits and mapping.
-- `trello-adapter.ts` and `trello-mapping.ts` — the Trello implementation: its
- REST API at the fixed `https://api.trello.com/1` with the job's API key and
- token, and the pure mapping from Trello's shapes. Lists become states, cards
- issues with their checklists and custom field values; the board's members
- reach the job already matched with project members' emails.
- `docs/dev/trello-import.md` has the requests, limits and mapping.
-- `cross-reference.ts` — pure text matching for a source's own "KEY-123"-style
- issue identifier: no `@repo/db`, no network, unit-tested directly. What
- the Rewrite phase resolves into itsaplan's own issue ids.
-- `import-store.ts` — all `@repo/db` access for imports: claiming due jobs,
- reading/writing a job's phase/cursor/status, the `import_record`
- source-id-to-local-id upsert, and creating the local rows (states, labels,
- cycles, custom fields, issues, checklists, comments, watchers, issue links)
- an import produces.
-- `import-worker.ts` — the phase state machine. Discover snapshots every
- source id up front (`import_record` rows with no local id yet) before Create
- begins, rather than treating the source's own pagination cursor as the
- resumability anchor across the whole job — see the notes file's "Pagination"
- section for why. Create/Link/Rewrite resume from `import_record`'s own id,
- not the source's cursor. Link also gives every issue's parent link a second
- chance to resolve, the same way it already does for relations. Rewrite scans
- every created issue's description and comments for a mention of the
- source's own identifier and rewrites it to this project's, purely from
- already-local data — it makes no further requests to the source. An issue's
- mention of itself stays as written (the Linear footer relies on it), and so
- does an identifier that is a segment of a URL path.
-- The Attachments phase re-lists each issue's attachments (metadata alone,
- captured during Create, is not reused — a download needs a fresh resolve of
- the two-hop, hour-lived URL right before it happens) and downloads the
- bytes it hasn't already created a local row for. Size and mime type are
- checked against the instance's own upload settings (`@repo/db`'s
- `getStorageSettings`/`mimeAllowed`) before the request; the project's
- storage quota (`@repo/db`'s `projectStoredBytes`, `@repo/storage`'s
- `putObject`/`attachmentObjectKey`) is checked before the upload and once
- more inside the same advisory lock (`lockAttachmentStorage`) an interactive
- upload takes, so the two never both pass a check that only one of them can
- actually fit. A download that answers anything but 2xx (an error page, a
- redirect) is refused before its body is read, and one that runs past the
- size limit is cut off there (`attachment-download.ts`): Linear reports no
- size, so that is its only size check. A rejected attachment
- (`AttachmentRejectedError`) is logged and skipped, not treated as a failed
- tick.
+Standalone Bun process (own Dockerfile). `start.ts` runs three poll loops: `worker.ts` (webhook and
+notification delivery, webhook cleanup, telemetry), `agent-worker.ts` (cron schedules) and
+`import-worker.ts` (source imports). Webhook defaults are in `src/config.ts`; other settings are
+read with `intEnv` where they are used. The import pipeline: `docs/dev/import-worker.md`.
## Invariants
-- **Reads/writes `@repo/db` directly, never the API over HTTP.** It is a DB
- consumer and an HTTP producer. It does not import `apps/api` and does not call it.
-- **Notification credentials are read, never taken from the caller.** A delivery
- row names its project; the credentials come from the team that owns it and from
- the instance config. Nothing about the recipient or the provider is passed in
- from outside.
-- **No migrations here.** The api applies them on startup; the worker only uses
- existing tables and tolerates their brief absence (a tick logs and retries).
-- **At-least-once delivery.** Duplicates are possible (a 2xx whose ACK is lost);
- the `event_id` is stable across retries so receivers deduplicate. Never mint a
- new id per attempt.
-- **Agent schedules are queued here, run in the api.** A due schedule gets an
- `agent_run` row; the api drains that queue, where the agent runtime and the model
- credentials live.
-- **Claim leases, not a status flag.** Claiming pushes `next_attempt_at` forward
- by `WEBHOOK_LEASE_SECONDS`; a crashed delivery is reclaimed after the lease. Keep
- the lease comfortably larger than `WEBHOOK_TIMEOUT_MS`.
-- **Pure logic stays dependency-free.** `backoff.ts`, `signature.ts`, and
- `isRetryableStatus` import nothing from `@repo/db`, so unit tests run without a
- database. Keep DB access in `store.ts`. Same split for imports: `canonical.ts`,
- `reader.ts`, `plane-adapter.ts`, `linear-adapter.ts`, `linear-mapping.ts`,
- `trello-adapter.ts`, `trello-mapping.ts`, `cross-reference.ts`,
- `attachment-download.ts`, `import-sources.ts`, and `import-retry.ts` import
- nothing from `@repo/db` (their state-category normalization, markdown
- conversion, cursor/rate-limit, and cross-reference matching logic are
- unit-tested directly); `@repo/db` access stays in `import-store.ts`.
+- **Reads and writes `@repo/db` directly, never the API over HTTP.** It does not import `apps/api`.
+- **No migrations here.** Compose and Helm apply them in a separate step and the worker waits. On
+ Railway and a plain `docker run` the api applies them at startup, so the worker can start first.
+- **A DB error is retried and can use up attempts.** `poll-loop.ts` logs a failed claim and the next
+ tick retries. During a notification send or an import phase the error goes only to `last_error`
+ and counts as an attempt.
+- **Queued webhooks are at-least-once.** `event_id` is set at enqueue and sent in
+ `X-Itsaplan-Event-Id`, so receivers deduplicate. Never mint a new id per attempt. Notifications
+ have no `event_id`: a retry can send a duplicate.
+- **The worker queues cron schedules and runs no agent.** A due `cron` schedule of an active
+ project gets an `agent_run` row. The api queues the other runs and executes internal agents. A
+ runner or an invocation endpoint executes external ones.
+- **Claims use a lease; `status` stays `pending`.** A claim pushes `next_attempt_at` forward by
+ `WEBHOOK_LEASE_SECONDS`, `NOTIFICATION_LEASE_SECONDS`, or `LEASE_SECONDS` in `import-store.ts`.
+ Cron schedules use a row lock in a transaction instead.
+- **Keep `WEBHOOK_LEASE_SECONDS` above `WEBHOOK_TIMEOUT_MS`; no code checks it.** The timeout is a
+ socket idle timeout, so a receiver that keeps sending bytes can outlast the lease.
+- **Notification credentials are read, never taken from the caller.** A delivery row names its
+ project; credentials come from the owning team and the instance config.
+- **Always send a supplied URL through `pinnedFetch` from `@repo/net`, the SSRF guard.** That covers
+ webhook URLs, import source hosts and attachment links.
+- **Pure logic stays free of `@repo/db`.** `backoff.ts`, `reader.ts`, `*-adapter.ts` and
+ `*-mapping.ts` import nothing from it, so unit tests run without a database.
- **An import job's credential is decrypted here, never routed through
- `packages/db/src/domains/`.** That directory is for config more than one
- process reads; only the worker ever decrypts a stored import credential (the
- api sees the raw token once, at creation, before it is encrypted).
-
-## Config
-
-All via env with defaults (see `src/config.ts`): `WEBHOOK_POLL_INTERVAL_MS`,
-`WEBHOOK_BATCH_SIZE`, `WEBHOOK_TIMEOUT_MS`, `WEBHOOK_MAX_ATTEMPTS`,
-`WEBHOOK_DISABLE_THRESHOLD`, `WEBHOOK_LEASE_SECONDS`, `WEBHOOK_CLEANUP_DAYS`,
-`WEBHOOK_CLEANUP_EVERY_TICKS`. Only `DATABASE_URL` is required for webhook
-delivery. Notification delivery also needs `APP_ENCRYPTION_KEY` (the same value the
-api uses) to read the stored provider credentials, and so does source import (it
-decrypts the stored source credential with it too). `IMPORT_POLL_INTERVAL_MS` tunes
-the import worker's poll interval. The Attachments phase needs the same `S3_*`
-variables (`S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`,
-`S3_REGION`, `S3_FORCE_PATH_STYLE`) the api reads for its own uploads — both
-processes write to the same bucket.
+ `packages/db/src/domains/`.** Only the worker decrypts it.
+- A new import source needs a `SourceReader` adapter, an entry in `import-sources.ts`, api routes
+ and a web form. The phases do not change. Rewrite makes no requests to the source.
+- **Only `AttachmentRejectedError` is logged and skipped.** Any other attachment error fails the
+ tick, an SSRF refusal (`UrlNotAllowedError`) included. `MAX_ATTEMPTS` failed ticks in a row fail
+ the job (`import-retry.ts`).
## Tests
-`src/__tests__/unit/` covers the pure logic with no database. `src/__tests__/integration/`
-covers what needs one — the notification send reads its config from the database — and
-runs against the test DB (`bun run test` loads `.env.test`; the Docker gate runs it
-after the api and bot suites). It inserts the rows the api writes in production, the
-way `apps/bot` does; there is no api to call.
-
-## Run
-
-- Dev: `bun run dev` at the repo root runs it under turbo alongside api + web
- (watch mode, loads root `.env`).
-- Prod: the `worker` service in `docker-compose.yml`.
+`src/__tests__/unit/` covers pure logic with no database. `src/__tests__/integration/` runs against
+the test DB, and `import-store.test.ts` also uses the S3 test store. These tests insert the rows the
+api writes in production; there is no api to call.
diff --git a/docs/dev/access-model.md b/docs/dev/access-model.md
new file mode 100644
index 00000000..5bf07451
--- /dev/null
+++ b/docs/dev/access-model.md
@@ -0,0 +1,180 @@
+# Access model
+
+How the api decides who may do what. The rules an agent must follow are in
+`apps/api/AGENTS.md`. Paths are relative to `apps/api/src/`.
+
+Access is enforced through macros in the route options. A rule that depends on the fetched row
+or on the request body is checked in the handler or the service.
+
+## Session
+
+- `authContext` (`shared/auth-context.ts`) puts `user` on the context, and `planner.ts` applies it
+ to every planner route. It reads the account through `requestUser`, which takes a session, an
+ `x-api-key` header or the MCP OAuth token of a tool call.
+- A request with no account gets 401. The GET routes in `PUBLIC_GET` run with `user: null`
+ instead: raw attachments, avatars, `/invites/:token` and `/share/*`. A `/share/*` token reads a
+ shared issue or view with no membership.
+- `authContext` answers 401 for a deactivated account. `requestUser` leaves that check to its
+ caller, so `/me`, which runs outside the planner, makes the check itself.
+- An API key cannot manage the account: `/api/auth/*` and `/account/connected-apps` refuse it.
+
+## Membership and workspace roles
+
+- Access to a project comes from a `project_member` row (`owner` | `member`), from the caller's
+ role in the workspace that holds the project, or from both.
+- Owners bypass the permission matrix. The global `user.role` (`god` | `user`) does **not**:
+ `getProjectAccess` never reads it. God acts through its own routes under `/god`.
+- A project keeps at least one owner. `members/` answers 400, `teams/` and SCIM answer 409. The
+ code enforces this; the database has no constraint for it.
+- Workspace roles are `owner` and `admin`, stored in `workspace_manager`. They reach every team
+ and project of the workspace without a membership row: the owner as an owner of each, an admin
+ with a matrix that only reads. The table is `shared/workspace-roles.ts`.
+- `ai_agents.read` also opens the agent run and chat routes, and an internal agent's tools act
+ with the agent's own key. So a workspace admin can start a run that writes.
+- **Whether the caller reaches something:** `getProjectAccess` and `getTeamAccess` in
+ `shared/access.ts` merge the membership with the grant, and the project and team guards read
+ them. Workspace guards read `requireWorkspaceManager`. `listProjects`, `listTeams` and `readRevs`
+ take the reached teams the same way. `listProjects` and `listTeams` answer `via: 'workspace'`
+ for what the caller reaches only through the workspace.
+- Two caller checks use the rows. `agentScopeOf` gives every agent of a team only to someone who
+ runs the team; anyone else, a workspace admin included, reaches the agents that share a
+ `project_member` row with them. A private view takes a project membership of their own
+ (`via: 'member'`).
+- **Whether someone else is a member:** assignees, mentions, watchers, notification recipients,
+ seats, the last-owner check and SCIM read the rows. A workspace owner or admin with no row is in
+ no member list, gets no notifications and takes no seat. With a row they count as any other
+ member. An admin holds a team row when appointed (`addAdmin`). The owner gets one by creating a
+ team or a project in the workspace.
+
+## Guards
+
+- **`:projectKey` routes:** `.use(guards)`, set one macro, read the resolved `project` from
+ context.
+ - `projectMember: true`: any member.
+ - `permission: ["<resource>", "<action>"]`: the role matrix.
+ - `projectOwner: true`: an owner of the project.
+ - `projectAdmin: true`: an owner of the project, or an owner or manager of its team.
+ - `teamRunsProject: true`: an owner or manager of its team.
+ - `memberAdmin`, `memberSelfOrAdmin`: see [Member lists](#member-lists).
+ - `feature: "<section>"` goes beside them and closes the route while the project has that
+ section off.
+- **Team routes:** `teamMember`, `teamManager`, `teamOwner` and `teamPermission` inject
+ `membership`.
+- **Workspace routes:** `workspaceManager`, `workspaceOwner` and `workspaceScim` inject `standing`.
+- **Entity-by-id routes** (`PATCH /issues/:issueId`): define a local macro with
+ `entityGuard(resource, notFound, resolveProjectId, feature?)` and set it in the route options
+ (`workItem: "edit"`). It injects `projectId` and runs `assertPermission` and
+ `assertProjectReachable`.
+- **A handler that checks a permission itself** spreads `requiresPermission([...])` into its
+ `detail`, so the MCP tool table still reports the requirement: `GET /issues/:issueId`, and
+ `PATCH` and `DELETE /views/:viewId`.
+- **A route that resolves the project itself** runs one of two checks on it.
+ `assertProjectReachable` covers the run binding, the MCP toggle, the optional section and writes
+ to an archived project. `assertMcpAllowed` covers only the run binding and the MCP toggle, so a
+ route that writes and uses it also calls `assertWritable`, as `moveTarget` does.
+- **`POST /issues/:issueId/move`** checks the target project in the `moveTarget` macro, which reads
+ `projectId` from the body and asserts `work_items` `create`. `GET
+/projects/:projectKey/issues/:sequenceNumber` asserts the read permission on the issue's project
+ when an old number resolved to an issue now in another project.
+- **MCP toggle** (`assertMcpEnabled`): the team switch, then the project flag. It applies only to
+ calls through `POST /mcp`, and an internal agent's run skips it. Team macros apply only the team
+ switch. Workspace macros apply neither.
+- **Run binding:** the run's tool dispatch sets `x-agent-project`, and a check above refuses an
+ object outside that project (403). On `:projectKey` routes the dispatch sets `projectKey` to the
+ run's project. Cross-project lists filter by `boundProjectId`.
+- **`x-permission`:** a guard built on one matrix pair publishes it on the route's OpenAPI detail,
+ and `mcp/generate.ts` reads it there. These are `permission`, `memberAdmin`, `memberSelfOrAdmin`,
+ `teamPermission` and `entityGuard`. Guards that check only a standing publish nothing, and
+ neither do `worklog`, `comment`, `moveTarget` and `viewableAttachment`, whose rule depends on the
+ row or the target. The value is one pair, so it can understate a route: `move_issue` reports
+ `work_items` `delete` and omits `create` on the target.
+
+## Workspaces and teams
+
+- **Team creation** (`POST /teams`, `assertMayCreateTeam` in `modules/workspaces/service.ts`): the
+ workspace named by `workspaceId` decides through `teamCreation`, which only its owner sets.
+ `owner` (the default) lets its owner, `managers` also its admins, `members` also anyone in one of
+ its teams. An agent's bot user never creates one. Anyone else gets 403, god included.
+- A team is in the workspace named when it was created. Its creator is its team owner and need not
+ own the workspace. Everyone in a workspace's teams shares that workspace.
+- **Personal workspaces:** no route creates a workspace. While `personalWorkspaces` is on in the
+ auth settings (the default), a person who owns none gets one at sign-up, or on the next request
+ through `ensurePersonalWorkspace` in `authContext`. While it is off, only the instance owner gets
+ one, and anyone else works in the teams they are added to. An agent's bot user never owns one.
+- **Account deletion** (`deleteAccount`): god and the instance's SCIM provider delete an account.
+ There is no self-delete, and the instance owner cannot be deleted. A workspace the account owned
+ is deleted while it holds no project and no AI agent, with all its teams. Any other passes to the
+ instance owner, with the teams and projects the account owned alone in it
+ (`releaseOwnedWorkspaces` in `modules/teams/service.ts`). This is the only way a workspace changes
+ owner. God mode asks about sole-owned projects only outside the account's own workspaces: 400
+ unless `?withProjects=true`, which deletes them.
+- **Workspace deletion** (`DELETE /workspaces/:workspaceId`, `workspaceDeletion` in
+ `modules/workspaces/service.ts`): the owner deletes a workspace that holds no project and no AI
+ agent. Any other answers 409.
+- **SCIM** is set up in god mode (`/god/scim`) for the instance. The `workspaceScim` routes are the
+ workspace owner's, and answer 403 unless SCIM is set up per workspace. See `docs/dev/scim.md`.
+
+## Joining a project
+
+- **A member of the team** is added directly (`POST /projects/:projectKey/members`, with
+ `members_manage` `create`). Someone outside the team gets 400.
+- **Anyone else** joins through an invite, which puts them in the team as well. Creating a project,
+ attaching an agent, SCIM and the hand-over of sole ownership write rows without an invite.
+- **Who invites:** a project invite takes `memberAdmin: ["members_invite", "create"]`, a team
+ invite (`POST /teams/:teamId/invites`) takes `teamManager`.
+- An invite belongs to its address: accepting takes a session with that email, otherwise 403.
+- One pending invite per (project, email), and one pending team invite with no project per (team,
+ email). Partial unique indexes answer 409, so an address can hold one of each.
+- An address already in the project or the team gets 409. A team member is added from the member
+ list. Accepting also refuses someone who joined the project in the meantime (409
+ `ALREADY_PROJECT_MEMBER`), and never lowers a team rank.
+- Inviting the address again, or renewing (`.../invites/:inviteId/renew`), replaces an expired
+ invite with a new one under a new link. A link is never rewritten. An expired invite is not
+ accepted, and the email routes refuse it. A project invite email already in the outbox can still
+ go out after expiry.
+- **Address policy** (`modules/invites/email-policy.ts`, 400 `EMAIL_DOMAIN_NOT_ALLOWED`) runs on
+ create and renew. By default an address with an account passes, and one without passes when its
+ domain is in `allowedEmailDomains` (an empty list allows all). It does not read `registration`,
+ so an invite can go to an address that cannot register on a closed instance.
+ `GET /teams/:teamId/invites/candidates` leaves out whom the policy refuses, and answers 403 while
+ `inviteSearch` is off (the default).
+
+## Member lists
+
+- `memberAdmin: ["members_manage", "<action>"]` passes on the role matrix, or for an owner or
+ manager of the team without a `project_member` row. List, candidates, add and assign a role use
+ it. Nobody changes their own role (400).
+- `memberSelfOrAdmin` is on the two other `:userId` routes, describe and remove. A member acts on
+ their own row, leaving the project or saying what they do in it, with no member permission.
+ Anyone else needs what `memberAdmin` asks for.
+- **Project `owner`:** an owner bypasses the matrix, so the member permission does not hand it out.
+ Adding, promoting, demoting, removing and inviting an owner take an owner of the project, or an
+ owner or manager of its team (`assertProjectAdmin`, and `mayGrantInviteRanks` for an invite).
+- **Team ranks** (`setTeamMemberRole`): a team owner or manager sets a non-owner to `member` or
+ `manager`. Only a team owner grants or takes `owner`, invites `owner` or `manager`, or removes a
+ member. Nobody changes their own rank.
+- **Invite sender:** `mayGrantInviteRanks` runs when the invite is made and again when it is
+ accepted, so a sender who was demoted or deleted leaves the link refused (409). It covers project
+ `owner` and a team rank above `member`. A plain or custom-role link stays valid. Removing the
+ sender from the team deletes their pending invites there (404).
+- **Custom roles:** adding, re-roling, inviting or renewing with a `roleId` goes through
+ `assertGrantablePermissions`, which refuses a role that grants more than the granter holds. A
+ project owner, or an owner or manager of the team, is not capped. The project's invite list hides
+ the link of an invite whose role the viewer could not grant.
+
+## SCIM rows
+
+- `project_member.source` is `'scim'` for a row the sync made, and `'invite'` for every other row.
+ `modules/scim/reconcile.ts` writes, re-roles and removes only its own `'scim'` rows. `members/`
+ refuses to re-role or remove one (409), the owner leaving included, because the next sync would
+ undo the change. Its description can be edited.
+- A project membership from the sync comes with a `team_member` row in the owning team, added as a
+ plain member with `source: 'scim'`. That row is removed once the person has no project row of any
+ source in the team. A row someone else created, or one whose rank was raised, stays.
+- `teams/` refuses to remove or leave a `'scim'` row of rank `member` (409). Its rank can be
+ changed: the rank is the team's to set, the membership is the identity provider's.
+- A workspace's provider, on deactivate or delete, removes every team and project row of that
+ person in the workspace, of any source (`dropWorkspaceMemberships`). What they owned alone passes
+ to the workspace owner.
+- A SCIM group mapping can grant `owner` on a project, outside `assertProjectAdmin`. It is set up in
+ god mode and on the `workspaceScim` routes.
diff --git a/docs/dev/agents-md.md b/docs/dev/agents-md.md
new file mode 100644
index 00000000..13b2df69
--- /dev/null
+++ b/docs/dev/agents-md.md
@@ -0,0 +1,113 @@
+# Maintaining AGENTS.md
+
+Each line of an `AGENTS.md` costs tokens on every task in its folder, and an agent does not question
+a wrong line. So these files contain only what an agent would get wrong without them.
+
+## How the files are loaded
+
+- Claude Code reads `CLAUDE.md`. Each `CLAUDE.md` here contains only the line `@AGENTS.md`, which
+ imports the `AGENTS.md` beside it. Put rules in `AGENTS.md`. A new `AGENTS.md` needs this
+ `CLAUDE.md` in the same change.
+- Claude Code loads the root file at session start. It loads an area file on the first read, write
+ or edit of a file in that folder.
+- Codex reads `AGENTS.md` files at session start, from the repository root down to the working
+ directory. A session started at the root gets an area file only through the root rule that says
+ to read it, so keep that rule.
+
+## Where a fact goes
+
+| Fact | Place |
+| --------------------------------------------------------- | ---------------------------------------- |
+| A rule the code does not show, that most tasks there need | the nearest `AGENTS.md` |
+| A rule a tool can check | the tool: ESLint, tsc, a test, CI |
+| How a feature works, a walkthrough, a design reason | `docs/dev/<topic>.md` |
+| A rule for one topic only | that doc, plus one routing row |
+| Steps for a rare procedure | `docs/dev/<topic>.md` |
+| A workflow an agent runs by name | `.agents/skills/` |
+| Why one line of code looks wrong | a comment on that line |
+| An extension point for the Pro build | `SEAMS.md` in the private Pro repository |
+| A fix, a feature, what changed | the commit message |
+
+The routing row goes in the Docs table of the root `AGENTS.md`, or in the area file when only that
+area needs the doc.
+
+## Test for a new line
+
+Add a line only when every answer is yes:
+
+1. Would an agent get this wrong without the line? Try it, or point to the mistake it made.
+2. Is it invisible in the code? If a neighbouring file shows the pattern, leave it out.
+3. Can no tool check it? If one can, add the check and leave the line out.
+4. Do most tasks in this folder need it? If not, it goes in a doc.
+5. Does breaking it cost data, security, a failed deploy or a release?
+
+## When to update
+
+Update in the same change when:
+
+- a rule changes or stops being true;
+- a file, function or command named in an `AGENTS.md` is renamed or removed;
+- agents made the same mistake twice and the test above passes.
+
+Do not update when:
+
+- you fixed a bug, added a route, a table, a setting or a feature;
+- a refactor kept the rules;
+- an agent offers to record what it learned;
+- a command such as `/init` generated the text.
+
+## Format
+
+- One rule per bullet, at most three lines, in the imperative.
+- Name the file, function or command.
+- Give the reason in one clause when it stops a workaround.
+
+```markdown
+<!-- Good -->
+
+- Never add `image:` to `docker-compose.coolify.yml`: with both `image:` and `build:` Coolify still
+ builds and stops making rollback images.
+
+<!-- Bad: describes the design and states no rule -->
+
+`socialProviders.google` is a factory that returns the module-level `googleOptions` object.
+better-auth builds the provider list once, but the provider keeps that object...
+
+<!-- Bad: records one change -->
+
+`0152_agent_execution_state.sql` adds the current execution marker to `agent_run`.
+
+<!-- Bad: ESLint already fails this -->
+
+Every language carries every key of `messages/en`.
+```
+
+## Limits
+
+`scripts/agents-md.test.ts` runs in CI on every pull request, and a failure blocks the merge. It
+reads every tracked `AGENTS.md` and fails when:
+
+- the file is over 10,000 bytes;
+- a backticked path does not exist.
+
+The path check covers file names with a common extension and paths under `apps/`, `packages/`,
+`docs/`, `scripts/`, `charts/` and `.github/`. It skips brace and wildcard forms and paths such as
+`.agents/skills/`. A reference also passes when any tracked path ends with it, so after a rename
+search for the old name by hand.
+
+Over the limit, remove a line. Do not raise the limit. Claude Code loads an area file whole. Codex
+cuts the combined text of the files from the repository root to the working directory at 32 KiB
+(`project_doc_max_bytes`) and adds no marker. Two files at the limit stay under that cut.
+
+No check covers the format rules or the `CLAUDE.md` files.
+
+## Reviewing a change to AGENTS.md
+
+A change to an `AGENTS.md` affects every later agent task in that folder. Ask for the mistake the
+line prevents. Reject a line that fails the test above, and move a good explanation to `docs/dev/`.
+
+## Measuring a change
+
+For a large rewrite, compare old and new on a set of task-like questions in clean copies of the
+repository, one copy per version, with a control copy that has no `AGENTS.md`. Compare correct
+answers, tokens and turns. A rule that the control gets right is a candidate for removal.
diff --git a/docs/dev/agents.md b/docs/dev/agents.md
new file mode 100644
index 00000000..fc8fc1fe
--- /dev/null
+++ b/docs/dev/agents.md
@@ -0,0 +1,238 @@
+# AI agents: how they work
+
+Paths are relative to `apps/api/src`. `runtime/` means `modules/agents/core/runtime/`.
+
+## Ownership and access
+
+Agents, the skill library, the configured tools and the integration credentials belong to the
+team. Their routes are under `:teamId` and use the `teamPermission` guard. The integration
+catalog, the provider models and the credential options take `teamMember` only.
+
+What acts in one project stays under `:projectKey`: an agent's chat, its schedules and starting
+a run. A run is read from the agent's history and traces under `:teamId`, the queue at each
+scope, and `/agent-runs/:runId`.
+
+Three decisions a reader would otherwise propose again:
+
+- **The team is the boundary.** There is no instance-level agent and no non-human flag on `user`.
+- **`ai_agents` `create` and `edit` are administrative.** `create` makes an agent, attaches it to
+ the caller's projects and returns an external agent's key once. That key reaches those projects
+ on the default role. `edit` attaches an existing agent to the caller's projects
+ (`PUT /teams/:teamId/ai-agents/:agentId/projects`). The caller's projects are the ones they are
+ a member of, or every project of the team for whoever runs it.
+
+ An action that reaches every project the agent works in also takes running the team or being a
+ member of all of them (`assertFullAgentAccess`): rotating the key, editing or deleting the
+ agent, setting its tools or skills, and reading, rotating or testing its invocation. Setting
+ tools or skills also takes `agent_tools` or `agent_skills` `edit`. The agent's `canManage`
+ reports this rule, so the web hides those actions from a caller the api would refuse. The web
+ attaches projects through `PATCH`, which takes full access, so it hides attaching as well,
+ although the `PUT` route does not need it.
+
+ `ai_agents` `read` is on the default role and gates chat and run. What the agents spent is a
+ separate read-only resource, `agent_usage`.
+
+- **An agent's role is its `project_member` row**, per project. Attaching an agent through the
+ agent routes, or as a team default on a new project, joins it on the default system role. A
+ project it already works in keeps its role. The project's member list sets its role like a
+ person's and can add it on another role. `members/` refuses to make it an owner, since an owner
+ bypasses the matrix.
+
+## Schema
+
+An AI agent is a row in `ai_agent` with a `team_id` and a `user_id`: the team that owns it and the
+bot user it acts as. Code that lists agents reads `ai_agent`. `team_member.role` also tells an
+agent from a person: it takes a fourth value, `'agent'`, which the seat count and the workspace
+admin candidates leave out.
+
+`agent_skill`, `agent_tool` and `integration_credential` carry a `team_id` and are shared by every
+project of the team. `agent_schedule` and `agent_run` carry a `project_id`: a run happens in one
+project.
+
+The projects an agent works in are its bot user's `project_member` rows. The `role_id` on each is
+what its requests in that project are checked against, so one agent can hold different roles in
+two projects. An internal agent's rights in a project are the intersection of that role and its
+actions: the keys in `ai_agent.tools` plus the always-on actions (`ALWAYS_ON_KEYS`). An external
+agent has no such list, so its key is checked against the role alone.
+
+`ai_agent_team_username_uq` makes the mention handle unique per team, ignoring case.
+`assertUsernameFree` also refuses a handle a person holds.
+
+## MCP
+
+The team is resolved from the API key (`mcp/server.ts`). An agent's key acts in its own team, a
+person with one team open to MCP in that team, and a person with several passes `teamId` after
+reading `list_teams`.
+
+`team.mcp_enabled` opens the team to MCP clients, and `project.mcp_enabled` says which of its
+projects that covers. A new project starts from the instance's project default. After that, both
+are written from `PATCH /teams/:teamId/mcp`, never from the project.
+
+The project guards check both through `assertMcpEnabled`. The team guards check the team switch
+through `assertTeamMcpAllowed`, which covers what no project flag reaches, such as the agents, the
+skills, the tools, the roles and the credentials. An internal agent's tool calls do not count as
+MCP access (`viaMcpEndpoint: false`), so neither switch stops them.
+
+## Traces
+
+Runs of an internal agent are traced. `runtime/observability.ts` holds the one Mastra container of
+the process. An agent built for a run writes no spans on its own, so each one is registered with
+it. Its exporter writes the spans into Mastra's `mastra_ai_spans` table on the application
+database.
+
+The spans carry no foreign keys of ours, so a run names what it belongs to in the trace metadata
+(`prepareRun` in `runtime/index.ts`): the agent, the team, the project, the issue and the schedule,
+and either the queued run with its trigger or, for a chat run, the person who asked.
+`runtime/traces.ts` filters on the agent, the project, the issue, the queued run and the person.
+`runtime/analytics.ts` and `runtime/trace-retention.ts` filter on the team. The trace of a chat run
+is read only by the person who chatted, the team's owner included.
+
+How long traces are kept is the instance setting `traceRetentionDays` under god mode (`app_setting`
+key `agents`), 30 days by default, 0 to keep them. `runtime/trace-retention.ts` applies it from the
+api's background loop. The sweep finds the root spans past the window and deletes those traces
+whole. Each attempt of a retried run has its own trace, so a run can lose its older attempts first.
+The same sweep drops every trace whose team no longer exists or that names no team, also when the
+window is 0.
+
+## Run time limit
+
+`maxRunSeconds` in the same setting is the longest one queued run may take.
+`ai_agent.run_timeout_sec` sets a shorter limit for one agent, and a workspace ceiling from
+`setLimitsProvider` lowers both. A chat run has no limit.
+
+A run that reaches the limit is aborted and saved as failed with the text it had produced. It is
+not retried. The abort does not interrupt a tool call in flight: the run ends when the call
+returns. A claim's lease is at least 60 seconds longer than the instance maximum, so the poller
+does not claim a run again while it is running, unless a tool call outlasts that margin.
+
+## Dashboard and cost
+
+The run traces back the agent dashboard (`runtime/analytics.ts`) at
+`GET /teams/:teamId/agent-analytics`. Over the last `days` days it returns runs and errors by agent
+and project, tokens and cost by model, agent, project and day, and calls by model. `previous` holds
+the totals of the same span before it.
+
+The team's owner and managers read every project of the team, and so does anyone whose workspace
+role grants `agent_usage` `read`, which covers a workspace owner and admin. Anyone else reads the
+projects where their project role grants it (`projectsWithPermission` in `shared/access.ts`), since
+a role is set per project and a team-wide figure would show the others. The response names those
+projects (`readableProjects`), and `projectId` narrows the dashboard to one of them.
+`GET /workspaces/:workspaceId/agent-analytics` reads it over every team of a workspace, with the
+teams compared, for its owner and its admins.
+
+The api applies the cost to the token counts of the `model_inference` spans. Mastra attaches a cost
+to its metric events, but `PostgresStore`, the store of `runtime/store.ts`, does not implement
+`batchCreateMetrics`, so the exporter drops them. `PostgresStoreVNext` in `@mastra/pg` implements
+that call, and the api does not use it. `runtime/model-pricing.ts` prices the spans from the table
+`@mastra/observability` bundles (`dist/metrics/pricing-data.json`).
+
+The table's provider ids are the registry `AI_PROVIDERS` mirrors, so a credential's integration key
+needs no mapping. A key the table lacks, such as `openai-compatible`, stays unpriced until the
+workspace sets a price. The file is outside the package's exports map: a release that moves it
+leaves the table empty. An unpriced call reports no cost, and the dashboard shows its tokens without
+an amount. A figure that mixes both shows the amount of the priced calls, and the dashboard names
+the models with no price.
+
+A workspace sets its own price for any model in `model_price`, which the dashboards of its teams
+read before the table (`ownPrices` in `analytics.ts`). It covers a model the table lacks, such as
+one behind an OpenAI-compatible proxy, and one bought at another rate. The cost is worked out when a
+dashboard is read, so a price also recounts past calls whose traces are still stored.
+
+`modules/agents/prices` lets the workspace's owner and admins read and set those prices. It lists
+the models the workspace called in the last 90 days or priced, those no price covers first, and the
+whole table, paged, each beside the workspace's own price.
+
+## Reading runs
+
+`GET /issues/:issueId/agent-runs` reads an issue's runs with cursor pagination. It requires
+`work_items read` and `ai_agents read` in the issue's current project.
+
+A run keeps its original project. Moving an issue cancels the pending runs of the issue and its
+subtasks. The issue panel, the trace routes and every queue then hide the moved issue's runs from
+everyone, members of the original project included, so a moved issue does not expose its former
+project's prompts or traces. The agent's run history (`GET /teams/:teamId/ai-agents/:agentId/runs`)
+has no such filter: members of the original project and whoever runs the team still read those runs
+there.
+
+Three routes read a run's trace:
+
+- `GET /issues/:issueId/agent-runs/:runId/trace` reads the Mastra trace of an internal run: the
+ latest recorded attempt, or the one named by `traceId`. Each trace links to the previous recorded
+ attempt (`previousTraceId`). It returns null for a missing latest trace and for an external run,
+ which has no Mastra trace. An unknown or unrelated `traceId` returns 404.
+- `GET /agent-runs/:runId/internal-trace` reads the same trace by the run alone, and takes the same
+ `traceId`.
+- `GET /agent-runs/:runId/trace?attempt=N` reads the transcript an external runner reported. The
+ latest recorded attempt is the default.
+
+The issue route requires both read permissions in the issue's current project. The two
+`/agent-runs/:runId` routes require them in the run's original project, and `documents read` for a
+run started in a document. Whoever runs the team needs none of them there. A run from a private
+document is read only by the document's owner. These two routes also serve runs without an issue: a
+schedule's, a manual run's, and one started in a document comment.
+
+The api stores the events an external runner reports in `agent_run_trace`, one row per attempt:
+messages, tool inputs and results, and a local Codex session link. Transcripts follow the instance
+trace retention window after the run finishes. Pending runs and final results are retained.
+
+`POST /agent-runs/:runId/events` accepts only the calling agent's current executing, unexpired
+attempt. Event offsets deduplicate retries and reject gaps with 409. An attempt's transcript stops
+recording after 2,000 events or 1 MB. Acknowledgements continue, so the runner can still report its
+final result. A Codex UUID forms the local `codex://threads/` link, and no supplied URL is accepted.
+
+The runner sends the attempt number on heartbeat and result calls. The api answers 404 to the
+process of a reclaimed attempt, and its command keeps running until it ends. `attempt` is optional
+on both calls: a custom invocation endpoint can leave it out, and the api then does not check it.
+
+## Runner queue
+
+`GET /agent-runs/queue` pages the active and past runs of internal and external agents across the
+caller's readable projects, including archived projects. It requires `work_items read` and
+`ai_agents read` in each project, and `documents read` for a run started in a document. `runId`
+narrows it to one authorized run for the detail pane.
+
+The same queue is narrowed to a project (`/projects/:projectKey/agent-runs/queue`), a team
+(`/teams/:teamId/...`) or a workspace (`/workspaces/:workspaceId/...`). The team's queue is for
+whoever runs the team and the workspace managers, the workspace's for its owner and admins. Whoever
+runs the team also reads the project queues of its projects without a role there.
+`GET /agent-runs/queue` still takes a role.
+
+Each of the three scopes also answers `.../agent-runs/in-flight`: the workspace's limit and the
+internal runs holding a slot in the workspace. A run in retry backoff holds a slot, so this count
+can differ from the queue's `running` count.
+
+## Concurrency limits
+
+Two limits hold the runs of internal agents in flight. An external agent's run counts against
+neither.
+
+- The instance's: `maxConcurrentRuns` in the god mode agent settings, 5 by default, 0 for none.
+ `claimDueRuns` applies it under an advisory lock, so api replicas take only the free slots between
+ them. It counts only the runs the api has claimed (`claimed_at`) under a valid lease. A deferred
+ run and one in retry backoff leave their slot to the other workspaces.
+- A workspace's: `workspace.max_concurrent_runs`, set by its owner up to the instance's limit,
+ lowered by `setLimitsProvider`. The poller applies it and defers a claimed run past it. Here a run
+ in retry backoff keeps its slot whatever its id. Among claims waiting for admission the lower id
+ goes first.
+
+## Execution state
+
+The stored `status` stays `pending` while a run waits and while it is claimed. `executionState` is
+`running` only after admission succeeds and while the lease is valid. It is `queued` during delays,
+retry backoff and after lease expiry. Terminal states keep their names.
+
+`execution_started_at` is cleared on claim, defer, retry, completion and cancel, and set before
+execution is handed out. A heartbeat sets it on a started external run that has none, unless the run
+has a `last_error`. A run in retry backoff has one, so its heartbeat answers 404.
+
+## Sync marker
+
+`runnerQueue:1` is a user-scoped sync marker. It combines the `runner-queue:` revisions of the
+projects a queue may list to the user, those of the teams they run included, with lease expiry,
+runner presence and the internal runs in flight in those projects' workspaces. Time-based state
+changes are visible without a write. The queue, the issue run panel, the agent's run list and the
+trace views watch it. A runner being online is separate from a run holding an execution lease.
+
+The `agent_run_rev` trigger bumps `runner-queue:<projectId>` on every write to `agent_run`, and
+`appendRunEvents` bumps it for a transcript write. The trigger does not write the issue scope, so the
+issue run panel watches this marker as well as its own scope.
diff --git a/docs/dev/api-tests.md b/docs/dev/api-tests.md
new file mode 100644
index 00000000..b6ed2cef
--- /dev/null
+++ b/docs/dev/api-tests.md
@@ -0,0 +1,79 @@
+# api tests: setup
+
+How to write a test is in `apps/api/AGENTS.md`.
+
+`bun test` drives the app in memory with Eden Treaty against a real test Postgres and real
+better-auth sessions. No mock library is used. External services are replaced at the network
+boundary: a local `Bun.serve` stub, a fake SMTP listener or a `globalThis.fetch` override. Tests
+import `app` through the helpers, from `src/app.ts`. `src/index.ts` binds the port.
+
+## Setup
+
+`bun run setup` at the repo root, in the Develop mode, creates the `<dev database>_test` database
+next to the dev one, writes `.env.test`, and migrates both databases. By hand, with the dev stack
+running:
+
+```bash
+cp .env.test.example .env.test # match DATABASE_URL to the root .env
+docker compose -f docker-compose.dev.yml exec -T postgres \
+ psql -U itsaplan -d itsaplan -c 'CREATE DATABASE itsaplan_test'
+bun run db:migrate:test # repo root
+```
+
+The database name must contain `test` and `NODE_ENV` must be `test`: `resetDb` refuses to run
+otherwise. The Postgres role must be a superuser, as the dev role is: `resetDb` sets
+`session_replication_role`, and the preload creates databases.
+
+Tests do not migrate. After a new migration, run `bun run db:migrate:test`.
+
+## Running
+
+| Command | Folder | Runs |
+| -------------------------------------------- | ---------- | ------------------------------------------ |
+| `bun run test` | repo root | `scripts/` tests, then every member's suite |
+| `bun run test` | `apps/api` | the api suite in up to 5 workers |
+| `bun test --env-file=../../.env.test <path>` | `apps/api` | one process on the test database itself |
+
+## Workers
+
+The api `test` script is `bun test --env-file=../../.env.test --parallel=5 --no-isolate`. With
+`--no-isolate`, `src/__tests__/preload.ts` runs once per worker. It drops and recreates the worker's
+copy of the test database, named `<name>_<worker>`, for example `itsaplan_test_3`, and points
+`DATABASE_URL` at it. The copies stay on the server until the next run replaces them.
+
+- Nothing may be connected to the test database when a worker starts: Postgres refuses to copy a
+ database that has open sessions. The root `bun run test` runs the api, bot, worker and `@repo/db`
+ suites one at a time, because bot, worker and `@repo/db` use the test database itself.
+- Do not start two api runs at once. The second run drops the copies the first run is using.
+- With `--no-isolate`, a worker keeps one set of globals and modules across its files. A change to
+ `process.env`, `globalThis.fetch` or a process-wide provider such as `setLimits` carries into the
+ next file unless the test restores it.
+- A worker can open up to 30 Postgres connections on demand: 10 for the `@repo/db` client and 20 for
+ the Mastra store. Postgres allows 100 by default, and the dev stack uses the same server. Check
+ that limit before you raise the worker count.
+
+The preload also hashes passwords with scrypt at its lowest cost, because nearly every test creates
+users. `apps/api/bunfig.toml` loads it for `bun test` only.
+
+## S3
+
+A test that uploads a file or writes an agent skill needs RustFS and `S3_*` in `.env.test`, and
+fails without them. `docker compose -f docker-compose.dev.yml up -d` starts RustFS and creates the
+bucket. The Docker test gate (`docker-compose.test.yml`) starts its own throwaway RustFS.
+
+## Layout
+
+Test files are in `__tests__/` folders, mostly inside the module they cover:
+
+- `integration/`: Treaty against the app and the test database.
+- `unit/`: pure functions, imported directly, with no session, HTTP or query.
+
+Helpers are in `src/__tests__/helpers/` and are imported as `#tests/helpers/<file>`:
+
+- `api` is the anonymous client. `authedApi(cookie, headers?)` is a client with a session.
+- `signUpTestUser(overrides?)` returns `{ cookie, userId, email, username, workspaceId }`.
+- `resetDb()` empties the `public` schema except `__drizzle_migrations` and `oauth_resource`. Each
+ test file calls it in its own `beforeEach`. The preload does not call it.
+
+The same folder has helpers for projects, agents, roles, members, limits, MCP and credentials.
+`modules/god/__tests__/helpers.ts` and `modules/scim/__tests__/helpers.ts` serve those modules.
diff --git a/docs/dev/auth.md b/docs/dev/auth.md
new file mode 100644
index 00000000..11b41c6b
--- /dev/null
+++ b/docs/dev/auth.md
@@ -0,0 +1,322 @@
+# @repo/auth: how it works
+
+The rules are in `packages/auth/AGENTS.md`.
+
+- `src/index.ts` builds the better-auth instance in `createAuth()`, with the Drizzle adapter
+ (`provider: "pg"`) over `@repo/db`. `auth` is a proxy that calls `createAuth()` on first use.
+ Email+password is enabled (`autoSignIn: true`; whether the address has to be confirmed first
+ is an instance setting, see below).
+- The plugins are passkey (`@better-auth/passkey`), API key, magic link, username, the instance
+ OIDC provider, `jwt()` and `mcp()` (HTTPS or a loopback host only), and `openAPI()`.
+- `emailAndPassword.revokeSessionsOnPasswordReset` is `true`: a reset ends every session of that
+ account, since a reset is how a stolen password is dealt with. The signed-in change-password
+ form in the web app sends `revokeOtherSessions` for the same reason. Neither touches personal
+ API keys or an MCP client's refresh tokens.
+
+## User role
+
+The user table has a `role` column (`"god"` | `"user"`), declared as a better-auth
+`additionalField` with `input: false` (not client-settable). A `databaseHooks.user.create.before`
+hook sets it: the first user to register gets `"god"`, everyone after gets `"user"`.
+
+`databaseHooks.user.create.after` calls `ensurePersonalWorkspace`, which gives an account that
+owns no workspace one named after the person: the `"god"` account always, every other account
+while `personalWorkspaces` is on in the auth settings. `authContext` in apps/api calls the same
+function on every authenticated planner request, and an MCP tool call reaches a planner route.
+So an account made by SCIM (a direct insert, which passes no hook), made while the setting was
+off, or left with no workspace after deleting or handing over its own gets one on its next such
+request, while the setting is on. `/me` does not pass through `authContext`. An agent's bot user
+never gets one.
+
+Each process keeps a set of accounts that need nothing (`settled`), so for them a request costs
+no query. `forgetPersonalWorkspace` removes an account from the set in that process only. With
+the setting off, a non-god account outside the set reads `app_setting` on each request.
+
+`lastSeenAt` is another `additionalField`, with `input: false` and `returned: false`, so
+better-auth leaves it out of a cookie session's response. A user loaded for an API key or an MCP
+token still holds it, and the `/me` response leaves it out. apps/api writes it in the same
+`authContext` step, at most once an hour per account, whether the request came with a session,
+an API key or an MCP OAuth token. `/me` writes nothing. god's users list shows it as "Last seen".
+Sessions are deleted on sign-out, so they are no record of when someone last used the app.
+
+## Instance settings (`src/instance.ts`)
+
+Registration mode, which sign-in methods are offered, the mail provider, the OAuth credentials
+and the SCIM token are stored in the database, so god mode can change them without a restart.
+The mail From address falls back to env (`EMAIL_FROM`, then `NOTIFICATIONS_EMAIL_FROM`).
+
+- `app_setting` key `auth` → `{ registration, requireEmailVerification, magicLink,
+ emailPassword, trustProviderEmails, personalWorkspaces, inviteTtlDays, inviteSearch,
+ allowedEmailDomains }`.
+- `app_secret` keys `auth.email`, `auth.google`, `auth.oidc` and `auth.scim` → the mail
+ provider, Google, the OIDC provider and the instance's SCIM token, set in god mode.
+- `app_secret` key `workspace.<id>.scim` → a workspace's SCIM token, set by the workspace owner.
+ Those routes answer 403 unless a build turns per-workspace SCIM on.
+
+Each secret is encrypted with `@repo/crypto` and has a `redacted` mirror. The settings routes
+decrypt the value and build their DTO from it. `workspacesWithOwnScim` and the worker's telemetry
+read the mirror, which needs no key. No route returns a stored secret. A new SCIM token is
+returned once, by the request that generates it.
+
+The mail provider is read by the api and the worker as well, so its shape and reader are in
+`@repo/db` (`domains/instance-email.ts`). `src/instance.ts` holds the write side god mode drives.
+
+"Invite only" means the address has a pending `team_invite` that has not expired
+(`hasPendingInvite`). An invite expires `inviteTtlDays` after it was created (7 by default, 0 for
+never, at most 3650). `inviteValidSince` computes the cutoff from the current setting on every
+read, so a change applies to existing invites: a shorter lifetime expires them, and a longer one
+or 0 brings expired ones back. An expired invite does not admit its address at the registration
+gate and cannot be accepted. A new invite for the same address to the same team or project
+replaces it. While the invite is live, a new one gets 409 `INVITE_ALREADY_PENDING`.
+
+Invites are created and revoked inside a team or one of its projects, so `team_invite` is the
+only invite table. God mode's invite settings are `inviteTtlDays` and `inviteSearch`.
+
+`hooks.before` runs the registration gate on `/sign-up/email` (see "Registration gate"). While
+verification is required it also holds back `/sign-in/email` and `/sign-in/username`: an existing
+account with an unconfirmed address gets 403 `EMAIL_NOT_VERIFIED`, better-auth's own code for it.
+The check runs before the password is compared, so a wrong password gets the same answer. It
+also applies to accounts made before the setting was turned on. It covers password sign-in only:
+a magic link confirms the address itself, and a Google or OIDC sign-in is not held back.
+`authError` in `features/auth/services` maps that code, and the sign-in form then offers the
+confirmation link again when an address was typed. A deactivated account and a disabled password
+form are 403s too, so the form goes by the code.
+
+The requirement needs a mail provider: the api refuses to turn it on without one, and
+`setEmailSettings` clears it when the provider is removed. So the gate, the sign-up endpoint and
+the public `/auth-config` read the setting alone. `magicLink` is refused and cleared the same way,
+so the magic-link sender reads only the setting. `/auth-config` answers it as the setting and the
+provider together.
+
+`emailAndPassword.requireEmailVerification` is a getter over a module variable that
+`hooks.before` refreshes from the setting on every password endpoint. better-auth reads the
+option off the options object when `/sign-up/email` decides whether to open a session, so this is
+what makes a required confirmation answer sign-up with `token: null` and no cookie instead of a
+working session.
+
+Authentication email (`src/mail.ts`) goes out through `@repo/mailer` and is best effort: with no
+provider configured, or when the provider rejects the message, it logs and returns false, and the
+endpoint answers as if the mail went out. Three kinds are sent: password reset, address
+confirmation, and the magic link. The handler runs on the API origin, so the web app passes
+`callbackURL`, `redirectTo` and, for a magic link, `errorCallbackURL` in `features/auth/services`.
+The session confirmation on the Security page sends its own magic link from
+`features/account/hooks/useConfirmSession.ts`.
+
+With confirmation required, sign-up opens no session. A new address gets its user back. An address
+that already has an account gets a made-up user, the same `token: null` and no mail, so the answer
+does not reveal that the address is taken. The web sign-up shows a "confirm your email" screen for
+both instead of entering the app, and the link opens the session (`autoSignInAfterVerification`).
+
+## Username
+
+The `username()` plugin adds `username` / `display_username` to the user table and the
+`/sign-in/username` endpoint. Nobody is asked for a name: `databaseHooks.user.create.before` calls
+`generateUsername`, which takes the local part of the address in lower case, removes everything
+the plugin's validator rejects, cuts it to 27 characters and uses `user` when nothing is left. It
+appends three random digits when that name is taken or is shorter than the 3-character minimum.
+SCIM calls `generateUsername` too, since its direct insert passes no hook. An agent's bot user is
+a direct insert that sets no username, so its username stays NULL.
+
+The owner changes the name afterwards through `updateUser`. The plugin checks it against other
+accounts on `/update-user` and `/sign-up/email`.
+
+A username also addresses an agent in a mention, and a mention is resolved against the project's
+members and its agents at once, so the two share one namespace. A member's name must differ from
+every agent's on the instance, and an agent's from every member's. Agents of different teams may
+share a handle (`ai_agent_team_username_uq`). Every path that sets a member's name checks it
+against `ai_agent`: `hooks.before` refuses an `/update-user` that takes a name an agent already
+uses, `databaseHooks.user.create.before` refuses a sign-up that carried one, and
+`generateUsername` skips such a name. The check for the other direction is in the api, where an
+agent is created or renamed.
+
+The plugin's `/is-username-available` takes no session, so it is in `disabledPaths` and answers
+404.
+
+The sign-in screen has one field for both identifiers and picks the endpoint by whether what was
+typed contains an "@". The verification gate in `hooks.before` runs before the plugin's own check
+of `emailAndPassword.requireEmailVerification`.
+
+## Generic OIDC
+
+One OIDC/OAuth2 provider, discovered from the well-known document the operator points it at in god
+mode (`app_secret` key `auth.oidc`). It is a social provider with the id `OIDC_PROVIDER_ID`
+(`"oidc"`): sign-in is `/sign-in/social` with that provider, the callback is `/callback/oidc`, and
+it reuses the `account` table, so it adds none.
+
+A provider per workspace is not built on this one. A sign-in through it joins the account that
+already holds the address, which is safe only because the provider is the instance owner's: a
+workspace owner's provider could name any address. A per-workspace provider needs the workspace
+to prove it owns the address's domain first, and is not part of this repository.
+
+`providerId` is a constant because it is what the `account` rows store, and the rows hold the OIDC
+`sub` (`accountSubject`). genericOAuth reads the discovery document once, when its plugin starts,
+while this provider changes in god mode without a restart. So better-auth holds a proxy
+(`oidcProvider`, registered by the `instanceOidc` plugin), and `refreshOidcProvider()` in
+`hooks.before` builds the real provider with genericOAuth from the stored settings whenever they
+change, on both halves of the round trip. When the provider is off or incomplete, the request is
+refused with `OIDC_DISABLED`.
+
+The redirect URI registered with the identity provider is `OIDC_REDIRECT_URI`,
+`/api/auth/oauth2/callback/oidc`. The api passes that path on to better-auth's
+`/api/auth/callback/oidc`, so the URI the identity providers hold stays valid.
+
+Signing out leaves the session at the identity provider alone (`disableProviderLogout`). No screen
+offers linking an OIDC identity to the signed-in account, so `hooks.before` refuses `/link-social`
+for it. Only the standard `email_verified` claim says the address is verified: the OIDC
+`mapProfileToUser` reads `true` and `"true"` as verified and anything else, `"false"` included, as
+not.
+
+## Turning password authentication off
+
+`AuthSettings.emailPassword` (default `true`). When it is off, `hooks.before` refuses every path in
+`PASSWORD_PATHS` with 403 `PASSWORD_AUTH_DISABLED`: the two sign-in endpoints, sign-up, password
+reset, and both halves of the magic link, so a magic link issued before the setting changed cannot
+be redeemed. Passkeys stay available: a passkey is only ever added to an account that already
+exists. A confirmation link is not covered: `/send-verification-email` and `/verify-email` stay
+open, and `autoSignInAfterVerification` opens a session for an unconfirmed account.
+
+The setting is read per request. `emailAndPassword.enabled` cannot do this job: better-auth reads
+it only on `/sign-up/email` and `/sign-in/email`, so `/sign-in/username`, password reset and the
+magic link would stay open. `disabledPaths` is a static array.
+
+The api refuses to turn it off while neither Google nor OIDC is usable, and refuses to make the
+last usable provider unusable while it is off (`assertUsableSignInMethod`). Usable means the
+provider is enabled with its credentials stored, plus a discovery URL for OIDC. Neither check
+contacts the provider, so a wrong secret or a discovery URL that does not answer passes it, and
+sign-in then fails.
+
+## Passkey
+
+`passkey({ rpID, rpName, origin })` adds WebAuthn. `rpID` is the hostname the credential binds to:
+the host of the first `APP_URL` entry, or `PASSKEY_RP_ID` when it is set. `rpName` is
+`PASSKEY_RP_NAME`, "It's a Plan" by default. The compose files and the Helm chart pass neither
+variable to the api. `origin` is the whole `APP_URL` list, because the WebAuthn ceremony runs in
+the frontend JS. The plugin adds the `passkey` table, which is mapped in the drizzle adapter's
+`schema`. localhost is a secure context, so passkeys work over http in dev.
+
+## Google sign-in
+
+The credentials are stored in the database (`app_secret` key `auth.google`, encrypted), so god mode
+can change them without a restart.
+
+`socialProviders.google` is a factory that returns the module-level `googleOptions` object.
+better-auth builds the provider list once per process, on first use, but the provider keeps that
+object by reference and reads `clientId` / `clientSecret` off it on every call. So
+`refreshGoogleOptions()` in `hooks.before` reloads it on `/sign-in/social`, `/link-social` and
+`/callback/google`, and refuses the request when the credentials are missing or the toggle is off.
+
+By default a provider address that has an account but no link to that identity signs into the
+account only when the provider reports the address verified and the account's email is confirmed.
+Otherwise the callback redirects with `account_not_linked`. The `trustProviderEmails` instance
+setting drops both conditions: `resolveTrustedProviders` then names Google and the OIDC provider,
+and `requireLocalEmailVerified` reads false.
+
+## Registration gate
+
+`assertRegistrationAllowed` runs in two places. `hooks.before` runs it on `/sign-up/email`, and
+`databaseHooks.user.create.before` runs it for every account better-auth creates, which is what
+applies closed/invite-only to a Google, OIDC or magic-link sign-up. SCIM accounts and agent bot
+users are written with a direct insert and never reach it.
+
+It refuses with 403 and `REGISTRATION_CLOSED` on a closed instance, `EMAIL_DOMAIN_NOT_ALLOWED` when
+the address is not at one of `allowedEmailDomains` (an empty list admits any), and on an invite-only
+instance `INVITE_ONLY` when the address has no pending invite and `INVITE_EXPIRED` when its only
+invites have expired. The domain check runs first, so an invited address outside the list gets
+`EMAIL_DOMAIN_NOT_ALLOWED`.
+
+`INVITE_EXPIRED` reveals that the address was invited, so it is given only in the create hook,
+where a provider or a magic link has proven the address. The hook treats any provider as proof and
+does not read `email_verified`. The email form, open to anyone, gets `INVITE_ONLY`. The `APIError`s
+carry a `code` because the provider callback and the magic link turn that into the `?error=` they
+redirect with; without one the callback fails the request instead.
+`registration-refusal-redirect.test.ts` pins that redirect, and `invite-forms.test.ts` pins
+`INVITE_EXPIRED` on a magic link and `INVITE_ONLY` on the email form.
+
+A domain in `allowedEmailDomains` matches the part of the address after the "@" exactly, so a
+subdomain is listed on its own. The list applies to new accounts only. The api also refuses to
+invite an address that has no account and is outside it, since it could not register. The gate asks
+`registrationEmailAllowed`, which checks the list unless a build installs its own policy with
+`setRegistrationEmailPolicy`.
+
+## API keys
+
+`apiKey({ enableSessionForAPIKeys: true })` makes an `x-api-key` header resolve to the owner's
+session, so a key is a full-account credential. It therefore expires:
+`keyExpiration.defaultExpiresIn` is 90 days and `maxExpiresIn` is a year, and the create dialog in
+the web app offers 30/90/180/365 days. The plugin's option is documented as milliseconds but its
+handler passes the value to `getDate(value, "sec")`, so `API_KEY_DEFAULT_EXPIRES_IN_SEC` is in
+seconds. `maxExpiresIn` is in days, as the plugin reads it. The plugin treats a NULL `expires_at` as
+no expiry. No migration sets one, so a personal key made before v1.0.0 works until its owner
+deletes it.
+
+The plugin resolves a key to the owner's session on every better-auth endpoint, and what that
+session sets up there stays after the key is gone: a passkey enrolled with it signs in after the key
+is deleted and the password reset, and a new key renews the expiry. So the first check in
+`hooks.before` refuses any request that carries an `x-api-key` header: a key is for the planner API,
+and the account is managed from a signed-in session. The connected-apps routes refuse a key too. The
+check reads `ctx.request`, which a server-side `auth.api.*` call does not carry, so `issueKey` and
+`getSessionFromHeaders` are unaffected. `hooks.before` also refuses an `/api-key/update` that carries
+`expiresIn`: a longer life is a new key.
+
+An agent's key carries no expiry. An agent replays its stored secret with nothing that would renew
+it, and an external agent's operator rotates it through `regenerate-key`. The plugin applies the
+default to every key it creates, so `issueKey` in `apps/api/src/modules/agents/core/service.ts`
+clears `expires_at` on the row afterwards.
+
+A key the plugin refuses with a 401 or 403 (expired, disabled, unknown or malformed) makes it throw
+out of `auth.api.getSession` rather than return no session. `getSessionFromHeaders` turns that into
+"no session", so an expired key is answered with a 401 instead of a 500. It rethrows any other
+refusal, such as a rate-limited key's 429.
+
+## MCP OAuth
+
+`mcp()` from `@better-auth/mcp` serves OAuth 2.1 to MCP clients, with `jwt()` signing the access
+tokens. A client that requests a token without the `resource` parameter gets an opaque token, which
+`/mcp` refuses. `mcp()` adds the `oauth_client`, `oauth_resource`, `oauth_client_resource`,
+`oauth_refresh_token`, `oauth_access_token`, `oauth_consent` and `oauth_client_assertion` tables,
+and `jwt()` adds `jwks`. `mcp()` writes the MCP resource (`<API_URL>/mcp`) into `oauth_resource`
+when the auth instance is created, on its first use, and leaves an existing row as it is. Any client
+registers itself (RFC 7591), as ChatGPT and Claude do. The provider asks the person for consent the
+first time a client asks for their account. Only `authorization_code` and `refresh_token` are
+granted, so every token acts for a person. A registration that also lists a grant the server does
+not issue, as Claude's connector does with `jwt-bearer`, is registered with the supported grants.
+One that lists none of them is refused.
+
+MCP clients register without `application_type`, and `mcp()` infers it
+(`clientRegistrationDefaultApplicationType: 'infer'`): a client whose callback is http on
+`localhost`, `127.0.0.1` or `[::1]` (Claude Code) or uses a custom scheme such as Cursor's
+`cursor://` is registered as `native`, and any other as `web`, which takes an https callback only.
+better-auth's own default, `web`, refuses the first two. A client that sends its `application_type`
+keeps it.
+
+The issuer is `API_URL` itself, path included, so the tokens and the discovery documents name the
+URL a client reaches. The api serves the documents at the root of its origin
+(`oauthAuthorizationServerMetadata`, `openIdConfiguration`, `oauthProtectedResourceMetadata`), and
+the endpoints in them get the path back the way the links in auth emails do.
+
+`verifyMcpAccessToken` checks a token against the instance's own keys in-process, with `iss` set to
+`API_URL` and `aud` to `<API_URL>/mcp`, so changing `API_URL` ends every issued token. It refuses a
+DPoP-bound token (`cnf` claim), because it takes no proof. Then it reads what a JWT cannot carry:
+
+- The account must not be deactivated. This ends every MCP token of the account at once, whichever
+ way it was deactivated. God mode also deletes the account's sessions and OAuth tokens. SCIM only
+ sets `user.active`.
+- A token issued in a session ends with that session, as better-auth's introspection has it.
+ Signing out does not disconnect a client: deleting a session sets `session_id` on its refresh
+ tokens to NULL, and a token refreshed after that carries no `sid`.
+- The token's client must still be connected to the account, through the person's consent or a
+ refresh token that is neither revoked nor expired. Disconnecting it on the account's Security page
+ (`DELETE /account/connected-apps/:clientId`) deletes the consent, the refresh tokens, the
+ `oauth_access_token` rows and any pending authorization code, which would otherwise connect the
+ client again. This ends its tokens at once.
+
+better-auth accepts a plain-HTTP MCP resource only on a loopback host, so any other instance without
+HTTPS leaves `mcp()` and `jwt()` out and serves MCP to API keys only.
+
+## OpenAPI reference
+
+The `openAPI()` plugin (`better-auth/plugins`) documents the auth handler. It serves a Scalar UI at
+`/api/auth/reference` and the raw schema at `/api/auth/open-api/generate-schema`. The schema is built
+from every active plugin, so the passkey and apiKey endpoints appear without any manual description.
+This is separate from the planner's own OpenAPI docs at `/docs` (the `@elysiajs/swagger` spec, which
+does not see the catch-all auth handler).
diff --git a/docs/dev/deploy-stack.md b/docs/dev/deploy-stack.md
new file mode 100644
index 00000000..3911640e
--- /dev/null
+++ b/docs/dev/deploy-stack.md
@@ -0,0 +1,30 @@
+# Deploy stack
+
+- The deploy composes do not publish the Postgres port.
+- `docker-compose.pro.yml` and `docker-compose.coolify-pro.yml` run the published Pro images:
+ migrate from `vendor/itsaplan/packages/db/src/migrate.ts`, start the api with `./pro-api`. The
+ Helm chart does the same with `values-pro.yaml`, which sets the Pro image repositories and
+ `pro: true`. `pro: true` alone selects only the two paths, so the core images fail on it.
+- Migrations run as a separate step before the apps start:
+ - Compose: the one-shot `migrate` service. api, worker and bot wait for it.
+ - Helm: the `migrate` init container of the api pods. Worker and bot pods wait in a
+ `wait-for-migrations` init container.
+ - Both run `migrate.ts` from the api image. The api container sets its own command, which
+ replaces the image CMD, so it only starts the server.
+- The api image's own CMD also runs the migrations before the server starts. Deploy targets
+ with no separate step (Railway, a plain `docker run`) need this.
+- Every `migrate.ts` run takes a Postgres advisory lock, so runs that start together apply each
+ migration only once.
+- When migrations are pending on an existing database, `migrate.ts` runs `pg_dump` into
+ `BACKUP_DIR` (default `/backups`) before it applies them. A failed dump stops the run, and no
+ migration is applied.
+- Migrations run without a dump in three cases: on a new database, with
+ `SKIP_PRE_MIGRATION_BACKUP=1`, and through `bun run db:migrate`, which uses drizzle-kit and
+ skips `migrate.ts`, so it also takes no lock.
+- Where the dump is stored:
+ - Compose: the `db-backups` volume, mounted on the `migrate` service only.
+ - Helm: the `backups` volume of the api pods. It is an `emptyDir`, lost with the pod, unless
+ `api.backups.persistence.enabled` is true.
+ - With no volume at `/backups` (Railway, a plain `docker run`): the container filesystem, lost
+ with the container.
+- Each `migrate.ts` run deletes dumps older than `BACKUP_RETENTION_DAYS` (default 30).
diff --git a/docs/dev/i18n.md b/docs/dev/i18n.md
index 3c4a070e..66ebcc74 100644
--- a/docs/dev/i18n.md
+++ b/docs/dev/i18n.md
@@ -40,7 +40,8 @@ namespace at a time.
Add the key to `messages/en/<namespace>.json` first. Then add it to the other languages. The
English file gives the type. Thus a `t('…')` for a key that is not in that file causes a
-typecheck error. A key that is absent from a translated file causes no error.
+typecheck error. A key that is absent from a translated file shows in English at runtime, and
+`bun run lint` fails it. So does a key that is present only in a translated file.
## How to add a namespace
@@ -51,8 +52,9 @@ Make the file in each language directory. Then add the namespace to `coreMessage
There are four locations, and no migration is necessary.
-1. Copy `messages/en/` to `apps/web/messages/<code>/` and translate the files. A partial
- translation is permitted, because the other keys show in English.
+1. Copy `messages/en/` to `apps/web/messages/<code>/` and translate the files. Keep every key:
+ `bun run lint` fails a file with a missing or an extra key. A value left in English is
+ permitted.
2. Add the code to `LOCALES` in `apps/web/src/i18n/locales.ts`. Add the name of the language, in
that language, to `LOCALE_LABELS`. Add a flag to `LOCALE_FLAGS`. TypeScript types both
records by locale, thus an absent entry causes a typecheck error.
diff --git a/docs/dev/import-worker.md b/docs/dev/import-worker.md
new file mode 100644
index 00000000..c1dac466
--- /dev/null
+++ b/docs/dev/import-worker.md
@@ -0,0 +1,80 @@
+# Source imports in the worker
+
+`import-worker.ts` polls `import_job` for a due `pending` row (`import-store.ts`,
+same claim-with-lease shape as `webhook_delivery`) and advances it by one bounded
+chunk of work per tick — a large import interleaves across many ticks rather than
+running to completion in one.
+
+- `canonical.ts` — the source-independent shape an adapter produces
+ (`CanonicalIssue`, `CanonicalState`, ...). Plain types, no logic.
+- `reader.ts` — the `SourceReader` port a source adapter implements, and the
+ `SourceRateLimitedError` an adapter throws when the source's rate limit is
+ reached.
+- `import-sources.ts` — one entry per `import_job.source`: its credential and
+ config types, how to build its reader, and its issue-key prefix for Rewrite. A
+ new source needs an entry here and a `SourceReader` adapter; the phases do not
+ change. It also needs a job type and routes in
+ `apps/api/src/modules/import-export`, and a connect form with its strings in
+ the web settings.
+- `import-retry.ts` — what a failed tick does: a rate limit is waited out and
+ does not count toward the attempt limit (the claim's bump is undone), a job whose
+ source has no registry entry fails at once, any other error retries with backoff
+ until `MAX_ATTEMPTS` in a row.
+- `plane-adapter.ts` — the Plane implementation. HTTP against a Plane
+ instance via `pinnedFetch`, using the credential decrypted from the job row
+ (base URL, workspace slug, API key — never from env, since this has to work
+ against any operator's self-hosted instance). `docs/dev/plane-import-source-notes.md`
+ is the spec it follows for pagination, rate limiting, and Plane's actual wire
+ shapes.
+- `linear-adapter.ts` and `linear-mapping.ts` — the Linear implementation: its
+ GraphQL API at the fixed `https://api.linear.app/graphql` with the job's
+ personal API key, and the pure mapping from Linear's shapes. Issues in
+ Linear's trash are left out. Files uploaded into Linear text are attachments;
+ `resolveAttachmentDownload` follows `uploads.linear.app`'s redirects itself
+ and sends the key to that host only. `docs/dev/linear-import.md` has the
+ queries, limits and mapping.
+- `trello-adapter.ts` and `trello-mapping.ts` — the Trello implementation: its
+ REST API at the fixed `https://api.trello.com/1` with the job's API key and
+ token, and the pure mapping from Trello's shapes. Lists become states, cards
+ issues with their checklists and custom field values; the board's members
+ reach the job already matched with project members' emails.
+ `docs/dev/trello-import.md` has the requests, limits and mapping.
+- `cross-reference.ts` — pure text matching for a source's own "KEY-123"-style
+ issue identifier: no `@repo/db`, no network, unit-tested directly. What
+ the Rewrite phase resolves into itsaplan's own issue ids.
+- `import-store.ts` — all `@repo/db` access for imports: claiming due jobs,
+ reading/writing a job's phase/cursor/status, the `import_record`
+ source-id-to-local-id upsert, and creating the local rows (states, labels,
+ cycles, custom fields, issues, checklists, comments, watchers, issue links)
+ an import produces.
+- `import-worker.ts` — the phase state machine. Discover snapshots every
+ source id up front (`import_record` rows with no local id yet) before Create
+ begins, rather than treating the source's own pagination cursor as the
+ resumability anchor across the whole job — see the notes file's "Pagination"
+ section for why. Create/Link/Rewrite resume from `import_record`'s own id,
+ not the source's cursor. Link also gives every issue's parent link a second
+ chance to resolve, the same way it already does for relations. Rewrite scans
+ every created issue's description and comments for a mention of the
+ source's own identifier and rewrites it to this project's, purely from
+ already-local data — it makes no further requests to the source. An issue's
+ mention of itself stays as written (the Linear footer relies on it), and so
+ does an identifier that is a segment of a URL path.
+- The Attachments phase re-lists each issue's attachments (metadata alone,
+ captured during Create, is not reused — a download needs a fresh resolve of
+ the two-hop, hour-lived URL right before it happens) and downloads the
+ bytes it hasn't already created a local row for. Size and mime type are
+ checked against the instance's own upload settings (`@repo/db`'s
+ `getStorageSettings`/`mimeAllowed`) before the request; the project's
+ storage quota (`@repo/db`'s `projectStoredBytes`, `@repo/storage`'s
+ `putObject`/`attachmentObjectKey`) is checked before the upload and once
+ more inside the same advisory lock (`lockAttachmentStorage`) an interactive
+ upload takes, so the two never both pass a check that only one of them can
+ actually fit. A download that answers anything but 2xx (an error page, a
+ redirect) is refused before its body is read, and one that runs past the
+ size limit is cut off there (`attachment-download.ts`): Linear reports no
+ size, so that is its only size check. A rejected attachment
+ (`AttachmentRejectedError`: size, type, quota, or a refusal from the file
+ host) is logged and skipped. Any other error fails the tick, including an
+ SSRF refusal (`UrlNotAllowedError`), a network error and a Plane resolve
+ failure. The cursor is saved after the whole chunk, so the next tick repeats
+ that chunk, and `MAX_ATTEMPTS` failed ticks in a row fail the job.
diff --git a/docs/dev/releasing.md b/docs/dev/releasing.md
new file mode 100644
index 00000000..a5714d67
--- /dev/null
+++ b/docs/dev/releasing.md
@@ -0,0 +1,27 @@
+# Commits and releases
+
+Subject: Conventional Commit, `type(scope): summary`. PRs are squash-merged, so the PR title
+becomes the commit subject on `main` (`pr-title.yml` checks it). release-please reads the
+subjects to pick the next version and write `CHANGELOG.md`.
+
+Pick the type by what the change gives the user, not by how much code it touches:
+
+- **`feat:` — minor.** A capability that did not exist: a new entity, page, integration, or a
+ setting that unlocks behaviour. Use it only for a change that earns a "Highlights" entry.
+- **`improvement:` — patch.** A visible change to something that exists: a redesign, a
+ reworked layout, a theme, a better interaction. Not a bug fix, not a new capability.
+- **`fix:` — patch.** Behaviour that was wrong is now right.
+- **Every other type (`perf`, `refactor`, `docs`, `build`, `ci`, `test`, `chore`, `revert`) —
+ patch.**
+
+Scope: the name of one app or package (`api`, `web`, `worker`, `bot`, `db`, `auth`, …). No
+scope when the change spans several.
+
+Release config traps:
+
+- Add a new commit type to both `pr-title.yml` and `changelog-sections` in
+ `release-please-config.json`. release-please drops a type that is not in
+ `changelog-sections` from the release notes.
+- Keep `"package-name": ""` in `release-please-config.json`. Without it, release-please skips
+ every release and stops at `There are untagged, merged release PRs outstanding - aborting`.
+
diff --git a/docs/dev/scim.md b/docs/dev/scim.md
new file mode 100644
index 00000000..d62d36db
--- /dev/null
+++ b/docs/dev/scim.md
@@ -0,0 +1,118 @@
+# SCIM
+
+## api
+
+`modules/scim/` serves SCIM 2.0 (RFC 7643 / 7644) at `/scim/v2` for an identity provider
+to provision users and groups with. Three things make it unlike every other module:
+
+- **Mounted on the root app in `app.ts`, not under `planner`.** The planner's `authContext`
+ answers 401 before the bearer check could run. Authentication is one `resolve` that hands
+ the token to `verifyScimToken` from `@repo/auth`, which answers with the provider the
+ token belongs to: the instance's (`workspaceId` null) or a workspace's. Every route acts
+ for that provider, and every function in `service.ts` takes its `workspaceId`.
+- **Its own error document.** `onError` sits on a parent instance that `.use()`s the routes
+ and answers only for paths under `/scim/v2`, handing everything else back to the planner's
+ handler. Two reasons for that shape: an `onError` beside the routes widens the inferred
+ response type of every one of them with the body it returns (which then reaches the Eden
+ client as a success shape), and Elysia propagates the handler to the root app either way.
+- **Bodies are `t.Any()`.** SCIM defines its own schemas and clients send attributes this app
+ ignores, so `resource.ts` validates instead and raises `ScimError`, which carries the
+ `scimType` a provisioning client branches on. Responses are declared per route from
+ `model.ts` — `scimErrors(...)` is the SCIM-shaped counterpart of `shared/responses.ts`.
+
+Filtering is `<attribute> eq "<value>"` only, over the attributes each resource lists in
+`service.ts`; that is what Okta, Entra and Authentik send, and `ServiceProviderConfig`
+advertises exactly that. A create inserts the `user` row directly, the way `createAgent`
+does, which deliberately skips the registration gate — with SCIM on, the identity provider
+brings people in, and that is what makes `registration: 'closed'` plus SSO work.
+
+An account is one `user` row across the instance. What a provider says about a person — its
+own id for them and whether they are active — is a `scim_user` row per (provider, user), where
+`workspace_id` is null for the instance's provider. Groups belong to a provider
+(`scim_group.workspace_id`, null for the instance's), their names are unique within it, and
+their members must be accounts it sees. A create for an address that has an account links
+it. The group mappings are in `scim/mappings.ts`; they and the settings are served from god
+mode (`/god/scim/...`) and, for a workspace, from `modules/workspaces/` (`/workspaces/:id/scim/...`).
+
+- **The instance's provider** is god's, set up in god mode, and every build has it. Its
+ token reads `scim_<secret>`. The provider sees every account, PUT and PATCH write the name
+ and address, a group maps to any project, and DELETE removes the account the way god mode
+ does (409 for the only owner of a project outside the workspaces they own, whose projects
+ pass to the instance owner).
+ A deactivated account (`user.active` false, written alongside `scim_user.active`) keeps
+ its teams and projects but cannot sign in, and `isAccountDeactivated` makes
+ `authContext`, `/me` and the MCP key check refuse what it already holds.
+ God mode writes `user.active` too (`POST /god/users/:userId/deactivate` and
+ `/reactivate` in `modules/god/`) while the instance's provider does not manage accounts
+ (`accountsManagedByScim` from `@repo/auth`), and answers 409 while it does. Deactivating
+ there also deletes the account's sessions, its MCP OAuth tokens and the pending invites
+ it created; its API keys are kept and answer 401 until it is reactivated. The instance
+ owner and an agent's account are refused (403). The user list and detail carry
+ `activeLock` (`owner`, `agent` or `scim`), the reason the switch is locked, or null.
+- **A workspace's provider**, where a hosted build turns `setWorkspaceScim()` on, decides
+ who is in the workspace, not who has an account, so the same person can be linked by
+ several workspaces. Its token reads `scim_<workspaceId>_<secret>`. It sees the accounts it
+ linked and the people in the workspace's teams (`inWorkspace` in `service.ts`), a name or
+ address it sends is accepted and the account keeps its own, and a group maps to projects
+ of its workspace only. The instance's groups grant nothing in a workspace that set up
+ SCIM of its own (`workspacesWithOwnScim`): `reconcile.ts` leaves them out there, the
+ mapping picker leaves its projects out, and turning that workspace's SCIM on or off
+ reconciles its mapped projects (`reconcileWorkspaceGrants` in `scim/mappings.ts`).
+
+A create first asks the installed policy whether the provider may provision the address
+(`email-policy.ts`, with `workspaceId` null for the instance's). By default it allows any
+address, since only god sets up the instance's provider; a hosted build calls
+`setScimEmailPolicy` with a check against the domains a workspace has verified, and a refused
+address answers 400 `invalidValue`.
+
+Set up per workspace, deactivation (`active: false`) and DELETE take the person out of every
+team of the workspace through `dropWorkspaceMemberships` in `teams/service.ts`, invite memberships
+included, and a team or project they owned alone passes to the workspace owner. Neither
+touches the account or its sessions. A deactivated person stays linked, so the provider can
+turn them back on, and `reconcile.ts` grants them nothing through the groups until then.
+
+The `god`-role account is refused (409), because nothing about the instance owner is
+provider-owned; set up per workspace, so is the workspace owner, who receives what a
+deprovisioned person owned alone. A create for an address the provider already linked
+with an `externalId` is refused the same way — it is a retry, not a new person, and must not
+overwrite the link the first create wrote.
+
+A group member removal arrives in two shapes: `path: 'members'` with the id(s) to drop in
+`value`, or RFC 7644 §3.5.2.2's path filter, `path: 'members[value eq "<id>"]'`, which Okta
+sends and which carries no `value` at all. `resource.ts`'s `memberFilterIds` reads the
+second shape; a `PATCH /Groups/:id` remove that only checked `value` would silently drop
+nothing for a provider that sends the filter form.
+
+The `scim_group` / `scim_group_member` tables have two writers, not one. A SCIM sync is
+the obvious one, but a group can also be embedded right on a resource instead of pushed on
+its own: `resource.ts`'s `groupDisplayNames` reads a SCIM User's `groups` attribute, and
+`oidc-sync.ts` reads an OIDC sign-in's `groups` claim off the ID token stored on the linked
+`account` row, decoded with no signature check since it already crossed a trusted, TLS
+channel and is read only for a claim, not for authentication. Both funnel into
+`syncEmbeddedGroups`, the same additive-only join a group pushed through `POST /Groups`
+gets — a name missing from a later sync is never removed by this path, only by an explicit
+`PATCH /Groups/:id` or an unmapping in the workspace settings.
+
+
+## @repo/auth
+
+What a provider says about a person is kept per provider in `scim_user`, written by
+`apps/api`. The instance's provider is set up in god mode and stored with `workspace_id`
+null; a hosted build also lets every workspace set up its own with `setWorkspaceScim()`
+(`workspaceScim()` reads it). The instance's provider writes `active`, one more
+`additionalField` on the user table (nullable, so every check is `active !== false`).
+God mode writes `active` too, from the users table, while that provider does not manage
+accounts (`accountsManagedByScim`: its SCIM on with a token); while it does, `apps/api`
+answers god's switch with 409. An account with `active` false (`isAccountDeactivated`) is
+refused at sign-in by the `session.create.before` hook with `ACCOUNT_DEACTIVATED`, which
+covers every sign-in method at once; `apps/api` refuses the sessions and keys it already
+holds. A workspace's provider decides who is in the workspace, not who has an account;
+`active` is not written for it, and nothing here refuses a session.
+
+`getScimSettings` / `rotateScimToken` / `verifyScimToken` take the workspace, or null for the
+instance, and hold the bearer token the SCIM endpoints in `apps/api` authenticate with. The
+instance's is stored under `auth.scim` and reads `scim_<secret>`; one it held while it
+belonged to the first workspace reads `scim_<id>_<secret>` and keeps working. A workspace's
+is stored under `workspace.<id>.scim` and reads `scim_<workspaceId>_<secret>`, so
+`verifyScimToken` checks the instance's first and then reads only the named workspace's.
+The token is returned in the clear exactly once, when it is generated; only its prefix is
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 3486c287..5408efe5 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -1,352 +1,41 @@
# @repo/auth
-The **server-side** better-auth instance. Consumed by `apps/api`. See root `AGENTS.md`.
-
-- `src/index.ts` — `export const auth = betterAuth({...})` with the Drizzle adapter
- (`provider: "pg"`) over `@repo/db`. Email+password enabled (`autoSignIn: true`;
- whether the address has to be confirmed first is an instance setting, see below),
- plus the WebAuthn passkey plugin (`@better-auth/passkey`).
-- Exports `auth`, `USER_ROLES` / `UserRole`, `generateUsername` (the SCIM module derives a
- handle with the same rule), `getSessionFromHeaders`, plus `Auth` / `Session` types.
-- `emailAndPassword.revokeSessionsOnPasswordReset` is `true`: a reset ends every session
- of that account, since a reset is how a stolen password is dealt with. The signed-in
- change-password form in the web app sends `revokeOtherSessions` for the same reason.
-
-## User role
-
-The user table has a `role` column (`"god"` | `"user"`), declared as a better-auth
-`additionalField` with `input: false` (not client-settable). A `databaseHooks.user.create.before`
-hook sets it: the first user to register gets `"god"`, everyone after gets `"user"`.
-`databaseHooks.user.create.after` gives the account a workspace of its own, named after
-the person (`ensurePersonalWorkspace`): the `"god"` account always, every other account
-while `personalWorkspaces` is on in the auth settings. apps/api
-calls the same function on every request, so an account made before, by SCIM (a direct
-insert, which passes no hook) or while the setting was off gets its own on its next
-request. It remembers per process who needs nothing, so a request costs a lookup; an
-agent's bot user never gets one.
-
-`lastSeenAt` is one more `additionalField`, with `input: false` and `returned: false`, so
-the session does not carry it. apps/api writes it from the same per-request step, at most
-once an hour per account, whether the request came with a session, an API key or an MCP
-OAuth token; god's users list shows it as "Last seen". Sessions are deleted on sign-out,
-so they are no record of when someone last used the app.
-
-## Instance settings (`src/instance.ts`)
-
-Registration mode, which sign-in methods are offered, the mail provider, the OAuth
-credentials and the SCIM token are stored in the database, not in env, so god mode and the
-workspace settings can change them without a restart. Read them
-through this module — never inline a query on `app_setting` / `app_secret` elsewhere.
-
-- `app_setting` key `auth` → `{ registration, requireEmailVerification, magicLink,
- emailPassword, trustProviderEmails, personalWorkspaces, inviteTtlDays, inviteSearch,
- allowedEmailDomains }`.
-- `app_secret` keys `auth.email`, `auth.google`, `auth.oidc` and `auth.scim` → the mail
- provider, Google, the OIDC provider and the instance's SCIM token, set in god mode;
- `workspace.<id>.scim` → a workspace's SCIM token, set by the workspace owner. All encrypted with `@repo/crypto`, each with a `redacted`
- mirror for the settings UI. Secrets never leave the server.
-
-The mail provider is read by the api and the worker as well, so its shape and reader
-live in `@repo/db` (`domains/instance-email.ts`); what is here is the write side god
-mode drives.
-
-"Invite only" means the address has a pending `team_invite` that has not expired
-(`hasPendingInvite`). An invite expires `inviteTtlDays` after it was created (7 by
-default, 0 for never, at most 3650; `inviteValidSince` gives the cutoff): it then neither gates
-registration nor can be accepted, and a new invite for the same address replaces it.
-Invites are created and revoked inside a team, so there is no instance-level invite
-table and god mode has no invite section — do not add one; god mode only sets how long
-they last.
-
-`hooks.before` gates `/sign-up/email` (closed → 403, an address outside
-`allowedEmailDomains` → 403, invite → no pending, unexpired invite for that address → 403)
-and holds back `/sign-in/email` for an unconfirmed address while verification is required, with 403
-`EMAIL_NOT_VERIFIED`, better-auth's own code for it. The sign-in form reads that code to offer the
-confirmation link again; a deactivated account and a disabled password form are 403s too. The requirement never outlives the mail provider: the api
-refuses to turn it on without one, and `setEmailSettings` clears it when the provider
-is removed, so the setting alone is what the gate, the sign-up endpoint and the
-public `/auth-config` read — none of them checks the provider again. The sign-in links
-(`magicLink`) follow the same rule, so the magic-link sender reads only the setting.
-
-`emailAndPassword.requireEmailVerification` is a getter over a module variable that
-`hooks.before` refreshes from the setting on every password endpoint. better-auth
-reads the option off the options object when `/sign-up/email` decides whether to
-open a session, so this is what makes a required confirmation answer sign-up with
-`token: null` and no cookie instead of a working session. Do not replace the getter
-with a static value: `true` would lock every account out the moment the setting is
-turned off, and `false` hands an unconfirmed sign-up a session.
-
-Authentication email (`src/mail.ts`) goes out through `@repo/mailer` and is best
-effort: with no provider configured it logs and returns false rather than failing the
-request. Three kinds are sent: password reset, address confirmation, and the magic
-link. Every link must carry a `callbackURL`/`redirectTo` on the **web** origin — the
-handler runs on the API origin, so a link built without one lands the reader on the
-API, which renders nothing. The web app passes them in `features/auth/services`.
-
-With confirmation required, sign-up returns the user and no session; the web sign-up
-shows a "confirm your email" screen instead of entering the app, and the link opens
-the session (`autoSignInAfterVerification`).
-
-## Username
-
-The `username()` plugin adds `username` / `display_username` to the user table and the
-`/sign-in/username` endpoint. Nobody is asked for a name: `databaseHooks.user.create.before`
-derives one from the address — the local part, with everything the plugin's validator
-rejects removed — and appends three random digits when that name is taken or is shorter
-than the 3-character minimum. The owner changes it afterwards through `updateUser`, which
-is where the plugin enforces uniqueness. Accounts that predate the column are filled in by
-`drizzle/0087_username_backfill.sql`, which repeats the same rule in SQL; agent bot users
-are skipped there, and their direct insert never reaches the hook, so their username stays
-NULL.
-
-A username also addresses an agent in a mention, and a mention is resolved against the
-project's members and its agents at once, so the two share one namespace. Every path that
-sets a member's name checks it against `ai_agent`: `hooks.before` refuses an `/update-user`
-that takes a name an agent already uses, `databaseHooks.user.create.before` refuses a
-sign-up that carried one, and `generateUsername` skips such a name. The check for the other
-direction sits in the api, where an agent is created or renamed.
-
-The plugin's `/is-username-available` is in `disabledPaths` and answers 404. It takes no
-session, and a username comes from the address, so it would tell a stranger which
-addresses are registered.
-
-The sign-in screen has one field for both identifiers and picks the endpoint by whether
-what was typed contains an "@". The instance verification gate in `hooks.before`
-covers `/sign-in/username` as well as `/sign-in/email`, and runs before the plugin's
-own check of `emailAndPassword.requireEmailVerification`.
-
-## Generic OIDC
-
-One OIDC/OAuth2 provider, discovered from the well-known document the operator points it
-at in god mode (`app_secret` key `auth.oidc`). It is a social provider with the id
-`OIDC_PROVIDER_ID` (`"oidc"`): sign-in is `/sign-in/social` with that provider, the
-callback is `/callback/oidc`, and it reuses the `account` table, so it adds none.
-
-A provider per workspace is not built on this one. A sign-in through it joins the account
-that already holds the address, which is safe only because the provider is the instance
-owner's: a workspace owner's provider could name any address. It needs the workspace to
-prove it owns the address's domain first, and is left to a hosted module, which adds its
-settings section through `useWorkspaceSections` in the web app's `@/cloud` seam.
-
-`providerId` is a constant because it is what the `account` rows store, and the rows hold
-the OIDC `sub` (`accountSubject`). genericOAuth reads the discovery document once, when
-its plugin starts, while this provider changes in god mode without a restart. So
-better-auth holds a proxy (`oidcProvider`, registered by the `instanceOidc` plugin), and
-`refreshOidcProvider()` in `hooks.before` builds the real provider with genericOAuth from
-the stored settings whenever they change, on both halves of the round trip.
-
-The redirect URI registered with the identity provider is `OIDC_REDIRECT_URI`,
-`/api/auth/oauth2/callback/oidc`. The api passes that path on to better-auth's
-`/api/auth/callback/oidc`, so the URI the identity providers hold stays valid.
-
-Signing out leaves the session at the identity provider alone (`disableProviderLogout`).
-No screen offers linking an OIDC identity to the signed-in account, so `hooks.before`
-refuses `/link-social` for it; better-auth already attaches a sign-in to a matching
-confirmed address on its own, when the provider reports the address verified. Only the
-standard `email_verified` claim says the address is verified: the OIDC `mapProfileToUser`
-reads `true` and `"true"` as verified and anything else, `"false"` included, as not.
-
-## Turning password authentication off
-
-`AuthSettings.emailPassword` (default `true`). When it is off, the first branch of
-`hooks.before` refuses every path in `PASSWORD_PATHS` — the two sign-in endpoints, sign-up,
-password reset, and both halves of the magic link, so a link issued before the switch was
-flipped cannot still be redeemed. Passkeys stay available: a passkey is only ever added to
-an account that already exists.
-
-Like every other instance setting this is read per request, so it cannot be
-`emailAndPassword.enabled: false` (evaluated at startup) and cannot live in `disabledPaths`
-(a static array). The api refuses to turn it off while neither Google nor OIDC is usable,
-which is what stops an instance being left with no way in.
-
-## SCIM
-
-What a provider says about a person is kept per provider in `scim_user`, written by
-`apps/api`. The instance's provider is set up in god mode and stored with `workspace_id`
-null; a hosted build also lets every workspace set up its own with `setWorkspaceScim()`
-(`workspaceScim()` reads it). The instance's provider writes `active`, one more
-`additionalField` on the user table (nullable, so every check is `active !== false`).
-God mode writes `active` too, from the users table, while that provider does not manage
-accounts (`accountsManagedByScim`: its SCIM on with a token); while it does, `apps/api`
-answers god's switch with 409. An account with `active` false (`isAccountDeactivated`) is
-refused at sign-in by the `session.create.before` hook with `ACCOUNT_DEACTIVATED`, which
-covers every sign-in method at once; `apps/api` refuses the sessions and keys it already
-holds. A workspace's provider decides who is in the workspace, not who has an account;
-`active` is not written for it, and nothing here refuses a session.
-
-`getScimSettings` / `rotateScimToken` / `verifyScimToken` take the workspace, or null for the
-instance, and hold the bearer token the SCIM endpoints in `apps/api` authenticate with. The
-instance's is stored under `auth.scim` and reads `scim_<secret>`; one it held while it
-belonged to the first workspace reads `scim_<id>_<secret>` and keeps working. A workspace's
-is stored under `workspace.<id>.scim` and reads `scim_<workspaceId>_<secret>`, so
-`verifyScimToken` checks the instance's first and then reads only the named workspace's.
-The token is returned in the clear exactly once, when it is generated; only its prefix is
-kept in the redacted mirror.
-
-## Passkey
-
-`passkey({ rpID, rpName, origin })` adds WebAuthn. `rpID` is the frontend hostname the
-credential binds to — derived from the first `APP_URL` entry, overridable with
-`PASSKEY_RP_ID` (set it to the public frontend hostname in prod). `origin` is the whole
-`APP_URL` list (the WebAuthn ceremony runs in the frontend JS). The plugin adds
-the `passkey` table, which is mapped in the drizzle adapter's `schema`. localhost is a
-secure context, so passkeys work over http in dev.
-
-## Google sign-in
-
-The credentials live in the database (`app_secret` key `auth.google`, encrypted), not in
-env, so god mode can change them without a restart. That is the only reason the provider
-is wired the way it is:
-
-`socialProviders.google` is a factory that returns the module-level `googleOptions`
-object. better-auth builds the provider list once at startup, but the provider keeps that
-object **by reference** and reads `clientId` / `clientSecret` off it on every call, so
-`refreshGoogleOptions()` in `hooks.before` reloads it on `/sign-in/social` and
-`/callback/google` and refuses the request when the credentials are missing or the toggle
-is off. Do not replace the object (`googleOptions = {...}`) — assign its fields, or the
-provider keeps reading the old one.
-
-Account linking is left at better-auth's defaults, which means
-`accountLinking.requireLocalEmailVerified` is `true`: a Google address that already has an
-account signs into it only when that account's email is confirmed, and gets
-`unable_to_link_account` otherwise. Do not add `trustedProviders: ['google']` — with
-instance email confirmation optional, it would let whoever registered an address first
-receive its real owner.
-
-The registration gate (`assertRegistrationAllowed`) runs in
-`databaseHooks.user.create.before`, which every account creation passes, and that is what
-applies closed/invite-only to a Google, OIDC or magic-link sign-up. It refuses with
-`REGISTRATION_CLOSED` on a closed instance, `EMAIL_DOMAIN_NOT_ALLOWED` when the address is
-not at one of `allowedEmailDomains` (an empty list admits any), `INVITE_ONLY` when the
-address has no pending invite, and `INVITE_EXPIRED` when its only invites have expired.
-That last one reveals that the address was invited, so it is given only where the address
-is proven (provider, magic link); the email form, open to anyone, gets `INVITE_ONLY`. Its
-`APIError`s carry a `code` because the provider callback and the magic link turn that into
-the `?error=` they redirect with; without one the callback fails the request instead
-(`invite-forms.test.ts` pins `INVITE_EXPIRED` and `INVITE_ONLY`). Agent bot users are
-written with a direct insert and never reach the hook.
-
-A domain in `allowedEmailDomains` matches the part of the address after the "@" exactly, so
-a subdomain is listed on its own. The list applies to new accounts only; the api also
-refuses to invite an address that has no account and is outside it, since it could not
-register. The gate asks `registrationEmailAllowed`, which checks the list unless a build
-installs its own policy with `setRegistrationEmailPolicy`, as one that lets a workspace
-keep domains of its own does to admit an address that workspace invited.
-
-## API keys
-
-`apiKey({ enableSessionForAPIKeys: true })` makes an `x-api-key` header resolve to the
-owner's session, so a key is a full-account credential. It therefore expires:
-`keyExpiration.defaultExpiresIn` is 90 days and `maxExpiresIn` is a year, and the create
-dialog in the web app offers 30/90/180/365 days. The plugin's option is documented as
-milliseconds but its handler passes the value to `getDate(value, "sec")`, so
-`API_KEY_DEFAULT_EXPIRES_IN_SEC` is in seconds; `maxExpiresIn` is in days, as the plugin
-reads it. Keys issued before this stay `expires_at` NULL and keep working.
-
-The plugin resolves a key to the owner's session on every better-auth endpoint, and what
-that session sets up there outlives the key: a passkey enrolled with it signs in after the
-key is deleted and the password reset, and a new key renews the expiry. So the first check
-in `hooks.before` refuses any request that carries an `x-api-key` header — a key is for the
-planner API, and the account is managed from a signed-in session. It reads `ctx.request`,
-which a server-side `auth.api.*` call does not carry, so `issueKey` and
-`getSessionFromHeaders` are unaffected. `hooks.before` also refuses an `/api-key/update`
-that carries `expiresIn`: a longer life is a new key.
-
-An agent's key is the exception and carries no expiry — an agent replays its stored secret
-with nothing that would renew it, and an external agent's operator rotates it through
-`regenerate-key`. The plugin applies the default to every key it creates, so `issueKey` in
-`apps/api/src/modules/agents/core/service.ts` clears `expires_at` on the row afterwards.
-
-A key the plugin will not accept makes it throw out of `auth.api.getSession` rather than
-return no session. `getSessionFromHeaders` turns that back into "no session", so an expired
-key is answered with a 401 instead of a 500. Use it instead of `auth.api.getSession` where
-a request may carry a key.
-
-## MCP OAuth
-
-`mcp()` from `@better-auth/mcp` serves OAuth 2.1 to MCP clients, with `jwt()` signing the
-access tokens. It adds the `oauth_client`, `oauth_resource`, `oauth_client_resource`,
-`oauth_refresh_token`, `oauth_access_token`, `oauth_consent`, `oauth_client_assertion`
-and `jwks` tables, and writes the MCP resource (`<API_URL>/mcp`) into `oauth_resource`
-at startup. Any client registers itself (RFC 7591), as ChatGPT and Claude do; the
-provider asks the person for consent the first time a client asks for their account.
-Only `authorization_code` and `refresh_token` are granted, so every token acts for a
-person. A registration that also lists a grant the server does not issue, as Claude's
-connector does with `jwt-bearer`, is registered with the supported grants; one that lists
-none of them is refused.
-
-MCP clients register without `application_type`, and `mcp()` infers it
-(`clientRegistrationDefaultApplicationType: 'infer'`): a client whose callback is http on
-`localhost`, `127.0.0.1` or `[::1]` (Claude Code) or uses a custom scheme such as Cursor's
-`cursor://` is registered as `native`, and any other as `web`, which takes an https callback
-only. better-auth's own default, `web`, refuses the first two. A client that sends its
-`application_type` keeps it.
-
-The issuer is `API_URL` itself, path included, so the tokens and the discovery documents
-name the URL a client reaches. The api serves the documents at the root of its origin
-(`oauthAuthorizationServerMetadata`, `openIdConfiguration`,
-`oauthProtectedResourceMetadata`), and the endpoints in them get the path back the way the
-links in auth emails do.
-
-`verifyMcpAccessToken` checks a token against the instance's own keys in-process, then
-reads what a JWT cannot carry: the account must not be deactivated, and a token issued in
-a session ends with that session, as better-auth's introspection has it. That is what
-makes deactivation, which deletes the sessions, end every MCP token at once. The token's
-client must also still be connected to the account, through the person's consent or a
-refresh token that has not expired: disconnecting it on the account's Security page
-(`DELETE /account/connected-apps/:clientId`, which deletes both) ends its tokens at once.
-
-better-auth accepts a plain-HTTP MCP resource only on a loopback host, so any other
-instance without HTTPS leaves `mcp()` and `jwt()` out and serves MCP to personal API keys
-only.
-
-## OpenAPI reference
-
-The `openAPI()` plugin (`better-auth/plugins`) documents the auth handler. It serves a
-Scalar UI at `/api/auth/reference` and the raw schema at
-`/api/auth/open-api/generate-schema`. The schema is built from every active plugin, so
-the passkey and apiKey endpoints appear without any manual description. This is separate
-from the planner's own OpenAPI docs at `/docs` (the `@elysiajs/swagger` spec, which does
-not see the catch-all auth handler). Docs-only: it adds no table, so `auth:generate` is
-not required for it.
-
-## What a build adds
-
-`@repo/auth/extensions` is the one module of this package that does not create the
-instance. A build calls `extendAuth({ plugins, schema, disabledPaths })` from it before
-the first request: the plugins join the core's, their drizzle tables join the adapter's
-schema by model name, and the paths are refused to requests while the server still calls
-them through `auth.api`. `./index.ts` creates the instance on its first use, not on
-import, so the call takes effect wherever a bundler puts the build's module; it reads the
-extensions then, and a later call throws. A plugin that needs origins trusted adds them
-itself, through its `init`. The plugins are typed as none, so `Auth` stays the core's
-type.
-
-`setRegistrationAdmission(fn)` is a build's say on an account the gate is about to create,
-by the request creating it (the better-auth endpoint context): true lets it past the
-registration mode and the allowed domains, as a sign-in through a provider the build
-manages that may create accounts; a throw turns it away. Without one the gate decides.
+The server-side better-auth instance, consumed by `apps/api`. `docs/dev/auth.md` explains how each
+sign-in method, setting and token works. Read it before you change one.
## Rules
-- This package is **server-only** — never import a client SDK (`better-auth/react`) here;
- the web app owns its own `auth-client.ts`.
-- Changing the config (plugins, fields) can change the DB tables → run `bun run auth:generate`
- (writes `packages/db/src/schema/auth.ts`), then `db:generate` + `db:migrate`.
-- Config is env-driven: `API_URL` (public URL of the backend), `BETTER_AUTH_SECRET`,
- `APP_URL` (frontend origin(s), comma-separated). `API_URL` and `APP_URL` are mandatory
- and have no default — importing this module throws when either is missing. Do not add
- a localhost fallback: cookies, the passkey relying party, the cookie domain and every
- link in an authentication email are derived from them, so a wrong value fails silently
- at runtime instead of at startup. The parsed `trustedOrigins` list (from `APP_URL`) is
- exported so the api's CORS uses the same value.
-- **`API_URL` with a path** (the api under a path of the web's host): better-auth's
- `baseURL` gets only the origin, because a path there replaces its `/api/auth` base path
- and the api's fixed mount stops matching. Every public URL built from it — the OAuth
- redirect URIs, the links in auth emails, the MCP resource and discovery documents — gets
- the path back through `apiPublicUrl` / `withPublicOrigin`.
-- **Cookies:** `sameSite: "lax"`. Web and api on sibling subdomains share the cookie through
- `advanced.crossSubDomainCookies` on the parent domain of `APP_URL` (`COOKIE_DOMAIN`
- overrides it). On one host the cookie has no domain, and over HTTPS the session cookies
- are named `__Host-better-auth.*`. If frontend/backend run on different domains, switch
- to `sameSite: "none"` + `secure: true`.
+- This package is server-only. Never import a client SDK (`better-auth/react`) here.
+- A change to plugins or fields can change the DB tables. Run `bun run auth:generate`, then
+ `db:generate` and `db:migrate`. `src/schema/auth.ts` in `@repo/db` is generated.
+- `API_URL` and `APP_URL` are mandatory. Do not add a localhost fallback: cookies, the passkey
+ relying party and every link in an auth email come from them, so a wrong value fails silently.
+- Instance settings are in the database so they change without a restart. Read them through
+ `src/instance.ts`. Never inline a query on `app_setting` or `app_secret`. Secrets never leave the
+ server.
+- Do not replace the `emailAndPassword.requireEmailVerification` getter with a static value: `true`
+ locks every account out, `false` hands an unconfirmed sign-up a session.
+- Do not reassign `googleOptions`. Assign its fields: the provider keeps the object by reference.
+- Keep `accountLinking.trustedProviders` as `resolveTrustedProviders`. It trusts a provider only
+ while `trustProviderEmails` is on. A static list would let whoever registered an address first
+ receive its real owner.
+- Password sign-in off is read per request, so it cannot be `emailAndPassword.enabled: false` or a
+ `disabledPaths` entry.
+- Use `getSessionFromHeaders`, not `auth.api.getSession`, where a request may carry a key. An
+ expired key throws out of `getSession` and would answer 500.
+- A key is for the planner API. `hooks.before` refuses `x-api-key` on every auth endpoint. Only an
+ agent's key has no expiry (`issueKey`).
+- Every auth email link carries a `callbackURL` or `redirectTo` on the **web** origin. Without one
+ it lands on the API, which renders nothing.
+- A username shares one namespace with agents. Every path that sets a member's name checks it
+ against `ai_agent`.
+- `/is-username-available` stays in `disabledPaths`: it would tell a stranger which addresses are
+ registered.
+- Invites belong to a team. There is no instance-level invite table. Do not add a god mode invite
+ section.
+- An OIDC provider per workspace is not built on the instance provider: a workspace owner's
+ provider could name any address.
+- **`API_URL` with a path:** better-auth's `baseURL` gets only the origin. Every public URL built
+ from it gets the path back through `apiPublicUrl` / `withPublicOrigin`.
+- **Cookies:** `sameSite: "lax"`. If frontend and backend run on different domains, switch to
+ `sameSite: "none"` + `secure: true`.
diff --git a/packages/db/AGENTS.md b/packages/db/AGENTS.md
index 70f7b4f6..03020ab3 100644
--- a/packages/db/AGENTS.md
+++ b/packages/db/AGENTS.md
@@ -1,96 +1,66 @@
# @repo/db
-Drizzle ORM + `postgres-js` over PostgreSQL. Single source of truth for the DB schema.
-See root `AGENTS.md` for monorepo-wide rules.
+Drizzle ORM + `postgres-js` over PostgreSQL. The source of truth for the DB schema.
## Structure
-- `src/client.ts` — the `db` instance (one `postgres()` connection, `prepare: false`).
-- `src/schema/auth.ts` — **generated** by better-auth CLI. Do NOT edit by hand;
- regenerate with `bun run auth:generate` (from the auth package / root).
-- `src/schema/app.ts` — hand-written application tables. Add domain tables here.
-- `src/schema/index.ts` — re-exports every table; `drizzle.config.ts` points at it.
-- `src/permissions.ts` — the permission matrix stored in `team_role.permissions`: the
- resource/action catalog, the default member role, and the normalizer.
-- `src/settings.ts` / `src/secrets.ts` — the two instance config stores: `app_setting`
- in plaintext jsonb, `app_secret` encrypted with `APP_ENCRYPTION_KEY`. Both are read
- by more than one app, which is why they are here.
-- `src/domains/` — one module per stored config that more than one process reads: its
- shape, its defaults and the reader that decrypts it. Only that. The write side, the
- redacted view an HTTP client gets, the validation and anything else specific to one
- caller stay with that caller — the api's settings routes, or god mode in
- `@repo/auth`. A config only one process reads does not belong here at all.
- Currently: the instance Telegram bot (api, bot, worker), the instance mail provider
- (`@repo/auth`, api, worker), a team's notification providers (api, worker), and the
- instance's upload limits and project-storage-quota accounting (api, worker — an
- imported attachment is checked against the same limits an interactive upload is).
-- `src/migrate.ts` — programmatic migrator (no drizzle-kit in prod), run by the `migrate` compose service, the api pods' init container, and the api image's CMD. With `BUILD_MIGRATIONS_DIR` set, it applies that folder too, after the core's, under the same lock and backup: a build's own tables, recorded in `drizzle.__build_migrations`.
-- `src/wait-for-migrations.ts` — exits once the database holds this release's migrations; the Helm init container of the worker and bot pods.
-- `drizzle/` — generated SQL migrations (committed).
+- `src/schema/auth.ts` is **generated** by better-auth. Do not edit it; run `bun run auth:generate`.
+- `src/schema/app.ts`: hand-written application tables. Add domain tables here.
+- `src/schema/scim.ts`: hand-written SCIM tables.
+- `drizzle.config.ts` reads only `src/schema/index.ts`. Export a new schema file from it.
+- `src/permissions.ts`: the permission matrix stored in `team_role.permissions`.
+- `src/settings.ts` / `src/secrets.ts`: instance config, `app_setting` in plaintext jsonb,
+ `app_secret` encrypted with `APP_ENCRYPTION_KEY`.
+- `src/domains/`: a new config that several processes read gets a module here: shape, defaults and
+ a reader that decrypts it if it is encrypted. A config only one process reads stays out. The
+ caller keeps writes and validation. `storage.ts` also holds the upload check and quota queries.
+- `src/migrate.ts`: programmatic migrator, no drizzle-kit in prod.
## Workflow
-1. Edit `schema/app.ts` (or regen `schema/auth.ts`).
-2. `bun run db:generate` → new SQL in `drizzle/`.
-3. `bun run db:migrate`.
+1. Edit `schema/app.ts` or `schema/scim.ts`, or regenerate `schema/auth.ts`.
+2. `bun run db:generate`, which writes SQL to `drizzle/`.
+3. `bun run db:migrate`, then `bun run db:migrate:test` for the test DB.
-Migrations only — never `drizzle-kit push`. Every schema change goes through a
-committed migration in `drizzle/`.
+Never `drizzle-kit push`. Every schema change goes through a committed migration.
-## Team-owned agents
-
-An AI agent is a row in `ai_agent` with a `team_id` and a `user_id`: the team that owns
-it, and the bot user it acts as. The team is the boundary — there is no instance-level
-agent and no flag on `user` marking a non-human identity, so anything that has to
-enumerate agents does it through `ai_agent`.
-
-What the team owns with it: `agent_skill`, `agent_tool` and `integration_credential`
-all carry a `team_id` and are shared by every project of the team. `agent_schedule` and
-`agent_run` carry a `project_id` — a run happens in one project.
-
-The projects an agent works in are its bot user's `project_member` rows, the same as for
-a person, and the `role_id` on each of them is what its requests are checked against —
-per project, so one agent can hold different roles in two of them. Its rights in a
-project are the intersection of that role and the actions in `ai_agent.tools`.
-`team_member.role` takes a fourth value, `'agent'`, so an agent stands in the team
-without being a person in it.
+## Conventions
-`ai_agent_team_username_uq` makes the mention handle unique per team, not per project.
+- Explicit snake_case column names (`text("created_at")`). No `casing` option.
+- New FK: `onDelete: "cascade"` if the row cannot exist without its parent, `onDelete: "set null"`
+ for an optional link (assignee, author, cycle, parent issue). Keep `cascade` on a nullable FK when
+ NULL has its own meaning (system role, public board) or a CHECK needs the owner.
+- Agents are enumerated through `ai_agent`; `user` has no non-human flag. See `docs/dev/agents.md`.
-## Revision engine
+## Revision triggers
-`revision` holds one counter per scope — the change markers the clients poll through
-`GET /sync/rev`. Nothing in the application writes them: the triggers in
-`drizzle/0070_revision_triggers.sql` do, so a write moves the marker whichever
-process it came from. `rev_issue()` is redefined in `0142_issue_key_alias.sql`: an
-issue moved to another project bumps the board of both projects, and its `issue:`
-scope row takes the new project id.
+Triggers write `revision`; application code leaves it alone. The one exception is `appendRunEvents`,
+which calls `bump_rev` because `agent_run_trace` has no trigger.
-To make a new table move an existing scope, add one line to a migration:
+To make a table move an existing scope, add one line to a migration:
```sql
-CREATE TRIGGER issue_reaction_rev AFTER INSERT OR UPDATE OR DELETE ON issue_reaction
+CREATE TRIGGER issue_cycle_rev AFTER INSERT OR UPDATE OR DELETE ON issue_cycle
FOR EACH ROW EXECUTE FUNCTION rev_issue_child('issue_id', 'detail');
```
-`rev_issue_child` takes the column holding the issue id, and `board` or `detail` —
-whether the board shows the change or only the issue screen does. Tables that reach
-their owner differently get their own function next to the ones in 0070; keep the
-order in which they take the scopes (board, then issue, then initiative, and two of
-one kind in id order), which is what stops two writers from deadlocking on the
-counters.
+For a new table, append the line to the SQL that `db:generate` writes. For an existing table
+`db:generate` writes nothing, so run `bunx drizzle-kit generate --custom --name=<name>` in
+`packages/db`: the migrator runs only files listed in the journal.
-A new scope kind also needs its entry in `apps/api/src/modules/sync/service.ts` — its name and
-the resource a watcher must be allowed to read — and the mirror in
-`apps/web/src/utils/revScopes.ts`.
+`rev_issue_child` takes the column holding the issue id, and `board` or `detail`. Both move the
+issue and its initiative; `board` also moves the board. Any other value acts as `detail`. Tables
+owned by an initiative use `rev_initiative_child('initiative_id')`, and tables with a `document_id`
+column use `rev_document_child()`.
-## Conventions
+A table that reaches its owner another way gets its own function in a new migration, modelled on
+`rev_checklist_item` in `0070_revision_triggers.sql`. A later migration can replace a function: the
+current `rev_issue` is in `0142_issue_key_alias.sql`.
-- Explicit snake_case column names (`text("created_at")`) — matches the generated auth schema; no `casing` option.
-- FKs use `.references(() => other.id, { onDelete: "cascade" })`.
-- `drizzle.config.ts` loads the root `.env` via `dotenv` — needs a valid `DATABASE_URL`.
+Inside a function, keep the lock order: board, then issue, then initiative, two of one kind in id
+order, with `documents` before issue and initiative. It stops two single-row writes from
+deadlocking. `inbox` and `runner-queue` are outside the order: each is taken alone.
-`0152_agent_execution_state.sql` adds the current execution marker to `agent_run`.
-Its trigger bumps `runner-queue:<projectId>` on queue writes. It does not write the
-issue scope: the issue run panel watches the user-scoped runner queue marker too,
-which avoids introducing a queue/issue revision lock ordering dependency.
+A new scope kind also needs its entry in `scopeKind` in `apps/api/src/modules/sync/service.ts`, its
+name in `apps/api/src/modules/sync/model.ts` and the mirror in `apps/web/src/utils/revScopes.ts`. A
+scope across projects has no `scopeKind` entry: `apps/api/src/modules/sync/index.ts` handles it.
diff --git a/scripts/agents-md.test.ts b/scripts/agents-md.test.ts
new file mode 100644
index 00000000..bf821ffd
--- /dev/null
+++ b/scripts/agents-md.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+const MAX_BYTES = 10_000;
+
+const tracked = Bun.spawnSync(['git', 'ls-files'], { cwd: ROOT }).stdout.toString().split('\n');
+const agentFiles = tracked.filter((file) => /(^|\/)AGENTS\.md$/.test(file));
+
+const fileReference = /^\w[\w./-]*\.(ts|tsx|json|sql|md|yml|yaml|sh|mjs|css)$/;
+const rootReference = /^(apps|packages|docs|scripts|charts|\.github)\/[\w./-]+$/;
+
+// Backticked file names with no folder resolve against any tracked file, since a rule often
+// names one by its base name. Forms with a wildcard or a placeholder are skipped.
+function missingReferences(file: string): string[] {
+ const text = readFileSync(join(ROOT, file), 'utf8');
+ const references = [...text.matchAll(/`([^`\n]+)`/g)].map((match) => match[1].replace(/\/$/, ''));
+ return references
+ .filter((ref) => fileReference.test(ref) || rootReference.test(ref))
+ .filter(
+ (ref) =>
+ !existsSync(join(ROOT, ref)) &&
+ !existsSync(join(ROOT, dirname(file), ref)) &&
+ !tracked.some((path) => path.endsWith(`/${ref}`) || path.includes(`/${ref}/`)),
+ );
+}
+
+describe('AGENTS.md files', () => {
+ test('the set of files is found', () => {
+ expect(agentFiles).toContain('AGENTS.md');
+ });
+
+ for (const file of agentFiles) {
+ test(`${file} stays within the size limit (see docs/dev/agents-md.md)`, () => {
+ expect(statSync(join(ROOT, file)).size).toBeLessThanOrEqual(MAX_BYTES);
+ });
+
+ test(`${file} names only paths that exist`, () => {
+ expect(missingReferences(file)).toEqual([]);
+ });
+ }
+});
diff --git a/turbo.json b/turbo.json
index 6ffe0e12..92784652 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,5 +1,6 @@
{
"$schema": "https://turbo.build/schema.json",
+ "agentGuidance": false,
"globalEnv": ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_SECRET", "API_URL", "APP_URL", "API_PORT"],
"tasks": {
"dev": {