1
0
Fork 0
Commit graph

917 commits

Author SHA1 Message Date
f2f637e289 feat(frontend): render threat assessment empty state and drop redundant internal header
When no analyst estimate exists, the card now shows an inline
'Threat assessment unavailable / insufficient intel' placeholder that
matches the card chrome instead of collapsing to nothing. The duplicate
internal 'Threat Assessment // Intel' strip is removed now that the
section header carries the icon and label; the unused refCode is dropped
with it.
2026-11-02 12:20:11 -05:00
0a8246ebcc feat(frontend): add lead icons to mission detail section headers
TacticalFrame takes an optional 'icon' prop rendered before the
classification label in the strip. Each of the 11 headers now passes an
icon, reused from its section's existing component icon for coherence:
RATING star, DETAILS clipboard, THREAT radar, BRIEFING doc,
OBJECTIVES crosshair, FACTIONS shield, ROLES users, COMMAND branch,
SIGN-UPS user-plus, LOGISTICS truck, COMMS radio.
2026-11-02 12:20:04 -05:00
bb7d7337ed chore(intelligence): standardize mission detail section labels and gutters
Standardize every TacticalFrame section header on the mission detail page to
"OPERATION // <Topic>" (was RATING // THREAT, OBJECTIVES, FACTIONS // INVOLVED,
ROLES // MANNING, etc.) so each card shares a uniform dossier label.

Add a consistent px-4 py-4 min-w-0 gutter to the six content-block sections
(briefing, objectives, factions, roles, comms, logistics) plus Mission Rating,
so their content no longer sits flush against the card borders. The already
bordered cards (Mission Details, Threat Assessment, Command Chain, Sign-Ups)
are left untouched.
2026-11-02 12:03:45 -05:00
7380131510 feat(frontend): style mission details sections as dossier cards
Wrap each main-content section of the mission details page in a
TacticalFrame card (classification strip, corner brackets, grid
texture, readout footer) following the tactical dossier recipe.
Add a `grow` prop to TacticalFrame for content-height frames.
The hero header is left untouched.
2026-11-02 11:14:43 -05:00
5d4dbab36b feat(dev): add seed-attendance bin for random mission attendance
New Payload bin seeds a random subset of users with weighted attendance
(75% yes / 15% no / 10% tentative) for a given mission, clearing prior records
first so each run produces a fresh sample. Written through the single attendance
write path so events and slot-holder notifications fire normally.
2026-11-02 10:01:32 -05:00
fa3e9ec865 chore(sidebar): add intro text to the Contribute dropdown 2026-11-02 10:00:16 -05:00
29bc2d40d7 fix(dashboard): center empty mission text and neutralize heading when none exist
The mission briefing widget now centers its 'No missions currently scheduled.'
empty state, and its heading falls back to a neutral 'Missions' label when there
is neither an upcoming nor a completed mission (previously it still said
'Last Mission').
2026-11-02 10:00:12 -05:00
51a6deb2b5 feat(mission-reminder): count chain supervisors as rateable leaders
The reminder endpoint/lib now treats a supervisor->subordinate command link as a
rateable relationship, so a completed mission prompts feedback even when the
co-attendees are at equal rank but linked by the mission chain.
2026-11-02 10:00:07 -05:00
79f790e02b feat(evaluations): allow equal-rank command-link reviews via mission chain
Resolve each evaluation mission against the command chain so a rater can rate a
ratee at equal rank when a supervisor->subordinate command link exists. Partition
graded docs into command vs spectrum buckets and surface command-link missions on
profiles that lack a strict rank gap.
2026-11-02 10:00:02 -05:00
ef3f26d4f9 feat(missions): add command chain editor and MissionCommandLinks collection
Introduce a per-mission command chain: a new MissionCommandLinks collection, a
lib/command-chain resolver, and an admin/mission-page editor for supervisor ->
subordinate links. Evaluations and mission reminders later consume this chain to
resolve equal-rank command relationships.
2026-11-02 09:59:55 -05:00
8951b32157 feat(sidebar): move Contributions link into Contribute sub-navlist above Minigames 2026-11-02 02:04:00 -05:00
e64c477250 fix(evaluations): require attendance from both players and route direct-supervisor reviews
- peer eligibility now requires a yes-RSVP from both rater and ratee, so
  absent players can neither rate nor be rated for that op
- a rating from the ratee's direct supervisor (rater leads an assignment the
  ratee is a member of and ranks above them) is the command review; every
  other rating feeds the anonymous leadership spectrum
- dialog copy and collection docs updated to match; tests cover both rules
2026-11-01 15:51:45 -05:00
99ef9ec73c fix(mission-ratings): block mission authors from rating their own mission
Authors can no longer rate a mission they ran or planned. The rating action, the availability check and the server submit all enforce it, and the UI explains why. The mission-ratings fixtures now use a dedicated author so the rater accounts stay non-authors.
2026-11-01 15:21:53 -05:00
e9bc929213 feat(bot): post modlist reminder 8 hours before scheduled operations
Adds reconcileModlistBuffer, which resends the modlist-updated message once per Scheduled mission with a modlist attached, when its start is within DISCORD_MODLIST_BUFFER_HOURS (default 8). Tracked by the new discordModlistBufferSentAt marker, so it is independent of the roll-call modlist sync. Also fixes type errors in modlist-file-access.int.spec.ts.
2026-11-01 15:20:02 -05:00
a6709e4cf3 fix(modlists): allow anonymous link download of preset files
The file-serving route (/api/mod-lists/file/<name>) runs the collection
read access with isReadingStaticFile: true, but mod-lists required the
mod-lists:read permission, so anyone clicking a shared download link got
403 until they signed in. Gate the read access on isReadingStaticFile: the
file-serving path serves the preset to anyone with the link, while REST and
admin-panel reads keep the mod-lists:read gate. Documented in
src/collections/AGENTS.md and covered by an integration test.
2026-10-31 15:01:29 -04:00
1f46275926 chore(mission-ratings): sanitize em-dash placeholders in overview + discord embed 2026-10-31 10:28:28 -04:00
afe47ccd87 feat(mission-ratings): add collection, mission field, and discord rating marker
- add_mission_ratings: mission-ratings collection + enum values + missions
  missionRating.customFactors field
- add_mission_rating_sent_at_marker: Missions.discordRatingSentAt one-shot flag
- register both in migrations/index.ts
2026-10-31 10:25:33 -04:00
ee622ff6dd feat(mission-ratings): UI, page wiring, discord embed + button handler
- MissionRating.tsx star form + overview renderer, wired into missions/[id]
- Discord rating embed + ptf-rate action row, posted on mission Completed
- interactionCreate ptf-rate handler replies ephemeral with mission URL
2026-10-31 10:25:28 -04:00
f41a5bd5e4 feat(mission-ratings): service, contribution rule, server action
- service: isRatingAvailable, submitMissionRating, getMissionRatingState,
  getMissionRatingAggregate (per-factor/distribution/overall-average math,
  anonymity threshold, custom-factor support)
