diff --git a/src/app/(frontend)/page.tsx b/src/app/(frontend)/page.tsx index 943c2394..5b959943 100644 --- a/src/app/(frontend)/page.tsx +++ b/src/app/(frontend)/page.tsx @@ -6,6 +6,7 @@ import type { Assignment, Campaign, GameStructure, Map, Media, Rank, User } from import { resolveLevel } from "@/utils/xp/resolveLevel"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { canViewIntelligence } from "@/utils/access-control/canViewIntelligence"; +import { excludeRoutineEventsWhere } from "@/utils/event-log/routine"; import { getCurrencyConfig } from "@/lib/banking"; import { CLOSING_STATUSES, NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta"; import { ProfileSummary } from "@/components/frontend/dashboard/ProfileSummary"; @@ -162,9 +163,11 @@ export default async function HomePage() { // Fetch recent events. Runs as the viewer with access control applied so // restricted events (dialogue effects, flag changes) stay hidden from - // members who lack the required permissions. + // members who lack the required permissions. Routine tick summaries are + // excluded so they cannot crowd real events out of the eight slots. const eventsRes = await payload.find({ collection: "game-event-logs", + where: excludeRoutineEventsWhere(), sort: "-timestamp", limit: 8, depth: 1, diff --git a/src/components/frontend/events/EventLogTable.tsx b/src/components/frontend/events/EventLogTable.tsx index 40bfc7ef..bf19dc02 100644 --- a/src/components/frontend/events/EventLogTable.tsx +++ b/src/components/frontend/events/EventLogTable.tsx @@ -1,6 +1,7 @@ "use client"; import * as React from "react"; +import type { Where } from "payload"; import { ChevronLeft, ChevronRight, Lock, RotateCcw, Search } from "lucide-react"; import { Badge } from "@/components/ui/badge"; @@ -15,6 +16,7 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { Label } from "@/components/ui/label"; import { Select, SelectContent, @@ -22,6 +24,7 @@ import { SelectTrigger, SelectValue, } from "@/components/ui/select"; +import { Switch } from "@/components/ui/switch"; import { Table, TableBody, @@ -32,6 +35,7 @@ import { } from "@/components/ui/table"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { formatType } from "@/utils/event-log/formatType"; +import { excludeRoutineEventsWhere, isRoutineEventType } from "@/utils/event-log/routine"; import { cn } from "@/lib/utils"; // Local label map mirroring GameEventLogs TARGET_COLLECTIONS (the collection @@ -147,6 +151,7 @@ export default function EventLogTable() { const [selectedTypes, setSelectedTypes] = React.useState([]); const [targetCollection, setTargetCollection] = React.useState("all"); const [source, setSource] = React.useState("all"); + const [showRoutine, setShowRoutine] = React.useState(false); const [dateFrom, setDateFrom] = React.useState(""); const [dateTo, setDateTo] = React.useState(""); const [sortDir, setSortDir] = React.useState("desc"); @@ -168,13 +173,24 @@ export default function EventLogTable() { // Any filter change resets to page 1. React.useEffect(() => { setPage(1); - }, [search, selectedTypes, targetCollection, source, dateFrom, dateTo, sortDir, pageSize]); + }, [ + search, + selectedTypes, + targetCollection, + source, + showRoutine, + dateFrom, + dateTo, + sortDir, + pageSize, + ]); const hasActiveFilters = search !== "" || selectedTypes.length > 0 || targetCollection !== "all" || source !== "all" || + showRoutine || dateFrom !== "" || dateTo !== ""; @@ -183,6 +199,7 @@ export default function EventLogTable() { setSelectedTypes([]); setTargetCollection("all"); setSource("all"); + setShowRoutine(false); setDateFrom(""); setDateTo(""); }, []); @@ -190,7 +207,7 @@ export default function EventLogTable() { React.useEffect(() => { const controller = new AbortController(); - const conditions: Record[] = []; + const conditions: Where[] = []; if (search) { conditions.push({ or: [{ message: { like: search } }, { type: { like: search } }] }); } @@ -203,6 +220,9 @@ export default function EventLogTable() { if (source !== "all") { conditions.push({ system: { equals: source === "system" } }); } + if (!showRoutine) { + conditions.push(excludeRoutineEventsWhere()); + } if (dateFrom) { conditions.push({ timestamp: { greater_than_equal: `${dateFrom}T00:00:00.000Z` } }); } @@ -250,9 +270,23 @@ export default function EventLogTable() { void load(); return () => controller.abort(); - }, [search, selectedTypes, targetCollection, source, dateFrom, dateTo, sortDir, page, pageSize]); + }, [ + search, + selectedTypes, + targetCollection, + source, + showRoutine, + dateFrom, + dateTo, + sortDir, + page, + pageSize, + ]); const toggleType = (value: string) => { + // Selecting a routine type (e.g. "Game Tick") would otherwise match nothing + // while the routine toggle is off. + if (isRoutineEventType(value)) setShowRoutine(true); setSelectedTypes((prev) => prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value], ); @@ -334,6 +368,19 @@ export default function EventLogTable() { + +
No events match the current filters. + {!showRoutine && " Routine tick events are hidden."} ) : ( diff --git a/src/lib/economy/events.ts b/src/lib/economy/events.ts index a88822d9..61d22098 100644 --- a/src/lib/economy/events.ts +++ b/src/lib/economy/events.ts @@ -12,19 +12,21 @@ import type { TickSummary } from "./tick"; type PayloadType = Awaited>; -export async function emitEconomyEvents( - payload: PayloadType, - result: TickSummary, -): Promise { - await emitGameEvent(payload, { - type: EventTypes.EconomyTick, - message: `Economy tick processed ${result.processed} item(s) with ${result.priceChanges.length} price change(s)${result.errors > 0 ? ` and ${result.errors} error(s)` : ""}.`, - data: { - processed: result.processed, - priceChangeCount: result.priceChanges.length, - errors: result.errors, - }, - }); +export async function emitEconomyEvents(payload: PayloadType, result: TickSummary): Promise { + // Repeated runs inside the same period process nothing; skip the summary so + // the event log only records ticks that actually advanced the ledger. Errors + // are still worth surfacing. + if (result.processed > 0 || result.errors > 0) { + await emitGameEvent(payload, { + type: EventTypes.EconomyTick, + message: `Economy tick processed ${result.processed} item(s) with ${result.priceChanges.length} price change(s)${result.errors > 0 ? ` and ${result.errors} error(s)` : ""}.`, + data: { + processed: result.processed, + priceChangeCount: result.priceChanges.length, + errors: result.errors, + }, + }); + } for (const change of result.priceChanges) { await emitGameEvent(payload, { diff --git a/src/scripts/AGENTS.md b/src/scripts/AGENTS.md index 3ca9f899..a6d394ec 100644 --- a/src/scripts/AGENTS.md +++ b/src/scripts/AGENTS.md @@ -6,7 +6,7 @@ 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)`. +- **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)`. A sweep with no active shipments, construction completions, or production activity skips the `game:tick` event; `market-tick` likewise skips `market:auto-generate` when it expired and generated nothing, and `economy-tick` skips the batch event when it processed nothing (errors still emit). - **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"`). diff --git a/src/scripts/gameTick.ts b/src/scripts/gameTick.ts index 32ca5b1e..9699a35f 100644 --- a/src/scripts/gameTick.ts +++ b/src/scripts/gameTick.ts @@ -46,16 +46,27 @@ export const script = async (config: SanitizedConfig) => { const construction = await processConstructionTick(payload, log); const production = await processProductionTick(payload, log); - await emitGameEvent(payload, { - type: EventTypes.GameTick, - message: `Game tick processed ${processedCount} of ${activeShipments.docs.length} active shipments`, - data: { - processedCount, - totalActive: activeShipments.docs.length, - construction, - production, - }, - }); + // A sweep that touched nothing is pure noise in the event log. Shipments + // are included because advancing an active shipment is itself activity. + const hasActivity = + activeShipments.docs.length > 0 || + construction.completed > 0 || + production.processed > 0 || + production.produced > 0 || + production.stalled > 0; + + if (hasActivity) { + await emitGameEvent(payload, { + type: EventTypes.GameTick, + message: `Game tick processed ${processedCount} of ${activeShipments.docs.length} active shipments`, + data: { + processedCount, + totalActive: activeShipments.docs.length, + construction, + production, + }, + }); + } const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, ""); const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET; diff --git a/src/scripts/marketTick.ts b/src/scripts/marketTick.ts index e982ccd4..6ae4aa92 100644 --- a/src/scripts/marketTick.ts +++ b/src/scripts/marketTick.ts @@ -146,16 +146,19 @@ export const script = async (config: SanitizedConfig) => { } } - await emitGameEvent(payload, { - type: EventTypes.MarketAutoGenerate, - message: `Market tick: expired ${expiredCount} listing(s), generated ${generatedCount} new market entry/entries${generatedNpcCount > 0 ? ` (${generatedNpcCount} new NPC${generatedNpcCount !== 1 ? "s" : ""} generated)` : ""}`, - data: { - expiredCount, - generatedCount, - generatedNpcCount, - activeListings: active.docs.length, - }, - }); + // A tick that expired and generated nothing is pure noise in the event log. + if (expiredCount > 0 || generatedCount > 0) { + await emitGameEvent(payload, { + type: EventTypes.MarketAutoGenerate, + message: `Market tick: expired ${expiredCount} listing(s), generated ${generatedCount} new market entry/entries${generatedNpcCount > 0 ? ` (${generatedNpcCount} new NPC${generatedNpcCount !== 1 ? "s" : ""} generated)` : ""}`, + data: { + expiredCount, + generatedCount, + generatedNpcCount, + activeListings: active.docs.length, + }, + }); + } // 3. Notify connected clients so the market refreshes. const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, ""); diff --git a/src/utils/AGENTS.md b/src/utils/AGENTS.md index 278a773c..323c9e84 100644 --- a/src/utils/AGENTS.md +++ b/src/utils/AGENTS.md @@ -45,6 +45,9 @@ Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent ### Visibility policies: `visibility.ts` `EVENT_VISIBILITY_POLICIES` maps event types to defaults (`public`, or `restricted` with an any-of `requiredPermissions` gate); `resolveEventVisibility(type, override)` merges per-emit overrides with independent fallbacks. Restricted today: `npc:dialogue`, `flag:set`. The `game-event-logs` read access turns this into a Where clause (public OR required-permission OR actor-is-me; staff/superusers see all). Local API consumers must pass `user` + `overrideAccess: false` to respect it. +### Routine events: `routine.ts` +`ROUTINE_EVENT_TYPES` lists the high-frequency background types (`game:tick`, `economy:tick`, `market:auto-generate`). The `/events` page hides them behind an off-by-default "Routine ticks" switch and the dashboard excludes them; `excludeRoutineEventsWhere()` builds the Payload `not_in` clause. Client-safe (type-only Payload import). + ### Event types: `EventTypes` constants (~105 types across 15+ categories) Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the `type` field. Categories include: `mission:*`, `finance:*`, `market:*`, `structure:*`, `staff:*`, `logistics:*`, `bank:*`, `notification:*`, `locker:*`, `contribution:*`, `ticket:*`, `wiki:*`, `minigame:*`, `attendance:*`, `system:*`. diff --git a/src/utils/event-log/AGENTS.md b/src/utils/event-log/AGENTS.md index bdeeb411..d3e6d3d0 100644 --- a/src/utils/event-log/AGENTS.md +++ b/src/utils/event-log/AGENTS.md @@ -8,6 +8,7 @@ - **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. +- **Routine events**: `src/utils/event-log/routine.ts` (client-safe) lists high-frequency background types (`game:tick`, `economy:tick`, `market:auto-generate`). `/events` hides them by default behind a "Routine ticks" switch; the dashboard RecentEvents query always excludes them via `excludeRoutineEventsWhere()`. The tick bins also skip emitting a no-op sweep. The admin panel stays unfiltered. - **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. @@ -24,6 +25,7 @@ - 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`. +- The "Routine ticks" switch reveals `ROUTINE_EVENT_TYPES` (off by default). Selecting a routine type in the Type filter turns it on automatically. - Narrative events (system: false) styled with amber border + book icon. - On re-fetch, preserves existing entries while loading to avoid flicker. diff --git a/src/utils/event-log/routine.ts b/src/utils/event-log/routine.ts new file mode 100644 index 00000000..829da2a0 --- /dev/null +++ b/src/utils/event-log/routine.ts @@ -0,0 +1,28 @@ +/** + * Routine background events. + * + * These are emitted by the tick bins (game, economy, market) on a schedule and + * are diagnostic noise for members. UI surfaces hide them by default and offer + * a toggle to reveal them; the admin panel always sees everything. + * + * Keep this module client-safe: no Payload imports. + */ + +import type { Where } from "payload"; + +import { EventTypes } from "./eventTypes"; + +export const ROUTINE_EVENT_TYPES: readonly string[] = [ + EventTypes.GameTick, + EventTypes.EconomyTick, + EventTypes.MarketAutoGenerate, +]; + +export function isRoutineEventType(type: string): boolean { + return ROUTINE_EVENT_TYPES.includes(type); +} + +/** Payload `where` fragment that excludes routine events. */ +export function excludeRoutineEventsWhere(): Where { + return { type: { not_in: [...ROUTINE_EVENT_TYPES] } }; +} diff --git a/tests/int/event-log-routine.int.spec.ts b/tests/int/event-log-routine.int.spec.ts new file mode 100644 index 00000000..2b3ba89d --- /dev/null +++ b/tests/int/event-log-routine.int.spec.ts @@ -0,0 +1,82 @@ +import { getPayload, type Payload } from "payload"; +import config from "@/payload.config"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { emitGameEvent } from "@/utils/event-log/emit"; +import { EventTypes, type EventType } from "@/utils/event-log/eventTypes"; +import { + ROUTINE_EVENT_TYPES, + excludeRoutineEventsWhere, + isRoutineEventType, +} from "@/utils/event-log/routine"; + +let payload: Payload; + +const RUN = `evlogroutine-${Date.now().toString(36)}`; +const TIMEOUT = 30_000; +const eventIds: number[] = []; + +describe("routine event classification (pure)", () => { + it("marks tick summaries as routine", () => { + expect(isRoutineEventType(EventTypes.GameTick)).toBe(true); + expect(isRoutineEventType(EventTypes.EconomyTick)).toBe(true); + expect(isRoutineEventType(EventTypes.MarketAutoGenerate)).toBe(true); + expect(ROUTINE_EVENT_TYPES).toHaveLength(3); + }); + + it("leaves player-facing events visible", () => { + expect(isRoutineEventType(EventTypes.MinigameFlappy)).toBe(false); + expect(isRoutineEventType(EventTypes.StoryBeatRead)).toBe(false); + }); +}); + +describe("routine event filtering (database)", () => { + beforeAll(async () => { + payload = await getPayload({ config: await config }); + }, TIMEOUT); + + afterAll(async () => { + if (!payload) return; + for (const id of eventIds) { + await payload + .delete({ collection: "game-event-logs", id, overrideAccess: true }) + .catch(() => {}); + } + }); + + const emit = async (type: EventType, message: string): Promise => { + await emitGameEvent(payload, { type, message }); + const res = await payload.find({ + collection: "game-event-logs", + where: { message: { equals: message } }, + sort: "-id", + limit: 1, + overrideAccess: true, + depth: 0, + }); + const doc = res.docs[0]; + expect(doc).toBeDefined(); + eventIds.push(doc.id); + return doc.id; + }; + + it("excludes routine types and keeps the rest", async () => { + const ids = [ + await emit(EventTypes.GameTick, `${RUN}-game-tick`), + await emit(EventTypes.EconomyTick, `${RUN}-economy-tick`), + await emit(EventTypes.MarketAutoGenerate, `${RUN}-market-generate`), + await emit(EventTypes.MinigameFlappy, `${RUN}-flappy`), + ]; + + const filtered = await payload.find({ + collection: "game-event-logs", + where: { and: [{ id: { in: ids } }, excludeRoutineEventsWhere()] }, + limit: ids.length, + overrideAccess: true, + depth: 0, + }); + + expect(filtered.docs.map((doc) => doc.type)).toEqual([EventTypes.MinigameFlappy]); + }); +});