Commit Graph
10790 Commits
Author SHA1 Message Date
adminandClaude Opus 4.7 77a071afcf Add Shardok-side connection status indicator
The strategic-map status widget already reports Your Turn / Waiting for
Players / etc. via ServerGameStatus. This adds the equivalent for
tactical battles so the player knows whether they're up, the AI is
thinking, or another human is about to act.

ShardokServerStatus is a separate proto from ServerGameStatus so the
strategic and tactical layers don't have to evolve in lockstep. The
server populates it per-battle in GameController by checking
shardokPlayerAvailableCommands across factions, classified into
AI vs human via aiClientFactionIds.

Client side: ShardokGameModel implements IShardokGameStateProvider and
caches the latest status. EagleGameController binds the persistent
ConnectionStatusUI to the Shardok model on entering battle;
ShardokGameController clears it on exit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:46:52 -07:00
7306c9cb06 Don't block dropGame on archive + battle cancellation (#6681)
When the last human drops a running game, the previous order was:
cancel-battles → archiveGame → mutate state → save() → return. Both
cancelBattlesForGame (gRPC roundtrip) and archiveGame (per-S3-file
copy + delete, all serialized) ran inside this.synchronized AND inside
the lock that gates the lobby push, so users could wait several
seconds to see the dropped game disappear from the lobby list.