- contributions: mission-rating-completion rule (50 instant XP)
- server action submitMissionRating with permission + contribution XP award
2026-10-31 10:25:24 -04:00
1db0aabb7c feat(mission-ratings): add permissions, collection, mission field, config, generated types
- permissions: mission-ratings group + ALL_PERMISSION_VALUES, granted in seedRoles
- collection: src/collections/intelligence/MissionRatings.ts (field-gated, Intelligence group)
- Missions: missionRating.customFactors group (array of {label})
- payload.config: register MissionRatings + requireAdminPageAccess
- regenerate payload-types
2026-10-31 10:24:04 -04:00
66666547ad refactor(evaluations): drop stored kind, derive rating direction from ranks 2026-10-31 03:26:51 -04:00
502eef5228 fix(profile): label downward leadership ratings as rate subordinate
Seniors viewing a junior's profile saw 'Rate leadership', but that rating is
stored as a subordinate review. The section now passes the rank direction to
the dialog, which labels the trigger, title, copy and toast accordingly.
2026-10-31 02:23:29 -04:00
3bef63af33 feat(map-objectives): superuser-authored strategic objectives on mission maps
Add a superuser-authored objective layer (defend, assault, secure, etc.)
shown as labelled map markers on both the world map and mission planning
map, with per-layer toggles on the planning map.

- collection: MapObjectives (map_objectives table, enums, FKs)
- lib: objectives service + objectiveTypes + permissions + event emit
- actions/api: create/update/delete objectives server actions
- UI: feature-layer toggles, objective picker dialog, world/plan markers,
  SQF export, dossier dialog integration
- generated: regenerate payload schema + types for map_objectives
- tests: 10 integration specs + e2e spec
- docs: CHANGELOG, map-system, AGENTS guides
2026-10-27 02:12:31 -04:00
245e70f3f2 feat(awards): brass-emboss ribbon devices, swap arrow for valor V 2026-10-27 01:47:10 -04:00
7430251adf feat(awards): render ribbon devices as vectors with tier-driven auto-layout
Introduce RibbonArt, a single shared SVG renderer used by both the production viewer and admin/studio preview so they can no longer diverge. Devices are now vector glyphs (star/oak leaf/campaign clasp/arrow up) instead of Unicode text, laid out as one centered cluster that shrinks to fit. Device count derives from advancement tier using the service-star convention (tier N shows N-1, cap 6; bare ribbon at tier 1 or for non-tiered awards). Legacy per-device x/y positions are stored but ignored, so no schema change. Designers add/remove/reorder device types and preview tiers.
2026-10-26 22:21:10 -04:00
f32afc6421 feat(logistics): restyle vehicle catalog cards in tactical dossier style
VehicleCard gains classification strip, corner brackets, squared corners, darkened cover imagery, faint grid texture and a permanent readout footer (matching CampaignCard). Fixes pre-existing defects: description rendered twice, category colors disagreed with the detail page, and stat accessors read nonexistent nested fields hidden by an 'as any' cast (now typed against Vehicle). Category color/label maps unified into src/lib/vehicles/categories.ts shared by card and detail pages.
2026-10-26 22:20:54 -04:00
acf47a75ea feat(operations): gate logistics extractions behind an officer review screen
Logistics operation-extraction effects now park as pending_action instead of auto-settling. Officers visit Operations > Extractions to keep, scrap, or expel each line; only kept lines deposit into HQ. A capacity failure leaves the effect retryable (pending_action) so a full HQ can free space and re-resolve. Adds resolveLogisticsExtraction/listPendingExtractions actions + ExtractionReview UI + tests.
2026-10-26 22:20:14 -04:00
40b074a693 feat(vehicles): add per-vehicle disallowed-cargo blacklist enforced at shipment
Vehicles gain a virtual-block disallowedCargo array (asset/vehicle/resource item + optional amount cap, 0 forbids outright). createShipment consults findDisallowedCargo() before deducting any origin stock and rejects matching cargo lines cleanly. Includes Payload migration + 7 integration tests.
2026-10-26 22:17:21 -04:00
02ef9f4954 feat(bot): add staff-only /debug command for previewing and reposting bot messages 2026-10-26 18:07:05 -04:00
6263730d9c refactor(bot): export render and send helpers for debug reuse 2026-10-26 18:07:05 -04:00
282b313cd5 fix(modlists): send modlist files as downloads instead of inline views 2026-10-26 18:07:05 -04:00
134c403b38 chore: regenerate db-schema (syncs payload-generated-schema.ts to current DB) 2026-10-26 03:39:40 -04:00
1fdb6bf872 feat(vehicles): add 'static' and 'drone' vehicle categories 2026-10-26 03:39:38 -04:00
c5bd74f297 chore(locker): commit pending stock handling refinements 2026-10-25 21:23:40 -04:00
977f841056 feat(evaluations): gate leadership ratings by rank instead of squad assignments
Eligibility now requires a strict rank gap plus a yes-RSVP from at least
one side of the pair on an evaluable mission. Junior rates senior writes
leader-direct (feeds the anonymous aggregate); senior rates junior writes
subordinate; leader-indirect stays readable for legacy rows only.

- New src/lib/evaluations/ranks.ts ladder helpers shared by all call sites
- Profile page: eligible missions union viewer+subject attendance, dialog
  hidden without a rank gap, subordinate line visible to higher ranks
- Bot and in-app reminder planners pair co-attendees by rank, not squads
- isDirectLeaderOf/isAnyLeader removed; no schema change or migration
2026-10-25 02:53:49 -04:00
633853589f feat(arma): dedupe vehicle templates by name and mod with cleanup CLI 2026-10-22 13:18:11 -04:00
59460111fd chore(minigames): log Bomperator transport kind and raw ping samples in debug stats
The rtt fields in __bompDbg.stats() are the smoothed EMA (seeded at 100ms,
one WS sample per 2s), so short playtests read as 35ms+ even on a 5ms path.
Record every raw RTT sample and the active transport (logged on mount, not
only on fallback) so the next playtest shows the real numbers.
2026-10-21 20:50:40 -04:00
54efc9453f Revert "feat(minigames): make Bomperator own-seat movement server-authoritative"
This reverts commit 98d5ec63f8.
2026-10-21 20:25:38 -04:00
88f060cead feat(sidebar): move Contribute (Voiceover) out of account popover into sidebar above Minigames 2026-10-21 19:56:40 -04:00
98d5ec63f8 feat(minigames): make Bomperator own-seat movement server-authoritative
Four prediction generations shipped and production still disagreed with the
server: v0.12.16's ack-sized envelope, wall-clock catch-up with a 1s cap,
ghost parity in both sims, and a forward-only replay clock. The last playtest
(n=645, rtt 41-69ms) still read gapP50 1.26, gapP95 7.05, 30% of snapshots
easing, with frameMax 17ms and zero server-side jumps. A second simulation
cannot be kept in agreement with the server by tuning.

