Stage 4: document template + per-fork clones, the env flag matrix (TEST_DATABASE_URI legacy serial bisect, TEST_DB_HARD_RESET, KEEP_TEST_DBS, VITEST_MAX_FORKS, TEST_PG_POOL_MAX), jsdom-opt-in docblocks, and the Vitest 4 returned-teardown contract.
248 lines
32 KiB
Markdown
248 lines
32 KiB
Markdown
# AGENTS.md — Polaris Task Force
|
||
|
||
> **This root guide is the always-loaded core.** Deep domain guidance lives in nested
|
||
> `AGENTS.md` files across `src/`: OpenCode injects a nested file automatically as soon as
|
||
> you read anything in its directory. If your task targets a domain from the index below
|
||
> but you have not read into that area yet, open the linked file before writing code.
|
||
>
|
||
> Area guides: `src/collections/AGENTS.md`, `src/lib/AGENTS.md`, `src/utils/AGENTS.md`,
|
||
> `src/components/frontend/AGENTS.md`, `src/bot/AGENTS.md`.
|
||
|
||
## What this is
|
||
|
||
Next.js 16 + Payload CMS 3.88.0 app for an Arma 3 unit. PostgreSQL database via `@payloadcms/db-postgres` + Drizzle. Tailwind CSS v4 (no config file — CSS-based). shadcn/ui (new-york style, `lucide` icons). Dark-themed frontend.
|
||
|
||
## Production data (read-only MCP)
|
||
|
||
This app exposes its Payload collections over MCP (`@payloadcms/plugin-mcp`). The project's `.opencode/opencode.json` connects this workspace to the production instance as `polaris-task-force-prod` (`https://arma.onyxsimple.com/api/mcp`).
|
||
|
||
**Prefer it for read-only reference data.** When you need to look at current production state (open tickets, a structure's contents, live market listings, a user's profile, and so on) reach for the MCP `find<Collection>` / `find<Global>` tools first: it is the fastest path to live prod data and needs no local setup.
|
||
|
||
- **Read-only by construction.** The key is minted by `bun run mcp:key prd` (`src/tools/cli/create-mcp-key.ts`), which enables only the `find` capability. It cannot create, update, or delete anything.
|
||
- **Tool shape.** One `find<Collection>` tool per collection (camel-cased, e.g. `findGameStructures`, `findMarketListings`), plus `find<Global>` for globals. Args accept a Payload `where` clause as a JSON string, plus `limit` (max 100), `sort`, `select`, `depth`, `page`.
|
||
- **Not authoritative for logic.** Read the repo for business rules; the MCP is a reference snapshot.
|
||
- **Not a test target, and never a reason to skip tests.**
|
||
- **Writes are unchanged.** Updates go through the normal channels (local/stg DB, server actions, Payload migrations via `bun run payload migrate`), verified by tests.
|
||
|
||
The live connection config is gitignored (`.opencode/`), which is fine for a single-developer setup.
|
||
|
||
## Package manager
|
||
|
||
**Bun** is the primary package manager (`bun.lock`; `bunfig.toml` is empty). `package.json` declares `packageManager: pnpm@9.15.4` and several scripts internally invoke pnpm (`db`, `test`, `test:e2e`) — always invoke them via `bun run <script>`, which still works; just don't edit those scripts to use bun directly without testing. `pnpm-lock.yaml` also exists.
|
||
|
||
## Essential commands
|
||
|
||
```bash
|
||
bun install # install deps
|
||
bun run dev # dev server (webpack, localhost:3000)
|
||
bun run devsafe # clears .next cache then dev
|
||
bun run build # production build (--max-old-space-size=8000, webpack)
|
||
bun run lint # BROKEN under Next 16 — see typecheck below
|
||
bun run test # runs test:int then test:e2e sequentially
|
||
bun run test:int # vitest integration tests only
|
||
bun run test:e2e # playwright e2e tests only
|
||
bun run db # drizzle-kit wrapper (e.g. bun run db migrate)
|
||
bun run generate:types # regenerates payload-types.ts
|
||
bun run generate:importmap # regenerates payload admin importMap
|
||
```
|
||
|
||
## Type checking / linting
|
||
|
||
`bun run lint` is **broken** under Next 16 — `next lint` was removed and errors out with `Invalid project directory provided, no such directory: .../lint`. Don't rely on it. The reliable typecheck is:
|
||
|
||
```bash
|
||
npx tsc --noEmit 2>&1 | grep -E "error TS" | grep -v "\.next/"
|
||
```
|
||
|
||
Known pre-existing errors (not yours, don't widen scope to fix them): `src/collections/users/Users.ts:57`, `src/tools/seed/backfillProfiles.ts:68`, `src/tools/seed/seedProfiles.ts:19` — all the same Payload profiles-create overload mismatch. Any **other** error introduced by your changes is yours.
|
||
|
||
## Test details
|
||
|
||
- **Dedicated test databases**: all tests run against databases derived from `DATABASE_URI`, never the dev database. The default mode builds them from a template: `<db>_test_template` is ensured once per schema change (`tests/test-db.ts`: ensure db, drizzle `push` with auto-accepted warnings via `tests/push-schema.ts`, analytics DDL, `seedRoles` + baseline seed, sequence repair; a broad schema-hash is cached in `.cache/testdb-template.json` and warm runs skip push/seed entirely), then vitest forks clone it into `<db>_test_w<ID>` at startup (`CREATE DATABASE ... TEMPLATE`; per-fork attach in `tests/vitest-worker-setup.ts`). Two forks never share tables, so files run sequentially-within-a-fork and in parallel across forks (pool `forks`, `isolate: false`, which is required for worker reuse and for the memoized `tests/helpers/get-test-payload.ts` boot). Teardown (returned by `tests/vitest-global.ts`; Vitest 4 removed the `globalTeardown` config) drops clones after green runs and keeps them after failures for postmortem; leftover clones from crashed runs are dropped at the next startup. E2E keeps the single serial `<db>_test`, recreated fresh from the template each run, then seeded with the shared e2e login. Environment flag matrix:
|
||
- `TEST_DATABASE_URI`: forces legacy serial mode against exactly this database (truncate-per-run, no templates/clones, `fileParallelism: false`), the documented bisect hatch for flaky specs.
|
||
- `TEST_DB_HARD_RESET=1`: ignores the template cache and rebuilds `<db>_test_template` from scratch.
|
||
- `KEEP_TEST_DBS=1`: teardown keeps worker clones even after green runs.
|
||
- `VITEST_MAX_FORKS`: fork cap (default 8).
|
||
- `TEST_PG_POOL_MAX`: internal (set by worker setup, default 8), caps the node-postgres pool per Payload boot in workers mode so N forks stay under `max_connections=100`.
|
||
- **Integration tests**: `tests/int/**/*.int.spec.ts` - Vitest, default `node` environment with component specs opting in via a `// @vitest-environment jsdom` docblock. Requires the live PostgreSQL test databases (bootstrapped automatically via `vitest-global.ts`; `vitest.setup.ts` points the process at it). Uses `dotenv/config` via `vitest.setup.ts`.
|
||
- **E2E tests**: `tests/e2e/*.e2e.spec.ts` — Playwright with a project named "vivaldi" that launches the **Vivaldi binary** (`/usr/bin/vivaldi`, headless args in `playwright.config.ts`) — not plain Chromium. Override the binary with `E2E_BROWSER_PATH` (e.g. Playwright's bundled chromium) when the installed Vivaldi crashes under automation; the default stays Vivaldi. The `webServer` config auto-starts `pnpm dev` with `DATABASE_URI` pointed at the test DB (bootstrapped by `tests/e2e/global-setup.ts`, with `reuseExistingServer: true`). `global-setup` also seeds the shared e2e login: `dev` / `Test123` (developer legacy role + a superuser Roles doc for permission-gated UI + the "J. Fraley" rank so the dashboard heading matches). E2E runs serially (`workers: 1`, one webpack dev server) with generous `timeout`/`expect` timeouts because first navigation to a route triggers a cold webpack compile. Currently: tours smoke (auto-start, dismissal, replay), frontend, operations, reservations, supply boxes, OPORD recall, session banner, tech tree. Caveat: when your own dev server is already on port 3000, `reuseExistingServer` silently reuses it and its DEV database, bypassing the test-DB wiring; free the port first for a true test-DB run.
|
||
- Run a single integration test: `bun run vitest run tests/int/api.int.spec.ts`
|
||
- Run a single e2e test: `bun run playwright test tests/e2e/frontend.e2e.spec.ts`
|
||
|
||
### Dev server & testing protocol
|
||
|
||
- If a dev server is **already running** when you want to test (port 3000 in use, or Next reports "Another next dev server is already running"), **ask the user whether you should kill the existing server and start a fresh one** before doing anything. A stale `.next/dev/devserver.lock` can also block startup — offer to clear it as part of the same question.
|
||
- If the user says **no**, do **not** start a dev server and do **not** attempt to verify via E2E or Playwright — the user will run the app and test themselves, then report back.
|
||
- Stale dev processes: killing the process is not always enough; remove `.next/dev/devserver.lock` before restarting.
|
||
- For browser/UI verification, make a reasonable attempt with Playwright. If the browser tooling is unavailable or repeatedly unreliable, stop rather than spending excessive effort on it and defer the manual UI check to the user.
|
||
- **Browser tool tab hygiene (OpenChamber)**: when driving the in-app browser, reuse a SINGLE tab. Call `browser.open` once to obtain a `tabId`, then pass that same `tabId` to every subsequent `browser.open` / `browser.snapshot` / `browser.click` / `browser.type` / `browser.capture` / `browser.inspect` call. Calling `browser.open` without a `tabId` opens a NEW tab every time and litters the panel; the tool has no close-tab action, so minimize new tabs by reusing one (re-read the tab list from a snapshot when a `tabId` goes stale, and reuse the matching existing tab rather than opening another).
|
||
- **Capture verification (OpenChamber)**: `browser.capture` returning `ok` only means a file was written, NOT that the page looks right. `read` the captured image and confirm it shows your change before reporting success. Next dev error overlays persist after the code is fixed (the devtools badge reads "stale"): reload the page, re-capture, and inspect again before concluding anything. After swapping a symbol (e.g. a lucide icon import), grep the file for the old name to catch missed usages like JSX elements.
|
||
|
||
## Agent debugging SOP (read before fixing any bug)
|
||
|
||
These rules were extracted from a real multi-failure debugging session — the full story, including every wrong turn, is in `docs/case-studies/login-return-url.md`. Follow them literally; each one exists because skipping it produced a wrong fix.
|
||
|
||
1. **Trace the real render path before writing any fix.** State in your reply: which layout wraps the failing route, what each conditional renders, and which component actually owns the navigation or mutation you're changing. If a layout conditionally replaces `{children}` (the `(frontend)` guest gate renders `<LandingPage />` instead of the page), then code inside those children — including `redirect()` calls — is **dead code for that branch** and never runs.
|
||
2. **Treat every framework API as a hypothesis.** Before calling a header, hook, or helper, confirm it exists and returns what you expect — against the running app or current docs. An observed default value (e.g. `?next=%2F` when you expected `%2Fflappy`) means the data source was **empty** and your fallback leaked through — not that the data got mangled.
|
||
3. **Two failed fixes = your mental model is wrong.** Do not add a third fallback layer on top of a failing approach. Stop editing, re-read the flow, find the wrong assumption.
|
||
4. **Ask "which component actually knows this fact?"** The current URL is known client-side (`usePathname()`), not in server layouts. Attach data where it is known, at the point the navigation happens — not where it is merely convenient to compute.
|
||
5. **Match producer and consumer.** If you emit a query param (`next`), confirm the consumer reads that exact name (`returnTo`). Mismatches fail silently.
|
||
6. **Verify end-to-end before reporting done.** curl the failing route as a guest, follow the redirect, hit the API, check the authed route (a copy-pasteable matrix is in the case study). "Should work" is not verification.
|
||
7. **Restate before acting.** For non-trivial changes, output: assumptions → plan → verification command. Then implement.
|
||
|
||
## Next.js 16 hard rules
|
||
|
||
Break these and you get runtime errors or silently dead code:
|
||
|
||
- **`searchParams` and `params` props are Promises** in pages/layouts. `await` them before any property access. Error if violated: ``Route used `searchParams.x`. `searchParams` is a Promise and must be unwrapped with `await` or `React.use()```.
|
||
- **Server components (layouts/pages) cannot mutate cookies.** `cookies()` from `next/headers` is read-only there; calling `.set()` throws `Cookies can only be modified in a Server Action or Route Handler`. Writing cookies is only legal in Server Actions and Route Handlers.
|
||
- **`headers.get("x-invoke-path")` does not reliably contain the current pathname** in layouts. Never build redirect logic on it. Reliable sources of the current path: `usePathname()` (client components) and the request object (middleware / Route Handlers).
|
||
- **`redirect()` narrows poorly across control flow.** After an `if (!user) redirect(...)` early exit, TypeScript may still see `user` as nullable when the narrowing crosses a closure boundary — keep an explicit truthy branch around later `user` usage.
|
||
- **Sanitize user-controllable redirect targets** (open-redirect guard): accept only values starting with `/` and reject `//` (protocol-relative URLs). Working example: `safeReturnTo` in `src/app/login/page.tsx`.
|
||
|
||
## Generated files — never edit manually
|
||
|
||
- `src/payload-types.ts` — regenerated by `bun run generate:types`
|
||
- `src/payload-generated-schema.ts` — regenerated by Payload db-schema generation
|
||
- `src/app/(payload)/admin/importMap.js` — regenerated by `bun run generate:importmap`
|
||
- `src/app/(payload)/layout.tsx` — auto-generated by Payload
|
||
|
||
## Path aliases
|
||
|
||
- `@/*` → `./src/*`
|
||
- `@payload-config` → `./src/payload.config.ts`
|
||
|
||
## App structure
|
||
|
||
- `src/app/(frontend)/` — public-facing pages (dashboard, logistics, home). Layout has sidebar + auth check (guests get `LandingPage`, no shell).
|
||
- `src/app/login/` — standalone login route, intentionally OUTSIDE the gated `(frontend)` group. Own dark `<html>` layout that reuses `(frontend)/styles.css`.
|
||
- `src/app/(payload)/` — Payload admin panel and API routes. Auto-generated layout.
|
||
- `src/app/my-route/` — example custom API route.
|
||
|
||
## Domain guide index
|
||
|
||
Nested `AGENTS.md` files load automatically when you read their subtree. If your task does
|
||
not touch an area's directories, read the linked file first; the "never-miss rule" column
|
||
lists the invariant that caused the most damage when ignored.
|
||
|
||
| Domain | Deep guidance | Never-miss rule |
|
||
|---|---|---|
|
||
| Collections map & relationships | `src/collections/AGENTS.md` | Hooks with side effects are listed there; field-level access silently strips on update |
|
||
| Event log system | `src/utils/event-log/AGENTS.md` | Local `payload.find` bypasses visibility filtering unless you pass `user` + `overrideAccess: false` |
|
||
| Shipments, game tick, SSE | `src/scripts/AGENTS.md` | Ticks are `payload <bin>` bins, not npm scripts; lifecycle is timestamp-driven (tick = sweeper); SSE bus is single-instance only |
|
||
| Storage rules | `src/lib/AGENTS.md` | Enforcement order prohibited → whitelist → cap; keep all 3 call sites in sync |
|
||
| Base management (staffing/upgrades/modules) | `src/lib/base/AGENTS.md` | Hiring gated by GameRules `staffHiringEnabled`; staffing fields come from the shared `staffingFields.ts` factory |
|
||
| Game map system | `src/lib/map/AGENTS.md` | Coordinates are meters, not degrees; water zones gate placement; `docs/map-system.md` predates the grid work |
|
||
| Mission planning map (Arma markers) | `src/lib/arma-markers/AGENTS.md` | Markers are mission-scoped; the Missions `beforeDelete` hook removes them (FK is NOT NULL) |
|
||
| Banking | `src/lib/banking/AGENTS.md` | `applyTransaction()` is the only balance-mutating path |
|
||
| Contributions & XP | `src/lib/contributions/AGENTS.md` | The service layer is the only writer of the ledger and the profile bucket; queued marker XP grants only when the mission completes |
|
||
| Marketplace & NPC negotiation | `src/lib/market/AGENTS.md` | Only "clean" locker stock can be listed; `buyListing()` is the single purchase path |
|
||
| Superstructure interiors (rooms/jobs/stations) | `src/lib/interior/AGENTS.md` | Cancel never touches storage (refund flows through the job's collectable output); collect prechecks deposits and parks on full storage |
|
||
| Notifications | `src/lib/notifications/AGENTS.md` | `notifyUser()` is fire-and-forget via `overrideAccess` |
|
||
| Announcements | `src/lib/announcements/AGENTS.md` | Client-side evaluation (Shims pattern); role targeting uses Roles docs, not the legacy enum |
|
||
| Narrative events editor | `src/components/admin/narrative-flow/AGENTS.md` | Flow data syncs to the Payload form via `useField().setValue()` with JSON diffing |
|
||
| Tech tree (admin) | `src/components/admin/tech-tree/AGENTS.md` | Positions go through one bulk POST; never PATCH per node (pool exhaustion) |
|
||
| Wiki | `src/lib/wiki/AGENTS.md` | Service layer runs with `overrideAccess` and emits no events; the actions layer emits |
|
||
| Training minigames | `src/lib/minigames/AGENTS.md` | Leaderboards match by user id; presence channel strings unchanged despite the route move |
|
||
| Mission role sign-ups | `src/lib/intelligence/AGENTS.md` | Queue is stateless FCFS recomputed from signup order + current RSVP |
|
||
| Guided tours | `src/lib/tours/AGENTS.md` | Dismissals are per-browser localStorage; the tour overlay blocks clicks |
|
||
| Discord bot | `src/bot/AGENTS.md` | Read `docs/bot/context.md` + `docs/bot/design.md` before touching bot code |
|
||
| Personnel directory | `src/components/frontend/AGENTS.md` | Sidebar nav data lives in `blocks/sidebarData.ts` |
|
||
|
||
## Auth
|
||
|
||
Username-based login (no email login). Users log in via Payload admin with `username` only.
|
||
|
||
- `src/app/(frontend)/layout.tsx` is the gate: guests render `LandingPage` (no app shell); authed users get sidebar + `GameTickRealtime`. Because the gate replaces `{children}` for guests, page-level `if (!user) redirect(...)` blocks under `(frontend)` are **unreachable dead code for guests** — they only serve as type-guards for the authed render path.
|
||
- `/login` (`src/app/login/page.tsx` + `src/components/frontend/auth/LoginForm.tsx`) POSTs `{ username, password }` to `/api/users/login`, then `router.push(returnTo ?? "/")` + `router.refresh()`.
|
||
- **Return-URL flow**: the `LandingPage` login CTA is `LoginLink` (`src/components/frontend/auth/LoginLink.tsx` — a client component using `usePathname()`), which links to `/login?returnTo=<current path>`. The login page awaits `searchParams`, sanitizes `returnTo` via `safeReturnTo` (must start with `/`, must not start with `//` — open-redirect guard), and passes it to `LoginForm`. Already-authed users hitting `/login?returnTo=X` are redirected straight to `X`. The path is attached client-side because server components cannot reliably know the current path (see "Next.js 16 hard rules"). Full design story: `docs/case-studies/login-return-url.md`.
|
||
- Logout lives in `NavUser` (sidebar) → `/api/users/logout`.
|
||
- Tip: a corrupted `payload-token` cookie causes an infinite login loop (`Unexpected end of JSON input` on `/api/users/me`) — clear cookies/use incognito. Dev user `dev` / `Test123`.
|
||
- **Admin panel access is two separate gates, do not collapse them**: (1) panel ENTRY is the Users collection `access.admin` (`src/collections/users/Users.ts`) and uses `canAccessAdminPanel` (superuser OR any `admin:<slug>:manage`); (2) per-page sidebar visibility is `requireAdminPageAccess` (applied centrally in `payload.config.ts`), requiring BOTH `<slug>:read` AND `admin:<slug>:manage` per collection.
|
||
- **Permission tiers**: `system:admin-access` (registry label "Superuser Tier (user management, notification oversight, final approval states)") is the functional superuser tier: final approval states (`approvalStatusFieldAccess` in `src/utils/access-control/divisionAccess.ts`, wired to the `approvalStatus` field on Assets/Resources/Vehicles/Technologies), the Users admin page, and read-all notifications. Only the built-in `admin` role and superuser roles hold it. NEVER grant it to division roles; they get panel access through `admin:<slug>:manage`. The dev DB once had it hand-granted to Logistics/Intelligence Officer, which silently made officers approval-superusers.
|
||
- **Impersonation**: `/api/impersonation/start` (POST `{ userId }`, operator must be a DYNAMIC superuser: `roleDocs` → Roles collection with `isSuperuser: true`; the dev user's legacy `role: developer` does NOT pass and gets 403). Swaps `payload-token` for a JWT signed as the target (a fresh session `sid` is added to the target's `sessions` first, or `auth()` returns null) and stashes the original token in the `ptf-impersonation-original` cookie. Stop via `/api/impersonation/stop`.
|
||
|
||
## Database
|
||
|
||
PostgreSQL via `@payloadcms/db-postgres`. Schema defined in `src/payload-generated-schema.ts`. Migrations in `src/migrations/` (timestamp-named .ts + .json pairs, registered in `migrations/index.ts`). Drizzle config reads `DATABASE_URI` from env.
|
||
|
||
In development, `postgresAdapter` uses `push: false` — run `bun run payload migrate` after schema changes to apply them locally. The repo also ships a wrapper, `bun run migrate` (`src/scripts/run-migrations.ts`), which adds env selection (dev/stg/prd), `--status`, and a dev-only `--fresh`.
|
||
|
||
**Always name your migrations**: create them with `bun run payload migrate:create <name>` (snake_case, e.g. `migrate:create add_evaluation_reminders_field`), never bare `migrate:create`. Unnamed migrations get timestamp-only filenames (`20260905_213824.ts`) that say nothing about what they do — several older migrations suffer from this and it makes the migration history and rollback auditing (data-loss review of `DROP COLUMN`/`DROP TABLE` steps) much harder than it needs to be. Named example: `20260906_050900_add_evaluation_reminders_field.ts`.
|
||
|
||
## Code style
|
||
|
||
- **Prettier**: double quotes, trailing commas (all), 100 char print width, semicolons.
|
||
- **ESLint**: `next/core-web-vitals` + `next/typescript`. `@typescript-eslint/no-unused-vars` warns (prefix unused with `_`).
|
||
- **Tailwind v4**: no `tailwind.config` — configured via `@tailwindcss/postcss` in `postcss.config.mjs` and CSS imports. Use `cn()` from `@/lib/utils` for class merging.
|
||
- **No em-dashes in final outputs**: never emit em-dashes (`—`, `–`) in anything you produce as a final deliverable: chat replies, commit messages, PR descriptions, docs, comments, UI copy. Replace them with a comma, semicolon, colon, or parenthetical, or split into two sentences. (Earlier bullets in this section predate the rule; new writing must comply.)
|
||
|
||
### Conventional Commit prefixes
|
||
|
||
- `docs` is for documentation **files** only: changes confined to `.md` files (AGENTS.md, README.md, DEPLOYMENT.md, `docs/`). Never use `docs` for edits to source files (`.ts`/`.tsx`), even when the edit is copy-only.
|
||
- User-facing string/copy changes inside source files (UI text, labels, hints) use `chore(<scope>)` when they change no behavior. If the edit adds or alters behavior (new UI, changed flow, changed logic), use `feat` or `fix` as usual.
|
||
- Examples: `docs: restrict release version bumps and tags to main deploys` (changed AGENTS.md/README.md/DEPLOYMENT.md only) is a correct `docs` commit; `chore(opord): rename veteran tier detail to extended order` is the right form for a UI-string tweak in `OpordArena.tsx` (that commit shipped as `docs(opord)` before this rule existed; do not rewrite the pushed history).
|
||
- Trivial non-functional source edits that are not user-facing copy (formatting, comment fixes, config touches) also use `chore` (or `style` for pure formatting).
|
||
|
||
## UI components
|
||
|
||
shadcn/ui components live in `src/components/ui/`. Use `bunx shadcn@latest add <component>` to add new ones. Frontend components in `src/components/frontend/`. Payload admin custom components referenced in `payload.config.ts` under `admin.components`.
|
||
|
||
**Rule**: always prefer shadcn/ui components (Dialog, Button, Input, Textarea, Select, etc.) over raw HTML elements or custom-built alternatives. Only build new components when no existing shadcn component fits the need. Do not override shadcn's default dark theme classes with custom `bg-*` `border-*` overrides — the admin panel's theme handles styling.
|
||
|
||
### Tactical "dossier" style (Battlefield-style UI)
|
||
|
||
An approved militaristic/intel-interface style for feature surfaces (large cards, section
|
||
headers, showcase surfaces). Full recipe + reference implementation:
|
||
`src/components/frontend/AGENTS.md`. **Protocol (MANDATORY)**: whenever creating a component
|
||
or refactoring its styling, ask the user once whether they want the dossier style; no answer
|
||
means stick with shadcn + the site's dark theme conventions. Never apply it unasked, and
|
||
never to dense data UI, tables, forms, dialogs, buttons, or shadcn-styled surfaces.
|
||
|
||
## Environment
|
||
|
||
- `.env` — local dev (PostgreSQL connection string + PAYLOAD_SECRET)
|
||
- `.env.example` — template. `DATABASE_URI` line still shows MongoDB (outdated — trust `.env.stg` for the real Postgres format), but `APP_URL` + `GAME_TICK_NOTIFY_SECRET` are current and required by the game tick.
|
||
- `.env.stg` — test/staging database
|
||
- `test.env` — NODE_OPTIONS for playwright (loaded by playwright config)
|
||
|
||
## Deploy
|
||
|
||
`bun run deploy` bumps the patch version (via `bun pm version patch`) and runs the production build. Push the resulting version commit to deploy through Coolify; the legacy `build/deploy.sh` path is no longer used.
|
||
|
||
**Volumes**: prod containers mount persistent volumes for `/app/media` (uploads) and `/app/public/tiles` (gitignored map tile pyramids, uploaded to the server by hand). Both dirs are created in the image; see DEPLOYMENT.md Sections 4 and 8.
|
||
|
||
**Pre-deploy dash gate**: before any production build, release version bump, or deploy, run the `dash-sanitize` skill (`/home/jason/.agents/skills/dash-sanitize/SKILL.md`) and show its verification output (re-scan classification + filtered tsc) before proceeding. A dirty user-facing dash scan pauses the release; a clean re-scan on an already-swept tree takes seconds and should still be run rather than assumed.
|
||
|
||
**Version bumps and release tags: `main` deploys only**: whenever a `/git` or `/git-master` workflow lands work on `main` (or a deploy is being cut), bump the version with `bun pm version patch --message "v%s - <descriptor>"` and push it together with the work. `<descriptor>` is a short comma-separated summary of what the release ships (derived from the commits just created), e.g. `v0.2.4 - add voicelines, update git rules` (never a bare version number). The command itself creates the `vX.Y.Z` version commit **and** a local git tag. `push.followTags` is set in this repo, so a plain `git push` automatically carries the annotated release tag with the commits, but never use a bare `git push --tags`, which sends only tags and not the branch. **Order that makes deploys readable**: commit the work, then commit the changelog entry for the range, then cut the release (version bump + tag) LAST via `bun pm version`, and push last. The version-bump commit is the pushed tip, so the Coolify deploy list shows the release descriptor rather than `docs: add vX.Y.Z changelog entry`. Because the changelog commit comes before the bump, the new tag does not exist yet, so generate the entry with explicit tags (`/changelog <prevTag> <nextVersion> --save`) or write it by hand (see `CHANGELOG.md`); `/changelog --save` with no arguments resolves the two most recent tags and can only run after the bump, which would place the changelog commit on top. **Feature branches must never bump versions or push release tags**: parallel branches bumping the same semver line desync `package.json` from the tags that actually deploy, and at merge time the version history no longer matches what shipped. Release tags exist solely to mark `main` deploys. The deployed site's version overlay reads `package.json`'s `version` (Coolify builds have no git metadata, so the displayed version is `<semver>+<commit sha>`), and an unbumped semver means every deploy shows the same `0.2.0`-style number even though the commit-hash suffix changes. Skipping the bump on a `main` deploy (or pushing the deploy commit without its tag) makes releases indistinguishable and breaks version history.
|
||
|
||
## Gotchas
|
||
|
||
- Next.js 16 framework traps (each one caused a real failed fix — see "Next.js 16 hard rules" above): `searchParams`/`params` are Promises and must be awaited; `cookies().set()` throws outside Server Actions/Route Handlers; `x-invoke-path` does not carry the real pathname in layouts.
|
||
- `.env.example` shows MongoDB URI but the app uses PostgreSQL — trust `DATABASE_URI` format in `.env.stg` as the real reference.
|
||
- `bun run build` passes `--max-old-space-size=8000` — the build is memory-intensive.
|
||
- The `devturbo` script uses Turbopack; `dev` and `devsafe` use webpack. These are different bundlers with different behavior.
|
||
- Playwright tests auto-start the dev server — make sure port 3000 is free before running e2e.
|
||
- Payload admin layout and importMap are auto-generated — do not edit by hand.
|
||
- `.npmrc` sets `legacy-peer-deps=true` for dependency resolution compatibility.
|
||
- `bun run db push` fails with `must be owner of table spatial_ref_sys` (a PostGIS table owned by the DB superuser) — drizzle-kit push does a full-schema diff and trips on it. Workaround: apply the needed `ALTER TABLE` directly (via node + `pg` reading `DATABASE_URI` from `.env`) or use Payload's migration runner (`bun run payload migrate`).
|
||
- **Payload 3 field-level access never rejects an update request**: when a field's `access` fn returns `false`, Payload silently deletes that field from the incoming data (`node_modules/payload/dist/fields/hooks/beforeValidate/promise.js`) and the save SUCCEEDS with the previous value. No 403, "Updated successfully." toast, other fields still save. It is enforcement without feedback; if you need a loud rejection or hidden dropdown options, that requires a collection `beforeChange` hook or a custom admin field component.
|
||
- **Admin edit views throw `54023 cannot pass more than 100 arguments` once the unit approaches 100 collections**: `payload_locked_documents_rels` gains one FK column per collection and Drizzle hydrates the lock's polymorphic relationship with a single `json_build_array(...)`, which Postgres caps at 100 arguments. `drizzle-orm@0.45.2` is bun-patched (`patches/drizzle-orm@0.45.2.patch`) to chunk that call into 100-argument groups joined with `::jsonb ||`; keep the patch (and its `patchedDependencies` entry) when upgrading drizzle, and `tests/int/locked-documents-query.int.spec.ts` fails loudly if it is missing.
|
||
- **Admin-panel-visible access bugs that contradict passing API tests**: check the actual role permission rows in the DB first, then the field-strip semantics above. The dev DB once had `system:admin-access` hand-granted to division roles (tests build clean roles, so tests pass while the panel misbehaves). The 30s `loadUserPermissions` cache is per-user-id and safe, but remember it exists when editing role data.
|
||
- PATCHing a document that is open in someone's admin edit tab returns **423 Locked** (Payload document locks). Test with a different document or wait for the lock to clear.
|
||
- For replaying admin-panel requests from the terminal: `/api/access` returns the caller's resolved permission map (collection `read` results are either a bare boolean like `true` or `{ permission, where }`; handle both shapes), and an officer-grade JWT can be crafted exactly like the impersonation route does (add a session `sid` to the target user, then `jwtSign` with `getFieldsToSign`).
|
||
|
||
## Server Actions convention
|
||
|
||
Every `actions.ts` file follows the same pattern (10+ files use it):
|
||
|
||
1. `"use server"` directive at top
|
||
2. `import config from "@payload-config"` + `const payload = await getPayload({ config })`
|
||
3. Local `authenticate()` helper — dynamic import of `next/headers`, calls `payload.auth()` and `headers()`
|
||
4. Return type `ActionResult<T>`: `{ success: boolean; error?: string; data?: T }`
|
||
5. Permission check: `const { user } = await authenticate()` then `await hasPermission(payload, user, "domain:action")`
|
||
6. Mutation via `payload.create` / `payload.update` / `payload.delete`
|
||
7. Event emission: `await emitGameEvent(payload, { type: EventTypes.xxx, message, ... })`
|
||
8. Error handling: `catch (e) { return { success: false, error: e instanceof Error ? e.message : "Unknown error" } }`
|
||
|
||
The `authenticate()` function is **duplicated in every file** — not extracted to a shared helper. If you add a new server action, copy the pattern from an existing one (e.g., `src/app/(frontend)/logistics/banking/actions.ts`). Do NOT attempt to extract it to a shared helper unless the entire codebase migrates at once.
|