diff --git a/AGENTS.md b/AGENTS.md index 743ce437..f9624418 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,6 +132,7 @@ lists the invariant that caused the most damage when ignored. | 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 | diff --git a/src/lib/interior/AGENTS.md b/src/lib/interior/AGENTS.md new file mode 100644 index 00000000..b75c7a7c --- /dev/null +++ b/src/lib/interior/AGENTS.md @@ -0,0 +1,108 @@ +# AGENTS.md: Superstructure Interior System + +> **Parent**: `../../../AGENTS.md` (root guide: commands, Server Actions convention, domain index). + +Player-facing interior layer for the Superstructure: enter a floorplan, clean junk for +scrap, open sealed rooms, upgrade rooms, repair fixtures, and run station recipes that +produce resources (asset outputs gated off until `locker.apply` is verified live). + +## Where things live + +- **Engine (server-only)**: `src/lib/interior/` — `access.ts`, `provision.ts`, + `gates.ts`, `jobs.ts`, `sweep.ts`, `effects.ts`, `decay.ts`, `storageBridge.ts`, + `relations.ts` (`relId` normalizer; engine + UI both read relationships through it), + `types.ts` (all blueprint/runtime shapes incl. `RuntimeRoom`). +- **Tick bin**: `src/scripts/interiorTick.ts` registered as `interior-tick` in + `payload.config.ts`; external cron every minute. Completes due jobs, applies decay, + then SSE-notifies clients (`source: "interior-tick"`). Logs via `createBinLogger`. +- **Collections**: `src/collections/interior/StructureRooms.ts` (`structure-rooms`) + and `InteriorJobs.ts` (`interior-jobs`); blueprint authoring group on + `collections/logistics/Structures.ts` (`interiorEnabled`, `interiorName`, + `floorplan`/`floorplanAlt`, `interiorAccess`, `rooms[]`); runtime snapshot group + `interior { provisionedAt, lastDecayAt, rooms, floorplan, interiorAccess }` on + `collections/game/GameStructures.ts`; global knobs on GameRules `interior` + (`decayEnabled` default off, `decayMultiplier` default 1, + `assetOutputsEnabled` default off). +- **UI**: `src/components/frontend/interiors/` (`InteriorShell`, `RoomSheet`, + `InteriorGraphTab`, `JobCountdown`) behind routes + `/logistics/interiors` (list, actions.ts) and + `/logistics/structures/[id]/interior` (floorplan + sheet + graph tab, actions.ts). + Sidebar entry "Interiors" is visibility-gated by `interiorsEnabled`. +- **Launch content seed**: `src/tools/seed/seedInteriorContent.ts` (also wired into + `seedEverything`): Scrap resource, tech prereqs, labor classification, repair-kit + asset, Barracks/Workshop/Rubble-annex blueprint, Superstructure instance. + +## Job lifecycle invariants (the expensive mistakes) + +- Statuses: `active -> awaiting_collect -> collected`, plus `cancelled` / `failed`. + One job per room; `awaiting_collect` and `cancelled` keep the room's output slot + blocked until `collectInteriorJob` clears it. +- **Inputs are consumed at start**, recorded on `committedResources`. **Cancel never + touches storage**: it moves the committed inputs into the job's own output row with + status `cancelled`; the starter recovers them by collecting that job. Collect of a + cancelled job therefore refunds exactly what was spent - a cancel can't fail or + duplicate. +- **Collect prechecks before crediting** (`storageBridge.precheckDeposit` for every + output line first). If anything wouldn't fit, collect refuses and parks the job in + `awaiting_collect` ("storage full"); nothing is half-deposited and no room slot is + cleared. Assets only credit when GameRules `interior.assetOutputsEnabled` is on + (storedAssets rows), otherwise that line parks the same way. +- `completeInteriorJob` (sweep-only) flips `active -> awaiting_collect` at/after + `endsAt` and sends `notifyUser` type `interior:job-ready`; the sweep re-checks + status inside `completeInteriorJob`, so concurrent starts/cancels resolve cleanly. + +## Storage bridge = shared deposit core + +`storageBridge.ts` holds the single placement/mass implementation extracted from +`addResourceInternal`: + +- `computeDepositPlacement()` - top up stacks, first-fit grid cells, flat-list + fallback; logistics `addResourceInternal` calls it, interior credits call + `depositToStructure` which wraps the same checks plus rules + mass + event. +- `withdrawFromStructure()` removes void storage first, then grid rows. +- Storage-rule order is prohibited -> whitelist -> cap (see `lib/AGENTS.md`); the + rules/capacity live on the blueprint (`structures.type`), runtime rows on + game-structures, exactly like logistics. + +## Effects math (`effects.ts`) + +- Duration: `base / max(0.1, levelSpeed * moduleSpeed * conditionFactor)`, floor 60s. +- Output: `round(baseOutput * (1 + levelBonus + moduleBonus))`. +- Module effect keys: `interior_job_speed`, `interior_output_bonus`, and the base + module system's `production_multiplier` stack in. +- Condition factor ramps output/speed down as condition falls; a room at/below its + authored decay `effectFloor` blocks produce (and stations block when a + `blocksStation` fixture is broken - `gates.isBlockingFixtureBroken`). + +## Never-miss rules + +- Provisioning is idempotent by (structure, roomKey) and **lazily bootstraps** the + snapshot from the blueprint on first entry; it also clears a self-referential + `parentStructure` (legacy GameStructures #1 = its own compound child) before work. + After provisioning, the snapshot on game-structures is the floorplan source of + truth: later blueprint edits must not retarget live rooms. +- All relationship fields arriving from Payload can be ids or populated objects - + normalize through `relations.relId()` before comparisons or writes. +- Job durations persist on the job row (`endsAt`); clients render countdowns from + it via the `ConstructionEta` pattern and refresh on `ptf:game-tick`. +- Access: `canUserEnterInterior` (admin with `game-structures:update`, then mode + anyone/roles/users against the snapshotted access config); per-room overrides may + tighten but never widen. UI hides hotspots a member cannot enter rather than + 403-ing. +- Decay: days-since-`lastDecayAt` x room `conditionPerDay` x GameRules + multiplier, applied only while `interior.decayEnabled` is on; condition floors at + 0, fixtures break once with one `interior:fixture-broken` event each. + +## Events & notifications + +`interior:job-started`, `interior:job-cancelled`, `interior:fixture-broken`, +plus `storage:deposit` from the bridge; collect-ready users get notification type +`interior:job-ready` (muteable via the standard prefs). + +## Tests + +`tests/int/interior.int.spec.ts` (provision idempotency, access modes, gates, cancel +refund, storage-full park, sweep + notify, effects math, module bonuses, recipes, +asset flag, repair, decay incl. toggle, station blocks) and +`tests/e2e/interior.e2e.spec.ts` (enter -> open -> clean -> collect smoke; Playwright +must own :3000 so its global-setup seeds the test DB).