Remove the second simulation instead:

- own seat renders the server's snapshot position through the same one-pole
  ease as remote players (shorter constant, 0.6 vs 0.4 per frame, because
  easing reads as input lag), snapping only past 1.5 cells (respawn/reset)
- drop the pending ledger, ack drain, input-to-ack EMA, envelope, trim and
  ease correction, optimistic kick overlay, and the local movement copy
- drop ghosts stay as visual feedback, placed at the server's own copy of our
  cell so they align with where the charge will appear
- telemetry now reports the ease's own-seat trail, own/remote snaps, snapshot
  cadence, frame max, ghost rows and RTT
- delete bomperator/prediction.ts, its offline harness and the prod-RTT
  fixture: they covered a mechanism that no longer exists

Input stays level-triggered on the monotonic seq + 400ms keepalive path. Cost
is one tick of queue (~25ms) plus one-way latency, the explicit trade for a
render that cannot diverge from the server.

tsc clean; bomperator-registry 19/19.
2026-10-21 11:42:32 -04:00
cc8a911502 test(vitest): parallel forks with per-worker database clones
Stage 2 of the int-suite speedup: pool=forks with fileParallelism and a
default cap of 8 (VITEST_MAX_FORKS), each fork cloning the template into
ptf_*_test_w<ID> via tests/vitest-worker-setup.ts; environment defaults
to node with jsdom opt-in docblocks on the six DOM-consuming specs; a
tiny reporter writes a failure marker so post-run cleanup keeps clones
after red runs (KEEP_TEST_DBS=1 forces keeping); pg pools cap at
TEST_PG_POOL_MAX=3 per boot in workers mode. Legacy serial mode stays
reachable by setting TEST_DATABASE_URI.

Notes from the gate G2 runs (Vitest 4.0.16): globalTeardown config was
removed in Vitest 4 entirely - cleanup now returns from globalSetup. The
pool scheduler only reuses worker processes when isolate:false, so this
per-file-fork stage lands short of the wall-time target and is expected
to be superseded by the gated isolate:false stage. Gate G2 warm serial
equivalent stays green via TEST_DATABASE_URI bisect mode.
2026-10-21 10:41:57 -04:00
a01ccaa7f1 fix(minigames): keep the Bomperator estimate replay clock moving forward
Root cause of the remaining jitter, and why stride tuning never touched it.
projectServerPosition replayed every unacknowledged input, then moved its
replay clock back to that input's receive time even when it predated the
snapshot. The trailing segment (targetMs - t) then included the input's
whole age, so a keepalive still in flight inflated the estimate by up to
the 400ms re-assert cadence: a phantom lead of 1-4 cells that the reconcile
then chased toward a position the server never occupied.

Prod telemetry fits exactly: gap p50 1.0, p95 4.12, max 4.5, 22% of
snapshots easing, frameMax 38ms, remoteSnaps 0, 13 ghost rows. No hitches,
no server-side jumps, just an estimator biased by pending input age. The
bias scale with ack latency, which is why the first match looked clean
(p50 0.18) and a match with RTT spikes to 53ms did not.

- clamp the replay clock: an input whose receive time is at or before `t`
  contributes its direction only, never a rewind
- the component now calls the shared projectServerPosition instead of
  keeping an inline copy of the same replay (one implementation, one fix)
- unit tests pin both behaviors (stale input adds no travel, newer input
  still advances); harness 12 scenarios plus the two new tests green
2026-10-21 01:40:50 -04:00
b51d4bc0d0 fix(minigames): stop Bomperator prediction losing time and disagreeing on ghosts
Prod telemetry (3291 snapshots, one match): gap p50 0.18 but p95 1.22,
max 4.19 cells and 43 eases. A 4-cell gap is ~0.6s of running, so these
are events, not latency noise. Tuning the correction envelope could only
change how they were presented.

- advance prediction by real elapsed time (1s sanity cap) instead of a
  100ms slice: the engine runs on wall clock, so every main-thread hitch
  over 100ms left a permanent gap that had to be eased back. The ease
  branch keeps its own 100ms slice so a catch-up frame cannot discharge
  a whole gap at once
- release held keys when the tab hides: input is level-triggered, so a
  backgrounded tab kept the technician running server-side and then
  snapped back on return
- replay optimistic ghost charges in the server estimate too; pred saw a
  charge the estimate did not, so every unconfirmed placement read as
  divergence while it was in flight
- telemetry: per-row longest frame and ghost count, frameMax/ghostRows in
  stats, so the next playtest attributes any remaining gap directly
- harness mirror: same 1s catch-up and 100ms ease slice; 12 scenarios green
2026-10-21 01:20:13 -04:00
69a3cb92fb docs: add superstructure interior domain guide and index entry 2026-10-20 20:08:25 -04:00
151a31efab fix(interior): clear self-referential parentStructure during provisioning 2026-10-20 20:08:25 -04:00
54cbf19fdf feat(interior): route logistics deposits through the shared placement core 2026-10-20 20:08:25 -04:00
0af105e055 test(interior): harden cleanup afterAll, raise decay timeouts, and fix seed typing 2026-10-20 19:50:19 -04:00
e52cc83198 feat(interior): interiors screens, sidebar entry, and launch content seed 2026-10-20 18:33:43 -04:00
f2de7941ca fix(interior): bootstrap snapshots lazily, enforce per-room access, and cover gaps 2026-10-20 18:33:43 -04:00
68cd3cce7c feat(interior): fixture repairs, condition decay, and station blocking
completeInteriorJob restores broken fixtures on repair jobs. New decay.ts applies per-room condition loss (elapsed days x conditionPerDay x Game Rules multiplier) on the interior-tick bin, gated by interior.decayEnabled with a baseline first run that only stamps the structure clock; fixtures at or below the authored effectFloor break with new interior:fixture-broken events, floors condition at 0, and station starts fail room_damaged below the floor.

Declares blocksStation on structure-rooms fixture state: provisioning wrote it but the missing column silently stripped it, so broken doorway fixtures could never block stations. Regression test covers persistence through provisioning plus the end-to-end gate.
2026-10-20 16:17:01 -04:00
6bc295b630 feat(interior): station recipes unlock gating and flagged asset outputs
Produce starts now honor presence-based unlocks_recipe/unlocks_station effects (station marker is its authored name) and reject unknown or gated recipes with recipe_locked, locked stations with station_locked. Asset outputs credit game-structures.storedAssets behind a new Game Rules interior.assetOutputsEnabled switch (default off), prechecked before any deposit so a disabled switch parks the job untouched; storageBridge.depositAssetsToStructure merges quantities by asset without duplicate rows.
2026-10-20 16:01:35 -04:00
0b7959662a feat(interior): upgrade completion, tech/labor gates, and module bonuses
Complete-time level advance (clamped to maxLevel), open/upgrade tech and labor gates sourced from npc-staffing and technologies.researchedAt, and pure duration/output math in effects.ts applied to job durations and produce resource output.