Now we mutate state and save() first so the lobby update reflects the
removal immediately, then run cancelBattles + archive on a background
Future. Failures are logged.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:28:12 -07:00
3ff012806f Reliably highlight reinforcement heroes in battle tutorial (#6679)
* Highlight Elena (and other reinforcements) reliably in tutorial dialogues

Elena Fyar's hex wasn't pulsing during her arrival dialogue even though
the trigger fired. The most likely causes are: she's matched in
ReserveUnitsById rather than UnitsById at the moment the dialogue plays,
the SelfHostility check rejects an allied-rendered reinforcement, or her
ProfessionInfo isn't populated on whichever diff happens to be the
latest UnitView in UnitsById when ApplyUnitHighlight runs.

Three changes, defense in depth:

- DialogueManager.ApplyUnitHighlight now scans UnitsById ∪ ReserveUnitsById
  (still requires a placed Location), and treats any non-enemy unit as
  highlightable rather than requiring SelfHostility.
- Elena's and Ranil's reinforcement dialogues, plus engineer_bombard
  (which is Ranil speaking about himself), now match by heroName instead
  of profession. Each dialogue is about a specific hero by name, and
  heroName goes through unit.Name (text-id-based) which doesn't depend
  on ProfessionInfo being present on the latest diff.
- duel keeps profession matching since the dialogue is about Champions
  in general.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Re-apply tutorial unit highlight every frame

The Shardok controller's ModelUpdated() calls hexGrid.ClearOverlays() on
every model update, which wiped the tutorial unit highlight applied
during step 1 of a multi-step dialogue: by the time the player was
reading Marek's lead-in line about Elena (or Ranil), a follow-up server
update had cleared the overlay. Step 2 happened to survive because no
further model updates arrived between the player advancing the dialogue
and the render.

DialogueManager now stores the current step's highlight criteria and
re-applies it every frame from Update() so it survives any number of
ClearOverlays calls. ApplyUnitHighlight is now idempotent (clears its
tracked cells before re-scanning).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:15:39 -07:00
904dadf170 Bump Luke the Prank-tricker tutorial bias to 300 to outpace decay (#6680)
The previous 130 setting netted +30 effective bias after
FactionBiasFromImprisonment (-100), which then decayed to 0 within
3 rounds via NewRoundAction's per-round bias decay (additive -10/round
below |100|, multiplicative *0.9 above). By the time prison-round odds
had accumulated, the bias contribution was already gone.

Setting the config to 300 yields +200 effective bias, putting it in the
multiplicative-decay regime: ~+131 by round 4 (Nov) and ~+96 by round 7
(Feb). That keeps Luke comfortably over MinOddsForRecruitment (80)
through the intended early-tutorial recruitment window.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:05:36 -07:00
579d04eafd Rename knights in tutorial opening dialogue to Doomriders (#6678)
Old Marek's first tutorial-battle line previously named Shardok's Guard
as "the finest soldiers in the realm" and referred to "knights besides"
as a separate unit. Since the heavy-cavalry battalion in the attacking
army is named Doomriders, attribute the knights line to them directly
and drop the implicit second unit reference.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 20:46:48 -07:00
acdea65632 Highlight referenced units during battle tutorial dialogues (#6676)
Several battle tutorial dialogues call out specific units by role
(longbows for archery, the champion for dueling, Marek for charging,
the engineer/paladin reinforcements, Hedrick for hiding) or by an
available action (melee, start fire). The dialogue had no way to point
at the unit on the battlefield, so the player had to find it themselves.

Adds an optional `highlightUnit` block to dialogue steps with criteria
fields (battalionType, profession, heroName, canStartFire, canMelee)
that DialogueManager resolves against the current Shardok model. Each
matching friendly unit gets a strobing border via HexGrid.OverlayCell
— the same primitive already used for archery range and movement
overlays — so the visual language matches existing combat highlights.
The overlay is cleared on step change and dialogue end.

Wires up the criteria for all relevant battle dialogues:
- archery_available → Longbowmen
- ability_charge_available → Old Marek the Learned
- melee_available → friendly unit with a MeleeCommand available
- start_fire_available → friendly unit with CanStartFire
- duel_available → Champion
- tutorial_reinforcement_paladin → Paladin (Elena)
- tutorial_reinforcement_engineer → Engineer (Ranil)
- engineer_near_enemy → Engineer
- hide_available → Hedrick the Hedge-Merchant

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 20:38:18 -07:00
b4bb2f6d7f Bump Luke the Prank-tricker tutorial recruitment bias to 130 (#6677)
The tutorial configures +110 faction-3 bias on Luke so that he becomes
recruitable shortly after capture, but EndBattleAftermathPhaseAction
applies FactionBiasFromImprisonment (-100) to the imprisoning faction
and merges in initialFactionBiases on top of it. The effective bias was
only +10, which left him needing several extra rounds of prison-time
odds adjustment before reaching MinOddsForRecruitment (~Feb/Mar 372 in
practice). Bumping to 130 raises effective bias to +30 (~4 rounds
earlier), pulling first recruitability to ~Nov 371 as intended.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 20:30:58 -07:00
44546ac3e0 Mutually distrust the three tutorial NPC factions (#6675)
Bregos, Bridget, and Hedrick now all start at -500 trust toward each
other. With trust drift at +1/round, that's effectively permanent for
tutorial timescales. The invitation gate (TrustForDiplomacy.scala) only
checks the inviter's trust toward the target, so previously Bregos's
trust toward the smaller factions was an unset 0 and he could try to
absorb them after his earliestRoundForInvitation passed.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 20:27:26 -07:00
ab44d53b60 Point tutorial highlight at the Fight button on the battle progress panel (#6674)
The opening tutorial's pre-battle step instructed the player to click
"Battle!" and highlighted "GoToBattleButton", but that UI was replaced
by per-battle Fight buttons on the BattleProgressPanel. The dialogue now
references "Fight!" and BattleProgressRowController dynamically registers
its action button as "FightButton" with the tutorial target registry while
the row is in the fightable state, unregistering otherwise (and on
destroy) to avoid stale highlight targets.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 20:03:09 -07:00
02cffbdccb Check off completed tutorial items (#6673)
The Shardok tutorial, narrative hook, and early-victory items are
already delivered by the dialogue system: tutorial_battle.json covers
combat mechanics start to finish, tutorial_opening provides Sadar's
backstory in the first scene, and surviving Tarn's attack is the
early-victory beat.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 19:52:07 -07:00
152b72d691 Load Eagle/Tarn province setup from game_parameters.json (#6671)
EagleAppearsAction had Province32Stats / Province6Stats hardcoded
alongside hardcoded battalion definitions and random hero counts —
all duplicating the corresponding entries in game_parameters.json.
Any tuning of the normal game's Ingia/Soria starting state would
silently diverge in the tutorial.

Replace the hardcoded constants with a lazy load from
GameParametersUtils.defaultExpandedGameParameters: find the
SetFaction whose head is The Eagle, derive ProvinceConfig (stats,
random hero count, battalion templates) from each occupied province,
and look up which province belongs to the Eagle vs. Tarn by primary
ruling hero name. Battalions come through BattalionConverter.fromProto
and have IDs assigned at result time.

Behavior is preserved (verified by EagleAppearsActionTest).

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 19:23:03 -07:00
ea7677e351 Add dialogue for Ranil and Elena forming their own factions (#6672)
* Add dialogue for Ranil and Elena forming their own factions

The tutorial_hero_faction_appears trigger fires when John Ranil and
Elena Fyar break off from Sadar's service to form their own factions
(Builders of a Better World, Champions of Justice) seven rounds after
The Eagle appears. The trigger had no dialogue script, so a major
narrative beat — losing two of the player's signature allies — fired
silently.

Add a 4-step dialogue: Marek frames the departures as the same
mysterious force that has been claiming the King's heroes; Ranil and
Elena each speak their reason for leaving; Marek closes by noting they
are not enemies and an alliance may be possible later.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Sharpen Marek's closing line to convey ambition

Old Marek now frames Ranil and Elena as obstacles the kingdom may need
to go through, not just former allies on different paths.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Don't blame Bregos Fyar as the realm's arsonist

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 19:15:45 -07:00
d57003e144 Add tests for EagleAppearsAction (#6670)
The TutorialStrategicEventsTest comment claimed EagleAppearsAction's
result-creation was tested in TutorialGameCreationTest, but no such
tests existed — leaving the Eagle/Tarn faction setup uncovered.

Add EagleAppearsActionTest covering: faction creation and hostility,
The Eagle hero, Tarn's faction switch and loyalty, province 32 and 6
ownership / hero placement / stats, and battalion creation. Run
against a real bootstrapped tutorial game state via
TutorialGameCreation.createTutorialGame.

Also fix the stale comment in TutorialStrategicEventsTest.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 19:10:04 -07:00
4c720983b7 Fix stale tutorial-battle origin province reference (#6669)
Doc said Tarn's attacking army originates from province 32; the
config in tutorial_parameters.json:102 has originProvinceId: 31.
Province 32 (Ingia) is unoccupied at game start and only becomes
relevant later when The Eagle appears.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:58:05 -07:00
5831dc6e7a Tutorial system doc: add missing triggers and full expected flow (#6668)
Catalog four triggers missing from the original doc:
tutorial_faction_appears, tutorial_hero_faction_appears,
tutorial_hero_departed, and tutorial_hero_departed_again (all from
OnStrategicActionResult), plus shardok_battle_reset (fired directly
from ShardokGameController, bypassing the registry).

Replace the brief expected-flow stub with the full strategic-map and
tactical-battle dialogue flow tables, plus the underlying narrative
arc, so future tutorial work has a concrete map of what fires and
when.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:12:42 -07:00
79ee1e4e28 Docs: update Small Eagle TODO and add tutorial system architecture doc (#6667)
* Update Small Eagle TODO: lobby fixes done, merge tutorial + onboarding

Mark lobby fixes complete and consolidate the tutorial and
first-session onboarding bullets into a single section, since they
overlap heavily (a guided first scenario is essentially a tutorial).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Add tutorial system architecture doc

Document the Unity tutorial system's class map, step lifecycle,
trigger catalog (with file:line citations), highlight targets,
persistence, and expected first-session flow. Calls out that the
step-based UI is currently dormant (RegisterAll early-returns) and
the dialogue system is the live path today.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:01:59 -07:00
26100acbe5 Show a proper page with a back link when a game URL is not found (#6666)
Previously /games/<id> returned a plain-text 404 with no way back to
the games list. Now renders an HTML error page through the shared
layout with a link back to /games.

Adds a generic error.html template and a renderError helper so other
handlers can use the same pattern.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 18:11:09 -07:00
0af9a11bc0 Commit missing .meta files for tracked scripts (#6665)
AddressableLoader.cs and AssetUsageAuditor.cs were committed without
their .meta files, so each dev's Unity was generating a different
local GUID. Commit the metas to lock the GUIDs so any future
prefab/ScriptableObject reference will be stable across clones.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 13:45:17 -07:00
a9ebe48a76 Align battle thermometer rows regardless of troop-count visibility (#6664)
Rows where the viewer sees troop counts (allied) render non-empty
AttackerLabel / DefenderLabel, while other rows render them empty.
The labels' LayoutElement had MinWidth=-1, so Unity fell through to
TMP's content-dependent minWidth, making the bar area's inner edges
land at different X positions across rows whenever available width
was tight.

Pin MinWidth=100 (== PreferredWidth) on both labels so their width is
content-agnostic and the bar areas line up.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 21:19:48 -07:00
a582af560d Update Gameplay scene layout (#6663)
Rebakes many UI RectTransforms in the Gameplay scene: several panels
switch to layout-driven sizing (anchors/position/size zeroed to let a
parent LayoutGroup/ContentSizeFitter drive them) and a few panels get
explicit resizes.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 20:15:15 -07:00
adminandGitHub 28f0081a86 Fix turn-mismatch reconnect during chronicle text generation (#6662)
* Report WAITING_FOR_PLAYERS while an AI is taking its turn

computeServerGameStatus only considered other human factions when
checking whether to report WAITING_FOR_PLAYERS, so when a human player
finished their turn and the server transitioned to AI play it returned
None. The client keeps its previous YOUR_TURN status when the server
sends a None update (ServerStatus is only overwritten when non-null)
while HandleAvailableCommands clears commands on the same update, so
CheckForTurnMismatch fired a spurious reconnect after its 3s grace.

Pass all other faction IDs (human + AI) into computeServerGameStatus
so WAITING_FOR_PLAYERS is reported whenever any other player has
commands to act on.

* Count unrequested (queued) texts in hasIncompleteTextsAccessibleTo

Chronicle texts begin their life in unrequestedTexts and only move to
incompleteTexts once withMarkedRequested fires as the LLM request
actually starts. If computeServerGameStatus ran during that window -
after the player's commands had already cleared but before the LLM
request had been kicked off - hasIncompleteTextsAccessibleTo returned
false, the status fell through to None, and the client kept its stale
YOUR_TURN while its commands were cleared on the same update. That is
the actual trigger for the 3s turn-mismatch reconnect we kept chasing:
waiting for the chronicle text to start streaming, not waiting for an
AI turn.

Include 'unrequested' alongside 'incomplete' in both the in-memory
default implementation and the SQLite EXISTS query so we report
GENERATING_TEXT for the full queued + generating window.
2026-04-22 19:08:41 -07:00
adminandGitHub fe6b50b055 Unify ServerGameStatus reported on re-subscribe with post-result path (#6661)
The re-subscribe path in HumanPlayerClientConnectionState.streamUpdates
was computing ServerGameStatus using simpler logic than
humanClientsAfterPostingResults: it only reported YOUR_TURN (when the
player had commands) or None otherwise. When a client re-subscribed
while another player was taking their turn, a battle was in progress, or
chronicle text was generating, the server sent serverGameStatus=None and
empty availableCommands. The client cleared its command state but kept
the stale YOUR_TURN status from the previous update (ServerStatus is
only overwritten when non-null), which tripped CheckForTurnMismatch
after its 3s grace and triggered a spurious reconnect.

Extract GameController.computeServerGameStatus as a single source of
truth, and route it through HumanPlayerClientConnectionState.apply and
through rewindTo so all three paths agree on
BATTLE_IN_PROGRESS / YOUR_TURN / GENERATING_TEXT / WAITING_FOR_PLAYERS.
2026-04-22 07:26:10 -07:00
4ee0230b18 Add failing test for fleeing army at hostile province (#6660)
* Add failing test: fleeing army at hostile province should not shatter

A defender that fled a battle lands at its pre-selected flee province
with fleeProvinceId cleared. If that province has since been conquered
by the enemy, shatterStrandedArmies destroys the army outright — but the
army still has combat power and should get a chance at battle via the
normal HostileArmySetup → AttackDecision flow.

This commit flips the prior "should shatter" test to the behavior we
actually want. Fix to follow.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* Remove shatterStrandedArmies so fleeing armies can trigger battle

Fleeing armies arrive at their pre-selected flee province with
fleeProvinceId cleared (by ResolveBattleAction) so they can't flee
again. If the province has been conquered by the enemy in the meantime,
shatterStrandedArmies was destroying the retreating force outright
during ProvinceMoveResolution — even though the army still had combat
power and should get a chance at battle.

Removing the block lets these incoming armies fall through to
HostileArmySetup later in the same round, where they become hostile
army groups and trigger the normal AttackDecision → battle flow.

Also drops the now-unused ShatteredArmyUtils.shatteredStrandedArmyResult
helper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-18 08:20:27 -07:00
af75f7af74 Add UpgradeBattalionQuest AI quest handler (#6659)
Adds a deterministic chooser that walks a priority tree per turn toward
fulfilling an UpgradeBattalionQuest: arm-completes (optionally preceded by
travel and/or a safe food sale to cover the gold cost) -> train-completes
-> march in a pre-qualified neighbor battalion -> organize/top-off of the
quest battalion type -> march in an unqualified neighbor battalion ->
develop Economy/Agriculture -> train progress -> develop Infrastructure
-> arm progress. Travel is only toggled when it directly enables an
arm-completes finisher, to avoid fragile multi-turn plans.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-16 22:12:37 -07:00
614534ac54 Add BetrayAllyQuest AI quest handler (#6658)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 22:02:24 -07:00
4696d56ec6 Add FightBeastsAloneQuest AI quest handler (#6656)
* Add FightBeastsAloneQuest AI quest handler

When an unaffiliated hero offers a FightBeastsAloneQuest, the AI now
sends the weakest expendable non-leader hero to fight beasts without a
battalion. Only heroes weaker than the quest-giving hero are considered,
since the hero will almost certainly die.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add MaxExpendableHeroPowerRatio setting for FightBeastsAloneQuest

Hero must have power at most 75% of the quest-giving hero's power to
be considered expendable, ensuring the trade is clearly worthwhile.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add MaxExpendableHeroPowerRatio to settings.tsv and regenerate loader BUILD

The new setting was added to the settings BUILD.bazel but was missing from the
TSV source file, causing the auto-generated settings_loader to lack the dep.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 21:47:13 -07:00
4af198fe1a Add BattalionDiversityQuest AI quest handler (#6657)
* Add BattalionDiversityQuest AI quest handler

When an unaffiliated hero offers a BattalionDiversityQuest, the AI now
hires one battalion of a type it doesn't already have. Only types where
the province meets development requirements are considered, and the
province must have sufficient gold and food surplus.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Only hire battalion when it would reach 3+ distinct types

The quest requires 3+ different types at near-full capacity. Skip
hiring if the province has fewer than 2 existing types, since adding
one more wouldn't reach the required 3.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 21:42:40 -07:00
e74e26f191 Update AI quest completion plan with prioritized backlog (#6655)
Reorganize the "Does Not Attempt" section into a prioritized plan for
future implementation and a list of quests not planned for active
pursuit.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 12:55:25 -07:00
dadb374143 Prefer CrackDown for riots when SuppressRiotByForceQuest exists (#6654)
When an unaffiliated hero has a SuppressRiotByForceQuest and the faction
has battalions available, the AI now prefers CrackDown over Give when
handling riots. This modifies the existing riot handler priority rather
than adding a quest command chooser, since riot handling runs before
FulfillQuestsCommandSelector.

The AI estimates survival odds against a 90th-percentile riot before
committing to CrackDown, and prefers non-leader heroes to avoid risking
the faction head.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 11:22:07 -07:00
5bccde82ac Add ApprehendOutlawQuest AI quest handler (#6653) (#6653)
Matches the quest's target outlawHeroId against available outlaws in the
province and issues an ApprehendOutlaw command when found.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 09:46:39 -07:00
b0c7c57402 Add ReconSpecificProvincesQuest AI quest handler (#6652) (#6652)
Higher priority than the count-based ReconProvincesQuest since reconning
a specific province also counts toward generic recon counts. Prefers
targets not yet reconned by the faction.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 09:26:59 -07:00
f6850fc838 Add ReconProvincesQuest AI quest handler (#6651)
* Add ReconProvincesQuest AI quest handler

When an unaffiliated hero has a ReconProvincesQuest, the AI now issues
a Recon command to reconnoiter a province, helping fulfill the quest.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Prioritize recon target provinces in ReconProvincesQuestCommandChooser

Sort candidates by (isNeighbor, isHostile, notRecentlyReconned) to
prefer hostile neighboring provinces that haven't been scouted recently,
matching the prioritization pattern from MidGameAIClient.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Deprioritize unowned provinces in recon target selection

Unowned provinces (no ruling faction) are now sorted last, even if
they're neighbors, since reconning owned hostile provinces is more
strategically valuable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 09:15:28 -07:00
2f783f7ab0 Add GrandArmyQuest AI quest handler (#6650)
* Add GrandArmyQuest AI quest handler

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Address review: extract helper, use flatMap/inside, verify quest fulfillable

- Extract grandArmyTarget into a private method with pattern matching
- Replace organize match with flatMap chain
- Only return command if total troops after organizing meet the quest
  target (prevents partial fulfillment)
- Replace asInstanceOf with inside() in tests
- Add test for insufficient resources to meet target

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 08:05:45 -07:00
7bdbd7ec8f Add AI quest handlers for blizzard, drought, and epidemic filtering (#6649)
* Add AI quest handlers for blizzard, drought, and epidemic own-province filtering

Create ControlWeatherQuestCommandChooser to handle StartBlizzardQuest and
StartDroughtQuest via the ControlWeather command. Update StartEpidemicQuest
CommandChooser to skip quests targeting the acting faction's own provinces.
Both handlers verify the appropriate command is available before selecting.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Address review: use inside() pattern and extract questTargets method

- Replace asInstanceOf with inside() pattern in ControlWeather and
  StartEpidemic test assertions
- Extract questTargets into a private method in
  ControlWeatherQuestCommandChooser and match directly on its result

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 07:35:23 -07:00
334a431f14 Add DevelopProvinces and MobilizeProvinces AI quest handlers (#6648)
* Add DevelopProvinces and MobilizeProvinces AI quest handlers

Implement IssueOrders-based quest command choosers so the AI can
fulfill DevelopProvincesQuest and MobilizeProvincesQuest by switching
province orders. Develop prefers non-hostile-neighbor provinces;
Mobilize prefers hostile-neighbor provinces. Mobilize is skipped when
a DevelopProvincesQuest also exists to avoid conflicting orders.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Extract ProvinceOrderQuestHelper to deduplicate order-switching logic

The Develop and Mobilize choosers shared nearly identical logic for
finding the IssueOrders command, counting current orders, partitioning
by hostile neighbors, and building the selection. Extract this into
ProvinceOrderQuestHelper.chooseOrders parameterized by target order
type, hostile-neighbor preference, and reason string.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove early returns from province order quest choosers

Use pattern matching, flatMap, and Option.when instead of early
returns for idiomatic Scala style.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-14 21:27:30 -07:00
4ba9a475da Filter out Fear from AI search when attacker is alone (#6647)
Without a teammate to capitalize on the stun, a solo attacker casting Fear
just ends its turn no closer to killing units or capturing castles. The
state scorer currently rewards the resulting morale drop on the victim,
so minimax/MCTS can pick Fear over useful actions. Prune it in
AICommandFilter with one exception: if the victim is already on a fire
tile, the stun locks them there and the burn damage supplies the
follow-up, so Fear is still worthwhile in that case.

The rule only applies to attackers — defenders legitimately use Fear to
stall, which is their win condition.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:52:30 -07:00
acb409bf3f Update AI quest completion docs to match code (#6646)
The doc was missing 11 quest handlers that were added since it was
written: all prisoner quests, TotalDevelopment, SpendOnFeasts,
SendSupplies, RestProvince, StartEpidemic, and SwearBrotherhood.
Also fixes the priority order (Alliance is last, not first).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-14 19:46:47 -07:00
0389357366 Hide [CNTL] modifier hint on iOS and Android (#6645)
There is no Ctrl key on mobile platforms, so the [CNTL] helper text
under the profession attack button is meaningless. Skip it when
running on IPhonePlayer or Android.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-14 19:06:58 -07:00
a470bb16da Hide [CNTL] helper for untargeted profession commands like Fortify (#6644)
The profession attack button group (group 5) always showed "[CNTL]"
underneath, but that hint only makes sense for targeted commands like
Reduce where the player can ctrl-click a hex. Fortify has no target,
so showing the modifier key shortcut is misleading. Now the helper
text only appears when the group has a targeted command.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-14 19:02:07 -07:00
37ac215b85 Dedupe stale ActionResultViews in EagleGameModel.HandleUpdates (#6635)
* Dedupe stale ActionResultViews by unfiltered result count on main thread

Eagle's HandleUpdates previously applied every ActionResultView it was
handed, regardless of whether those results had already been applied.
The only count-based safety net was the heartbeat SyncMismatch check,
which triggers a reconnect but does not stop an in-flight MainQueue job
from applying stale deltas first. Applying a stale ActionResultView
(e.g. re-executing VASSAL_EXILED) can corrupt client state and throw
"Duplicate unaffiliated hero".

Track a main-thread-only high-water mark _lastAppliedUnfilteredCount and
gate HandleUpdates on it: if a delivery's UnfilteredResultCountAfter is
not ahead of the high-water mark but carries results, drop them with a
[DEDUP] log line. Reset the high-water mark in HandleStartingState so
state resyncs/rewinds rebuild the baseline cleanly.

This is defense-in-depth alongside the mid-stream SUBSCRIBE fix: it
protects the main thread against any source of stale/duplicate
ActionResultView delivery, not just the specific TryPendingCommands race.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Handle mid-batch exceptions in HandleUpdates by forcing a state resync

The previous commit added a dedupe gate but assumed ActionResultView
batches were applied atomically. If HandleNewHistoryEntry throws partway
through a batch, _currentModel is left partially mutated:
_lastAppliedUnfilteredCount never advances (so future batches would
re-apply the 1..k results that did land), while _lastUnfilteredResultCount
on the gRPC thread has already advanced (so the heartbeat sync check
reports "in sync" and never schedules a reconnect). The client
invisibly corrupts and the dedupe gate itself makes the next delivery
worse, not better.

Wrap the apply loop in try/catch. On exception:
- mark the model _modelCorrupted and refuse to apply any further
  GameUpdates in ReceiveGameUpdate until a fresh StartingState arrives
- reset both _lastUnfilteredResultCount (under its lock) and
  _lastAppliedUnfilteredCount to 0 so the upcoming subscribe asks the
  server for a fresh snapshot
- report the exception via ErrorHandler so we still get a stack trace
- trigger PersistentConnection.ForceReconnect() to drive the resync

HandleStartingState clears the _modelCorrupted flag when the fresh
snapshot lands, at which point normal update processing resumes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 08:57:26 -07:00
830985e01f Run S3 archive cleanup on self-hosted runner with aws CLI (#6643)
Switches from ubuntu-latest to [self-hosted, bazel] and replaces
s3cmd with aws CLI. Installs aws via brew if not already present.
Uses DO_SPACES credentials (same key pair the Eagle server uses to
write archived games) and macOS date syntax.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 08:47:30 -07:00
a50d64ee94 Disable scheduled Bazel cache cleanup (#6642)
bazel clean races with other runners sharing the output_base on
/Volumes/remote_cache, causing "Directory not empty" failures
(4 of last 5 runs). Manual trigger preserved via workflow_dispatch.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-12 08:13:26 -07:00
b8f6b99db2 Color unit labels via TMP_Text.color instead of rich-text tags (#6640)
* Color unit labels via TMP_Text.color instead of rich-text tags

SetOneUnitLabels was building <color=#...>Name</color> / <b> wrapped
strings on every update. Since each label is rendered in a single color,
setting TMP_Text.color directly is cheaper (no per-update string
concatenation, no rich-text tag parsing) and safer (type-checked Color
instead of hex string formatting). Secondary-label bold is now a font
style set once at cell creation.

SetUnitInfoLabels now takes an explicit Color parameter; all four
callers updated.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Disable richText on hex-grid labels

None of the hex-grid TMP labels (hero names, battalion sizes, odds
percentages, action points, coord debug strings) use rich-text tags
after the previous commit. Disabling richText in the shared label
factory skips TMP's per-update tag-scanning pass and makes the labels
robust against accidental '<' characters in localized text.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 21:25:38 -07:00
c340f2b79d Color retargetable mages purple in battle UI (#6639)
Adds a third unit-label color in Shardok battles: purple (#8000FF) for a
player's mage that has already picked a meteor target but is still in the
Target state and could retarget on the same turn. Blue/black remain for
"has commands" / "no commands".

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 13:37:29 -07:00
c94422f1cf Clear focus province when faction loses ruler (#6638)
* Clear focus province when faction loses ruler to keep state valid

RuntimeValidator requires that every faction's focusProvinceId points
to a province it rules. ProvinceConqueredAction and
EndPlayerCommandsPhaseAction already emit ChangedFactionC with
clearFocusProvinceId for their respective pathways, but other pathways
(hero departures, battle casualties leaving a province unruled, etc.)
reach the applier's fixRulerIfNeeded hook without any faction-side
cleanup. The next validation pass then crashes with "Unowned focus
province for faction ...".

Clear the stale focus alongside fixRulerIfNeeded in the applier so any
ChangedProvinceC that removes or transfers a ruling faction also drops
the now-invalid focus pointers. The negative case (same ruler, just
losing some heroes) is preserved so active focuses aren't dropped
unnecessarily.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Switch to end-of-phase focus cleanup instead of applier side-effect

Reverts the applier-level focus-clearing added in the previous commit.
Modifying factions as a side-effect of applyChangedProvinceC violates
the event-sourcing model: every game state change should be described
by an ActionResult, not implicit in the applier.

New approach, matching the pattern used by other
EndPlayerCommandsPhaseAction-style cleanups:

- RuntimeValidator.validateFactions now only enforces the "focus must
  be an owned province" invariant during PlayerCommands. Other phases
  may legitimately leave a stale focusProvinceId in transit (e.g.
  fixRulerIfNeeded silently clears rulingFactionId after hero
  departures or battle casualties).

- EndVassalCommandsPhaseAction is the sole entry point into
  PlayerCommands. Its final ActionResultC now carries
  ChangedFactionC(clearFocusProvinceId = true) for every faction
  whose focus province is no longer ruled by it, so the invariant
  holds when the validator re-engages.

- Removes the three applier-level tests that exercised the reverted
  side-effect, and adds EndVassalCommandsPhaseActionTest covering the
  new cleanup behavior (unruled focus, focus taken by another
  faction, and focus still held).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 10:10:08 -07:00
4b4a4e7dc6 Don't shatter stranded armies arriving at unoccupied provinces (#6637)
shatterStrandedArmies only checked whether an incoming army's destination
was not its own faction's territory. Since isFriendlyMove does
`province.rulingFactionId.contains(...)`, unoccupied provinces (None)
also returned false, so any already-retreated army (fleeProvinceId = None)
arriving at an unoccupied province was spuriously shattered with a
"nowhere to withdraw to" notification.

Add an explicit `rulingFactionId.isDefined` guard so arrivals at
unoccupied provinces fall through to the normal uncontested conquest
flow.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 19:54:55 -07:00
aba582bd10 Stop mid-stream SUBSCRIBE on stale command token to prevent duplicate updates (#6634)
TryPendingCommands' stale-token branches called StreamOneGameAsync to
"refresh state" when a pending command's token was behind the current
token. This sent a SUBSCRIBE(unfilteredCount=N) over the active stream,
which caused the server to replay history.since(N) as a new
ActionResultResponse while normal updates were still in flight.

Those re-delivered ActionResultViews were then applied a second time on
the main thread, which could surface as (e.g.) "Duplicate unaffiliated
hero N in province M" when a VASSAL_EXILED action ran twice.

The refresh is unnecessary: we only reach the stale-token branch because
an ActionResultResponse already delivered the newer token and its
updates were applied. Drop the stale command without re-subscribing.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 18:40:38 -07:00
a7d3b2b421 Fix nonsensical "over X months" in supply/feast quest descriptions (#6636)
The divination and quest-ended prompts for SendSuppliesQuest and
SpendOnFeastsQuest both said "over $componentCount months", but
componentCount on these quests equals the total food/gold (since the
counter is incremented by units delivered, not months elapsed). This
produced confusing output like "send 1337 food over 1337 months".

Drop the time clause — these quests are purely cumulative totals.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 16:46:59 -07:00
f6ff303ba9 Catch exceptions in ReceiveGameUpdate to avoid silent state corruption (#6633)
When an exception propagates out of an async-void lambda enqueued to
MainQueue, it goes through AsyncMethodBuilderCore.ThrowAsync to Unity's
SynchronizationContext, which logs it but cannot undo the partial state
changes already applied by the failing update. Subsequent updates then
apply diffs on top of corrupt state, cascading further errors until the
client is effectively unusable.

Wrap ReceiveGameUpdate at all four call sites in HandleGameUpdate so
exceptions are caught at the source, logged via Debug.LogException
(triggering the in-game ErrorHandler panel) and the file logger, and the
enclosing lambda completes normally. TryPendingCommands and timing logs
still run, keeping the MainQueue pump healthy.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 07:14:40 -07:00
5813bc9500 Restore missing VelociraptorColor1/2 prefabs (#6632)
VelociraptorEffect.prefab's animalPrefabs array references two
prefab GUIDs (8fa2338697777704fafc6374e9750de9 and
df9fda81573442940a2a92a3628b3cbc) from the Dino Pack Low Poly V1
asset bundle that were never committed to the repo in PR #6525.
The pack's Velociraptor.fbx, materials, and textures were added,
but the standalone .prefab files that wrap the fbx with an
Animation component and a MeshRenderer were missing.

The dangling references didn't fail until something in the live
game actually triggered ProvinceBeastsController.SpawnBeastsEffect
for a "velociraptor" beast, at which point AnimalEffect.SpawnAnimals
threw MissingReferenceException on the null array element.

Re-import the two referenced prefabs from Dino Pack Low Poly V1
(PrefabPack/PrefabSingleTexture/VelociraptorP/). The re-imported
prefab GUIDs match exactly, and the root GameObject fileIDs
(7255238702826593904 and 8644578109599837090) match the fileIDs
VelociraptorEffect.prefab already references. Internal references
(VelociraptorC1.mat material, Velociraptor.fbx mesh and animations,
VelociraptorMapAnims.controller) are all already in the repo.

The atlas-texture variant prefabs from the same pack were not
committed since nothing references them.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 22:02:49 -07:00