1
0
Fork 0
Commit graph

214 commits

Author SHA1 Message Date
4264431e4d feat(npc-dialogue): AI-assisted conversation drafting behind the review gate
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.

- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
  Compose and dialogue drafting share one path; add generateStructured and
  resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
  breadth layout, validator that rejects unknown flag keys, unauthorised
  effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
  than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
  author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
  prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
  rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
2026-11-12 12:26:35 -05:00
c4cbe43c4f fix(bot): survive a stale Discord interaction instead of crashing
A manual /rollcall took the bot down: the command fetched the guild member
and ran the staff check before acknowledging, missed Discord's 3 second ack
window, then died on "Unknown interaction" when it tried to defer (and again
when the error path tried to reply). discord.js re-emits a rejected event
listener on the client as an 'error' event, and with no handler attached Node
threw and exited the process.

Ack first, protect the error paths:
- /rollcall, /remind-evaluations and /debug defer immediately and report
  permission denials through editReply.
- safeEphemeralReply (bot/lib/interactions.ts) never rethrows, and the RSVP
  and transfer handlers use the same guarded behaviour.
- client.on(Events.Error) logs instead of exiting. The entrypoint restarts a
  dead bot after 5 seconds, so the previous symptom was a silent gap.
2026-11-03 12:50:29 -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
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
8faa45a954 test(mission-ratings): eligibility, aggregate math, threshold, XP
Covers window classification, yes-RSVP/prior-rating gating, idempotent write,
factor validation, per-factor/distribution/overall-average aggregation,
anonymity threshold, custom-factor aggregation, numeric myValues, XP grant +
per-user idempotency, and permission gating (deny without / allow with read).
2026-10-31 10:25:37 -04:00
66666547ad refactor(evaluations): drop stored kind, derive rating direction from ranks 2026-10-31 03:26:51 -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
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
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
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
54efc9453f Revert "feat(minigames): make Bomperator own-seat movement server-authoritative"
This reverts commit 98d5ec63f8.
2026-10-21 20:25:38 -04:00
938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler
only reuses worker processes between isolate:false tasks, so per-file fork
spawning made clone+boot costs unavoidable at stage 2):

- config: workers branch runs pool=forks with isolate:false, cap 8 via
  VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs),
  failure-marker reporter, and idempotent setupFiles chain
- vitest-worker-setup: one template clone PER FORK PROCESS named by pid
  (VITEST_WORKER_ID churns per task, which silently re-cloned per file);
  DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3)
- vitest.setup: once-per-process serial test URI markers; afterEach
  useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock
  module factories mid-file); logging absorber for fire-and-forget event
  writes that reject after their spec's cleanup deleted fixture users
- helpers/get-test-payload.ts: memoized Payload boot shared across files
  in a fork; codemod converted all 91 self-booting specs mechanically
- pinned opt-outs (own boot + comments): game-structures-labor-route,
  mission-reminder, notification-inbox-scope (jwtSign writes leak into
  the shared instance's auth state across files)
- promotion-nominations: create the superuser before its rank ladder so
  the Users-hook Recruit rank gets leading orderable tokens (its
  top-of-ladder guard needs Col to remain ladder-max on fresh clones);
  operation-economy: itemType-scope the market-state assertion (asset
  and resource ids collide as bare integers under per-fork databases)

Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s
vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4
note: globalTeardown config no longer exists; teardown returns from
globalSetup.
2026-10-21 12:54:30 -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
e3926ab828 fix(db): chunk drizzle json_build_array under postgres argument cap
Postgres caps function arguments at 100. `payload_locked_documents_rels`
holds one foreign-key column per collection, and Drizzle hydrates the
locked document's polymorphic relationship with a single
`json_build_array(...)` over all of them. At 103 collections the query
throws 54023 and every admin edit view breaks while a lock row exists.

Patch drizzle-orm 0.45.2 to split the call into 100-argument groups
joined with `::jsonb || ::jsonb`, mirroring the unmerged upstream PR
drizzle-team/drizzle-orm#4495. Relations with 100 or fewer columns keep
the original code path unchanged.

Add tests/int/locked-documents-query.int.spec.ts, which creates a lock
row and reads it back at depth 1 (what getIsLocked and
handleFormStateLocking do). It fails on pristine drizzle with the exact
54023 error and passes with the patch.
2026-10-21 10:31:11 -04:00
1738a66e40 test: isolate locker-sync and award-automation specs from cross-file db state
Vitest 4 orders serial test files by cached durations, so adding the interior
suite reshuffled the schedule and exposed two order-dependent specs.

- arma-locker-sync: floor the apply-command scan at a beforeAll id baseline and
  assert the two enqueue tests via per-test id deltas (the pattern the echo-guard
  describe already used) instead of absolute totals that accumulate rows when
  foreign online game-servers change enqueue fan-out
- award-automation: scope every evaluateAwardRules call to this file's ruleIds,
  and track veteran/rookie USER ids separately from PROFILE ids because plans
  key on userId while makeUser returned profile ids; equality only held while
  both sequences stayed aligned
2026-10-21 02:14:43 -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
0af105e055 test(interior): harden cleanup afterAll, raise decay timeouts, and fix seed typing 2026-10-20 19:50:19 -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
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
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
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
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
ad512bde11 test(minigames): cover bomperator input seq guard and snapshot echo
Two registry specs: stale/out-of-order seq posts are ignored while the newest
intent wins, and each seat's last applied seq is echoed in the snapshot.
2026-10-16 01:41:41 -04:00
e29af6bc29 test(minigames): add bomperator engine and registry specs
22 engine tests cover grid seeding, movement, charge fuse/detonation, chain
blasts, kick-push, round end and sudden death. 17 registry tests cover lobby,
seat lifecycle, reconnect window, dissolve below two seats, expiry sweep and XP
reward derivation.
2026-10-16 00:32:54 -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
1d6db3b92b Merge branch 'feat/first-party-analytics'
# Conflicts:
#	src/migrations/index.ts
2026-10-15 00:17:58 -04:00