Adds interior_job_speed and interior_output_bonus module effect types to the shared module system (additive aggregates; existing consumers unaffected) with a migration, which also closes Step 1 drift making structures_rooms_levels_effects.value nullable and adding its target column.
2026-10-20 15:44:36 -04:00
1b8c84be47 feat(interior): open-room and cleanup jobs with junk loot rolls
Open jobs consume the entry level's materials and duration, then flip the room to its destination level at completion. Cleanup runs fixed-time, decrement one junk level per run, and roll one weighted drop from the authored junk loot table onto the job for collection.

Fixes provisionInterior's inverted guard so rooms provision lazily on first entry instead of requiring an already-set provisionedAt, and adds the interior integration suite covering provisioning idempotency, access modes, start gates, cancel refund, collect refusal on full storage, sweep completion, notifications, and loot roll determinism.
2026-10-20 14:57:30 -04:00
c57fc3d23d feat(interior): add superstructure interior schema and engine core
Adds the interior authoring fields on structure blueprints, runtime interior snapshot fields on game structures, the structure-rooms and interior-jobs collections, GameRules toggles, and a Scrap resource seed.

Adds the src/lib/interior engine: access gate, room provisioning, job-start gates, structure storage bridge, job lifecycle (start, cancel, complete, collect), completion sweep, and the interior-tick bin.

Registers interior event types and the interior:job-ready notification type.
2026-10-20 14:37:13 -04:00
f62f5265fa feat(intelligence): export mission briefings to SQF
Add a briefing export dialog with a diary script and a structured text array. Convert Lexical formatting, including bold, code, underline, colors, headings, lists, and quotes, into Arma Structured Text. Scope the shared color palette to the briefing editors and render colors on the mission page.
2026-10-20 14:22:17 -04:00
3c774279aa feat(minigames): superuser developer console dock across all ten games
Adds a shared fixed-position debugging dock (Controls/State/Log tabs) gated
to dynamic superusers, mounted per minigame. Multiplayer games gain synced
server-authoritative admin commands with [dev-admin] audit logging: poker
(force fold, force street, per-viewer reveal-all, clock control, stack
adjust, force expire), blackjack (bankroll adjust, next-card injection,
dealer override, force expire), bomperator (pure applyAdminCommand: crates,
pickups, eliminate, freeze, sudden death, timer, end round; mirrored over
the arena REST path), and CFF Versus (reveal fleets, force shot outcome,
skip turn). Solo games get client-side tuning via persisted dev settings:
flappy physics sliders plus pause and invincibility, EOD layout reveal and
seeded boards, radio transcript view and timer freeze, aim trainer seed and
difficulty overrides plus hitbox overlay, OPORD answer reveal and study
window, call-for-fire target reveal, seeded grids, and free corrections.

Includes 26 new integration specs (command purity, gating, audit lines) and
a poker e2e smoke for the dock. Plan: Minigame Developer Console.
2026-10-20 12:48:27 -04:00
d15beb8e35 fix(minigames): end Bomperator WS jitter with ack-sized envelope and rate-limited trims
Prod telemetry (bompDebug, 783 snapshots): ping RTT of 3-24ms shrank the
correction envelope to ~0.75 cells while the real gap noise floor sat at
p95 1.0, so 13% of snapshots trimmed and each trim closed its whole
excess in one frame - constant micro-teleports.

- size the envelope from transport RTT plus the server-side component of
  measured input-to-ack latency (tick queue + snapshot turnaround),
  which ping/pong cannot see; HTTP behavior stays near the v0.12.6 tuning
- rate-limit trims to 0.35 cells per snapshot (a run-speed glide); the
  >2.5-cell ease branch remains the fallback for genuine divergence
- harness mirror updated: maxJump now capped at 0.35 across all 12
  scenarios, prod-trace pulls 162 -> 47, zero teleports throughout
2026-10-20 02:02:00 -04:00
1883a1aabe feat(minigames): powerup name tags, centered loadout pips, prediction telemetry probe
- drawDrop now renders the powerup name on a semi-opaque plate pinned to
  the cell bottom (no bob, stays readable while the drop animates)
- own loadout pip row centered above the play area
- opt-in client telemetry behind localStorage.bompDebug='1': one row per
  reconciled snapshot (gap, envelope, correction branch, rttAvg, snapshot
  delivery cadence, remote-player snaps) plus transport kind changes,
  exposed as window.__bompDbg.stats()/.table()/.dump() to diagnose the
  reported WS jitter with data instead of guesses
2026-10-20 01:16:31 -04:00
2235d0d33d fix(xp): floor XP total so displays never render a float
The virtual profiles.progression.xp field summed awards, scoreboard
kills, and minigame/contribution xpEarned buckets without flooring,
so fractional values leaked into user-facing displays (e.g. 9,001.625
XP). Floor the total in the afterRead hook so every consumer receives
an integer, and update the profile page to show the already-resolved
xpLevel.xp instead of the raw value.
2026-10-20 00:15:50 -04:00
707c5f6c81 feat(event-log): hide routine tick events behind a toggle
Add a client-safe ROUTINE_EVENT_TYPES list (game:tick, economy:tick, market:auto-generate) and hide those types on /events behind an off-by-default Routine ticks switch. The dashboard always excludes them so real events fill the recent list.

Tick bins now skip no-op emissions: game tick requires shipment, construction, or production activity; market tick requires an expiry or generation; economy tick requires processed items or errors. Historical events stay in the database and remain visible via the toggle or the admin panel.
2026-10-19 20:03:51 -04:00
afa79b4be4 feat(tech): member-facing tech research system and tech tree
Add a research pipeline over the existing technology tree: Research
Facility blueprint fields copied to structure instances, tech-researches/
tech-ballots/tech-ballot-votes collections, Game Rules research config,
pure rules lib (capacity, duration math, eligibility, intel-weighted
tally with tie cascade), a timestamp-derived tech-tick bin that opens,
resolves, advances and completes research with notifications, vote
casting server actions, and a read-only member-facing tech tree page at
/intelligence/tech-tree with veil blackout and dossier-style panels.

Includes migration 20261019_184409_add_tech_research_system, permission
groups, event and notification types, sidebar entry, and integration
plus e2e coverage.
2026-10-19 17:28:26 -04:00
57b6999e61 fix(base): allow admin labor headcount edits while hiring is disabled
The admin game-structures Labor Crew panel writes through setLaborHeadcount, which failed closed whenever Game Rules staffHiringEnabled was off. Back-office operators had to toggle hiring on just to adjust headcount.

