<!-- Stacklift documentation: "Architecture". Source: https://stacklift.joynul.com/docs/architecture · All pages for LLMs: https://stacklift.joynul.com/llms-full.txt -->

> About Stacklift: Stacklift is a hosted platform with source-available SDKs for shipping app releases and over-the-air updates. It works for mobile (React Native, Expo, Flutter, native iOS and Android, Kotlin Multiplatform, .NET MAUI, Unity), web, desktop (Electron, .NET, Java) and backend apps. Developers create releases with the `stacklift` CLI or the dashboard; the server verifies and signs every artifact (SHA-256 + Ed25519), deploys releases to channels with staged rollouts and rollback, and app SDKs check, download and verify updates. Native apps can change screens over the air with server-driven UI layouts and logic with sandboxed scripts, within App Store and Google Play rules. Apps never depend on Stacklift to keep working: everything has a built-in fallback and an exit path.
>
> This page: Control and delivery planes, data model, decisions.

# Architecture

## Shape

```text
apps/
  web/        Next.js (App Router) dashboard, marketing site, docs portal
  api/        NestJS: control plane (REST + SSE) and delivery plane (SDK-facing)
  cli/        `stacklift` command line
packages/
  shared/     zod schemas, roles/permissions, release state machine, constants
  database/   Prisma schema, migrations, dev seed
  adapters/   stack adapter registry + one adapter per ecosystem
  sdk-core/   Node update client, cohort bucketing, checksum + Ed25519 helpers
  sdk-js/ sdk-electron/ sdk-swift/ sdk-dart/ sdk-dotnet/ sdk-java/   client SDKs (tested)
  sdk-react-native/   React Native: code push (native bundle loader on the Swift and Android SDKs), StackliftScreen renderer
  sdk-android/   Android SDK: Compose renderer, QuickJS scripts, update lifecycle (Gradle; includes sdk-java from source)
  sdk-kotlin/ sdk-tauri/   client SDKs (untested source)
  sdk-conformance/   language-neutral signature test vectors every SDK must pass
  ui-schema/  the open stacklift-ui/1 layout format: JSON Schema, validator, reference resolver, code export, shared fixtures
  sdk-flutter-scripts/ sdk-flutter-ui/   Flutter packages: JavaScript runtime for scripts, StackliftScreen widget
infrastructure/docker/   Postgres, Redis, MinIO (S3) for local development
docs/                    this documentation (also rendered by the web docs portal)
```

The frontend, API, CLI and SDK share only `packages/*` — there are no imports between apps, and no business logic lives in React components (they render API state and send intents).

## Control plane vs delivery plane

| | Control plane | Delivery plane |
| --- | --- | --- |
| Path | `/api/v1/*` (port 4000) | `/v1/*` (port 4100) |
| Callers | Dashboard, CLI, CI | Apps in the field (SDK) |
| Auth | User JWT, `slp_` token, `slk_` secret key | `slk_` **public** key |
| Writes | Projects, releases, deployments, rollouts… | Telemetry events only |
| Scaling | Modest, stateful operations | Read-mostly, stateless, scale out freely |

They are two Nest applications built from the same codebase. `PLANE=control|delivery|all` picks which to start, so production can run them as separate deployments. Artifact bytes never flow through either: uploads and downloads use presigned URLs against S3-compatible storage (the `local` driver exists for development only). Object keys are tenant-prefixed and content-addressed (`artifacts/<org>/<project>/<release>/<sha256>/<file>`), so they are immutable and CDN-cacheable.

## Request pipeline (control plane)

`ThrottlerGuard → AuthGuard → AccessGuard → zod pipe → controller → service → Prisma`

- **AuthGuard** accepts a JWT, a personal access token, or a project secret key (a machine principal).
- **AccessGuard** resolves `:org` (and `:project` *inside* that org), checks membership and the `@Require(permission)`; for machine principals it maps scopes to permissions and confines them to one project.
- Controllers are thin. Services own the logic; `@stacklift/shared` owns the rules (permissions, state machine) so API, CLI and UI can't disagree.

## Data model (Prisma / PostgreSQL)

Identity: `User`, `OAuthAccount`, `RefreshToken`, `VerificationToken`, `PersonalAccessToken`.
Tenancy: `Organization`, `Membership`, `Invitation`, `Workspace`.
Delivery domain: `Project` (+ signing key pair), `ProjectMember`, `Environment`, `Channel`, `Release`, `Artifact`, `Deployment`, `Rollout`, `RolloutEvent`, `Rollback`.
Credentials & telemetry: `ApiKey`, `UpdateEvent` (append-only), `Integration`, `WebhookDelivery`, `AuditLog`.

Principles:

- **Tenant isolation:** every org-owned table has `orgId`; the API never queries without it.
- **Soft deletion** for users, organizations, projects, releases. History tables (audit log, deployments, rollbacks, events) are never deleted.
- **Constraints do real work:** `@@unique([projectId, version])`, `@@unique([releaseId, platform, kind])`, `@@unique([projectId, idempotencyKey])`, `Channel.activeRolloutId @unique` (at most one rollout per channel).
- **Indexes** follow the access paths: `(orgId, status)`, `(projectId, occurredAt)`, `(status, nextStepAt)` for the rollout scheduler.
- Secrets are stored hashed (`secretHash`) or encrypted (`signingPrivateKeyEnc`, `Integration.secretEnc`).

## The release engine

States are defined in `@stacklift/shared` (`RELEASE_TRANSITIONS`) and enforced by `assertTransition` / `syncReleaseStatus`:

1. `requestUpload` creates an artifact row (`PENDING`) and a signed upload URL; release → `UPLOADING`.
2. `complete` checks the object exists, marks it `UPLOADED`, release → `PROCESSING`, enqueues `artifact.process`.
3. `artifact.process` (idempotent job) streams the object, computes real size/SHA-256, compares to the declaration, signs, marks `VERIFIED`. `refreshFromArtifacts` (row-locked) moves the release to `READY` only when every release platform has a verified artifact and nothing is pending — or `FAILED`.
4. `DeploymentsService.request` records a `PENDING` deployment and moves the release to `DEPLOYING`. **It does not touch the channel.**
5. `deployment.execute` (idempotent job) re-validates, then in one transaction (channel + release row locks) either sets `Channel.currentReleaseId` and marks the deployment `SUCCEEDED` (100%), or creates a `Rollout` (<100%).
6. `RolloutsService.act` pauses, resumes, cancels or raises a rollout; reaching 100% completes it with the same switch. A one-minute scheduler evaluates **opt-in** auto-expansion and the failure-rate pause guard.
7. `RollbacksService.create` runs the adapter's compatibility check, then in one transaction cancels any rollout, repoints the channel, records a `ROLLBACK` deployment and the reason.

`syncReleaseStatus` derives `ACTIVE` / `DEPLOYING` / `ROLLED_BACK` / `READY` from what channels and rollouts actually say, so a release can never claim to be live when nothing serves it.

## Decisions (ADR summary)

| # | Decision | Why |
| --- | --- | --- |
| 1 | Monorepo with pnpm workspaces; apps share only packages | Independent deployability, single source of truth for rules |
| 2 | NestJS modular monolith, two planes from one codebase | Operational simplicity now, split by env var later |
| 3 | zod as the contract (validation, OpenAPI bodies, CLI config, forms) | One definition for server, CLI and UI |
| 4 | Adapters declare capabilities, restrictions and limitations as data | Product honesty is enforced, not marketing copy |
| 5 | Presigned direct-to-storage transfer | Large files never traverse the API; CDN-friendly |
| 6 | Server-side checksum + Ed25519 signature bound to release identity | Integrity, and no cross-release replay |
| 7 | Rollout cohorts by stable hash | Monotonic, stateless, no per-device storage |
| 8 | Deployment ≠ switch: request is `PENDING`, the job flips the channel | A deployment is never reported done before it is |
| 9 | Machine principals via scoped project keys | CI gets least privilege without a user account |
| 10 | BullMQ with an `inline` mode | Durable retried jobs in prod; deterministic tests, Redis-free dev |
| 11 | Access token in memory + `HttpOnly` rotating refresh cookie | Limits XSS blast radius |
| 12 | One channel serves one release | Simple, atomic. Trade-off: no per-runtime-version pointers yet (warned in UI) |
| 13 | Telemetry in Postgres behind an API | Fine to a large scale; swap for a columnar store later without API change |

## Technical limitations by ecosystem

See [Stack adapters](https://stacklift.joynul.com/docs/adapters.md). In short: mobile native binaries are tracked, never OTA-updated; desktop installers are delivered and verified but run by your app (no rollback, no delta updates); Flutter Dart OTA and the React Native/Expo/Capacitor on-device loaders are not implemented; web and backend are artifact/deployment tracking — Stacklift does not host or run your software. See [Desktop apps](https://stacklift.joynul.com/docs/desktop.md) and [SDKs](https://stacklift.joynul.com/docs/sdk.md).

## Infrastructure requirements

PostgreSQL 16, Redis 7 (BullMQ + SSE fan-out; optional with `QUEUE_MODE=inline`), S3-compatible object storage + optional CDN, SMTP for mail (dev prints to the console), Node 20+.

## Security risks considered

Cross-tenant access, credential theft (public key in apps, CI secrets), artifact tampering/replay, SSRF via webhooks, upload abuse, refresh-token theft, privilege escalation through invitations/role changes. Mitigations are listed in [Security](https://stacklift.joynul.com/docs/security.md) and covered by `apps/api/test/security.e2e.test.ts`.
