# Development

How to install, build, test and extend the Helpdock monorepo. Contribution rules are in [CONTRIBUTING.md](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/CONTRIBUTING.md); the definition of done is in [AGENTS.md](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/AGENTS.md).

## Prerequisites

| Tool | Version | Notes |
|---|---|---|
| Node.js | 24 LTS | Pinned in `.nvmrc` and `.node-version`. `nvm use` or `fnm use` picks it up. |
| pnpm | 12 | Pinned in `packageManager`. `corepack enable pnpm` installs the right one. |
| Docker | any recent version, with the Compose plugin | For the integration tests and the dev stack. The unit tests and the build run without it. |

No database to install by hand: the integration tests start the services they
need in containers themselves, and [the dev Compose stack](https://helpdock.oday-bakkour.com/docs/development/#docker) starts
Postgres, Redis, MinIO and Mailpit for the dev loop.

The shared API Docker probe (used by the API container suites and eval/perf setup)
allows 60 seconds for a loaded daemon to answer. Without Docker these suites
may skip locally. With a nonempty `CI` environment variable, a failed probe
throws instead: required database tests must not silently disappear from CI
or its coverage report. Start Docker or repair the runner before retrying;
do not lower the coverage threshold to compensate for skipped suites.

## Install

```bash
pnpm install
```

`packageManager` in the root `package.json` pins pnpm, and pnpm switches to that version itself. `engines` records the supported Node range but pnpm does not enforce it, so check `node --version` if something behaves oddly.

## Scripts

Run these from the repository root.

| Script | What it does |
|---|---|
| `pnpm build` | `turbo run build` — compiles each workspace into its own `dist/`, the website (`site/`) included. |
| `pnpm typecheck` | `turbo run typecheck` for workspace sources, then a root `tsc --noEmit` that covers the test files and `scripts/`. |
| `pnpm lint` | `biome check .` — lint, format and import order for the whole repository in one pass. |
| `pnpm lint:fix` | The same, applying the safe fixes. |
| `pnpm format` | Rewrites formatting only. `pnpm format:check` reports without writing. |
| `pnpm test` | Unit tests for every workspace in one run, with the coverage gate. |
| `pnpm test:integration` | The Testcontainers suites. Needs Docker; skips itself without it. |
| `pnpm test:watch` | Vitest in watch mode. |
| `pnpm check:boundaries` | Enforces the app import rule described below. |
| `pnpm check:routes` | Fails when a controller handler declares neither `@Requires`, `@Authenticated` nor `@Public`. |
| `pnpm check:validation` | Fails when a `@Param`, `@Query` or `@Body` on a controller handler names no Zod schema. |
| `pnpm design:render` | Renders the artboard sources in `docs/design/artboards/` to PNGs in `docs/design/screens/`. See [docs/design/](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/design/README.md). |
| `pnpm changeset` | Records what a change should say in the next release. See [the release guide](https://helpdock.oday-bakkour.com/docs/release/). |
| `pnpm --filter @helpdock/api seed:dev` | Creates the development install: one brand, one admin, a published password. Refuses `NODE_ENV=production`. |

For a single workspace, use the per-package scripts through pnpm or Turborepo:

```bash
pnpm --filter @helpdock/db test
pnpm turbo run typecheck --filter=@helpdock/api
```

## Layout

```
apps/          api, admin, helpcenter, widget
packages/      db, schemas, ai, channels, ui, i18n, config, net, jobs
scripts/       repository checks run by CI, and the artboard renderer
docs/          planning, guides, decisions, rendered design screens
site/          the product website (Astro, static), deployed to GitHub Pages (website.md)
```

Every workspace is `@helpdock/<directory name>`, private, ESM (`"type": "module"`), and has the same four scripts: `build`, `typecheck`, `lint`, `test`. A workspace is a placeholder until its own deliverable lands — it exports a `PACKAGE_NAME` constant and has one test asserting it matches `package.json`, which is enough to prove the pipeline runs end to end. `apps/admin` adds `dev`, `e2e` and `e2e:baselines`, and its `build` is `vite build` rather than `tsc`; see [Admin app](https://helpdock.oday-bakkour.com/docs/development/#admin-app).

Seven packages and two apps are real so far. `packages/config` is the configuration loader; see [Configuration](https://helpdock.oday-bakkour.com/docs/development/#configuration). `packages/db` is the schema, the migrations and the row-level security; see [Database](https://helpdock.oday-bakkour.com/docs/development/#database). `packages/net` is the SSRF-safe outbound HTTP client and URL policy from M0-15, which everything that fetches a user-supplied URL goes through; see [`packages/net/README.md`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/net/README.md). `packages/jobs` is the queue names, job schemas, outbox relay and idempotent consumers from M0-14; see [Jobs and outbox](https://helpdock.oday-bakkour.com/docs/development/#jobs-and-outbox). `packages/schemas` holds the Zod schemas the api, admin and widget share; every request and response shape belongs there rather than in the app that happens to need it first. `packages/ui` and `packages/i18n` hold the design system and the catalogs; see [UI and i18n](https://helpdock.oday-bakkour.com/docs/development/#ui-and-i18n). `apps/api` is the NestJS application from M0-04, which carries the request context, the guards and the tenant transaction; see [API](https://helpdock.oday-bakkour.com/docs/development/#api). `apps/admin` is the admin SPA from M0-07; see [Admin app](https://helpdock.oday-bakkour.com/docs/development/#admin-app).

TypeScript settings live in `tsconfig.base.json` (strict, `nodenext` modules, `verbatimModuleSyntax`). A workspace `tsconfig.json` only adds `rootDir`, `outDir` and which files to include. Because module resolution is `nodenext`, relative imports carry the `.js` extension even when the file on disk is `.ts`.

## Adding a package

1. Create `packages/<name>/` with `src/index.ts` and `src/index.test.ts`.
2. Add `package.json`: name `@helpdock/<name>`, `"private": true`, `"type": "module"`, an `exports` map pointing at `dist/`, and the four scripts. Copy an existing package.
3. Add `tsconfig.json` extending `../../tsconfig.base.json`.
4. Run `pnpm install` so the workspace is linked.
5. Check that `pnpm-lock.yaml` gained an `importers` entry for it, and commit the change.

Vitest discovers the new workspace through the `packages/*` glob in `vitest.config.ts`, and Turborepo through `pnpm-workspace.yaml`. Neither file needs editing. The coverage gate starts applying to it immediately.

Step 5 is not busywork. CI installs with `--frozen-lockfile`, which refuses a workspace that has no `importers` entry — and when the new package has no dependencies of its own, a plain `pnpm install` does not add one, nor does `pnpm install --lockfile-only` despite what the error message suggests. Only a clean resolve writes it:

```bash
rm -rf node_modules pnpm-lock.yaml && pnpm install
```

That produces a one-line diff (`packages/<name>: {}`) and no version drift, because every dependency is pinned exactly. Confirm with `pnpm install --frozen-lockfile` before pushing; it fails locally exactly as it does in CI.

A package that imports another workspace package adds a `resolve.alias` for it in its own `vitest.config.ts`, as `packages/db` does for `@helpdock/config`. Without it the `exports` map sends the test to the other package's last build instead of to its source.

Dependencies must come from the stack table in [ARCHITECTURE.md §1](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/ARCHITECTURE.md); anything else needs an ADR first.

## The app import rule

`apps/*` never import each other. They share code only through `packages/*` (ARCHITECTURE §2).

`scripts/check-app-boundaries.ts` enforces it and runs in CI. It scans every source file under `apps/` and fails on two things: importing another app by workspace name (`@helpdock/widget` from `apps/api`), and reaching into another app with a relative path (`../../widget/src/…`). Imports of `packages/*`, of external modules, and within the same app all pass.

It is a lexical scan rather than a parse, so a module specifier written inside a string or a comment can trigger a false positive. That fails loudly, which is the right direction for a boundary check.

## Configuration

Configuration has two layers, both typed and both validated with Zod
([ARCHITECTURE §4](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/ARCHITECTURE.md#4-configuration-model)). They live in
`packages/config`.

### The bootstrap environment

`.env` holds what the process needs before it can read the database: the database
and Redis URLs, the S3 credentials, the master key, the public URL, the role and
the port. [`.env.example`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.env.example) documents every one of them; copy
it to `.env` and fill it in; `env.test.ts` fails if the two ever drift apart.

```ts
import { loadEnv } from '@helpdock/config';

const env = loadEnv(); // reads process.env; pass a record to test it
```

`loadEnv` returns a frozen, typed object, or throws one `EnvValidationError`
naming every key that is wrong and what it expected. It never quotes the value:
these keys hold the master key and the S3 credentials. An empty value counts as
unset, so an optional key can stay blank in the file.

`APP_MASTER_KEY` is 32 bytes of base64 (`openssl rand -base64 32`). Every secret
setting is encrypted under it with AES-256-GCM and stored as
`v1.<keyId>.<iv>.<ciphertext>.<tag>`. The key id is the first 8 hex characters of
`sha256(key)`, so a row records which key generation wrote it. During a rotation
`APP_MASTER_KEY_PREVIOUS` holds the old key: both generations stay readable, and
`rotateSecret` re-encrypts a value under the current key
([DOMAIN-RULES §10](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#10-operations-and-recovery)).

### The settings registry

Everything else — SMTP, OAuth client ids, CAPTCHA keys, feature toggles — is a
key in the registry in `packages/config/src/registry.ts`. Each entry declares its
Zod schema, its default, whether it is a secret, whether it is install-wide or
per-brand, a description, and the environment variable that can override it.

```ts
import {
  createKeyring,
  createSettings,
  InMemorySettingsStore,
  LocalInvalidation,
} from '@helpdock/config';

const settings = createSettings({
  store: new InMemorySettingsStore(), // PostgresSettingsStore in @helpdock/db for a real install
  keyring: createKeyring(env),
  invalidation: new LocalInvalidation(),
});

await settings.get('smtp.port'); // 587, typed as number
await settings.set('smtp.host', 'smtp.example.com', { updatedBy: userId });
```

A value resolves in one order: **environment override → stored value →
default**. Secret keys are decrypted on the way out and encrypted on the way in;
`getAll()` leaves them out entirely unless it is called with
`{ includeSecrets: true }`, which is for server-side use only and must never
reach a response DTO.

Reading a secret whose master key is gone fails with a `SecretDecryptionError`
rather than falling back to the default, because an OAuth client silently running
on an empty secret is worse than one that refuses to start.

Resolved values are cached in process. `set` publishes the key on the
invalidation channel — `helpdock:settings:invalidate` under `RedisInvalidation` —
every replica drops it from its cache and reads it again on the next `get`, so an
admin change applies everywhere within a second and without a restart.
`LocalInvalidation` does the same in one process, for tests and for an install
running a single replica.

### Locking a setting from the environment

Setting a registry key in the environment pins it. The name is `HD_` plus the key
in upper snake case — `smtp.host` is `HD_SMTP_HOST`, `oauth.google.clientId` is
`HD_OAUTH_GOOGLE_CLIENT_ID` — and a definition may name its own variable instead.

A pinned key wins over the database, `isLockedByEnv(key)` returns `true` so admin
can show it as "set by environment", and `set` rejects it with a
`SettingLockedError`. An override that does not satisfy its schema stops the
process at construction rather than being ignored.

### Adding a setting

1. Add a `defineSetting({ … })` entry to `SETTING_DEFINITIONS`. The key, schema,
   default, `secret`, `scope` and description are all required; `envKey` is
   derived unless you give one.
2. Nothing else needs a type: `SettingKey`, `SettingValues` and `settingsSchema`
   are derived from the list, so `get` and `set` are typed immediately.
3. Add or extend a test in `registry.test.ts` if the key carries a rule worth
   stating, such as a bound or an enum.
4. Document it wherever operators will look for it. Bootstrap keys go in
   `.env.example`; registry keys are described in the registry itself and surface
   in admin.

## UI and i18n

Everything a screen looks like and every word it says come from two packages, so
the admin app, the help center and the widget stay one product.

[`packages/ui`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/ui/README.md) is
[DESIGN.md](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/DESIGN.md) in code: `tokens.json` is the single source of truth
for colour, type, spacing, radius, elevation and motion, and the package builds
the MUI theme, the light and dark `--hd-*` custom properties the widget uses, the
two Emotion caches that make RTL work, and `resolveBrandTheme` for the per-brand
accent, ramp and radius. Its contrast suite asserts every pair DESIGN §2.2 claims,
in both modes, so a colour change that breaks AA fails CI. The self-hosted IBM
Plex, Noto Sans and Vazirmatn woff2 files live there too, under a 1.5 MB budget.

```ts
import { createHelpdockTheme, createRtlCache, tokens } from '@helpdock/ui';
```

[`packages/i18n`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/i18n/README.md) holds the `en` and `ar` catalogs,
one namespace per screen area, and `createI18n` plus the `dir(lng)` helper that
decides text direction everywhere. No user-facing string is written in an app —
labels, hints, errors and `aria-label`s all go through `t()`. A key present in one
language and missing in the other fails the parity test, and every plural key
carries all six Arabic forms.

```ts
import { createI18n, dir } from '@helpdock/i18n';
```

Both packages compile with `rootDir` at the package root rather than `src/`,
because `tokens.json` and `locales/` sit beside the source and have to reach
`dist/`. Their `exports` maps therefore point at `./dist/src/index.js`.

Before changing either, read DESIGN.md. A new colour, font size, radius or
spacing value needs a change there first, and a new component needs a DESIGN §6
entry in the same pull request.

Formatted dates and numbers go through
[`apps/admin/src/ui/format.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/admin/src/ui/format.ts)
(`formatDay`, `formatDayTime`, `latinNumbering`), never through a bare
`toLocaleString()` and friends: a call with no locale argument follows the
browser's locale instead of the app's and prints Arabic-Indic digits in `ar`,
against DESIGN §7 (finding UX-04 of the
[1.0 UX review](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/completed/ux-review-1-0.md)). `pnpm lint` fails on such a call, or one that passes `undefined` as the
locale, anywhere in `apps/admin/src` (the Biome plugin
[`scripts/biome/bare-locale-call.grit`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/scripts/biome/bare-locale-call.grit),
scoped by an override in `biome.json`); pass an explicit locale or go through
the helper. Case folding on comparisons uses the
locale-independent `toLowerCase` and `toUpperCase` for the same reason.

## Database

The schema, the migrations and the row-level security policies live in
`packages/db`. Its [README](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/db/README.md) is the reference; this
is what you need to run it.

### The two connection URLs

Helpdock connects to Postgres as two different roles ([DOMAIN-RULES
§1.5](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#1-authorization)):

| Key | Role | Used for |
|---|---|---|
| `DATABASE_MIGRATION_URL` | the owner | migrations only, at api boot |
| `DATABASE_URL` | `helpdock_app` | every runtime query |

`helpdock_app` is `NOSUPERUSER NOBYPASSRLS`, owns nothing, and may only read and
write rows. The first migration creates it, with the password from
`DATABASE_URL`, so a fresh database needs only the owner to exist and to have
`CREATEROLE`. `assertRuntimeRoleIsSafe(db)` throws rather than let a process
serve on a connection that can bypass row-level security; api boot calls it from
M0-04 onwards.

### Running migrations

Migrations run from the application, not from a CLI. Api boot calls this from
M0-04 onwards; until then it is what the integration tests call:

```ts
import { appRolePasswordFromUrl, runMigrations } from '@helpdock/db';

const { applied } = await runMigrations({
  migrationUrl: env.DATABASE_MIGRATION_URL,
  appRolePassword: appRolePasswordFromUrl(env.DATABASE_URL),
});
```

It takes a Postgres advisory lock first, so several api replicas can start
together and the migrations still run once. `drizzle-kit migrate` and
`drizzle-kit push` are deliberately not part of any workflow.

### Changing the schema

```bash
pnpm --filter @helpdock/db gen:migration   # drizzle-kit generate from src/schema
pnpm --filter @helpdock/db gen:rls         # append the missing policies to that migration
```

Both write into `packages/db/drizzle/`, and both belong in the same commit as
the schema change. A new tenant table also has to be added to `TENANT_TABLES`
and to the negative suite in `rls.integration.test.ts`; unit tests fail until it
is, which is how [DOMAIN-RULES
§1.6](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#1-authorization) stays true.

### Integration tests with Postgres

`packages/db/src/*.integration.test.ts` start `pgvector/pgvector:pg17` through
Testcontainers, apply the migrations and run against the real thing, as the real
runtime role:

```bash
pnpm test:integration packages/db
```

The first run pulls the image, which can take a few minutes; pull it in advance
with `docker pull pgvector/pgvector:pg17` if the suite times out. No local
Postgres is needed, and without Docker the suites skip themselves.

## Jobs and outbox

Queues, job schemas, the outbox relay and the consumer wrapper live in
`packages/jobs`. Its [README](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/jobs/README.md) is the reference;
this is the part you need before writing a feature.

One rule governs everything here
([DOMAIN-RULES §6](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#6-transactional-outbox)): **a side
effect is enqueued in the same transaction as the change that causes it, and
executed at least once, idempotently.** Sending an email, calling an LLM,
delivering a webhook, indexing knowledge, processing media — all of them start as
a row in `outbox`.

### Asking for a side effect

Never call `queue.add` from a request handler, a service or an event listener.
Write an outbox row through the transaction you are already in:

```ts
import { enqueueOutbox } from '@helpdock/jobs';

await withTenant(db, context, async (tx) => {
  const ticket = await tx.insert(tickets).values(…).returning();
  await enqueueOutbox(tx, {
    brandId,
    event: 'ticket.replied',
    payload: { ticketId: ticket.id },
  });
});
```

If the transaction rolls back, the row was never there and no job exists. If it
commits, the relay publishes the row to BullMQ with `jobId = outbox.id` and
stamps `published_at` in one transaction, so a crash costs at most a duplicate
job and never a lost one.

### Handling it

Register a handler for the event and let the dispatcher route to it. The handler
runs inside the brand's transaction, next to the `job_receipts` claim that makes
the delivery exactly-once:

```ts
import { registerEventHandler } from '@helpdock/jobs';

registerEventHandler('ticket.replied', async ({ brandId, payload, tx }) => {
  await tx.insert(notifications).values({ brandId, … });
});
```

Throwing asks BullMQ for a retry and rolls back both the writes and the receipt.
Returning commits both, so every later delivery of the same key stops at the
receipt. A payload that fails its Zod schema is not retried at all: it goes
straight to the failed set with the issues in `job.failedReason`.

### Adding a job

Jobs are declared in `packages/jobs/src/jobs.ts` with a name, a queue from
[ARCHITECTURE §13](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/ARCHITECTURE.md#13-background-jobs-bullmq-queues),
a Zod payload schema that includes `brandId`, and a retry profile. The schema is
used on enqueue and on consume, so the two cannot drift.

### Running it

The relay and the consumers run in the worker, which is the same image with
`APP_ROLE=worker`. The README's "What the worker host wires at boot" shows the
order: register handlers, start the workers, then start the relay.

The suites in `packages/jobs/src/*.integration.test.ts` start a real Postgres and
a real Redis and prove the guarantees, including a relay killed between the `add`
and the commit:

```bash
pnpm test:integration packages/jobs
```

## Admin app

[`apps/admin`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/admin/README.md) is the Vite + React SPA agents and
administrators work in. It is the first app with screens, so it is also where
the browser tests live.

```bash
pnpm build                          # once, so the packages have a dist/
pnpm --filter @helpdock/admin dev   # http://localhost:5273
```

The app talks to the api through an `AuthApi` interface with two adapters.
`VITE_AUTH_API` picks one — `mock`, the in-memory fixture, by default in dev and
test; `http`, the real service, in a production build — and
[`apps/admin/.env.example`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/admin/.env.example) documents it. The
fixture's credentials are in the app's README; running against a real api is in
[the authentication guide](https://helpdock.oday-bakkour.com/docs/authentication/#the-development-install).

`apps/admin` owns its whole TypeScript program, including its tests and its
Playwright specs, because they need `jsx`, `dom` types and bundler resolution
that the Node-shaped root config does not have. It is therefore excluded from
the root `tsc --noEmit`, and `pnpm --filter @helpdock/admin typecheck` covers it
instead; `pnpm typecheck` runs both.

### Browser tests

```bash
pnpm --filter @helpdock/admin e2e             # both locales, against the fixture
pnpm --filter @helpdock/admin e2e:api         # against a real api; needs Docker
pnpm --filter @helpdock/admin e2e:screenshots # the tagged screenshot suite
pnpm --filter @helpdock/admin e2e:baselines   # regenerate Linux screenshots
```

Playwright runs every spec twice, once in `en` and once in `ar`, as two projects
that differ only in the locale they seed into `localStorage`. An RTL layout is a
different layout (DESIGN §7), so a spec that passes in one direction proves
nothing about the other. `@axe-core/playwright` scans each screen against WCAG
2.1 A and AA and the suite fails on any violation.

Screenshot baselines live under `apps/admin/e2e/__screenshots__/<locale>/` and
are **Linux pixels**, because the comparison runs on `ubuntu-latest`. They are
generated by CI, not on a laptop:
[`.github/workflows/screenshots.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/screenshots.yml)
renders them on the same runner image, with the same
`playwright install --with-deps chromium`, as the step that compares them, and
uploads them as an artifact called `screenshot-baselines`. Run it from the
Actions tab or with `gh`, then commit what comes back:

```bash
gh workflow run screenshots.yml --ref <your-branch>
# gh will not overwrite existing files, so download elsewhere and copy them in.
gh run download <run-id> --name screenshot-baselines --dir /tmp/screenshot-baselines
cp -R /tmp/screenshot-baselines/ apps/admin/e2e/__screenshots__/
git add apps/admin/e2e/__screenshots__
```

It also runs by itself on a pull request that touches `apps/admin/src/**`,
`packages/ui/src/**` or the spec, so a deliberate layout change arrives with its
new baselines attached to the run.

The spec stays tagged `@screenshot` and stays out of `pnpm e2e`. That is not a
leftover: a comparison against Linux pixels fails on macOS and on Windows, and
`pnpm e2e` has to be a command a contributor can run. CI runs the comparison as
its own step, `pnpm --filter @helpdock/admin e2e:screenshots`, which is also the
command to run on a Linux machine. `e2e:baselines` regenerates them locally
through `mcr.microsoft.com/playwright`; the admin README explains why the dev
server stays outside that container, and why the workflow is the answer that
does not depend on a 2 GB pull.

The help center and the widget have RTL snapshots of their own, in text rather
than pixels, so they read the same on every machine:
`apps/api/e2e/help-center-rtl.spec.ts` (the Arabic article page) and
`apps/widget/e2e/rtl-snapshot.spec.ts` (the Arabic chat window). Each compares
an aria snapshot and a list of layout facts (which column a region is in, which
side a line of text starts from, which icons are mirrored) against the
baselines in that app's `e2e/__snapshots__/`. After a deliberate layout change,
regenerate them with `--update-snapshots` and review the diff:

```bash
pnpm --filter @helpdock/api build
pnpm --filter @helpdock/api e2e e2e/help-center-rtl.spec.ts --update-snapshots
pnpm --filter @helpdock/widget e2e e2e/rtl-snapshot.spec.ts --update-snapshots
```

`e2e:api` is a second config: it starts Postgres and Redis with Testcontainers,
runs the built api as its own process, seeds a known account, and drives the
same screens with `VITE_AUTH_API=http`. It needs a `pnpm build` first, and it
skips itself with a message when Docker is not running.

CI installs Chromium with `pnpm exec playwright install --with-deps chromium`,
caches it by the Playwright version in the lockfile. The fixture suite runs in
two shards (`e2e (1/2)` and `e2e (2/2)`); the screenshot comparison and
`e2e:api` run together in `browser-api`, after `pnpm build`.

## Docker

`docker/` holds the image and the Compose stack. Operators read
[the install guide](https://helpdock.oday-bakkour.com/docs/install/); this is what the stack is for while developing.

```
docker/Dockerfile              one image, two roles (APP_ROLE=api|worker)
docker/docker-compose.yml      the production stack of ARCHITECTURE §17
docker/docker-compose.dev.yml  local overrides: build here, publish ports
docker/caddy/Caddyfile         host routing and TLS
docker/postgres/init.sql       creates the helpdock_app role on first boot
```

### Infrastructure for the dev loop

The usual loop runs the apps on the host with `pnpm dev` and only the services
in containers:

```bash
cd docker
cp ../.env.example .env         # fill in APP_MASTER_KEY and the passwords
docker compose -f docker-compose.yml -f docker-compose.dev.yml \
  --profile dev up -d postgres redis minio minio-bucket mailpit
```

That publishes Postgres on 5432, Redis on 6379, MinIO on 9000 (console 9001) and
Mailpit on 1025 (inbox at http://localhost:8025). Point the repository-root
`.env` at `localhost` for each of them, as [API](https://helpdock.oday-bakkour.com/docs/development/#api) below shows. Mailpit is
what the first-run wizard's "Send a test email" can be pointed at — host
`localhost`, port `1025`, encryption **None**, no username — and what M2's
outbound email will use; the wizard's integration suite starts its own copy.

Nothing is bind-mounted from the source tree. The containers run what the image
contains; the code you are editing runs on the host.

### The whole stack from your working copy

```bash
cd docker
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
curl -s localhost:3000/health
```

This builds `docker/Dockerfile` from the repository root and runs one api
replica on `127.0.0.1:3000` plus a worker. Caddy is behind the `proxy` profile
and stays down, because it would try to get certificates for hostnames that do
not resolve on your machine.

`scripts/compose-smoke.sh` is the same thing as a check: it writes a throwaway
`docker/.env`, waits for the api to be healthy, and asserts that `/health` and
`/ready` answer 200, that `/` returns the admin build, that an unverified domain
gets no certificate, and that `/api/me` still answers 401. Then it does what a
new operator does: runs the first-run wizard, signs in as the administrator it
made — which, since that account must have a second factor, answers with an
enrolment challenge rather than a session — enrols an authenticator from the
secret the api hands back (the script computes the code itself, with `base32`
and `openssl`), and pushes an image through the media pipeline on the session
that produced. CI runs it after building the image, and so can you:

```bash
docker build -f docker/Dockerfile -t ghcr.io/docker-hunterpedia/helpdock:ci .
HELPDOCK_VERSION=ci ./scripts/compose-smoke.sh
```

### The image

Three stages: `deps` installs the whole workspace from the lockfile, `build`
runs `pnpm build` and then `pnpm deploy --filter @helpdock/api --prod` into
`/out`, and `runtime` takes that plus `apps/admin/dist` into a `node:24-bookworm-slim`
running as the non-root `helpdock` user. The entry point is
`node dist/main.js` for both roles; `APP_ROLE` decides which one boots.

Two things worth knowing before changing it:

- **The admin build lives at `/app/admin`**, which is the default of
  `ADMIN_DIST_DIR`. The api serves it at `/` and rewrites the install meta tags
  per request; see [Serving the admin SPA](https://helpdock.oday-bakkour.com/docs/development/#serving-the-admin-spa).
- **`pnpm fetch` runs with `trustLockfile`**, so the image build does not repeat
  pnpm's supply-chain verification of a lockfile that `pnpm install` has already
  verified on the developer's machine and in CI. It resolves nothing of its own;
  a change to the lockfile still goes through a verified install first.

## API

`apps/api` is the NestJS application. Its
[README](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/api/README.md) is the reference for the boot sequence, the
request lifecycle and how to add a route; this is how to run it.

Start Postgres and Redis with [the dev Compose stack](https://helpdock.oday-bakkour.com/docs/development/#docker), then copy
`.env.example` to `.env` at the repository root and set at least:

```bash
APP_URL=http://localhost:3000
APP_ROLE=api
APP_MASTER_KEY=$(openssl rand -base64 32)
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://helpdock_app:app-password@localhost:5432/helpdock
DATABASE_MIGRATION_URL=postgres://helpdock_owner:owner-password@localhost:5432/helpdock
REDIS_URL=redis://localhost:6379
```

`DATABASE_URL` must name `helpdock_app`; the first migration creates that role
with the password you put there. The `S3_*` keys are required to boot but
nothing reads them until M1, so any non-empty values will do for now.

The api is compiled before it runs: Node's built-in type stripping does not
transform decorators, and NestJS is built on them. So a dev loop is two
terminals — one compiling, one running what it compiled.

```bash
pnpm --filter @helpdock/api dev:build   # tsc --watch into dist/
pnpm --filter @helpdock/api dev         # node --watch dist/main.js, reads ../../.env
```

The first start runs the migrations, verifies that the runtime role cannot
bypass row-level security, and logs both. `GET /health` and `GET /ready` answer
without a session.

### Authenticating locally

Sign in the way a person does. `pnpm --filter @helpdock/api seed:dev` creates one
brand and one install admin with a password that is written down in [the
authentication guide](https://helpdock.oday-bakkour.com/docs/authentication/#the-development-install), and

```bash
curl -s -X POST localhost:3000/api/auth/sign-in \
  -H 'content-type: application/json' \
  -d '{"email":"admin@helpdock.test","password":"helpdock dev password"}'
```

answers with an access token to send as `Authorization: Bearer …`.

On a database with no accounts in it you can instead do what an operator does
and take the first-run wizard. Point the browser at the api itself rather than
at the Vite dev server — the wizard reads a meta tag the api rewrites into
`index.html`, and Vite serves its own copy of that file — which means building
the admin first and telling the api where it is:

```bash
pnpm build
ADMIN_DIST_DIR="$PWD/apps/admin/dist" pnpm --filter @helpdock/api dev
```

Then open http://localhost:3000 and follow [the install
guide](https://helpdock.oday-bakkour.com/docs/install/#first-run).

To exercise the tenancy plumbing without a session — a different principal
shape, an api key, a worker — set

```bash
HD_DEV_PRINCIPAL_HEADER=1
```

in `.env` and send a whole principal as JSON in the `x-hd-dev-principal` header
instead. It is refused when `NODE_ENV=production`, and boot logs a warning
whenever it is on, because anyone who can reach the port can name themselves an
install admin.

```bash
curl -s localhost:3000/api/me \
  -H 'x-hd-dev-principal: {"type":"staff","id":"0199f4b2-6a91-7c27-9a1f-000000000001","brands":{},"installAdmin":true}'
```

The flag replaces the session resolver rather than adding to it: a process that
trusts the header trusts it for every request.

### Serving the admin SPA

With `ADMIN_DIST_DIR` pointing at a built `apps/admin/dist`, the api serves the
SPA at `/`: a request for a file in the build gets that file, and anything else
that is not under `/api` gets `index.html` so the client router can take over. A
missing endpoint under `/api` stays a JSON 404, because handing a `fetch` a page
where it asked for data hides the error rather than reporting it.

`index.html` is sent with `no-store` and its two `helpdock:*` meta tags rewritten
from this install's brands; everything under `assets/` is content-hashed by Vite
and sent as `immutable` for a year. The image sets `ADMIN_DIST_DIR=/app/admin`;
outside the image it defaults to that same path, so a dev api simply logs that
it found no build and serves `/api` alone.

The dev loop does not use any of this: `pnpm --filter @helpdock/admin dev` runs
Vite on 5273 and proxies `/api` to `http://localhost:3000`, so the browser sees
one origin and a session cookie works. `VITE_API_ORIGIN` points the proxy
somewhere else.

### The worker role

`APP_ROLE=worker` boots the same process without the HTTP listener and without
running migrations: a worker waits for an `APP_ROLE=api` replica to migrate,
polling for up to 60 seconds. It then registers the `outbox.event` consumer and
starts the outbox relay, in that order, and shuts them down in the reverse one
(`apps/api/src/worker/start-worker.ts`, following
[`packages/jobs/README.md`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/packages/jobs/README.md)). The relay reports
each cycle to Redis, which is what the System page's Worker card and the
`outbox_relay_up` metric read; with no worker running, both say so.

```bash
cd docker && docker compose -f docker-compose.yml -f docker-compose.dev.yml \
  up -d --build worker
docker compose logs -f worker
```

### Watching it run

Logs are pino JSON on stdout. With `NODE_ENV=development` they are prettified
instead, so a dev loop is readable without a pipe. `LOG_LEVEL` sets the level;
`info` is one line per request.

`GET /metrics` answers from `localhost`, so a local Prometheus or a plain `curl`
reaches it with no token:

```bash
curl -s localhost:3000/metrics | head
```

Tracing is off unless `OTEL_EXPORTER_OTLP_ENDPOINT` is set. With a collector
running, set it in `.env` and spans go there; the `dev` script already preloads
the SDK with `--import`.

The [operations guide](https://helpdock.oday-bakkour.com/docs/operations/) is the reference for all three, and for
what the admin System page shows.

### Routes declare their permission

Every controller handler carries `@Requires(permission)`, `@Authenticated()` or
`@Public()`. The permission guard refuses a handler that carries none, and
`pnpm check:routes` fails the build for one
([DOMAIN-RULES §1.3](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/planning/DOMAIN-RULES.md#1-authorization)). The check is
a token scan over `apps/*/src` using TypeScript's own scanner, so a decorator
name in a comment or a string is not mistaken for a declaration.

§1.3 says "per route **or event**", so a `@SubscribeMessage` handler on a
`@WebSocketGateway` is held to the same rule by the same guard and the same
check.

### Routes name their input schema

Every `@Param`, `@Query` and `@Body` on a controller handler passes its schema
explicitly:

```ts
@Post('sign-in')
@Public()
async signIn(@Body(new ZodValidationPipe(SignInRequestDto)) body: SignInRequestDto) {}
```

Not because the global pipe does not work, but because it works *conditionally*.
nestjs-zod's global `ZodValidationPipe` finds a DTO's schema through the
`design:paramtypes` metadata the compiler emits for a decorated parameter. An
`import type` erases that metadata — and Biome's `useImportType` rewrites any DTO
used only as a type into one — so validation stops without a word. A transform
that never emits the metadata at all, like the esbuild Vitest uses, removes it
everywhere at once. That is what
[issue #36](https://github.com/Docker-Hunterpedia/Helpdock/issues/36) was:
`GET /api/brands/:brandId` had not been validating anything, and its 400 for a
malformed id came from the permission guard.

`pnpm check:validation` fails the build for a parameter that names no schema. It
shares its scanner with `pnpm check:routes`
([`scripts/controller-scan.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/scripts/controller-scan.ts)).

Two things the check leaves alone, on purpose:

- **Socket events.** `@MessageBody()` on the `/staff` gateway is typed `unknown`
  and parsed inside the handler with `parseMessage(schema, body)`, because a
  pipe cannot answer through an acknowledgement.
- **Which values a schema allows.** `oauthProviderParamSchema` bounds the
  `:provider` segment but does not list the providers, because both OAuth routes
  answer a browser with a redirect and a pipe can only answer with a body. The
  handler maps an unknown provider to a refusal the sign-in screen renders.

Guards run before pipes, so a brand-scoped route's `:brandId` is read by the
permission guard first. It refuses a malformed one with `brandIdParamSchema` —
the same schema the handler names — so the response carries
`fields: [{ path: "brandId" }]` either way.

### Realtime

The api serves a Socket.IO `/staff` namespace on `/socket.io`, and the admin
connects to it as soon as there is a session. Nothing extra has to be
configured: `APP_URL` decides the allowed origin and `REDIS_URL` the adapter's
connections. [The realtime guide](https://helpdock.oday-bakkour.com/docs/realtime/) is the contract — namespaces,
the handshake, rooms and their permission rule, presence, revocation, and what
to do to add an event.

## Tests

Unit tests are Vitest, colocated as `src/**/*.test.ts`. `pnpm test` runs one Vitest process across all workspaces, defined as projects in the root `vitest.config.ts`.

### Coverage gates

The large migration reference fixtures run separately from instrumented API
coverage. Run Zendesk with `pnpm exec vitest run --project integration apps/api/src/imports/zendesk-reference.integration.test.ts --maxWorkers=1`.
Run Freshdesk or Zoho with `pnpm exec vitest run --project integration apps/api/src/imports/native-reference.integration.test.ts --testNamePattern freshdesk --maxWorkers=1`
(replace `freshdesk` with `zohodesk` for Zoho). Build workspace packages first:
the disposable worker process uses their normal `dist/` exports.
CI requires both `api` and the `import-reference` matrix for affected API changes; the latter
is skipped for changes confined to unrelated workspaces, such as admin UI.
The API coverage gate still includes every production import file, exercised by
the smaller real-database integration cases. Only the two large reference test files
are excluded from that instrumented run. Each source job has a 45-minute budget
for full extraction, dry run, loading, repeat and delta; it does not contact a
real vendor. The Freshdesk/Zoho cases also kill an owned worker process during
attachment I/O and restart it through production claim recovery. They advance
only the dead claim's timestamp to avoid waiting the 30-minute lease timeout;
they do not modify cursors, receipts or business records to simulate recovery.

Run the import wizard against the real API in both languages with
`pnpm --filter @helpdock/admin e2e:imports --workers=1`. Build the workspace
packages and API first. This separate Playwright configuration starts its own
Postgres and Redis, a compiled API process and the import/media workers. It
signs in through real TOTP, reads from the Zendesk stand-in, confirms mapping
choices over the public API, and reviews/approves the import through the wizard.
It checks original history and managed file bytes, plus SMTP/HTTP tripwires,
quiet domain/outbox rows and credential purge. Its storage driver is the local
test stand-in, so this does not replace the real object-storage integration
suite. Docker absence may skip this suite locally; a failed probe fails CI.
The fixture's vendor DNS mapping accepts only the named local test hosts; the
browser must still approve the stand-in's separate attachment CDN host.
These newly authored cases still require a passing run before acceptance is claimed.

Coverage uses `@vitest/coverage-v8`. There are three gates, all on lines, all
run by their own CI job — a drop below any of them fails that job, and with it
the required `ci` check:

| What it measures | Gate | Command | Configured in |
|---|---|---|---|
| `packages/*/src` | **80 %** | `pnpm test` (CI leaves out the two app projects, whose own gates run them) | [`vitest.config.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/vitest.config.ts) |
| `apps/api/src`, unit **and** integration suites together | **90 %** | `pnpm --filter @helpdock/api test:coverage` | [`apps/api/vitest.coverage.config.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/api/vitest.coverage.config.ts) |
| `apps/admin/src` | **85 %** | `pnpm --filter @helpdock/admin test:coverage` | [`apps/admin/vitest.config.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/apps/admin/vitest.config.ts) |

80 % on `packages/*` is the number in ARCHITECTURE §15. The two apps have gates
of their own for opposite reasons. `apps/api` has no UI, so nothing else covers
it — and it is measured across both suites because half of it is only reached
over HTTP, and a figure from the unit run alone would say more about where the
tests are than about what is covered. `apps/admin` is measured by Vitest for its
logic and by Playwright for its layout, so its gate is lower; it was raised from
70 with M0-06 and held there by M0-08, because those screens decide what a
person may do and whether an install can be finished at all.

Raising a gate is a pull request of its own. Lowering one needs a reason in the
pull request description.

### Integration tests

Anything that touches Postgres, Redis, a queue or a channel adapter is tested against the real thing, started by [Testcontainers](https://node.testcontainers.org/). These files are named `*.integration.test.ts`, sit beside the code they cover, and belong to a Vitest project called `integration`:

```bash
pnpm test:integration                                  # the whole project
pnpm test:integration packages/config                  # one directory
pnpm test:integration apps/api                         # the api against real Postgres and Redis
```

They do cover input validation, which they did not until M0-11: every route now
names its schema on the parameter rather than leaving it to the global pipe's
`design:paramtypes` metadata, which esbuild — what Vitest transforms with — does
not emit. [Routes name their input schema](https://helpdock.oday-bakkour.com/docs/development/#routes-name-their-input-schema) is
the rule and `pnpm check:validation` is what keeps it.

They are not part of `pnpm test`, which stays fast and needs nothing installed. CI runs them as a step of its own; GitHub-hosted runners have a Docker daemon, so no service container is declared in the workflow.

Without Docker the suites skip themselves and say so on stderr instead of failing, so `pnpm test:integration` is safe to run anywhere. A skipped run is not a passing run: if you changed anything that talks to infrastructure, start Docker before you open the pull request.

Each file detects Docker for itself and guards its suite:

```ts
const hasDocker = await promisify(execFile)('docker', ['info', '--format', '{{.ServerVersion}}'], {
  timeout: 10_000,
}).then(
  () => true,
  () => false,
);

describe.skipIf(!hasDocker)('settings invalidation over Redis', () => {
  // …
});
```

### Standing in for a vendor

No suite reaches a vendor: CI has no network and no credentials. Telegram has a
local Bot API server (`apps/api/src/testing/fake-telegram.ts`); the Meta
channels (WhatsApp, Messenger, Instagram; [ADR 0025](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/docs/decisions/0025-meta-channels-through-one-graph-adapter.md))
have a stand-in for Graph and a driver that posts signed webhooks, both
exported from `packages/channels/src/meta/testing/` as
`@helpdock/channels/testing`. That subpath is for tests only: the package's root,
which the api and the worker import, has none of it. It also exports the fixtures
the stand-in, the driver and the unit tests share (`whatsappText`, `pageText`,
`instagramText`, `whatsappStatus`, …), written against the Graph version
`META_GRAPH_VERSION` defaults to. Bumping that version means reading Meta's
changelog for these shapes first, and the fixtures second.

```ts
import { FakeGraph, MetaWebhookDriver, whatsappText } from '@helpdock/channels/testing';

const graph = new FakeGraph();
await graph.start();

// Point the api at it, and let `safeFetch` reach 127.0.0.1:
//   META_GRAPH_API_ROOT=<graph.facebookRoot>
//   META_INSTAGRAM_API_ROOT=<graph.instagramRoot>
//   OUTBOUND_ALLOW_CIDRS=127.0.0.0/8
graph.connect({
  platform: 'whatsapp',
  id: '106540352242922',     // the phone number id
  wabaId: '102290129340398', // required: the business account the number belongs to
  name: 'Acme',
  token: 'EAAG…',
});

// Meta posts: signed with the test app's secret, through the Nest app's `inject`.
const meta = new MetaWebhookDriver({ target: app, secret: 'the-test-app-secret' });
await meta.post(whatsappText({ wamid: 'wamid.1', text: 'Hello' }));

// What Helpdock sent back, and to whom.
graph.sentTo('16505551234'); // the messages it accepted
graph.callsTo('/messages');  // every call, with root, version, token, query and body
```

`graph.windowClosed`, `.pairLimited`, `.blocked` and `.expiredTokens` make it
refuse the way Meta does (`131047`, `131056`, `551`, `190`), `graph.failures`
queues a 5xx or a redirect for the next matching request, and a token is good
on the root of its own platform only, so a call sent to the wrong host fails as
it would in production. It checks every body it is sent against the contract in
`send-payloads.ts` and the platforms' text limits (4096 characters, 2000
characters, 1000 bytes), so a splitter that cuts wrongly fails a test and not a
customer. The driver's `post(body, { secret, header, tamper })` sends a wrong
signature, none, or a body changed after it was signed, and `handshake` makes
the callback-URL request.

WhatsApp is shaped as Meta shapes it: a number belongs to a business account.
`connect` throws for a WhatsApp number without its `wabaId`, and the token opens
the business account as well as the number. The webhook subscription lives on
the business account, `GET|POST|DELETE /{waba}/subscribed_apps`, shared by every
number under it; the same path on a number's own id answers Graph's
"Unsupported get request" (HTTP 400, code 100). In a test,
`graph.subscribe(wabaId)`, `graph.dropSubscription(wabaId)` and
`graph.subscriptionOf(wabaId)` take the business account's id for WhatsApp and
the Page's or Instagram account's own id for the others, and say which id to use
when given a number's.

The driver posts to the Nest app's `inject` in the example above. To post to a
running server instead, pass `httpWebhookTarget(baseUrl)` as the target.

The admin's browser suites start the same `FakeGraph` (`apps/admin/e2e/api/fake-graph.ts`
connects the accounts the specs use, as a workspace devDependency on
`@helpdock/channels`). The seeded api is started with `META_GRAPH_API_ROOT` and
`META_INSTAGRAM_API_ROOT` pointed at it, on `HD_E2E_GRAPH_PORT` (3095 by
default). A spec runs in another process than the stand-in, so it reaches it
over HTTP, under `/__control/`, with no token: `GET /__control/subscriptions/<id>`
reads back the fields the app is subscribed to (on the business account for a
number), `POST /__control/tokens/expire` and `/restore` with `{ token }` make a
token Meta has revoked and give it back, and `POST /__control/failures` with
`{ status, body?, match? }` queues a refusal for the next call whose `METHOD /path`
matches the pattern. Nothing runs the stand-in from a shell on its own, and Meta cannot reach
a development machine, so a real webhook needs a public HTTPS address at
`APP_URL`, as in production. The [Meta channels guide](https://helpdock.oday-bakkour.com/docs/meta-channels/#developing-without-meta)
covers the rest. Two reads help a connect flow find the business account
from a number: `GET /debug_token?input_token=…` answers a WhatsApp token's
`data.granular_scopes` (`whatsapp_business_management` and
`whatsapp_business_messaging`, each with the business account ids in
`target_ids`), and `GET /{waba}/phone_numbers` lists the numbers under one with
their `display_phone_number`, `verified_name` and, when the test sets
`qualityRating`, `quality_rating`.

## CI

Five workflows, under [`.github/workflows/`](https://github.com/Docker-Hunterpedia/Helpdock/tree/main/.github/workflows). Every
third-party action in all of them is pinned to a full commit sha with the
version in a comment beside it, because a moving tag is a moving dependency
nobody reviews; Renovate proposes the bumps.

| Workflow | Runs on | What it is for |
|---|---|---|
| [`ci.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/ci.yml) | every pull request, pushes to `main` | The required check: parallel jobs, gathered by one named `ci`. |
| [`screenshots.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/screenshots.yml) | manually, and pull requests touching `apps/admin/src/**` | Renders the Linux screenshot baselines and uploads them. |
| [`codeql.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/codeql.yml) | pull requests, pushes to `main`, Mondays | Static analysis into the security tab. |
| [`changesets.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/changesets.yml) | pushes to `main` | Keeps the "version packages" pull request open. |
| [`release.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/release.yml) | a `v*` tag | Publishes the image and the GitHub Release. |
| [`zap.yml`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/.github/workflows/zap.yml) | pushes to `release/**`, `v*` tags, manually | The ZAP baseline scan against the Compose stack. |

### The `ci` workflow

The jobs run in parallel, each on its own runner, and a last job named `ci`
passes only when all of them did. That job is the required status check on the
`main` ruleset, so adding a job never needs a settings change. Every step is a
command you can run locally:

| Job | Steps |
|---|---|
| `checks` | `pnpm lint`, `pnpm check:boundaries`, `pnpm check:routes`, `pnpm check:validation`, `pnpm typecheck`, `pnpm audit --audit-level high` |
| `semgrep` | `semgrep scan --test .semgrep`, then Helpdock's rules over `apps`, `packages` and `scripts` ([security scanning](https://helpdock.oday-bakkour.com/docs/security-scanning/#semgrep)) |
| `unit` | `vitest run --coverage --project='!integration' --project='!@helpdock/api' --project='!@helpdock/admin'`: the `packages/*` 80 % gate |
| `admin-unit` | `pnpm --filter @helpdock/admin test:coverage`: the admin's 85 % gate |
| `api` | `pnpm --filter @helpdock/api test:coverage`: API unit and representative real-DB integration suites with the 90 % gate |
| `import-reference (source)` | Zendesk, Freshdesk and Zoho 500-ticket import/repeat/delta suites on real Postgres/Redis; one worker per source, without coverage instrumentation; Freshdesk/Zoho include a real worker kill. Pull requests run it only when the import path changes (below) |
| `integration` | `vitest run --project=integration packages/`: the packages' integration suites (Testcontainers) |
| `e2e (1/4)` … `e2e (4/4)` | `pnpm --filter @helpdock/admin e2e --shard=<n>/4`: browser tests, `en` and `ar`, against the fixture |
| `browser-api` | `pnpm build`, then `e2e:screenshots` when the baselines are committed, `e2e:api`, and `e2e:imports --workers=1` against a real API, Postgres and Redis |
| `image` | the image for `linux/amd64`, loaded not pushed, then [`scripts/compose-smoke.sh`](https://helpdock.oday-bakkour.com/docs/development/#the-whole-stack-from-your-working-copy) against it |

Pull requests select suites with [`scripts/ci-scope.ts`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/scripts/ci-scope.ts).
An admin-only edit runs admin coverage, fixture browsers and real-api browser
flows, but skips API coverage, package integration and widget browsers. An
API-only edit runs API coverage and real-api browsers, but skips admin fixture
suites. Shared packages include their transitive consumers from workspace
manifests, including test and peer dependencies. Package changes retain the
complete package coverage and integration suites. Every affected app is typechecked,
and any code change also runs the root `tsc --noEmit` over every test file and
`src/testing` helper, as `pnpm typecheck` does on `main`, so a helper that only
the full check would catch cannot slip through a pull request. API route guards run only when the API is affected. Lint, import boundaries and
the dependency audit remain repository-wide checks. Semgrep and the production
image smoke test run for any affected workspace.

Global configuration, workspace manifests, tooling, unknown paths, empty diffs
and incomplete GitHub file lists select every suite. A manifest change that only
bumps `"version"` (the Changesets release pull request) selects none. Renames
check both paths. Documentation changes and the website in `site/` (tested by pages.yml) skip
heavy jobs, except the two guides a
package test renders and compares: `docs/guides/configuration.md` selects
`@helpdock/config` and `docs/guides/webhooks.md` selects `@helpdock/jobs`, so a
hand edit to either fails on its pull request. The reference imports,
the slowest jobs at 15 to 30 minutes, run on a pull request only when it touches
the import path: `apps/api/src/imports/`, files named `import*` or `imported*`
under `apps/api/src/`, `apps/api/src/media/`, `packages/importers/`,
`packages/jobs/src/`, the database schema and migrations, or
`packages/schemas/src/import*`.

A push to `main` runs only `checks`: the `main` ruleset requires a pull request
to be up to date with `main` and green before it merges, so the merged commit
already passed its suites. The complete regression suite, including every
reference import, runs nightly at 02:23 UTC and on demand (**Actions › CI ›
Run workflow**). The workflow itself is never path-filtered: the final `ci`
check still runs, and fails if selection or any selected job fails or is cancelled.
The scope job records its decision in the run summary. CodeQL skips the
Changesets release pull request; its push to `main` is analysed after merging.

Each suite runs once. The test jobs build the workspace packages first
(`turbo run build --filter='./packages/*'`, a few seconds), because the suites
import them through their `dist/` exports. A run takes about as long as its
slowest job, roughly ten minutes, instead of the sum of every step; with the
reference imports selected, about thirty.

Install is `pnpm install --frozen-lockfile`; a `package.json` changed without
its lockfile fails there. GitHub-hosted runners ship a Docker daemon, so
Testcontainers starts its own containers and no service container is declared.
The image build uses a BuildKit cache in GitHub Actions and is never pushed —
[`release.yml`](https://helpdock.oday-bakkour.com/docs/development/#releases) is the only workflow that publishes anything.

On a failure the browser jobs upload their Playwright report as an artifact for
seven days.

### Docker Hub rate limits

Anonymous pulls from Docker Hub are rate limited per IP address, and a
GitHub-hosted runner shares its address with everybody else's. The CI jobs
pull `node` for the image build, `pgvector/pgvector:pg17` and `redis:7-alpine`
for both Testcontainers and the Compose smoke test, and Testcontainers' own
`ryuk` reaper — so a busy hour could fail a run for a reason that had nothing to
do with the code.

Every job that uses Docker therefore logs in first, **when a Docker Hub account
is configured**:

> **For the repository owner.** Add two repository secrets, `DOCKERHUB_USERNAME`
> and `DOCKERHUB_TOKEN` (a Docker Hub access token with the *Public Repo Read-only*
> scope — it never needs write). Until they exist, the login step is skipped and
> runs stay anonymous, which is also what happens for a pull request from a fork.

`secrets` is not a context an `if:` can read, on a step or on a job, so each job
turns the two secrets into one boolean in its `env:` — which *can* read them —
and the step is conditioned on that. The token itself never appears in an
expression or in a log.

Without an account the jobs do not stay at Docker Hub's mercy either: every
image that would come from Docker Hub comes through `mirror.gcr.io`, Google's
pull-through cache of it, which is not rate limited. Testcontainers reads the
prefix from `TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX` (`ryuk` included; MinIO
names its own registry and is left alone), the Dockerfile takes the base image
from its `NODE_IMAGE` argument, and the smoke test's Postgres and Redis are
pulled through the mirror and tagged under the names `docker-compose.yml` uses
before `compose up`, which then finds them in the daemon. With the secrets
present none of this happens and the jobs pull from Docker Hub as themselves.

### Renovate

Dependencies are updated by Renovate, configured in
[`renovate.json`](https://github.com/Docker-Hunterpedia/Helpdock/blob/main/renovate.json): pull requests on Monday mornings,
security advisories at any time and at a higher priority. GitHub Actions bumps
are one pull request, minor and patch dev-dependency bumps another, and the
`@opentelemetry/*` and `@nestjs/*` families are grouped because a mixed set of
either does not work. Node stays below 25 until the stack table in
ARCHITECTURE §1 says otherwise.

### Releases

[`docs/guides/release.md`](https://helpdock.oday-bakkour.com/docs/release/) is the procedure: a changeset per change,
a "version packages" pull request that Changesets keeps open on `main`, and a
`v*` tag that publishes the multi-architecture image to GHCR with a CycloneDX
SBOM attached to the GitHub Release.

### Security scanning

`codeql.yml` analyses `javascript-typescript` with the `security-extended` query
pack on every pull request, on pushes to `main`, and weekly — advisories appear
for code that has not changed. Semgrep's rules run in `ci.yml` and the ZAP
baseline scan in `zap.yml`; [security scanning](https://helpdock.oday-bakkour.com/docs/security-scanning/) covers all
of them and what to do when one fails.