setLaborHeadcount now accepts an allowWhenHiringDisabled option. Only the admin API route passes it; player-facing server actions keep the gate.
2026-10-19 14:25:55 -04:00
f5166c80b6 fix(ai-compose): keep named action instructions in the system prompt
The plugin carries a named action's whole instruction in the system
prompt (Expand, Simplify, Rephrase, Proofread, Summarize, Tone,
Translate), while Compose on richText wraps the field's own system prompt
in buildRichTextSystem, which adds rules demanding lexical JSON and a
blog layout. buildComposeSystem discarded the incoming system prompt and
kept only the block-placeholder paragraph, so every named action reached
the model without its instruction and richText Compose lost the field's
own prompt too.

Keep the caller's prompt and strip only the contradiction: cut at the
plugin's RULES marker, re-append the extracted block-placeholder
paragraph, drop the JSON and layout lines as a backstop in case that
marker is reworded, then append AI_OUTPUT_RULES. The fieldType argument
is no longer needed.

The tests embed the plugin's real Expand, Simplify and Rephrase systems
and assert each instruction arrives intact with the rules appended.
2026-10-19 13:34:37 -04:00
2713a786e4 fix(arena): clamp early-timer catch-up so the tick loop holds 20Hz
Node timers can fire a sub-millisecond early relative to
performance.now(); Math.floor((now - scheduledFor) / TICK_MS) then yields
-1, and (1 + extra) shaved a whole tick off the next schedule. The
resulting delay-0 re-fire doubled the sim rate (~33-40Hz observed on the
live arena during integration testing; local repro confirmed it is the
scheduler, not the host).

Clamp extra to [0, TICK_CATCHUP_CAP] and add a wall-clock regression test
that pins driftReport ticksRun to ~20/s (fails at the doubled rate).
2026-10-19 13:12:20 -04:00
3d73aee193 fix(ai-compose): one prose output contract for every field prompt
Rich text fields received the plugin's richText system prompt, which
demanded lexical JSON and a blog layout of [paragraph]/[heading] markers,
next to an instruction asking for plain prose. The model answered by
arguing about the conflict, and that argument was saved into the field.
Text fields had the mirror problem: a prose instruction sent over a
transport that forced JSON.

Every field now asks for plain prose and nothing else, and the handler
assembles the JSON the Compose client already parses:

- src/lib/ai/composeSystem.ts owns the shared rules, keeps only the
  plugin's [[[BLOCK_<n>]]] echo instruction for richText, and wraps prose
  into lexical JSON or a single field value.
- payload.config.ts routes every wrappable schema through
  generatePlainText; streamObject stays only as the fallback for shapes
  prose cannot fill, such as a hasMany array.
- Truncated output reaches the client again (finish_reason length was
  swallowed on the prose path).

Adds tests/int/ai-compose-system.int.spec.ts (10 cases) and picks up the
generated payload-types.ts drift for the model field description.
2026-10-19 13:03:33 -04:00
394db6dfa1 feat(arena): websocket match replication for Ordnance Disposal
Adds a dedicated Node 22 + ws arena server (src/arena) that owns live
Ordnance Disposal matches: drift-corrected 20Hz tick loop with capped
catch-up and tick-drift logging, per-socket snapshot fan-out, 30s jose
ticket auth, and awards via the idempotent results callback route.

