From b28708c590911026865189798a41618d8cfe2f2d Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Fri, 9 Oct 2026 15:46:36 -0400 Subject: [PATCH] docs(agents): split domain guidance into nested AGENTS.md files Move 19 domain sections out of the root guide into per-directory AGENTS.md files that OpenCode v2 injects lazily when an agent reads each subtree. The always-loaded root drops from 121KB to ~30KB and gains a domain index table with never-miss invariants. Original root and pre-merge sub-guides are preserved under docs/backups/pre-agents-split-20261009/ for restoration. Note: also carries the pre-existing uncommitted wiki-section edits to the root AGENTS.md, preserved verbatim in src/lib/wiki/AGENTS.md. --- AGENTS.md | 374 ++---------- .../pre-agents-split-20261009/ROOT-AGENTS.md | 537 ++++++++++++++++++ .../pre-agents-split-20261009/bot-AGENTS.md | 97 ++++ .../collections-AGENTS.md | 96 ++++ .../components-frontend-AGENTS.md | 82 +++ .../pre-agents-split-20261009/lib-AGENTS.md | 108 ++++ src/bot/AGENTS.md | 12 +- src/collections/AGENTS.md | 3 +- src/components/admin/narrative-flow/AGENTS.md | 19 + src/components/admin/tech-tree/AGENTS.md | 14 + src/components/frontend/AGENTS.md | 33 ++ src/lib/AGENTS.md | 8 + src/lib/announcements/AGENTS.md | 12 + src/lib/arma-markers/AGENTS.md | 13 + src/lib/banking/AGENTS.md | 21 + src/lib/base/AGENTS.md | 16 + src/lib/intelligence/AGENTS.md | 17 + src/lib/map/AGENTS.md | 17 + src/lib/market/AGENTS.md | 30 + src/lib/minigames/AGENTS.md | 11 + src/lib/notifications/AGENTS.md | 12 + src/lib/tours/AGENTS.md | 16 + src/lib/wiki/AGENTS.md | 26 + src/scripts/AGENTS.md | 27 + src/utils/event-log/AGENTS.md | 39 ++ 25 files changed, 1300 insertions(+), 340 deletions(-) create mode 100644 docs/backups/pre-agents-split-20261009/ROOT-AGENTS.md create mode 100644 docs/backups/pre-agents-split-20261009/bot-AGENTS.md create mode 100644 docs/backups/pre-agents-split-20261009/collections-AGENTS.md create mode 100644 docs/backups/pre-agents-split-20261009/components-frontend-AGENTS.md create mode 100644 docs/backups/pre-agents-split-20261009/lib-AGENTS.md create mode 100644 src/components/admin/narrative-flow/AGENTS.md create mode 100644 src/components/admin/tech-tree/AGENTS.md create mode 100644 src/lib/announcements/AGENTS.md create mode 100644 src/lib/arma-markers/AGENTS.md create mode 100644 src/lib/banking/AGENTS.md create mode 100644 src/lib/base/AGENTS.md create mode 100644 src/lib/intelligence/AGENTS.md create mode 100644 src/lib/map/AGENTS.md create mode 100644 src/lib/market/AGENTS.md create mode 100644 src/lib/minigames/AGENTS.md create mode 100644 src/lib/notifications/AGENTS.md create mode 100644 src/lib/tours/AGENTS.md create mode 100644 src/lib/wiki/AGENTS.md create mode 100644 src/scripts/AGENTS.md create mode 100644 src/utils/event-log/AGENTS.md diff --git a/AGENTS.md b/AGENTS.md index 976e306e..dd4d0d2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,12 @@ # AGENTS.md — Polaris Task Force -> **Sub-AGENTS.md files** (read these for domain-specific context): +> **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. > -> - `src/components/frontend/AGENTS.md` — Frontend component patterns, server/client split, Item primitive -> - `src/collections/AGENTS.md` — Payload collection map, RBAC, hooks, relationship graph -> - `src/lib/AGENTS.md` — Shared business logic, domain services, dependency graph -> - `src/utils/AGENTS.md` — Access control layers, event log, utilities -> - `src/bot/AGENTS.md` — Discord bot architecture, commands, services +> 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 @@ -114,311 +114,33 @@ Break these and you get runtime errors or silently dead code: - `src/app/(payload)/` — Payload admin panel and API routes. Auto-generated layout. - `src/app/my-route/` — example custom API route. -## Collections (Payload CMS) - -Organized by domain under `src/collections/`: - -- **users/** — Users (auth, username login), Ranks, Profiles (incl. minigame stats), Awards, Qualifications, Assignments, AssignmentTransfers, Experience, Evaluations, Roles (dynamic RBAC), UserNotifications -- **intelligence/** — Missions, MissionAttendances, Campaigns, Factions, Technologies -- **logistics/** — Assets, Resources, Vehicles, Structures (with staffing defaults), Shipments -- **banking/** — BankAccounts, BankTransactions, LedgerEntries -- **market/** — MarketListings, MarketNegotiations, MarketState (supply/demand ledger, one doc per tradeable resource/asset) -- **locker/** — LockerStorages, Loadouts -- **world/** — Maps, NarrativeEvents -- **server/** — MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents -- **game/** — GameRules (global, incl. currency display names + staff hiring flags), GameStructures, GameHardResources, GameEventLogs, GameVehicles, GameNpcs, NpcStaffing, LaborClassifications (+ shared `staffingFields.ts` factory) -- **projects/** — Projects, Labels, Releases, Sprints -- **tickets/** — Tickets, TicketVotes -- **wiki/** — WikiPages, WikiRevisions, WikiTemplates -- top-level — `Media.ts` (image uploads, used by wiki), `Shims.ts` (audience-targeted content), `Announcements.ts` (banner/modal/dialog/toast announcements) - -Access control helpers live in `src/utils/access-control/` (isRole, hasRoles). Full RBAC lives in `src/permissions/index.ts` + the `Roles` collection. Roles: `guest`, `user`, `admin`, `developer`. - -## Event Log System - -`src/collections/game/GameEventLogs.ts` — `game-event-logs` collection. - -- **Schema**: `system` (boolean, default `true` — system-generated vs GM/narrative), `timestamp`, `type` (text/indexed), `message` (human-readable), `actor` (→ users), `structure` (→ game-structures), `targetCollection` (select — pick from known collections), `targetId` (number, polymorphic ref), `data` (JSON blob), `visibility` (select `public` default | `restricted`, indexed), `requiredPermissions` (select hasMany from the permission registry; any-of gate shown only when restricted). -- **Access**: read is visibility-filtered: every logged-in user sees public events; restricted events additionally require one of their `requiredPermissions`, event-log staff (`game-event-logs:update`), superuser status, or being the actor (you always see your own events). Create: any logged-in user. Update restricted to admins/developers. Delete restricted to developers. The admin panel keeps its boolean gate (`scopedAdminPageAccess`), so event-log staff see everything there. -- **Visibility policies**: `src/utils/event-log/visibility.ts` maps event TYPES to defaults (`EVENT_VISIBILITY_POLICIES`); `emitGameEvent` stamps documents via `resolveEventVisibility(type, override)`. Restricted today: `npc:dialogue` (gated `npc-dialogues:read` / `player-flags:read`) and `flag:set` (gated `player-flags:read`). Everything else defaults public. Callers may pass `visibility` / `requiredPermissions` per emit. -- **Local API gotcha**: `payload.find` on `game-event-logs` defaults to `overrideAccess: true` and bypasses the filter. Consumers that must respect visibility pass `user` + `overrideAccess: false` (the dashboard RecentEvents query in `src/app/(frontend)/page.tsx` does this). REST consumers (`/events` page, `EventLedger`) are filtered automatically. -- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data?, visibility?, requiredPermissions? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`; stamps visibility from the policy map. -- **Types**: `EventTypes` constants in `src/utils/event-log/eventTypes.ts` — add new event categories there without touching the collection. Using these constants gives TypeScript narrowing on the `type` field. -- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`. `PlayerFlags` afterChange/afterDelete hooks emit restricted `flag:set` audit events for every flag write (admin-panel edits and dialogue effects alike). -- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`, `player-flags`. If a new collection is added that should be a valid target, add an option here. -- **Narrative events**: admins/developers can create entries manually in the Payload admin panel with `system: false` for GM-written narrative events. These are visually distinct in the UI (amber accent, book icon). - -### UI - -`EventLedger` component (`src/components/frontend/storage/EventLedger.tsx`): - -- Queries the REST API (`/api/game-event-logs`) for a given `structureId` and renders a scrollable feed. -- Accepts optional `refreshKey` prop — parent passes an incrementing counter to trigger re-fetch after mutations. -- Auto-polls every 30s for background updates. -- Shows actor name prefix ("You" for current user, username for others). -- Filter by event type via multi-select shadcn `DropdownMenuCheckboxItem`. -- Narrative events (system: false) styled with amber border + book icon. -- On re-fetch, preserves existing entries while loading to avoid flicker. - -### Adding event logging for new actions - -1. Add event type constant to `src/utils/event-log/eventTypes.ts` if it doesn't exist yet. -2. If the target collection slug isn't in the `TARGET_COLLECTIONS` array in `GameEventLogs.ts`, add it. -3. Call `emitGameEvent(payload, { type: EventTypes.xxx, message: "...", ... })` after the successful mutation in the server action. -4. `EventLedger` will pick it up automatically if it's scoped to the same `structureId`. - -### Non-structure events - -The `EventLedger` currently filters by `structure.id`. For event logs scoped to other entities (e.g., faction finance ledger), a new ledger variant would need to be created that queries by `targetCollection` + `targetId` instead. - -## Shipments & game tick - -Shipping simulation (`src/collections/logistics/Shipments.ts`, `src/scripts/`, `src/lib/shipping.ts`, `src/lib/distance.ts`): - -- **Shipment fields**: `origin`/`destination` → `game-structures`, `transportVehicle` → `game-vehicles`, `cargo[]` (relationship to resources/assets/vehicles + amount), `distance`, `fuelCost`/`fuelConsumed`, `status` (`pending`/`dispatched`/`in_transit`/`arrived`/`completed`/`cancelled`/`failed`/`stranded`), `autoReturn` checkbox, `failureReason`. -- **Game tick**: `bun run payload game-tick` — a `bin` registered on `payload.config.ts`, NOT an npm script. It processes active shipments + fuel consumption, then `process.exit(0)`. -- **Shipment lifecycle is tick-independent** (`src/lib/shipping/lifecycle.ts`): `advanceShipment(payload, shipment, now?)` derives everything from timestamps (continuous fuel burn `fuelCost x elapsedFraction` with the vehicle draining by the delta, `dispatched` -> `in_transit`, full delivery via `completeShipment` at/after ETA, `stranded` when fuel can't cover the elapsed burn) and is idempotent (fresh status re-check before crediting cargo). The game tick just sweeps all active shipments; the **shipment detail page also advances on load**, so a due shipment completes the moment anyone opens it instead of waiting for a tick. Callers must pass a depth-2 shipment doc (vehicle relation hydrated). The old `src/scripts/processShipmentTick.ts` module was folded into this lib. -- **Bin file logging**: all seven bins (`game-tick`, `market-tick`, `mission-tick`, `server-tick`, `base-tick`, `economy-tick`, `generate-mission`) tee their logs to daily files `logs//.log` (UTC) via `createBinLogger` in `src/scripts/lib/binFileLogger.ts` — in addition to the console. Writes are `appendFileSync` (bin scripts `process.exit` immediately, so async streams would truncate). A fatal error in a bin is caught, logged to the file, and exits code 1. Directory override: `BIN_LOG_DIR` env (defaults to `/logs` — inside Docker point it at a persistent volume). `logs/` is gitignored. -- **Base tick**: `bun run payload base-tick` — bin registered like the others (needs external cron). Runs `processBaseTick` (`src/lib/base/tick.ts`): pays staff salaries from the structure treasury (banking `applyTransaction` type `salary`), charges structure maintenance, flags upkeep shortages (see Base Management below). Emits `staff:salary-paid`/`staff:salary-unpaid`/`structure:maintenance-paid`/`structure:maintenance-unpaid` events. Notifies clients via the same SSE path as the other ticks (`source: "base-tick"`). -- **Economy tick**: `bun run payload economy-tick` — bin registered like the others (needs external cron; cadence hint is GameRules `economy.tickIntervalHintMinutes`). Runs `processEconomyTick` (`src/lib/economy/tick.ts`): ensures a `market-state` ledger doc exists per tradeable resource/asset (copied from GM baselines), decays `realDemand`, drifts `artificialDemand` (deterministic per period via `periodSeed` → mulberry32 rng — a cron retry within the same period recomputes the same values), recomputes `priceModifier` from the demand/supply ratio clamped to the item's band. Master gate: GameRules `economy.enabled` (default **off** — no-op when disabled). Cold-start gate: items with fewer than `coldStartObservations` completed purchases keep `priceModifier = 1`. Period idempotency: docs with `lastComputedAt >= periodStart` are skipped. Emits a batch `economy:tick` event + one `economy:price-change` event per item whose modifier moved ≥ `PRICE_CHANGE_THRESHOLD` (0.05) — target `market-state` (logic: `src/lib/economy/` incl. `events.ts`, tests: `tests/int/economy.int.spec.ts` + `tests/int/economy-events.int.spec.ts`). Nothing consumes the modifier yet (P1d: market-tick new-listing pricing). Notifies clients via the same SSE path as the other ticks (`source: "economy-tick"`). -- **Economy consumption (P1d)**: market-tick prices new NPC listings from the ledger — `price = max(1, round(baseBuyPrice × priceModifier))` (neutral 1 when no market-state doc) then `applyNpcPriceModifier` (vendor's own modifier); the old `autoPrice` ±15% randomness is **removed**. Restock quantity scales down under shortage via `scaleQuantityForShortage` (bounded to a 0.25 factor floor, never below 1). `buyListing` ingests real demand: purchases of NPC/vendor stock (`seller == null`) call `recordPurchase` (fire-and-forget, `src/lib/economy/consumption.ts` — quantity-weighted `realDemand` increment). GM tools: `resetEconomyState` server action (permission `market-state:update`, rebuilds the doc from baselines, emits `economy:reset`; per-listing "Reset economy" button gated by `canResetEconomy` on the market page) and `getReferencePrices` (modifier-applied reference price shown in `CreateListingDialog`'s tip when it differs from the resting valuation). Tests: `tests/int/economy-consumption.int.spec.ts`. Notifies clients via the same SSE path as the other ticks (`source: "economy-tick"`). -- **Mission lifecycle auto-start / auto-completion**: `bun run payload mission-tick` — bin registered like the others (needs external cron). Each tick runs two sweeps (start first, then complete) in `src/lib/intelligence/missionLifecycle.ts`: `autoStartMissions` flips `Scheduled` missions whose `classification.startDateTime` has arrived to `Active` (emitting `mission:auto-start`), skipping missions whose whole window already elapsed so they don't get a spurious start event; `autoCompleteMissions` then sets missions whose scheduled window (`startDateTime` + `estimatedDuration`, default 240 min when missing/invalid) has fully passed to `Completed` with `completedAt` stamped at the sweep time (emitting `mission:auto-complete`). Draft statuses (Concept/Planning/Ready) and terminal statuses (Completed/Cancelled) are never auto-started; only `Scheduled`/`Active` are auto-completed. Both sweeps are idempotent. Notifies clients via the same SSE path as the other ticks (tests: `tests/int/mission-lifecycle.int.spec.ts`). -- **Side-op workflow (Ready draft → Scheduled committed)**: `createFridaySideOp` creates a side op as a quiet `Ready` draft (no roll-call). The creator commits it with `markSideOpScheduled` (the "Mark as Scheduled" control on the mission page), which flips it to `Scheduled` and emits `mission:commit`. Only `Scheduled` ops post a Discord roll-call (about 3 days out) and are driven by the auto-start/auto-complete lifecycle above. The daily reminder (`readyReminders`, web notification + Discord DM, notification type `mission:ready-reminder`, label "Schedule reminder") nudges the creator to set the op to `Scheduled` while it is still Concept/Planning/Ready; the internal "ready" names are legacy and kept to avoid a migration. -- **Server presence**: `bun run payload server-tick` — bin registered like the others (needs external cron, every minute). Flips `game-servers` docs that claim `status: "online"` but whose last heartbeat (`lastSeenAt`) is older than 180s to `offline`, including online docs with no `lastSeenAt` at all; emits a `server:offline` event per flipped server (logic: `src/lib/arma-bridge/presence.ts`, test: `tests/int/server-presence.int.spec.ts`). Idempotent. Notifies clients via the same SSE path as the other ticks. -- **Arrival handling** (`src/scripts/processShipmentTick.ts`): destination storage rules are re-checked on arrival; rejected cargo bounces back to origin, shipment goes `failed`, `ShipmentFail` event logged. -- **GameRules tuning**: `proximityThreshold` and `gameTickIntervalMinutes` live on the global `game-rules` doc. -- **UI**: `src/app/(frontend)/logistics/shipments/` (list + `[id]` detail with `ShipmentActions` controls), `src/app/(frontend)/logistics/game-vehicles/` (deployed vehicle views). - -### Realtime SSE pipeline (in-memory, single-instance only) - -gameTick → POST `/api/game-tick/notify` (guarded by `x-game-tick-secret` header = `GAME_TICK_NOTIFY_SECRET` env) → in-process bus (`src/lib/realtime/bus.ts`, module-level subscriber Set) → SSE `GET /api/realtime` → `GameTickRealtime` (`src/components/frontend/realtime/`) calls `router.refresh()` and dispatches `ptf:game-tick` → consumers via `src/hooks/useGameTick.ts` (`ShipmentToasts`, `EventLedger`). **Will not work across multiple server instances.** - -- `GameTickRealtime` mounts only for logged-in users; `ShipmentToasts` only for logistics-qualified users. -- `hasLogisticsQualification(payload, user)` (`src/utils/access-control/hasLogisticsQualification.ts`) queries Profiles `progression.qualifications` for "logistics" (case-insensitive); admin/developer always pass. Used to gate logistics-only UI. - -## Storage rules (logistics) - -`Structure` collection has `allowedStorage` (per-item caps), `prohibitedStorage`, and `restrictToAllowed` (whitelist gate) under `storage`. Shared logic in `src/lib/storageRules.ts` (`checkStorageDeposit`, `isResourceProhibited`, `isResourceWhitelisted`, `getResourceStorageCap`, `storageViolationMessage`). - -- Enforcement order: **prohibited → whitelist → per-item cap**, counting grid + void storage. -- Enforced in: `structures/actions.ts` (`addResource`, `transferResource`, `placeResourceOnGrid`), `shipments/actions.ts` (`createShipment` destination check), and `processShipmentTick.ts` on arrival. -- UI: `ManageStorageDialog` caps deposits to `min(mass, allowance)` and filters non-whitelisted items; structure page shows an amber "whitelist mode" banner when `restrictToAllowed` is set. - -## Base Management (staffing & upgrades) - -Labor/staffing simulation for structures. Collections in `src/collections/game/`: `npc-staffing` (named NPC staff + labor headcount blocks on game-structures), `labor-classifications` (labor trades: name, key, `defaultUnitSalary`, `availableHeadcount`), and a shared `staffingFields.ts` factory (`createStaffingFields`) that adds `maintenanceCost` / `laborRequirements` / `staffPositions` to both GameStructures instances and Structures blueprints ("Staffing Defaults" group). A `GameStructures` beforeChange hook copies blueprint staffing defaults on create. - -- **Service lib**: `src/lib/base/` — `staffing.ts` (`hireStaff`, `fireStaff`, `setLaborHeadcount`, `assertStaffHiringEnabled` — enforces position caps, labor-vs-named-staff rules), `upgrade.ts` (`upgradeStructure` — validates + consumes stored materials, swaps structure type via `upgradesInto`), `storage.ts` (`consumeStorage`, `storedAmount`, ...), `staffingDefaults.ts`, `tick.ts` (`processBaseTick`), `types.ts`. -- **Modules (slice 3)**: blueprints declare `moduleSlots` + a `moduleOptions` catalog (name, category, effects, install materials) via `moduleFields.ts`; instances only store `installedModules` (action-managed, readOnly). `src/lib/base/modules.ts`: `installModule`/`uninstallModule` (materials consumed grid+void, no refund; operational structures only), `installedModuleEffects` aggregates `capacity_mass` (extra kg) / `production_multiplier` (output fraction boost) / `storage_slots` (grid slots metric). `effectiveMaxMass` wires the capacity bonus into the deposit/transfer/shipment checks + map route; the production tick applies the multiplier and the raised cap; `getGridSlots`/`calculateUtilization` take the bonuses. Events: `structure:module-install` / `structure:module-uninstall`. UI: `SlotsPanel` (structure detail page + map drawer). -- **Adjacency auras (slice 5)**: blueprint "Adjacency Aura" group (`auraFields.ts`: `effectType` production_multiplier|capacity_mass, `value`, `rangeMeters`) projects one effect onto operational neighbors. `src/lib/base/adjacency.ts` `auraBonusAt` (pure: operational sources only, self excluded, range in meters) is wired into the production tick (multiplier stacks with module multipliers; capacity raises the clamp) and computed from the tick's own site list with no extra queries (scoped runs fetch unscoped sources). -- **Server actions**: `src/app/(frontend)/logistics/base/actions.ts` — `upgradeStructure`, `hireStaff`, `fireStaff`, `setLaborHeadcount` (logistics-qualification gated, canonical ActionResult pattern). -- **Gate**: Game Rules globals `staffHiringEnabled` + `staffHiringDisabledMessage` disable all hiring when off. -- **Base tick**: see `base-tick` bin under Shipments & game tick. -- **UI**: `src/components/frontend/baseManagement/` (`StaffRoster`, `HireStaffDialog`, `EmploymentCard`, `UpgradeCard`) mounted on the structure detail page (`logistics/structures/[id]`). -- **Compounds (slice 4)**: game-structures `parentStructure` self-rel; children attach at placement (PlacementDialog "Compound" picker, validated: same map, hub not itself a child). Operational children pool storage into the hub via `src/lib/map/compounds.ts` (`aggregateCompoundStorage`); the map feature route folds child storage into the hub feature, force-hides child map labels, and reports `compoundChildren`; the hub ribbon reads "Compound: N buildings" and the popup gains a Compound cell. Structure detail pages show a Compound block (hub link on children; child chips on hubs). -- **Events**: `staff:hired` / `staff:terminated` / `staff:headcount-set` / `staff:salary-paid` / `staff:salary-unpaid` / `structure:maintenance-paid` / `structure:maintenance-unpaid` / `structure:upgraded` / `structure:upkeep-short`. Event target: `npc-staffing`. - -## Game Map System - -Leaflet world map at `/map` (top-level sidebar entry, whole unit views it). Full docs: `docs/map-system.md`. - -- **Collections** (`src/collections/world/`): `maps` (redesigned: `worldSizeWidth`/`worldSizeHeight` meters, `basemapMode` select `image`/`tiles`, `basemapImage` upload, `tileUrlTemplate`, zoom defaults, `isActive`, `worldMap` checkbox (opt-in "World Map Entry", default false; existing active maps backfilled true), optional `campaign` relationship, optional intel fields: `description`, `weather` freeform text (colored by keyword match on picker cards), `latitude`/`longitude` real-world reference, `easeOfAccess` select (easy/moderate/difficult), `factionControl` relationship; picker cards show weather/ease/faction stats + a truncated description), `map-roads` (name, description, map rel, surface select, `speedMultiplier`, strokeColor/strokeWeight/strokeStyle/labelVisible (tri-state: unset = auto, paved labels always, dirt/trail only at close zoom via `roadLabelShown` in style.ts, 4 m/px threshold), `points` JSON array of [x, y] meters), `map-zones` (name, description, type select water/land/territory/border/other (territory/border are informational political boundaries, other is for generic areas like named compounds; none gate placement, only water does; default fills amber 0.1 / violet 0.06 / slate 0.08), fillColor/strokeColor/fillOpacity/strokeWeight/labelVisible, polygon points JSON), `resource-nodes` (`resources` hasMany rel OPTIONAL (empty = plain marker node: placement's resourcesInRange never matches it), `icon` select from the shared set in `src/lib/map/nodeIcons.ts` (marker/droplet/trees/mountain/flag/star/skull/home/anchor/fuel; rendered on the map + picked in the authoring toolbar and admin), `position` JSON [x, y], richness, name, description). Feature collections read: any logged-in user; write: `maps:*` permissions. World Map screen eligibility (`src/lib/map/screen.ts`): `worldMap && isActive && (no campaign or campaignMode != custom)` — mission-only / side-op maps (flag off, or tied to a custom campaign) never appear on the screen but stay attachable to missions. Admin-panel visibility needs `:read` + `admin::manage` ("Map Features" permission group). -- **Coordinates**: real meters, per-map Cartesian grid, origin top-left, y runs south (Arma convention). JSON geometry for map features; `game-structures.coordinates` keeps its PostGIS point but stores meters (`validate: () => true` overrides Payload's geographic lng/lat validation; meters are not degrees). -- **Routing**: `src/lib/map/routing.ts` (pure) builds a graph from road polylines (1 m vertex epsilon; shared vertex = junction), Dijkstra weighted by `length / speedMultiplier`; origin/destination snap to the nearest vertex within 1000 m; no connected route refuses ground shipments with a clear error. Air/sea (`vehicles.transportMode`) go straight-line. Distance = geometric route length in meters; `routePath` JSON snapshot on shipments (auto-return reverses it). Speed math converts meters to km once in `calculateTransitTime`; fuel stays `meters x rate`. -- **Placement**: `src/lib/map/placement.ts` (pure: terrain point-in-polygon, resourcesInRange vs multi-resource nodes OR resource-bearing zones at the site, structuresInRange) + `placeStructure` action (`src/app/(frontend)/logistics/map/actions.ts`, hasLogisticsQualification gate, emits `structure:placed`). Map UI placement mode for logistics-qualified users (click to place, dialog with blueprint/name/faction, client pre-validation + server enforcement). Water zones block land blueprints; water blueprints need a water zone; no zones = everything allowed. -- **Construction**: `src/lib/map/construction.ts`. Construction runs on timestamps: `maybeStartConstruction(payload, siteId, now)` is called at delivery time (shipment `completeShipment`, the structures `addResource`/`transferResource` actions via `addResourceInternal`, and `placeStructure` for materialless blueprints) and, when every blueprint material is stored, consumes them via `consumeStorage`, sets `constructionStartedAt`/`constructionCompletesAt` from the blueprint's `constructionDurationMinutes` (minutes, replacing the old tick-based `constructionTime`), and flips `awaiting_materials` to `building`. The game tick's `processConstructionTick` is a sweeper only: building sites past `constructionCompletesAt` flip to `complete` + `structure:construction-complete` (idempotent). Crew speed (slice 2): blueprint `constructionCrewRequired` gates start (`no_crew` with no labor) and scales duration by staffed fraction (floor 0.25); labor-classifications `buildEfficiency` weights each worker; `setLaborHeadcount` re-prices the remaining work via `applyCrewRateChange` (`src/lib/base/constructionSpeed.ts`). Default constructionStatus on game-structures is `complete` (backward compat). ConstructionPanel on the structure detail page shows required vs delivered + a timestamp-derived progress bar; map markers interpolate progress from the timestamps. -- **UI**: `/map` is a **picker screen** (grid of eligible map cards with basemap thumbnails, linking to `/map/[id]`); the map view itself is `/map/[id]` (`MapLoader` ssr:false + `src/components/frontend/map/MapClient.tsx`, single-map props, no switcher). CRS.Simple with y-flip (latlng = [-y, x]), image (ImageOverlay) or XYZ (TileLayer) basemap, layer toggles (structures/nodes/roads/zones/shipments/ranges), structure markers as status-colored pins (emerald building icon = operational, blue hammer = building, amber package = awaiting materials, with a progress bar under construction sites), popovers linking to `/logistics/structures/[id]`, shipment markers interpolated along `routePath` from `dispatchedAt`/`estimatedArrival`, refreshed by `useGameTick`. Feature data served by `GET /api/map-features?mapId=` (view surface, logged-in). Map labels: zone names render at the polygon centroid, road names render as curved SVG textPath labels following a Catmull-Rom smoothed road line every 400 screen px (max 12/road, flipped to a reversed path when the direction would render upside down or straight down, so vertical labels read bottom-to-top; dark casing stroke for contrast), structure names render as persistent labels with cluster priority (`labelVisible` + `labelPriority` on game-structures; winner = highest `labelPriority`, then stored mass, then id; cluster radius 56 screen px, so zooming in reveals suppressed labels). Road/zone stroke + fill colors, widths, dash styles, and opacities are editable in the authoring toolbar (`strokeColor`/`strokeWeight`/`strokeStyle` on roads; `fillColor`/`strokeColor`/`fillOpacity`/`strokeWeight` on zones; hex validated by `validateHexColor` in `src/lib/map/style.ts`, empty = per-type defaults). Pure label/styling math lives in `src/lib/map/style.ts` (`metersPerPx`, `roadLabelPoints`, `polygonCentroid`, `dashArrayFor`, `roadLabelShown`, `labelScreenAngle`; roads under 600 screen px render one straight midpoint label instead of curved text, since glyphs fold on tiny wiggly paths). -- **Authoring**: edit mode on `/map` (maps:*-gated) draws roads/zones/nodes, edits existing features (popup Edit loads geometry + attributes into the authoring toolbar; Save passes the feature id and requires `maps:update`), and deletes features (server actions in the same actions.ts). Drafts get vertex editing: draggable square handles per draft vertex (drag-end snaps), right-click deletes (min 2 road / 3 zone points), cyan midpoint handles insert a vertex; clicks and drags snap within 12 screen px to feature vertices and zone/road edges (closing segments included; vertices beat edges unless the edge is 2x closer) via pure `src/lib/map/snapping.ts` (`findSnap`, `closestPointOnSegment`, `segmentMidpoints`; `AuthoringSnapLayer` + `DraftHandles` in MapClient). `POST /api/map-import` imports a GeoJSON FeatureCollection (LineString to roads, Polygon to zones, Point to nodes; [x, y] positions used directly as map meters). Mapping table in `docs/map-system.md`. -- **Coordinate grid**: per-map Arma-style grid config on the Maps collection ("Coordinate Grid" group, admin panel): `gridEnabled` master switch, `gridOriginEasting`/`gridOriginNorthing` (meters from the west/south edges to the grid zero line; vanilla terrains use 0), `gridStartEasting`/`gridStartNorthing` (label numbers on the zero line), `gridSpacingMeters` (base cell, default 1000), `gridLabelDigits` (default 2), `gridNumbersOverLines` (Tanoa style: labels on lines instead of cell-centered). Pure math in `src/lib/map/grid.ts` (`gridConfigFromMapDoc`, `gridLevelFor` (power-of-ten ladder, 10x subdivision at close zoom: 1 km/2-digit -> 100 m/3 -> 10 m/4, chosen by on-screen cell size via `GRID_MIN_CELL_PX`), `gridLinesForBounds` (viewport lines + labels in map meters), `gridRef` (6/8-digit references)). Semantics mirror CfgWorlds Grid: floor truncation, labels wrap mod 10^digits with leading zeros (negatives wrap too), levels nest exactly (1 km cell "10" contains 100 m lines "100".."109"). `armaGridRef` (missionMarkers.ts) is a thin wrapper over `gridRef` with `DEFAULT_MAP_GRID`, which reproduces the legacy output. The config rides `MapConfig.grid` from `/api/map-features`; `GridLayer.tsx` (`src/components/frontend/map/`) renders hairlines + edge labels on the world map (Map Control "Grid" toggle) and mission planning maps (header "Grid" switch); both cursor readouts show the configured reference. Migration `20261005_001212_add_map_grid_config` (hand-trimmed; the .json snapshot intentionally covers the full current schema to repair missing sidecars on the three prior hand-written migrations). -- **GameRules**: `proximityThreshold` now means meters (default 1000; migration backfilled rows still at the old default 10). Both call sites (shipments/actions.ts, structures/actions.ts transferResource) use meters. -- **Tests**: `tests/int/map-system.int.spec.ts` (routing graph/snap/refusals, cross-map refusal, ground route + path snapshot, air straight-line, proximity, terrain/range validation, placeStructure happy/water/range cases, construction tick lifecycle, permission gating, label/styling helpers + save-action styling validation). Gotcha: Payload applies select `filterOptions` server-side, so test fixtures must use `approvalStatus: "in_progress"`. - -## Mission Planning Map (Arma 3 markers) - -Optional per-mission planning layer: the mission's own map (`classification.map`) rendered on the mission page with Arma 3 map markers that belong to that mission only (never on the shared world map). - -- **Marker assets**: `bun run markers:arma` (`src/tools/arma/extractMarkers.ts`, needs the game install + `hemtt`; default game root `/mnt/LData/SteamLibrary/steamapps/common/Arma 3`, override `--game`). Scans `Dta`, `Addons` and every DLC `addons` dir (skips `@` mod folders), parses + merges `CfgMarkers` / `CfgMarkerColors` / `CfgMarkerBrushes` / `CfgMarkerClasses` with inheritance, resolves `$STR_` names via stringtables, converts icons to PNG in `public/arma/markers/` (committed, so prod needs no game files) and regenerates `src/lib/arma-markers/catalog.generated.ts` (never edit by hand). Side-color expressions resolve to Arma's default profile colors (BLUFOR 0,0.3,0.6 etc.). -- **Catalog lib** (`src/lib/arma-markers/`, pure, client-safe): `index.ts` (case-insensitive `markerTypeOf`/`markerColorOf`/`markerBrushOf`, `resolveMarkerRgba` where color `Default` = the type's own config color, `markerTypesByCategory`), `missionMarkers.ts` (marker model mirroring Arma: shape icon/rectangle/ellipse/polyline + type/color/brush/text/size/direction/alpha/points; `normalizeMarkerInput` validation; `areaOutline` (direction = degrees clockwise from north, size = half-extents like `markerSize`); `hatchSegments` for pattern brushes; `armaGridRef`; `markersToSqf` export, y flipped against world height). -- **Collection**: `mission-map-markers` (`src/collections/intelligence/MissionMapMarkers.ts`, permission group "Mission Map Markers", REST access permission-gated). Missions gained `classification.planningMapEnabled` (opt-in) and a `beforeDelete` hook that removes the mission's markers (the FK is NOT NULL, so Payload's default ON DELETE SET NULL would fail the delete). Migration `20261003_190000_add_mission_map_markers` (hand-written; matches the generated schema). -- **Rules**: read = anyone who can read the mission (user-scoped `findByID`); edit = `missions:update` or the mission's `createdBy`. Service `src/lib/intelligence/missionMap.ts`; server actions `src/app/(frontend)/intelligence/missions/mapActions.ts` (`setMissionPlanningMap`, `getMissionMapMarkers`, `saveMissionMapMarker`, `deleteMissionMapMarker`, `clearMissionMapMarkers`; events `mission:planning-map-toggle` / `mission:map-marker-*` / `mission:map-markers-clear`, target `missions`). Max 1000 markers per mission. -- **UI**: `src/components/frontend/intelligence/missionMap/` (tactical dossier section above the mission detail grid). `MissionPlanningMap` (state, debounced per-marker saves, 30s background refresh, Delete/Escape keys, SQF copy, Arma grid readout), `MissionMapCanvas` (Leaflet, basemap + roads/zones via `GET /api/map-features?mapId=&layers=base`, which skips structures/nodes/shipments), `MarkerToolPanel` (tools, type picker, colors, brush, text, scale/size, direction, opacity), `markerIcon.ts` + `iconStyle.ts` (icons render as texture MULTIPLIED by the marker color and masked by the texture alpha, exactly like Arma: white glyphs take the color, flags keep theirs). Editors see an "Enable planning map" card until it is on; non-editors see nothing until enabled. -- **Gotchas**: leaflet click/dblclick/mousedown/mouseup fire faster than React re-renders, so draft line vertices and the area drag start live in refs (state only drives the preview). URLs inside divIcon HTML must use single quotes (`url('...')`): a double quote ends the `style` attribute and the glyph silently disappears. Radix Select keeps `pointer-events: none` on `` briefly after closing (affects scripted drags right after choosing a brush). Tests: `tests/int/mission-map.int.spec.ts`, `tests/e2e/mission-planning-map.e2e.spec.ts`. - -## Personnel (NPC directory) - -- `/personnel/contacts` — NPC directory over `game-npcs` (`src/components/frontend/personnel/`: `NpcDirectory`, `NpcCard`); `/personnel/contacts/[id]` — NPC profile (faction, in-game vs generated badges, vendor listings, `NpcProfile`). -- `/personnel/statistics` — theater-wide NPC stats: faction distribution, in-game vs generated counts, vendor stall count, top 5 vendors by active auto listings. -- Sidebar entries live in `src/components/frontend/blocks/sidebarData.ts` (nav data extracted from `AppSidebar`). - -## Banking System - -`src/collections/banking/` — `bank-accounts`, `bank-transactions`, `ledger-entries`. Per-person money for a future market feature plus unit/faction treasuries. Admin group: **Banking**. - -- **BankAccounts**: `name`, `accountType` (`treasury`/`faction`/`personal`), `ownerFaction`/`ownerUser` (relationship, conditionally shown by type), `currency` (→ resources, defaults to the Game Rules main currency), `balance` (number, admin read-only — maintained by transactions), `status` (`open`/`frozen`/`closed`). Read: any logged-in user. Create/update: admin/developer. Delete: developer only. -- **BankTransactions**: `transactionNumber` (unique, auto-generated), `type` (`deposit`/`withdrawal`/`transfer`/`payment`/`fee`/`salary`/`adjustment`), `fromAccount`/`toAccount` (→ bank-accounts, optional per type), `amount`, `fee`, `memo`, `actor` (→ users), `status` (`completed`/`reversed`), `reference` (reversal), `timestamp`. Access: developer create/update/delete, any logged-in read. - - `transactionNumber` is auto-generated in a **beforeValidate hook** (`TXN--`) when empty. **Do not require callers to pass it.** Callers may pass `""` to satisfy TS on the required field — the hook treats falsy as missing. -- **LedgerEntries**: one per affected account per transaction. `account`, `transaction`, `type`, signed `amount` (positive = credit, negative = debit), `balanceAfter`, `memo`, `timestamp`. Read: any logged-in user. Create/update/delete: developer only. -- **Service lib**: `src/lib/banking/index.ts`. - - `applyTransaction(payload, { type, fromAccountId?, toAccountId?, amount, fee?, memo?, actorId? })` — single source of truth for balance math. Validates accounts exist/open/frozen + sufficient funds, creates the `bank-transactions` doc, appends ledger entries (signed), updates both balances, returns the transaction. Throws descriptive `Error`s. - - `createAccount(payload, { name, accountType, ownerFactionId?, ownerUserId? })` — creates a zeroed account in the main currency; throws if no main currency is set in Game Rules. - - `ensurePersonalAccount(payload, userId)` — finds-or-creates a personal account for a user (dedup). - - `getMainCurrencyId` / `getMainCurrencyName` — resolve the Game Rules `mainCurrency` → resource. - - `src/lib/banking/format.ts` — `formatAmount`, `currencyLabel`, `formatDate`. Takes a `CurrencyConfig` (threaded from Game Rules) — labels prefer the configured display names over the resource's `name` (e.g. "Gold") over `codeName` (e.g. "res_gold"), with pluralization. -- **Server actions**: `src/app/(frontend)/logistics/banking/actions.ts`. `createBankAccount` (regular users may only create their own personal account; treasury/faction require a manager), `ensureMyAccount`, `depositFunds`/`withdrawFunds`/`transferFunds`. Permission model: personal accounts are owner- or manager-only; **treasury/faction accounts are manager-only**. Manager = admin/developer or logistics-qualified (`hasLogisticsQualification`). Emits `finance:deposit` / `finance:withdraw` / `finance:transfer` / `bank:account-create` events. -- **UI**: `src/app/(frontend)/logistics/banking/` (overview + `[id]` detail), components in `src/components/frontend/banking/` (`BankingOverview`, `AccountCard`, `AccountDetail`, `CreateAccountDialog`, `BankTransactionDialog`, `LedgerTable`, `MyWalletCard`). Sidebar entry "Banking" under Logistics. -- **Event targets**: `bank-accounts`, `bank-transactions`, `ledger-entries` added to `GameEventLogs` `TARGET_COLLECTIONS` and `emit.ts` `targetCollection` union. Finance event types in `eventTypes.ts`. -- **Gotchas**: Payload's create TS overloads reject `undefined` on relationship/required fields — pass `null` for empty relationships and a concrete value (`""` for `transactionNumber`) or TS falls through to the draft-variant and errors `Property 'draft' is missing`. No migration has been added for these collections yet (dev uses `push: false`; run `bun run payload migrate` after schema changes). - -## Trading Marketplace - -`src/collections/market/MarketListings.ts` — `market-listings` collection. Tarkov-style flea market: users list locker items at a fixed price, buyers pay via banking, items transfer directly into the buyer's locker. Admin group: **Market**. - -- **Schema**: `asset` (→ assets), `seller` (→ users, **null for auto-generated vendor entries**), `npc` (→ game-npcs, set for auto-generated entries), `quantity`, `price` (per unit), `currency` (→ resources, defaults to main currency), `status` (`active`/`sold`/`cancelled`/`expired`), `isAutoGenerated` (checkbox), `listedAt`, `expiresAt`, `soldAt`, `buyer`. Negotiation pricing: `desiredPrice` (target during haggling, defaults to `price`) + `minPrice` (floor; when `minPrice < price` the listing is **negotiable**). -- **Access**: read/create any logged-in user; update owner or admin/developer; delete developer only. -- **Service lib**: `src/lib/market/index.ts`. - - `buyListing(payload, listing, buyer, { unitPrice?, quantity? })` — single source of truth for purchases: validates active, ensures buyer/seller personal accounts (`ensurePersonalAccount`), resolves treasury for vendor stock (`getTreasuryAccountId`), calls `applyTransaction` with type `"payment"` (`fromAccountId` buyer → `toAccountId` seller, or treasury for auto entries), credits buyer's locker, marks listing sold. Passing `unitPrice` buys at a negotiated price instead of the asking price. Passing `quantity` buys only that many units (defaults to the full `listing.quantity`): the stock is decremented and the listing stays `active` until the last unit, which marks it `sold`. `quantity` must be an integer in `[1, stock]` or `buyListing` throws "Quantity must be between 1 and {stock}.". - - `createMarketListing` flow (in server actions): validates `tradeable === true` + `isLive === true`, checks clean stock, `deductLockerQuantity` from the seller's locker, then creates the listing. - - **"Clean" stock rule**: only locker entries without attachments/skin can be sold (`isEntryClean`/`countCleanQuantity`) — listing or selling an entry with equipment would destroy the attachments. - - `creditLockerQuantity(payload, userId, assetId, quantity)` — merges stackables / fills empty grid spots; throws if no space (this is how buyers receive items and how cancelled/expired listings return stock). - - `autoPrice(asset, kind)` — base price ±15% deviation; `autoQuantity(asset)` — 1 (or 1–3 for stackables). `USER_LISTING_DURATION_MS` (30d) and `AUTO_LISTING_DURATION_MS` (7d) set `expiresAt`. - - `negotiationRange(listing)` → `{ min, desired }` (min = `minPrice ?? desired`); `isNegotiable(listing)` → `min < desired`. -- **Server actions**: `src/app/(frontend)/logistics/market/actions.ts`. `createMarketListing` (accepts optional `minPrice`; sets `desiredPrice = price`), `cancelMarketListing` (returns stock to seller), `buyMarketListing` (re-fetches listing, verifies active, delegates to `buyListing` with an optional `quantity`), plus negotiation actions `makeMarketOffer` (accepts optional `quantity`, stored on the thread and used when the deal closes) / `acceptMarketOffer` / `rejectMarketOffer` / `counterMarketOffer` / `cancelMarketOffer`. Emits `market:listing-create` / `market:listing-cancel` / `market:sale` / `market:offer*` events. -- **Negotiations**: `src/collections/market/MarketNegotiations.ts` — `market-negotiations`. One thread per listing+buyer. Fields: `listing`, `buyer`, `status` (`open`/`accepted`/`rejected`/`closed`/`cancelled`/`expired`), `amount` (per-unit price on the table), `quantity` (how many units the buyer is haggling for — set on the first offer, defaults to `1`), `proposedBy` (`buyer`/`seller`), `patience` (NPC vendor meter 0–100), `acceptedPrice`, `history[]`. Access: read/update scoped to buyer or `listing.seller` (admin/developer bypass); delete developer only. - - **Flow**: buyer `makeMarketOffer` → thread with `proposedBy: buyer`. For **player listings** the seller is notified and can accept/reject/counter. For **NPC vendor listings** (`seller == null`) the offer is auto-resolved immediately via `npcResponseToOffer` in `src/lib/market/negotiations.ts`. A party may only accept/reject/counter the _other_ side's proposal. - - **Strictly-increasing buyer offers**: the buyer's offers on a listing must keep rising — a repeat of an amount or a lower offer is rejected server-side in `makeMarketOffer`/`counterMarketOffer` (`enforceHigherBuyerOffer`, driven by `lastBuyerOfferOf` over thread history) with "Your offer must be higher than your previous offer of X." The vendor's own `movedBackward` firm-hold in `npcResponseToOffer` is a second line of defense. - - **NPC vendor pricing** (`NPC_ACCEPT` constants: `concedeRatio` 0.3, `marginRatio` 0.02, `chance` 0.85): the vendor keeps a private **stance** starting at the asking price that only moves down. Offers ≥ stance are accepted outright; offers within 2% of the stance are accepted with 85% chance (else the vendor holds firm at the stance); well-below offers draw a concession — the stance moves 30% of the gap toward the buyer but never rises past its last counter and **never drops below `minPrice`** (counters are clamped to the vendor's floor), and the vendor holds firm if the buyer offers _less_ than their previous offer (`lastCounter`/`lastBuyerOffer` from `npcStateOf`). Counter responses carry a `reason` (`firm`/`lowball`/`backward`/`stall`/`concede`) and accept responses a `reason` (`good`/`overpay`/`accept`) that drives the vendor's dialogue line. - - **NPC dialogue**: `npcDialogue(kind, amount?, asking?, rng?)` in `src/lib/market/npcDialogue.ts` (pure module — safe to import client-side) produces vendor flavour lines from per-kind variant arrays (picked at random via the `rng` argument, default `Math.random`). `resolveNpcOffer`/`finalizeNegotiation` write these into the history `note`; the chat transcript is rebuilt by `buildChatBubbles(negotiation, listing, currencyLabel)` in `src/lib/market/chatBubbles.ts` (pure — vendor greeting, buyer "How does {amount} sound?", seller lines from history; accept/closed fallback lines appended only for vendor threads with no dialogue, picked deterministically from the thread id). Bubbles render via `ChatBubbleList` (`src/components/frontend/market/ChatBubbleList.tsx`, auto-scrolls, configurable buyer/seller labels). Old threads with generic notes fall back to "How about {amount}?". - - **Patience meter (NPC vendors)**: `NPC_PATIENCE` constants (`roundCost` 12, `lowballPenalty` 25, `stallPenalty` 35, `stallRatio` 0.01, `goodOfferRelief` 9, `goodOfferRatio` 0.85, `cap` 100). Every bargaining round advances the meter on the thread: lowballs (< `minPrice`) add `roundCost + lowballPenalty`, **stalls** (offers that move up by less than `stallRatio × desired`, e.g. +$1 on a $5,000 item) add `roundCost + stallPenalty`, offers at/above `0.85 × desired` _relieve_ `goodOfferRelief`, otherwise `roundCost`. At the cap the thread closes (`status: closed`) — the buyer can only buy at the asking price. One persistent thread per listing+buyer holds the meter (NPC path reuses/reopens it, never resets); `makeMarketOffer` blocks after `accepted`/`closed`. Meter UI: `PatienceMeter` (`src/components/frontend/market/PatienceMeter.tsx`, green→amber→red) in `MakeOfferDialog` + buyer-side rows of `NegotiationPanel`. Bounds (`min`/`desired`) stay server-side — never shown to buyers. - - **Completion**: `finalizeNegotiation` (internal to actions) runs `buyListing` at the agreed `unitPrice` and the thread's `quantity`, marks the thread `accepted` with `acceptedPrice`, expires sibling open threads (`expireNegotiationsForListing` — notifies other interested buyers), notifies both parties, emits `market:offer-accept` + `market:sale`. Buying/cancelling/expiring a listing also expires its open threads. - - **UI**: `MakeOfferDialog` (buyer-facing haggle flow on `ListingCard` — loads existing thread via REST on open, shows counter/accept/withdraw actions + `NpcChat` chat for vendor listings; after a deal closes it stays visible for a 3.5s minimum window so the result and vendor line stay readable, and the refresh is deferred until that window passes so a sold listing doesn't unmount the dialog early), `NegotiationPanel` on the market page (open threads with role-aware Accept/Counter/Reject/Withdraw + recent closed chips + a **History** button opening `NegotiationHistoryDialog`, which lists all of the user's past negotiations as expandable chat rows), `Countdown` live "expires in" timer on every card. `CreateListingDialog` has a "Allow offers below the asking price" section (min price) and only lets you select locker items that are `tradeable` **and** `isLive` (disabled otherwise; "not approved for trading yet" hint when nothing qualifies). Deal-closed feedback fires a `sonner` toast (accept in `MakeOfferDialog`/`NegotiationPanel`, plus NPC auto-accept) — `` is mounted in `src/app/(frontend)/layout.tsx` via `src/components/ui/sonner.tsx`. -- **Market tick**: `bun run payload market-tick` (bin `market-tick` in `payload.config.ts`, NOT npm script). Expires overdue listings (`expireListing` — user stock returned, auto entries just close; also expires open negotiations) then tops up auto-generated entries for any tradeable+live asset with a base buy price that has no active listing. Each entry is assigned an NPC via `resolveVendorNpc`; the price is multiplied by the NPC's `vendor.priceModifier`. Auto entries get `desiredPrice = price`, `minPrice = round(price × 0.6)`. Emits `market:listing-expire` (per listing) + `market:auto-generate` (batch summary), then notifies clients via the same `/api/game-tick/notify` SSE path. -- **NPC attribution**: auto entries belong to a `game-npcs` NPC instead of a user. `src/lib/market/npcs.ts` — `resolveVendorNpc(payload, assetId)` prefers an in-game vendor NPC that `vendor.sells` the asset, falls back to any enabled vendor NPC selling it, otherwise `createGeneratedNpc` (random name/occupation, `isGenerated: true`, `isInGame: false`, set up as a vendor for that asset). `applyNpcPriceModifier(base, npc)` applies `vendor.priceModifier`. GMs create real NPCs in the admin panel and tick `isInGame` on generated placeholders to promote them. -- **UI**: `src/app/(frontend)/logistics/market/` page + `src/components/frontend/market/` (`MarketView` with search/rarity/type filters, `ListingCard` with Buy/Offer/Cancel, `CreateListingDialog`, `NegotiationPanel`, `MakeOfferDialog`, `NpcChat`, `Countdown`). Sidebar entry "Market" under Logistics. Uses `formatAmount` from `src/lib/banking/format` for prices. Auto entries show the NPC name + occupation in the "from" line (`npcLabel`), falling back to "Market vendor" for legacy entries with no NPC. -- **Event targets**: `market-listings` + `market-negotiations` added to `GameEventLogs` `TARGET_COLLECTIONS` and `emit.ts` `targetCollection` union. Market event types in `eventTypes.ts`. -- **Gotchas**: The `market-tick` bin must be run regularly (external cron) for expiry + vendor stock to update. `buyListing` credits the locker before clearing the payment — if the buyer's locker is full, the payment already moved and the purchase throws; consider escrow/refund handling in a later pass. When a seller accepts a buyer's offer, `buyListing` runs as the **buyer** (from `negotiation.buyer`), never the accepting actor. No migration added yet (dev uses `push: false`; run `bun run payload migrate` after schema changes). `bun run db push` fails with `must be owner of table spatial_ref_sys` — use Payload's migration runner instead. - -## Notifications - -`src/collections/users/UserNotifications.ts` — `user-notifications` collection. In-app notification inbox for players (market offers, deal outcomes, etc.). Admin group: **Users**. - -- **Schema**: `user` (→ users), `type` (text, e.g. `market:offer`), `title`, `message`, `link` (optional internal path), `read` (checkbox), timestamps. -- **Access**: users read/update only their own; create/delete developer only (creation happens via `notifyUser`, which uses `overrideAccess`). -- **Helper**: `notifyUser(payload, { userId, type?, title, message?, link? })` in `src/lib/notifications/index.ts` — fire-and-forget create. `notificationLabel(type)` maps types to short labels. Notification type strings: `market:offer`, `market:counter`, `market:accept`, `market:reject`, `market:withdrawn`, `market:sold`, `market:expired`. -- **UI**: `NotificationsBell` (`src/components/frontend/notifications/NotificationsBell.tsx`) mounted in `SiteHeader`. Polls `/api/user-notifications?limit=12&sort=-createdAt` (cookie auth) every 30s, shows an unread-count badge, dropdown with unread highlight + relative time, click-to-open-link, per-row mark-as-read check button on unread rows (`stopPropagation` — marks read without navigating, dropdown stays open), "Mark all read". Mark-read server actions live in `src/app/(frontend)/notifications/actions.ts` (`markNotificationsRead`, `markAllNotificationsRead`). -- **Wiring**: negotiation flows in `market/actions.ts` notify the counterparty at every step; `expireNegotiationsForListing` notifies interested buyers when a listing sells/cancels/expires. - -## Announcements - -`src/collections/Announcements.ts` — `announcements` collection (admin group: **Announcements**). Admin-authored user-facing announcements rendered in the frontend as a `banner` (strip above the content, like ImpersonationBanner), `modal` (shadcn Dialog), `dialog` (confirmation dialog, shadcn AlertDialog), or `toast` (sonner). Variants: `info`/`success`/`warning`/`error` (blue/emerald/amber/red). Fields: `title` (required), `subtitle`, `description`, up to 3 `buttons` (`{ label, href, style }`, used by dialogs/modals and inline on banners), `enabled`, `dismissible`, `activeFrom`/`activeUntil` date window, plus `targeting` (all/specific users/roles) and `paths` (include/exclude prefixes) groups copied from Shims. - -- **Evaluation is client-side** (Shims pattern): the `(frontend)` layout fetches enabled announcements (local API) and hands them to `AnnouncementHost` (`src/components/frontend/announcements/`); pure helpers in `src/lib/announcements/evaluate.ts` (`isAnnouncementActive` = enabled → time window → audience → path) decide per user/path/moment. The layout resolves the user's `roleDocs` to IDs (`userRoleDocIds`) for role targeting (the `roles` targeting field is a relationship to the dynamic Roles collection, NOT the legacy role enum). `description` is Lexical richText rendered via `RichText` (`@payloadcms/richtext-lexical/react`) wrapped in `lexical-content` on all display surfaces (legacy plain-string fallback kept). No server actions; authoring happens in the Payload admin panel. -- **Access**: create/update/delete via `announcements:create|update|delete` permissions (admin group in `src/permissions/index.ts`); read via `announcements:read`. Admin panel visibility needs `announcements:read` + `admin:announcements:manage` (central `scopedAdminPageAccess`). -- **Dismissals**: per-browser localStorage (`ptf:announcement:dismissals`, id → expiry) via `src/lib/announcements/dismissals.ts` (mirrors mission-reminder dismissals); expiry defaults to the announcement's `activeUntil` or 30 days. Non-dismissible announcements reappear on every page load while active. Overlays (modal/dialog) queue one at a time per session. -- Tests: `tests/int/announcements.int.spec.ts` (evaluate + dismissal logic, access gating, local-API roundtrip). -- Migration: `20260922_230950_add_announcements_collection` + `20260923_001209_add_announcements_role_docs_targeting` + `20260923_002422_announcements_description_richtext` (hand-written, additive; snapshot sidecars included so future drizzle diffs exclude announcements). - -## Narrative Events System - -`src/collections/world/NarrativeEvents.ts` — `narrative-events` collection. A flowchart-based narrative event editor using `@xyflow/react` (React Flow) in the Payload admin panel. - -- **Schema**: `name` (text, title), `summary` (textarea), `flowData` (JSON — React Flow nodes + edges), `triggers` (group with type select + optional condition JSON). -- **Access**: developer-only (create/update/delete/read). -- **Flow editor**: custom admin field component at `src/components/admin/narrative-flow/NarrativeFlowEditor.tsx`. Renders a React Flow canvas with a toolbar to add node types. -- **Node types** (custom React Flow nodes in `src/components/admin/narrative-flow/`): - - **NarrativeBeat** (`NarrativeBeatNode.tsx`) — blue, story exposition. One source handle (bottom) + one target handle (top). Fields: `title`, `text`. - - **Choice** (`ChoiceNode.tsx`) — amber, player decision point. One target handle (top), one source handle per option (right side). Fields: `question`, `options[]` (each with `id`, `label`). - - **Outcome** (`OutcomeNode.tsx`) — emerald, terminal result. Target handle only. Fields: `title`, `text`, `effects[]` (each with `type`, `value`). -- **Context menu**: right-click any node/edge to open a Radix context menu with a "Delete" action. Deleting a node also removes connected edges. -- **Data flow**: changes to nodes/edges sync to Payload's form state via `useField().setValue()`. Serialization uses `JSON.stringify` diffing to avoid loops. -- **Editing**: double-click or click the edit icon on a node to edit its properties via node edit dialog (modal with type-specific fields). -- **Dependencies**: `@xyflow/react` (v12), `radix-ui` (context-menu primitives), `lucide-react` (icons). -- To add a new node type, create the component + register it in the `nodeTypes` object in `NarrativeFlowEditor.tsx`. - -## Tech Tree (admin) - -`/admin/tech-tree` — visual tech tree editor over `technologies`, built on `@xyflow/react` v12 following the narrative-flow patterns. Custom admin view (root view) + a "Tech Tree" nav entry injected under the Intelligence group; the Technologies list/edit views are untouched. - -- **Schema**: `tech-categories` collection (`src/collections/intelligence/TechCategories.ts`: `name` unique, `position` number = timeline order, optional hex `color`) + `Technologies.category` relationship (FK `ON DELETE set null`, so deleting a category just unfiles its techs) + `Technologies.treePosition` group (`x`/`y` numbers; manual canvas position from dragging, empty = automatic). Permissions mirror technologies (`tech-categories:*` + `admin:tech-categories:manage`, registered in `src/permissions/index.ts`); `tech-categories` is in `DIVISION_ADMIN_QUALIFICATIONS`, so Intelligence division members get admin-panel access exactly like `technologies`. Migrations: `20260930_230747_add_tech_categories`, `20261001_000320_add_tech_tree_position`. -- **View wiring**: `payload.config.ts` `admin.components.views.techTree` (path `/tech-tree`, component `src/components/admin/tech-tree/TechTreeView.tsx`) and `admin.components.Nav` → `TechTreeNav.tsx`. Custom root views are public by default, so the view gates itself (logged-in + `technologies:read` OR Intelligence qualification). The nav replica injects the entry into the group containing `technologies` and reuses public exports (`NavWrapper`/`NavHamburger`/`DefaultNavClient` from `@payloadcms/next/client`, `groupNavItems` from `@payloadcms/ui/shared`); registered admin components must be **default exports** (importMap convention in this repo). -- **Layout** (`layout.ts`, pure): a **propagating left-to-right tree**. A technology WITH prerequisites is placed one column to the right of its parents, at their average row, so linking A -> B drops B immediately beside A and B's dependents continue further right; nothing is teleported to a distant column when its depth changes. Technologies in a category stay pinned to that category's column (the category contract); uncategorized roots fill a catalog grid whose slots come from each tech's rank among ALL uncategorized technologies (`MAX_ROWS_PER_COLUMN` = 10 rows, spilling into more columns) so promoting a tech into the tree leaves an empty slot rather than re-shuffling the grid; uncategorized dependents follow their parents inside the uncategorized zone. Collisions search rows outward from the desired row (dependents may also grow upward, and their columns are not height-capped, so a link from a full column still lands beside its parent rather than far right). Category bands are the bounding box of their members' final positions. Prerequisites placed to the RIGHT of their dependent surface as amber warnings (toolbar chip + node icon + preview panel section). -- **Edges**: AND prerequisites solid slate, OR prerequisites dashed cyan with an OR label. Connections are editable on the canvas: drag from a node's right handle onto another node (the target card OR its handle) to add it as an AND prerequisite; the drop-on-card case is resolved by an `onConnectEnd` fallback because React Flow only resolves drops onto a handle. Select an edge and press Backspace to remove the prerequisite. Duplicates, self-references, and cycles (direct or transitive) are rejected by the pure `prereqEdits.ts` helpers with an inline error in the toolbar. Lines are also manually routable: selecting an edge reveals a "+" handle at each segment's midpoint (click to add a bend), bends drag to move, and double-clicking a bend removes it (`RoutedEdge.tsx` + `edgeRoutes.ts`). Routes are stored per browser in `localStorage`; making them shared would need a persisted field on the target technology. Edges also route around technologies they are not connected to: `edgeRouting.ts` detours each segment around the node rectangles it would cross (inflated by a clearance margin) and `buildRoutePath` rounds every corner. An unrouted edge keeps its automatic out/across/in shape unless that path would cut through a node, in which case it falls back to a direct line the router can bend around. -- **Interactions**: nodes are draggable; dropping one PATCHes its `treePosition` (persisted, survives reload) and the toolbar shows an "Auto-arrange" button (technologies:update gated) that clears every manual position and restores the ordered layout. A **Save positions** button (technologies:update gated), next to Auto-arrange, commits the current on-screen position of every node to `treePosition` in one pass (matching what React Flow rendered, not just dragged/pinned cards) so the exact arrangement survives a reload; Auto-arrange then clears them. Dragging one card of a multi-selection moves and persists the whole selection (React Flow hands the full dragged set to `onNodeDragStop`), and a category band is draggable by its header (`dragHandle`), which moves every technology in that band. A **Snap: On/Off** toggle (default on, remembered per browser, 46px grid that divides `COLUMN_STEP`/`ROW_STEP`) snaps dragged cards to the grid. **Every canvas position write is one bulk request**: drags, Save positions, Auto-arrange, and freeze pins all POST `{ positions: [{ id, x, y }] }` to `/api/tech-tree/positions` (null x/y clears a pin), which `writeTreePositions` (`src/lib/tech-tree/positions.ts`) applies as a single `UPDATE ... FROM (VALUES ...)` on the `tree_position_x/y` columns (access = `technologies:update` or Intelligence membership, the collection's own update rule; batches capped at 2000). Never persist positions with a PATCH per node: firing dozens of concurrent document updates exhausted the database pool and could crash the server on Auto-arrange. Auto-arrange is optimistic (the canvas re-lays out on click, pins are restored if the save fails) and a spinner status chip plus disabled layout controls and node dragging cover the save. **Connecting does not move anything**: if the ordered layout would relocate the connected technology, the canvas pins it to its current spot (`treePosition` written in the same PATCH as the prerequisite) so the edge appears without the card jumping; the catalog grid also uses stable slots (each tech's rank among all uncategorized technologies, so a tech promoted into the tree leaves its slot empty instead of re-shuffling every other root). Pressing "Auto-arrange" clears those pins and moves everything, including the connected node, to its ordered position. Node click opens the side panel, which is a **lite editor** over the fields it shows (name, type, approval status, summary, category with inline create, prerequisites with AND/OR grouping and add/remove, research costs with resource rows and min/max durations): dirty tracking, Save/Reset, and an "Edit in full view" jump to the standard admin edit route. Final approval states stay superuser-only (`canSetFinalApproval` = `system:admin-access`), mirroring the field access. Quick-create dialog (name, type, summary, category, research durations) creates via REST; the category picker is a native input + suggestion list (existing values selectable, new values creatable inline) because Radix Popover inside the admin Dialog proved layer-unstable. New categories get `position = max + 1`. The canvas uses React Flow's `` so the grid scales with zoom (a CSS-background grid does not, and looked broken at low zoom), and `fitView` is capped at `maxZoom: 0.85`. Panel and toolbar controls carry dark tactical chrome (the admin panel's light shadcn defaults would render as white slabs on the dark surface; bare `