Client gains a transport abstraction (transport.ts): WsTransport first
when NEXT_PUBLIC_ARENA_URL is baked into the bundle, HttpTransport
(today's actions + SSE + guarded poll, behavior unchanged) as automatic
fallback after two connection failures or a 5s setup timeout; absent
env var means pure HTTP (kill switch / rollback path). Next actions
proxy the match lifecycle to the arena when ARENA_SECRET +
ARENA_INTERNAL_URL are set; the in-process registry stays untouched as
the default backend.

Deploy wiring: runner-arena Dockerfile target, compose service, env
docs, DEPLOYMENT.md checklist. Tests: arena module suite (19), live
server WS suite (3), prediction harness ws-grade latency scenario.
2026-10-19 12:27:17 -04:00
5e4ecd455b docs(minigames): note period-primary game pages with collapsed all-time boards 2026-10-19 12:14:58 -04:00
923831ba82 feat(minigames): make period standings the primary board on game pages
The six period-scored game pages (flappy, eod, opord, radio,
qualification, call-for-fire) now render their current-period
PeriodStandingsCard directly under the game board, in the slot the
lifetime board used to occupy. Each game's all-time leaderboard moves
below it into a collapsed AllTimeLeaderboard disclosure (shadcn
Collapsible) that expands on click, so period standings are centered and
primary and the lifetime board is opt-in.

PeriodStandingsCard drops its period/all-time toggle and keeps the
current period only, now with the presence line the pages previously
omitted. The old "Anchored period standings" heading and card block are
removed from the six page.tsx files. The e2e spec covers the collapsed
all-time section on /minigames/flappy.
2026-10-19 12:14:57 -04:00
15e434998a feat(ai): configure Compose model and label via env
UNSLOTH_MODEL selects the model the Compose plugin calls, and the optional UNSLOTH_MODEL_NAME labels it in the admin (derived from the model id when omitted). The model-id select keeps its stable internal key, a Postgres enum, so switching models needs no schema change.

The seeded per-prompt model value is cleared so the env var applies; an admin can still pin a model on a single prompt row. Migration 20261019_121500_use_env_ai_model drops the column default and clears the seeded value.
2026-10-19 12:13:22 -04:00
88982bfcdf fix(ai): resolve compose title and name the entity in seeded prompts 2026-10-19 11:32:59 -04:00
c149f07347 fix(ui): unify remaining page caps to 96rem and repair story xl cap
Raise the centered operations, supply-boxes, campaigns, factions and
missions wrappers from max-w-7xl to the same max-w-[96rem] used by the
logistics detail pages so all capped pages share one width.

The story page used xl:max-w-screen-2xl, a utility Tailwind v4 removed,
so that override silently did nothing; swap it for xl:max-w-[96rem],
which restores the intended wider gutter layout on xl screens.
2026-10-19 10:52:04 -04:00
9f05351798 fix(ui): center and widen left-aligned detail pages
Structure, vehicle, resource, shipment, banking, profile and awards
pages capped content at max-w-7xl pinned to the left edge, so all
slack pooled on the right on wide monitors (worse with the sidebar
hidden). Raise the cap to 96rem and center it, matching the existing
mx-auto convention on operations and intelligence pages.
2026-10-19 10:50:35 -04:00
ce682becec feat(minigames): touch controls and responsive board for Bomperator
- Extract pressDir/releaseDir/stopAll edge callbacks; keyboard, D-pad and
  swipes all feed the same held-stack path (prediction, keepalives and the
  pending ledger stay input-source agnostic)
- BomperatorTouchControls: 4-way pad + stop center + plant button on coarse
  pointers, per-button pointer capture for hold-and-plant multi-touch
- Board gestures: dominant-axis swipe sets direction, quick tap stops
- Canvas scales via CSS (w-full h-auto, fixed internal buffer), so prediction
  is viewport-independent; touch-action/overscroll guards on the board
- Harness: backgrounded-tab scenario (4s rAF freeze under prod trace replay)
  proves resume never teleports (teleports=0, maxJump 0.43)
- E2E smoke at 390x844 hasTouch: page loads without horizontal overflow
2026-10-19 10:11:30 -04:00
a72f1bbe03 feat(call-for-fire-versus): resize fleet, add second FOB, charred destroyed cells with burn effect
Command Post becomes a 3x2 rect that flips wide/tall, the Ammo Depot L grows to four cells, the FOB becomes two cells, and a second FOB (Forward Operating Base II) joins the fleet for 16 cells across five structures. Fully destroyed structures now render charred black instead of red, and their cells burn with flame and ember particles for 45 seconds after destruction, driven by a new impact timestamp on each shot.
2026-10-19 09:34:40 -04:00
d3bb69ffbc fix(minigames): end Bomperator teleport-back with trace-proven envelope correction
Root cause: Node event-loop stalls drop the server's setInterval ticks with
no catch-up, so the sim permanently lags wall clock; the old all-inputs-acked
pull let that gap stack past the snap threshold and discharge as an instant
backward teleport (the reported complaint).

- Component: lead-aware correction envelope, trim on every snapshot,
  capped-rate ease (2.5x speed) past 2.5 cells; resets still snap via the
  ack-backwards branch. No latency-precision mechanisms (the v0.12.4 lesson).
- prediction.ts: drop the unused decision-nudge exports.
- Harness: replay recorded production HAR latency
  (tests/fixtures/bomperator-prod-rtt.json), model server tick stalls, add
  per-reconcile jump telemetry. A/B proof under trace+stalls: v0.12.3 policy
  teleports twice (max jump 2.59 cells); envelope policy zero (max 1.10).
2026-10-18 02:11:15 -04:00
2a941c5a5b fix(minigames): resolve the current period before building standings boards
The default ?period=current scope arrives as periodId null, and
buildLeaderboardPayload built the boards before resolving currentPeriod(),
so buildPeriodBoards short-circuited to zero entries: the live period's
board was always empty even while ledger rows existed for it. Resolve the
period first and feed its id into the boards, and cover the default scope
with a real-clock regression test (the suite previously only exercised
explicit period ids).
2026-10-18 02:06:32 -04:00
a9f047f214 revert(minigames): roll back Bomperator prediction update after prod regression
Reverts 655407a (component + guide). Production HAR showed input POST
TTFB p50 87ms / p90 236ms / max 384ms (server pipeline variance, not
network). The nudges and ghost projection trusted rttAvg too tightly and
glitched under that variance; v0.12.3 behavior is restored.

Kept on purpose: bomperator/prediction.ts and the offline prediction
harness stay as test-only infrastructure for the re-fix, which will be
calibrated against the recorded production latency trace.
2026-10-18 01:40:44 -04:00
655407ab7d fix(minigames): stop Bomperator teleport-back with envelope correction and decision nudges
- Extract client prediction helpers to bomperator/prediction.ts (predStep/
  predAdvance port, alignDecisionToServer, projectServerPosition)
- Nudge prediction across cell boundaries at turn/stop edges so client and
  server commit to the same rounding decision; ghosts use the server's
  projected placement cell
- Stamp snapshot arrival time; event projections use measured age, reconcile
  estimate keeps the calibrated half-tick bias
- Replace pending-gated pull and instant 2.5-cell snap with a lead-aware
  correction envelope plus capped-rate ease (2.5x speed); resets still snap
  via the ack-backwards branch
- Add offline deterministic prediction harness (real engine + modeled network
  + frame-by-frame reconcile mirror), 9 scenarios incl. rAF stalls and a
  pre/post-fix ghost-mismatch comparison
2026-10-18 01:09:56 -04:00
76c01d2f3c feat(minigames): run Ordnance Disposal at 20 Hz, fix float-dust glide rest
Halve TICK_MS (100 -> 50) so every snapshot-bound surface (opponents,
explosions, drops) arrives twice as fresh, and double every hardcoded
tick-denominated constant so real-world durations stay identical:
BOMB_FUSE_TICKS 25->50, FLAME_LIFETIME_TICKS 3->6,
SUDDEN_DEATH_INTERVAL_TICKS 40->80, SPAWN_INVULNERABLE_TICKS 10->20.
TPS-derived durations (round timer, countdown, end hold) scale on their
own. Client fuse-blink and flame-fade thresholds are now derived from
the constants instead of hardcoded for 10 Hz.

Fixes a latent engine bug the old rate masked via lucky float rounding:
approach() snapped to the target only when the remaining delta was
<= step exactly, so a multi-tick glide accruing float dust (5.3 + 0.35
= 5.6499999999999995) could overshoot on the final step and park the
technician at 5.999999999999999 forever (isCellCentered accepted it,
Number.isInteger did not). approach() now tolerates step + 1e-6 and the
movement loop snaps resting positions to whole cells, restoring the
documented rest-exactly-on-center invariant at any tick rate.

Docs: registry header and minigames AGENTS.md updated to ~20 Hz; also
corrected stale rate-limit (40/s) and polling (500ms fallback) notes.
2026-10-16 15:25:24 -04:00
99e610e955 feat(minigames): tighten Ordnance Disposal feel, ghost charges and flight-safe correction
Two client-side follow-ups from the first prod playtest of prediction v2:

Reconciliation no longer position-corrects while the latest inputs are still
in flight. In that window the server legitimately trails the local sim (it is
still applying the previous direction), and the previous always-on 20% pull
dragged the sprite backwards on every turn and key release; that drag is what
made movement feel heavy even after prediction landed. Soft correction now
only runs once every sent input is acknowledged and the gap exceeds a 0.4
cell deadzone, pulling the excess; the teleport hard-snap is unchanged.

Dropping a charge now renders an optimistic ghost at the technician's cell
the same frame, mirroring every server rejection rule against the freshest
state. The ghost blocks movement like a real charge (but cannot be kicked),
burns its fuse on the local clock, and is retired per snapshot by a bomb at
its cell, by a fresh bomb owned by our seat (possibly one cell away when the
server trailed the displayed position), or by a 1.2s expiry covering server
rejections.
2026-10-16 15:04:15 -04:00
7935e857af feat(minigames): make Ordnance Disposal movement feel instant
The client rendered the local technician only from server round trips, so
every keypress showed up RTT + tick + easing late (roughly 250-500ms in
production, per HAR analysis of a live playtest). Two changes, shipped
together:

Direction edges now fire immediately with a monotonic seq instead of queueing
behind an in-flight POST. The registry applies only strictly newer seqs, so
out-of-order action POSTs can never resurrect a stale intent, and echoes the
last applied seq back in every snapshot for client reconciliation.

The client predicts its own seat locally with a line-level port of the
engine's movement rule (align-first turns, blocked settle, slip-to-rest,
kick-push with an optimistic overlay) and reconciles per snapshot by
replaying unacknowledged inputs forward from the server position, timed by
send time plus measured latency, instead of snapping toward a stale sample.
A soft 20%/frame correction absorbs sub-cell error; teleports and round
resets still snap.
2026-10-16 01:41:19 -04:00
bbee22a457 docs(minigames): drop em-dash from bomperator AGENTS note 2026-10-16 00:38:45 -04:00
bfb5cea3c1 feat(minigames): add Ordnance Disposal (bomperator) multiplayer drill
Add a 2-8 player free-for-all Bomberman-style charge-clearing drill at
/minigames/bomperator, category multiplayer. Pure engine plus a single-instance
in-memory match registry, mirroring the call-for-fire-versus split but upgraded
from turn-based to a fixed ~10 Hz tick loop.

Engine (src/lib/minigames/bomperator): seeded RNG via state.rngState/gridSeed;
grid is 15x13 with border, even/even pillars and seeded crates; classic pickups
bomb/range/speed/kick. Movement is grid-locked with sub-cell interpolation,
charges fuse about 2.5s, cross-flames stop at walls, crates are destroyed and
charges chain-detonate and kick-push. Round ends at one alive; sudden death
spawns random explosions after 150s with a draw guard.

Registry (registry.ts): one setInterval per live match started on startMatch and
cleared on complete/dissolve; globalThis-anchored map; holds seats across a
reconnect window then eliminates; below two active seats it dissolves. On a
manual end, broadcasts a bomperator-terminated event so remaining players see a
toast, then awards rewards via stats.ts (minigame:bomperator, profile group
bomperator: matchesPlayed/matchWins/roundsWon/kills/xpEarned).

Clients POST rate-limited inputs and poll fetchBomperatorMatch; the SSE bus pushes
snapshots with a guarded slow-poll fallback. Registry row ships as upcoming so the
page renders the coming-soon shell until an admin flips it active. Adds the
migration for the stats group, the minigame:bomperator event type, XP
aggregation on the profile, generated types, and real-time event wiring.
2026-10-16 00:32:52 -04:00
4c6d34e868 feat(realtime): anchor SSE client set on globalThis for cross-bundle delivery
Next.js dev bundles server packages per route, so a module-level Set forks
into one copy per bundle: a broadcast issued from a server action or registry
bundle would never reach a client subscribed through the /api/realtime route
bundle. Anchoring the client set on globalThis unifies every bundle copy within
the single dev process, the same trick blackjack/poker already use. It is a
no-op in production, which has one module instance anyway.
2026-10-16 00:32:42 -04:00
3eb8ada8f8 feat(bot): add edit modal to /changelog for last-minute copy tweaks
/changelog edit=true resolves the target entry (latest or one version,
ranges rejected) and opens a modal prefilled with its raw markdown
instead of posting. Submit re-checks staff, renders the edited text
through the existing splitForDiscord pipeline and posts the amber
embed(s). One-shot by design: CHANGELOG.md is never written back.
Entries over the 4000-char modal cap refuse edit mode. Modal path
skips deferReply (first-response rule, same as /announce); submits
route through bot/index.ts on the ptf-changelog-edit: prefix.
2026-10-15 12:34:18 -04:00
caf77e3a6b feat(tech-tree): optimistic concurrency for the tree editor
Guard the Technologies collection with an X-PTF-If-Unmodified-At
precondition hook (update-only, header-only) that rejects stale writes
with HTTP 409 and a stale_write payload, placed before the approval
reset hook. Bulk position writes gain per-row ifUnmodifiedAt tokens in
one all-or-nothing statement; conflicts return the offending ids and
successful writes return fresh tokens so clients advance their own
versions. The lite editor shows a Version Conflict dialog (load latest
or overwrite anyway); canvas position conflicts surface as a toolbar
banner with refresh / force-overwrite plus red node rings.

Tests: new tech-tree-concurrency int spec (guard, coexistence with the
approval reset, positions preconditions), two e2e scenarios for the
dialog and the banner; existing positions spec adapted to the new
return shape.
2026-10-15 11:48:30 -04:00
4f129fc59a feat(approval): reset reviewed documents to in progress on non-superuser edits
Add resetApprovalStatusOnEdit(), a collection beforeChange hook factory: when a
non-superuser updates a document whose stored approvalStatus is approved or
revision_requested, the status is rewritten to in_progress so the edit goes
through review again. Creates, superusers (system:admin-access), and system
writes with no user (catalog imports, seeds) are exempt, and an explicit
in_progress/ready_for_review in the edit is honored.

Wired into Technologies, Assets, Resources, Vehicles, and Structures.

Structures also moves from the legacy isDeveloper filterOptions gate to
approvalStatusFieldAccess("structures"), matching the other four collections
and removing the hard ValidationError when saving an already-approved structure.

Tests: 12 cases in tests/int/division-admin-access.int.spec.ts.
2026-10-15 10:01:02 -04:00
a5bbcdd8ec fix(analytics): drop non-route export from collector route
Next.js rejects arbitrary exports from a route module, so the production
build failed on `export const ANALYTICS_SID_COOKIE` in /api/collect. The
constant is used only inside that file, so make it module-private. The client
SDK keeps its own copy in client-analytics/core.
2026-10-15 00:32:41 -04:00
1d6db3b92b Merge branch 'feat/first-party-analytics'
# Conflicts:
#	src/migrations/index.ts
2026-10-15 00:17:58 -04:00
33f3f7aa75 feat(minigames): add phasing-out status with estimated removal date
Add a "phasingOut" minigame status and an `estimatedRemovalDate` field so a
game can be announced as leaving soon while staying fully playable and keeping
scoring periods (unlike retired games). Visibility is the only difference:

- Sidebar badge + tooltip (amber "Phasing out", countdown to removal) in
  NavMinigames, via new phasingOutTooltip in countdown.ts.
- In-game banner (PhasingOutBanner) on all 9 game pages, wired from
  getMinigameReleaseState (added the fetch to call-for-fire, which lacked it).
- registry.ts status union + field; loadRegistry.ts maps the field;
  config status select + estimatedRemovalDate date field added.
- Migration adds the enum value and column (idempotent); types + db schema
  regenerated.

Adds tests for visibility, round-trip, and period scoring; updates the
minigames domain guide.
2026-10-14 23:51:37 -04:00
88e89c9e55 feat(npc-dialogue): post opted-in event effects to Discord dispatch channel
Event nodes gain a 'Post this event to the Discord NPC dispatch channel'
checkbox. The flag rides emit() onto game_event_logs (discordRequested +
announcement bookkeeping columns, migration add_event_log_discord_fields),
and a new bot poller stamps pending rows into an amber NPC Dispatch embed
with relative-time mention and a link back to the source contact.

Bot delivery itself is unverifiable locally (no Discord token or channel id
in dev); the DB-side contract is covered by an integration test and a live
probe walk confirmed discord_requested persists end to end.
2026-10-14 16:57:33 -04:00
20c70151e3 feat(npc-dialogue): rich text editor and block lists in dialogue markup
DialogueText gains line-based block lists: consecutive lines starting
with - / * render as bullets, 1. / 2) as ordered lists, with item
content running through the inline parser so markup nests inside items.

Node editing swaps plain textareas for a shared MarkupEditor (line,
narration, lead-in, closing, tooltip, lock message, event message):
a formatting toolbar (bold, italic, code, color, link, bullet and
numbered list), a right-click menu wrapping the selection in tokens,
and a live DialogueText preview on the long-form fields. Storage stays
the plain custom-markup string; the editor only wraps selections.
2026-10-14 16:33:23 -04:00
c299acbe4f feat(npc-dialogue): condition groups and ternary text tokens
Conditions become a discriminated union: the existing flag leaf plus a
single-level group combining leaves with AND / OR / NOR. The evaluator
recurses one level, and every flat-assuming site (choice gating, graph
validation, editor, canvas previews) is group-aware; DB entry gates stay
flat by design. The node editor gains a shared condition builder with a
combinator dropdown and repeatable rows for both branch nodes and gated
choices.

Display strings also gain ternaries: {{ key ? yes : no }}, {{ !key ? .. }},
and numeric compares like {{ rep >= 5 ? .. }}. A brace-depth scanner
rewrites ternaries over bounded passes so branches may nest flag tokens
and even nested ternaries, then plain interpolation runs its single
never-rescanned pass. Ternary keys join collectNodeTokens so the server
reads exactly the flags a node needs.
2026-10-14 16:21:16 -04:00
a1aaed913d feat(npc-dialogue): attach files to conversation lines
Nodes can carry pointers to media docs (transcripts, sealed orders,
images). Authors upload from the node editor (gated on
npc-dialogues:update); the runtime resolves ids to file URLs server-side
and players open them in a dossier-styled viewer modal with download
and new-tab escape hatches. Deleted media resolve to nothing instead of
dead chips.
2026-10-14 16:05:15 -04:00
799c3216d2 feat(npc-dialogue): back NEW badges with server-side read markers
The per-browser localStorage tracking reset on every new device and kept
re-badging whole conversations whenever a GM edited the flowchart (hash
change), which players read as "nothing I read is remembered". Read
progress now lives in a npc-dialogue-states collection: one row per
(user, dialogue, node) with a unique index, so a node badges NEW exactly
once per player and GM edits never re-flag content they already saw.

- New collection NpcDialogueStates (own-doc access, staff-visible admin
  view) plus migration add_npc_dialogue_states.
- lib/npc-dialogue/states.ts: listSeenNodeIds for the page and an
  idempotent markNodeRead; exposed via the markNpcDialogueNodeRead
  server action, called fire-and-forget as nodes type in.
- The contacts page seeds initialSeenNodeIds into NpcConversation; the
  component keeps an optimistic local set and no longer touches
  localStorage. seen.ts and its tests are removed.

Verified live: fresh account shows NEW on all choices, reading the
"Who are you?" branch and reloading drops that badge while unread
branches keep theirs; npc_dialogue_states holds exactly the traversed
nodes. Interpolation int suite green (30/30).
2026-10-14 15:35:47 -04:00
59f01610ca feat(npc-dialogue): opt-in public visibility for event node effects
Dialogue-emitted game events default to restricted (npc:dialogue policy) so
narrative branches stay spoilable-free, which also hid announcements authors
intended for everyone. Event nodes can now mark their effect's log entry
public: NpcDialogueEffect gains an optional eventVisibility field, runEffect
threads it into every emitGameEvent call (emit, reward, flag), and the node
editor exposes a "Show this event to everyone" checkbox for those effect
types.

Omitted eventVisibility keeps today's behavior exactly: resolveEventVisibility
falls back to the per-type restricted policy. The separate restricted flag:set
audit written by the PlayerFlags hooks is untouched.

Verified live on dev: two injected event nodes (with and without the flag)
stored visibility "public" and "restricted" respectively; flow and probe rows
cleaned up afterward.
2026-10-14 15:15:38 -04:00
95a2412206 fix(npc-dialogue): re-route edges live while dragging cards
Edges in the dialogue flow editor bent around where cards used to be until
the page was saved and refreshed, because RoutedFlowEdge memoized its
obstacle rectangles on the React Flow store's nodeLookup Map. That Map is
mutated in place during a drag, so the memo key never changed and the cached
rects only refreshed on remount.

Compute the card rectangles in the editor from its own live `nodes` state and
hand them to each edge through `data`, which is how the tech tree already
drives its routed edges. Obstacles stay render-only: serialize() persists
deriveEdges(clean) separately, so nothing new reaches stored flow data.

Verified by dragging a non-endpoint card over an unrelated edge and sampling
that edge's path mid-drag: 4 of 5 held positions re-routed with the fix, 0 of
5 without it (same test, same document).
2026-10-14 15:00:08 -04:00
43397f16cb docs(analytics): add event taxonomy README and analytics domain guide 2026-10-14 12:13:01 -04:00
268d4bb117 feat(analytics): add first-party analytics collector, SDK, rollups, and admin dashboard
Phase 1 of replacing Microsoft Clarity with first-party usage analytics:
- Plain Postgres tables via shared DDL module (src/lib/analytics/schema.ts)
  executed by both the add_analytics_tables migration and the test bootstrap;
  test-db.ts drops them around drizzle push (composite-PK introspector bug)
- /api/collect beacon collector with IP/UA enrichment, retroactive login
  attribution, bot blocklist, per-IP rate limiting, strict validation
- Client SDK (src/lib/client-analytics): SPA pageviews, clicks, scroll depth,
  focus, data-track visibility, heartbeats; NEXT_PUBLIC_ANALYTICS_DEV=1 dev
  gate with console mirror; mounted beside Clarity in the two frontend layouts
- Hourly rollup + daily retention bins (payload analytics-rollup/-purge)
- Chronicle read progress/completion, wiki new-clicked/created, minigame
  route mapping custom events
- admin:analytics:manage permission (+ roles enum migration) and the
  /admin/analytics Payload view with six recharts-backed report panels
2026-10-14 12:12:53 -04:00
61ac2122d6 fix(garage): pad garage page content like sibling routes
The page root used flex flex-col gap-6 without the site-standard p-5,
so contents rendered flush against the header and sidebar.
2026-10-13 16:43:16 -04:00