Compare commits

...
Author SHA1 Message Date
admin 5c874f3e53 Relax warmup command availability check 2026-06-07 19:05:35 -07:00
adminandGitHub d210cbb820 Add Connection scene migration tool (#6957)
* Add Connection scene migration tool

* Copy connection UI into split scene
2026-06-07 18:59:42 -07:00
adminandGitHub 50948bccae Persist SQLite history with base and deltas (#6956) 2026-06-07 18:52:12 -07:00
adminandGitHub 98a1c2b361 Add Connection scene readiness marker (#6955) 2026-06-07 18:35:47 -07:00
adminandGitHub 38608bd3e4 Keep shared error handler scene-owned (#6954) 2026-06-07 18:24:23 -07:00
adminandGitHub e4e43292df Default Main scene to split startup (#6952) 2026-06-07 18:16:07 -07:00
adminandGitHub 351cc6f658 Use remote persister for SQLite database uploads (#6953) 2026-06-07 18:15:10 -07:00
adminandGitHub 603e7fb071 Stop tracking Unity editor user settings (#6951) 2026-06-07 17:24:13 -07:00
adminandGitHub 0ccf0539ba Centralize connection mode visibility (#6939) 2026-06-07 17:16:34 -07:00
adminandGitHub 033e1f4675 Serialize SQLite history access internally (#6950) 2026-06-07 17:11:11 -07:00
adminandGitHub c9aa6df721 Fix Shardok model lifecycle cleanup (#6948) 2026-06-07 16:54:42 -07:00
adminandGitHub 734ea7c62e Validate SQLite downloads before loading (#6949) 2026-06-07 16:53:59 -07:00
adminandGitHub 23f29249ef Upload SQLite history from snapshots (#6947) 2026-06-07 16:14:31 -07:00
adminandGitHub eeab47e480 Persist Shardok SQLite deltas to S3 (#6944) 2026-06-07 15:48:59 -07:00
adminandGitHub 22b52f498a Use passive SQLite checkpoints for uploads (#6945) 2026-06-07 15:42:47 -07:00
adminandGitHub f403980853 Fallback build warmup binary during deploy (#6946) 2026-06-07 15:39:33 -07:00
adminandGitHub eb6fcb5ce6 Move sqlite history uploads off command path (#6943) 2026-06-07 15:01:26 -07:00
adminandGitHub 299f4625cd Map Shardok clicks through screen space (#6942) 2026-06-07 13:45:11 -07:00
adminandGitHub 84788452b3 Add JFR tracing for SQLite persistence (#6941) 2026-06-07 11:41:24 -07:00
adminandGitHub 5a81a203e8 Bootstrap Unity client from split scenes (#6935) 2026-06-07 09:11:31 -07:00
adminandGitHub 9c60652eaa Instrument Shardok battle latency (#6938) 2026-06-07 09:08:06 -07:00
adminandGitHub 9b384234d8 Clean up AI quest completion docs (#6937) 2026-06-06 18:51:15 -07:00
adminandGitHub ef591539d3 Add prisoner quest invariant coverage (#6936) 2026-06-06 17:10:32 -07:00
adminandGitHub 1db0c6b282 Clarify failed quest notification source hero (#6932) 2026-06-06 05:48:54 -07:00
adminandGitHub 61da5c1e92 Include recon counts in quest prompts (#6934) 2026-06-06 05:11:56 -07:00
adminandGitHub 2d713f4e57 Use release wording for prisoner quests (#6933) 2026-06-06 05:11:14 -07:00
adminandGitHub fab32ae871 Normalize quest LLM request ids (#6931) 2026-06-06 05:10:51 -07:00
adminandGitHub bc762f3b45 Fix quest outcome prompt name grammar (#6930) 2026-06-06 05:10:21 -07:00
adminandGitHub 7e5c5af876 Document Unity scene separation plan (#6929) 2026-06-06 04:43:26 -07:00
adminandGitHub c71c846a81 Allow text listeners to change during updates (#6928) 2026-06-05 05:39:57 -07:00
adminandGitHub cfc218ba30 Regenerate Shardok AI baselines after timeout fix (#6927) 2026-06-04 13:15:08 -07:00
adminandGitHub 29a481f7b4 Show sworn hero faction in Free Heroes panel (#6926) 2026-06-04 10:47:17 -07:00
adminandGitHub fce2a104e8 Fix break alliance imprisonment notification text (#6925) 2026-06-04 10:40:22 -07:00
adminandGitHub 0fb419cbd8 Suppress invited faction destroyed notifications (#6924) 2026-06-04 10:03:13 -07:00
adminandGitHub bf83e7bde3 Preserve Shardok selection during command updates (#6921) 2026-06-04 08:21:30 -07:00
adminandGitHub 54bfea07d4 Fix ID timeout score pollution (#6923) 2026-06-04 06:23:52 -07:00
adminandGitHub ab74172744 Only generate fulfillable prisoner quests (#6922) 2026-06-03 16:15:41 -07:00
adminandGitHub 80cbe1b60f Stream command results before phase advancement (#6920) 2026-06-03 14:17:05 -07:00
adminandGitHub 488ffbf559 Acknowledge commands before AI continuation (#6919) 2026-06-03 09:45:35 -07:00
adminandGitHub 50f9ccb28c Discover dynamic text editor tests (#6918) 2026-06-03 09:44:59 -07:00
adminandGitHub 34cce82cb0 Reject null dynamic render values (#6917) 2026-06-03 09:43:07 -07:00
adminandGitHub f0baa8bdba Require client text provider inputs (#6916) 2026-06-03 09:41:37 -07:00
adminandGitHub 52fe13325b Require generated text listener inputs (#6915) 2026-06-03 09:41:13 -07:00
adminandGitHub de15e2a66a Reject null dynamic placeholder entries (#6914) 2026-06-03 09:33:41 -07:00
adminandGitHub a506abae98 Send human command results before AI continuation (#6912) 2026-06-03 09:26:23 -07:00
adminandGitHub b43406b7c7 Require dynamic text binding inputs (#6913) 2026-06-03 09:25:13 -07:00
adminandGitHub 919990a95c Require parsed dynamic template text (#6911) 2026-06-03 09:18:36 -07:00
adminandGitHub 48162b20c0 Require dynamic placeholder fallback text (#6910) 2026-06-03 09:07:42 -07:00
adminandGitHub 88433e481e Clarify prisoner quest divine prompts (#6909) 2026-06-03 09:07:16 -07:00
adminandGitHub cc5eb01dba Preserve dynamic placeholder discovery order (#6908) 2026-06-03 09:03:11 -07:00
adminandGitHub d5dda77a47 Render dynamic text templates in one pass (#6907) 2026-06-03 08:47:16 -07:00
adminandGitHub 663b2b34f7 Seal dynamic text carrier types (#6906) 2026-06-03 08:17:18 -07:00
adminandGitHub 1e936374b0 Clean up stale AI scoring experiments (#6905) 2026-06-03 08:10:42 -07:00
adminandGitHub 8adc8953cf Centralize dynamic placeholder token parsing (#6904) 2026-06-03 08:08:52 -07:00
adminandGitHub ea5a16ba6b Promote expected-impact archery scoring (#6902) 2026-06-03 07:45:50 -07:00
adminandGitHub b4fae126ef Run all dynamic text editor tests (#6903) 2026-06-03 07:42:58 -07:00
adminandGitHub d468037358 Avoid ascii identifier assumption in placeholder audit (#6901) 2026-06-03 07:17:25 -07:00
adminandGitHub 49f9e53be8 Use unicode placeholder validation in audits (#6900) 2026-06-03 07:17:12 -07:00
adminandGitHub 2c2e405ebc Validate dynamic text placeholder names (#6899) 2026-06-03 07:01:37 -07:00
adminandGitHub b49132e3de Evaluate target-aware archery scoring (#6876)
* Evaluate target-aware archery scoring

* Refine target-aware archery experiment

* Record broader archery scoring evaluation

* Record future-position archery experiment

* Evaluate expected-impact archery scoring
2026-06-03 06:54:58 -07:00
adminandGitHub 340bd806fa Type dynamic text binding keys (#6898) 2026-06-03 06:52:44 -07:00
adminandGitHub 31e6277d87 Centralize indexed riot placeholders (#6897) 2026-06-03 06:52:10 -07:00
adminandGitHub e17115ee07 Type faction display placeholders (#6896) 2026-06-03 05:35:52 -07:00
adminandGitHub 09023e9f1f Remove unused faction leader template helper (#6895) 2026-06-02 22:05:40 -07:00
adminandGitHub b82c6a5dd8 Share ARN victim hero descriptions (#6894) 2026-06-02 21:54:20 -07:00
adminandGitHub b702f1f8bd Audit notification dynamic text placeholders (#6893) 2026-06-02 19:43:47 -07:00
adminandGitHub 9beb308b80 Type dynamic text placeholder names (#6892) 2026-06-02 19:28:35 -07:00
adminandGitHub 7f3b3b65a3 Use typed captured hero executed placeholders (#6891) 2026-06-02 19:04:33 -07:00
adminandGitHub 902513d0b5 Use typed captured hero imprisoned placeholders (#6890) 2026-06-02 19:04:17 -07:00
adminandGitHub 0ddfeff937 Use typed ransom paid notification placeholders (#6882) 2026-06-02 18:58:33 -07:00
adminandGitHub d540ed425f Use typed ransom rejected notification placeholders (#6883) 2026-06-02 18:58:18 -07:00
adminandGitHub ed636ef358 Use typed invitation ambassador notification placeholders (#6884) 2026-06-02 18:58:02 -07:00
adminandGitHub e5590bc848 Use typed truce ambassador notification placeholders (#6885) 2026-06-02 18:57:48 -07:00
adminandGitHub 5eb4ca38c9 Use typed alliance ambassador notification placeholders (#6886) 2026-06-02 18:57:29 -07:00
adminandGitHub f65e03137f Use typed break alliance ambassador placeholders (#6887) 2026-06-02 18:57:13 -07:00
adminandGitHub 35144f95fb Use typed captured hero returned placeholders (#6888) 2026-06-02 18:56:52 -07:00
adminandGitHub 5fd4182245 Use typed captured hero exiled placeholders (#6889) 2026-06-02 18:56:34 -07:00
adminandGitHub ffbdb5d5c7 Use typed prisoner exchange notification placeholders (#6881) 2026-06-02 16:28:59 -07:00
adminandGitHub b9b4d5254f Use typed vassal rise notification placeholders (#6880) 2026-06-02 16:28:39 -07:00
adminandGitHub e2a2a64204 Use typed profession notification placeholders (#6879) 2026-06-02 16:28:16 -07:00
adminandGitHub 30d8f8575a Use typed hero departure placeholders (#6878) 2026-06-02 16:14:55 -07:00
adminandGitHub 4cdd9371c6 Use typed faction head placeholders (#6877) 2026-06-02 16:10:16 -07:00
adminandGitHub f23e81dc52 Use typed prisoner status placeholders (#6875) 2026-06-02 16:06:12 -07:00
adminandGitHub 3de29fd23e Use typed outlaw apprehension placeholders (#6874) 2026-06-02 15:54:16 -07:00
adminandGitHub 52143a9481 Use typed food warning placeholders (#6873) 2026-06-02 15:44:05 -07:00
adminandGitHub 7a5185f6bf Use typed brotherhood notification placeholders (#6872) 2026-06-02 15:32:41 -07:00
adminandGitHub 8ac97cda58 Use typed placeholders in simple notifications (#6871) 2026-06-02 15:11:14 -07:00
adminandGitHub 06e82a84cd Systematize Shardok AI battle experiments (#6870) 2026-06-02 14:59:28 -07:00
adminandGitHub abfd27b495 Use typed prisoner notification placeholders (#6869) 2026-06-02 14:57:21 -07:00
adminandGitHub abb4504355 Use typed quest notification placeholders (#6868) 2026-06-02 14:38:34 -07:00
adminandGitHub 5cb1b155cd Fix riot killed hero placeholders (#6867) 2026-06-02 14:31:04 -07:00
adminandGitHub d258e65a6f Audit inline dynamic text template parsing (#6866) 2026-06-02 14:21:01 -07:00
adminandGitHub 9005ddf00c Type ambassador imprisonment templates (#6865) 2026-06-02 14:08:41 -07:00
adminandGitHub fd66a5d4dd Type ransom dynamic text templates (#6864) 2026-06-02 14:00:21 -07:00
adminandGitHub 1d06fa4368 Type riot dynamic text template construction (#6863) 2026-06-02 13:43:43 -07:00
adminandGitHub 9fdeb07d9c Type branch-selected dynamic text templates (#6862) 2026-06-02 13:33:24 -07:00
adminandGitHub 9893a79296 Type simple dynamic text template locals (#6860) 2026-06-02 12:48:17 -07:00
adminandGitHub 05f17ca569 Fix registry cleanup workflow (#6861) 2026-06-02 12:36:59 -07:00
adminandGitHub 7652b798a8 Regenerate AI battle baseline data (#6859) 2026-06-02 12:36:02 -07:00
adminandGitHub e27cbf1143 Require streaming dynamic notifications to use templates (#6858) 2026-06-02 12:10:26 -07:00
adminandGitHub 4276a211a0 Fix AI battle simulator unit capabilities (#6857) 2026-06-02 12:07:09 -07:00
adminandGitHub 0ebb240f6f Require dynamic notification constructors to use templates (#6856) 2026-06-02 12:00:34 -07:00
adminandGitHub 07bf5fc72f Add dynamic text binding validation tests (#6855) 2026-06-02 11:25:12 -07:00
adminandGitHub 09fb31fad4 Require dynamic text bindings to use templates (#6854) 2026-06-01 21:52:50 -07:00
adminandGitHub 989915a62d Remove unused ARN notification LLM message locals (#6853) 2026-06-01 21:52:24 -07:00
adminandGitHub 1f6ba6ff1f Fix AI random command sampling (#6852) 2026-06-01 19:58:01 -07:00
adminandGitHub f7942f67fd Separate dynamic template literals (#6850) 2026-06-01 17:04:10 -07:00
adminandGitHub a01935d1f7 Redo Shardok scoring experiments with hero-only units (#6845) 2026-06-01 08:40:14 -07:00
adminandGitHub be673810f6 Fix ransom placeholder validation (#6851) 2026-06-01 06:43:14 -07:00
adminandGitHub fcc21b1d5c Validate dynamic text placeholders (#6848) 2026-06-01 06:32:27 -07:00
adminandGitHub 234979c2f6 Avoid duplicate ready-to-join notifications (#6849) 2026-05-31 22:01:00 -07:00
adminandGitHub 806cdf4d68 Centralize dynamic placeholder factories (#6847) 2026-05-31 21:49:04 -07:00
adminandGitHub befd7df406 Require typed dynamic placeholders (#6846)
* Require typed dynamic placeholders

* Fix captured hero placeholder migration
2026-05-31 21:38:52 -07:00
adminandGitHub fc3c88e6e6 Extract dynamic text binding (#6844) 2026-05-31 18:56:01 -07:00
adminandGitHub 94a7f01b35 Avoid freezing placeholder notification text (#6843) 2026-05-31 18:43:50 -07:00
adminandGitHub c1dbebb60b Keep notification names live until text loads (#6842) 2026-05-31 15:22:36 -07:00
adminandGitHub 9fa873ed53 Fix Shardok thunderstorm weather icon import (#6841) 2026-05-31 15:09:26 -07:00
adminandGitHub 816417931e Document worktree boundary rule (#6840) 2026-05-31 15:01:24 -07:00
adminandGitHub ba1b62c792 Fix zero-size units in AI battle configs (#6839) 2026-05-31 15:00:56 -07:00
adminandGitHub 4066996d77 Face beast visuals toward camera on spawn (#6838) 2026-05-31 14:30:52 -07:00
adminandGitHub 1651c362fa Fix standard AI timeout and scatter scoring (#6837) 2026-05-31 13:11:36 -07:00
adminandGitHub 10552ac843 Record ID scoring benchmark baseline (#6832)
* Record ID scoring benchmark baseline

* Add real battle benchmark subset

* Record all real battle scoring matrix

* Record close battle scoring experiments

* Correct real battle benchmark round-limit results

* Document Shardok scoring benchmark baseline
2026-05-31 08:12:52 -07:00
adminandGitHub b93bfc745a Remove obsolete MCTS integration assertions (#6836) 2026-05-31 08:03:16 -07:00
adminandGitHub a539740046 Remove normalized Shardok AI scoring (#6835) 2026-05-31 07:51:34 -07:00
adminandGitHub f0f22b7818 Document PR timing guidance (#6834) 2026-05-31 07:46:07 -07:00
adminandGitHub 0f7e8d201d Fix artifact storage check for expired artifacts (#6833) 2026-05-31 04:43:55 -07:00
adminandGitHub 9dc6a691f0 Update agent workspace guidance (#6830) 2026-05-30 19:21:45 -07:00
adminandGitHub cae2cf4e07 Avoid json4s reflection for admin history (#6829) 2026-05-30 19:21:20 -07:00
adminandGitHub 3e58063303 Add saved-state AI battle benchmark support (#6831) 2026-05-30 19:19:46 -07:00
adminandGitHub 1f0d70ccb2 Add AI battle scoring benchmark summaries (#6828) 2026-05-30 18:41:31 -07:00
adminandGitHub 38cf715f86 Add Shardok weather condition icon (#6817) 2026-05-30 18:36:55 -07:00
adminandGitHub 8bd118759a Fix AI battle simulator config handling (#6827)
* Fix AI battle simulator config handling

* Stabilize MCTS setup reserve filtering
2026-05-30 14:36:40 -07:00
adminandGitHub 04d2e2d0cc Add repository agent instructions (#6826) 2026-05-30 14:35:56 -07:00
adminandGitHub 454d4a4e12 Fix low food warnings with incoming supplies (#6825)
* Fix low food warning with incoming supplies

* Fix low food shipment forecast invariants
2026-05-30 12:47:58 -07:00
adminandGitHub 6ee0485a05 Normalize MCTS UCB action priors (#6824) 2026-05-30 10:25:56 -07:00
adminandGitHub cffc11ef5c Report terminal winners to MCTS (#6823) 2026-05-30 10:20:36 -07:00
adminandGitHub 81f0eca49a Account for unvisited MCTS chance outcomes (#6822) 2026-05-30 10:19:08 -07:00
adminandGitHub 7a99609383 Expand all MCTS chance outcomes (#6821) 2026-05-30 10:14:45 -07:00
adminandGitHub cf72e50e49 Key MCTS legal action cache by root role (#6820) 2026-05-30 10:12:19 -07:00
adminandGitHub baf2dd184d Fix MCTS filtering for opponent turns (#6819) 2026-05-30 09:56:04 -07:00
adminandGitHub f60bcc4fa1 Delete iOS handoff artifact after extraction (#6818) 2026-05-30 09:45:24 -07:00
adminandGitHub b7e6b6a0e7 Double notification beast visual scale (#6816) 2026-05-29 20:51:33 -07:00
adminandGitHub 7101b83166 Label scoped feast quests in Unity (#6815) 2026-05-29 20:27:18 -07:00
adminandGitHub 3052b65282 Implement scoped feast quests (#6814) 2026-05-29 20:11:43 -07:00
adminandGitHub bc0b85e86a Add scoped feast quest proto fields (#6813)
* Add scoped feast quest proto fields

* Decode scoped feast quest proto fields
2026-05-29 20:07:03 -07:00
adminandGitHub 408979fd80 Highlight ransom participant factions (#6811) 2026-05-29 19:54:34 -07:00
adminandGitHub 0bc84928c7 Add Scala staging runtime to Eagle server (#6810) 2026-05-29 18:44:28 -07:00
adminandGitHub b475e806bd Use new hero data for ready-to-join notifications (#6809) 2026-05-29 18:44:05 -07:00
adminandGitHub b987277f8b Skip stale ready-to-join notifications (#6808) 2026-05-29 18:29:10 -07:00
adminandGitHub 2536e43e56 Apply Xcode sync to all macOS Bazel builds (#6807) 2026-05-29 18:10:24 -07:00
adminandGitHub ff7fcbcac8 Harden SQLite persistence edge cases (#6804) 2026-05-29 17:17:03 -07:00
adminandGitHub a28d4d6631 Defer notification beast loading until panel is active (#6806) 2026-05-29 17:16:11 -07:00
6cb4591c4e Store tutorial results as a SQLite .db instead of a Scala literal (#6803)
Follow-up to #6802 that swapped the proto-shape JSON resources for a
generated `ExpansionTutorialResults.scala` (820-line `Vector` literal).
Replaces that with the originally-intended shape from the design
discussion: a `tutorial_expansion.db` resource in the same format as a
live `game.db`, read back via `SqliteHistory`.

Changes:

- New `tutorial_expansion.db` (~500KB binary resource) generated from
  the previous `ExpansionTutorialResults.results` by running them
  through `withNewResults` with a placeholder resulting state. (The
  placeholder is recorded but never read — `allActionResults`
  reconstructs each `ActionResultC` from the decomposed per-entity
  tables only.)
- New `SqliteHistory.allActionResults`: public method that returns
  every `ActionResultT` in the db without folding through the applier.
  Skips replay/snapshots, so it's safe on a db whose resulting-state
  columns are placeholders.
- `TutorialPhaseResultsLoader` rewritten as 10 lines: copy resource
  to tempfile, `SqliteHistory.loaded(...).allActionResults`. Same
  public surface as before.
- Deleted: `ExpansionTutorialResults.scala` (820 generated lines),
  `TutorialDbGenerator.scala` (one-shot tool, job done).
- BUILD deps on the loader collapse from ~30 to 3 — the loader no
  longer references domain types directly.

The generator stayed alive long enough to cross-validate the .db
round-trip against the Scala source (the test asserted
`expansionResults shouldBe ExpansionTutorialResults.results`); that
passed before this PR was finalized, so the round-trip is faithful.
The cross-validation assertion goes away with the Scala source.

Net: 4 source files changed (+540 / -3050 lines), plus the new
binary resource. `TutorialPhaseResultsLoaderTest` 1/1 green; full
Scala suite 225/225 green.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 16:37:08 -07:00
adminandGitHub 9629bfd9de Show beast visuals on appearance notifications (#6800)
* Show beast visuals on beast appearance notifications

* Wire beast visual container in gameplay scene

* Let notification beast previews render inside popups

* Tune notification beast preview framing
2026-05-29 16:08:21 -07:00
e11ddf3e21 Retire ActionResultProtoConverter (#6802)
Closes the converter-chain retirement that PRs #6798, #6799, and #6801
chipped away at. The last remaining caller of
`ActionResultProtoConverter.fromProto` was
`TutorialPhaseResultsLoader`, which read proto-shape JSON tutorial
resource files and walked them through the converter.

Replaced the resource-based loader with compile-time-baked Scala
constants:

- New `ExpansionTutorialResults.scala` (820 lines, generated) contains
  the same `Vector[ActionResultT]` that the JSON used to produce, but
  as a literal expression.
- New `TutorialResultsCodegen` was the one-shot generator that walked
  an `ActionResultC` via `Product` introspection + the Scala 3 enum's
  superclass reflection, emitting fully-qualified Scala source. Used
  once to convert the two existing resource files; deleted in this
  commit since its job is done.
- `TutorialPhaseResultsLoader` is now ~10 lines: just references
  `ExpansionTutorialResults.results` and an empty mobilization vector
  (the original mobilization JSON was `{}`).

Deleted:

- `ActionResultProtoConverter.scala` + BUILD target
- `ChangedHeroConverter.scala` + BUILD target (only caller was the
  parent converter)
- `ChangedFactionConverter.scala` + BUILD target (same)
- `TutorialPhaseResultsExtractor.scala` (broken anyway — it read
  `.e0a` chunk files through `PersistedHistory` machinery that #6798
  deleted)
- `expansion_results.json`, `mobilization_results.json`, and their
  resource BUILD target

BUILD churn: visibility widened on ~10 `model/state` and
`model/action_result/concrete` targets so the new
`tutorial_phase_results_loader` can see them. Two unused
`action_result_proto_converter` deps fell out of `service` and
`service/new_game_creation`. Dependency cleanup is minor compared to
the deletions; net ~4,000 lines removed.

`json4s` reflection on Scala 3 case classes is broken in this
codebase (the `ScalaSigReader` is Scala 2-only and throws
`NoClassDefFoundError: scala/quoted/staging/package$`), which is why
the codegen used `Product` introspection + JVM-class-name parsing
instead of a runtime JSON serializer.

Verification: full Scala suite 225/225 green;
`TutorialPhaseResultsLoaderTest` still passes against the new path
(asserts the expected `generatedTextRequest.requestId` values are
preserved through the round-trip).

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 14:45:05 -07:00
bf48be685d Serialize admin action JSON from the domain ActionResultC directly (#6801)
Drops the only remaining production caller of `ActionResultProtoConverter.toProto`.

The admin history endpoint had been doing `domain → proto → JSON`:
```
val arProto    = ActionResultProtoConverter.toProto(ar)
val actionJson = writePretty(JsonFormat.toJson(arProto))
```

Switched to `writePretty(ar)` — json4s reflects on the case class
directly. The Go admin server passes `action_json` straight through to
an HTML template (no parsing), so a format change is tolerable; the
field's proto-comment "serialized as JSON" describes the previous
implementation, not a contract.

After this:
- The `getRawGameHistory` flow still uses scalapb's `JsonFormat` —
  the inputs there are raw `ActionResult` protos (loaded from the
  legacy `.e0r` admin-debug path), not domain types.
- The `getCurrentGameState` flow still uses `JsonFormat` on the
  `GameState` proto — out of scope here (it's `GameStateConverter`,
  not `ActionResultProtoConverter`).
- `game_admin_service` BUILD target drops its
  `:action_result_proto_converter` dep.

One ActionResultProtoConverter caller remains:
`TutorialPhaseResultsLoader` (reads bundled tutorial JSON resources
via `fromProto`); retiring it needs the tutorial JSON files
regenerated in a domain-shape format.

Verification: full Scala suite 225/225 green; `game_admin_service`
builds cleanly. The new JSON output format should be visually
checked against the existing admin UI history view — json4s
DefaultFormats reflection on Scala 3 enums and sum types may produce
slightly different shape than scalapb's JsonFormat did. No code
parses this JSON; the admin UI just renders it as a string.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 11:49:38 -07:00
adminandGitHub ded1939106 Persist tutorial dialogue progress per game (#6778) 2026-05-29 11:20:25 -07:00
3b378a6d02 Delete InMemoryHistory.fromResults (#6799)
Removes one of the three remaining ActionResultProtoConverter callers
left after #6798. `fromResults(Vector[ActionResult])` only existed as a
test convenience that walked proto results through
`ActionResultProtoConverter.fromProto`. Its 17 call sites — across
`InMemoryHistoryTest`, `SqliteHistoryTest`, and `GameControllerTest` —
have been switched to the existing `fromScalaResults(Vector[ActionResultT])`
sibling, with each test's local `makeActionResult` helper now returning
domain `ActionResultC` instead of the proto.

After this:
- `InMemoryHistory.scala` no longer imports `ActionResultProtoConverter`
  or the internal `ActionResult` proto.
- `in_memory_history` BUILD target drops the proto + converter deps;
  three test targets drop the proto deps that fell to unused under
  strict-deps.
- The two remaining ActionResultProtoConverter callers are
  `GameAdminServiceImpl` (admin JSON serialization) and
  `TutorialPhaseResultsLoader` (tutorial resource loading), both of
  which need bigger replacements before they go.

Verification: full Scala suite 225/225 green.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 11:19:27 -07:00
786608a6ec Retire PersistedHistory (#6798)
Closes out the legacy non-SQLite history implementation. SqliteHistory
has been the sole runtime backend since 4.5h.5d shipped; the only
remaining caller of PersistedHistory was the RemoveActions admin tool,
whose BUILD target was already commented out.

Changes:
- RemoveActions rewritten on SqliteHistory: open game.db directly,
  call truncateTo(count - countToTruncate), close. Persister-based
  chunk-deletion logic falls away. BUILD target re-enabled with the
  new (much smaller) dep set.
- PersistedHistory.scala, PersistedActionResult.scala, and
  PersistedHistoryTest.scala deleted; their BUILD targets removed.
- games_manager's transitive `:persisted_history` dep removed (was
  unused even before this PR).
- Stale doc-comment references to PersistedHistory in SqliteHistory
  and FullGameHistory rephrased to stand on their own.

Out of scope: ActionResultProtoConverter (and the per-entity converter
chain) still exists. It's no longer used by any history path, but
remains alive for GameAdminServiceImpl's admin JSON serialization and
TutorialPhaseResultsLoader's resource loading. Retiring those is a
separate effort with bigger blast radius (custom JSON serializer for
ActionResultC, regenerated tutorial JSON resources).

Verification: full Scala suite 225/225 green (was 226 with the
deleted PersistedHistoryTest); RemoveActions builds.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 10:20:07 -07:00
7526817a3b Phase 4.5i (cont.): delete v3-v14 per-entity backfills (#6797)
Continues #6791 (which removed the v15-v20 column/vector-table
backfills). Same predicate: after #6787 every persisted game.db is at
v >= 21 in S3, and #6784 dropped the `payload` column. The v3-v14
per-entity backfills (which read each existing `action_results.payload`
to populate the decomposed tables) are unreachable on any healthy game
and cannot run anyway with `payload` gone.

Removed:
- `def backfill(connection: Connection): Unit` from each of the 11
  per-entity table writers (ChangedHero/Faction/Battalion/Province +
  NewBattalion/Faction/Hero/Province + Notification +
  GeneratedTextRequest + ClientTextVisibilityExtension).
- The corresponding `<Writer>.backfill(connection)` calls from
  applyV3-V14 in SqliteHistory. Each migration collapses to a single
  `execEach(connection, schemaStatements)`.
- applyV6ReapplyChangedEntityDecomposition (#6738 hotfix) keeps its
  DROP+CREATE schema reset for the ChangedHero/Faction tables; the
  re-backfill step is gone. For pre-#6737 games it would still fix
  the table shape but leave them empty — same "schema v < 15 is no
  longer supported" caveat as for v15-v20.
- 15 `"<entity> vN backfill"` tests in SqliteHistoryTest and 3
  orphaned section banners (v3, v4, v5).
- Unused proto imports in 11 writer files; unused private helpers
  (`factionRowCount`) and unused imports in SqliteHistoryTest.
- ~40 BUILD deps that fall out as unused: each writer no longer needs
  `internal:action_result_scala_proto` or
  `proto_converters:action_result_proto_converter`. Several writers
  needed their per-entity proto target added directly (e.g.
  `battalion_scala_proto`, `hero_scala_proto`, `faction_scala_proto`)
  because they used `.toByteArray` on the proto type — previously
  available transitively via `action_result_scala_proto`.

Verification: `sqlite_history_test` 75/75 green (90 - 15 backfill
tests deleted); full Scala suite 226/226 green.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 08:46:13 -07:00
adminandGitHub 46891abb5b Normalize remaining Unity LFS assets (#6796) 2026-05-29 08:43:01 -07:00
adminandGitHub ceed22d6de Prioritize remaining small Eagle alpha work (#6795) 2026-05-29 08:31:41 -07:00
adminandGitHub 75f35e981e Unpin Bazel workflows from specific runners (#6792) 2026-05-29 08:29:29 -07:00
adminandGitHub 76d8f07827 Keep command factory test flatbuffers alive (#6794) 2026-05-29 08:23:27 -07:00
adminandGitHub 705a36e901 Update Unity 6000.4.9 project files (#6793) 2026-05-29 08:21:19 -07:00
adminandGitHub 758ae6d44f Ensure Bazel is available in self-hosted workflows (#6785)
* Ensure Bazel is available in self-hosted workflows

* Allow Bazel CI to use Command Line Tools

* Set macOS C++ deployment target for Bazel

* Use Bazel macOS minimum OS flags

* Raise macOS Bazel deployment target for filesystem

* Ensure git-lfs is available for CI fetches

* Authenticate CI LFS fetches with workflow token

* Disable stale LFS hooks during CI checkout

* Disable LFS filters during CI checkout

* Prepare Git LFS before persistent checkout

* Harden generated Bazel rc and LFS auth

* Let Xcode sync skip without full Xcode

* Harden Unity build cache markers

* Require full Xcode for mactools sync
2026-05-29 07:52:17 -07:00
899162bbc5 Phase 4.5i: delete v15-v20 payload-parsing backfills (#6791)
After #6787 (upload-on-load) deployed and the admin-load pass pushed
every persisted game.db to v ≥ 21 in S3, the v15-v20 migration
backfills that re-derived their new columns/tables from
`action_results.payload` are unreachable on any healthy game. This PR
deletes that code so the proto dependency surface shrinks and the
"only used by backfill" file headers stop misleading future readers.

Removed:
- `backfill(Connection)` (and supporting `bindOpt*` helpers / `select`
  loops) from each of the 6 writers that populated the 4.5h.1–4
  scalars/vectors:
    - ActionResultEntityRefColumnsWriter (v15)
    - ActionResultEnumColumnsWriter (v16)
    - ActionResultNumericColumnsWriter (v17)
    - ActionResultDateBattleColumnsWriter (v18)
    - ActionResultStructuredBlobColumnsWriter (v19)
    - ActionResultVectorTablesWriter (v20)
- `applyV15`–`applyV20` collapse to a single line each — just
  `execEach(connection, ...schemaStatements)`. Doc note added that
  schema v < 15 is no longer supported (if `applyV15` ever runs on a
  non-empty `action_results` table, the new columns are left NULL and
  state diverges silently; the migration runner's `schema_version`
  gate is the only protection).
- 6 corresponding `"action_results vN backfill"` tests in
  `SqliteHistoryTest` (one per migration). The matching `vN live
  write` tests stay — those still exercise the live-write column
  binding.

BUILD dep cleanup falls out: each of those writers no longer needs
`internal:action_result_scala_proto` or
`proto_converters:action_result_proto_converter` (the
payload-parse + full-converter round-trip is gone). The remaining
narrow deps (`tutorial_phase_scala_proto`, `game_type_scala_proto`,
etc.) cover the proto-enum `.value` reads that `bindColumns` still
needs.

Verification: `sqlite_history_test` 90/90 green (96 - 6 backfill
tests deleted); full Scala suite 226/226 green.

The per-entity table backfills (v3-v14) still parse `payload` and are
out of scope here — they kept ChangedHero/Faction/Battalion games
alive across the .5c cutover, and removing them needs the same
"prove all games are at v ≥ 21 in S3" gate. Future cleanup.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 07:51:34 -07:00
adminandGitHub d174c06ddb Reduce Unity LFS asset footprint (#6789)
* Delete unused Animal pack deluxe v2 assets

* Delete unused preview and demo LFS assets

* Normalize bridge FBX assets into LFS
2026-05-29 07:51:00 -07:00
4935b81037 Upload migrated game.db to persister on load (red+green) (#6787)
* Upload migrated game.db to persister on load (red)

Prep for 4.5i (deleting v15-v20 backfill payload-parsing). Before we
can delete migration code, every persisted `game.db` needs to be at the
current schema in S3 — otherwise a server restart re-downloads a stale
blob and re-walks the old migrations.

Today `SqliteHistory.loaded` runs migrations on the local file but
nothing pushes the migrated form back to the persister until an action
is actually committed (`withNewResults` is the only upload trigger).
Result: admin-loading every game upgrades the local server's copy but
leaves S3 at the old schema, so the upgrade unwinds on restart.

This commit adds two red tests:

  1. Loading a v1 DB out of the persister with a wiped local copy must
     bump the persister's `saveCount` — i.e., the migrated bytes get
     pushed back. Today this fails because nothing in the load path
     uploads.

  2. Loading an already-current DB must NOT bump `saveCount`. Today
     this passes vacuously (the load path never uploads), so it's a
     forward-guarantee that the fix won't spam uploads on every restart
     of a healthy server.

GREEN will thread an "any pending migrations applied?" boolean out of
`Migrations.applyPending` and, when true, do a one-shot
checkpoint+upload after constructing the `SqliteHistory`.

Holding for review of the test design before I land GREEN on the same
branch.

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

* Upload migrated game.db to persister on load (green)

Thread an "any pending migrations applied?" boolean out of
`Migrations.applyPending` and through `initializeSchema`. In `loaded`,
when migrations actually ran and a persister is set, do a one-shot
checkpoint+upload so the migrated bytes propagate to S3.

Factored the WAL-checkpoint + readAllBytes + persister.save block out
of `maybeUploadToPersister` into a shared
`uploadCurrentBytesToPersister(p, nowMillis)` helper; `loaded` calls
the public no-arg variant. The `lastUploadAtMillis` field is anchored
inside the upload so the subsequent withNewResults time-based trigger
stays correct.

`create` discards the migration boolean explicitly: a fresh game has
no stale S3 form to compete with, and the first `withNewResults`
upload will be the v-current bytes anyway.

Verification: sqlite_history_test 95/95 green; full Scala suite
226/226 green.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 06:58:50 -07:00
503801e7c4 Add PerEntityWriteDispatcher with compile-time + runtime coverage guards (#6790)
Background. We just hit a production state-loss bug on a saved game:
`Province 40 has an army that should have already arrived`. Root cause:
`ChangedProvinceTableWriter` was added in 4.5b (#6725, 5/17) but its call
into `withNewResults` wasn't wired until 4.5h.5c (#6779, 5/28). For the
11 days between, every action committed had `payload` populated but
zero rows in `action_changed_provinces`. When 4.5h.5d (#6784) dropped
`payload`, those actions' changedProvinces became permanently lost.
On the affected game that's ~24k actions out of 28k.

ChangedHero and ChangedFaction had similar (hours-long) wiring gaps, but
v6 (#6741) included a re-backfill that rescued them. Every other
decomposition (4.5e/f/g/h.4) shipped writer + migration in a single PR,
so no orphan window. Only ChangedProvince bled data in production.

This PR adds two complementary guards so the same shape of bug can't
ship again:

1) New `PerEntityWriteDispatcher` object owns the fan-out to every
   per-entity decomposition writer. Its `writeAll` matches `ar` against
   the full `ActionResultC` case-class constructor pattern, binding
   every field (Vector ones by name, scalars as `_`). Adding any new
   field to `ActionResultC` breaks the constructor arity at compile
   time, forcing whoever adds the field to come here and decide
   "scalar → new column on `action_results`" or "vector → new
   per-entity table + writer + wiring".

2) New test ("withNewResults populates every per-entity decomposition
   table when given an ActionResult with one of each vector")
   constructs an ActionResult with a non-empty entry for every 17
   `Vector[_]` field on `ActionResultC`, runs `withNewResults`, and
   asserts every per-entity table has >= 1 row. Catches "wrote a
   writer but didn't call it" — which is the second variant of the
   same class of bug.

`SqliteHistory.withNewResults` now delegates to
`PerEntityWriteDispatcher.writeAll`. The previous inline foreach blocks
plus the `ChangedProvinceConverter` import move to the dispatcher.
Visibility of `model/action_result/changed_province/concrete` widened to
`//src/test/scala/net/eagle0/eagle/service:__pkg__` so the new test
can build the source `ChangedProvinceC` directly.

Memory updated: `changed_entity_decomposition_pitfalls.md` now lists
this as a third recurring pitfall with the guard documented.

Verification: `sqlite_history_test` 94/94 green; full Scala suite
226/226 green.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 06:53:56 -07:00
adminandGitHub 646c47259c Upgrade Unity project to 6000.4.9f1 (#6788) 2026-05-29 06:52:18 -07:00
4e411695f2 Phase 4.5h.5d (red+green): drop action_results.payload column (#6784)
* Phase 4.5h.5d (red): assert action_results.payload column is gone

Final 4.5h chunk: stop writing the `payload` blob and drop the column from
the SQLite schema. After .5c the read path no longer touches `payload`, so
it's now dead weight on every write. .5d closes that loop.

Two red tests:
  1. Fresh DB: `PRAGMA table_info(action_results)` must not include `payload`.
  2. v20 → v21 upgrade: a DB that has a populated `payload` column gets the
     column dropped on `SqliteHistory.loaded`, and a subsequent read still
     returns the action via `ActionResultDbReader`.

Both fail RED because the column is still present (v20 schema). GREEN will:
  - Stop binding `payload` in the `withNewResults` INSERT (and drop
    `ActionResultProtoConverter.toProto` from the write path).
  - Add migration v21 to `ALTER TABLE action_results DROP COLUMN payload`.

Holding for review of the test design before I land GREEN on the same branch.

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

* Phase 4.5h.5d (green): stop writing payload and drop the column

Final step of the 4.5x decomposition. After this commit every
ActionResultC field on disk lives in a dedicated column or per-entity
table; `action_results.payload` is gone.

Changes:
- Add migration v21: ALTER TABLE action_results DROP COLUMN payload.
  SQLite >= 3.35.0 supports DROP COLUMN; the xerial sqlite-jdbc driver
  bundles a new-enough engine.
- Remove `payload` from the withNewResults INSERT (drops the bind at
  position 6 and the ActionResultProtoConverter.toProto call) and
  renumber the trailing column positions.
- Drop the ActionResultProtoConverter import from SqliteHistory.scala
  and the corresponding sqlite_history Bazel deps
  (action_result_proto_converter, action_result_scala_proto); add
  changed_province_scala_proto, which had been pulled in transitively
  via the action_result proto.
- Delete the .5b parity test and the .5c "read path doesn't touch
  payload" test. Both queried `payload` directly to make their
  assertions; with the column gone, the assertions are moot. Their
  intent — that ActionResultDbReader assembles a faithful
  ActionResultC from the decomposed tables — is now covered implicitly
  by every test that round-trips through withNewResults + last/all.

Verification: `sqlite_history_test` 93/93 green; full Scala suite
226/226 green.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 22:09:38 -07:00
adminandGitHub 237efb9c0c Temporarily pin self-hosted CI to halfdan (#6786) 2026-05-28 22:05:35 -07:00
0368a9f24a Phase 4.5h.5c (red+green): swap read path off action_results.payload (#6779)
* Phase 4.5h.5c (red): assert read path no longer depends on payload

Continues 4.5h.5 after .5b (the ActionResultDbReader orchestrator).
This sub-PR is the read-path cutover: swap replayFrom + readActionAt +
stateAfter to use ActionResultDbReader instead of
ActionResultProtoConverter.fromProto(payload), and wire
ChangedProvinceTableWriter into withNewResults so the cutover is
correctness-complete for changedProvinces.

The cleanest single test for "read path doesn't touch payload" is to
persist an action, then corrupt its payload column (overwrite with a
1-byte garbage blob), then re-load and read. If anything in the read
path still calls parseFrom on payload, that parse throws
InvalidProtocolBufferException; the test fails. If the read path uses
ActionResultDbReader (which doesn't touch payload), the test sees the
populated fields and passes.

The test exercises both stateAfter (which replays actions to advance
state) and readActionAt (which returns the last action) via a single
SqliteHistory.last call — both must avoid touching the corrupted
payload.

This commit (red):
- No code changes to SqliteHistory; the read path still parses payload.
- One red test: persist an action with 4 populated scalar/Option fields,
  wipe payload column to x'00', reload, call last, assert the fields
  come back populated.

The GREEN commit will:
  - Swap replayFrom + readActionAt + the stateAfter inner loop to
    ActionResultDbReader.read (no more parseFrom + fromProto).
  - Wire ChangedProvinceTableWriter into withNewResults (so live actions
    populate action_changed_provinces — needed for the read path to
    return changedProvinces correctly).
  - Note: payload is still written by withNewResults (kept around as a
    safety net for one PR); .5d drops the column entirely.

Verification: sqlite_history_test 92/93 pass, 1 RED for the right
reason (parseFrom throws "Protocol message contained an invalid tag
(zero)" on the corrupted bytes).

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

* Phase 4.5h.5c (green): swap read path to ActionResultDbReader, wire ChangedProvinceTableWriter

stateAfter / replayFrom / readActionAt now go through ActionResultDbReader.read,
which assembles ActionResultC from the decomposed columns + per-entity tables
(4.5b–4.5h.4) instead of `parseFrom(payload)`. Also wires
ChangedProvinceTableWriter into withNewResults so the action_changed_provinces
table is populated by live writes (it was already populated by the 4.5b
backfill; this closes the gap for new actions). The `payload` column is still
written; it gets dropped in 4.5h.5d.

The RED test added in 6b6134afef passes now that the corrupted payload is
no longer touched on read; gave it a `newDate` so the applier (which runs
during stateAfter's replay) has a date.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 20:49:06 -07:00
adminandGitHub 39b8c3360e Tidy Bazel rc marker and Mac deploy runner label (#6782) 2026-05-28 20:05:11 -07:00
adminandGitHub c2b04c2109 Pass iOS TestFlight build between jobs (#6781) 2026-05-28 06:25:48 -07:00
adminandGitHub 875f34a624 Harden GitHub Actions workflows (#6780) 2026-05-27 22:04:56 -07:00
7f2cdbd111 Phase 4.5h.5b: ActionResultDbReader (#6777)
* Phase 4.5h.5b (red): ActionResultDbReader stub + parity test

Continues 4.5h.5 after .5a (the two missing per-entity readers). This
sub-PR adds the top-level orchestrator that will assemble a domain
ActionResultC from the 24 action_results columns + the eleven per-entity
table readers — without touching the legacy payload BLOB.

The 24 columns now on action_results (added by 4.5h.1, .2a, .2b, .2c,
.3) cover every top-level scalar/Option field of ActionResultC plus the
three structured-Option blobs (new_battle_proto / new_chronicle_entry_proto
/ new_eagle_map_proto). The eleven per-entity vectors are read via the
existing per-entity table readers:

  - ChangedBattalionTableReader, ChangedFactionTableReader,
    ChangedHeroTableReader, ChangedProvinceTableReader (last from .5a)
  - NewBattalionTableReader, NewFactionTableReader, NewHeroTableReader,
    NewProvinceTableReader
  - NotificationTableReader (readNew + readRemoved)
  - GeneratedTextRequestTableReader, ClientTextVisibilityExtensionTableReader
  - ActionResultVectorTablesReader (the five v20 vector tables, from .5a)

Parity contract with the converter-based read:
  - For every field both paths handle, this reader produces an
    ActionResultC equal to ActionResultProtoConverter.fromProto(payload).
  - newGeneratedTextRequests is the one intentional asymmetry: the
    converter drops it ("LLM text requests are not used by the
    applier"), this reader returns the populated vector from the
    decomposed table. Strictly better.
  - changedProvinces is excluded from this PR's parity test:
    ChangedProvinceTableWriter is not yet wired into withNewResults
    (that's a .5c concern). Adding it back to parity is straightforward
    once the wiring lands.

Reader is unused by production — replayFrom still goes through
ActionResultProtoConverter.fromProto(payload). The cutover lands in
.5c; the payload column gets dropped in .5d.

This commit (red):
- ActionResultDbReader stub: read returns a near-empty ActionResultC
  (only actionResultType = UnknownActionUnspecified). GREEN lands the
  real read.
- One parity test in SqliteHistoryTest: builds a rich source
  ActionResultC (one of each shape — scalar/Option columns, structured
  blobs, v20 vector tables, per-entity vectors except changedProvinces
  and newGeneratedTextRequests), persists via withNewResults, then
  asserts ActionResultDbReader.read produces the same ActionResultC as
  the converter-based read of the payload.
- Visibility widening:
  model/action_result/concrete:action_result_concrete adds
  service:__pkg__; model/proto_converters:action_result_proto_converter
  adds test/.../service:__pkg__.

Verification: sqlite_history_test 91/92 pass, 1 RED for the right reason
(stub returns near-empty AR; parity assertion fails the long structural
comparison).

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

* Phase 4.5h.5b (green): implement ActionResultDbReader

Fills in the ActionResultDbReader stub from the red commit with the
real read implementation. The parity test added in red now passes:
ActionResultDbReader.read produces an ActionResultC equal to
ActionResultProtoConverter.fromProto(payload) for every field both
paths handle.

Implementation:
- Single action_results SELECT for the 24 column values (action_result_type,
  the 4 entity-ref columns, 4 enum columns, 4 numeric Option columns,
  date pair + resolved_battle, 3 blob columns).
- Eleven per-entity reader calls (ChangedBattalion/Faction/Hero/Province,
  NewBattalion/Faction/Hero/Province, NotificationTableReader.readNew +
  readRemoved, GeneratedTextRequest, ClientTextVisibilityExtension,
  ActionResultVectorTables — readDestroyedBattalionIds/etc).
- All thirty fields plug straight into ActionResultC's case-class
  constructor — single allocation, no .copy() (the custom copy method
  uses different parameter names like `actingFaction` vs `actingFactionId`
  and `removedHeroes` vs `removedHeroIds`).

Decoding helpers:
- getOptInt / getOptLong: nullable INTEGER via JDBC's wasNull() pattern
  (getInt returns 0 for SQL NULL, indistinguishable without wasNull).
- decodeGameType: handles the (new_game_type, new_tutorial_phase) pair.
  Writer never stores UNKNOWN_GAME_TYPE (stores NULL instead), so
  fromProto's UNKNOWN→throw path is unreachable; defensive throw on
  None from CommandTypeConverter.fromProto for the same reason.
- decodeDate: handles the (new_date_year, new_date_month) pair.
  Inconsistent (one NULL) would throw IllegalArgumentException from
  Date.Month.fromInt(0), surfacing writer bugs loudly.
- Blobs use Option(rs.getBytes(...)).map(parseFrom + Converter.fromProto).

BUILD additions (green-only):
- action_result_db_reader deps: all 11 per-entity readers + 6 enum/blob
  converters + their proto packages (chronicle_entry, command_type,
  eagle_map_info, game_type, round_phase, tutorial_phase, shardok_battle)
  + Date domain type + eagle_internal_exception.

The read path is NOT swapped here — replayFrom still parses payload.
The reader is unused by production until .5c.

Verification: sqlite_history_test 92/92 pass; full Scala test suite
226/226.

Next: 4.5h.5c — swap replayFrom to use ActionResultDbReader, stop
writing payload, wire ChangedProvinceTableWriter into withNewResults.
Then .5d drops the payload column.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 08:14:40 -07:00
a466c42cd8 Phase 4.5h.5a: missing per-entity readers (#6776)
* Phase 4.5h.5a (red): missing per-entity readers (stub) + round-trip tests

Begins Phase 4.5h.5 (the final read-path-swap chunk). Per the agreed
four-slice plan:
  .5a (this PR): the two missing per-entity readers + round-trip tests
                 with their writers. Readers exist but are unused by
                 production.
  .5b:           the top-level ActionResultDbReader orchestrator +
                 parity tests asserting it produces the same ActionResultC
                 as the converter-based read path.
  .5c:           swap replayFrom to use the new reader, stop writing
                 payload.
  .5d:           drop the payload column.

The 4.5b–g per-entity readers were created alongside their writers
(paired RED+GREEN PRs). Two gaps remain:

- ChangedProvinceTableReader: ChangedProvince was the first option-B
  entity (4.5b) and its reader was deferred because nothing needed it
  until 4.5h.
- ActionResultVectorTablesReader: the v20 vector tables (4.5h.4) were
  built with only a writer because the read path hadn't started yet.

Both readers are needed by .5b's top-level orchestrator. Adding them
now closes the gap.

This commit (red):
- ChangedProvinceTableReader stub: read returns Vector.empty. Reads
  from action_changed_provinces' changed_province_proto BLOB (the
  scalar denorm columns are ignored on read; the blob is authoritative
  per the writer's contract).
- ActionResultVectorTablesReader stub: five public read methods (one
  per v20 table), all returning Vector.empty. The four primitive-ID
  methods will share an internal readIds helper in GREEN;
  readNewBattalionTypes will parse battalion_type_proto via
  BattalionTypeConverter.fromProto.
- Two red tests in SqliteHistoryTest: round-trip ChangedProvinces via
  the writer + new reader (two protos, exercises n ordering); round-trip
  all five vectors via withNewResults + new reader.
- Visibility widening: model/action_result/changed_province:changed_province
  and model/proto_converters:changed_province_converter to add the
  service main + test service packages (GREEN reader will need the
  converter).

Verification: sqlite_history_test 89/91 pass, 2 RED for the right reason
(stub readers return Vector.empty → "Vector() was not equal to Vector(17,
23)").

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

* Phase 4.5h.5a (green): implement missing per-entity readers

Fills in the two reader stubs from the red commit with real
implementations. No new tests — the round-trip tests added in the red
commit now turn green.

ChangedProvinceTableReader:
- read(connection, actionSeq): SELECT changed_province_proto ORDER BY n,
  parse each blob via ChangedProvinceProto.parseFrom, convert to domain
  via ChangedProvinceConverter.fromProto.

ActionResultVectorTablesReader:
- readDestroyedBattalionIds / readRemovedHeroIds / readRemovedFactionIds
  / readAffectedFactionIds: all delegate to the shared private readIds
  helper which does SELECT $idColumn FROM $table WHERE action_seq = ?
  ORDER BY n. Table and column names are internal constants, never user
  input.
- readNewBattalionTypes: SELECT battalion_type_proto ORDER BY n, parse
  each blob via BattalionTypeProto.parseFrom, convert via
  BattalionTypeConverter.fromProto. The type_id column is ignored on
  read — the blob is authoritative.

BUILD additions (green-only):
- changed_province_table_reader deps:
  internal:changed_province_scala_proto (for parseFrom),
  proto_converters:changed_province_converter (for fromProto).
- action_result_vector_tables_reader deps:
  common:battalion_type_scala_proto (for parseFrom),
  proto_converters:battalion_type_converter (for fromProto).

Verification: sqlite_history_test 91/91 pass; full Scala test suite
226/226.

Next: 4.5h.5b — top-level ActionResultDbReader orchestrator that uses
all the per-entity readers (plus the action_results column reads) to
assemble an ActionResultC. Parity tests assert it matches the
converter-based read.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 07:30:36 -07:00
adminandGitHub 40dd82e638 Print Shardok binary hash during deploy (#6775) 2026-05-27 07:12:51 -07:00
824748d88f Phase 4.5h.4: action_results vector tables (#6773)
* Phase 4.5h.4 (red): action_results vector tables schema + tests

Continues 4.5h after .3 (structured-Option blob columns). Five remaining
top-level ActionResultC vectors decomposed into child tables (one row
per element), matching the per-entity table precedent from 4.5e–g:

  - action_destroyed_battalion_ids (destroyedBattalionIds: Vector[BattalionId])
  - action_removed_hero_ids        (removedHeroIds: Vector[HeroId])
  - action_removed_faction_ids     (removedFactionIds: Vector[FactionId])
  - action_affected_faction_ids    (affectedFactionIds: Vector[FactionId])
  - action_new_battalion_types     (newBattalionTypes: Vector[BattalionType]
                                    — quest-hybrid: type_id queryable +
                                    whole battalion_type_proto BLOB)

All five share the (action_seq, n) PK pattern (n = position in the
source vector — the #6735/#6737/#6738 disambiguator). The four
primitive-ID tables index the id column for the obvious "actions
affecting entity X" lookups. BattalionType is a flat 12-field struct
that's only ever looked up by type_id, so it gets the quest-hybrid
shape (type_id column + whole battalion_type_proto BLOB) rather than
fully columnizing — consistent with how flat-but-deep entities are
handled elsewhere in this package.

All FK back to action_results(action_seq) ON DELETE CASCADE.

Unified writer (ActionResultVectorTablesWriter) with a facade
write(connection, actionSeq, ar: ActionResultT) that iterates all five
vectors internally. SqliteHistory.withNewResults calls it once per
action; backfill calls the same facade per row after fromProto. Single
source of truth, no risk of drift between live + backfill.

Read path is NOT swapped here — replayFrom still parses payload. The
rows are "shadow" until 4.5h.5 drops payload and switches the read
path.

This commit (red):
- ActionResultVectorTablesWriter stub: real schemaStatements (5 CREATE
  TABLE + 5 CREATE INDEX), no-op write + no-op backfill.
- Migration v20 registered.
- Two red tests in SqliteHistoryTest, each asserting all 5 tables: live-
  write via withNewResults, and backfill from an existing payload.
  Shared assertVectorTablesPopulated helper checks every row of every
  table.

After this lands, the only remaining 4.5h work is .5 — drop payload +
read-path swap.

Verification: sqlite_history_test 87/89 pass, 2 RED for the right reason
(tables exist per migration, no rows because stubs are no-ops →
rs.next() returns false in withRow).

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

* Phase 4.5h.4 (green): implement action_results vector tables

Fills in the ActionResultVectorTablesWriter stub from the red commit
and wires SqliteHistory.withNewResults to call the writer's facade
once per action. v20 backfill turns from a no-op into a real per-row
decomposition of every existing payload.

Writer (ActionResultVectorTablesWriter):
- write(connection, actionSeq, ar): facade that dispatches to four
  insertIdVector calls (one per primitive-ID vector, each batched) plus
  insertNewBattalionTypes. Single source of truth for "what gets
  inserted from a domain ActionResultT" across live + backfill.
- insertIdVector(connection, table, idColumn, actionSeq, ids): batched
  INSERT into one of the four primitive-ID join tables. No-op when ids
  is empty. (table/idColumn are internal constants, never user input.)
- insertNewBattalionTypes: batched INSERT into action_new_battalion_types
  binding type_id + BattalionTypeConverter.toProto(bt).toByteArray.
  Domain → proto happens here at the storage edge.
- backfill(connection): drains every action_results.payload (closing
  the SELECT first per the xerial quirk), then per row goes through
  ActionResultProtoConverter.fromProto and delegates to write.

SqliteHistory.withNewResults:
- Single new line after the existing per-vector loops:
  ActionResultVectorTablesWriter.write(connection, seq, awrs.actionResult).
  The facade iterates all five vectors internally.

BUILD additions (green-only):
- action_result_vector_tables_writer deps:
  action_result_scala_proto (for parseFrom),
  action_result_proto_converter (for fromProto in backfill),
  battalion_type_converter (for toProto + transitively pulls in the
  BattalionType proto for .toByteArray).

The read path is NOT touched here — replayFrom still parses payload.
The rows are "shadow" until 4.5h.5 drops payload and switches the
read path.

Verification: sqlite_history_test 89/89 pass; full Scala test suite
226/226.

Next: 4.5h.5 — drop payload BLOB, swap replayFrom to assemble from
the columns + per-entity blobs. The last 4.5h chunk.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 07:08:41 -07:00
adminandGitHub 0b70e6e9bf Load Shardok image tarball on Hetzner deploy (#6774) 2026-05-27 07:02:20 -07:00
adminandGitHub 0ad09f4067 Delete first unused Unity asset batch (#6770) 2026-05-27 06:56:53 -07:00
adminandGitHub 3c23afecfa Downscale oversized Unity texture sources (#6769) 2026-05-27 06:53:29 -07:00
adminandGitHub 596143f54d Make DragonEffect tolerate child animators (#6768) 2026-05-27 06:46:58 -07:00
adminandGitHub 6cbc99ae73 Disable checkout credential persistence (#6767) 2026-05-27 06:46:18 -07:00
2497e7114d Phase 4.5h.3: action_results structured-Option blob columns (#6772)
* Phase 4.5h.3 (red): action_results structured-Option blob columns schema + tests

Continues 4.5h after .2 (the nine scalar/Option columns split across .2a/.2b/.2c).
Three structured-Option top-level ActionResultC fields promoted as
nullable BLOB columns on action_results — small nested aggregates that
aren't analytics-queried at this level, so per the design doc's stopping
rule (same as ChangedProvince / newProvinces / etc.) each becomes a
single whole-entity BLOB column rather than being further decomposed:

  - new_battle_proto         (newBattle: Option[ShardokBattle])
  - new_chronicle_entry_proto (newChronicleEntry: Option[ChronicleEntry])
  - new_eagle_map_proto      (newEagleMap: Option[EagleMapInfo])

No indexes — these are BLOBs whose internals aren't queried at the SQL
level; the analytical handles for "which actions started a battle /
advanced chronicle / loaded a map" come from per-entity tables and
scalar columns elsewhere on action_results.

Same shared-bindColumns-helper pattern as .2a / .2b / .2c — backfill
will go through ActionResultProtoConverter.fromProto and delegate to
bindColumns; live INSERT in withNewResults calls the same helper. Single
source of truth, no risk of drift between live + backfill.

Read path is NOT swapped here — replayFrom still parses payload. The
columns are "shadow" until the final 4.5h sub-PR drops payload and
switches the read path.

This commit (red):
- ActionResultStructuredBlobColumnsWriter stub: real schemaStatements
  (3 ALTER TABLE ADD COLUMN ... BLOB), no-op backfill.
- Migration v19 registered.
- Two red tests in SqliteHistoryTest: live-write asserts the three BLOB
  columns populated from the ActionResultC fields (assertions parse the
  stored bytes via the per-entity converter and compare to the domain
  instance — robust to serialization-order differences); backfill asserts
  the same from an existing payload.
- Visibility widening: model/state/shardok_battle:shardok_battle,
  model/state/chronicle_entry:chronicle_entry,
  model/proto_converters/shardok_battle:shardok_battle_converter,
  model/proto_converters/chronicle_entry:chronicle_entry_converter,
  model/proto_converters:eagle_map_info_converter — all to add the
  test (and where relevant, service) packages.

After this lands, the remaining 4.5h work is the primitive-ID vectors +
the small newBattalionTypes vector, then the payload drop + read-path
swap.

Verification: sqlite_history_test 85/87 pass, 2 RED for the right reason
(columns exist per migration, default NULL → getBytes returns null and
parseFrom(null) throws NPE).

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

* Phase 4.5h.3 (green): implement action_results structured-Option blob columns

Fills in the ActionResultStructuredBlobColumnsWriter stub from the red
commit and wires the live INSERT in SqliteHistory.withNewResults to call
the writer's bindColumns helper. v19 backfill turns from a no-op into a
real per-row UPDATE through the full ActionResultProtoConverter.fromProto.

Writer (ActionResultStructuredBlobColumnsWriter):
- bindColumns(ps, startPosition, ar): single source of truth for the
  three blob column bindings — each is the per-entity converter's
  toProto.toByteArray (or SQL NULL for None).
    * new_battle_proto         ← ShardokBattleConverter.toProto(...).toByteArray
    * new_chronicle_entry_proto ← ChronicleEntryConverter.toProto(...).toByteArray
    * new_eagle_map_proto      ← EagleMapInfoConverter.toProto(...).toByteArray
- backfill(connection): drains every action_results.payload (closing
  the SELECT first per the xerial quirk), then per row goes through
  ActionResultProtoConverter.fromProto and delegates to bindColumns.
- bindOptBytes helper via .fold (no match-on-Option).

SqliteHistory.withNewResults:
- INSERT extended from 21 to 24 columns. The three new bindings are a
  single call:
  ActionResultStructuredBlobColumnsWriter.bindColumns(insertStmt,
  startPosition = 22, awrs.actionResult).

BUILD additions (green-only):
- action_result_structured_blob_columns_writer deps:
  action_result_scala_proto, eagle_pkg, action_result_trait,
  action_result_proto_converter, eagle_map_info_converter,
  chronicle_entry_converter, shardok_battle_converter.
- Widened eagle_map_info_converter visibility to include service:__pkg__
  (chronicle_entry_converter and shardok_battle_converter already had
  service visibility from the red commit / prior phases).

The read path is NOT touched here — replayFrom still parses payload.
These columns are "shadow" until the final 4.5h sub-PR drops payload
and switches the read path.

Verification: sqlite_history_test 87/87 pass; full Scala test suite
226/226.

Next: 4.5h.4 — primitive-ID vectors (destroyedBattalionIds,
removedHeroIds, removedFactionIds, affectedFactionIds) + the small
newBattalionTypes vector. Then 4.5h.5 = drop payload + read-path swap.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 06:45:39 -07:00
adminandGitHub fbe7f9606b Update Unity Rider package (#6771) 2026-05-27 06:44:48 -07:00
adminandGitHub 1573e73419 Add Unity LFS asset audit tooling (#6766) 2026-05-26 21:42:31 -07:00
5ea7908db0 Phase 4.5h.2c: action_results date + resolvedBattle columns (#6765)
* Phase 4.5h.2c (red): action_results date + resolvedBattle columns schema + tests

Closes the 4.5h.2 family (enums → numerics → date+text). The last two
scalar/Option top-level ActionResultC fields:

Three nullable columns + two indexes:
  - new_date_year   (newDate.year)
  - new_date_month  (newDate.month.value, 1..12)
  - resolved_battle (resolvedBattle: Option[String] — shardok game id)

The year/month pair mirrors the v1 date_year/date_month pattern already
used for the resulting state's currentDate — newDate is a distinct field
(the change-of-date event), but storing it identically keeps the table
shape uniform. A composite (new_date_year, new_date_month) index matches
the v1 composite on the resulting-state date columns; resolved_battle
is independently indexed.

Same shared-bindColumns-helper pattern as .2a / .2b — backfill goes
through ActionResultProtoConverter.fromProto, then delegates to
bindColumns; live write calls the same bindColumns from the existing
INSERT in withNewResults. Single source of truth, no risk of drift.

Read path is NOT swapped here — replayFrom still parses payload. The
columns are "shadow" until the final 4.5h sub-PR drops payload and
switches the read path.

This commit (red):
- ActionResultDateBattleColumnsWriter stub: real schemaStatements
  (3 ALTER TABLE ADD COLUMN + 2 CREATE INDEX, including the composite
  on (year, month)), no-op backfill.
- Migration v18 registered.
- Two red tests: live-write asserts all three columns populated; backfill
  asserts the same from an existing payload.

After this lands, 4.5h.2 is complete. The remaining 4.5h work is
structured Options (newBattle / newChronicleEntry / newEagleMap),
primitive-ID vectors, the small newBattalionTypes vector, and finally
the payload drop + read-path swap.

Verification: sqlite_history_test 83/85 pass, 2 RED for the right reason
(columns exist per migration, default NULL → getInt returns 0).

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

* Phase 4.5h.2c (green): implement action_results date + resolvedBattle columns

Fills in the ActionResultDateBattleColumnsWriter stub from the red
commit and wires the live INSERT in SqliteHistory.withNewResults to call
the writer's bindColumns helper. v18 backfill turns from a no-op into a
real per-row UPDATE through the full ActionResultProtoConverter.fromProto.

This commit closes the 4.5h.2 family — all 9 scalar/Option top-level
ActionResultC fields are now promoted onto action_results columns. The
remaining 4.5h work is structured Options, primitive-ID vectors, and the
payload drop + read-path swap.

Writer (ActionResultDateBattleColumnsWriter):
- bindColumns(ps, startPosition, ar): single source of truth for the
  three column bindings — delegates to bindOptDate (year/month pair)
  and bindOptString (resolved_battle).
- backfill(connection): drains every action_results.payload, then per
  row goes through ActionResultProtoConverter.fromProto and delegates to
  bindColumns. Same pattern as .2a / .2b.
- bindOptDate(ps, yearIdx, monthIdx, opt): Option[Date] → (setInt year,
  setInt month.value) or (setNull, setNull), via .fold.
- bindOptString(ps, idx, opt): Option[String] → setString or setNull,
  via .fold.

SqliteHistory.withNewResults:
- INSERT extended from 18 to 21 columns. The three new bindings are a
  single call:
  ActionResultDateBattleColumnsWriter.bindColumns(insertStmt,
  startPosition = 19, awrs.actionResult).

BUILD additions (green-only):
- action_result_date_battle_columns_writer deps:
  action_result_scala_proto, eagle_pkg (for type aliases referenced
  through ActionResultT), action_result_trait,
  action_result_proto_converter, model/state/date.

The read path is NOT touched here — replayFrom still parses payload.
These columns are "shadow" until the final 4.5h sub-PR drops payload
and switches the read path.

Verification: sqlite_history_test 85/85 pass; full Scala test suite
226/226.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 21:16:26 -07:00
090ce2b1f6 Phase 4.5h.2b: action_results numeric columns (#6763)
* Phase 4.5h.2b (red): action_results numeric columns schema + tests

Continues 4.5h after .2a (enum columns). The second of the three 4.5h.2
sub-PRs (enums → numerics → date+text).

Four numeric-primitive top-level ActionResultC fields promoted as
nullable INTEGER columns + indexes:

  - new_round_id           (newRoundId: Option[RoundId]   — RoundId = Int)
  - new_victor_faction_id  (newVictorFactionId: Option[FactionId] — FactionId = Int)
  - game_ended             (gameEnded: Option[Boolean] — stored as 0/1)
  - new_random_seed        (newRandomSeed: Option[Long]   — SQLite INTEGER takes int64)

Note new_round_id is distinct from the v1 round_id column: the latter is
the resulting state's current round id (always set), this is the action's
change-of-round event (sparse, only set when an action advances the round).

Unlike .2a's enums, these four are direct Option-unwrap from the proto
(no UNKNOWN→None or back-compat semantics), so the GREEN backfill is
simpler — though it'll still go through ActionResultProtoConverter.fromProto
to keep the bindColumns helper as the single source of truth for "what
gets bound and from what" across live INSERT + backfill UPDATE.

The shared-bindColumns-helper pattern from .2a continues. Live-write
path is the existing INSERT INTO action_results (...) in withNewResults,
extended in GREEN to bind these four additional columns positionally via
ActionResultNumericColumnsWriter.bindColumns(insertStmt, position, ar).

Read path is NOT swapped here — replayFrom still parses payload. The
columns are "shadow" until the final 4.5h sub-PR drops payload and
switches the read path.

This commit (red):
- ActionResultNumericColumnsWriter stub: real schemaStatements
  (4 ALTER TABLE ADD COLUMN + 4 CREATE INDEX), no-op backfill (no
  bindColumns yet — that lands in green alongside the impl).
- Migration v17 registered.
- Two red tests in SqliteHistoryTest: live-write asserts the four
  columns populated from the ActionResultC fields; backfill asserts
  the four columns populated from an existing payload.

Verification: sqlite_history_test 81/83 pass, 2 RED for the right reason
(columns exist per migration, default NULL → getInt returns 0).

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

* Phase 4.5h.2b (green): implement action_results numeric columns

Fills in the ActionResultNumericColumnsWriter stub from the red commit
and wires the live INSERT in SqliteHistory.withNewResults to call the
writer's bindColumns helper. v17 backfill turns from a no-op into a
real per-row UPDATE through the full ActionResultProtoConverter.fromProto.

Writer (ActionResultNumericColumnsWriter):
- bindColumns(ps, startPosition, ar): single source of truth for the
  four numeric-column bindings.
    * new_round_id          ← ar.newRoundId             (Option[Int])
    * new_victor_faction_id ← ar.newVictorFactionId     (Option[Int])
    * game_ended            ← ar.gameEnded.map(_→0/1)   (Option[Boolean])
    * new_random_seed       ← ar.newRandomSeed          (Option[Long], setLong)
- backfill(connection): drains every action_results.payload (closing
  the SELECT first per the xerial quirk), then issues a batched UPDATE
  per row. Each row goes through ActionResultProtoConverter.fromProto
  to get the domain ActionResultC, then delegates to bindColumns at
  position 1. Same pattern as .2a — keeps live + backfill on a single
  source of truth.
- bindOptInt / bindOptLong helpers via .fold (no match-on-Option).

SqliteHistory.withNewResults:
- INSERT extended from 14 to 18 columns. The four new bindings are a
  single call: ActionResultNumericColumnsWriter.bindColumns(insertStmt,
  startPosition = 15, awrs.actionResult).

BUILD additions (green-only):
- action_result_numeric_columns_writer deps: action_result_scala_proto,
  eagle_pkg (for type aliases referenced through ActionResultT),
  action_result_trait, action_result_proto_converter.

The read path is NOT touched here — replayFrom still parses payload.
These columns are "shadow" until the final 4.5h sub-PR drops payload
and switches the read path.

Verification: sqlite_history_test 83/83 pass; full Scala test suite
226/226.

Next in 4.5h.2: .2c — newDate (year+month columns) + resolvedBattle
(text column) — the last scalar/Option chunk before the structured
Options + primitive-ID vectors + the payload drop.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 18:52:32 -07:00
9d114b89a7 Phase 4.5h.2a: action_results enum columns (#6761)
* Phase 4.5h.2a (red): action_results enum columns schema + tests

Continues 4.5h after .1 (entity-ref columns). The 4.5h.2 family is the
remaining 9 scalar/Option ActionResultC fields, split per the three-group
plan: .2a = enums (this PR), .2b = numeric primitives, .2c = Date +
String.

The three enum-typed fields become four columns — GameType is a sum type
(Normal vs Tutorial(phase: TutorialPhase)) so it needs a kind discriminator
plus a wrapped TutorialPhase column. All nullable INTEGER, all indexed:

  - new_round_phase     (newRoundPhase: Option[RoundPhase])
  - last_command_type   (lastCommandTypeForActingProvince: Option[CommandType])
  - new_game_type       (newGameType: Option[GameType]) — kind discriminator
  - new_tutorial_phase  (TutorialPhase wrapped inside GameType.Tutorial;
                         NULL when Normal or None)

Storage value is the **proto enum number** (Converter.toProto(domain).value)
for all three — the proto enum's wire-format number is intentionally
stable across schema evolutions, unlike e.g. Scala enum .ordinal. The
domain RoundPhase.value happens to match the proto enum number, but going
through the converter for all three keeps the pattern uniform (and forces
any drift into one place — the converter).

GREEN backfill will go through the full ActionResultProtoConverter.fromProto
rather than reading proto fields directly, because the domain
lastCommandTypeForActingProvince has a back-compat fallback path to a
deprecated SelectedCommand field. The converter is the single source of
truth for "domain Option-value from this payload"; reusing it eliminates
drift risk for the cost of a one-time per-row conversion on the migration
path.

Live-write path is the existing INSERT INTO action_results (...) in
withNewResults, extended in GREEN to bind these four additional columns
positionally. Read path is NOT swapped here — replayFrom still goes
through the full converter on the payload blob; the columns are "shadow"
until the final 4.5h sub-PR drops payload and switches the read path.

This commit (red):
- ActionResultEnumColumnsWriter stub: real schemaStatements
  (4 ALTER TABLE ADD COLUMN + 4 CREATE INDEX), no-op backfill.
- Migration v16 registered.
- Two red tests in SqliteHistoryTest: live-write exercises the Tutorial
  branch (both new_game_type AND new_tutorial_phase populated); backfill
  exercises the Normal branch (new_game_type set, new_tutorial_phase
  NULL) so the two tests together cover both GameType branches.

Verification: sqlite_history_test 79/81 pass, 2 RED for the right reason
(columns exist per migration, default NULL → getInt returns 0).

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

* Phase 4.5h.2a (green): implement action_results enum columns

Fills in the ActionResultEnumColumnsWriter stub from the red commit and
wires the live INSERT in SqliteHistory.withNewResults to call the writer's
new bindColumns helper. v16 backfill turns from a no-op into a real
per-row UPDATE through the full ActionResultProtoConverter.fromProto.

Writer (ActionResultEnumColumnsWriter):
- bindColumns(ps, startPosition, ar): single source of truth for "what
  the four enum columns get bound to from a domain ActionResultT".
  Returns nothing; binds 4 positional parameters via the shared
  bindOptInt helper. Used by both the live INSERT and the migration
  UPDATE — eliminates drift risk between the two paths.
- backfill(connection): drains every action_results.payload (closing the
  SELECT first per the xerial quirk), then issues a batched UPDATE per
  row. Each row goes through the full ActionResultProtoConverter.fromProto
  to get the domain ActionResultC (which handles the deprecated
  SelectedCommand fallback for lastCommandTypeForActingProvince), then
  delegates to bindColumns at position 1.
- GameType handling: GameType.Tutorial(phase) populates BOTH
  new_game_type AND new_tutorial_phase; GameType.Normal populates only
  new_game_type, leaving new_tutorial_phase NULL (rather than the proto
  sentinel TUTORIAL_PHASE_UNKNOWN = 0).

SqliteHistory.withNewResults:
- INSERT extended from 10 to 14 columns. The four new bindings are a
  single call: ActionResultEnumColumnsWriter.bindColumns(insertStmt,
  startPosition = 11, awrs.actionResult). The 4.5h.1 entity-ref columns
  stay inline (their inline-vs-helper choice can be revisited later).

BUILD additions (green-only):
- action_result_enum_columns_writer deps: tutorial_phase_scala_proto,
  action_result_scala_proto, eagle_pkg (for the BattalionId etc. types
  referenced through ActionResultT), action_result_trait,
  action_result_proto_converter, command_type_converter,
  game_type_converter, round_phase_converter.
- Widened visibility of command_type_converter and round_phase_converter
  to include service:__pkg__.

The read path is NOT touched here — replayFrom still parses payload and
goes through ActionResultProtoConverter.fromProto. These columns are
"shadow" until the final 4.5h sub-PR drops payload and switches the
read path.

Verification: sqlite_history_test 81/81 pass; full Scala test suite
226/226.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 17:01:56 -07:00
adminandGitHub 9112e60378 Queue client update notifications until UI is ready (#6762) 2026-05-26 16:46:19 -07:00
37fa64bdad Phase 4.5h.1: action_results entity-ref columns (#6760)
* Phase 4.5h.1 (red): action_results entity-ref columns schema + tests

Begins Phase 4.5h. The first chunk: four top-level entity-ref Option fields
from ActionResultC promoted onto the existing action_results table as
nullable INTEGER columns, indexed for the obvious query shapes
("show all actions by hero X"):

  - acting_hero_id      (domain actingHeroId     / proto leader)
  - acting_faction_id   (domain actingFactionId  / proto player)
  - province_id         (domain provinceId       / proto province)
  - province_id_acted   (domain provinceIdActed  / proto province_acted)

Proto field names don't match the domain — the column names follow the
domain since that's what the read path will ultimately expose.

Distinct from the per-entity table writers: there's no new table here,
and no per-row write helper. The live-write path is the existing
INSERT INTO action_results (...) statement in withNewResults, which the
green commit extends to bind these four extra columns positionally
(RED: INSERT unchanged, new columns default to NULL, so getInt returns 0
and the test fails 0 != 9).

The read path is NOT swapped here — replayFrom still parses the payload
blob and goes through ActionResultProtoConverter.fromProto. The columns
are "shadow" until the final 4.5h sub-PR drops payload and switches the
read path.

This commit (red):
- ActionResultEntityRefColumnsWriter stub: real schemaStatements
  (4 ALTER TABLE ADD COLUMN + 4 CREATE INDEX), no-op backfill.
- Migration v15 registered (runs the schema; backfill is the stub no-op).
- Two red tests in SqliteHistoryTest: live-write asserts the four
  columns are populated from the ActionResultC fields, and backfill
  asserts the four columns are populated from an existing payload.

Verification: sqlite_history_test 77/79 pass, 2 RED for the right reason
(columns exist per migration, default NULL → getInt returns 0). The impl
that turns them green is the next commit on this branch.

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

* Phase 4.5h.1 (green): implement action_results entity-ref columns

Fills in the ActionResultEntityRefColumnsWriter.backfill stub from the
red commit and extends the existing INSERT in SqliteHistory.withNewResults
to populate the four new columns. v15 backfill turns from a no-op into
a real one-row-per-existing-payload UPDATE.

Writer (ActionResultEntityRefColumnsWriter):
- backfill(connection): drains every action_results.payload (fully
  closing the SELECT ResultSet before any UPDATE — the xerial
  sqlite-jdbc quirk), then issues one batched UPDATE per row binding
  leader/player/province/provinceActed from the parsed proto. The
  UPDATE is unconditional: rows whose four proto fields are all unset
  bind NULL × 4, identical to the post-ALTER default — keeps the logic
  uniform with no extra branching.
- bindOptInt helper: Option[Int] → setInt or setNull, via .fold (no
  match-on-Option).

SqliteHistory.withNewResults:
- The INSERT INTO action_results (...) statement is extended from 6
  columns to 10 — adding acting_hero_id, acting_faction_id, province_id,
  province_id_acted at positions 7–10. The four new bindings each use
  .fold to handle the Option[Int] domain field. The existing
  date_year/date_month pattern-match stays as-is (local convention).

BUILD addition (green-only):
- action_result_entity_ref_columns_writer: action_result_scala_proto
  (for ActionResultProto.parseFrom in backfill).

The read path is NOT touched here — replayFrom still parses payload and
goes through ActionResultProtoConverter.fromProto. These columns are
"shadow" until the final 4.5h sub-PR drops payload and switches the
read path.

Verification: sqlite_history_test 79/79 pass; full Scala test suite
226/226.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 15:53:08 -07:00
adminandGitHub 9eca1f4a91 Clarify expired OAuth session login state (#6759) 2026-05-26 15:09:36 -07:00
5d807ef268 Phase 4.5g.3: client text visibility extensions decomposition (#6758)
* Phase 4.5g.3 (red): client text visibility extensions decomposition tests + schema

Final 4.5g chunk. ClientTextVisibilityExtensionT is small and all-scalar
(textId: ClientTextId + recipientFactionIds: Vector[FactionId]) with no
sealed-hierarchy variants and no nested aggregates — so it's a **refined**
entity, fully columnized with no *_proto BLOB. Two tables, mirroring the
ChangedFaction primitive-ID-join precedent:

  - action_client_text_visibility_extensions (parent): one row per
    extension, (action_seq, n) PK, text_id queryable column (indexed).
  - action_client_text_visibility_extension_recipients (child): one row
    per (extension, faction_id), PK (action_seq, n, faction_id),
    faction_id indexed. Set semantics: the reader sorts by faction_id on
    read, matching the existing ChangedFaction _*_ids children.

Both FK back to action_results(action_seq) ON DELETE CASCADE directly
(matching the existing convention) — cascading from the parent action
keeps both tables in sync without an explicit parent-to-child FK.

There is no ClientTextVisibilityExtensionConverter file — conversion is
inlined in ActionResultProtoConverter. Backfill will build a
ClientTextVisibilityExtensionC directly from the proto's nested
ClientTextVisibilityExtension fields.

This commit (red):
- ClientTextVisibilityExtensionTableWriter stub: real schemaStatements
  (both tables + indexes), no-op write/backfill.
- ClientTextVisibilityExtensionTableReader stub: read returns
  Vector.empty.
- Migration v14 registered (runs the schema; backfill is the stub
  no-op).
- Two red tests in SqliteHistoryTest: live-write/reader round-trip
  preserving text_id and recipients (including an extension with empty
  recipients, to exercise the no-child-rows case), and backfill from an
  existing payload (asserts parent rows + recipients child rows for both
  the populated and empty-recipients case).
- client_text_visibility_extension_trait visibility widened to the
  service main + test packages; client_text_visibility_extension_concrete
  visibility widened to the service main + test service package.

Verification: sqlite_history_test 75/77 pass, 2 RED for the right reason
(schema exists, rows absent). The impl that turns them green is the next
commit on this branch.

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

* Phase 4.5g.3 (green): implement client text visibility extensions decomposition

Fills in the ClientTextVisibilityExtensionTableWriter / Reader stubs from
the red commit and wires the write into withNewResults. v14 backfill
turns from a no-op into the real per-extension decomposition of every
existing action_results.payload.

Writer (ClientTextVisibilityExtensionTableWriter):
- write(connection, actionSeq, n, extension): one INSERT into
  action_client_text_visibility_extensions (parent row with text_id),
  then a batched INSERT into action_client_text_visibility_extension_recipients
  (one row per faction_id). Skips the child INSERT entirely when
  recipientFactionIds is empty.
- backfill(connection): reads every action_results.payload (fully
  draining the SELECT ResultSet before any INSERT), parses ActionResult
  proto, iterates clientTextVisibilityExtensions and builds a
  ClientTextVisibilityExtensionC directly from the nested proto fields
  (the same inline conversion ActionResultProtoConverter does), then
  delegates to write.

Reader (ClientTextVisibilityExtensionTableReader):
- read(connection, actionSeq): two-pass — first drain parent rows
  (n, text_id) ordered by n, then per-parent SELECT of the recipient
  faction_ids ordered ascending (set semantics, matching
  ChangedFactionTableReader's _*_ids children).

SqliteHistory:
- withNewResults: after the action_results executeBatch (so the FK
  target rows exist), for each (awrs, i) iterate
  awrs.actionResult.clientTextVisibilityExtensions.zipWithIndex and call
  ClientTextVisibilityExtensionTableWriter.write — same loop shape as
  the other per-vector writes already in place.

BUILD additions (green-only):
- client_text_visibility_extension_table_writer: action_result_scala_proto
  (for ActionResultProto.parseFrom) + client_text_visibility_extension_concrete
  (for the ClientTextVisibilityExtensionC constructor in backfill).
- client_text_visibility_extension_table_reader:
  client_text_visibility_extension_concrete (same — assembling each
  read row).

Verification: sqlite_history_test 77/77 pass; full Scala test suite
226/226.

This closes Phase 4.5g. Next is 4.5h: top-level ActionResultC scalar
columns on action_results + drop the payload BLOB, swapping the read
path to scalar columns + per-entity blobs.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 15:06:34 -07:00
c9b045cd78 Phase 4.5g.2: generated text requests decomposition (#6756)
* Phase 4.5g.2 (red): generated text requests decomposition tests + schema

Continues Phase 4.5g. After notifications (4.5g.1), this is the second
chunk: the newGeneratedTextRequests "new entity" vector.

GeneratedTextRequestT is a sealed trait (FixedHeroName, GeneratedHeroName,
and the ~45-case LlmRequestT enum), so per the quest-hybrid stopping rule
each request is stored as a whole-entity generated_text_request_proto BLOB
plus a queryable `kind` discriminator column — the same shape as
notifications, minus the notification-only `deferred` column (a
GeneratedTextRequest carries no field beside the proto).

One table, action_new_generated_text_requests (there is no "removed"
counterpart): (action_seq, n, kind, generated_text_request_proto), PK
(action_seq, n), kind indexed.

A wrinkle worth noting: the production read path
(ActionResultProtoConverter.fromProto) deliberately drops
newGeneratedTextRequests ("not used by the applier"), so the proto blob in
action_results.payload is the only place old requests survive. Backfill
therefore reads the proto's repeated new_generated_text_requests field
directly, and the decomposed table becomes the first relational home for
this data.

This commit (red):
- GeneratedTextRequestTableWriter stub: real schemaStatements (table +
  kind index), no-op write/backfill.
- GeneratedTextRequestTableReader stub: read returns Vector.empty.
- Migration v13 registered (runs the schema; backfill is the stub no-op).
- Two red tests in SqliteHistoryTest: newGeneratedTextRequests round-trip
  preserving kind + order via withNewResults, and backfill from an
  existing payload (asserting the kind discriminator in n order).

The converter and domain-type targets were already visible to the service
and test packages, so no visibility widening was needed.

Verification: sqlite_history_test 73/75 pass, 2 RED for the right reason
(schema exists, rows absent). The impl that turns them green is the next
commit on this branch.

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

* Phase 4.5g.2 (green): implement generated text requests decomposition

Fills in the GeneratedTextRequestTableWriter / Reader stubs from the red
commit and wires the write into withNewResults. v13 backfill turns from a
no-op into the real per-request decomposition of every existing
action_results.payload.

Writer (GeneratedTextRequestTableWriter):
- write(connection, actionSeq, n, request): INSERT one row with
  (action_seq, n, kind, generated_text_request_proto). Converts the
  domain request to proto exactly at the storage edge via
  GeneratedTextRequestConverter.toProto.
- kindOf(request): productPrefix-based discriminator. Every subtype —
  FixedHeroName, GeneratedHeroName, and each LlmRequestT enum case — is
  a Product, so the compiler proves the match exhaustive (no fallback,
  which would be unreachable under -Werror).
- backfill(connection): reads every action_results.payload (fully
  draining the SELECT ResultSet before any INSERT, the xerial
  sqlite-jdbc quirk), parses ActionResult proto, then iterates the proto's
  repeated new_generated_text_requests field directly — because
  ActionResultProtoConverter.fromProto deliberately drops this vector
  ("not used by the applier"), the blob is the only place these
  requests survive. Each is converted to the domain type via
  GeneratedTextRequestConverter.fromProto and delegated to write.

Reader (GeneratedTextRequestTableReader):
- read(connection, actionSeq): SELECT generated_text_request_proto in n
  order, parse each blob, convert via fromProto.

SqliteHistory:
- withNewResults: after the action_results executeBatch (so the FK target
  rows exist), for each (awrs, i) iterate
  awrs.actionResult.newGeneratedTextRequests.zipWithIndex and call
  GeneratedTextRequestTableWriter.write — same loop shape as the other
  per-vector writes already in place.

BUILD additions (green-only):
- generated_text_request_table_writer: action_result_scala_proto (for
  ActionResultProto.parseFrom) + generated_text_request_converter (for
  toProto / fromProto at the storage edge).
- generated_text_request_table_reader: llm_request_scala_proto (for
  GeneratedTextRequestProto.parseFrom — the target name is historical
  baggage; the proto is generated_text_request.proto) +
  generated_text_request_converter.

Verification: sqlite_history_test 75/75 pass; full Scala test suite
225/225.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 13:49:48 -07:00
adminandGitHub f2c3772304 Preserve Shardok setup placements on reconnect (#6757) 2026-05-26 13:37:54 -07:00
adminandGitHub 7ab1b44989 Apply faction name diffs on client (#6755) 2026-05-25 07:26:23 -07:00
adminandGitHub e584e85642 Handle factionless profession gain notifications (#6754) 2026-05-24 13:18:53 -07:00
adminandGitHub e543d7b53f Run scalafmt hook through Bazel (#6753) 2026-05-24 13:01:56 -07:00
adminandGitHub c08ed8c170 Suppress ready-to-join notification after province ownership change (#6751) 2026-05-24 14:56:58 -04:00
adminandGitHub 86d396c5f5 Suppress ready-to-join notification after quest fulfillment (#6752) 2026-05-24 11:14:08 -04:00
adminandGitHub e635e2d5cf Preserve tutorial generated text requests (#6750) 2026-05-23 22:42:24 -04:00
266039df60 Phase 4.5g.1: notifications decomposition (#6749)
* Phase 4.5g.1 (red): notifications decomposition tests + schema

Starts Phase 4.5g — notifications + generated text requests. This is the
first chunk: the newNotifications / removedNotifications vectors.

NotificationT's details is a ~45-subtype sealed hierarchy, so per the
quest-hybrid stopping rule each notification is stored as a whole-entity
notification_proto BLOB plus a queryable `kind` discriminator column.
Two wrinkles unique to notifications:

  - deferred is NOT in the proto. NotificationConverter.toProto returns
    (NotificationProto, Boolean) — the Boolean is deferred, carried
    beside the message. So deferred is its own column.
  - the proto representation of newNotifications is lossy: it splits into
    a single new_deferred_notification + a repeated notifications_to_deliver,
    so multiple deferred new notifications and original order across the
    split don't survive a proto round-trip. The decomposed tables store
    the domain vector faithfully — one row per element, in n order, each
    with its own deferred — which is strictly better than the proto.

Both action_new_notifications and action_removed_notifications share the
shape (action_seq, n, kind, deferred, notification_proto), PK
(action_seq, n), kind indexed.

This commit (red):
- NotificationTableWriter stub: real schemaStatements (both tables +
  kind indexes), no-op writeNew/writeRemoved/backfill.
- NotificationTableReader stub: readNew/readRemoved return Vector.empty.
- Migration v12 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest: newNotifications round-trip
  preserving deferred + order (the proto-can't-do-this case),
  removedNotifications round-trip, and backfill from an existing payload
  (asserting the kind discriminator).
- notification_trait / notification_concrete / notification_converter
  visibility widened to the service main and/or test packages.

Verification: sqlite_history_test 70/73 pass, 3 RED for the right
reason (schema exists, rows absent). The impl that turns them green is
the next commit on this branch.

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

* Phase 4.5g.1 (green): implement notifications decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring.

- NotificationTableWriter.writeNew / writeRemoved: INSERT one row per
  notification at (action_seq, n) — kind discriminator + deferred column
  + the Notification proto bytes. kind = details.productPrefix (clean
  subtype name; the compiler proves the Product case exhaustive over the
  sealed NotificationDetails hierarchy, so no reflection and no
  45-case map). deferred comes from NotificationConverter.toProto's
  second tuple element (it lives beside the proto, not in it).
- NotificationTableWriter.backfill: for every existing payload,
  reconstruct newNotifications exactly as ActionResultProtoConverter
  does (single new_deferred_notification ++ notifications_to_deliver),
  plus removedNotifications; write each. Reads all payloads before any
  INSERT (closes the SELECT ResultSet first).
- NotificationTableReader.readNew / readRemoved: inverse — parse each
  blob and combine with the deferred column via
  NotificationConverter.fromProto(proto, deferred), ordered by n.
- SqliteHistory.withNewResults: live-write loop now also writes
  newNotifications + removedNotifications.
- BUILD: writer/reader gain action_result_scala_proto /
  action_result_notification_details_scala_proto + notification_converter
  deps.

Verification: sqlite_history_test 73/73 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-23 07:51:55 -07:00
ec8223fb4f Phase 4.5f.4: newProvinces decomposition (#6747)
* Phase 4.5f.4 (red): newProvinces decomposition tests + schema

Last and deepest of the "new entity" vectors (after newBattalions
4.5f.1, newFactions 4.5f.2, newHeroes 4.5f.3): newProvinces. A
ProvinceT creation snapshot transitively embeds armies, units, heroes,
battalions, events, deferred changes — exactly the nesting 4.5b's
ChangedProvince kept as a proto blob by the same stopping rule. So it
takes the whole-entity province_proto BLOB shape + a queryable
province_id index.

action_new_provinces is a brand-new table, distinct from 4.5b's
action_changed_provinces (deltas). PK is (action_seq, n) from the
start — the disambiguator the #6735/#6737/#6738 outages taught us — so
multiple new provinces in one action all land; province_id is indexed
but non-unique.

This commit (red):
- NewProvinceTableWriter stub: real schemaStatements (CREATE the
  (action_seq, n) table + index), no-op write and backfill.
- NewProvinceTableReader stub: returns Vector.empty.
- Migration v11 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest: live write + reader round-trip,
  two new provinces preserved in n order, and backfill from an existing
  payload.
- ProvinceC concrete visibility widened to the service test package
  (ProvinceT and ProvinceConverter are already //visibility:public).

Verification: sqlite_history_test 67/70 pass, 3 RED for the right
reason (schema exists, rows absent). The impl that turns them green is
the next commit on this branch.

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

* Phase 4.5f.4 (green): implement newProvinces decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring. Completes Phase 4.5f
(all four "new entity" vectors decomposed).

- NewProvinceTableWriter.write: INSERT one row per new province at
  (action_seq, n) — province_id column (denormalized, indexed) plus the
  Province proto bytes in province_proto. Domain type in;
  ProvinceConverter.toProto only at the blob storage edge.
- NewProvinceTableWriter.backfill: decompose every newProvinces entry in
  every existing action_results.payload. Reads all payloads before any
  INSERT (closes the SELECT ResultSet first); the proto field is a
  Province per entry, converted via fromProto before write.
- NewProvinceTableReader.read: inverse — parse each blob back to a
  ProvinceT, ordered by n. (Round-trip test confirms ProvinceConverter
  is lossless for the test province.)
- SqliteHistory.withNewResults: live-write loop now also writes
  newProvinces (same n-disambiguator pattern as the other new-entity
  vectors).
- BUILD: writer/reader gain action_result_scala_proto /
  province_scala_proto + province converter deps.

Verification: sqlite_history_test 70/70 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 16:40:06 -07:00
adminandGitHub 76d3d25d05 Account for incoming food in low food warnings (#6748) 2026-05-22 08:30:44 -07:00
adminandGitHub 6672683289 Display ready-to-join hero notifications (#6745)
* Show ready-to-join hero notifications

* Update Unity project file
2026-05-22 08:16:15 -07:00
91ee65f7d0 Phase 4.5f.3: newHeroes decomposition (#6746)
* Phase 4.5f.3 (red): newHeroes decomposition tests + schema

Third of the "new entity" vectors (after newBattalions 4.5f.1 and
newFactions 4.5f.2): newHeroes. Full HeroT creation snapshots (no
Changed* wrapper), embedding backstory versions, backstory events, and
faction biases — a deep entity, so it takes the whole-entity hero_proto
BLOB shape + a queryable hero_id index.

action_new_heroes is a brand-new table (the "new entity" vectors had no
v2 scaffolding). PK is (action_seq, n) from the start — the
disambiguator the #6735/#6737/#6738 outages taught us — so multiple new
heroes in one action all land; hero_id is indexed but non-unique.

This commit (red):
- NewHeroTableWriter stub: real schemaStatements (CREATE the
  (action_seq, n) table + index), no-op write and backfill.
- NewHeroTableReader stub: returns Vector.empty.
- Migration v10 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest: live write + reader round-trip,
  two new heroes preserved in n order, and backfill from an existing
  payload.
- hero converter target visibility widened to the service main and test
  packages (HeroT and HeroC are already visible to service).

Verification: sqlite_history_test 64/67 pass, 3 RED for the right
reason (schema exists, rows absent). The impl that turns them green is
the next commit on this branch.

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

* Phase 4.5f.3 (green): implement newHeroes decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring.

- NewHeroTableWriter.write: INSERT one row per new hero at (action_seq,
  n) — hero_id column (denormalized, indexed) plus the Hero proto bytes
  in hero_proto. Domain type in; HeroConverter.toProto only at the blob
  storage edge.
- NewHeroTableWriter.backfill: decompose every newHeroes entry in every
  existing action_results.payload. Reads all payloads before any INSERT
  (closes the SELECT ResultSet first); the proto field is a Hero per
  entry, converted via fromProto before write.
- NewHeroTableReader.read: inverse — parse each blob back to a HeroT,
  ordered by n. (Round-trip test confirms HeroConverter is lossless over
  all HeroC fields.)
- SqliteHistory.withNewResults: live-write loop now also writes
  newHeroes (same n-disambiguator pattern as newBattalions/newFactions).
- BUILD: writer/reader gain action_result_scala_proto / hero_scala_proto
  + hero converter deps.

Verification: sqlite_history_test 67/67 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 08:14:18 -07:00
7d3dee125a Phase 4.5f.2: newFactions decomposition (#6744)
* Phase 4.5f.2 (red): newFactions decomposition tests + schema

Second of the "new entity" vectors (after newBattalions, 4.5f.1):
newFactions. Full FactionT creation snapshots (no Changed* wrapper),
which transitively embed diplomacy offers, faction relationships, and
reconned province views — a deep entity, so it takes the whole-entity
faction_proto BLOB shape + a queryable faction_id index.

action_new_factions is a brand-new table (the "new entity" vectors had
no v2 scaffolding). PK is (action_seq, n) from the start — the
disambiguator the #6735/#6737/#6738 outages taught us — so multiple new
factions in one action all land; faction_id is indexed but non-unique.

This commit (red):
- NewFactionTableWriter stub: real schemaStatements (CREATE the
  (action_seq, n) table + index), no-op write and backfill.
- NewFactionTableReader stub: returns Vector.empty.
- Migration v9 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest: live write + reader round-trip,
  two new factions preserved in n order, and backfill from an existing
  payload.
- faction (FactionT) / faction/concrete (FactionC) / faction converter
  target visibility widened to the service main and/or test packages.

Verification: sqlite_history_test 61/64 pass, 3 RED for the right
reason (schema exists, rows absent). The impl that turns them green is
the next commit on this branch.

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

* Phase 4.5f.2 (green): implement newFactions decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring.

- NewFactionTableWriter.write: INSERT one row per new faction at
  (action_seq, n) — faction_id column (denormalized, indexed) plus the
  Faction proto bytes in faction_proto. Domain type in;
  FactionConverter.toProto only at the blob storage edge.
- NewFactionTableWriter.backfill: decompose every newFactions entry in
  every existing action_results.payload. Reads all payloads before any
  INSERT (closes the SELECT ResultSet first); the proto field is a
  Faction per entry, converted via fromProto before write.
- NewFactionTableReader.read: inverse — parse each blob back to a
  FactionT, ordered by n.
- SqliteHistory.withNewResults: live-write loop now also writes
  newFactions (same n-disambiguator pattern as newBattalions).
- BUILD: writer/reader gain action_result_scala_proto /
  faction_scala_proto + faction converter deps.

Verification: sqlite_history_test 64/64 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 07:32:49 -07:00
adminandGitHub 8aedd945cf Notify when heroes are ready to join (#6743) 2026-05-22 07:25:21 -07:00
5d537db8c8 Phase 4.5f.1: newBattalions decomposition (#6742)
* Phase 4.5f.1 (red): newBattalions decomposition tests + schema

Starts Phase 4.5f — decomposing the "new entity" vectors
(newProvinces/newHeroes/newFactions/newBattalions) out of the
ActionResult payload blob. Per the session cadence, 4.5f is split into
one PR per vector; this is the first, newBattalions — the lowest-risk
because it reuses BattalionConverter and the deep-blob pattern just
landed for ChangedBattalion (4.5e), establishing the action_new_*
table convention.

newBattalions holds full BattalionT creation snapshots (no Changed*
wrapper). It's a deep entity: one whole-entity battalion_proto BLOB
(the Battalion proto bytes) + a queryable battalion_id index.

action_new_battalions is a brand-new table (the "new entity" vectors
had no v2 scaffolding). Its PK is (action_seq, n) from the start — the
disambiguator the #6735/#6737/#6738 outages taught us to use — so
multiple new battalions in one action all land; battalion_id is indexed
but non-unique.

This commit (red):
- NewBattalionTableWriter stub: real schemaStatements (CREATE the
  (action_seq, n) table + index), no-op write and backfill.
- NewBattalionTableReader stub: returns Vector.empty.
- Migration v8 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest: live write + reader round-trip,
  two new battalions preserved in n order, and backfill from an existing
  payload.
- battalion (BattalionT) target visibility widened to the service main
  package.

Verification: sqlite_history_test 58/61 pass, 3 RED for the right
reason (schema exists, rows absent). The impl that turns them green is
the next commit on this branch.

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

* Phase 4.5f.1 (green): implement newBattalions decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring.

- NewBattalionTableWriter.write: INSERT one row per new battalion at
  (action_seq, n) — battalion_id column (denormalized, indexed) plus the
  Battalion proto bytes in battalion_proto. Domain type in;
  BattalionConverter.toProto only at the blob storage edge.
- NewBattalionTableWriter.backfill: decompose every newBattalions entry
  in every existing action_results.payload. Reads all payloads before
  any INSERT (closes the SELECT ResultSet first); the proto field is a
  Battalion per entry, converted via fromProto before write.
- NewBattalionTableReader.read: inverse — parse each blob back to a
  BattalionT, ordered by n.
- SqliteHistory.withNewResults: live-write loop now also writes
  newBattalions (same n-disambiguator pattern as the changed-* family).
- BUILD: writer/reader gain action_result_scala_proto /
  battalion_scala_proto + battalion_converter deps.

Verification: sqlite_history_test 61/61 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 07:18:13 -07:00
14100fcb50 Phase 4.5e: ChangedBattalion decomposition (#6741)
* Phase 4.5e (red): ChangedBattalion decomposition tests + schema

Sets up Phase 4.5e — decomposing ChangedBattalion. It's a deep entity
(ChangedBattalionC's sole field is the contained BattalionT), so it
takes the whole-entity blob shape like ChangedProvince: one
changed_battalion_proto BLOB (the Battalion proto bytes) plus a
queryable battalion_id index.

Critically, the v2 action_changed_battalions scaffolding (from 4.5a)
carried the same latent (action_seq, battalion_id) PK bug that caused
the #6735/#6737/#6738 outages for the other entities. v7 fixes it up
front: PK is (action_seq, n), battalion_id is indexed but non-unique,
so two ChangedBattalions for the same battalion in one action both
land.

This commit (red):
- ChangedBattalionTableWriter stub: real schemaStatements (DROP the
  v2 shape + CREATE the (action_seq, n) table + index), no-op write
  and backfill.
- ChangedBattalionTableReader stub: returns Vector.empty.
- Migration v7 registered (runs the schema; backfill is the stub no-op).
- Three red tests in SqliteHistoryTest:
  - live write + reader round-trip of a domain ChangedBattalionC.
  - two ChangedBattalions with the same battalion_id preserved in n
    order (the dup-entity case).
  - backfill from an existing payload (the backfill-on-load path that
    crashed the other entities in prod).
- changed_battalion_concrete visibility widened to the service main +
  test packages; battalion_converter / battalion_type_id /
  battalion/concrete widened to the service test package for the
  fixtures.

All three battalion tests are RED on the stubs with clean assertion
mismatches (schema exists, rows absent). The impl that turns them
green is the next commit on the same branch.

Verification: sqlite_history_test 55/58 pass, 3 RED for the right
reason.

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

* Phase 4.5e (green): implement ChangedBattalion decomposition

Turns the three RED tests from the previous commit green by filling in
the writer, reader, and live write-path wiring.

- ChangedBattalionTableWriter.write: INSERT one row per ChangedBattalion
  at (action_seq, n) — battalion_id column (denormalized, indexed) plus
  the Battalion proto bytes in changed_battalion_proto. Domain type in;
  BattalionConverter.toProto only at the blob storage edge.
- ChangedBattalionTableWriter.backfill: decompose every ChangedBattalion
  in every existing action_results.payload. Reads all payloads before any
  INSERT (closes the SELECT ResultSet first — xerial dislikes interleaving
  writes with an open ResultSet); the proto field is a Battalion per entry,
  converted via fromProto and wrapped in ChangedBattalionC before write.
- ChangedBattalionTableReader.read: inverse — parse each blob back to a
  ChangedBattalionC, ordered by n.
- SqliteHistory.withNewResults: live-write loop now also writes
  changedBattalions (same n-disambiguator pattern as ChangedHero /
  ChangedFaction).
- BUILD: writer/reader gain action_result_scala_proto / battalion_scala_proto
  + battalion_converter deps; battalion_converter visibility widened to the
  service main package.

Verification: sqlite_history_test 58/58 pass; full //src/test/scala/...
225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 07:06:39 -07:00
dd0eba3f48 Test: round-trip coverage for ChangedFactionTableReader's non-trivial decoders (#6740)
Fast-follow to #6739, which shipped ChangedFactionTableReader with
round-trip tests covering only Tier-1 scalars, a primitive-ID join
field, the empty case, and the same-faction_id n disambiguation. The
small-struct and Tier-3 leaf-blob decoders were left untested (deferred
because the reader has no production consumer yet). Adding that coverage
now per request.

New test "round-trip the small-struct and Tier-3 leaf-blob decoders"
builds a ChangedFactionC exercising every remaining decoder and asserts
the reader reconstructs it exactly:

- PrestigeModifier (new + removed): kind TEXT <-> Type enum
  (Festival / SuppressedBeasts / TutorialHandicap), ordered by i.
- FactionRelationship: relationship_level TEXT <-> RelationshipLevel
  (Ally / Hostile), nullable reset_date year/month <-> Option[Date]
  (one Some, one None).
- TrustLevelUpdate: explicit columns, two entries ordered by i.
- DiplomacyOffer (AllianceOffer): Tier-3 leaf blob round-tripped via
  DiplomacyOfferConverter.
- ProvinceView: Tier-3 leaf blob round-tripped via ProvinceViewConverter.
- One OutgoingTruceOfferFactionId for the wrapper path.

Test-only change plus three additive visibility entries exposing the
model targets the fixture constructs to the service test package
(state/faction:prestige_modifier, state/faction:faction_relationship,
state/diplomacy_offer:diplomacy_offer); view/province was already
test-visible. No production logic change.

Verification:
- sqlite_history_test - 55/55 pass.
- //src/test/scala/... - 225/225 pass.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 06:36:01 -07:00
ff5e6bd461 Phase 4.5d.2 (read path): ChangedFactionTableReader (#6739)
* Phase 4.5d.2 (red): ChangedFactionTableReader round-trip tests

Adds the failing tests for the 4.5d.2 read path — the inverse of
ChangedFactionTableWriter, reconstructing ChangedFactionT for an
action from the v5 decomposed tables (parent + 15 child tables).
Parallels ChangedHeroTableReader (#6733). Nothing in production
consumes it yet; it verifies the v5 columns round-trip and seeds
4.5h.

Three test cases:

- Round-trip a ChangedFactionC (Tier-1 scalars + a primitive-ID
  join field) through withNewResults and assert the reader returns
  it. Focused fixture — the writer's per-table-type behavior is
  covered in detail by the v5 backfill tests; the reader test only
  needs to prove it inverts the writer end-to-end.
- Return Vector.empty for an action with no ChangedFactions (vacuous
  on the stub; kept for the green-side guarantee).
- Preserve two ChangedFactions with the same faction_id in their
  original (n) order — exercises the (action_seq, n) PK from the
  #6737 hotfix.

Reader returns rows in `n` order (not faction_id), matching the
post-hotfix ChangedHeroTableReader contract. Stub returns
Vector.empty so the two non-vacuous cases are RED with clean
assertion mismatches. The impl that turns them green is the next
commit on the same branch.

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

* Phase 4.5d.2: implement ChangedFactionTableReader (turns red tests green)

Fills in the stub. Inverse of ChangedFactionTableWriter:

- Pass 1: SELECT the parent rows from action_changed_factions
  WHERE action_seq = ? ORDER BY n, decoding Tier-1 scalars into a
  ChangedFactionC with empty Vector fields.
- Pass 2: for each parent (keyed by its n), read the 15 child tables
  filtered by (action_seq, n) and .copy() the Vector fields in:
  - 9 primitive-ID join tables → Vector[Int] (sorted by id; these
    are set-semantics fields with no `i`, so original order isn't
    preserved — equivalent for the applier). The four Outgoing*
    ones wrap the ids back in their type-safety case classes.
  - 4 small-struct tables ordered by i: PrestigeModifier (kind
    string → Type via prestigeTypeFromString), FactionRelationship
    (relationship_level string → RelationshipLevel, nullable
    reset_date year/month → Option[Date]), TrustLevelUpdate.
  - 2 Tier-3 leaf-blob tables ordered by i: parse the proto bytes
    and convert via DiplomacyOfferConverter.fromProto /
    ProvinceViewConverter.fromProto.

Returns ChangedFactionT in n order, matching the post-#6737
ChangedHeroTableReader contract; multiple entries with the same
faction_id come back in their original positions.

Test coverage scope: the three reader tests cover Tier-1 scalars, a
primitive-ID join field, the empty case, and the same-faction_id n
disambiguation. The small-struct and leaf-blob decoders are not
round-tripped here — exercising them needs Scala model imports
(PrestigeModifier / FactionRelationship / DiplomacyOffer / ProvinceView)
and test-package visibility widenings on four model targets. Deferred
because the reader has no production consumer yet (4.5h will wire it up
and bring its own broader coverage); the writer side that those
columns come from is already validated end-to-end by the v5 backfill
test. A reader decoder bug therefore can't cause a live outage today.

Verification:
- sqlite_history_test - 54/54 pass, including the 3 reader tests.
- //src/test/scala/... - 225/225 pass.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 21:27:11 -07:00
adminandGitHub c9268d61c8 Hotfix v2 for #6737: v6 migration brings already-migrated games onto the new schema (#6738) 2026-05-21 12:15:11 -04:00
8bb45a57af Unity client: clear deprecation/unused warnings (#6732)
- Replace deprecated FindObjectsByType(FindObjectsSortMode) and
  FindFirstObjectByType with non-deprecated overloads.
- Replace deprecated GetInstanceID() with GetEntityId() in three
  files that use the value as a dictionary key or for equality.
- Prefix fire-and-forget async calls with `_ =` to silence CS4014
  in ConnectionHandler, CustomBattleHandler, ErrorHandler,
  ShardokGameModel, and ResourceFetcher.
- Remove the unused `listen` field from ConnectionHandler.
- Suppress CS0162 around tutorial content intentionally preserved
  after an unconditional return, and CS0067 on
  SingleInstanceEnforcer.OnDeepLinkReceived (declared cross-platform
  but only invoked on UNITY_STANDALONE_WIN).

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 21:51:05 -07:00
307ea245ee Hotfix: same-entity duplicate PK bug for both ChangedFaction and ChangedHero (#6737)
Same shape as the ChangedProvince hotfix in #6735 (PR title "Hotfix:
v3 backfill crash on duplicate-province ChangedProvinces"), applied
preemptively to the other two decomposed entity tables.

The crash:

  !!! CRITICAL: Failed to load game 2798739292a60a5f:
  SQLITE_CONSTRAINT_PRIMARYKEY ... action_changed_factions.action_seq,
  action_changed_factions.faction_id
    at ChangedFactionTableWriter.writeParentRow
    at ChangedFactionTableWriter.backfill
    at SqliteHistory$Migrations$.applyV5ChangedFactionDecomposition

The root cause is identical to the ChangedProvince case I'd just
hot-fixed. The v2 / v4 / v5 schemas for action_changed_heroes and
action_changed_factions used (action_seq, entity_id) as the PK,
assuming at most one Changed<Entity> per entity per action. That
invariant doesn't hold: ActionResultApplierImpl folds through the
changed<Entity> Vector sequentially and applies each entry as its
own delta, so two entries for the same entity_id are two valid
sequential deltas, both applied.

I failed to apply the ChangedProvince lesson when fixing the analogous
ChangedFaction crash, and the structurally-identical bug was sitting
in ChangedHero too (no production game has hit it yet, but it's the
same landmine — fixing preemptively in this PR per Dan's request).

Fix shape (mirrors the ChangedProvince hotfix):

- Parent table PK becomes (action_seq, n), where n is the position
  within the source ActionResult's changed<Entity> vector. entity_id
  becomes an indexed column but no longer unique.
- write() takes n as a parameter; backfill iterates with
  changed<Entity>.zipWithIndex and passes n.
- SqliteHistory.withNewResults call sites updated to use
  zipWithIndex for both entities.
- Schema rewrite is via DROP + CREATE in the same migration
  (applyV4ChangedHeroColumns and applyV5ChangedFactionDecomposition
  edited in place, same justification as the ChangedProvince hotfix:
  affected games never successfully ran these migrations, so editing
  isn't retroactively rewriting their history).
- For ChangedFaction's 15 child tables (4.5d.1): all gain n column,
  FK on (action_seq, n) → parent, keep faction_id denormalized for
  query convenience. Child tables that had their own within-vector
  index (renamed from n to i to avoid colliding with the parent's
  n). PK becomes (action_seq, n, i) for indexed children or
  (action_seq, n, <id>) for join tables.
- For ChangedHero's events child (4.5c.1): same treatment — add n
  for parent FK, rename internal n → i, keep hero_id denormalized,
  PK (action_seq, n, i).
- ChangedHeroTableReader updated to order by n (preserves the source
  changedHeroes vector order — multiple entries with the same
  hero_id come back in their original positions) and to filter
  events by (action_seq, n) so same-hero_id entries get their own
  event sets.

Tests:

- Existing tests that query "WHERE entity_id = X" on parent / child
  rows still work (entity_id remains a column, denormalized on
  children; single-row fixtures still match uniquely).
- Updated v4 backfill test's events ORDER BY n → ORDER BY i.
- Updated ChangedHeroTableReader "ordered by hero_id" test → now
  asserts insertion order (by n) instead of sorted-by-hero_id.
- Added two regression tests:
  - ChangedHero: two ChangedHeroes with the same hero_id in one
    action round-trip via the reader in their original order.
  - ChangedFaction: two ChangedFactions with the same faction_id
    in one action both land in the parent + child tables at n=0
    and n=1.

Out of scope: games on other deployments that successfully ran the
old (buggy) v4/v5 (because their history lacked duplicate-entity
actions) keep the old PK shape. They're not currently exercising
the bug. A separate v6 migration for those can land when 4.5h needs
the decomposed read path; same trade-off as the ChangedProvince
hotfix.

Verification:

- sqlite_history_test - 50/50 pass, including both new regressions
  and the updated reader ordering test.
- //src/test/scala/... - 225/225 pass. No regressions.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 21:45:37 -07:00
c0d00d4b81 Phase 4.5d.2 (live write): wire ChangedFactionTableWriter into withNewResults (#6736)
* Phase 4.5d.2 (red): live ChangedFaction decomposition test

Adds a failing test for the 4.5d.2 live-write contract. 4.5d.1
(#6734) added v5 schema + backfill but left SqliteHistory.with-
NewResults unchanged — it only writes the action_results payload
blob and (since 4.5c.2) ChangedHero. On a freshly-created game the
v5 backfill is a no-op, so action_changed_factions and its 15
child tables stay empty forever. That gap is what 4.5d.2 closes.

The new test builds a Scala ChangedFactionC directly (factionId 7,
newFactionHeadHeroId 11, newName "foo", newLeaderHeroIds [10, 20]),
hands it through withNewResults on a fresh DB, and asserts the
parent row plus the new_leader_hero_ids join table populated.

Scope: parent row + one join-table assertion. The writer's full
per-table behavior is already exercised by the v5 backfill tests
landed in 4.5d.1; the live-path test only needs to prove
withNewResults invokes ChangedFactionTableWriter.write at all. RED
on the current code with a clean assertion mismatch (false was not
equal to true at withRow's rs.next() — no parent row exists).

Adds changed_faction_concrete to the test BUILD deps (for the
Scala ChangedFactionC import). The impl that turns this green is
the next commit on the same branch.

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

* Phase 4.5d.2: wire ChangedFactionTableWriter into withNewResults

Turns the red test from the previous commit green. The existing
ChangedHero decomposition loop in withNewResults now also iterates
awrs.actionResult.changedFactions and calls ChangedFactionTableWriter.
write for each. Same shape as the ChangedHero live-path loop landed
in #6730. Sits inside the same transaction, after the action_results
executeBatch (FK target rows must exist), so a failure rolls back the
action_results inserts too.

Updates the comment to reflect both 4.5c.2 (hero) and 4.5d.2 (faction)
as the live write paths sharing this loop.

Verification:

- sqlite_history_test - 48/48 pass, including the previously-red
  4.5d.2 live write path test.
- //src/test/scala/... - 225/225 pass. No regressions on the critical
  write path.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 21:24:40 -07:00
b8cb342bc5 Phase 4.5d.1: ChangedFaction refined per-field decomposition (schema + backfill) (#6734)
* Phase 4.5d.1 (red): ChangedFaction schema v5 + backfill red tests

Sets up the refined per-field decomposition of ChangedFaction (Decisions
#2 in the design doc: classified `refined`, no whole-entity blob).

ChangedFactionC has 15 non-scalar Vector fields. Per the design doc's
refined-option-B tiers, each gets a child table sized to its shape:

- 9 primitive-ID join tables for Vector[HeroId/FactionId/ProvinceId]
  and the four Outgoing*OfferFactionId wrappers. Keyed by
  (action_seq, faction_id, value) so the join carries set semantics
  with no n column.
- 4 small-struct tables for PrestigeModifier (new + removed),
  FactionRelationship (changed), and TrustLevelUpdate. Explicit
  columns + n for ordering.
- 2 Tier-3 leaf-blob tables for DiplomacyOffer (sealed with 5
  subtypes including the deeper RansomOffer) and ProvinceView (deep
  aggregate with FullProvinceInfo plus nested vectors). Leaf-blob
  avoids re-incurring the child-table explosion option B exists to
  prevent.

All 15 tables FK (action_seq, faction_id) into the existing v2
action_changed_factions parent table ON DELETE CASCADE. Tier-1
scalars stay on that parent table (v2). Backfill populates parent
row + every applicable child row from each ChangedFaction in each
existing action_results.payload.

This commit (red):
- Writer stub (ChangedFactionTableWriter) with the real 15-table
  schemaStatements (the contract under review) and no-op write +
  backfill methods.
- Migration v5 hooked into SqliteHistory.Migrations.
- Two red tests in SqliteHistoryTest. The first exercises a fully-
  populated ChangedFaction through seedV1WithPayloads + load and
  asserts the parent row and every child table got the expected
  rows. The second asserts a minimal ChangedFaction leaves child
  tables empty but still emits a parent row. Both RED on the stub:
  schema exists (no "no such table" errors) but rows are absent, so
  the assertions fail cleanly.
- changed_faction_concrete visibility widened to the production
  service package (and the service test package) so the writer can
  consume ChangedFactionT. Same precedent as for ChangedHero in
  #6730.

The impl commit (next, same branch) fills in `write` and `backfill`
to turn the tests green.

Verification:
- sqlite_history_test - 44/46 pass, 2 RED for the right reason
  (clean assertion mismatches at the row-count and column checks,
  not exceptions or compile errors).
- //src/test/scala/... - 224/225 targets green elsewhere. No
  regressions.

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

* Phase 4.5d.1: implement ChangedFactionTableWriter (turns red tests green)

Fills in write + backfill so the two v5 backfill tests from the
previous commit pass.

write(connection, actionSeq, ChangedFactionT) pattern-matches to
ChangedFactionC and fans out:

- Parent row: INSERT into v2 action_changed_factions with the
  Tier-1 scalar / entity-reference columns.
- 9 primitive-ID join tables via a shared insertIds helper:
  (action_seq, faction_id, <id>) batched inserts. Covers
  newLeaderHeroIds, removedLeaderHeroIds,
  removedFactionRelationshipFactionIds,
  removedIncomingDiplomacyOfferFactionIds,
  removedReconnedProvinceIds, and the four
  newOutgoing{Truce,Alliance,Invitation,Ransom}OfferFactionIds
  (mapped through .fid to unwrap the type-safety wrappers).
- 4 small-struct tables: PrestigeModifier kind column uses
  prestigeModifierType.toString (matches case-object names like
  "Festival", "SuppressedBeasts"); FactionRelationship's reset_date
  becomes a year/month nullable pair, relationship_level uses
  toString of the sealed RelationshipLevel.
- 2 Tier-3 leaf-blob tables: DiplomacyOffer and ProvinceView convert
  per-element via DiplomacyOfferConverter.toProto(...).toByteArray
  and ProvinceViewConverter.toProto(...).toByteArray respectively,
  exactly at the storage edge.

backfill parses each existing payload, converts each ChangedFaction
proto to the domain type via ChangedFactionConverter.fromProto, then
delegates to the shared write path - one code path for live and
backfill.

Test fixture fix:

- DiplomacyOfferProto in the v5 backfill fixture now sets both
  offer_details (AllianceOfferDetails) AND status (UNRESOLVED). Real
  payloads have both; the converter rejects "Empty offer details"
  and "Unknown diplomacy offer status".

BUILD:

- changed_faction_table_writer gains deps on the model concrete /
  converter / state targets it now references: action_result_-
  concrete:changed_faction_concrete, proto_converters:changed_-
  faction_converter, proto_converters/diplomacy_offer,
  proto_converters/view/province:province_view, state/diplomacy_-
  offer, state/faction:faction_relationship + :prestige_modifier,
  state/date, view/province:province_view, internal:action_result_-
  scala_proto.
- 5 visibility widenings on production targets to expose them to
  //src/main/scala/.../service:__pkg__: changed_hero_concrete's
  precedent, applied here to changed_faction_concrete,
  proto_converters:changed_faction_converter, proto_converters/-
  diplomacy_offer:diplomacy_offer, state/diplomacy_offer:diplomacy_-
  offer, state/faction:faction_relationship + :prestige_modifier.
- Test BUILD gains diplomacy_offer_status_scala_proto for the
  fixture status field.

Verification:

- sqlite_history_test - 46/46 pass, including both v5 backfill
  tests.
- //src/test/scala/... - 225/225 pass. No regressions.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 16:44:37 -07:00
cf70169e3c Hotfix: v3 backfill crashes on ActionResults with duplicate-province ChangedProvinces (#6735)
Production games failed to load with SQLITE_CONSTRAINT_PRIMARYKEY
during the v3 ChangedProvince migration:

  UNIQUE constraint failed: action_changed_provinces.action_seq,
  action_changed_provinces.province_id

The v2 schema PK on action_changed_provinces was (action_seq,
province_id), which assumes at most one ChangedProvince per province
per action. That invariant doesn't hold: ActionResultApplierImpl folds
through result.changedProvinces sequentially and applies each as a
delta, so two entries for the same province in one action are two
valid sequential deltas, both applied. The v3 backfill iterated
.changedProvinces.foreach and INSERTed each, hitting the PK constraint
on the second entry. Confirmed in production logs for games
cf27e3e7... and 2798739...

Fix: change v3 to drop the v2 action_changed_provinces table and
recreate it with PK (action_seq, n), where n is the position within
the source ActionResult's changedProvinces vector. province_id stays
as an indexed column but no longer constrains uniqueness. Two
ChangedProvinces with the same province_id now land as two separate
rows with different n values.

Why edit v3 instead of adding a new migration:
- The games crashing are at schema_version less than 3 (or sitting at
  v2 with v3 never run). v3 itself crashes before any new migration
  could fix things. Editing v3 is the only path that lets affected
  games load.
- The CLAUDE.md "migrations are append-only" rule exists to prevent
  silently changing semantics for games that have already migrated.
  Here, the affected games never successfully ran v3, so editing it
  isn't retroactively rewriting their history.
- Nothing reads action_changed_provinces yet (4.5h hasn't shipped),
  so dropping and recreating the table is safe. v2 created it empty
  for crashing games; the drop is a no-op there.
- For games on other deployments that did successfully run the old
  buggy v3 (no duplicate-province actions in their history), their
  schema stays with the old shape. They're not currently exercising
  the bug. A separate v6 migration can drop+recreate for them when
  4.5h needs the read path. Out of scope for this hotfix.

Changes:
- ChangedProvinceTableWriter.schemaStatements now drops the v2 table
  and recreates it with the new PK shape plus the n column and the
  changed_province_proto BLOB. CREATE INDEX on province_id recreated
  (drop took it).
- ChangedProvinceTableWriter.write takes (connection, actionSeq, n,
  cp); INSERT includes n.
- backfill iterates changedProvinces.zipWithIndex.foreach and passes
  n to write.
- Regression test: an ActionResult with two ChangedProvinces sharing
  province_id (id=7, goldDelta 5 and 10) lands as both rows ordered
  by n. Pre-fix this crashes loaded() with SQLITE_CONSTRAINT_PRIMARYKEY.

Verification:
- sqlite_history_test - 45/45 pass, including the new regression.
- Full Scala suite - 225/225 pass.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 08:09:52 -07:00
e96a86f1a6 Phase 4.5c.2 (read path): ChangedHeroTableReader (#6733)
* Phase 4.5c.2 (red): ChangedHeroTableReader round-trip tests

Adds the failing tests for the 4.5c.2 read path. ChangedHeroTableReader
is the inverse of ChangedHeroTableWriter — it reconstructs the
ChangedHeroT domain values for a given action_seq from the v4 tables
(action_changed_heroes plus action_changed_heroes_new_backstory_events).
Nothing in production consumes it yet; replayFrom and friends still
parse action_results.payload. The reader exists to verify the v4
columns are a faithful round-trip representation (paired with the
writer landed in #6730) and to seed 4.5h, which will swap the production
read path off the payload blob entirely.

Three test cases for the read path contract:

- Round-trip a single ChangedHeroC with all three tiers populated
  (Tier-1 scalars, Tier-2 loyalty/vigor pairs, Tier-3 backstory
  event) through withNewResults and assert the reader reconstructs
  the exact same Scala value.
- Return Vector.empty for an action with no ChangedHeroes (the
  vacuous case — currently passes because the stub also returns
  Vector.empty, kept for the green-side guarantee).
- Return multiple ChangedHeroT ordered by hero_id (the writer does
  not preserve insertion order, so the contract is sort by id).

Stub returns Vector.empty so the red signal is a clean assertion
mismatch (parallel to the red test in #6730). Two of three cases are
RED on this commit. The impl will land as a follow-up commit on the
same branch after review.

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

* Phase 4.5c.2: implement ChangedHeroTableReader (turns red tests green)

Fills in the stub from the previous commit so the round-trip tests
pass. Inverse of ChangedHeroTableWriter:

- Pass 1: SELECT every row from action_changed_heroes WHERE action_seq
  = ? ORDER BY hero_id. Decode Tier-1 columns directly into
  ChangedHeroC fields. Tier-2 loyalty/vigor pairs decode to StatChange
  via column-name discrimination (delta column non-NULL means
  StatDelta, absolute column non-NULL means StatAbsolute, both NULL
  means StatNoChange, both non-NULL throws — that would be a violated
  schema invariant). newProfession reverses the writer: column holds
  the proto enum ordinal, ProfessionProto.fromValue then
  ProfessionConverter.fromProto. Backstory text id is a nullable
  String.
- Pass 2: for each hero, SELECT event_proto FROM
  action_changed_heroes_new_backstory_events WHERE action_seq = ? AND
  hero_id = ? ORDER BY n, parse each blob via
  EventForHeroBackstoryProto.parseFrom plus
  EventForHeroBackstoryConverter.fromProto. Reuses one
  PreparedStatement across all heroes.

Two passes (not a JOIN) because xerial sqlite-jdbc dislikes
interleaving statements with an open ResultSet, and the per-hero
event cardinality is small. The hero ResultSet is drained and closed
before any event query runs.

Verification:

- sqlite_history_test — 44/44 pass, including the three reader cases.
- Full Scala suite — 225/225 pass. No regressions.

BUILD deps added to the reader target: profession + event_for_hero_-
backstory proto targets (for parseFrom and fromValue), the two
proto_converters/hero targets (for the converters), and state/unit_-
status (transitively referenced via the EventForHeroBackstory
converter signature — same as the writer needs).

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 06:51:39 -07:00
a07b679a5a Phase 4.5c.2: live ChangedHero decomposition in withNewResults (#6730)
* Phase 4.5c.2 (red): failing test for live ChangedHero decomposition

Red-test PR, no production fix — committed for review before the
implementation, per the established workflow.

4.5c.1 (#6727) added the v4 schema plus a backfill that decomposes
ChangedHero out of *existing* action_results.payload during the
migration. It did not wire the decomposition into the live write path:
SqliteHistory.withNewResults still writes only the whole-ActionResult
payload blob (plus snapshots) and never calls ChangedHeroTableWriter.
On a freshly-created game the backfill is a no-op, so action_changed_heroes
and action_changed_heroes_new_backstory_events stay empty forever. That
gap is what 4.5c.2 closes.

This adds one failing test, "4.5c.2 live write path", asserting that a
ChangedHero pushed through withNewResults on a fresh DB lands in the v4
tables (tier-1/2 columns plus the tier-3 per-event blob rows) — symmetric
to the existing v4 backfill test but via the live path. It fails today on
the missing-row assertion (the action_results row is written, the
decomposed rows are not). It will go green when withNewResults invokes
ChangedHeroTableWriter.write inside the same transaction.

Scope notes:
- The test bypasses the applier deliberately. InMemoryHistory.fromResults
  runs ActionResultApplierImpl, which looks up hero 80 in an empty state
  and throws — not the behavior under test. The awrs is built directly
  from ActionResultProtoConverter.fromProto plus a trivial resulting
  state, exactly the shape withNewResults consumes.
- That needs two test deps (action_result_applier,
  action_result_proto_converter) and one additive visibility entry on
  the proto_converters target for the service test package — the
  Bazel-recommended, precedented fix (the list already grants other test
  packages). No production behavior change.
- Only the live-write half of 4.5c.2 is pinned here. The read-path
  reconstruction depends on an API not yet designed and gets its own red
  assertion when that lands.
- Full //src/test/scala/... is intentionally not run: a red-test PR makes
  it nonzero by design, so it yields no clean signal. The touched service
  test package was run instead — 18/19 targets green, only the intended
  new test red.

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

* Address review: build the Scala ActionResult directly, no converter

Review feedback: the test built a throwaway proto ActionResult only to
run it through ActionResultProtoConverter.fromProto. Construct the
domain ChangedHeroC / ActionResultC directly instead and hand
withNewResults exactly what it consumes.

Net changes vs the first commit:
- SqliteHistoryTest: the 4.5c.2 fixture is now ChangedHeroC (loyalty/
  vigor as StatDelta/StatAbsolute, newProfession Profession.Mage, one
  HeroDeparted backstory event) wrapped in ActionResultC. The tier-3
  read-back still parses the stored EventForHeroBackstory proto bytes
  and compares to an expected proto literal — that is verifying the
  stored format, not converting the input.
- Reverts the proto_converters visibility entry from commit 1 (the
  converter is no longer referenced), so that target is untouched vs
  origin/main.
- Test deps: drop action_result_proto_converter, add the model targets
  the direct construction needs (action_result_concrete,
  changed_hero_concrete, action_result/types, the two state/hero
  targets). action_result_applier stays (ActionResultWithResultingState).
- Widens three internal model targets to the service test package
  (changed_hero_concrete, event_for_hero_backstory_trait, profession).
  This is the cost of the direct approach over the converter (1 vs 3
  visibility entries) and was chosen deliberately on review.

Still a red-test PR. The new test fails for the same reason as before
(no action_changed_heroes row after a live withNewResults on a fresh
DB). Verified: 40/41 in the suite pass, 18/19 service targets green,
only the intended new test red. scalafmt + gazelle pre-commit pass.

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

* Phase 4.5c.2: wire ChangedHeroTableWriter into withNewResults (live path)

Implementation that turns the red test in #6730 green. 4.5c.1 (#6727)
added the v4 schema + a backfill that decomposed ChangedHero out of
existing action_results.payload during the migration, but left the
live write path untouched. On a freshly-created game the backfill is
a no-op, so action_changed_heroes and action_changed_heroes_new_-
backstory_events stayed empty forever. This wires the decomposition
into withNewResults so every new action's ChangedHero is written to
the v4 tables in the same transaction as the action_results row.

Mechanics:

- Hoist ActionResultProtoConverter.toProto out of the per-action loop
  to compute each protoResult once. It is both the stored blob and
  the source for the decomposed rows, so doing it twice was wasted
  work.
- After the action_results batch executeBatch (so the FK target rows
  exist), iterate protoResults again and call
  ChangedHeroTableWriter.write for each ChangedHero. Still inside the
  outer try, so a failure here rolls back the action_results inserts
  too — write atomicity preserved.

Verification:

- //src/test/scala/net/eagle0/eagle/service:sqlite_history_test —
  41/41 pass, including the previously-red 4.5c.2 live write path.
- //src/test/scala/net/eagle0/eagle/service/... — 19/19 targets green.
- //src/test/scala/... — 225/225 green. No regressions.

Read path is still the proto blob (replayFrom etc. unchanged). The
decomposed-table read path comes later in 4.5c.2 or in 4.5h when
action_results.payload is dropped.

This PR is stacked on #6730 (the red test). Merge #6730 first, then
this PR will rebase cleanly onto main.

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

* Address review: writer takes Scala domain types, not proto

The 4.5c.1 writer took ChangedHeroProto because its only caller was
the backfill (whose source is proto bytes parsed from existing
payloads). With the 4.5c.2 live caller in place, that interface is
wrong — the live path has Scala domain types and was being forced to
hand them through a proto round-trip that the writer then re-pattern-
matched. Refactors the writer to take the domain type and converts
only at the actual storage boundaries.

Writer changes (ChangedHeroTableWriter):

- write(connection, actionSeq, ChangedHeroT) instead of
  write(connection, actionSeq, ChangedHeroProto). Pattern-matches on
  ChangedHeroC (sole concrete impl).
- Tier-1/2 columns read Scala fields directly. Loyalty/vigor branches
  match on StatChange (StatDelta / StatAbsolute / StatNoChange)
  instead of the proto Loyalty.LoyaltyDelta / Vigor.VigorAbsolute /
  Empty cases.
- Tier-3 is the only proto edge: each EventForHeroBackstory is
  converted via EventForHeroBackstoryConverter.toProto(event).toByteArray
  inside the per-event INSERT loop, where the bytes actually go into
  the BLOB column.
- Profession stored as the proto enum ordinal via
  ProfessionConverter.toProto(p).value (None means no change means
  NULL), symmetric with ChangedHeroConverter.
- backfill stays the entry point for migrating existing payloads:
  parses ActionResult proto, converts each ChangedHero to ChangedHeroC
  via ChangedHeroConverter.fromProto, then hands it to the shared
  write. Live and backfill share one code path.

Caller changes (SqliteHistory.withNewResults):

- Drops the protoResults hoist that the previous impl introduced.
  payload is back to a single inline ActionResultProtoConverter.toProto
  in the action_results insert loop — exactly the pre-4.5c.2 shape.
- Decomposition loop iterates newResults.zipWithIndex and passes
  awrs.actionResult.changedHeroes (Vector[ChangedHeroT]) straight to
  the writer. No proto conversion in this loop at all.

The whole-action ActionResultProtoConverter.toProto at line 83 stays,
because the action_results.payload BLOB column is still proto bytes
until 4.5h drops it. That conversion is no longer load-bearing for the
decomposed writes though.

BUILD:

- changed_hero_table_writer drops common:profession_scala_proto (the
  ProfessionConverter handles it), adds the model concrete and
  converter targets it now references (changed_hero_concrete,
  changed_hero_converter, hero:event_for_hero_backstory,
  hero:profession), plus eagle_pkg (HeroId / ClientTextId aliases) and
  state/unit_status (transitively referenced through the
  EventForHeroBackstory converter signature).
- Three additive visibility entries on production targets, exposing
  them to the production service package:
  changed_hero_concrete, hero:event_for_hero_backstory, and
  changed_hero_converter all gain
  //src/main/scala/net/eagle0/eagle/service:__pkg__. This is the cost
  of the domain-types-at-the-edge approach and was chosen on review.

Test fixture fix:

- The v4 backfill test fixture now sets a date on each backstory
  event. Real EventForHeroBackstory protos always carry a date (the
  converter requires it). The previous fixture got away with date-less
  events because the old writer was a direct proto-bytes passthrough
  and never went through the converter. The new backfill does, so the
  fixture now matches what real payloads look like in the wild.

Verification:

- //src/test/scala/net/eagle0/eagle/service:sqlite_history_test —
  41/41 pass, including both v4 backfill tests and the 4.5c.2 live
  write path.
- //src/test/scala/... — 225/225 pass. No regressions.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 22:22:40 -07:00
c27715904c Design doc: record refined option B (ChangedHero 4.5c.1 reality) (#6729)
The 4.5c.1 PR (#6727) shipped a refinement of option B for ChangedHero
that the design doc never recorded, so the doc and the merged code
diverged. What actually merged: loyalty/vigor StatChange oneofs as
typed nullable column pairs (column name discriminates), and
newBackstoryEvents as per-event EventForHeroBackstory blobs in a child
table. No whole-entity changed_hero_proto blob. changed_hero.proto and
ChangedHeroConverter become deletable, only event_for_hero_backstory.proto
is retained as a leaf blob format.

Reconciles the doc with that reality:

- New authoritative "Refinement" subsection under Status defining the
  three-tier pattern (scalar columns, typed columns for sealed
  value-oneofs, per-row leaf-proto blobs in child tables) and the
  per-entity classification all-scalar / refined / deep.
- Scope, "Deleting the proto", ChangedHero section, Decisions #1-#3,
  and Sequencing rows 4.5c and 4.5i updated to match. 4.5c is split
  into 4.5c.1 (merged) and 4.5c.2 (live write/read path, pending).
- 4.5i is no longer "near-nothing": refined entities' protos and
  converters get deleted there, scope scales with how many entities
  went refined.

Documentation only. No code or schema change.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 07:16:36 -07:00
7830c42cd2 CLAUDE.md: forbid cd-prefixed commands; fix contradictory git rule (#6728)
Adds a no-`cd` rule to the CRITICAL BASH RULES section: run git/gh/bazel
directly from the cwd (repo/workspace discovery walks up from a subdir;
the shell resets cwd after every command so a cd never persists; and
`cd <dir> && <cmd>` also trips the no-chaining rule and forces an
approval prompt every time).

Also fixes the no-`git -C` rule, which previously said "Instead, cd to
the repo root" — directly contradicting the new rule. It now points at
the no-`cd` rule instead.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 07:03:29 -07:00
f4ef9d83c4 Phase 4.5c.1: ChangedHero scalar columns + proto blob (option B) (#6727)
* Phase 4.5c.1: ChangedHero scalar columns + proto blob (option B)

Same pattern as 4.5b/#6725, applied to ChangedHero. v4 migration:
ALTER TABLE action_changed_heroes ADD COLUMN changed_hero_proto BLOB +
a one-time backfill over existing action_results.payload that
populates the 4.5a scalar columns (faction change, XP/stat deltas,
profession, backstory text id, clear-events flag) and the full proto
blob. Inside the migration transaction; no-op on fresh games.

ChangedHero is shallow: only the sealed loyalty/vigor StatChange
oneofs and the newBackstoryEvents vector are non-scalar, and those
stay in the blob (the design doc flagged per-stat StatChange columns
as overkill — option B blobs them). new_profession stores the proto
enum ordinal, UNKNOWN_PROFESSION -> NULL, mirroring ChangedHeroConverter
and the improvement_type/action_result_type precedent.

Scalars are query denormalization; the blob is authoritative. Not in
this PR (4.5c.2): live withNewResults write path + read path.

~95-line writer, mirrors ChangedProvinceTableWriter. New
changed_hero_table_writer Bazel target. Tests: scalar promotion +
ChangedHero.parseFrom(blob) == original (covers the loyalty/vigor
oneofs that live only in the blob) + minimal-hero NULL case. Full
Scala suite green (225/225).

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

* Phase 4.5c.1: refined option B for ChangedHero — full columns + per-event blobs

Implements the two refinements suggested on #6727:

- Tier 2: store the loyalty/vigor StatChange oneofs as two nullable REAL
  columns each (loyalty_delta/loyalty_absolute, vigor_delta/vigor_absolute).
  The column name is the discriminator; at most one of each pair is non-NULL;
  both NULL ⇒ StatNoChange. No kind column.
- Tier 3: keep the EventForHeroBackstory proto and store just those bytes,
  one row per event, in action_changed_heroes_new_backstory_events.

ChangedHero now has no whole-entity blob: it round-trips losslessly from
columns + per-event blobs, so changed_hero.proto/ChangedHeroConverter become
deletable later while event_for_hero_backstory.proto is retained as the blob
format. Renames the v4 migration to applyV4ChangedHeroColumns and rewrites the
v4 tests for the new schema (loyalty/vigor columns + events child table).

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 06:48:53 -07:00
f76d4b785c Design doc: record option B + re-plan 4.5c-i per-entity (#6726)
ChangedProvince shipped via option B (scalars + proto blob, #6725), not
the full-relational "decision locked" plan. Update the doc so it stops
contradicting what's on main and so 4.5c-i has a coherent plan:

- New "Status — option B adopted" section at the top; it supersedes the
  body, which is kept as historical context / the migration target if a
  structured-query need on deep aggregates ever appears.
- Rescind "Decisions locked #1" (fully relational, no blob fallback);
  rewrite the locked decisions around option B + per-entity blob choice.
- Re-plan the Sequencing table per-entity: each gets 4.5a scalars + an
  <entity>_proto BLOB, split .1 (schema+backfill) / .2 (live+read).
  Estimate drops from ~3-4 weeks to ~1.
- Revise principle 7 (proto blob is the retained authoritative store),
  the Scope (per-entity protos are NOT deleted), and "Deleting the
  proto" (superseded).

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 07:21:20 -07:00
7d6961fc86 Phase 4.5b (option B): ChangedProvince scalar columns + proto blob (#6725)
Alternative to PR #6721. Applies the design doc's "stopping rule"
consistently: instead of exploding ChangedProvince's ~25 nested
aggregates into ~37 child tables, keep the v2 top-level
action_changed_provinces table (per-(action,province) scalar deltas +
the province_id index — the part anyone actually queries) and store the
full ChangedProvince proto in one changed_province_proto BLOB for
lossless round-trip / replay.

This is the same reasoning the doc already applies to Quest, applied to
the deep army/unit/hero nesting that is likewise never analytics-
queried. ~110 lines of writer vs ~1100 in the full-relational approach.

The scalar columns are pure query denormalization; the blob is
authoritative. A future fully-relational pass (if a structured-query
need on the deep aggregates ever materializes) is a pure
read-blob -> write-columns migration — which is why the blob must
survive any later proto deletion. This deliberately re-opens the doc's
"new-entity vectors are fully relational, no blob fallback" lock; the
quest hybrid is the precedent.

Not in this PR (would be 4.5b.2): the live withNewResults write path
and the read path. Nothing reads these columns yet.

v3 = ALTER TABLE action_changed_provinces ADD COLUMN
changed_province_proto BLOB + a one-time backfill over existing
action_results.payload (scalars + blob), inside the migration
transaction; a no-op on freshly-created games.

Tests: a ChangedProvince with a genuinely nested aggregate (defending
army -> combat unit) + a repeated field, asserting scalar promotion and
that ChangedProvince.parseFrom(blob) == original (proves the deep
structure round-trips), plus that no child tables are created. Full
Scala suite green (225/225).

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 11:17:09 -07:00
9b6cbe6455 Fix tutorial chronicle crash: tutorial creation must use SqliteClientTextStore (#6724)
* Red test: tutorial game text store diverges from reload path

createTutorialGameForUser builds its ClientTextStore as the legacy
file-based ClientTextStoreImpl (persists to completeText.txt), but every
reload reconstructs the store from text_store.db via
SqliteClientTextStore.loaded. Texts generated during a tutorial session
(e.g. yearly chronicle updates) are therefore unrecoverable after a
save+reload, surfacing in production as:

  EagleInternalException: Unknown dependency for LLM request
  chronicle_update_373_11: chronicle_update_371_11

This is a failing regression test only — no fix yet. It creates a
tutorial game, persists a chronicle text through the game's live store,
then reads it back via the production reload path and asserts it
resolves. Fails today (TextGenerationDependencyUnknown).

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

* Fix: tutorial creation uses SqliteClientTextStore (text_store.db)

createTutorialGameForUser built its ClientTextStore as the legacy
file-based ClientTextStoreImpl (completeText.txt), while every reload
reconstructs the store from text_store.db via SqliteClientTextStore.loaded
and normal game creation already uses SqliteClientTextStore. Texts
generated during a tutorial session (e.g. yearly chronicle updates) were
written to completeText.txt and lost on the first save+reload, causing:

  EagleInternalException: Unknown dependency for LLM request
  chronicle_update_373_11: chronicle_update_371_11

Switch tutorial creation to SqliteClientTextStore.createWithData, matching
the normal-creation path, so create and reload agree on text_store.db.
Behavior-preserving otherwise (unrequestedTexts/accessibleTo were already
empty here). Turns the regression test from the previous commit green;
full Scala suite (225 tests) passes.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 23:17:16 -07:00
9eb90c2cb4 Vary maxWindMph per map by terrain composition (#6723)
All maps shipped with maxWindMph: 25 for every month, giving them no
geographic windiness identity. This sets maxWindMph based on each
map's terrain mix — open terrain (plains, still water) pushes the
ceiling up, dense terrain (forest, swamp) pulls it down — with a
small additional bump on winter months (proxied by snow/blizzard
chance).

Spread across maps now ranges roughly 20–29 mph (median 24).
Forest-heavy maps like Nikemi land at 20–22; open-water maps like
Chia and field maps like MeetThemInTheField land at 27–29.

Note: the existing exploding-roll mechanic in NewWeather amplifies
the tail proportionally, so a 28 mph cap produces ~55 mph outliers
where a 22 mph cap produces ~44 mph outliers (same ~5% explosion
frequency). That's intended texture but worth flagging if any of the
downstream wind consumers want a tighter cap.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 10:15:25 -07:00
48a44e126a Couple wind speed to weather conditions (#6722)
Wind speed was previously a uniform-then-exploding roll against a
per-map maxWindMph, with no awareness of the rolled weather
conditions. Stormy days were as likely to be calm as sunny days.

This adds six per-condition multipliers (settings.tsv) applied on top
of the existing wind-speed formula. Defaults: 1.0× for sun/clouds,
1.2× for rain/snow, 1.5× for thunderstorms, 1.8× for blizzards.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 10:14:49 -07:00
b8605a3662 Fix free-hero backstory visibility (placement hook + load migration) (#6719)
* Red test: Traveler move does not extend backstory visibility to dest ruler

Reproduces the [BACKSTORY-VISIBILITY] production diagnostic. When a Traveler
unaffiliated hero with a backstory moves into a province, the destination
province's ruling faction should gain visibility of the hero's backstory text
(as ProvinceConqueredAction and TravelCommand already do for their cases).

PerformUnaffiliatedHeroesAction.heroMovedResult builds the HeroMoved result
with no clientTextVisibilityExtensions, so this test FAILS until the fix:

  Vector() did not contain element
  ClientTextVisibilityExtensionC("Leah_backstory 0", Vector(2))

The move + relocation sanity assertions pass; only the visibility assertion
fails, isolating the root cause. Committed test-only for review before the fix.

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

* Red test: stationary free hero's ruler change does not extend backstory visibility

Adds the broader case behind the [BACKSTORY-VISIBILITY] diagnostic: a free
hero with a backstory sitting still in a province whose current ruler is not
in the backstory's visibility set. Conquest already extends visibility via
ProvinceConqueredAction, but nothing heals a stationary hero whose ruler
changed by other means (faction split, vassal independence, inheritance).

The per-round unaffiliated-hero phase emits no clientTextVisibilityExtensions
for this case, so the test FAILS until the fix:

  Vector() did not contain element
  ClientTextVisibilityExtensionC("Leah_backstory 0", Vector(2))

14 pre-existing tests still pass; the 2 new red tests isolate the two gaps
(Traveler move-in, and stationary ruler-change). Test-only for review.

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

* Fix: extend free-hero backstory visibility to current province ruler

Two complementary fixes for the [BACKSTORY-VISIBILITY] diagnostic; turns the
two red tests green (16/16 in the class, full Scala suite 224/224).

1. heroMovedResult: the HeroMoved ActionResult now emits a
   ClientTextVisibilityExtensionC for the destination province's ruling
   faction (guarded by backstoryVersions.nonEmpty, since backstoryTextId
   throws on empty). Mirrors ProvinceConqueredAction and TravelCommand,
   keeping visibility extension atomic with the move event.

2. EndUnaffiliatedHeroActionsPhaseAction: a per-round self-healing sweep
   emits visibility extensions for every free hero with a backstory to its
   province's current ruler. Covers ruler changes by non-conquest means
   (faction split, vassal independence, inheritance) where the hero is
   stationary, and retroactively heals already-stuck heroes. Visibility is
   additive and de-duplicated downstream, so re-emitting each round is safe;
   the engine has no visibility state to dedupe against, so this redundancy
   is the deliberate tradeoff.

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

* Redesign: fix backstory visibility at placement + one-time load migration

Replaces the per-round sweep with the true root-cause fix. Pool heroes arrive
with a pre-authored backstory and previously had NO visibility set at
appearance (the all-faction request fires only for spawned heroes with an
empty backstory), so they were legible only to whatever faction a later narrow
event happened to extend to.

- UnaffiliatedHeroAppearedAction: for the pre-existing-backstory branch, emit
  a ClientTextVisibilityExtensionC to all factions, matching the spawn-time
  policy. This is the missing event-driven hook.
- Reverted the EndUnaffiliatedHeroActionsPhaseAction per-round sweep: the only
  engine path that changes a province's ruler is ProvinceConqueredAction
  (already handled), so no perpetual sweep is needed for correctness.
- heroMovedResult fix (Fix 1) retained: extension stays atomic with the move.
- FreeHeroBackstoryVisibilityRecovery: one-time on-load repair (mirrors
  MissingHeroNameRecovery) widening any free-hero backstory not visible to its
  current province ruler. No-op for healthy games; heals already-stuck heroes
  like prod hero 184. Wired into GamesManager.gameController load path.

Tests: placement-hook tests in UnaffiliatedHeroAppearedActionTest, migration
tests in new FreeHeroBackstoryVisibilityRecoveryTest, Test 1 (move-in) kept,
obsolete sweep test removed. Full Scala suite 225/225.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:02:25 -07:00
2d3779448c Draw faction-target province highlights as a single grouped outline (#6720)
When the Diplomacy command selector targets a faction, MapController
was drawing TargetedProvinces with per-province borders, so each of
the faction's provinces got its own outline (including the internal
borders between adjacent same-faction provinces). The visual the
user wanted is the unified outline used by notifications and popups:
one boundary around the faction's territory as a whole.

The mechanism already exists — ProvinceBorderManager.SetHighlightGroup
fills a per-province lookup texture that the shader consults to
suppress borders between provinces in the same group, and
OverrideTargetedProvinces uses it. TargetedProvinces was calling
ClearHighlightGroup unconditionally.

Add MapController.TargetedProvincesAsGroup. When true, the no-override
branch calls SetHighlightGroup(TargetedProvinces) before the existing
per-province strobe/border loop, producing the unified outline.
EagleGameController.Update sets the flag to
selector.TargetedFactionIds.Count > 0 alongside the existing
mapController.TargetedProvinces assignment, so it stays in sync with
the selector each frame.

DiplomacyCommandSelector itself needs no change — its TargetedFactionIds
is already non-empty when a target faction is picked, and the base
CommandSelector.TargetedProvinces getter already expands a non-empty
TargetedFactionIds into the faction's provinces. Other selectors
(AttackDecision, BattleAftermath) don't populate TargetedFactionIds
and so render per-province as before.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:01:15 -07:00
7eb5894a57 Phase 4.5a: schema migration scaffolding + changed-entity top-level tables (#6716)
Introduces an append-only migration system for SqliteHistory and adds
the four "changed entity" top-level tables (scalar columns only). No
write or read paths target these tables yet — they're scaffolding for
the per-aggregate decomposition that lands across Phase 4.5b–e. See
docs/SQLITE_ACTION_RESULT_DECOMPOSITION.md.

Migration runner
- `SqliteHistory.Migrations` holds a Vector[Migration(version, apply)],
  append-only. Versions must be strictly ascending; new schema work is
  always a *new* migration, never an edit of an existing one.
- `applyPending` reads `metadata.schema_version`, runs every migration
  with a higher version, bumps the stored version after each — the whole
  sequence inside a single transaction so a partial failure rolls back
  to the pre-migration version.
- `metadata.value` is now TEXT (was BLOB) to hold the schema_version as
  a stringified int. The column had no readers before this PR.

v1 — baseline
The existing tables (action_results, state_snapshots, shardok_*),
unchanged, repackaged into the migration runner. Idempotent (CREATE
TABLE IF NOT EXISTS) so any pre-migration DB that already has these
tables ends up at v1 without an error.

v2 — changed-entity top-level tables
- action_changed_provinces (PK action_seq + province_id) with the
  scalar fields of ChangedProvinceC.
- action_changed_heroes (PK action_seq + hero_id) with the scalar fields
  of ChangedHeroC. StatChange fields (loyalty/vigor) and
  newEventsForHeroBackstory are deferred — they belong in child tables
  per the design doc.
- action_changed_factions (PK action_seq + faction_id) with the scalar
  fields of ChangedFactionC.
- action_changed_battalions (PK action_seq + battalion_id only).
  ChangedBattalionC has no scalar fields at the top level — its sole
  field is the contained BattalionT, which gets its own decomposition
  in Phase 4.5e.
- Per-entity-id indexes on each of the four tables so cross-game queries
  like "all actions touching hero X" are single-index lookups.
- FOREIGN KEY (action_seq) REFERENCES action_results(action_seq)
  ON DELETE CASCADE on each, so truncateTo only needs to drop from
  action_results and the rest cascades.

Tests
- Fresh DB ends up at `latestSchemaVersion`.
- All four new tables exist after create.
- Re-loading is a no-op (no migrations re-run, no schema_version change).
- A simulated pre-v2 DB (v1 baseline + schema_version='1') upgrades to
  the latest version and gains the new tables on load.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 16:36:34 -07:00
e9f10ee540 Phase 4 fix: wire SqliteHistory through the cloud persister (#6718)
Phase 4's cutover wrote game.db only to local disk. PersistedHistory had
shipped every chunk through the Persister, so .e0a files landed in S3
(DigitalOcean Spaces in prod) automatically; SqliteHistory dropped that
because the dbFile-based factories never accepted a Persister.
Result: a Hetzner host crash would lose every active game; only
text_store.db survived in cloud storage. This restores parity with the
SQLITE_HISTORY_DESIGN.md plan (lines 43, 244–245, 271).

Mechanism
- `SqliteHistory` constructor now takes `dbFile` + `Option[Persister]`.
  After each successful `withNewResults` commit, it calls
  `maybeUploadToPersister(previousCount)`, which uploads the whole
  game.db blob when either (a) the batch crossed at least one 25-action
  snapshot boundary or (b) more than 60s has elapsed since the last
  upload.
- Before reading bytes off disk, it issues
  `PRAGMA wal_checkpoint(TRUNCATE)` so the uploaded file is a
  self-consistent snapshot — without the checkpoint the upload would
  miss whatever's still in game.db-wal.
- Upload failures are caught + logged so a transient cloud-storage
  outage does not break local game progress.
- `AsyncS3Persister` (the production wiring) already coalesces saves for
  the same key on a 500ms tick and has a JVM shutdown-hook flush, so
  uploading more often than that costs at most a memcopy.

Load path
- New `SqliteHistory.loadedOrDownloaded(dbFile, persister)` first tries
  the local file, otherwise tries `persister.retrieveAsStream("game.db")`
  and writes it locally. Returns `None` when both are absent (the game
  simply does not exist).
- `GamesManager.gameHistoryFromFiles` uses this so a wiped local saves
  directory recovers games from cloud storage on next boot.

Plumbing
- `NewGameCreation.createEngine` and
  `TutorialGameCreation.createTutorialGame` pass their `persister` to
  `SqliteHistory.createWithScalaResults` (un-`@annotation.unused`).
- BUILD: sqlite_history depends on the persister target; the
  SqliteHistoryTest target depends on it as well.

Tests
- An in-memory `FakePersister` records save calls.
- `withNewResults` triggers an upload at the 25-action boundary but not
  before; a single batch spanning a boundary also triggers exactly one.
- No persister configured → no observable behavior change.
- `loadedOrDownloaded` opens the local file when present; downloads from
  the persister when the local file is missing; returns `None` when
  both are absent.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 16:31:34 -07:00
58030a56a7 Split Eagle server fat JAR into deps + app Docker layers (#6717)
The Docker Build and Push workflow spends more time pushing than building
because the entire ~115MB Eagle classpath ships as one pkg_tar layer, so
every Scala commit re-uploads the whole blob to DOCR.

Add a jar_split rule that partitions the scala_binary's transitive runtime
jars by workspace into a stable third-party layer (76MB, 137 jars) and a
first-party layer (38MB, 989 jars). crane skips the unchanged deps blob, so
typical Scala-only commits re-upload ~38MB instead of ~115MB. Entrypoint
switches from -jar fat.jar to a -cp classpath glob over both layer dirs.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 16:19:47 -07:00
3a45347549 Phase 4: cutover game creation from PersistedHistory to SqliteHistory (#6715)
GamesManager, NewGameCreation, and TutorialGameCreation now open per-game
game.db SQLite files via SqliteHistory instead of chunked .e0a blobs via
PersistedHistory. PersistedHistory remains in the tree so the existing
unit tests still build; it is no longer reachable from the running server.

- SqliteHistory.createWithScalaResults / emptyStartingState convenience
  constructors mirror the PersistedHistory new-game shape (raw scala
  ActionResultTs folded through the applier).
- GamesManager.gameHistoryFromFiles looks up
  saveDirectoryForGame(gameId)/game.db and opens it with
  SqliteHistory.loaded; the persister is now unused on that path.
- TutorialGameCreationTest's "successfully creates" case forces the lazy
  val instead of calling createTutorialGame a second time with the same
  gameId — duplicate creates would collide on snapshot PK.
- Tests that exercise game creation point eagle.save.dir at a temp dir so
  the bazel sandbox can write game.db.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-14 06:29:49 -07:00
660d349e50 Design doc: full decomposition of ActionResult into relational tables (#6714)
* Design doc: full decomposition of ActionResult into relational tables

Follow-up to docs/SQLITE_HISTORY_DESIGN.md. Plans replacing the
proto-blob action_results.payload with native relational tables for
every field of ActionResultC, recursively.

Key facts that motivate full decomposition (vs blob middle ground):
- ActionResult-family protos are storage-only (one file imports them,
  ChangedProvinceConverter; no RPC consumers).
- ActionResultC has no top-level polymorphism — 34 flat fields with no
  sealed-trait discriminator at the action level.
- Pre-alpha is the right window: we can nuke save dirs as part of the
  rollout, and we never have to migrate real user data.

Doc covers principles, top-level schema, the four changed-entity
families (~25 tables each under the ChangedProvince family), notifications
and generated-text-requests, the "new entity" vectors with a fallback
flag, schema migration scaffolding (now load-bearing), read/write/replay
path changes, and a 9-step sub-phase plan (4.5a–4.5i) starting after the
Phase 4 cutover lands. Three open questions for sign-off at the bottom.

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

* Lock in the three open questions

- "New entity" vectors get full relational decomposition (no blob fallback).
- Sub-phase ordering stays as proposed.
- Phase 4 cutover lands separately, before 4.5a starts.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 06:51:34 -07:00
57c2862a57 Phase 3: SqliteHistory shardok integration (#6713)
All seven FullGameHistory shardok methods land, plus truncateTo cleanup
of orphaned battles. Pure foundation — no production caller yet.

Schema:
- shardok_results: (shardok_game_id, action_seq) -> ShardokActionResult bytes
- shardok_state: shardok_game_id -> (game_state bytes, last_eagle_round_id)
- shardok_player_results: (shardok_game_id, faction_id, seq) -> ActionResultView bytes
- shardok_player_commands: (shardok_game_id, faction_id) -> AvailableCommands bytes (nullable)

Behavioral semantics mirror PersistedHistory:
- shardokPlayerCount / shardokPlayerResultsSince fall back to faction -1
  if the requested faction has no registered presence.
- shardokPlayerAvailableCommands does NOT fall back to -1 (exact match only).
- withNewShardokResults: append results and per-faction views, upsert
  per-faction commands (replacing previous value, NULL if not in the new
  availableCommands), upsert per-battle game_state. Touched factions =
  old participants union newPlayerResults factions.
- withResetShardokResults: drop all rows for the given battle.

truncateTo now uses stateAfter(target).outstandingBattles to determine
which shardok rows to preserve; rows for any other battle are deleted in
the same transaction. Mirrors deleteOrphanedShardokFiles.

8 new tests covering each method plus the full battle reset case.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 06:30:39 -07:00
3923ae8c11 Phase 2: SqliteHistory read paths (all / since / sinceDate / recentResultsForRound) (#6712)
All four trait methods land via a single replayFrom helper: find the latest
snapshot at or before the emit boundary, replay forward to the end of the
range, emit ActionResultWithResultingState only for action_seq >= emitFrom.

- all: replayFrom(0, count)
- since: clamp start to [0, count], replayFrom(start, count)
- sinceDate: SQL SELECT MIN(action_seq) WHERE date_year IS NOT NULL AND
  (date_year, date_month) >= (?, ?), then replayFrom(thatSeq, count).
  Matches PersistedHistory semantics: actions with NULL date are filtered
  out (they're pre-game-start; once currentDate is Some it stays Some).
- recentResultsForRound: SQL SELECT MIN/MAX(action_seq) WHERE round_id = ?,
  replay that contiguous range, filter by the Scala predicate.

stateAfter is refactored to share the new readLatestSnapshotAtOrBefore
helper. Behavior unchanged.

Tests cover all four methods including snapshot-boundary crossings and
out-of-range clamping.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 21:10:53 -07:00
d0e39bfc02 Phase 1: SqliteHistory skeleton — schema, write paths, stateAfter (#6711)
Adds SqliteHistory implementing FullGameHistory. Phase 1 scope:

- Schema (action_results, state_snapshots, metadata) with WAL, NORMAL
  synchronous, FK pragmas at connection init.
- Lifecycle: create(dbFile, startingState), createWithResults(...),
  loaded(dbFile), close().
- Write paths: withNewResults (transactional batch insert + snapshot at
  every 25-action boundary), truncateTo, saveNow (no-op).
- count cached in-memory, refreshed from DB on construction.
- last and stateAfter implemented via snapshot+replay (latest snapshot
  <= N, replay forward via ActionResultApplier).
- Other read paths (all, since, sinceDate, recentResultsForRound) and
  all shardok methods throw NotImplementedError with phase markers;
  filled in in Phase 2 and 3.

Tests cover: empty create, withNewResults sequencing, snapshot writes
at the 25-boundary, stateAfter at and between boundaries, truncateTo,
saveNow no-op semantics, reload-and-continue.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 21:03:43 -07:00
78ed12052b Phase 0: SQLite game history design doc (#6710)
* Phase 0: SQLite game history design doc

Per-game game.db replaces .e0a / .e0s / .e0i file-based persistence.
SqliteHistory implements the existing FullGameHistory trait so the
cutover at the call site is a single constructor swap.

Schema, connection lifecycle, read/write paths, snapshot strategy,
shardok results layout, migration trigger, rollback policy, and four
open questions called out for sign-off before Phase 1.

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

* Phase 0: fold in user feedback — drop migration, separate DBs rationale

- Remove the migration importer entirely. At cutover we nuke save
  directories one time; pre-alpha trade-off accepted explicitly.
- Add the writer-lock-contention rationale for keeping game.db and
  text_store.db as separate files instead of one combined DB.
- Lock in the four open questions with the agreed defaults.
- Note the GameAdminServiceImpl.getActionDetail follow-up to move off
  history.all; not blocking.
- Phase plan drops from 5-6 weeks to 3-4 weeks with migration gone.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 17:19:04 -07:00
abdb91b8d9 Add direct domain ↔ Common-proto enum converters (#6709)
CommonConverters and ShardokInterfaceGrpcClient.fromCommon no longer
round-trip through the Eagle proto enums to harvest .value: Int just to
feed CommonProfession.fromValue / CommonBattalionTypeId.fromValue.

New CommonEnumConverters defines CommonProfessionConverter and
CommonBattalionTypeIdConverter with toCommon / fromCommon. The shardok
interface boundary now only touches domain types and the Common proto
it's actually emitting; the Eagle proto enums are out of this path.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 16:01:44 -07:00
2debfe546c Drop proto conversion in ShardokInterfaceGrpcClient.resolveBattle (#6708)
EagleUnit now holds domain HeroT and Option[BattalionT], and ExpandUnit
takes the domain GameState. That removes the per-battle
GameStateConverter.toProto call and the dual-arg playerInfo signature.

CommonConverters.toCommon reads domain fields and routes Profession /
BattalionTypeId through the existing proto converters to keep the
Common* enum values stable.

fromCommon now builds HeroC / BattalionC directly instead of building
proto types only to convert them back to domain at the call site.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 15:36:40 -07:00
5d81972093 Use domain GameState in ShardokInterfaceProxy.resolveBattle (#6707)
* Use domain GameState in ShardokInterfaceProxy.resolveBattle

The Shardok gRPC client used to take a proto GameState directly, which
forced GamesManager to convert domain → proto right before the call
and forced the client to inline its own proto-relationship-level
filtering. Now the trait accepts the domain GameState; the gRPC client
uses FactionUtils.alliedFactions for the watcher derivation and reads
the relationship enum via the domain Hostile case object. Proto
conversion still happens once inside the client where the unit-
construction helpers (toCommon, EagleUnit.ExpandUnit) require it.

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

* Use FactionUtils.nonHostileFactions and flag the dual-arg as TODO

Add a nonHostileFactions helper to FactionUtils paralleling alliedFactions,
covering Ally + Truce (and defensively Unknown). playerInfo now uses it
instead of the inline relationshipLevel != Hostile filter.

Add a TODO at the GameStateConverter.toProto call inside resolveBattle so
the dual-arg playerInfo signature (domain + proto) doesn't calcify -- it's
a transition state until toCommon and EagleUnit.ExpandUnit are moved to
take the domain GameState.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 15:05:45 -07:00
c8aa26058b Send watcher faction IDs in Shardok NewGameRequest (#6705)
Populates the watcher_eagle_faction_ids field added in the prior
Shardok-side change. The watcher set is the union of each
participant's non-hostile faction relationships, minus the
participants themselves.

Once both this and the Shardok-side change are deployed, factions
allied to a battle's participants but not themselves participating
receive filtered views that include hero stats and hidden actions for
their allies' units.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 13:55:06 -07:00
386d99d553 Cache parsed games.e0es to skip per-lobby-tick re-parse (#6706)
* Cache parsed games.e0es to skip per-lobby-tick re-parse

games.e0es was being read from disk and parsed by six call sites:
ensureGameLoaded, gamesFor, gamesForWithoutBlocking, loadGamesInBackground,
save (for the merge), and getAllRunningGamesSummary. Combined with the
EagleServiceImpl path that fans lobby updates out to every connected user
on every game-affecting action, this produced repeated "Read N ongoing
games from games.e0es" log lines per lobby tick and a parse-and-allocate
churn that grew with both lobby user count and games count.

The freshness justification ("called fresh each time to handle race
conditions during blue-green deployment") is already covered by the
existing flush-marker invalidation: when the active server flushes
state, the new server detects the flush-marker mod-time bump and clears
its caches.

Add an in-process cache (cachedRunningGames) populated lazily by the
read paths and refreshed at the end of save() from the just-written
state. The flush-marker invalidation path also clears the cache so
blue-green semantics are preserved.

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

* Use Option.getOrElse instead of match in runningGamesFromStorage

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 13:54:02 -07:00
b3d99c6f85 Generate ally-aware Shardok views for non-participant watchers (#6704)
When a faction watches an ally's battle, the Eagle layer falls back to
Shardok's generic observer (factionId == -1) view because Shardok only
emits filtered views for battle participants. The observer view treats
every unit as an enemy, so visibility is knowledge-gated: battalion
stats (threshold 50) usually creep above the floor while hero stats
(threshold 75) lag behind, leaving watchers with battalion data but no
hero stats for their own allies' heroes.

This change adds a watcher_eagle_faction_ids field to NewGameRequest
and has Shardok emit one filtered view per watcher in GetUpdates. Each
watcher's view treats their allied participants' units as fully
visible (hero stats, hidden actions like meteor casts, hidden-target
coords) while non-allied units fall back to observer-style knowledge
gating.

The watcher path is implemented via new
GameStateFilteredForPlayerWithAllies and
ActionResultFilteredForPlayerWithAllies overloads that take alliedPids
explicitly, plus a new ShardokEngine::FilterNewResultsForWatcher that
drives them. The IsHiddenFromOpponents predicate now treats the
actor's allies as self for visibility purposes.

The Eagle side that populates watcher_eagle_faction_ids is in a
follow-up PR; this change is a no-op until that lands.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 13:49:11 -07:00
afb143645a AI: imprison the messenger when accepting a truce would box us in (#6702)
If the AI's only neighbor is the proposing faction (every one of our
provinces' neighbors is owned by us or them), accepting a truce locks
us out of attacking the only faction we could expand into for the
duration of the truce. The existing alliance-acceptance guard already
catches this for alliances; truces had no such guard and the AI would
happily accept and stagnate.

When boxed-in:
  - choose Imprisoned if the offer's eligible statuses include it
    (which requires us to have at least one province, per
    EligibleDiplomacyStatuses.maybeImprisonStatus)
  - otherwise fall back to Rejected.

Factor the boxed-in predicate into a shared helper
(acceptingWouldBoxUsIn) and have allianceOfferAcceptanceChance use it
so the two paths stay in lockstep.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 20:31:59 -07:00
ba160b9669 AI: break alliance with weakest bordering ally when boxed in (#6700)
When the midgame AI has no neutral or hostile neighbors anywhere on its
border, it has no path to growth and gets stuck in the
chosenNoNeutralNeighborsCommand fallback resting and improving forever.
The upstream allianceOfferAcceptanceChance guard refuses alliances that
would immediately box us in, but that state can still emerge later --
e.g., a shared hostile neighbor gets conquered by our ally.

Add a chooser that, in that state, finds the weakest bordering ally
(measured by province count, since post-truce conquest is the goal)
and emits a DiplomacyAvailable BreakAlliance command targeting them.
Inserted just before chosenNoNeutralNeighborsCommand so the recovery
path runs ahead of the catch-all rest/improve.

Truces are intentionally not treated as boxing-in: they expire, and
breaking would burn trust unnecessarily -- waiting them out is cheaper.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 19:51:38 -07:00
5664f15dac Push locally-resolved hero names to connected clients (#6698)
Hero names from the local heroNameCache (and FixedHeroName text) are
resolved synchronously inside UnrequestedTextHandler and stored as
complete in the ClientTextStore -- but unlike LLM-generated text, they
never flow through the streaming pipeline that pushes updates to
connected clients. Mid-session UIs sit on the "Hero" fallback until the
user reconnects (which triggers the on-subscribe bulk-send of every
accessible complete text).

Surface the resolved CompleteClientTexts from
clientTextStoreWithHandledUnrequestedTexts via a new
HandledUnrequestedTextsResult, and have GamesManager push them through
GameController.withResolvedTextsPushedToClients (which routes through
the existing humanClientsAfterUpdatingLlmStream path used for LLM
streaming responses). Initial-load callers continue to ignore the
list since the on-subscribe bulk-send already covers that case.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 19:24:06 -07:00
8009ed62d2 Auto-fire End Turn after AI action when next player has no options (#6699)
The AI thread's post path didn't run the only-one-option auto-loop, so
when an AI player ended their turn and control passed to a player whose
only available command was End Turn (e.g., a player with one stunned
unit), that player had to click End Turn manually. The human-driven
PostCommand path already called PostWhileCurrentPlayerHasOnlyOneOption.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 19:21:26 -07:00
8abd355883 Suppress FMOD output-switch error in ErrorHandler (#6696)
Unity's internal FMOD wrapper logs an Error whenever the macOS audio
output device changes (headphones plug/unplug, AirPods, system output
switch): the wrapper tries to call setOutput on FMOD after System::init
and FMOD rejects with "Cannot call this command after System::init"
(error 32). The audio continues to play on whichever device was active
at app launch; nothing actionable for us, but the message was reaching
ErrorHandler and surfacing the in-game error panel.

Filter the specific message in ErrorHandler.HandleLog. Match both
halves of the string so a genuine FMOD failure (different cause) still
surfaces.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 19:11:22 -07:00
fb8408fd64 Gate Observe battle button on ShardokGameModel readiness (#6697)
ShardokBattles is populated when a NewBattle eagle update arrives, but
the matching ShardokGameModel isn't created until the first
ShardokActionResultResponse for that battle reaches the client (in
EagleGameModel.MakeGameModel via the ReceiveGameUpdate handler). In
that gap, the Observe button on an allied battle was unconditionally
interactable, and clicking it threw KeyNotFoundException out of
EagleGameController.GoToBattle's Model.ShardokGameModels[gameId]
indexer access.

Gate the Observe button on Model.ShardokGameModels.ContainsKey(gameId).
Show "Loading..." until the matching shardok model arrives, then flip
to interactable "Observe". The Self/Fight! path was already implicitly
gated via fightableGameId (derived from RunningShardokGameModels), so
no change needed there.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:44:29 -07:00
9f155a359b Centralize popup-driven province highlight in PopupCanvasController (#6693)
* Centralize popup-driven province highlight in PopupCanvasController

Multiple PopupPanelController subclasses (PleaseRecruitMeCommandSelector,
NotificationPanel, ResolveDiplomacyCommandSelector,
ResolveRansomOfferCommandSelector) all wrote directly to
MapController.OverrideTargetedProvinces from their SetUpPanel hooks,
and SetUpPanel only ran when state changed. So when a notification
arrived or was dismissed while the Please Recruit Me popup was open,
the notification panel's SetUpPanel would overwrite the recruit
popup's province highlight, and the recruit popup would never
re-assert. Result: the requesting hero's province often wasn't
highlighted even though the popup said it should be.

Switch to a single-writer model:

- PopupPanelController exposes CurrentAffectedProvinceIds (the current
  popup's affectedProvinceIds), and no longer writes to MapController
  itself.
- PopupCanvasController gains a MapController reference and, in
  Update, applies the topmost active panel's CurrentAffectedProvinceIds
  every frame, so popups can't clobber one another. On the transition
  from "popup active" to "no popup", we clear the override once and
  then leave the field alone so non-popup writers (table hovers etc.)
  can drive it normally.
- ResolveDiplomacyCommandSelector and ResolveRansomOfferCommandSelector
  used to compute their highlight inline in SetUpPanel; that logic
  moves into the PopupInfo construction so each offer carries the
  right affectedProvinceIds, and their SetUpPanel overrides shrink
  accordingly. PleaseRecruitMeCommandSelector and NotificationPanel
  already populated affectedProvinceIds correctly and didn't need
  changes.

PopupCanvasController has a new public MapController field. Wire it in
the prefab/scene where the PopupCanvasController lives (drag the
MapController object onto the new "Map Controller" Inspector field)
before testing — without it, opening a popup will throw a
NullReferenceException, which is intentional per the project's
no-defensive-checks policy on Inspector fields.

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

* Wire MapController into both PopupCanvasController instances in Gameplay scene

Companion to the previous commit. Two PopupCanvasController instances
exist in Gameplay.unity (narrow + wide layout); both now reference the
MapController so the new single-writer Update path can drive
OverrideTargetedProvinces from any active popup.

Also includes auto-saved DialogueManager unitHighlight default colors
that Unity wrote into the scene when loading after the prior tutorial
unit-highlight PR landed — incidental, but moot to revert.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:28:22 -07:00
19cf9c592a Add failing test for backstory visibility on hero imprisonment (#6695)
* Add failing test for backstory visibility on hero imprisonment

When a hero is captured via battle aftermath and imprisoned, the captor
faction has no visibility on the prisoner's backstory text. This test
asserts the imprisonment ActionResult should emit a
ClientTextVisibilityExtensionC granting the imprisoning faction
visibility on the captured hero's backstory text -- matching the
parallel pattern in ProvinceConqueredAction.afterUpdatingUnaffiliatedHeroes.

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

* Extend backstory visibility to captor in convertToUnaffiliated

When a captured hero with an existing backstory is converted into an
unaffiliated hero (imprisoned or exiled), emit a
ClientTextVisibilityExtensionC granting the captor faction visibility
on the prisoner's backstory text. Without this the captor sees blank
text for their own prisoner -- the same gap ProvinceConqueredAction
already closes for inherited unaffiliated heroes when a province changes
hands.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:27:56 -07:00
537f846fee March marks the acting (menu) province as acted (#6694)
* Add failing test: March should mark the acting (menu) province as acted

Currently, MarchCommand.make takes only originProvinceId and marks
that as the only acted province (via provinceIdActed). If the player
opens the command menu on province A and chooses to march units from
a different origin province B, only B is marked acted. Province A
retains its full command menu and can issue another command in the
same round — the player can effectively shuffle units around without
spending province A's action.

Plumbing changes (necessary for the test to express the desired
behavior, behavior unchanged):

- Add actingProvinceId: ProvinceId parameter to MarchCommand.make.
  The inner MarchCommand class accepts it but currently marks it
  @scala.annotation.unused — immediateExecute does not yet emit a
  hasActed change for the acting province.
- CommandFactory passes ac.actingProvinceId from the MarchAvailable
  pair when constructing the MarchCommand. The wire protocol already
  carries the menu province on EagleCommand.province_id, so no proto
  or client changes are required.
- Existing MarchCommandTest cases pass actingProvinceId =
  originProvinceId to preserve current behavior; they all still pass.

New failing test:

- "should mark the acting (menu) province as having acted, even when
  marching from a different province" — sets actingProvinceId=14,
  originProvinceId=7, asserts the result includes a ChangedProvinceC
  for province 14 with setHasActed = Some(true). Currently fails:
  "None was not equal to Some(true)" — no ChangedProvinceC for 14
  exists in the result.

Implementation fix to follow.

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

* Mark the acting (menu) province as acted on March

Implementation for the test added in the previous commit.

When actingProvinceId == originProvinceId (the typical case where the
player issued March from the same province their units march from),
provinceIdActed = Some(originProvinceId) already marks that single
province as acted. No extra change needed.

When actingProvinceId != originProvinceId (the player opened the
menu on A, chose origin B), append a ChangedProvinceC for the acting
province with setHasActed = Some(true) so it can no longer issue
commands this round. The origin still gets hasActed via
provinceIdActed.

Drops @scala.annotation.unused on actingProvinceId since it's now
used.

All 8 MarchCommandTest cases pass, full Scala suite (223 tests) green.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 17:19:12 -07:00
2bd9fb4022 Compute PersistedActionResult.gameState lazily (#6692)
formAwrs (called on game load) and withNewResults (called per applied
result at runtime) were eagerly running GameStateConverter.toProto on
every Scala game state to populate PersistedActionResult.gameState —
3 seconds of the 4.5-second game-load time per the timing logs and
ongoing per-result cost during play.

In practice, the proto game-state is only ever read at "last entry of
batch" boundaries:

- PersistedHistory.scala:214 — last entry of a loaded chunk during
  orphan recovery.
- PersistedHistory.scala:471 — invariant check on
  recentHistory.headOption.gameState.actionResultCount.
- PersistedHistory.scala:592 — results.last.gameState in saveNow,
  passed to the next batch as starting state.
- PersistedHistory.scala:664 — toSave.last.gameState in withNewResults
  chunk save, passed to next batch as starting state.

So at most ~1 in resultsPerSaveFile (25) entries ever needs the proto
form; for the others the conversion was pure waste. Make
PersistedActionResult.gameState a lazy val derived from
scalaGameState — entries that never become a "last in batch" never
pay for toProto. (Also drops the unused fromProto factory.)

formAwrsFromScala still eagerly converts the action result to proto
since saveIndividualResult writes individual ActionResult bytes for
crash recovery — that conversion happens regardless.

223 Scala tests pass.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 15:03:18 -07:00
21eb10d2e5 Skip proto conversion in PersistedHistory.stateAfter replay (#6691)
The disk-load branch of stateAfter went through formAwrs, which
unconditionally calls GameStateConverter.toProto on every replayed
intermediate state — wasted work for stateAfter callers, since the
replayed entries are transient and never persisted. With a 19k-action
game, a single stateAfter(14790) call (e.g. from
UnrequestedTextHandler processing a stale incomplete LLM request)
materialized ~4500 PersistedActionResult instances, each holding both
proto and Scala forms of the game state, allocating an estimated
1.1-1.5 GB and OOMing the 2g heap on Province.apply during one of
those toProto calls.

Add a private replayScalaOnlyToState helper that replays in Scala and
returns just the final state, with no proto conversion. Use it in the
stateAfter disk-load branch, and short-circuit the replay at the
target index by taking only `count - initialIndex` actions instead of
replaying through persistedCount.

Behavior preserved:

- formAwrs is unchanged (the save flow still gets eager proto for
  in-memory entries, avoiding repeated toProto cost across save
  accumulations).
- partialGames load range is unchanged (chunk-range optimization
  intentionally deferred).
- recentHistory branch is unchanged.

Per-call impact on the failing stateAfter(14790) path:

  before: replay 4575 actions, run toProto 4575 times,
          retain Vector[PersistedActionResult] of length 4575 with
          proto + Scala state on every entry — ~1.1-1.5 GB transient.
  after:  replay 15 actions, no toProto calls,
          allocate one GameState — a few MB.

223 Scala tests pass.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 12:39:27 -07:00
1d99eefbd6 Fix CombatUnitSelector hero/battalion matching (#6688)
* Add failing tests for CombatUnitSelector hero/battalion suitability

Documents three desired behaviors that the current greedy
selectedCombatBattalions() does not satisfy:

1. Engineer should be taken over a no-profession hero on a Longbowmen
   battalion when only one slot is available — Suboptimal pairing is
   preferable to leaving the much more capable Engineer behind.
2. Same for a Mage: a Suboptimal Longbowmen pairing is preferable to
   leaving the Mage behind.
3. A Mage with only Restrictive options (e.g. only a non-casting
   Heavy Cavalry battalion) should be skipped entirely, not glued to
   the Restrictive battalion via the getOrElse fallback.

The current code:

- Uses a lexicographic (suitability.ordinal, -power) sort, so any
  Optimal hero beats any Suboptimal hero regardless of how much more
  capable the Suboptimal hero is. This causes (1) and (2).
- Has a getOrElse fallback that pairs the strongest hero with the
  strongest battalion when every (hero, battalion) pair is Restrictive,
  ignoring suitability. This causes (3).

These tests fail today and will pass after the planned fix.

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

* Fix CombatUnitSelector matching: soft Suboptimal penalty, skip Restrictive

Three changes to selectedCombatBattalions's chooseOne:

1. Replace the lexicographic (suitability.ordinal, -power) sort with a
   soft scoring scheme: power minus SuboptimalPairingPenalty (50) when
   the pairing is Suboptimal. An Engineer's +200 profession bonus still
   outweighs a no-profession hero on a Suboptimal Longbowmen pairing,
   but an equally-strong Optimal hero still wins the slot.
2. Filter Restrictive heroes out of the candidate pool entirely for the
   chosen battalion rather than relying on suitability ordering — so a
   Mage can never win a non-casting battalion via lexicographic ranking.
3. Replace the getOrElse fallback (which previously glued any hero to
   any battalion regardless of suitability) with a three-way match:
   valid pairing exists -> take it; no battalions left -> strongest
   hero marches alone (preserves prior behavior); battalions remain but
   every pairing is Restrictive -> return None and stop adding heroes.

The five tests in CombatUnitSelectorTest now all pass.

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

* Take Restrictive pairings rather than abandon a battalion

Earlier in this branch we treated "all options for a hero are
Restrictive" as a signal to skip the hero. That was wrong: a Restrictive
pairing (e.g. Mage leading Heavy Cavalry) is still better than leaving
the battalion behind entirely. The correct rule is "prefer non-Restrictive
heroes when any are available, but fall back to Restrictive rather than
losing the unit."

- Replace test 3 ("leave a mage behind ... if every battalion is
  Restrictive") with the inverse: "take a mage on a Restrictive
  battalion if that's the only way to take the battalion at all".
- Add a counterpart test confirming a no-profession hero is still
  preferred over a mage on a Restrictive Heavy Cavalry when both are
  available.
- Simplify chooseOne: always pick the strongest battalion, prefer
  non-Restrictive heroes for it, fall back to Restrictive heroes if
  none are non-Restrictive. Drop the early-return / skip path.

All six CombatUnitSelector tests pass; full Scala suite (223 tests)
still green.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 07:16:41 -07:00
ebc29a75d4 Default Shardok server status to WAITING_FOR_AI when no faction is queued (#6689)
In Eagle battles, computeShardokServerStatus checks each faction's
currentCommand to decide between YOUR_TURN, WAITING_FOR_AI,
WAITING_FOR_HUMAN_PLAYER, and PROCESSING. The AI's currentCommand,
however, isn't populated during the window when the AI is computing
its move — so the typical post-player-turn state had no faction with
a current command and fell through to PROCESSING. Clients never
observed WAITING_FOR_AI in practice; they bounced between YOUR_TURN
and "Processing...".

When no faction has a current command, infer the most useful status
from which other factions are present in the battle: WAITING_FOR_AI
if any AI faction remains, WAITING_FOR_HUMAN_PLAYER if any other
human remains, and PROCESSING only when no other factions are present
(an edge case at battle boundaries).

The custom-battle path (CustomBattleManager.customBattleStatus) was
already binary YOUR_TURN/WAITING_FOR_AI and not affected.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 07:05:47 -07:00
f0d7067cc9 Wire ShardokServerStatus into the connection-status indicator (#6686)
* Wire ShardokServerStatus into the connection-status indicator

Client half of the Shardok-side connection-status work. The server
already populates ShardokServerStatus on SingleShardokGameResultResponse
(see #6685); this hooks it up to the persistent ConnectionStatusUI so
players can see whether they're up, the AI is thinking, or another human
is about to act while a battle is on screen.

- ShardokGameModel implements IShardokGameStateProvider and caches the
  latest ShardokServerStatus, updated as new responses arrive in
  EagleGameModel.
- ConnectionStatusUI gains a Shardok provider slot; when set, it renders
  Your Turn / Waiting for AI / Waiting for Other Player / Processing
  instead of the strategic-layer status.
- EagleGameController binds the UI to the Shardok model when entering a
  battle; ShardokGameController clears the binding on exit.

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

* Fix PersistentUIManager namespace in ShardokGameController

CI build failed with:
  error CS0234: The type or namespace name 'PersistentUIManager' does
  not exist in the namespace 'eagle'

PersistentUIManager lives in the `common` namespace, and Shardok already
has `using common;`, so the `eagle.` qualifier was both wrong and
unnecessary.

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

* Wire ShardokServerStatus through CustomBattleHandler

Custom battles use CustomBattleHandler as the gRPC subscriber instead
of GameModelUpdater, so the existing wiring on EagleGameController +
EagleGameModel didn't reach them — the indicator stayed on "Connected"
in custom battles even after the server began populating
ShardokServerStatus correctly.

- Set the ShardokGameModel as the connection-status UI's Shardok game
  state provider when entering a custom battle. Cleanup is already
  handled by ShardokGameController.EndTurn for both battle paths.
- Forward resp.ShardokServerStatus to the model from
  CustomBattleHandler.ReceiveGameUpdate, mirroring the per-response
  handling that GameModelUpdater already does for Eagle battles.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 06:58:32 -07:00
e05ea92c46 Populate ShardokServerStatus in remaining response paths (#6687)
* Add doc describing server-side work for Shardok status indicator

Hand-off note for the Scala worktree: client wiring on
shardok-status-client is complete, but the indicator only ever shows
"Connected" in battle because the server attaches a ShardokServerStatus
proto with status left at the default UNKNOWN value.

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

* Populate ShardokServerStatus in remaining response paths

PR #6685 added the ShardokServerStatus proto and populated it in
GameController.humanClientsAfterPostingResults, but three other
SingleShardokGameResultResponse construction sites left the field
unset, defaulting to UNKNOWN on the wire and producing the symptom
flagged in docs/SHARDOK_SERVER_STATUS_SERVER_WORK.md.

Fix:

- HumanPlayerClientConnectionState.streamUpdates / apply factory now
  take a shardokServerStatusFor: ShardokGameId => ShardokServerStatus
  callback and set the field on each per-battle response. Avoids a
  Bazel dep cycle into game_controller by accepting the precomputed
  function rather than calling computeShardokServerStatus directly.
- GameController.streamUpdates wires
  GameController.computeShardokServerStatus into that callback.
- CustomBattleManager populates the field at both construction sites
  via a small helper (YOUR_TURN if the human has a current command,
  WAITING_FOR_AI otherwise) — custom battles have only one human
  faction and the AI on -1, so the full computeShardokServerStatus
  machinery is overkill.

Existing test sites in HumanPlayerClientConnectionStateTest pass a
stub shardokServerStatusFor since they don't exercise active battles.

Removes the now-stale TODO doc — its diagnosis (enum never set) no
longer applies.

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 15:49:01 -07:00
b0639dc8d0 Add ShardokServerStatus proto and server-side population (#6685)
Introduces a new ShardokServerStatus message on
SingleShardokGameResultResponse so the client can render a tactical-side
connection-status indicator (Your Turn / Waiting for AI / Waiting for
Other Player / Processing).

ShardokServerStatus is intentionally separate from ServerGameStatus so
the strategic and tactical layers don't have to evolve in lockstep.

GameController.computeShardokServerStatus picks the status from the
receiving player's perspective by checking shardokPlayerAvailableCommands
across factions and classifying them via aiClientFactionIds. The two
humanClientsAfterPostingResults overloads now thread an aiFactionIds set
through and populate the new field on every per-battle response.

This is the server half of a two-PR split. The client wiring lands
separately; until then the new field is emitted but unread, which is
safe.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 06:07:54 -07:00
9eb8f7f086 Highlight March button in post-taxes tutorial dialogue (#6683)
Matches the existing pattern used for the Improve Province and Give Alms
buttons earlier in the strategic tutorial.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:49:53 -07:00
9f18322013 Increase Handle Captured Heroes panel font size (#6682)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 21:36:31 -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
a912347dbd Serialize TryPendingCommands to prevent BAD_TOKEN bursts (#6630)
Multiple MainQueue actions (one per ActionResultResponse and
ShardokActionResultResponse) each call TryPendingCommands as
async void lambdas. When one yields at an await, the MainQueue
Update loop immediately invokes the next action, which re-enters
TryPendingCommands. Because PostRequest synchronously re-adds
the command to _pendingCommands before yielding for WriteAsync,
each parallel invocation re-drains the same buffered command and
writes it to the gRPC stream again. This produces bursts of 10+
identical writes in a single frame, all of which the server
rejects with BAD_TOKEN.

Wrap TryPendingCommands in a non-blocking SemaphoreSlim acquire.
If another invocation is already running, skip and return — any
items added to _pendingCommands while it runs will be picked up
by the next ActionResultResponse handler that fires.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 21:34:12 -07:00
e2221c4e45 Suppress "Reconnecting..." UX during the first retry (#6627)
Occasional disconnects are normal and usually recover on the first
retry, so the old behavior of immediately flashing "Reconnecting..."
(and a 2s countdown) on every blip was too noisy.

Now the first retry after a fresh disconnect is "silent": we don't
touch _currentState, so the status UI keeps showing Connected while
the retry attempt runs in the background. Only after the first retry
has itself failed does the ScheduleReconnect path flip state to
Reconnecting, at which point the user sees the countdown (starting
from the 4s second-attempt backoff).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 20:37:37 -07:00
5af91f6e8b Multiply focus province storage caps by a settable multiplier (#6628)
Introduces the FocusProvinceStorageMultiplier setting (default 1.50) and
applies it to food and gold caps when a province is its ruling faction's
focus province, so focus provinces can stockpile extra reserves.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 20:27:12 -07:00
bc442ba230 Add delta gradient flash to battle thermometer (#6624)
* Add delta gradient flash to battle thermometer

When the thermometer ratio changes, overlay a gradient on the delta
region showing the gaining side's color fading toward white-tinted,
making the territory shift visible. Fades out 2.5x faster than the
existing boundary flash line.

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

* Fix invisible delta gradient by using FullRect sprite mesh

The gradient sprite was using the default SpriteMeshType.Tight which
trimmed out the fully-transparent pixel, producing either an empty or
half-sized mesh. Use SpriteMeshType.FullRect with a 256x1 texture for a
cleaner gradient, and SetAsLastSibling so the overlay renders on top of
the attacker/defender bars. The boundary flash line also reasserts
last-sibling so it stays visible above the gradient.

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

* Add diagnostic logging for delta gradient

Temporary logging to diagnose why the gradient overlay isn't visible
in-game. Will be removed after diagnosis.

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

* DEBUG: render delta gradient as opaque magenta to test positioning

Temporarily replace the gradient sprite with plain opaque magenta and
add canvas renderer state logging to isolate whether the problem is
with the sprite/shader or with positioning/z-order/masking.

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

* DEBUG: use attackerBar sprite, bright green, no fade

Set the delta gradient to use the attacker bar's known-working sprite,
force opaque bright green, and disable the fade coroutine so the image
stays permanently visible. Also log the full transform path to confirm
which thermometer instance is being modified.

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

* DEBUG: test gradient sprite with permanent green tint

Swap back to the procedural 256x1 gradient sprite while keeping the
permanent no-fade green tint. This isolates whether the gradient sprite
itself renders correctly (gradient visible) or has a mesh/UV issue
(solid green or invisible).

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

* Use losing side's color for delta gradient, remove debug scaffolding

The previous implementation tinted the delta region with the *gaining*
side's color, but the bar underneath the delta region is already that
same color — so the gradient was nearly invisible (faction color fading
to a slightly lighter faction color).

Flip it around: use the *losing* side's color. The old owner's
territory briefly lingers in the lost region, then fades to reveal the
new owner's bar underneath. This is a more intuitive visualization of a
territory change.

Also flip the gradient direction so the opaque (losing-color) edge sits
at the old boundary (where the losing side's territory previously
ended), fading toward the new boundary.

Remove the debug logging, green color override, and disabled fade that
were added while diagnosing the earlier rendering issue, and re-enable
the DeltaGradientRoutine fade coroutine.

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

* Flip delta gradient direction

The losing color should be on the side of the delta closer to the
losing side's remaining bar, so it visually points "home" to its own
side. The transparent edge reveals the new owner's bar underneath.

- Attacker gained → losing=defender → opaque on right (near defender).
- Defender gained → losing=attacker → opaque on left (near attacker).

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

* Double the delta gradient fade duration

Previously 0.16s (flashDuration/2.5); now 0.32s (flashDuration/1.25)
so the gradient is easier to see.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 20:06:25 -07:00
3d169136a4 Fix orphaned backstory text ID for rubber-band spawned heroes (#6626)
RandomHeroGenerator.createLowPowerHero pre-populates backstoryVersions
with hero_${id}_backstory_0, but UnaffiliatedHeroAppearedAction only
emits a HeroInitialBackstoryRequest when backstoryVersions is empty. The
rubber-band spawn path in PerformUnaffiliatedHeroesAction was relying on
that action to emit the request, so the initial backstory text ID was
orphaned from the start — never registered with ClientTextStore, always
resolving to TextGenerationDependencyUnknown.

Clear backstoryVersions before handing the hero to
UnaffiliatedHeroAppearedAction so it creates a proper
hero_${id}_initial_backstory_$roundId text ID with a matching LLM
request. This restores effectiveBackstory's ability to fall back to the
initial backstory when later updates are legitimately skipped (e.g. for
heroes only visible to AI factions).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 19:41:49 -07:00
fae53369bf Switch default Gemini model to 3.1 Flash-Lite preview (#6625)
3.1 Flash-Lite is faster (throughput + TTFT), meaningfully smarter, and
still among the cheapest Gemini options, making it a strict upgrade
over 2.5 Flash-Lite for narrative text generation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-09 19:00:51 -07:00
ae65205d34 Add temporary debug logging for free hero backstory visibility (#6623)
Logs a warning in GameController.withHandledEngineAndResults when a
free hero's most recent backstory is not visible to the province's
ruling faction. Includes game ID, history count, round, and phase
to help trace back to the action that caused the visibility gap.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 13:15:43 -07:00
d0c87c838e Add retry logic to all Addressable asset loading (#6622)
* Retry beast effect Addressable loads on failure

Beast effect prefabs are loaded from a remote CDN via Addressables.
If the download failed (network hiccup, CDN timeout), the effects
were permanently lost for the session with no retry. Now retries up
to 3 times with backoff delays (2s, 5s, 10s). Also releases failed
handles to avoid leaking resources.

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

* Extract AddressableLoader utility with retry logic for all Addressable loads

All Addressable assets load from a remote CDN and a single transient
network failure permanently broke the affected feature for the session.
Extracts retry logic (3 retries with 2s/5s/10s backoff) into a shared
AddressableLoader.LoadWithRetry<T>() utility and updates all 6 callers:
ProvinceBeastsController, TacticalAssetLoader, SoundManager,
ImageForTerrainTracker, BattleInProgressController, ProvinceActionAnimator.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 12:09:33 -07:00
6c01a81bbf Remove unused Modern UI Pack scripts, animations, and prefabs (#6621)
Removed ButtonManagerBasic and UIGradient components from the lobby
AvailableGame prefab (they were no-ops — the button already had a
normal onClick callback). Then deleted all non-texture content from
Modern UI Pack: Scripts, Animations, Editor, Fonts, Scenes, Unused
prefabs, and Documentation. Only Textures/ is retained.

Saves ~34 MB of unused assets.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 08:21:16 -07:00
c25ecadd60 Add editor tool to audit third-party asset usage (#6619)
* Add editor tool to audit third-party asset pack usage

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

* Include Addressable group entries in asset usage audit

The previous version only traced dependencies from build scenes, completely
missing assets loaded via Addressables. This caused ~8.5 GB of assets to
be falsely reported as unused. Now traces dependencies from all Addressable
group entries (Beast Effects, Hex Tiles, Tactical Assets, Sound Effects)
in addition to build scenes.

Also logs all USED files per pack for easier analysis.

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

* Remove Pixel Fonts Megapack from audit pack list

Pack was deleted in PR #6620.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 08:02:12 -07:00
251aeb5794 Remove unused Pixel Fonts Megapack asset pack (#6620)
Asset usage audit (scenes + Addressables) confirmed 0 files from this
pack are referenced anywhere in the build. Saves 2 MB.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 08:00:43 -07:00
9223b0452e Clear fleeProvinceId after fleeing to prevent stale flee destination (#6618)
When an army flees after losing a battle, the flee province is consumed
but was not being cleared. This caused armies arriving at a now-hostile
flee province to get attack decision options instead of being shattered.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 07:23:19 -07:00
05299dbe77 Remove debug logs from battle progress UI (#6617)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 20:01:45 -07:00
f06ba27a6f Fix reversed thermometer bar widths in Shardok tactical view (#6616)
The Shardok Container prefab had defender on the left and attacker on
the right, but BattleThermometer code forces the defender bar to the
right and attacker bar to the left. This caused the wide bar to appear
next to the smaller number. Swap the field references so bars and labels
are on matching sides.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:54:19 -07:00
bf90c98add Update Unity prefabs for battle progress row and editor re-serialization (#6615)
Wire up flashDuration on BattleThermometer in the Battle Progress Row
prefab and right-align the attacker troop count label. Includes Unity
editor re-serialization of Emu and peasant prefabs.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:34:06 -07:00
95afb025e1 Replace inappropriate Excellent Glory headshot (#6614)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:31:26 -07:00
93e3804eef Only grant Allied hostility for actual alliances in battle views, not truces (#6613)
FactionUtils.hostilityStatus treats both truce and alliance as non-hostile,
which caused battle player infos to show Allied hostility for truce holders.
The client then displayed an "Observe" button that threw an exception on click
because the server correctly rejects observation for truce-only relationships.

Fix shardokBattlePlayerInfos to use hasAlliance directly instead of the
general hostilityStatus, so only actual alliances produce Allied hostility.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:27:32 -07:00
6c13ade07e Flash thermometer boundary on every day update (#6611)
Previously the flash only triggered when the ratio changed by more
than 0.001. Now it flashes on every update after the first, so each
day tick produces a visible flash even if the ratio barely moved.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:15:55 -07:00
dee2574a59 Fix losing armies being shattered instead of retreating to flee province (#6612)
ResolveBattleAction was discarding the original fleeProvinceId for
armies that lost a battle, causing them to shatter instead of retreating
to the province the player designated when dispatching the army.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 19:06:41 -07:00
8bb8a8f791 Only send BattleProgressResponse when gated round advances (#6610)
postBattleUpdate sent a BattleProgressResponse for every Shardok
action, even when the gated round hadn't changed. In AI-only battles
this floods clients with dozens of identical-day updates per round.
Now only sends battle progress when the gated round actually advances,
reducing redundant updates while still delivering Shardok action
results to participants.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 18:45:50 -07:00
51b95d0b62 Forward battle progress during strategic turn updates (#6609)
withHandledEngineAndResults used the 5-parameter overload of
humanClientsAfterPostingResults which did not send battle progress.
This meant non-combatant observers only received battle progress
updates when Shardok sent a GameUpdateResponse, not during Eagle
strategic turn resolution. Switch to the 7-parameter overload to
forward existing battle progress on every client update.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 18:45:30 -07:00
d06f26bffe Reset lastRevealedRound when all battles end (#6608)
The gated round (lastRevealedRound) used max(previous, current) to
prevent information leakage, but never reset when all battles ended.
This caused new battles to start at the previous battle's final day
(e.g. "Day 29") instead of "Day 0".

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 18:28:19 -07:00
7375d9f8ee Reset BattleDay to 0 when a new battle starts (#6607)
BattleDay was only set from BattleProgressResponse, so it retained
stale values from previous battles until the first progress update
arrived for the new battle.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 18:22:27 -07:00
0a650dec2c Add flash effect at thermometer boundary when balance shifts (#6606)
A thin white line briefly flashes at the attacker/defender boundary
whenever the troop ratio changes, giving visual feedback during battle.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 16:46:20 -07:00
22cdf99d4d Propagate isDefender flag to Shardok thermometer (#6604)
* Use isDefender flag in Shardok thermometer and game model

Use the new is_defender field from ShardokBattlePlayerInfo instead of
assuming player 0 is always the defender. Updates ShardokGameController
thermometer, ShardokGameModel.IsDefender, EagleGameModel.MakeGameModel,
and CustomBattleHandler player setup.

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

* Update Gameplay scene layout and soldier prefabs

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 15:41:38 -07:00
86e9489f21 Add is_defender to ShardokBattlePlayerInfo proto (#6605)
Add is_defender field (field 5) to ShardokBattlePlayerInfo so the
client can identify which players are defenders without assuming
player 0 is always the defender. Populate it from
ShardokPlayer.isDefender in BattleFilter and serialize it in
ShardokBattleViewConverter.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 15:20:47 -07:00
2339050154 Fix battle progress bar: swap sides and forward updates to client (#6601)
Two fixes for the battle progress thermometer:

1. Swap attacker/defender sides so attacker fills from left and defender
   from right, matching the expected layout.

2. Add missing BattleProgressResponse case in PersistentClientConnection's
   HandleGameUpdate switch. The server was sending progress updates but
   the client silently dropped them, causing the bar to stay at 50%.

Also extract UpdateBattleProgressDisplay helper in EagleGameController
and call it from SwapModel's early-return path so progress updates aren't
skipped when the player has active strategic commands.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 14:51:13 -07:00
f7fefe078e Fix crash in AttackDecisionCommandSelector when configuring toggles (#6602)
ConfigureToggle used toggle.isOn = false which fires the ToggleChanged
callback. That callback accesses SelectedDecision, which throws when no
toggle is on yet during SetUpUI. Use SetIsOnWithoutNotify instead.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 14:50:49 -07:00
ad3e7f19b9 Fix reversed troop counts in battle progress tracker (#6603)
The updatedBattleProgress method assumed player 0 was always the
defender, but RequestBattlesAction builds the players vector with
attackers first and defender last. Use the isDefender flag from the
battle's player list to correctly classify troop counts.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 14:45:25 -07:00
022bdab53f Fix ToggleGroup preventing disabled toggles from turning off (#6600)
When ConfigureToggle sets isOn=false on a toggle that is the last active
member of a ToggleGroup with allowSwitchOff=false, Unity forces it back
to true. The toggle is then removed from the group but retains the stale
isOn=true state. This causes the wrong option to be sent to the server
(e.g. Recruit when only Imprison/Return/Execute were available).

Fix by removing the toggle from its group before setting isOn=false.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 10:27:41 -07:00
c01e64265d Seed initial troop counts in BattleFilter from army battalion data (#6598)
When a battle is first created, participants now see troop counts and an
accurate balance bar immediately instead of a blank 50/50 bar while
waiting for the first Shardok GameUpdateResponse.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 07:25:17 -07:00
a7572a5a9a Use faction-specific colors in battle thermometer (#6597)
- BattleThermometer: accept IList<Color> for attacker colors, dynamically
  create extra bar segments for multi-attacker battles
- BattleProgressRowController: look up defender faction from province
  RulingFactionId and attacker factions from PlayerInfos, using
  LightPlayerColor for faction-correct colors; use DarkColoredProvinceName
  for more readable province name text
- ShardokGameController: wrap single attacker color in list for new API

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 07:03:45 -07:00
44edd8cc5e Clear hex overlays on every model update and turn end (#6596)
ModelUpdated() never unconditionally cleared overlays, so stale highlights
persisted after phase transitions (setup -> running) and after issuing a
command that ends the turn. Add ClearOverlays() at the top of ModelUpdated()
so overlays are always wiped before being selectively re-drawn, and in
EndTurn() for immediate visual feedback when clicking Commit/End Turn.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 22:03:13 -07:00
3a1f1c2bbe Add battle progress display for non-combatant observers (#6581)
* Add battle progress tracking and real-time progress updates

During BATTLE_RESOLUTION phase, track Shardok battle progress (troop counts
and defender/attacker ratios) and push synchronized updates to clients via
a new BattleProgressResponse message. All battles advance together using
gated round progression to prevent information leakage. Allied observers
see troop counts; non-allied players see only the ratio bar.

Key changes:
- Add defender_ratio, troop counts, and winning_faction_id to ShardokBattleView proto
- Add updated_battles to GameStateViewDiff proto
- Add BattleProgressResponse to GameUpdate oneof
- Track battle progress in GameController with synchronized round gating
- Send enriched battle views to clients via HumanPlayerClientConnectionState
- Update GameStateViewDiffer to detect battle updates
- Add GameStateViewDifferTest with 6 test cases

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

* Move BattleProgressResponse to views layer to fix proto layering

BattleProgressResponse only contains ShardokBattleView objects, which
belong to the views layer. Move it from eagle.proto (api layer) to
game_state_view.proto (views layer) and remove the direct
shardok_battle_view.proto import from eagle.proto.

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

* Add battle progress display for non-combatant observers

During BATTLE_RESOLUTION, non-combatant players now see real-time
progress bars instead of a single "Observe Battle" button. Each bar
shows defender/attacker balance with green/red coloring. Allied battles
show troop counts and an Observe button; non-allied battles show only
the bar. When a battle ends, the bar is replaced with Victory/Defeat.

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

* Fix TextAlignmentOptions.MidlineCenter compile error and meta GUID conflict

MidlineCenter does not exist in Unity 6 TMP; use Center instead.
Also include reassigned .meta GUID to resolve conflict with duel.asset.

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

* Add BattleProgressPanel GameObject to Gameplay scene

Wire the panel to EagleGameController.battleProgressPanel with
VerticalLayoutGroup and ContentSizeFitter components.

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

* Remove BattleInProgressController from BattleProgressPanel GameObject

BattleInProgressController belongs on the map, not the progress panel.

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

* Remove unused ShardokGameStateView import from GameController

The import triggered -Werror and broke the battle_progress_test build.

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

* Show BattleProgressPanel for all battles, not just observed ones

The panel was only activated for non-combatant observers. Now it shows
whenever there are battles, alongside the "Battle!" button for combatants.

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

* Use ShardokBattles instead of RunningShardokGameModels for panel visibility

RunningShardokGameModels requires the client to have connected to the
Shardok game and received a GameRunning status, which may not have
happened yet. ShardokBattles comes from the server game state view and
is available immediately when battles exist.

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

* Refactor BattleProgressPanel to use prefab rows and display battle day

Replace programmatic CreateRow()/PopulateRow() with a prefab-based
approach using BattleProgressRowController. The panel now instantiates
rows from a prefab into a scroll view, displays "Day X" from the
server's gated round, and uses colored province names.

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

* Use BattleThermometer in battle progress rows

Replace manual anchor/color logic with the existing BattleThermometer
component, which already handles both troop-count and ratio-only modes.

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

* Fix row container cleanup, observe button visibility, and prefab transforms

Clear stale children from rowContainer on first update. Only show
Observe button for allied battles (not the player's own). Fix bar
rotation/scale in row prefab. Add debug logging for battle progress.

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

* Update BattleProgressPanel layout in Gameplay scene

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

* Replace goToBattleButton with per-row Fight!/Waiting.../Observe buttons

Each battle row now has its own action button: "Fight!" for the
fightable battle, "Waiting..." (grayed) for other own battles,
and "Observe" for allied battles. The global goToBattleButton is removed.

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

* Remove goToBattleButton from scene and adjust battle panel layout

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

* Adjust battle progress panel layout

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 21:31:16 -07:00
0f3ffc24c2 Send gated round as current_day in BattleProgressResponse (#6595)
The server already computes lastRevealedRound (the minimum round across
all active battles) for fair reveal timing, but never sent it to the
client. Add current_day field to the proto and pass gatedRound through
sendBattleProgress so clients can display the battle day.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 20:56:53 -07:00
741efecc66 Fix AnimalEffect spamming "State could not be found" errors (#6594)
Guard idle and walk Play() calls with HasState(), matching the existing
pattern already used for eat/attack transitions.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 20:10:55 -07:00
4c7ac587e7 Add Scala battle progress tracking for non-combatant observers (#6585)
* Add battle progress tracking with proto-based troop counts

Adds real-time battle progress tracking so non-combatant observers can
see defender/attacker troop ratios during BATTLE_RESOLUTION phase.

C++ Shardok extracts current_round and per-player troop counts from the
FlatBuffer game state and sends them as new proto fields on
GameUpdateResponse, avoiding the previous approach of parsing opaque
FlatBuffer bytes as Protobuf on the Scala side.

Scala Eagle tracks progress via BattleProgressTracker, gates round
reveals across concurrent battles, and enriches ShardokBattleView with
defender_ratio and troop counts for allied observers.

Includes tests for both C++ troop count extraction and Scala progress
tracking logic.

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

* Remove default values from ShardokBattleView fields

Make all new fields (defenderRatio, defenderTroopCount,
attackerTroopCount, winningFactionId) required at construction sites
instead of relying on defaults.

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

* Preserve battleProgress across GameController operations

Convert withHumanClient, withAiClient, stopStreaming, aiClientCommands,
and withHandledEngineAndResults from explicit GameController construction
to copy(), so battleProgress and lastRevealedRound are preserved when
clients connect/disconnect or commands are processed.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 20:10:13 -07:00
3c18918634 Extract battle progress data from FlatBuffer game state in Shardok (#6593)
Populates the new proto fields (current_round, player_troop_counts) on
GameUpdateResponse by extracting data from the FlatBuffer game state in
ShardokGameController::GetUpdates(). Counts troops for each player
across NORMAL, RESERVE, and NEVER_ENTERED units.

Updates the OnUpdates callback signature to pass the new fields through
EagleInterfaceGrpcServer to Eagle.

Includes tests verifying troop count extraction for both normal games
and games with reserved slots.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:52:23 -07:00
b930ca626f Add proto fields for battle progress tracking (#6592)
Adds new proto fields to support real-time battle progress updates for
non-combatant observers:

- shardok_internal_interface: PlayerTroopCount message, current_round
  and player_troop_counts on GameUpdateResponse
- shardok_battle_view: defender_ratio, troop counts for allied viewers,
  winning_faction_id
- game_state_view: updated_battles on GameStateViewDiff,
  BattleProgressResponse message
- eagle.proto: battle_progress_response in GameUpdate oneof
- BUILD.bazel: game_state_view_scala_proto target

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:45:11 -07:00
d1219787a8 Add weekly S3 archive cleanup workflow (#6591)
Deletes game folders from eagle/archived/ where directory.e0i is over
1 month old. Runs weekly on Sundays at 05:00 UTC with manual trigger support.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:39:59 -07:00
8019986ea7 Populate "Your Army" table in Battle Aftermath panel (#6590)
The surviving units data was being sent by the server but never displayed.
Wire the EventBasedTable to show heroes and battalions using the same
CombatUnitRowController pattern as AttackDecisionCommandSelector.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:30:06 -07:00
62b7e3abe1 Fix "What's New" showing same entries on every sign-in (#6588)
MarkAllAsSeen() assumed entries[0] had the latest date, but entries
in whats-new.json aren't necessarily in chronological order. When a
backdated entry was added at position 0, the saved last-seen date was
older than other entries, causing them to reappear on every sign-in.

Now scans all entries to find the maximum date.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:09:21 -07:00
88b049334b Archive S3 game files on game removal (#6589)
When a game is archived (last player exits) or deleted (admin console),
S3 files under eagle/save/{gameId}/ are now moved to eagle/archived/{gameId}/
to prevent the lazy-loader from resurrecting stale data and to keep S3 clean.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 19:07:21 -07:00
0aaa726abb Preserve schemaVersion when saving loaded games (#6586)
* Preserve schemaVersion when saving loaded games to games.e0es

GamesManager.save() was building RunningGame entries for loaded games
without setting schemaVersion, causing it to default to 0. This made
every game appear as needing migration on every server restart after
being loaded into memory, even when the schema version hadn't changed.

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

* Also stamp currentSchemaVersion on newly created games

Pass GameMigrator.currentVersion into GamesManager so new games get the
correct schema version on their first save, avoiding a needless no-op
migration on the next server restart.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 18:57:33 -07:00
37f75d4f6b Fix CompoundPersister.delete to remove from all backends (#6587)
delete() and deleteAll() only removed from the first (local) persister,
leaving stale files in S3. This caused rewound shardok battles to be
resurrected via lazy-loading from S3.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 18:44:47 -07:00
adminandGitHub b35a4b834e Revert "Add battle progress tracking and real-time updates (#6580)" (#6584)
This reverts commit 4fdc97590b.
2026-04-01 17:15:38 -07:00
adminandGitHub 01a19f740d Revert "Fix battle progress parsing FlatBuffer bytes as Protobuf (#6582)" (#6583)
This reverts commit f86f53326f.
2026-04-01 17:14:45 -07:00
f86f53326f Fix battle progress parsing FlatBuffer bytes as Protobuf (#6582)
* Fix battle progress parsing FlatBuffer bytes as Protobuf

The updatedBattleProgress method was calling ShardokGameStateView.parseFrom()
on opaque FlatBuffer bytes, causing InvalidProtocolBufferException in production.

Fix: Add current_round and player_troop_counts fields to GameUpdateResponse
proto so Shardok serializes the data explicitly. Eagle reads from these new
proto fields instead of trying to parse the opaque game state bytes.

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

* Add tests for battle progress proto fields

C++ test verifies troop count extraction from FlatBuffer game state
matches GetUpdates() logic. Scala test covers updatedBattleProgress()
for tracker creation, same-round updates, round boundary snapshots,
multi-attacker summation, and missing defender defaults.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 12:05:52 -07:00
4fdc97590b Add battle progress tracking and real-time updates (#6580)
* Add battle progress tracking and real-time progress updates

During BATTLE_RESOLUTION phase, track Shardok battle progress (troop counts
and defender/attacker ratios) and push synchronized updates to clients via
a new BattleProgressResponse message. All battles advance together using
gated round progression to prevent information leakage. Allied observers
see troop counts; non-allied players see only the ratio bar.

Key changes:
- Add defender_ratio, troop counts, and winning_faction_id to ShardokBattleView proto
- Add updated_battles to GameStateViewDiff proto
- Add BattleProgressResponse to GameUpdate oneof
- Track battle progress in GameController with synchronized round gating
- Send enriched battle views to clients via HumanPlayerClientConnectionState
- Update GameStateViewDiffer to detect battle updates
- Add GameStateViewDifferTest with 6 test cases

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

* Move BattleProgressResponse to views layer to fix proto layering

BattleProgressResponse only contains ShardokBattleView objects, which
belong to the views layer. Move it from eagle.proto (api layer) to
game_state_view.proto (views layer) and remove the direct
shardok_battle_view.proto import from eagle.proto.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 21:45:35 -07:00
1d46bdd452 Fix Sparkle sign_update path to match tarball structure (#6579)
The Sparkle-2.6.4.tar.xz extracts to ./bin/sign_update, not
./Sparkle-2.6.4/bin/sign_update. This broke mac builds when the
runner had a fresh /tmp/sparkle-cache.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 07:51:29 -07:00
292097f03e Fix Please Recruit Me not highlighting the acting province (#6578)
new List<ProvinceId>(heroInfo.provinceId) calls the capacity constructor,
creating an empty list with capacity = provinceId. Changed to collection
initializer syntax { heroInfo.provinceId } so the province ID is actually
added as an element. The PopupPanelController already feeds this list into
mapController.OverrideTargetedProvinces for highlighting, but the list was
always empty.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 06:39:13 -07:00
9a8ef4f243 Log command details when postCommand fails (#6577)
Include game ID, command type, and province/player info in the error
log line so failed commands are diagnosable without reproducing.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 21:03:13 -07:00
c99d45bda7 Fix smuggler figures rendering white by using prefab refs instead of raw FBX (#6576)
SoldierEffect.prefab referenced 3 of 4 character models as raw .fbx files
(PT_Male_Soldier_01.fbx, PT_Female_Soldier_01.fbx, PT_Female_Soldier_02.fbx).
Raw FBX instantiation doesn't carry material assignments, causing models to
render with the default white material. Updated references to use the proper
.prefab files from Polytope Studio which have materials correctly configured.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 21:02:05 -07:00
18222f9cc4 Upgrade GitHub Actions to Node.js 24 versions (#6575)
Node.js 20 actions are deprecated and will stop working June 2, 2026.

- actions/checkout v4 → v6
- actions/upload-artifact v4 → v7
- actions/download-artifact v4 → v8
- actions/setup-node v4 → v6
- appleboy/ssh-action v1.0.3 → v1.2.5
- docker/setup-qemu-action v3 → v4
- docker/setup-buildx-action v3 → v4

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 07:51:55 -07:00
adminandGitHub 344f1134f6 Detect missing prefab references in Unity builds (#6574) 2026-03-22 18:20:09 -07:00
9aaca0d993 Add diagnostic for Windows-only NullRef in SettingsPanelController (#6573)
All prefab override fields are null at runtime on Windows builds only.
Log the missing fields and gracefully bail out of ApplyPersistedSettings,
Start, and HandleEscape so the game can still launch and we can
investigate whether other prefab overrides are also broken.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 13:43:39 -07:00
94db3634db Add artifact cleanup job to purge stale logs every 6 hours (#6572)
GitHub Actions retention-days: 3 is unreliable — 1,846 expired artifacts
(282 MB) accumulated over 5+ weeks. Add a cleanup-expired job that deletes
artifacts older than 3 days before the storage check runs.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 21:17:19 -07:00
adminandGitHub 19c8e63152 Replace necromancer control chain with interlocking ring links (#6571) 2026-03-21 16:22:34 -07:00
5d7f298d1c Suppress harmless stream-closed exceptions from Sentry (#6570)
* Suppress harmless stream-closed IllegalStateException in SyncResponseObserver

The most common Sentry exception was "Stream is already completed" from
CustomBattleManager. This happens when Shardok sends battle results to a
client that already disconnected — the isCancelled check passes because
"cancelled" and "completed" are different stream states, so the underlying
onNext throws IllegalStateException. Catch it silently in all three stream
methods, matching the existing pattern in GameController.

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

* Narrow catch to only suppress "already completed" stream exceptions

Only catch IllegalStateException when the message contains "already completed",
so unexpected IllegalStateExceptions still propagate to Sentry.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 14:10:25 -07:00
1cfd0ded6c Narrow longbow wind bonus cone from 120° to 60° (#6569)
The wind-assisted range-3 check was allowing tiles in adjacent hex
directions (±60° from wind), producing a 120° cone. This let longbows
shoot northwest with a northeast wind. Tighten the check so only tiles
whose direction matches the wind direction (or sits on the boundary
between two sectors, one of which is the wind direction) qualify.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 13:53:26 -07:00
ab69d40e64 Fix control undead animation targeting wrong location (#6568)
The control command's CommandDescriptor has target_unit but no target
coords, so the client treated it as fully untargeted and animated toward
the nearest enemy instead of the controlled undead unit. Now
PlayUntargetedCommandAnimation uses the command's target_unit when
available. Also set target_unit on the CONTROLLED action result so
server-side history replays animate correctly.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 13:48:00 -07:00
be94acebbf Remove noisy MeteorStart Debug.Log from ShardokGameController (#6567)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 13:33:29 -07:00
4f5df7d697 Remove noisy SHA256 validated Debug.Log messages from ProvinceIDLoader (#6566)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 10:48:47 -07:00
c5af75db7d Remove noisy Debug.Log messages from ProvinceBeastsController (#6565)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 10:23:10 -07:00
24421db613 Defer beast effect spawning until province centroids are loaded (#6564)
The ProvinceBeastsController could attempt to spawn beast effects before
centroids arrived from CDN, causing "No centroid found" warnings. The
effect prefabs (loaded from local Addressables) often finished loading
before the centroids (fetched over the network), creating a window where
UpdateBeastsEffects would proceed without centroid data.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 10:12:19 -07:00
35a804cf18 Fix AnimalEffect animator state errors (#6563)
* Guard AnimalEffect animator state plays with HasState check

Some animal prefab animator controllers don't have states named idle,
walk, eat, or attack, causing spammy "State could not be found" and
"Invalid Layer Index '-1'" errors every frame. Added SafePlay helper
that checks HasState before calling Play.

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

* Fix AnimalEffect animator state errors for kangaroo, leopard, black panther

Three animator controllers (KangarooMapAnims, LeopardMapAnims,
BlackPantherMapAnims) used "idle1" instead of "idle", causing
"State could not be found" errors every frame. Renamed to "idle".

Also skip eat/attack actions for animals whose controllers don't have
those states (e.g. scorpion has no eat) — falls back to idle instead
of playing a missing state.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 10:04:14 -07:00
ba9091409a Skip auto-placement of reserve units during reconnect resync (#6562)
On reconnect, HandleStartingState clears all ShardokGameModels and
re-creates them, then the server replays the full battle history. Each
ChangedReserveUnit in the replayed history was triggering auto-placement
to starting positions, causing visible UI thrashing — especially with
repeated reconnect attempts during idle periods. The user's manual
placements (local-only until submitted) were lost each time.

Added SkipAutoPlacement flag to ShardokGameModel, set during resync
model creation and cleared after the first successful HandleUpdates.
This prevents auto-placement during history replay while preserving
it for genuinely new battles.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 17:27:37 -07:00
b4452d4e9c Fix tribute sliders not activating in Attack Decision command (#6561)
The 4 decision toggles (Advance, Demand Tribute, Withdraw, Safe Passage)
were not wired to ToggleChanged in the prefab, so selecting Demand Tribute
never activated the tribute container with gold/food sliders. Also changed
ConfigureToggle to use SetIsOnWithoutNotify when disabling unavailable
toggles, preventing a "No decision selected" exception during setup.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 15:32:08 -07:00
adminandGitHub 32f5c6838c Add externalObjects material remapping to animal/creature FBX meta files (#6560) 2026-03-20 12:45:34 -07:00
8fa13da9c1 Add URP migration plan for BiRP-to-URP pipeline conversion (#6559)
Documents phased approach for migrating from Built-In Render Pipeline
to Universal Render Pipeline before Unity drops BiRP support after 6.7.
Covers shader inventory, long-lived branch strategy, and effort estimates.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 11:24:08 -07:00
a2958a7672 Fix backstory visibility for unaffiliated heroes after conquest (#6558)
Unaffiliated hero backstory updates were only visible to the current
province owner, so when another faction conquered and tried to recruit,
the backstory was missing. Now unaffiliated hero backstory updates use
empty recipientFactionIds (meaning all factions), matching the initial
backstory behavior.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 11:03:38 -07:00
1eb9f07c9c Unity 6.4 upgrade (#6557)
* Upgrade Unity from 6000.3.8f1 to 6000.4.0f1

Also clear the CI runner's Library/ cache when the Unity version
changes to prevent infinite import loops on version upgrades.

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

* Fix em dash characters in workflow YAML breaking GitHub Actions

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

* Fix gray textures after Unity 6.4 upgrade by switching to embedded materials

materialLocation: 0 (External) is deprecated in Unity 6.4 and causes FBX
models to render without textures. Changed all 749 .fbx.meta files to use
materialLocation: 1 (Embedded) which is the new default.

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

* Trigger CI checks

* Add trailing newline to workflow file to re-trigger CI

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

* Fix YAML syntax error on line 125 of unity_build.yml

The run: value contained | and > characters that confused the YAML parser.
Switching to block scalar syntax (run: |) avoids the ambiguity.

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

* Remap bridge materials to fix gray textures after materialLocation change

With materialLocation: 1 (Embedded), Unity ignores external .mat files.
Added externalObjects remapping so the bridge FBX models still use the
correctly-textured bridges_d material from TileableBridgePack/Materials/.

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

* Add material remapping to all remaining bridge FBX meta files

The old-format meta files (serializedVersion: 18) had no materialLocation
or externalObjects fields, causing Unity 6.4 to default to the deprecated
External material path and render bridges gray. Added externalObjects
remapping and materialLocation: 1 to all 47 remaining bridge models.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 10:14:43 -07:00
393fe7bdca Add rounded corner mask to battle thermometer bar area (#6555)
Use UISprite with Mask component on the Bar Area container to clip
the colored bars with smooth rounded corners.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 21:44:42 -07:00
51fc0ac99c Add battle thermometer to Shardok tactical view (#6554)
* Add battle thermometer to Shardok tactical view

Replace the always-visible armies table with a horizontal thermometer bar
showing defender vs attacker troop balance at a glance. The bar uses
Fantasy RPG boss gauge sprites with faction-matched colors. Hovering the
thermometer reveals the full armies table as a popup.

Also adds icons to Army Info Row and removes the totals row from the
armies table since troop counts are now shown on the thermometer.

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

* Fix thermometer bar sizing and null model crash

Use anchor-based horizontal sizing instead of fillAmount, preserving
vertical inspector settings. Replace BarMask with plain Bar Area
container. Guard UpdateReserves against null Model when Shardok
container is active at game launch.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 21:15:15 -07:00
f3211cf239 Replace Dumb Edged-Rod headshot with one that shows her face (#6553)
The previous headshot only showed her torso up to her lips.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 19:28:54 -07:00
a73e758551 Remove unnecessary DontDestroyOnLoad from UpdateNotificationManager (#6552)
UpdateNotificationManager lives in Gameplay.unity which is the
persistent base scene — it is never unloaded. DontDestroyOnLoad is
unnecessary and produces a warning because the object is a non-root
UI child under a Canvas. Remove the call entirely.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 06:32:20 -07:00
b47e37a083 Remove noisy startup Debug.Log messages (#6551)
Remove happy-path confirmation logs that fire on every normal startup
and provide no diagnostic value: tutorial UI built, state loaded, token
cache initialized, Sparkle version/platform info, auth configured,
session restored, and WhatsNew check results.

Error/warning logs (LogWarning, LogError) are preserved.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:48:48 -07:00
bccd861230 Fix Unity 6 compiler warnings across 30 C# files (#6548)
Replace deprecated APIs to eliminate non-third-party warnings:
- FindObjectOfType<T>() → FindAnyObjectByType<T>() (23 files)
- FindObjectsOfType<T>() → FindObjectsByType<T>(FindObjectsSortMode.None) (1 file)
- enableWordWrapping → textWrappingMode (3 files)
- Add _ = discard to unawaited async Task.Run calls (2 files)
- Remove unused variable in TutorialManager

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 16:25:25 -07:00
d1b675cb99 Remove dead duplicate tracking in FearAnimator (#6549)
FearAnimator maintained its own _activeObjects list, Track(), Untrack(),
and OnDestroy() that duplicated base class TrackedEffectAnimator's
tracking. Since all objects were created via CreateTrackedObject() (which
adds to the base's _trackedEffects), but Track() was never called,
_activeObjects was always empty — making FearAnimator's Untrack() calls
no-ops and its OnDestroy() cleanup redundant.

Remove the dead code and let the base class handle all tracking.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 16:18:54 -07:00
df7a724542 Increase tutorial battle defender units by 20% (#6547)
The tutorial battle is too hard for new players. Buff the defender's
starting longbowmen and two reinforcement battalions by ~20% to make
the battle easier, staying within battalion type capacity limits.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 07:02:03 -07:00
6f4041a510 Handle tutorial battle reset in Unity client (#6546)
* Handle ShardokBattleResetResponse in Unity client

Route the battle reset message through PersistentClientConnection and
EagleGameModel to the ShardokGameModel, which clears its mutable state
and signals the controller. The controller clears overlays, labels, and
the game-over UI so the restarted battle rebuilds normally from new
setup results.

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

* Add Old Marek dialogue on battle reset

When a tutorial battle resets, Old Marek comments on a strange feeling
of deja vu and encourages the player to try a different approach.

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

* Wait for Eagle confirmation before allowing battle exit

Previously, the Shardok controller showed "Exit Battle" as soon as the
game reached Victory state and immediately cleaned up the model. This
meant a subsequent ShardokBattleResetResponse had nothing to reset.

Now the model stays alive after Victory, and "Exit Battle" only appears
once Eagle confirms removal via RemovedBattleIds. If a battle reset
arrives instead, the model is still intact for ResetForNewBattle().

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

* Fix GetPlayerName crash with negative playerId after battle reset

ResetForNewBattle sets CurrentPlayer to -1, which passed the
"playerId < players.Count" check but threw on list access.
Add a lower bounds check.

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

* Reset battle tutorials on battle reset so they re-fire on retry

Adds ResetBattleTriggerFlags() for combat-only trigger flags and
ResetCompletedScriptsById() for selective dialogue reset. Strategic
tutorial progress is preserved.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 06:56:56 -07:00
15e6cc2e5f Handle BattleResetResponse in Eagle for tutorial battle resets (#6537)
- Add receiveBattleReset to BattleUpdateReceiver trait
- Handle BattleResetResponse in ShardokInterfaceGrpcClient streaming
- Implement receiveBattleReset in GamesManager (delegates to controller)
- Add no-op implementation in CustomBattleManager
- Add postBattleReset to GameController: resets shardok history and
  notifies human clients via ShardokBattleResetResponse
- Add sendBattleReset to HumanPlayerClientConnectionState
- Add withResetShardokResults to FullGameHistory/PersistedHistory/InMemoryHistory
- Add shardok_battle_scala_proto dependency to BUILD.bazel

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 06:49:43 -07:00
657e46ad4c Detect tutorial battle loss and send BattleResetResponse in Shardok (#6536)
- Add IsTutorialBattleEnabled() and DidDefenderLose() to ShardokEngine
- Add WaitResult enum (GAME_OVER, DISCONNECTED, BATTLE_RESET) replacing
  bool return from WaitForUpdatesAndPush
- Add OnBattleReset() to StreamSubscriber interface
- Detect tutorial loss in WaitForUpdatesAndPush and return BATTLE_RESET
- In SubscribeToGame, loop on BATTLE_RESET: tear down the old game,
  restart from serialized NewGameRequest, and stream fresh state

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 06:48:56 -07:00
3c2dd7f562 Fix settings panel not showing on first Escape press (#6545)
* Fix settings panel not showing on first Escape press

SettingsPanelController lives on an inactive panel prefab, so Start()
only runs the first time the panel is activated. When ToggleActive()
activated the panel, Start() would immediately set _active=false and
hide it again, swallowing the first Escape press. The slider
initialization in Start() also triggered volume change callbacks,
causing an audible volume shift.

Sync _active with the panel's current state in Start() instead of
forcing it to false.

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

* Remove defensive null checks on Inspector fields in SettingsPanelController

Per project convention, Inspector fields should throw NullReferenceException
if not linked rather than silently skipping code.

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

* Remove tileBorderWidth serialized fields from Settings Panel prefab

These fields were removed from SettingsPanelController.cs; clean up the
prefab to avoid Unity serialization warnings.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 19:33:44 -07:00
fd851c83b0 Fix Shardok battle race condition: hex tiles not rendering (#6544)
* Fix Shardok battle race condition — hex tiles sometimes never render

ImageForTerrainTracker and TacticalAssetLoader were plain C# singletons
whose LoadAsync() coroutines ran on ShardokGameController (which gets
deactivated). ConnectionHandler.Start() deactivates the shardokContainer,
killing any in-flight coroutines. The singletons' _loadStarted guard
then prevented reloading, leaving IsLoaded permanently false and
SetUpGameAfterLoad() spinning forever at its while-loop.

Convert both to MonoBehaviour singletons meant to live on a persistent
GameObject (Main Camera). They now own their own Awake() → LoadAsync()
lifecycle and are immune to container deactivation. Remove the redundant
StartCoroutine kicks from ShardokGameController and EagleGameController.

Requires adding ImageForTerrainTracker and TacticalAssetLoader components
to Main Camera in Gameplay.unity (scene change not included in this
commit).

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

* Add ImageForTerrainTracker and TacticalAssetLoader to Main Camera

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 19:16:42 -07:00
d3712699d8 Bump actions/github-script v7 to v8 for Node 24 support (#6543)
Node.js 20 actions are deprecated and will be forced to Node 24 starting
June 2, 2026.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 08:06:59 -07:00
94459d6e87 Restore keychain search list before iOS export (#6542)
xcodebuild archive can reset the user keychain search list during long
builds, dropping the temporary CI keychain that holds the Apple
Distribution signing cert. Re-add and unlock the keychain right before
the export step so xcodebuild -exportArchive can find the certificate.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 08:05:36 -07:00
64fdb5e08a Remove chimpanzee beast — no suitable animation available (#6541)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 07:05:31 -07:00
52a7accfa2 Retry LFS pull to handle Gitea mirror sync race (#6540)
Gitea's mirror-sync API is async — the GitHub webhook triggers it but
returns 200 before the sync completes. CI runners can start git lfs pull
before new LFS objects are available on Gitea. Extract LFS fetch into a
shared script with retry logic (5 attempts, 15s backoff) to bridge the
gap.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 06:59:13 -07:00
71d7f62023 Add 26 new human-type beasts reusing existing Polytope archetypes (#6539)
Knight: inquisitor, zealot
Soldier: smuggler, racketeer, raider, looter, privateer
Archer: poacher, rustler, bushwhacker
Militia: vandal, goon, scoundrel, lout, delinquent, rapscallion
Peasant: anarchist, dissident, malcontent, provocateur, demagogue,
         mutineer, firebrand, deserter, squatter
Butcher: maniac

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 06:58:37 -07:00
1f0104e484 Fix RemoveController using shared_lock for map mutation (#6538)
RemoveController was using std::shared_lock (read lock) while calling
erase() on the runningControllers map. This is undefined behavior
since other threads could be concurrently reading the map. Use
std::unique_lock (write lock) instead.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 06:54:43 -07:00
98d70fa995 Add hippogryph beast effect using DragonEffect flight system (#6533)
* Add hippogryph beast effect using DragonEffect flight system

Reuses DragonEffect.cs (flight/ground state machine) with a custom
HippogryphMapAnims controller mapping 15 animation states to the
PROTOFACTOR Hippogriff asset. Includes PBR materials, 12 animation
FBXes, and tuned flight parameters (scale 8, fly height 12).

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

* Reduce hippogriff texture maxTextureSize to 512

The Addressable bundle build was failing during ArchiveAndCompress
because the hippogriff textures were imported at 4096x4096 (default
from the asset pack). For a map-view beast effect, 512 is plenty.

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

* Fix texture .meta files stored as LFS pointers instead of YAML

The broad directory-level LFS pattern in .gitattributes was catching
.meta text files. Replace with a global *.jpg pattern (other binary
formats already have global patterns) and re-add the 8 texture .meta
files as regular blobs so Unity can read them on CI.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 22:16:51 -07:00
e7f9f5cc35 Add BattleResetResponse proto messages (#6534)
* Add BattleResetResponse proto messages for tutorial battle reset

Add BattleResetResponse to the internal Shardok interface (oneof case 4
in GameStatusResponse) and ShardokBattleResetResponse to the client-facing
Eagle API (oneof case 8 in GameUpdate). These signal that a tutorial battle
should reset after the defender loses.

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

* Add no-op handler for BattleResetResponse in exhaustive match

Prevents -Werror build failure from non-exhaustive pattern match
after adding the new oneof case. Full handling in follow-up PR.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 22:11:57 -07:00
fc0edc38ef Clean up Unity-iPhone DerivedData after iOS archive (#6535)
Each xcodebuild archive creates a new ~3.6GB Unity-iPhone-<random>
folder in DerivedData that was never cleaned up, accumulating on
the build runner.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 22:11:38 -07:00
e6aa15ec50 Update BEAST_EFFECTS.md with 9 new beast animations (#6531)
Add black panther, rhinoceros, gorilla, hyena, leopard, warthog, emu,
kangaroo, and tasmanian devil to the custom animations table. Remove
them from the "not yet set up" section and note which remaining pack
animals are not in beasts.tsv.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 06:35:08 -07:00
5f082f9e4d Implement Blow Bridge command and factory (#6524)
Engineers standing on a bridge tile can attempt to destroy it. The
player selects an adjacent traversable, unoccupied tile as the
destination. A D100 success roll determines if the bridge is destroyed.
Whether the roll succeeds or fails, the engineer moves to the selected
tile. Bridges are no longer valid Reduce targets.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 21:53:28 -07:00
25592e7268 Add Unity client support for Blow Bridge command (#6526)
* Add Unity client support for Blow Bridge command

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

* Improve Blow Bridge UX: icon, sound, animation position and rendering

- Change command icon from catapult (reduce.png) to manabomb
  (Engineering_25_manabomb.png)
- Use explosion impact sound (Fire Spelll 02) for attempt, structural
  breakage sound for success, failure horn for failure
- Fix animation position: use sourceGridIndex (bridge hex) instead of
  targetGridIndex (engineer's destination) since the engineer starts ON
  the bridge and jumps to an adjacent hex
- Preserve cached source position for BlowBridge results so the server's
  post-move actor location doesn't override the bridge hex
- Replace hammer/axe attempt animation with debris explosion
  (AnimateRepairFailed) matching the destructive nature of the action
- No visual animation on failure, just the negative sound
- Add zPosition parameter to AnimateRepairFailed so BlowBridge debris
  renders in front of the bridge 3D object (at Z=-5)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 21:50:04 -07:00
b49ffbadbe Propagate AI thread errors to Eagle via gRPC stream (#6530)
When the AI thread throws an exception, instead of re-throwing (which
calls std::terminate and silently kills the thread), store the error
message, set an atomic flag, and wake up waiting subscribers. The gRPC
stream subscriber detects the failure and returns INTERNAL status to
Eagle, which triggers Sentry notification. The error message includes
game ID, player ID, and round number for easier debugging.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 16:32:11 -07:00
efe99e298b Fix AI generating invalid Become Outlaw commands (#6529)
ToPlayerInfoProto() was not copying the cannot_become_outlaw flag
when converting flatbuffer PlayerInfo to proto for the AI's
GameStateView. This caused the AI to always think outlaw was
available, generating extra BECOME_OUTLAW_COMMAND entries and
triggering a command count mismatch crash.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 16:28:59 -07:00
a2aea00034 Add 9 new beast effects: black panther, rhinoceros, gorilla, hyena, leopard, warthog, emu, tasmanian devil, kangaroo (#6527)
Each beast has TSV stats, FBX animation converted to Generic, animator
controller with idle/walk/eat/attack states, effect prefab with tuned
spawn parameters, and Addressables registration. Models sourced from
Africa Animals Pack V1 (black panther, rhinoceros), Africa Animals Pack
Low Poly V2 (gorilla, hyena, leopard, warthog), and Australia Animals
Pack V1 (emu, tasmanian devil, kangaroo).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 16:09:15 -07:00
5f17877e71 Add lion and velociraptor beast effects (#6525)
* Add lion and velociraptor beast effects

Add animated lion (male + lioness) and velociraptor province beast effects
with Generic animation controllers. Includes only the specific model files
needed from Africa Animals Pack V1 and Dino Pack Low Poly V1.

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

* Fix lioness animation with per-prefab animator controller

The lioness wasn't animating because the shared LionMapAnims controller
references clips from the Lion FBX, whose bone paths (LionSkeleton/...)
don't match the Lioness model (LionessSkeleton/...). Create a separate
LionessMapAnims controller referencing Lioness FBX clips and use the
per-prefab animatorControllers array to assign each model its own
controller. Also add the standalone Lion/Lioness prefabs that LionEffect
references.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 10:59:21 -07:00
9cd22c43c9 Add Blow Bridge proto definitions (#6523)
Add BLOW_BRIDGE_COMMAND (38), BLOW_BRIDGE (80), and
BLOW_BRIDGE_FAILED (81) enum values for the upcoming
Blow Bridge engineer command.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 10:48:05 -07:00
7786191430 Add hippopotamus beast animation using Africa Animals Pack Low Poly V2 (#6522)
Import the Africa Animals Pack and wire up hippopotamus as an AnimalEffect
beast. Switch the hippo FBX import to Generic animation type for Mecanim
compatibility and enable loopTime on looping clips. AnimalEffect now strips
legacy Animation, Rigidbody, and Collider components and adds an Animator
when prefabs lack one, supporting asset packs that ship with legacy setups.
Document the per-animal setup workflow for future Africa Animals Pack imports.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 22:11:32 -07:00
dfc334267c Add animated wind direction indicator to Shardok battle view (#6518)
* Add animated windsock wind direction & speed indicator to Shardok battle view

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

* Redesign wind indicator as animated arrow, remove weather from round info

Replace windsock (pole + sock) with a simpler arrow that points in the
wind direction, shakes with layered sine waves for organic feel, and
grows thicker at higher speeds. Fix NW/SW direction mapping swap. Remove
weather text from round info label since visual indicators now convey
this. Show "No Wind" in speed label when calm.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 14:43:49 -07:00
7c4b4ef490 Reduce unnecessary UI raycasting in Shardok battle view (#6520)
- Remove GraphicRaycaster from Weather Canvas (no interactive elements)
- Set raycastTarget=false on Odds Panel and Button Tooltip images
  (display-only elements that don't need click handling)
- Use Color.clear instead of null when clearing bg highlights in HexGrid
  to preserve mesh fill triangles

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 07:58:13 -07:00
79d26fa73a Fix duplicate unaffiliated hero exception in client (#6519)
Use ID-based lookup instead of object equality when diffing unaffiliated
heroes. The old code used Vector.contains (full object equality), so any
field change (profession, recruitmentInfo, etc.) caused the hero to
appear in both removed and added lists. If ordering or batching led to
the add arriving before the remove was processed, the client threw
"Duplicate unaffiliated hero" InvalidOperationException.

Now builds a Map by heroId for comparison, which correctly handles all
three cases: truly removed, truly added, and changed-in-place (emitted
as remove+add by ID so the client replaces the old entry).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 19:17:16 -07:00
72ef203a8a Always include shardokGameId in battle views for non-participants (#6517)
BattleFilter was setting shardokGameId to None for restricted
non-participant observers. This broke GameStateViewDiffer's
removedBattleIds computation, which uses flatMap(_.shardokGameId)
and silently drops None entries. The result: battle animations
were added to the client but could never be removed.

myPlayerId = None already prevents non-participants from joining
the Shardok game, so hiding the game ID served no purpose and
broke battle removal tracking.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 18:56:00 -07:00
85b620b644 Remove battle from ShardokBattles when Shardok game ends (#6515)
When a Shardok game ends (victory/defeat), the game model was
removed from ShardokGameModels but the battle was left in
ShardokBattles (OutstandingBattles). The only other removal path
was RemovedBattleIds in Eagle diffs, which may arrive late or not
at all for auto-resolved battles the player never entered.

This left the battle animation running on the strategic map
indefinitely after the battle ended.

Fix: also remove from ShardokBattles when processing ended games
in the Shardok update path.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 18:30:39 -07:00
fb36684e35 Update battle effects even when SwapModel skips due to commands (#6514)
SwapModel returns early when both old and new model have available
commands, skipping mapController.Model assignment and all province
effect updates. This meant battle animations persisted after a
battle ended if commands were available at the time.

Fix: call mapController.UpdateBattleEffects before the early return
so battle start/end animations are always kept in sync with the
model, even when the full model swap is skipped.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 18:14:42 -07:00
b6d83e3775 Fix battle animation appearing at center of conquered province (#6513)
When a province changed hands after a battle, UpdateBattleEffects
identified the defender by looking up the current ruling faction of
the defender province. After conquest, the attacker's faction matched
the province owner and was skipped, while the old defender was
processed — with OriginProvinceIds containing the defender province
itself, producing key (Wichel, Wichel) and an animation at the
province center.

Fix: skip any origin that equals the defender province. This can
never produce a meaningful animation (midpoint = province center)
and eliminates the dependency on current province ownership for
defender identification.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:43:12 -07:00
2d3050eded Fix BetrayAllyQuest: breaking an alliance was failing the quest instead of fulfilling it (#6512)
The failure check treated "no longer allied" as a failure condition, but
that's the success condition. Now: failure only if the target faction no
longer exists. Also added a general fulfillment check so the quest succeeds
even if the inline check in BreakAllianceResolutionHelpers doesn't fire
(e.g. when the ambassador is imprisoned).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:38:33 -07:00
bb848e73f3 Restrict battle observation to participants and allies (#6509)
Non-involved players can no longer observe tactical Shardok combat. They
still see the battle-in-progress animation on the strategic map and learn
the outcome, but won't receive individual Shardok actions or be offered
the observation UI. Allied non-participants can still observe.

Controlled by the RestrictBattleObservation setting (default 1/on). Set
to 0 in the admin console to revert to the old behavior.

Also syncs settings.tsv with LLM settings that were previously only in
BUILD.bazel, and fixes the settings generator to include string_setting
dep and correct battalion_type_loader deps.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:15:49 -07:00
37c96eceec Fix settings generator and sync settings.tsv with BUILD (#6511)
The settings generator had two issues:
- Missing string_setting dep when String-type settings exist
- Wrong battalion_type_loader deps (proto target instead of model state)

Also syncs settings.tsv with LLM settings (llmProvider, openAiModelName,
claudeModelName, geminiModelName) that were previously only manually
added to BUILD.bazel, and updates the openai_model_name target to match
the generator's snake_case convention.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:08:56 -07:00
64e41a3c12 Set cannotBecomeOutlaw for tutorial opening battle (#6508)
* Set cannotBecomeOutlaw for tutorial opening battle

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

* Fix: only set cannotBecomeOutlaw for the first battle, not all tutorial battles

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:55:06 -07:00
b81e795350 Direct March and Send Supplies animations toward destination province (#6506)
Instead of fixed directions (March slides right, Send Supplies launches
upward), both animations now compute the direction to the destination
province from the game state diff and animate toward it.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:48:11 -07:00
f8c2b19609 Prevent King from inviting Bridget and Hedrick in tutorial (#6507)
Add -500 trust toward the King (faction 2) for both Bridget (faction 4)
and Hedrick (faction 5) so the King's AI never sends them invitations.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:42:58 -07:00
95fbbf91a3 Add cannot_become_outlaw flag to battle request (#6505)
* Add cannot_become_outlaw flag to per-faction battle request

When set on a faction's PlayerSetupInfo, the BecomeOutlaw command
is suppressed for that faction's units. Default false preserves
existing behavior.

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

* Remove default values for cannotBecomeOutlaw, require explicit specification

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:42:02 -07:00
a1bd0a61ae Add tutorial Mobilization phase start logic (#6482)
* Add tutorial Mobilization phase start logic (#6478)

When starting a tutorial at Mobilization or EagleAppears, fast-forward
the game state past the opening battle to a plausible mid-game state
where Sadar controls two provinces and King's satellites are vacated.

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

* Replace dynamic tutorial phase setup with JSON resource loading

Add an extractor tool and loader to store pre-computed tutorial phase
transition results as JSON resources instead of computing them at
runtime from game state. This eliminates fragile dependencies on
knowing exact hero IDs and post-battle state deltas.

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

* Populate expansion_results.json with battle resolution data

Extracted from a tutorial playthrough: actions 4-7 covering battle
resolution, province held, Tarn disappearance, and end of resolution
phase. Actions 0-3 (GAME_START through FOOD_CONSUMED) are already
produced by the initial game creation flow.

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

* Pretty-print expansion_results.json

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:38:48 -07:00
0553da332e Boost tutorial defender unit sizes and Luke's faction bias (#6504)
Increase Sadar's three starting battalions by 15% (460→529, 270→311,
346→398) to give the player a stronger opening battle position.
Raise Luke the Prank-tricker's Sadar faction bias from 80 to 110.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 14:57:58 -07:00
d39038296f Update Unity prefab layouts and reimported assets (#6503)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:30:03 -07:00
36bc30f2bb Scale province action animations up ~30% (#6502)
Increase all spatial fields (icon sizes, distances, heights, spreads,
radii) by approximately 1.3x across all province action animation types.
Durations, counts, angles, and colors are unchanged.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:08:35 -07:00
1952ab796d Color March "keep" amount red when over province capacity (#6501)
Match the Send Supplies behavior: goldLeftLabel and foodLeftLabel turn
red when the amount remaining in the origin province would exceed its
gold or food capacity.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:43:40 -07:00
118311209f Add map validation: no starting positions on water, mountains, or overlapping (#6498)
Validates all maps to ensure starting positions are not placed on
impassable terrain (water, river, mountain) and that attacker starting
position sets don't overlap with each other.

Kojaria currently fails both checks and needs a map editor fix.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 07:40:47 -07:00
adminandGitHub 75b93ac3fc Update map: Kojaria (#6500) 2026-03-13 07:34:30 -07:00
fe5360d6f1 Fix missing flee/captured sound when battle ends (#6497)
When an AI unit flees and ends the battle, the GameStateViewDiff
removes the unit from UnitsById before ModelUpdated processes the
history. The sound-playing code required the actor to be found in
UnitsById to determine animation coordinates, silently skipping
the entire sound block when the lookup failed.

Add a fallback else branch that plays the sound without animation
when the actor unit has been removed from the model.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 07:26:29 -07:00
adminandGitHub 7dc0ce220f Update map: Chapellia (#6496) 2026-03-13 07:20:49 -07:00
74ade84dcd Replace Feast sound effect with crowd victory cheer (#6495)
The previous "battle_shout" sound felt more like rioting than
feasting. Replace with a group victory cry from freesound.org
(chripei, CC BY 4.0) that better conveys celebration.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 07:16:53 -07:00
f626eff404 Update Gameplay scene RectTransform anchors and prefab overrides (#6494)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 21:44:53 -07:00
0b06173e96 Fix Shardok overlay flash on unit selection (#6493)
* Stop label updates from clearing hex background highlights

SetUnitInfoLabels and SetOverlayLabel were calling SetCellBaseColor
(which sets Geometry.Color = Color.clear) and hexMesh.Triangulate on
every invocation. These methods manage TMP_Text labels, not hex
geometry, so the SetCellBaseColor and Triangulate calls were
unnecessary. Removing them eliminates O(N²) Triangulate calls per
selection change (one per cell, each iterating all cells).

ClearOverlays now explicitly resets Geometry.Color for cells that had
a BackgroundHighlightColor and does a single Triangulate when needed.

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

* Defer hex background highlight updates to HexGrid.Update for atomic mesh rendering

ClearOverlays was eagerly triangulating hexMesh (clearing background
highlights) while overlayMesh borders were only updated in Update().
This caused the two meshes to render out of sync for one frame when
Update order put HexGrid before MouseHandler. Now both meshes are
updated atomically in Update(), and ClearOverlays just clears the
data. Also reduces hexMesh.Triangulate calls from O(N) per overlay
cell per frame to at most one.

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

* Fix overlay label/image flash by deferring all cleanup to Update

ClearOverlays was eagerly clearing labels and follow-up images while
the overlay border mesh was only updated in HexGrid.Update(). When
Unity's script execution order put HexGrid.Update before
MouseHandler.Update (which changed after the Shardok prefab
extraction in #6485), the labels/images were cleared mid-frame but
not re-set until next frame — causing a visible one-frame flash on
every unit selection.

Now ClearOverlays just clears the data list. Update() owns all visual
state: it clears stale labels, images, and background highlights from
the previous frame, sets new ones from current overlayCells, and
triangulates both meshes — all atomically regardless of script order.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 21:41:24 -07:00
32a58fd8eb Clean up orphaned animation sprites when Map deactivates (#6492)
Animation objects are parented to mapContainer, not the animator. When
the Map deactivates mid-animation (e.g. entering a battle), coroutines
die but the partly-faded sprites linger. Track all objects created by
CreateUIObject and destroy any survivors in OnDisable.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 21:22:17 -07:00
53eb739cfe Add elephant/mammoth beast effect (#6489)
* Add elephant/mammoth beast effect using Animal Pack Deluxe v2

Wire up African and Indian elephant prefabs from the newly purchased
Animal Pack Deluxe v2 as a proper beast effect. Mammoths reuse the
same elephant models. Includes a custom ElephantMapAnims controller
to remap v2 animation state names to AnimalEffect's expected states.

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

* Fix elephant animation: use v2 pack's own controller, fix prefab refs

- Use the v2 pack's African_elephant_anim_controller directly instead
  of our custom ElephantMapAnims (which couldn't resolve FBX clips)
- Fix animalPrefabs fileIDs to match actual root GameObjects
- Regenerate animation FBX .meta files for Unity 6 compatibility

The v2 controller's state names don't fully match AnimalEffect's
expected names (idle A/attack A vs idle/attack), so animations are
partial. Next step: remap state names to get all 4 animations working.

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

* Rename v2 controller states to match AnimalEffect expectations

Rename 'idle A ' → 'idle' and 'attack A' → 'attack' in the v2 pack's
African_elephant_anim_controller so all 4 animation states work with
AnimalEffect's Animator.Play() calls.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 20:09:17 -07:00
4e39baf3fa Queue province animations while Map is inactive, replay on reactivate (#6490)
Action results arriving from the server while the Map game object is
inactive (e.g. during a battle) are queued and replayed 1s after the
Map reactivates, so the player sees what happened while they were away.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 19:53:24 -07:00
95ce201b20 Apply lightweight loop filter at root of iterative deepening search (#6491)
The full AICommandFilter was only applied during lookahead (inside
FindBestCommand), not at the root level of IterativeSearch. This
caused the AI to repeatedly choose METEOR_TARGET_COMMAND because the
re-target filter never ran on the top-level command list.

Adds FilterLoopingCommands — a minimal filter that only removes
genuinely never-useful commands (meteor re-target/cancel when a target
is already set). The full aggressive filter stays in lookahead only,
where pruning is a performance optimization. Applying the full filter
at the root could miss moves that look bad locally but prove
worthwhile with deeper search.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 19:47:28 -07:00
aeeb3ec8e0 Fix AI crash: meteor cancel with 0 AP after meteor start (#6487)
METEOR_START uses ActionCost::usesAll which drains AP to 0. The
MeteorTargetCommandFactory then unconditionally generates a
METEOR_CANCEL command (cost 1 AP) for the mage in TARGET state.
When the AI evaluates this command, MutatingSpendActionPoints throws
because 1 > 0.

Two fixes:
1. Set meteorCancelActionPointCost to 0, matching #6454's fix for
   meteorTargetActionPointCost.
2. Filter out meteor re-target/cancel in AICommandFilter when the
   mage already has a target. Re-targeting exists for human misclick
   correction; the AI commits to its first choice and could otherwise
   loop endlessly re-targeting at 0 AP cost.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 18:41:54 -07:00
6886964efa Fix mammoth stats from bandit template to large animal (#6488)
Mammoth had human-bandit-like stats (likelihood 0.10, power 1.5,
economy devastation) instead of large-animal stats. Update to be
rarer than elephants with appropriate power, count, and devastation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 06:40:48 -07:00
aa77094790 Extract Command Panel and 35 sub-panels into prefabs (#6486)
* Extract Command Panel into prefab

Move the Command Panel hierarchy (37 command sub-panels) from
Gameplay.unity into its own prefab at Assets/Eagle/. This is the
largest single component in the scene at ~126K lines. Scene-level
cross-references (eagleGameController, connectionHandler, hexGrid,
shardokContainer, etc.) are preserved as PrefabInstance overrides.

Reduces Gameplay.unity from ~232K to ~102K lines (56% reduction).

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

* Extract 35 command sub-panels into individual prefabs

Break down Command Panel.prefab (126K lines) into 35 individual
prefabs under Assets/Eagle/CommandPanels/. Command Panel itself
becomes a thin container (~6K lines) with PrefabInstance references.

Largest sub-panel (March Panel) is 12.7K lines; smallest are ~230
lines. All are independently editable and produce focused diffs.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 21:45:54 -07:00
3ccdcaa6cd Extract Shardok Container into prefab (#6485)
Move the Shardok Container hierarchy (Shardok Canvas + Weather Canvas)
from Gameplay.unity into its own prefab at Assets/Shardok/. External
field references (mainCamera, eagleCanvas, soundManager, audioClipSource)
are preserved as scene-level PrefabInstance overrides.

Also adds UNITY_POST_PROCESSING_STACK_V2 scripting define symbols.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 14:18:52 -07:00
c8c95ac1b6 Refactor EagleCommonTextures to singleton pattern (#6484)
Eliminates 3 duplicate instances by adding a static Instance property,
replacing all GetComponentInParent lookups and serialized field references
with EagleCommonTextures.Instance. Removes the duplicate components from
ConnectionCanvas, Shardok Container, and Eagle Canvas in the scene, and
moves the single remaining instance to Main Camera so it's guaranteed to
have Awake() called regardless of which canvases are active.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 14:03:04 -07:00
bbbe4211e3 Extract Custom Battle Panel into prefab (#6483)
* Extract Custom Battle Panel into prefab

Remove baked-in Custom Unit Row instances from the prefab since
EventBasedTable.Awake() destroys them and recreates from rowPrefab
at runtime. Also remove stale SimpleFileBrowser references from
eagle0.sln.

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

* Convert Custom Battle Panel prefab from LFS to regular git

This prefab is actively edited line-by-line and benefits from normal
git diff/blame/merge. LFS is better for opaque binary assets.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 11:25:51 -07:00
a1391cdad2 Add missing Unity .meta files and import artifacts (#6481)
* Add missing Unity .meta files, HoneyBadger import artifacts, and fix_import.py

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

* Remove HoneyBadger import artifacts and gitignore FBX auto-generated files

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 09:21:22 -07:00
c25d042690 Remove SimpleFileBrowser plugin and associated UI (#6480)
Remove the SimpleFileBrowser plugin and its usage in CustomBattleHandler
(custom map loading and game request loading via file dialogs). Remove
the Custom Map Toggle, Load Button from the Custom Battle Panel, and
the obsolete Tutorial Lite button from the Lobby Panel prefab.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 08:58:21 -07:00
d9666dc01d Apply persisted settings at startup even when Settings Panel is inactive (#6479)
The Settings Panel prefab starts inactive, so Start() never runs until
the user opens it. This caused persisted values (province label font
size, audio volumes, tooltip behavior) to not be applied until Escape
was pressed, producing a visible font resize.

Split initialization: ApplyPersistedSettings() loads PlayerPrefs and
applies to game systems early via SettingsKeyListener.Start() on the
always-active PersistentCanvas. The deferred Start() just syncs UI
sliders/toggles to match the already-applied values.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 07:57:40 -07:00
cd9fc49bde Replace tutorial buttons with phase dropdown (#6474)
* Replace tutorial buttons with phase dropdown in ConnectionHandler

Replace the two separate tutorial buttons (tutorialButton, skipBattleTutorialButton)
with a TMP_Dropdown + Button combo so any tutorial phase can be selected from the lobby
without adding more buttons for each new phase.

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

* Fix C# TutorialPhase enum names to match protobuf codegen

C# protobuf strips the common prefix, so the enum values are
TutorialPhase.OpeningBattle (not TutorialPhaseOpeningBattle), etc.

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

* Wire tutorial phase dropdown and start button in Gameplay scene

Add missing using directive for Net.Eagle0.Eagle.Common namespace
and re-wire tutorialPhaseDropdown and startTutorialButton to the
Lobby Panel prefab instance.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 07:25:31 -07:00
1ca4ee5cc0 Extract Connection, Lobby, and DropGameConfirmation panels into prefabs (#6478)
Reduces Gameplay.unity by ~13k lines by extracting three connection UI
panels into standalone prefabs with scene-level overrides for callbacks
that reference the scene-level ConnectionHandler.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 07:12:39 -07:00
42957266ba Add wind-assisted range 3 archery for longbowmen (#6457)
Longbowmen can now target enemies at range 3 when shooting in the
direction the wind is blowing (±1 hex sector), provided wind speed
meets the configurable `longbowWindBonusRangeMinSpeed` threshold
(default 20 mph). The 20 mph threshold reflects the point where wind
meaningfully extends arrow range, below the 35 mph blizzard threshold
where archery is already disabled.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 07:06:31 -07:00
6a81ce97db Replace tutorial booleans with TutorialPhase enum (#6477)
* Replace tutorial booleans with TutorialPhase in CreateGameRequest

Replace `is_tutorial` + `skip_tutorial_battle` booleans with a single
`TutorialPhase tutorial_start_phase` field, making the API extensible
for future tutorial phases (Mobilization, etc.) without adding more
boolean flags.

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

* Add service visibility to tutorial_phase_converter BUILD target

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

* Keep old tutorial boolean fields in CreateGameRequest proto

Keep is_tutorial and skip_tutorial_battle fields so the Unity build
doesn't break. They'll be reserved in the client-side PR.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 07:05:11 -07:00
5b84d20f69 Extract Settings Panel into prefab (#6476)
* Extract Settings Panel into prefab to reduce Gameplay.unity size

The Settings Panel hierarchy (~11k lines) was inline in the scene file,
making Gameplay.unity harder to diff and merge. Extract it into a
standalone prefab with scene-level overrides for cross-references.

Fix 15 event callback targets that Unity zeroed out during extraction
(sliders, toggles, buttons all needed re-pointing to the
SettingsPanelController inside the prefab).

Add SettingsKeyListener on PersistentCanvas to handle Escape/F11 keys,
since the SettingsPanelController now lives on the (sometimes inactive)
prefab root and can't run Update() when hidden.

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

* Remove scene overrides that zeroed out prefab event callbacks

The prefab instance in Gameplay.unity had overrides that set 6 event
callback targets to null, overriding the correct values in the prefab.
Remove these overrides so the prefab's own targets take effect.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 22:14:49 -07:00
b3adebbb0a Add tiger beast effect using ithappy Animals FREE pack (#6475)
* Add tiger and lion beast effects using ithappy Animals FREE pack

Import the free ithappy Animals FREE asset pack and create tiger/lion
beast effects. The tiger model is reused at 1.7x scale for lion.
A custom TigerMapAnims controller maps ithappy's idle/walk/idle_rare/run
clips to AnimalEffect's expected idle/walk/eat/attack state names.

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

* Remove lion effect (scaled tiger is not convincing)

Lion falls back to generic vultures until a proper model is found.

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

* Fix ithappy files stored as LFS objects breaking Unity import

The broad ithappy/** LFS rule was storing text YAML files (.controller,
.mat, .prefab, .anim, etc.) as LFS objects, causing Unity to fail with
"File may be corrupted" errors. Remove the rule and re-add files so text
files are stored as regular git objects while binaries (.fbx, .png) are
still covered by per-extension LFS rules.

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

* Strip third-party scripts/physics from animal prefabs on spawn

ithappy Tiger_001 prefab includes CharacterController, CreatureMover,
and MovePlayerInput components that conflict with AnimalEffect's own
movement system. DestroyImmediate these after instantiation to prevent
"CharacterController.Move called on inactive controller" errors.

Also wires up tigerEffectPrefab in Gameplay.unity.

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

* Move beast effect prefabs to Addressables for CDN delivery (#6373)

Replace 33 serialized GameObject fields in ProvinceBeastsController with
Addressables.LoadAssetsAsync label-based loading ("beast-effects").
Prefabs stay in Assets/Eagle/Effects/ but are now delivered via CDN at
https://assets.eagle0.net/addressables/[BuildTarget] instead of being
bundled in the app binary. This removes ~80-100 MB of 3D models,
textures, and animations from the initial app download.

Loading strategy:
- Eager load in Start() (last priority — after music)
- Game state that arrives before loading completes is stashed and
  applied when ready
- If loading fails (offline, no cache), beasts simply don't render

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* Add tiger and elephant beast effects using Animal Pack Deluxe

Route "tiger" and "elephant" beast names to dedicated TigerEffect and
ElephantEffect prefabs in ProvinceBeastsController. Prefabs to be wired
up in the Unity editor using existing Animal Pack Deluxe assets.

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

* Register TigerEffect in Addressable beast-effects group

The TigerEffect prefab was added in the add-tiger-effect branch but was
never registered in the Beast Effects Addressable group, so LookupPrefab
returned null at runtime. Also removes a duplicate "tiger" switch case
from the merge.

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

* Fix AnimalEffect component removal errors on spawn

Instantiate prefabs inactive to prevent CharacterController stepOffset
validation errors, and remove MonoBehaviours in reverse component order
to respect [RequireComponent] dependency chains before removing
CharacterController.

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

* Fix ithappy Animals_FREE material to use Built-in Standard shader

The material shipped with a URP Lit shader reference, causing solid pink
rendering on Built-in render pipeline. Swap to Built-in Standard shader
and remove the URP version tracker MonoBehaviour.

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

* Fix tiger animations by using standalone .anim clips

The ithappy Animals_FREE FBX was imported with avatarSetup: 0 (no
avatar), so its embedded animation clips had no bone binding data.
Switch TigerMapAnims.controller to reference the standalone .anim files
which have explicit transform path bindings. Also build a Generic avatar
at runtime for prefabs missing one, and set up the Animator before
activation so it initializes with correct avatar and controller.

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

* Fix duplicate Start/LoadBeastEffects from rebase

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

* Remove unused ithappy Animals_FREE assets

Only the tiger model, texture, material, and animations are needed.
Removes all other animals (chicken, deer, dog, horse, kitty, penguin),
demo scenes, skyboxes, scripts, floor material, animation controllers,
and render pipeline conversion files.

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

* Remove CharacterController and deleted scripts from Tiger prefab

The prefab still referenced CreatureMover and MovePlayerInput scripts
that were deleted in the previous commit, causing missing script errors
in the Unity editor.

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

* Update Tiger_001 prefab after Unity re-serialization

Unity re-serialized the prefab after we removed the CharacterController
and missing script components. This is the clean editor-saved version.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 16:44:05 -07:00
007fd039be Add battle-in-progress animation on strategic map (#6473)
* Add battle-in-progress animation on strategic map

Display looping weapon-clash effects between defender and attacker origin
provinces while battles are active. Follows the ProvinceFestivalController
pattern for centroid loading and effect lifecycle management.

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

* Load battle sound from sfx-combat addressables instead of inspector field

Use the "melee" clip from the "sfx-combat" addressable label, matching
the pattern used by ProvinceActionAnimator and SoundManager.

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

* Tune execution animation duration

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

* Fix battle effect: orientation, sound, two weapons, test provinces

- Fix upside-down weapons by flipping weapon2 Y-scale (mirroring)
- Play melee clip as one-shot at each impact instead of continuous loop
- Use two different weapon sprites (sword + axe) for visual variety
- Change test ContextMenu to use adjacent provinces 2 and 5
- Add Gameplay.unity scene wiring

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

* Add arrow volleys, fix weapon orientation, fix audio pattern

- Add arrow volley animations flying between province centers with
  parabolic arc, random direction, and archery sound
- Fix weapon rotation: per-weapon offsets (sword blade down = +90,
  mace head up = -90) so both swing business-end first
- Fix arrow sprite rotation offset (-135 for strategic map UI space)
- Fix audio: move playback to controller using Action callbacks,
  matching ProvinceActionAnimator pattern (same object owns AudioSource
  and calls PlayOneShot)
- Load audio in OnEnable with Dictionary<string,AudioClip> like
  ProvinceActionAnimator
- Add configurable volume and rotation offset inspector fields

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

* Add meta files for new battle effect scripts and addressable settings

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 13:31:54 -07:00
6472e1dabe Add origin province IDs to ShardokBattleView for battle-in-progress animations (#6472)
Expose attacker army origin provinces in the ShardokBattlePlayerInfo view so the
Unity client can draw battle-in-progress animations between defender and attacker
origin provinces on the strategic map.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 12:30:19 -07:00
d9e7b55279 Split captured hero recruitment ActionResultTypes and add animations (#6470)
* Split captured hero recruitment into distinct ActionResultTypes and add captured hero animations

HandleCapturedHeroesCommand previously used RecruitHeroes (21) for both successful
and failed captured hero recruitment, making them indistinguishable on the client.
Add CapturedHeroRecruited (162) and CapturedHeroRecruitmentRefused (163) so the
Unity client can play the correct animation for each outcome. Also add province
animations for all 6 captured hero dispensations (recruited, refused, imprisoned,
exiled, executed, returned).

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

* Add sound effects for captured hero animations

Map each captured hero ActionResultType to an appropriate sound clip,
reusing the same clips as the animations they share patterns with.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 11:15:24 -07:00
2e8d2bc83d Split captured hero recruitment into distinct ActionResultTypes (#6471)
HandleCapturedHeroesCommand previously used RecruitHeroes (21) for both successful
and failed captured hero recruitment, making them indistinguishable on the client.
Add CapturedHeroRecruited (162) and CapturedHeroRecruitmentRefused (163) so the
client can play the correct animation for each outcome.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 11:08:39 -07:00
1776198890 Fix tutorial duplicate hero bug by changing Tarn from Fled to Outlawed (#6469)
* Fix tutorial duplicate hero bug by changing Tarn from Fled to Outlawed

PR #6464 set fleeProvinceId to None for the tutorial attacker army, but
TutorialBattleAutoResolve still marked Tarn as Fled. With no flee
province, unitReturned() returned true for Fled, triggering the
shattered army path which created outlaws for ALL attacker heroes —
duplicating the heroes already created via defenderCP's newOutlaws.

Changing Tarn to Outlawed avoids the shattered army path entirely while
preserving the tutorial storyline: Tarn escapes capture and doesn't
appear in HandleCapturedHeroes, then EagleAppearsAction picks him up.

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

* Update TutorialTarnDisappearsAction to handle Outlawed status

With Tarn now marked as Outlawed (instead of Fled), he ends up as an
unaffiliated hero in the battle province rather than in an incoming
army to Nikemi. Update the disappears action to remove him from
unaffiliated heroes so he's properly hidden until EagleAppearsAction.

Also remove the now-dead fled/incoming-army logic and unused MovingArmy
import.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 09:50:28 -07:00
a74cf4fbbf Fix missing Ranil and Elena portraits in post-battle tutorial dialogue (#6468)
Set speakerImagePath directly in tutorial_strategic.json for John Ranil
and Elena Fyar instead of relying on dynamic resolution, which can fail
due to timing issues with the Eagle model.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 08:51:52 -07:00
90c9327b25 Add tutorial indicator to lobby running game items (#6467)
* Add tutorial indicator to lobby running game items

Add a tutorialIndicator GameObject field to RunningGameItem that is
shown/hidden based on the game_type from the server. Pass GameType
through from ConnectionHandler so the client can distinguish tutorial
games in the lobby list.

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

* Wire tutorial indicator in Running Game prefab

Connect the Tutorial TextMeshPro label to the tutorialIndicator
field on RunningGameItem so it shows/hides based on GameType.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 08:27:15 -07:00
51579752a2 Add 19 province action animations with sound effects (#6466)
Adds one-shot visual animations at province centers for all remaining
player commands: Rest, Train, OrganizeTroops, ArmTroops, RecruitHeroes,
Trade, OrdersIssued, SentSupplies, SuppressBeasts (success/fail),
Divined, March, SwearBrotherhood (success/fail), ControlWeather, Alms,
HeroGift, ApprehendOutlaw, Recon, ExileVassal, and StartEpidemic.

Each animation includes inspector-tunable parameters, a ContextMenu test
method, and a sound effect mapping wired through the actionSounds array.
21 audio clips added to the sfx-combat Addressables group.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 07:40:23 -07:00
e8be706370 Add game_type to lobby GameInfo proto and server (#6465)
Plumb the existing GameType enum (NORMAL/TUTORIAL) through to the lobby
response so clients can distinguish tutorial games from normal games.

- Add game_type field to RunningGame (persistence) and GameInfo (API) protos
- Add gameType to GamePlayerInfo case class and populate it in all 4
  construction sites (gamesFor cached/full-load, gamesForWithoutBlocking
  loaded/unloaded) plus save()
- Pass gameType through to GameInfo in EagleServiceImpl

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 07:37:04 -07:00
b313ad6507 Fix tutorial battle flee by setting fleeProvinceId to None and remove dead canFleeHeroIds (#6464)
The tutorial attacking army had fleeProvinceId set to its origin province, which
allowed Tarn's forces to flee during the opening battle. Since canFleeHeroIds was
always Set.empty, the flee logic fell back to fleeProvinceId.isDefined (true).
Fix by setting fleeProvinceId = None for the tutorial army, and remove the unused
canFleeHeroIds field entirely from ShardokBattle, its proto, converter, and all
call sites.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 07:11:49 -07:00
bb02481df9 Add TutorialPhase to GameType ADT (#6453)
* Add TutorialPhase to GameType ADT to track tutorial progression

Converts GameType from a simple Normal/Tutorial enum into an ADT where
Tutorial wraps a TutorialPhase (OpeningBattle, Expansion, Mobilization,
EagleAppears, Complete). This separates "what kind of game" from "what
phase of the tutorial", enabling phase-aware event logic and future
ability to start at a specific phase.

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

* Fix C# tutorial check to match on Tutorial specifically

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

* Use TUTORIAL_PHASE_ prefix for proto enum values

Follow Google's protobuf enum naming best practice of prefixing all
values with the enum name.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 06:47:00 -07:00
10b43e9225 Add necromancer control chain visual effect (#6463)
Pale yellow/white particle chain connects necromancers to their
controlled undead units. Shimmers in and out when not actively
controlled this round, becomes solid translucent when controlled.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 22:06:59 -07:00
f79b89a721 Widen meteor beam destination and speed up during Cast phase (#6462)
Increase destinationScale from 45 to 60 for a wider cone at the target.
Track the mage's meteor phase per beam and apply a 3x speed multiplier
to vibration and shimmer during the Cast phase.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 21:57:10 -07:00
bcf1641d39 Add sound effect for meteor start animation (#6461)
* Add sound effect for meteor start animation

Map ActionType.MeteorStart to Fire Spelll 01 from the magic spells
sound pack so the meteor preparation animation has an accompanying
magic charging sound.

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

* Add sound effect for meteor target animation

Map ActionType.MeteorTarget to Fire Spelll 02 so the targeting
crosshairs animation also plays a fire magic sound.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 21:55:52 -07:00
c43750c206 Fix tutorial button visibility not updating after login (#6460)
SetupLobbyUI ran at startup before login, so IsAdmin was stale.
Re-evaluate admin-gated button visibility in OnOAuthLoginSuccess.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 21:38:44 -07:00
4c81a90aac Add Feast province animation with food toss effect (#6459)
Add a feast animation to ProvinceActionAnimator that spawns food items
(drumstick, beer, wine, grapes, cheese, bread) tossed into the air on
parabolic arcs with spin and fade. Plays a battle_shout cheering sound.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 21:36:13 -07:00
491a9427e6 Skip auto-selecting mage with existing meteor target (#6458)
* Skip auto-selecting mage unit that already has a meteor target

When a mage already has a CastTarget set, don't auto-select them
via SelectAppropriateDefaultCommand. The player can still manually
click the unit to re-target, but we no longer default to showing
commands for a unit that has already targeted.

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

* Find untargeted mage when multiple have MeteorTarget available

Instead of checking the first unit with MeteorTargetCommand and
skipping the entire command type if that unit already has a target,
search through all available commands of the type to find a unit
that hasn't targeted yet.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:38:51 -07:00
f43a2b852c Wire ProvinceActionAnimator in Gameplay scene (#6456)
* Wire ProvinceActionAnimator in Gameplay scene

Add ProvinceActionAnimator component to the scene with Inspector
references and action sound configuration for Improve animations.

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

* Update ProvinceActionAnimator scene wiring

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:25:38 -07:00
85e499e47f Add game ID and backtrace to AI thread exceptions (#6455)
Log game ID, player ID, round, and stack trace to stderr before
re-throwing, so AI thread crashes are diagnosable without a debugger.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:17:05 -07:00
62730414bd Add province action animations to Eagle strategic map (#6451)
* Add province action animations to Eagle strategic map

Play one-shot animations at province centers when action results arrive.
Starting with the Improve action, which shows a hammer-strike animation
with sparks. Sound effects loaded from sfx-combat Addressables by name.

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

* Fix hammer head alignment and restore rotation defaults

Offset tool position upward by half the tool size so the hammer head
(bottom of rotated image) aligns with the province center where sparks
appear. With Image+RectTransform the pivot is at center, unlike
SpriteRenderer which uses the sprite's imported pivot — without the
offset the middle of the hammer sat on the province.

Restore hammerBaseRotation=180 and hammerFlipHorizontal=true to match
ToolAnimator defaults.

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

* Set hammer rotation default to 90, fix sound loading robustness

Change hammerBaseRotation default to 90 to match tested working value.

Sound effects were silently failing — the Addressables coroutine started
in Awake() could be interrupted if the GameObject was deactivated during
scene setup. Now uses lazy-load pattern: retries loading on first play
attempt if clips aren't ready. Added diagnostic logging for load
success/failure and missing clip names.

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

* Remove defensive null checks on inspector fields

Let missing inspector wiring throw NullReferenceException immediately
rather than silently skipping. This was hiding the sound bug — the old
guard clause bailed before any logging could fire.

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

* Fix sound loading: move coroutine to OnEnable, remove silent null guard

The LoadSoundEffects coroutine started in Awake() was being killed when
the GameObject gets deactivated during scene setup. Moving it to
OnEnable() ensures it retries on reactivation. Also removes the
_loadedClips null guard so failures are visible via NullReferenceException
rather than silently skipping sound playback.

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

* Play metal strike sound per hammer impact, add to Addressables

Switch from repair sound to Metal Weapon Hit Stone 2_1 for Improve
animation. Sound now plays once per hammer strike at impact rather
than once at the start of the animation. Added the clip to the
sfx-combat Addressables group.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:15:48 -07:00
5cd5163c79 Make meteor targeting free (0 AP) to fix re-targeting (#6454)
PR #6450 allowed meteor re-targeting, but it fails at runtime because
the initial target uses ActionCost::usesAll which drains all AP to 0,
leaving nothing for the re-target. Setting the target cost to 0 fixes
this: usesAll with minimum 0 always succeeds (0 >= 0), still drains
remaining AP (ending the mage's turn), and removes the vigor penalty.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:50:11 -07:00
ed35d00c60 Fix Eagle Appears tutorial event to match normal game faction setup (#6448)
Previously province 6 (Soria) had battalions but no heroes, and province
stats were hardcoded only for province 32. Now The Eagle's faction matches
the normal game: Tarn defects from faction 2, random vassals are generated
(5 for province 32, 4 for province 6), per-province stats are correct,
faction is hostile to Bregos with trust -100, and battalion names use
"Tarn's" prefix for province 6.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:43:04 -07:00
8772b5a988 Fix validation error when non-allied armies converge on unoccupied province (#6452)
The validateAtMostOneAttackingAlliance check was firing during
UncontestedConquest phase, before PerformUncontestedConquestAction could
resolve the situation (largest army conquers). Skip the validation during
UncontestedConquest, matching the existing AttackDecision exemption.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:41:09 -07:00
fa1f0ffcb0 Replace hardcoded IsTester with is_admin from UserInfo proto (#6449)
Add is_admin field to UserInfo proto and populate it through Go auth
handlers, Scala fallback handler, and C# client storage. Replace the
hardcoded display name check with the server-provided admin flag.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:25:49 -07:00
05cb22dcd7 Allow meteor re-targeting after initial target selection (#6450)
Previously, once a mage selected a meteor target, the command was
locked in with no way to correct a misclick. Now the target/cancel
commands remain available after targeting, but as optional (not
required to end turn), so the player can re-target, cancel, or
simply end their turn keeping the current target.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:23:58 -07:00
adminandGitHub 60203343ab Tutorial tuning: boost Luke's faction bias, add Hedrick prestige penalty (#6447) 2026-03-08 22:08:53 -07:00
adminandGitHub 072749c63f Add persistent meteor targeting beam effect (#6446) 2026-03-08 22:07:49 -07:00
e850ba7546 Trim two-stage animation doc to just the implementation pattern (#6445)
All two-stage actions now have distinct success/failure animations.
Remove the completed status tracking table and animation descriptions,
keeping only the 7-step wiring guide for adding new two-stage actions.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:39:27 -07:00
f2ff4cc912 Add distinct success/failure animations for BraveWater (#6443)
* Add distinct success/failure animations for BraveWater

Split the shared BraveWater animation into two-stage success/failure variants:
- Success: Strong upward splash with bright droplets, expanding ripples, blue-white flash
- Failure: Droplets rise partway then fall back, darkening color, foam churns turbulently

Updates ShardokGameController enum, mapping methods, and dispatch.
Adds AnimateBraveWaterSuccess/AnimateBraveWaterFailed to WaterEffectAnimator.

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

* Add BraveWater success/failed test buttons to AnimationTestController

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

* Use distinct splash sound for BraveWater success

Attempt uses braved_water (wading in), success now uses splash
(satisfying water crossing) so the two phases sound different.

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

* Make BraveWater failure animation more dramatic and violent

Rewrote AnimateBraveWaterFailedEffect with 4 phases: high promising rise
(14 large particles with wide spread), brief stall with shuddering and
color flickering at peak, violent cubic-acceleration crash back down past
center with particles growing on impact, and aggressive turbulent churn
with large oscillations darkening to murky water.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:36:26 -07:00
4e84dbc4a4 Add distinct success/failure animations for DismissUnit (#6442)
* Add distinct success/failure animations for DismissUnit

Split the shared DismissUnit animation into two-stage success/failure variants:
- Success: Golden particles rise upward with warm golden glow pulse
- Failure: Particles expand then snap back inward, turning red with rejection flash

Updates ShardokGameController enum, mapping methods, and dispatch.
Adds AnimateDismissSuccess/AnimateDismissFailed to DismissAnimator.

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

* Add DismissUnit success/failed test buttons to AnimationTestController

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

* Double the spread width of DismissUnit success and failure effects

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

* Use undead_break_control sound for DismissUnit failure

The undead have broken free — use the dramatic control-broken sound
instead of the generic failure horn.

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

* Scale up DismissUnit effects: attempt 50% wider/taller, particles 2x

Attempt: particle spread multiplied by 1.5x, rise height 1.5x.
Success and failure: particle sizes doubled (3-6 to 6-12, 3-5 to 6-10).

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

* Fix attempt particles: use visible sizes (4-8) instead of near-zero (0-4)

The original Random.Range(4f, 0f) produced values 0-4 with many near
zero, making particles invisible. Now uses 4-8 for consistently visible
particles that shrink to zero as they drift.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:25:04 -07:00
f040b4df3a Add distinct success/failure animations for RaiseDead (#6441)
* Add distinct success/failure animations for RaiseDead

Split the shared RaiseDead animation into two-stage success/failure variants:
- Success: More figures rise quickly with bright green glow and pulse
- Failure: Figures rise partway then collapse back, glow flickers green to grey

Updates ShardokGameController enum, mapping methods, and dispatch.
Adds AnimateRaiseDeadSuccess/AnimateRaiseDeadFailed to RaiseDeadAnimator.

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

* Add RaiseDead success/failed test buttons to AnimationTestController

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

* Use distinct success sound for RaiseDead (undead_grew instead of raise_undead)

Attempt uses raise_undead (eerie summoning), success now uses
undead_grew (undead power surge) so the two phases sound different.

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

* Make RaiseDead failure more dramatic and use impactful success sound

Failure: figures now rise 75% of the way (was 40%), fully visible at
near-full opacity, stall with flickering glow shifting green to grey,
then get yanked back down with cubic acceleration. Much more visible
contrast between "almost worked" and sudden collapse.

Success sound: use holy_wave_damage for a darker, more impactful surge
instead of undead_grew.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 21:01:21 -07:00
cab6883c66 Add distinct Scout success/failure animations (#6440)
* Add distinct Scout success/failure animations

Success: cone fully extended, glow pulses bright and expands at target.
Failure: cone extends partway, hits a dark barrier with red flash,
cone recoils, eye dims and shrinks to nothing.

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

* Add Scout success/failed test buttons to AnimationTestController

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

* Use boo sound for Scout failure instead of generic horn

Scout failure plays "boo" — a disappointed reaction when the scout
can't see through the barrier.

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

* Rework Scout failure animation as dark reversal of attempt

Replace the red-barrier-and-recoil failure animation with a reversal:
glow disk at target turns dark, then cone and glow retract back toward
the source eye, which darkens and shrinks away. Also change failure
sound from boo to generic negative effect horn.

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

* Remove leftover merge conflict marker from TWO_STAGE_ANIMATIONS.md

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:55:08 -07:00
732ffb2aa8 Move AnimationTestController to Right Sidebar for better visibility (#6444)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:50:01 -07:00
79a64e2be7 Add distinct FreezeWater success/failure animations (#6439)
* Add distinct FreezeWater success/failure animations

Success: crystals solidify with bright white flash and intense shimmer.
Failure: crystals form then crack, flicker, and shatter outward as
spinning shards fading from icy blue to dull grey.

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

* Add FreezeWater success/failed test buttons to AnimationTestController

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

* Use splash sound for FreezeWater failure instead of generic horn

Ice shatters and reverts to water — splash conveys the ice losing.

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

* Make freeze success 30% bigger in both spread and crystal scale

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:25:21 -07:00
d562266044 Add distinct ExtinguishFire success/failure animations (#6438)
* Add distinct ExtinguishFire success/failure animations

Success: heavy water deluge with thick rising steam cloud.
Failure: droplets evaporate mid-fall, fire flares back with
orange/red burst.

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

* Add ExtinguishFire success/failed test buttons to AnimationTestController

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

* Make ExtinguishFire failure more dramatic with fire flare-up

When extinguish fails, also trigger FireEffectAnimator.AnimateFireSuccess
so the fire blazes back up with tall flickering flames and rising embers
alongside the evaporating water droplets.

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

* Use distinct sounds for ExtinguishFire attempt/success/failure

- Attempt: splash (water thrown at fire)
- Success: fire_extinguish (satisfying sizzle/hiss)
- Failure: raging_fire (fire flares back up)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:11:39 -07:00
11430be186 Filter destroyed battalion IDs from aftermath claimants and update doc (#6437)
Captured units' battalions are destroyed during BattleEnded processing,
but the multi-victor branch was storing those destroyed IDs in
AftermathClaimantUnit. This caused invalid battalion references when
claimants withdrew. Filter them out when building claimants and
notFledDefenders, and exclude them from armySize calculation.

Also update ALLIED_VICTORY_BATTLE_RESOLUTION.md to reflect PR 6429
changes (LastAllianceStanding for attackers, allied co-attacker added
to winners for solo castle holder) and document the dead-ally
GameOverResponsePopulator bug fixed in PR 6435.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:15:35 -07:00
57703ffbda Fix honey badger red stripes: remove shader replacement for 3D models (#6434)
* Remove ClipRectMeshUnlit shader replacement for 3D beast models

The shader replacement multiplied texture color by vertex colors, turning
honey badger white stripes red. RendererViewportClipper already handles
viewport clipping for all 3D models generically, making the shader
approach redundant and harmful.

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

* Set render queue on beast models to render above province texture

The old ClipRectMeshUnlit shader used Queue=Transparent+100 and
ZTest Always to draw above the province colour layer. Now that models
keep their original shaders, set mat.renderQueue = 3100 in
RendererViewportClipper.Awake() to match.

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

* Fix spelling: colour -> color

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:08:31 -07:00
dad8c9ebe7 Remove ally_victory and draw from Shardok victory_condition proto (#6436)
Reserve removed fields (ally_victory=2, draw=3) and delete the
DrawType enum to match the Eagle-side proto cleanup. Update C++
conversion code: ALLY_VICTORY now maps to victory, DRAW now throws.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:07:25 -07:00
13ecf9cd1a Fix dead-ally throw in GameOverResponsePopulator (#6435)
When your alliance wins a battle but your own units were destroyed,
you should still get a victory — not an internal error. Change the
else-if branch from throwing to assigning victory for allied
non-winners.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 13:24:38 -07:00
beabcede11 Fix Shardok tooltip positioning for Screen Space Camera canvas (#6433)
The buttonTooltip and oddsPanel were setting transform.position/localPosition
using screen-space coordinates directly, which placed them incorrectly when
the canvas uses Screen Space Camera mode. Convert screen positions to canvas
world space via ScreenPointToWorldPointInRectangle.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:50:16 -07:00
2b54f4aa7c Add raw game history fallback to admin server for broken games (#6432)
When GetGameHistory returns a non-empty error field (game failed to load),
the admin server now transparently falls back to GetRawGameHistory. The UI
shows a warning banner and uses raw-rewind instead of normal rewind. This
lets admins view and fix broken games without any manual switching.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:48:12 -07:00
b292644f76 Fix allied attacker victory conditions (#6429)
* Fix allied attacker victory conditions

Allied attackers couldn't win by elimination because LastAllianceStanding
wasn't in their victory conditions. When one attacker held all castles,
the ally was treated as a loser because they weren't in winning_shardok_ids.

- Add LastAllianceStanding to attacker victory conditions in RequestBattlesAction
- Add mutually-allied co-attackers to winning_shardok_ids when one player holds all castles
- Add tests for both fixes

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

* Extract PopulateGameOverResponse into testable library and add tests

Move PopulateGameOverResponse and its helpers (IncludeUnitProtoInReturn,
FromUnitFb, FromInternalStatus) from EagleInterfaceGrpcServer.cpp into a
separate GameOverResponsePopulator library so they can be unit tested
directly. Add 7 tests covering victory/loss assignment, allied player
validation, unit filtering, and status conversion.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:47:35 -07:00
528335c8d9 Remove AllyVictory from Eagle battle resolution (#6431)
Shardok now emits Victory for all winners instead of distinguishing
AllyVictory. Remove the AllyVictory case from EndGameCondition, simplify
all isWinOrAllyVictory checks to isVictory, reserve the ally_victory
proto field, and update the allied victory documentation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:26:26 -07:00
4dbd6279cd Add GetRawGameHistory and RawRewindGame admin RPCs for broken games (#6430)
When a game's action history contains a broken action result, the game
can't load because formAwrs throws during state replay. This means the
admin console can't view history or rewind to fix it.

These two new RPCs operate directly on persisted chunk files, bypassing
the formAwrs state-replay pipeline:
- GetRawGameHistory: reads ActionResult protos from .e0a chunks and
  returns them as JSON without replaying game state
- RawRewindGame: truncates chunk files to a target action count without
  loading the game into memory

Also adds an error field to GetGameHistoryResponse so load failures are
reported instead of returning empty results.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:24:34 -07:00
ce18908688 Remove draw handling from EagleInterface game-over conversion (#6427)
PR #6425 removed DrawType from the Eagle common proto but didn't
update the C++ conversion code in EagleInterfaceGrpcServer, causing
a linux-aarch64 cross-compile failure.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 08:36:05 -07:00
fd89f9e059 Validate WIN_AFTER_MAX_ROUNDS at game setup and remove DRAW codepath (#6426)
Every battle must have exactly one player with WIN_AFTER_MAX_ROUNDS.
This adds startup validation in StartGame and replaces the unreachable
DRAW result with a ShardokInternalErrorException.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 08:07:25 -07:00
8602f1cf72 Remove Draw from battle resolution and add WinAfterMaxRounds validation (#6425)
Draws are dead code left over from removed Free For All battles. Shardok
battles always have exactly one defender with WinAfterMaxRounds, so if
max rounds is exceeded the defender wins — a draw is never produced.

- Remove DrawType enum and Draw case from EndGameCondition
- Remove isDraw method and all isDraw checks in unitReturned
- Remove Draw proto conversion code from ShardokBattleConverter
- Remove DrawType from victory_condition.proto (Eagle common only)
- Add internalRequire validation that exactly 1 player has
  WinAfterMaxRounds when building shardokPlayers

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 08:05:20 -07:00
43bb0bcf74 Fix tooltip positioning for Screen Space Camera canvas (#6421)
* Fix tooltip positioning for Screen Space Camera canvas

HoveringTooltip.SetPosition() was mixing world-space and screen-space
coordinates. With Screen Space Camera, GetWorldCorners returns world
coordinates (not screen pixels), and the tooltip was placed at the
wrong position. Now routes all positioning through screen space using
RectTransformUtility, with the correct canvas plane z for projection.

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

* Use world-space positioning instead of screen-space roundtrip

Work directly in world space using lossyScale for offsets and
canvas GetWorldCorners for overflow, avoiding broken coordinate
space conversions.

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

* Convert tooltip providers to pass screen-space Rects

The camera looks downward, so GetWorldCorners returns points where
the visual "height" is along z, not y. A 2D Rect from world coords
loses the z axis entirely (height=0). Fix by converting world corners
to screen space in the providers via WorldToScreenPoint, then
converting back to canvas world space in HoveringTooltip via
ScreenPointToWorldPointInRectangle for final placement.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 08:02:54 -07:00
36e61da168 Remove auto-create first game logic from lobby (#6424)
Players with no active games were being automatically thrown into a
new 7-faction game. Remove this behavior so they always land in the
lobby and can choose what to do.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 07:59:12 -07:00
4bdade4744 Fix allied battle victory: treat AllyVictory as winner in ResolveBattleAction (#6423)
* Fix allied battle victory: treat AllyVictory as winner in ResolveBattleAction

The multi-victor battle aftermath code (added in #6411) was dead code because
the winner/loser partition used `isVictory` which excludes `AllyVictory`.
Allied winners were classified as losers, so only one faction ever "won"
and the province was awarded immediately without a claim decision.

Changes:
- Add `isWinOrAllyVictory` to EndGameCondition
- Use it for the winner partition, backstory, and quest fulfillment
- Fix `unitReturned` so AllyVictory heroes stay at the battle province
  as claimants instead of being sent home

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

* Update tests to expect multi-winner behavior for allied victories

Tests previously expected AllyVictory units to be sent home. With
the partition fix, allied winners now stay as claimants for the
BattleAftermath claim decision.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 07:44:30 -07:00
42dfd143ea Fix bounced armies not processed by WithdrawnArmiesReturnHomeAction (#6422)
The auto-bounce results set hostile armies to Withdrawing status, but
WithdrawnArmiesReturnHomeAction received the original provinces where
those armies were still AwaitingDecision. This caused a validation
error when transitioning to DefenseDecision because non-allied factions
remained in hostileArmies. Apply bounce status changes to the province
list before passing to WithdrawnArmiesReturnHomeAction so it properly
removes the bounced armies.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:33:18 -08:00
db77a33003 Fix bounce for non-allied co-attackers when no army advanced (#6420)
When multiple non-allied factions attack the same occupied province and
none makes an AttackDecision, they all remain AwaitingDecision. The
existing auto-bounce logic only triggers when an army has Attacking
status. Add a new branch that detects non-allied undecided factions and
bounces all of them to Withdrawing, preventing the
validateAtMostOneAttackingAlliance runtime error.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:07:16 -08:00
468c863a63 Fix aftermath supply caps, auto-keep last claimant, and persist PendingConquestInfo (#6417)
Three correctness fixes for the battle aftermath decision system:
- Cap withdrawal gold/food at what each faction brought into battle (broughtGold/broughtFood)
- Auto-keep last undecided claimant when nobody has kept yet (prevents broken province state)
- Serialize PendingConquestInfo to proto so server restarts during BattleAftermath don't lose state

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:15:24 -08:00
865fe2c58d Fix Royal Lancers HEAVY_CAVALRY size exceeding capacity (800 → 600) (#6419)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:14:57 -08:00
7f01067d4c Fix duplicate province labels on map zoom (#6418)
Destroy previous label container before creating new ones when
OnMapLoaded fires multiple times. Add OnDestroy to unsubscribe
from the event.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:14:41 -08:00
b3d494d820 Fix battle aftermath finalization and hero-battalion pairing bugs (#6416)
Add FinalizeAftermathAction to handle the all-decided case (run
ProvinceConqueredAction for keeper, create withdrawal armies, clear
pendingConquestInfo), fix hero-battalion pairing by replacing separate
heroIds/battalionIds vectors with paired AftermathClaimantUnit, and
remove dead destroyedBattalions field from MultiVictorBattleSetupAction.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 16:41:15 -08:00
73bc28e13a Add BattleAftermathDecisionCommandSelector for Unity client (#6413)
* Add BattleAftermathDecisionCommandSelector for Unity client

Adds the UI component for the battle aftermath decision system. When
allied factions jointly conquer a province, each winning faction chooses
to Keep Province or Withdraw (with destination and supply sliders).

The selector follows the AttackDecisionCommandSelector pattern with
toggle group, province dropdown, and gold/food sliders. It is inert
until the server command infrastructure sends the corresponding
available command.

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

* Add missing EagleGUIUtils using for GUIUtils.DarkColoredProvinceName

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

* Wire up BattleAftermathDecisionCommandSelector in Gameplay scene

Add the command selector as a child of CommandPanelController with
all Inspector fields connected: toggles, toggle group, withdraw
container, destination dropdown, gold/food sliders and labels, info
text, and button image. Unity events wired for ToggleChanged,
GoldSliderChanged, and FoodSliderChanged.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 16:09:30 -08:00
a22041f975 Add battle aftermath decision command infrastructure (#6415)
Wire up the full command pipeline for battle aftermath decisions so
winning allied factions can choose Keep Province or Withdraw after a
multi-victor assault.

- Add proto messages for available/selected command (field 41) and command type
- Add Scala model types: CommandType, AvailableCommand, SelectedCommand cases
- Add proto converters for all new command types
- Add AvailableBattleAftermathDecisionCommandFactory (sequential by army size)
- Add BattleAftermathDecisionCommand (keep triggers conquest, withdraw creates army)
- Add AutoResolveBattleAftermathAction (last claimant auto-keeps)
- Add BattleAftermathDecisionCommandChooser for AI (always keeps when possible)
- Update AvailableCommandsFactory and RoundPhaseAdvancer for aftermath phase
- Update CommandFactory routing and AIClient integration

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 16:02:14 -08:00
7c6bff4464 Remove Map Editor scene from build (#6414)
* Remove Map Editor scene from build to eliminate duplicated hex tile assets

The Map Editor scene directly references hex tile textures via RawImage
components, pulling ~4.6 MB of textures into the player build that are
already served via Addressables from CDN.

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

* Remove Map Editor button from connection screen

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

* Remove EditorButtonClicked and unused SceneManagement import

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

* Delete Map Editor scene and MapEditorController

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 15:58:09 -08:00
81e7aa6d34 Show animation tests toggle only in Unity Editor (#6412)
Enable the toggle GameObject in the scene but hide it at runtime
via Application.isEditor, so it only appears in the settings panel
when running inside the Unity Editor. The checked state still comes
from PlayerPrefs as before.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 15:38:14 -08:00
859087f1bb Add multi-victor battle state model and ResolveBattleAction branch (#6411)
When multiple allied attackers win a province assault, defer province
assignment by storing PendingConquestInfo on the province instead of
immediately running ProvinceConqueredAction. This lays the groundwork
for the battle aftermath decision command (next PR).

- Add PendingConquestInfo, AftermathClaimant, and AftermathDecision types
- Add pendingConquestInfo field to ProvinceT/ProvinceC/ChangedProvinceC
- Branch ResolveBattleAction for multi-victor case via MultiVictorBattleSetupAction
- Add ActionResultType values for aftermath actions
- Update proto converters to handle new province field
- Remove unused validate method from ResolvedEagleUnit (breaks dep cycle)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 15:37:47 -08:00
0f96a7bfdf Add distinct success/failure animations for Repair (#6410)
* Add distinct success/failure animations for Repair

Repair previously used the same hammer-strike animation for both attempt
and result. Now it follows the StartFire/Fear two-stage pattern: attempt
shows hammer strikes, success shows a golden shimmer beam rising, and
failure shows debris collapsing with a dust puff.

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

* Increase two-stage animation delay to let attempt animations finish

The delay cap between attempt and result phases was 0.5s (or 0.3s with
no sound), but the hammer animation runs ~0.6s and fire runs ~0.8s.
Raised the cap to 0.8s and the no-sound fallback to 0.6s so result
animations don't overlap with attempt animations.

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

* Add distinct repair success sound and make debris explosive

Sound: Wire up a "repair_success" clip for the result sound so it
doesn't repeat the hammer attempt sound. Falls back to the hammer
clip until the audio asset is added to sfx-combat.

Debris: Replace gentle falling animation with a violent explosion —
pieces burst outward from center with physics-driven trajectories
(initial velocity + gravity), fast spin, an initial flash burst,
and a drifting dust cloud.

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

* Use "Positive Effect 6" as repair success sound

Add the clip to the sfx-combat addressable group and load it as the
repair success result sound so it plays a distinct chime instead of
repeating the hammer attempt sound.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 15:33:10 -08:00
b5ec52ea44 Add allied castle victory: allies collectively holding all castles triggers win (#6409)
When multiple allied players each occupy different critical tiles (castles)
such that all castles are covered, this now triggers a HOLDS_CRITICAL_TILES
victory for all occupants — provided they all have the victory condition set
and are mutually allied. Previously only a single player holding all castles
could trigger this win condition.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 15:25:38 -08:00
5a4f65b416 Add distinct success/failure animations for StartFire (#6408)
* Add distinct success/failure animations for StartFire

Split StartFire into three-stage visuals following the Fear pattern:
attempt shows ignition, success shows fire blazing up (taller/brighter
flames, hotter colors, outward burst), failure shows fire dying out
(shrinking flames, cooler colors, smoke puff).

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

* Move StartFire doc to repo-root docs/TWO_STAGE_ANIMATIONS.md

Update the existing doc instead of creating a duplicate in the Unity
client directory.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 14:26:13 -08:00
a1c00e45c2 Use client_id to deduplicate same-device connections on the server (#6407)
Thread client_id from StreamGameRequest through EagleServiceImpl →
GamesManager → GameController → HumanPlayerClientConnectionState.
Update withHumanClient eviction logic to always evict connections with
the same client_id (same device reconnecting/refreshing), while keeping
connections from different client_ids alive (multi-device support).
Cancelled connections for the same faction are still cleaned up.

Changed client_id type from int64 to string for future extensibility
(e.g. embedding device name, platform, or version).

This fixes duplicate updates when a single client calls
StreamOneGameAsync for a refresh on the same gRPC stream, which caused
the "Duplicate unaffiliated hero" crash.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 08:31:04 -08:00
543cd02e51 Add client_id field to StreamGameRequest proto and populate in C# client (#6406)
Add a stable string client_id to StreamGameRequest so the server can
distinguish same-device reconnects from multi-device connections. The
C# client generates a GUID per PersistentClientConnection instance and
sends it with every StreamOneGameAsync request. The server currently
ignores this field; server-side eviction logic follows in a subsequent
PR. Using string instead of int64 for future extensibility (e.g.
embedding device name, platform, or version).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 08:25:44 -08:00
3eac386757 Throw on duplicate unaffiliated hero and fix table crash (#6405)
Guard UpdateUnaffiliatedHeroSelections against count mismatch by
rebuilding the table when the model changes between rebuilds.
Keep the throw on server-side duplicate as a safety net.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 07:53:45 -08:00
407d7701e8 Add post-Eagle tutorial events: Ranil & Elena depart and form factions (#6365)
* Add post-Eagle tutorial events: Ranil & Elena depart and form factions

After the Eagle appears, John Ranil departs the player's faction 2 rounds
later and Elena Fyar departs 4 rounds later. At 7 rounds after Eagle,
both form their own factions in isolated provinces.

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

* Add tests for TutorialHeroDepartureAction and TutorialHeroFactionsAction

Tests cover action result creation, province selection, hero changes,
battalion/faction creation, unaffiliated hero removal, and edge cases
(missing heroes, no suitable province, hero in different province).

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

* Fix Eagle hero missing backstoryVersions causing validation failure

EagleAppearsAction.createEagleHero was creating the hero without
setting backstoryVersions, which defaults to Vector(). The runtime
validator requires backstoryVersions.nonEmpty for all heroes.

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

* Fix Eagle appearance crash: split entity creation from province changes

The action result applier processes changedProvinces before newHeroes,
so when EagleAppearsAction put both in a single ActionResultC, the
province change tried to look up the Eagle hero (via
ProvinceUpdateHelpers.applyRulingAndBattalions) before it existed in
the game state, causing a HashMap key-not-found exception.

Split into two sequential action results: first creates the faction,
hero, and battalions; second applies the province changes.

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

* Fix duplicate Eagle hero: only place in province 32, not both provinces

The Eagle hero was added to rulingFactionHeroIds for both provinces 32
and 6, violating the one-hero-per-province invariant and causing a
validation crash on game load. Province 6 now gets the Eagle's faction
and battalions but not the hero itself.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 21:31:39 -08:00
cc49924af8 Throw on duplicate unaffiliated heroes instead of silently appending (#6402) (#6403)
Replace blind `Add(AddedUnaffiliatedHeroes)` with per-hero loop that
throws InvalidOperationException when a hero already exists in the
province's unaffiliated list.  This surfaces the root cause of duplicate
rows in the free heroes table instead of masking it.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 21:06:24 -08:00
f79b9d61f5 Fix multi-client eviction: allow simultaneous connections per faction (#6402)
When two clients connected for the same faction (e.g., iPad + Unity
editor), withHumanClient evicted all existing same-faction connections.
Now only cancelled connections are removed, allowing multiple active
clients to coexist with independent update streams.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 18:34:04 -08:00
a46dc40198 Fix province effects missing after CDN centroids change (#6401)
* Fix province effects missing when CDN centroids arrive after model

Since #6396 moved centroids.json to CDN, it loads asynchronously and
often arrives after MapController.Model is set. All province effect
controllers (festival, epidemic, blizzard, drought, flood, beasts)
silently skipped spawning because _provinceCentroids was empty.

Re-apply effects in OnProvinceMapLoaded when the model is already set.

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

* Fix province effects missing when CDN centroids arrive after model

Since #6396 moved centroids.json to CDN, it loads asynchronously and
often arrives after MapController.Model is set. All province effect
controllers silently skipped spawning because _provinceCentroids was
empty.

Add lazy centroid loading to each controller's update method so they
load centroids on-demand from ProvinceIDLoader.CentroidsJsonText. This
eliminates the callback ordering dependency with OnMapLoaded. Also
re-apply effects in OnProvinceMapLoaded when model is already set.

Remove defensive null checks on Inspector-wired controller references
in UpdateProvinceEffects — missing wiring should fail loudly.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:21:19 -08:00
b93171528c Randomize firework burst colors instead of cycling sequentially (#6400)
Sequential _colorIndex caused all firework instances to show correlated
color sequences. Use Random.Range per launch for independent colors.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:02:47 -08:00
1508fce835 Faster connection recovery on flaky networks (#6399)
Reduce sync mismatch grace period (60s→5s), HTTP/2 keepalive interval
(15s→5s), and add per-command response timeout (10s) to dramatically
cut recovery time when the client misses a game update.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 15:55:22 -08:00
52cd8397c2 Make games.e0es S3 upload non-blocking with AsyncS3Persister (#6398)
GamesManager.save() writes games.e0es to S3 synchronously on the gRPC
executor thread via CompletableFuture.join(), blocking all user
operations for the duration of the upload. JFR profiling showed this
blocking for 28-65ms per command, with potential for much longer spikes.

Wrap the top-level S3Persister in AsyncS3Persister, matching what
per-game persisters already do in LocalGamePersisterCreation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 15:54:21 -08:00
fd75833208 Use API key auth for iOS export to prevent Xcode-Token expiry failures (#6397)
The exportArchive step was relying on the Xcode-Token in the keychain
for App Store Connect authentication. This token expires periodically,
breaking headless CI builds. Pass the App Store Connect API key (already
used by the upload step) to the export step as well.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 15:17:14 -08:00
8aa3be6401 Fetch centroids.json from CDN via EagleMapInfo (#6396)
* Fetch centroids.json from CDN via EagleMapInfo instead of baked TextAsset

ProvinceIDLoader now fetches both the map data and centroids JSON from
CDN using SHA256 hashes from the server-provided EagleMapInfo. OnMapLoaded
fires only after both arrive and validate. All controllers subscribe to
OnMapLoaded for centroid data instead of loading in Awake().

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

* Guard MapController.ProvinceFromPoint against null map bytes

OnMapLoaded now fires later (after both map + centroids arrive),
so Update() can run before _mapIdBytes is set.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 14:27:56 -08:00
192aaf73c6 Remove unused map_name from EagleMapInfo (#6395)
The SHA256 hash is used as the content-addressable filename for CDN
fetches, making map_name redundant. Reserve field 1 in the proto to
prevent accidental reuse.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 14:27:31 -08:00
026d962ca6 Add centroids SHA256 to EagleMapInfo for CDN validation (#6394)
Extends EagleMapInfo with centroidsSha256 so the client can validate
centroids.json after CDN download, matching the existing rawGray pattern.
Bumps migration to v3 so existing saves get backfilled.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 14:13:33 -08:00
100700582e Centralize centroidsJson in ProvinceIDLoader (#6393)
* Centralize centroidsJson reference in ProvinceIDLoader

All 7 province controllers now read centroidsJson from ProvinceIDLoader
instead of each having their own Inspector-linked TextAsset field.
This prepares for making centroids server-driven in the future.

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

* Wire up provinceIDLoader references and remove stale centroidsJson links

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 14:12:07 -08:00
ef683e939b Move rawGray.gz.bytes from Unity Assets to src/main/resources (#6392)
The province ID map is now fetched from CDN at runtime, so it no longer
needs to be a Unity TextAsset. Move it to the resources directory
alongside other game data files and delete the .meta file.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:59:37 -08:00
bd38b4ad5b Load province map from server-provided EagleMapInfo (#6388)
* Load province map dimensions and hash from server-provided EagleMapInfo

Replaces hardcoded map dimensions (3786x1834) across 8 Unity client files
with server-driven values from the EagleMapInfo proto added in #6381.

ProvinceIDLoader no longer auto-loads in Awake() — instead, EagleGameController
calls Initialize(EagleMapInfo) on first GameStateView, which looks up the map
asset by name, validates SHA256 integrity, and fires OnMapLoaded for dependents
(MapController, ProvinceBorderDistanceGenerator).

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

* Keep rawGrayCompressed as direct Inspector field instead of map lookup

The server provides dimensions and SHA256 but the client only has one
map asset — no need for a name-based lookup table.

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

* Fetch province map from CDN instead of bundled TextAsset

ProvinceIDLoader now uses ResourceFetcher.mapFetcher to download the
map data at runtime rather than reading a baked-in TextAsset. The server
provides the map name, dimensions, and SHA256 via EagleMapInfo.

Also fixes:
- Duplicate `using Net.Eagle0.Eagle.Common` in EagleGameController
- ProvinceLabelsController timing: defers CreateLabels to OnMapLoaded
  to avoid division by zero when mapWidth/mapHeight are still 0

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

* Use eagle0-assets CDN for map fetcher instead of headshots CDN

Make ResourceFetcher base URI an instance field so each fetcher can
point at a different CDN. Map data is at:
https://eagle0-assets.sfo3.digitaloceanspaces.com/strategic-maps/

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

* Use SHA256 as CDN fetch path instead of map_name

Content-addressable: the SHA256 hash serves as both the CDN filename
and the integrity check, so map_name is not needed for fetching.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:54:08 -08:00
5eba718632 Update eagle map hash and make migration read from config (#6391)
* new sha

* Update EagleMapInfoMigration to read from game_parameters.json

Replace hardcoded map info with GameParametersUtils.defaultExpandedGameParameters
so the migration stays in sync with the config file. Bump version to 2 to
re-migrate existing saved games with the new map hash.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:43:27 -08:00
e1babbda41 Add error diagnostics to warmup tool for server-side failures (#6390)
When Eagle returns an error during command processing (e.g. battalion
over-capacity validation), the warmup tool now logs the server error
message and dumps its full state (game ID, province, hero, token,
command) instead of silently timing out.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:08:51 -08:00
e0dc941799 Update Gameplay scene: clean up stale serialized fields and adjust UI layout (#6389)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:08:15 -08:00
9aec075f51 Add smooth_boundaries.py for natural province boundary smoothing (#6382)
* Add smooth_boundaries.py for natural province boundary smoothing

Post-processing tool for rawGray.gz.bytes that replaces jagged
province boundaries with smooth, natural-looking ones using:
1. Majority-filter smoothing (iterative mode filter on boundary pixels)
2. Fragment cleanup (BFS expansion preserving ocean-separated islands)
3. Domain warping (Gaussian displacement for organic character)

Includes automated verification (province preservation, neighbor
adjacency, connectivity) and before/after visualization output.

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

* Apply boundary smoothing to province map

Run smooth_boundaries.py --seed 42 to smooth jagged province boundaries.
Uses pixel-based adjacency instead of TSV for neighbor verification.
Updates centroids.json with new label positions.

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

* Add targeted boundary smoothing for West Faluria borders

Adds --targeted-smooth mode to smooth_boundaries.py that applies a
bilateral majority filter to specific province border pairs. Smooths
the 40-37 (West Faluria/Yuetia) and 40-11 (West Faluria/Garholtia)
boundaries to reduce bubble protrusions.

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

* Redraw West Faluria borders via manual edit with roughened edges

Hand-edited province boundaries for West Faluria (40) expanding into
Usvol (33) and Hofolen (17), then applied localized domain warp to
roughen the new borders for a natural look. Added rawgray_editor.py
for PNG export/import workflow and roughen_borders.py for localized
border roughening.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 12:05:18 -08:00
c461d5d04e Add git -C prohibition to CLAUDE.md (#6387)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 12:01:01 -08:00
087aeb3484 Add reusable game save migration system with EagleMapInfo backfill (#6385)
Old saved games predate the EagleMapInfo proto fields and will break
once the client stops hardcoding map info. This adds a migration
framework that patches saved game files at server startup, plus the
first migration (version 1) to backfill eagleMap on all existing games.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 11:26:40 -08:00
b3b57db0fa Move EagleMapInfo from hardcoded values to JSON game config via event sourcing (#6384)
EagleMapInfo (map name, dimensions, SHA256) was hardcoded in GameStateViewFilter.
Now it flows through the event-sourcing pipeline: JSON config → GameParameters proto
→ ActionResultC → ActionResultApplierImpl → GameState → GameStateViewFilter, matching
the existing gameType pattern. The proto definition moves from views/ to common/ so
both internal and views packages can reference it.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:25:13 -08:00
5317a3f8a2 Add EagleMapInfo to GameStateView proto and server (#6381)
Server now sends map metadata (name, dimensions, SHA256) to clients
via the EagleMapInfo field. Clients will initially ignore this unknown
field until a follow-up client PR adds CDN-based map fetching.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:09:15 -08:00
e5e636801c Fix stale Laufarvia-West Faluria neighbor entry in province_map.tsv (#6383)
Laufarvia (3) and West Faluria (40) are listed as neighbors in the TSV
but are 113 pixels apart on the actual map -- they haven't been adjacent
since an earlier map revision. Remove the stale adjacency from both
provinces' neighbor/neighborPositions/neighborNames fields.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:43:47 -08:00
e5d9dd00ca Centralize rawGray province ID map references to ProvinceIDLoader (#6379)
Weather effect controllers (flood, drought, blizzard) each independently
decompressed the same 6.9 MB rawGray texture. Replace with a shared
reference to ProvinceIDLoader, eliminating 3x duplicate decompression.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:09:25 -08:00
641f09fced Move combat sound effects to Addressables for CDN delivery (#6378)
* Move combat sound effects to Addressables for CDN delivery

All 41 SoundManager AudioClip serialized fields replaced with
Addressables loading via single "sfx-combat" label. Clips are loaded
asynchronously and matched by name to build the ActionType dictionary.
Sound effects gracefully degrade (no sound) if loading hasn't completed.

GauntletThrowAnimator.impactSound and WeatherEffectAnimator audio clips
retain their serialized Inspector references (separate from SoundManager).

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

* Route weather and gauntlet sounds through SoundManager

Move WeatherEffectAnimator's rain/thunder/blizzard audio clips and
GauntletThrowAnimator's impact sound to load via SoundManager instead
of serialized Inspector fields. This routes all game audio through
Addressables for CDN delivery.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 08:01:12 -08:00
7c27737fe9 Fix DivideByZeroException when hex tile Addressables return empty lists (#6377)
Some terrain labels may load successfully but return 0 textures (e.g.
when Addressable bundles haven't been built yet or CDN cache is stale).
Return null instead of crashing on images[random % 0].

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 07:12:57 -08:00
161eba96b7 Move tactical combat assets to Addressables for CDN delivery (#6376)
* Move tactical combat assets to Addressables for CDN delivery

Fire effect prefab, permanent bridge models (5), and constructed bridge
models (4) are now loaded via Addressables instead of serialized Inspector
fields. TacticalAssetLoader singleton pre-loads in EagleGameController.Start()
so assets are cached before the first battle. Empty arrays as defaults
provide graceful degradation if loading hasn't completed.

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

* Fix HexGrid NRE when cells not yet initialized, re-render on late load

HexGrid.Update() could NRE when cells array was null (grid not yet set
up due to async asset loading). Added null guard matching the pattern
used in all other HexGrid methods.

Also added LoadTacticalAssetsAndRefresh coroutine so bridges and fire
effects re-render if tactical assets finish loading after the initial
grid draw.

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

* Fix IndexOutOfRange when tactical assets load before model setup

The LoadTacticalAssetsAndRefresh coroutine called SetModifiers() when
Model was non-null but _randomNumberForCellIndex was still empty. Guard
on the list being populated; the normal model-update paths will call
SetModifiers() once setup completes.

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

* Remove SetModifiers() call from asset loading coroutine

The coroutine's SetModifiers() crashes because _randomNumberForCellIndex
is populated in row-order but MapCoordsToGridIndex flips rows, so the
list indices don't match. This was a latent bug exposed by async loading.

SetModifiers() is already called from ModelUpdated() on every model
update, so modifiers will render correctly without the coroutine call.

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

* Wait for Addressables to load before setting up hex grid

SetUpGame() called GetImageForTerrain() immediately, but after moving
hex tiles to Addressables the textures load asynchronously. In custom
battles the shardok container activates and SetUpGame runs on the same
frame, before textures are ready — crashing with NullReferenceException
and leaving no hex grid visible.

Fix: split SetUpGame into a sync preamble + SetUpGameAfterLoad coroutine
that waits for IsLoaded. Also change _randomNumberForCellIndex from List
to int[] indexed via MapCoordsToGridIndex so indices match SetModifiers.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 06:49:04 -08:00
24e4942d20 Move hex tile textures to Addressables for CDN delivery (#6375)
Move 118 hex tile PNGs from Assets/Resources/Hex Tiles to
Assets/Hex Tiles and register them as Addressables with 22
per-directory labels (hex-plains, hex-forest, hex-winter-hills,
etc.). This removes them from the app binary so they're hosted on
CDN and only redownloaded when content changes.

ImageForTerrainTracker is now a shared singleton that loads textures
via Addressables.LoadAssetsAsync instead of Resources.LoadAll. The
load kicks off in EagleGameController.Start() (strategic scene) so
textures are cached before the player's first tactical battle.
ShardokGameController and MapEditorController reuse the same instance
with a load guard that prevents double-loading.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 05:35:21 -08:00
84af6ceb61 Fix artifact retention-days to match repo maximum of 3 (#6374)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 21:41:13 -08:00
11c65ab063 Move beast effect prefabs to Addressables for CDN delivery (#6373)
Replace 33 serialized GameObject fields in ProvinceBeastsController with
Addressables.LoadAssetsAsync label-based loading ("beast-effects").
Prefabs stay in Assets/Eagle/Effects/ but are now delivered via CDN at
https://assets.eagle0.net/addressables/[BuildTarget] instead of being
bundled in the app binary. This removes ~80-100 MB of 3D models,
textures, and animations from the initial app download.

Loading strategy:
- Eager load in Start() (last priority — after music)
- Game state that arrives before loading completes is stashed and
  applied when ready
- If loading fails (offline, no cache), beasts simply don't render

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 19:56:54 -08:00
fcb8758762 Show Tutorial and Tutorial Lite buttons for testers on all platforms (#6372)
Previously the Tutorial button was gated to nolen/tarn but the Tutorial
Lite (skip-battle) button was editor-only. Now both buttons appear for
testers on any platform (iOS, macOS, etc.), and Tutorial Lite also
remains visible in the editor.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 16:59:40 -08:00
046daa08a9 Remove standalone iOS Addressables build workflow (#6371)
The nightly iOS TestFlight build already builds and uploads iOS
addressables as part of its pipeline. The standalone workflow added
unnecessary complexity and forced platform switches on the unity-mac
runner. Manual TestFlight dispatches cover any need for immediate
addressable updates.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 16:59:21 -08:00
faadd91ceb Remove UIApplicationSceneManifest from iOS plist, don't quit on iOS (#6369)
Two fixes for iOS deep link handling:

1. CI: Remove UIApplicationSceneManifest from the generated Info.plist
   during archive. Unity 6 adds this key, which opts the app into the
   scene-based lifecycle. iOS then routes deep links through
   UISceneDelegate instead of UIApplicationDelegate, but Unity doesn't
   implement that path, so deep link URLs are silently dropped.

2. OAuthManager: Don't call Application.Quit() on iOS — it's documented
   as having no effect. Instead, let the app go to background when the
   browser opens and handle the deep link callback when iOS brings it
   back via OnDeepLinkActivated.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 16:31:56 -08:00
3d45938d33 Fix Mac/Windows builds using wrong platform for Addressables (#6370)
BuildMacPlayer and BuildWindowsPlayer called BuildAddressables() without
first switching the active build target. On self-hosted runners where
Unity state persists between runs, this caused Addressables to be built
for whatever platform ran last (e.g. iOS), resulting in incompatible
bundles at runtime.

Extract SwitchBuildTarget helper from BuildiOSAddressables and call it
in all three build methods before building Addressables.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 16:31:41 -08:00
adminandGitHub b66659f3c7 Register eagle0:// URL scheme via PlayerSettings, remove post-processor (#6368) 2026-03-05 12:59:53 -08:00
aacecfe1cb Auto re-auth when stored OAuth token expires (#6367)
When a stored account's token expires and refresh fails, automatically
initiate a fresh OAuth login with the same provider instead of just
showing a brief error. On startup, show "Session expired" message
instead of silently clearing the status text.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 10:16:01 -08:00
1bdd888886 UI layout tweaks in Gameplay scene (#6364)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 16:26:29 -08:00
971e632c22 Delay departures for king's low-loyalty outer-province heroes in tutorial (#6363)
Set roundIdJoined=1 for heroes with per-hero loyalty overrides, pushing
their earliest possible departure back by one month. This gives the
player more time before The Tumbler, Aldric the Overlooked, and similar
low-loyalty heroes leave.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 13:41:23 -08:00
0575ae865c Add catch-all exception handling to SubscribeToGame (#6362)
SubscribeToGame only caught NewGameException, so any other exception
(e.g. file-not-found during map loading) propagated uncaught through
gRPC as a generic "UNKNOWN" error with no logging. Now matches the
PostCommand/PostPlacementCommands pattern: catches ShardokClient,
ShardokInternal, and std::exception with stderr logging and proper
gRPC status codes.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:25:37 -08:00
370a2af356 Throw on failed file open in byte_vector::FromPath (#6361)
Previously, FromPath silently returned garbage data when a file didn't
exist (tellg() returns -1, leading to std::bad_alloc from size_t(-1)).
Now throws std::runtime_error with the file path for clear diagnostics.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:24:52 -08:00
437d417a93 Have Ranil and Elena explain Improve/Alms in tutorial (#6359)
* Have Ranil and Elena explain Improve/Alms instead of Marek

Replace Marek's combined Improve/Give Alms tutorial step with two
separate steps: John Ranil explains province improvement (highlighting
the Improve button) and Elena Fyar explains giving alms (highlighting
the Alms button). Each step notes that any hero can use the command
but the specialist gets a bonus.

Register each command button as a dynamic tutorial target in
CommandButtonPanelController so individual buttons can be highlighted.
Target IDs are derived from the button tooltip (e.g. "ImproveProvinceButton",
"GiveAlmsButton").

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

* Fix speaker portraits, highlight visibility, and notification timing

- Resolve speaker headshots from the Eagle model (strategic map) when
  the Shardok model is unavailable, fixing blank portraits for Ranil
  and Elena in post-battle dialogue

- Add override sorting Canvas (sortingOrder 999) to dialogue highlights
  so they render above sibling UI elements like adjacent command buttons.
  Increase default thickness from 3 to 5 and minimum strobe alpha from
  0.2 to 0.5 for better visibility

- Delay tutorial_rebuild_support trigger until all notifications are
  dismissed, so the Marek/Ranil/Elena dialogue sequence starts cleanly

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

* Use public GameModel accessor instead of private Model

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

* Fix NRE: Canvas already adds RectTransform, use GetComponent

Adding a Canvas component automatically creates a RectTransform, so
AddComponent<RectTransform>() returned null. Use GetComponent instead.

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

* Re-check deferred tutorials when notifications are dismissed

CheckTutorialRebuildSupport only ran during OnModelUpdated, but after
dismissing notifications no model update occurs. Add OnAllDismissed
callback to NotificationPanel, and have TutorialTriggerRegistry
subscribe to it so deferred tutorials fire once notifications clear.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:23:44 -08:00
e8e967fde2 Filter nightly iOS TestFlight by relevant paths (#6360)
* Filter nightly iOS TestFlight by relevant paths

Instead of rebuilding whenever any file changes, compare changed files
against paths that actually affect the iOS build (C#, protobuf, resources,
C++ plugins, scripts, CI config). Scala, Go, and test-only changes no
longer trigger unnecessary nightly builds.

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

* Remove src/main/cpp/ from iOS-relevant paths

Shardok C++ code is server-side only. Native Unity plugins come from an
external Bazel dep (@net_eagle0_unity_godice), not the in-repo C++ code.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:16:20 -08:00
09d31630f8 Register AI client for factions created mid-game (#6357)
The Eagle faction is created mid-game via EagleAppearsAction but
withHandledEngineAndResults only removed AI clients for destroyed
factions — it never added AI clients for newly created ones. The
Eagle faction appeared on the map but never took any turns.

After filtering out removed AI clients, detect new factions from
action results and register AI clients for any that aren't already
human-controlled or AI-controlled.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 09:57:16 -08:00
e6acac9bd6 Skip nightly iOS TestFlight build when nothing changed (#6358)
Adds a check-changes job that compares HEAD against the last successful
scheduled run. If the SHA matches, the build is skipped. Manual
workflow_dispatch triggers always build regardless.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 09:55:26 -08:00
88a311094b Fix missing flee/retreat animations for untargeted commands (#6356)
Flee and retreat commands have no target in their protobuf (only actor),
so the Unity client treated them as untargeted and called
PerformUntargetedCommand without triggering any animation or sound.

Add PlayUntargetedCommandAnimation which looks up the animation type
for the command, finds the nearest enemy to use as the flee direction,
and calls PlayAnimationAndSound with the two-stage flow so both the
attempt and result animations play correctly.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 07:22:29 -08:00
503d92fc3c Fix Eagle Appears event never firing in tutorial (#6355)
The game type check compared GameType (non-optional) against
Some(GameType.Tutorial), which always evaluates to true in Scala,
causing checkForEvents to always return empty.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:03:47 -08:00
81179dc268 Add nightly schedule to iOS TestFlight workflow (#6354)
Runs at 9 PM Pacific (5 AM UTC) every night, alongside the existing
manual workflow_dispatch trigger.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:48:49 -08:00
68ded773ec Add per-hero initial faction biases for tutorial captured heroes (#6353)
Adds a JSON-configurable faction bias that gets applied when a tutorial
hero becomes unaffiliated (imprisoned/exiled). Currently used to give
Luke the Prank-tricker a +30 bias toward Sadar's faction, making him
more willing to join after capture.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:48:18 -08:00
5ff2639b84 Include province name in ready-to-join hero tutorial (#6352)
* Include province name in ready-to-join hero tutorial dialogue

Marek now says which province the recruitable hero is in, e.g.
"there's a hero in Onmaa who's ready to join our cause."

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

* Advise taking most gold and food when expanding

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:18:11 -08:00
16ffe21d46 Rework tutorial pacing: delay expansion, add town tutorials (#6348)
* Rework tutorial pacing: delay expansion until taxes, add town tutorials

- Change "support reached 40" dialogue to congratulate and encourage
  continued development until January instead of immediately pushing expansion
- Move expansion instructions to the "taxes collected" dialogue
- Add tutorial_ready_to_join: fires when a free hero with WouldJoin status
  appears in the player's province, instructs them to Travel and Recruit
- Add tutorial_in_town: fires when player enters town (ReturnCommand
  available), explains all town activities and that Return advances the month

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

* Refine tutorial expansion advice and remove redundant Give Alms

Remove Give Alms from the support tutorial instructions (already covered
earlier). Update the expansion panel to advise taking most heroes
(especially those with professions) and leaving only one or two behind.

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

* Add second hero departure tutorial when King loses another follower

Fires tutorial_hero_departed_again on the second month a King's hero
departs (must be a different month than the first departure). Marek
reacts with alarm that the King is losing authority across the realm.

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

* Adjust second hero departure dialogue to hint at something strange

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

* Rewrite second departure dialogue in Marek's voice

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:01:30 -08:00
e76873515a Bump tutorial outer province hero loyalty by 5 (#6351)
Raise loyalty from 30 to 35 for distant provinces (15% departure
chance) and from 25 to 30 for Nikemi/Pieksa (20% departure chance).
Heroes were departing too early even with the roundIdJoined fix.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:52:10 -08:00
85f7ecbde9 Set roundIdJoined in LoadedHeroConversion so tutorial heroes are protected (#6350)
LoadedHeroConversion.toHeroC was not setting roundIdJoined, leaving it
as None. This meant hero.roundIdJoined.exists() returned false in
PerformHeroDeparturesAction, so the MinimumRoundsBeforeLoyaltyDegrades
check was silently skipped for all tutorial heroes. Move the
roundIdJoined = Some(0) assignment into toHeroC and remove the now-
redundant set in NewGameCreation.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:43:26 -08:00
bb93676bce Fix Polytope humanoid models rendering as solid white/black (#6349)
Polytope Studio characters (rebels, peasants, knights, etc.) use a
complex zone-coloring shader that can't be replaced by ClipRectMeshUnlit.
ShaderUtils.ReplaceWithClipRect now skips materials without _MainTex and
returns false.  When any material is skipped, the effect attaches a new
RendererViewportClipper component that clips by toggling renderer.enabled
based on the global _ViewportClipRect/_PopupClipRect each frame.

Also force vertex color alpha to 1 in ClipRectMeshUnlit to prevent 3D
mesh models with zero vertex alpha from becoming invisible.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:33:58 -08:00
b336594173 Prevent newly-joined heroes from departing and tune tutorial loyalty (#6347)
Add a roundIdJoined check to PerformHeroDeparturesAction so heroes
that joined within MinimumRoundsBeforeLoyaltyDegrades rounds cannot
depart. This mirrors the existing loyalty degradation gating in
NewYearAction.

Also raise tutorial hero loyalty from 25 to 30 for outer King's
provinces (20% departure chance), keeping 25 for Nikemi and Pieksa
which are adjacent to Onmaa (25% departure chance).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:20:33 -08:00
2fabbba081 Wire skip tutorial battle button and PopupClipper in Unity scenes (#6346)
Adds Inspector wiring for the skip_tutorial_battle button in lobby prefabs
and includes PopupClipper.cs.meta for the popup effect clipping component.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:21:16 -08:00
652cb7e732 Enable prebuilt protoc binaries via module extension (#6345)
The .bazelrc flags prefer_prebuilt_protoc and
incompatible_enable_proto_toolchain_resolution were set but the
prebuilt binary repos were never made available. Add the required
use_extension/use_repo calls so Bazel can actually find and use the
prebuilt protoc instead of compiling it from source.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:02:38 -08:00
30d1822981 Add skip_tutorial_battle client-side support (#6344)
Adds editor-only "Skip Battle Tutorial" button that creates a tutorial
game with skip_tutorial_battle=true. Fixes CheckTutorialBattleEnded to
detect server-side auto-resolved battles (no RunningShardokGameModels
were ever observed) and fire tutorial_battle_ended normally.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:54:45 -08:00
3ee8293794 Add skip_tutorial_battle server-side auto-resolution (#6343)
When skip_tutorial_battle is set in CreateGameRequest, the server
creates the tutorial game normally then immediately resolves the
opening battle with a synthetic BattleResolution — defender wins,
Tarn flees, other attackers captured, defender battalions at ~70%.
The existing ResolveBattleAction pipeline runs so all post-battle
logic executes authentically without Shardok involvement.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:12:25 -08:00
57c42d71f7 Clip map effects behind hero backstory popup (#6342)
* Render hero backstory popup above map effects

The hero popup panel was rendering behind 3D effects (dragons, animals,
monsters) because effects use sortingOrder=103 / renderQueue=4000 while
the popup was on the root Canvas at sortingOrder=0. Add an override
sorting Canvas (sortingOrder=200) to the popup panel at startup so it
draws above all map effects.

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

* Lower effect renderQueue so popup Canvas override can draw above them

The effects used renderQueue=4000 (Overlay), which draws after all
standard UI regardless of Canvas sortingOrder. Changed the
ClipRectMeshUnlit shader queue from Overlay to Transparent+100 and
removed explicit renderQueue=4000 from effect classes. The shader's
ZTest Always + ZWrite Off + sortingOrder=103 is sufficient to render
above the map without needing the Overlay queue.

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

* Use shader-based popup masking instead of Canvas override sorting

Canvas override sorting doesn't affect MeshRenderer draw order in
Screen Space - Overlay mode. Instead, use the same clip rect pattern
as viewport clipping: PopupClipper broadcasts the popup's screen-space
bounds as _PopupClipRect, and all effect shaders discard fragments
inside it. The popup rect is cleared on disable so effects render
normally when the popup is hidden.

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

* Add popup clip rect to weather shaders (drought/flood overlay)

The ProvinceWeatherShader and ProvinceWeatherMapShader render weather
overlays as UI elements using custom shaders, so they also need the
_PopupClipRect discard check to avoid rendering over the hero popup.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:57:49 -08:00
40f379c206 Clip map effects to scroll view viewport using shader clip rect (#6341)
ViewportClipper broadcasts the viewport's screen-space bounds as a global
shader property (_ViewportClipRect). Each effect shader discards fragments
outside those bounds, preventing particles, 3D models, and sprites from
overflowing the map viewport during zoom/pan.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 13:47:37 -08:00
b0bcc5fd8d Fix PleaseRecruitMe appearing before quest completion notification (#6339)
When a quest grants a free hero, both the quest notification and
PleaseRecruitMe command arrive in the same batch. Both panels call
SetAsLastSibling() during setup, but PleaseRecruitMe was set up last,
hiding the notification behind it. After the blocking command switch,
re-raise the notification panel if it has pending info so the player
sees the quest completion first.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 19:23:01 -08:00
c310894fb0 Remove redundant LFS cache step from CI workflows (#6338)
Self-hosted runners persist .git/lfs/objects/ between runs, and LFS
objects are now served from a local Gitea mirror on the LAN. The
actions/cache step was downloading ~1.8 GB from GitHub on every run,
adding ~35s and consuming transfer quota unnecessarily.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 19:21:40 -08:00
4717423f8b Add Flee as two-stage animation with captured-while-fleeing variant (#6337)
* Add Flee as two-stage animation with captured-while-fleeing variant

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

* Move TWO_STAGE_ANIMATIONS.md to docs/

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

* Move TWO_STAGE_ANIMATIONS.md to repo root docs/

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

* Wire up flee attempt and run away sound effects in Unity scene

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

* Add Flee Captured test button to AnimationTestController

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

* Split Flee into three distinct animations: attempt, success, captured

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

* Fix test buttons to play full two-stage sequence for result animations

Result variant test buttons (Fear Success/Resisted, Flee Success/Captured,
Duel/Declined) now play the complete attempt→result sequence instead of
only the attempt sound.

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

* Make flee attempt animation more visible and cap two-stage delay at 0.5s

Flee attempt now uses full dust burst and multiple blur trail afterimages
instead of minimal dust and single blur. Two-stage delay between attempt
and result capped at 0.5s in both PlayTwoStageSequence and
PlayTwoStageSoundSequence (affects other players' actions and test buttons).

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

* Tune flee animation parameters in Unity scene

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 19:16:34 -08:00
5730873601 Add TrackedEffectAnimator base class to prevent effect leak on battle end (#6336)
When a battle ends mid-animation, coroutines stop but GameObjects parented
to the hex grid survive and leak. This extracts the Track/OnDestroy pattern
(originally fixed in FearAnimator for the skull persistence bug) into a
shared base class and applies it to all 22 Shardok animators.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 16:35:34 -08:00
858338307f Add Heavy Cavalry battalion to King's starting province (#6335)
The King was consistently getting overwhelmed in the early game. Add a
Royal Lancers heavy cavalry unit (800 troops) to province 37 to give
him a stronger opening position. Hero count already matches at 7.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 16:17:21 -08:00
93b7b723b9 Fix pregenerated hero names not delivered to client during gameplay (#6334)
HeroGenerator.getHero returned NoNameRequest for pregenerated heroes,
so no name text request was created when they appeared mid-game. The
name existed in the in-memory pregenerated store but was never written
to SQLite, and getCompleteTextsAccessibleTo only queries SQLite. The
client received the hero's nameTextId but never the actual text,
showing "Hero" as a fallback.

Now getHero assigns an hn_ nameTextId and returns FixedName, so the
name goes through the normal FixedHeroName pipeline: added to SQLite
by foldInLlmRequests, immediately resolved by UnrequestedTextHandler,
and delivered to the client like any other hero name.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 16:04:12 -08:00
c81ce990bc Fix fear animation sprites persisting after battle ends (#6333)
FearAnimator creates GameObjects (skull, tendrils, shield, etc.) as
children of the hex grid and only cleans them up at the end of each
coroutine. If the battle ends mid-animation, the coroutine is
interrupted and cleanup never runs, leaving orphaned sprites visible
in subsequent battles.

Track all created GameObjects and destroy them in OnDestroy().

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 15:04:50 -08:00
08cca4c5f0 Fix Shardok battle replay after admin rewind (#6331)
When rewinding a game and replaying to the same battle, the Shardok
server returned cached results instead of fighting fresh. The C++ server
kept completed game controllers in runningControllers indefinitely, so
ControllerForGame returned the old controller and SubscribeToGame
immediately sent back game_over_response with stale results.

Fix: detect rewind by checking for an existing game + NewGameRequest +
knownResultCount == 0, then replace the old controller with a fresh one.
Also cancel pending Eagle-side battle subscriptions on rewind.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:54:03 -08:00
20fd177746 Fix border security quest offered when already fulfilled by alliances (#6332)
Quest creation only checked if neighbors were owned by a different faction,
ignoring alliances. Fulfillment logic counted allied neighbors as secured.
This mismatch caused quests to be offered and immediately fulfilled. Now
creation also checks for alliances, matching the fulfillment logic.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:45:58 -08:00
4aefe06683 Cap drawn beast count at actual ProvinceEvent beast count (#6330)
Take the lower of the Inspector-configured count and the actual beast
count from BeastsEvent.Count. Effect classes now initialize in Start()
instead of Awake() so SpawnBeastsEffect can cap the count field after
Instantiate but before creatures are spawned.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:32:41 -08:00
9eb954be65 Handle removed FFA proto values gracefully in converters (#6329)
RoundPhaseConverter maps Unrecognized(13|14|15) to UncontestedConquest
instead of throwing, allowing saved games from removed FFA phases to
load. CommandTypeConverter maps Unrecognized(12) to None.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:20:15 -08:00
a1c436b398 Remove Free-For-All battles, replace with sequential AttackDecision (#6328)
* Remove Free-For-All battles, replace with sequential AttackDecision

When multiple hostile factions march on the same province, instead of a
separate FFA decision/battle phase, the AttackDecision phase now handles
them sequentially: armies sorted by troop count (largest first), only
the largest undecided army gets the command. After someone advances,
allied armies can join while hostile armies are auto-bounced (occupied)
or can contest (unoccupied).

Phase flow: HostileArmySetup → UncontestedConquest → AttackDecision →
DefenseDecision → Battle (removed FreeForAllDecision,
FreeForAllBattleRequest, FreeForAllBattleResolution phases).

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

* Remove FFA protos, simplify unoccupied province attack logic

- Remove FFA proto fields from available_command, selected_command,
  command_type, round_phase, and army protos (mark as reserved)
- Remove corresponding converter match arms (ArmyConverter,
  SelectedCommandConverter, CommandTypeConverter, RoundPhaseConverter)
- Simplify isMyTurnToDecide: hostile armies are always blocked when
  another army has advanced (no more unoccupied province special case)
- Replace preBattleConquestResults with uncontestedConquestResults:
  handles single/allied/hostile armies on unoccupied provinces with
  conquest + bounce of hostile AwaitingDecision armies
- Add 6 tests covering tiebreak, hostile blocking, allied joining,
  auto-bounce, and uncontested conquest scenarios

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

* Remove FFA references from Unity C# client

Delete FreeForAllDecisionCommandSelector and its .meta file,
remove FFA tutorial entry from TutorialContentDefinitions.

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

* Fix alliance check and simplify uncontested conquest logic

Fix exists→forall bug in AvailableAttackDecisionCommandFactory: armies
must be allied with ALL advancing armies, not just any one. Move all
unoccupied province conquest into UncontestedConquest phase (largest army
always wins) and remove redundant logic from EndAttackDecisionPhaseAction.

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

* Improve army tiebreaking: troop count, then power, then pseudo-random

When choosing the "largest army" (for attack decision ordering and
uncontested conquest), tiebreak by total unit power after troop count,
then by factionId XOR randomSeed for a pseudo-random final tiebreak
that varies across games instead of always favoring lower factionIds.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:01:02 -08:00
f38f638512 Fix analyzer warnings in ShardokGameController (#6327)
Materialize LINQ chain to avoid multiple enumeration in
HandleOverlays, simplify redundant return in HandleLongHover,
and replace always-matching UnitId type pattern with var.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 09:48:45 -08:00
96a1f0580e Remove debug logging and unused code from ShardokGameController (#6326)
Remove MeteorCast/MeteorTarget Debug.Log calls, unused HeroId alias,
and unused NoHistoryText constant.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 09:43:02 -08:00
675daa2424 Capture losing non-defender attackers' units after province conquest (#6325)
When a non-defender attacker lost a multi-faction battle, their surviving
units were silently dropped. ProvinceConqueredAction only processed the
winner's and defender's units, so a third-party loser's Normal units were
not returned (unitReturned=false for Loss), not captured (not a defender),
and not outlawed — they just vanished. Fixed by changing the filter from
defenders-only to all non-winning players.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 08:14:07 -08:00
24307445ed Fix AllyVictory never granted in Shardok battle resolution (#6324)
The AllyVictory check in PopulateGameOverResponse compared the current
player's own ID (shardokPid) against their own allies list — which is
always false since a player is never listed as their own ally. Fixed by
using the lambda's `pid` parameter (the winning player's ID, previously
unused) instead of `shardokPid`.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 08:11:55 -08:00
dcf9ce6a84 Fix leader cache crash when faction head is in killedHeroes (#6322)
GamesManager.leaderCache looked up faction heads with
gameState.heroes(faction.factionHeadId), which throws
NoSuchElementException if the hero died in battle and was moved to
killedHeroes. Use getOrElse fallback to killedHeroes, matching the
pattern used elsewhere (HeroInfoUtilities, ChronicleEventTextGenerator).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 22:04:25 -08:00
655e37e1f2 Shatter retreating armies arriving at conquered provinces (#6321)
When an army retreats from battle, its return destination is set at march
time. If that province is conquered while the army is fighting, the
retreating army arrives at a now-hostile province, causing a "Mismatched
factionIds" validation error. Fix by detecting these stranded armies in
PerformProvinceMoveResolutionAction and shattering them (heroes become
outlaws) instead of letting them fall through to hostile army processing.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:50:40 -08:00
f389053e33 Suppress UI status flicker during expected gRPC reconnects (#6320)
When reconnecting due to idle timeout, deadline exceeded, or normal
stream end, keep the displayed connection status unchanged instead of
briefly showing "Connecting..." or "Retry in Xs".

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:25:44 -08:00
640a2e0269 Fix cross-wired fileIDs in ScorpionEffect prefab references (#6319)
The two animalPrefabs entries had their fileIDs swapped between the
scorpion_prefab and yellow_fattail_scorpion_prefab GUIDs, causing
MissingReferenceException at runtime.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 16:51:28 -08:00
c5b38f7adc Color Send Supplies held-back amounts red when over province capacity (#6318)
Matches the existing Trade command selector behavior where food/gold
amounts turn red when they exceed the province's storage cap.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 16:40:35 -08:00
2b29dc6b06 Fix opponent two-stage animations and sounds not sequencing properly (#6317)
Two-stage actions from the opponent were playing the attempt sound
sequenced correctly but only one animation immediately. The attempt and
result animations were not sequenced.

Fear and Duel exposed this most visibly since they have distinct result
animations (FearSuccess/FearResisted, Duel/DuelDeclined), but the
pattern was wrong for all two-stage actions.

Replace the separate PlayTwoStageSoundSequence + PlayAnimation calls with
a unified PlayTwoStageSequence coroutine that sequences both animations
and sounds: attempt animation+sound → wait → result animation+sound.

Add AttemptAnimationType() to map result animation types back to their
attempt type (FearSuccess/FearResisted → Fear, Duel/DuelDeclined →
DuelChallenge). For actions where attempt and result use the same
animation, the result animation phase is skipped.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 16:20:12 -08:00
79c5be3a54 Decouple non-Mac builds from Xcode dependency (#6316)
* Decouple non-Mac builds from Xcode via BAZEL_NO_APPLE_CPP_TOOLCHAIN

Set BAZEL_NO_APPLE_CPP_TOOLCHAIN=1 in .bazelrc so apple_support skips
Xcode detection (xcode-locator) entirely for Scala/C++/Go builds.
Only mactools builds (Mac/Sparkle) re-enable the Apple CC toolchain.

This means Xcode version changes no longer affect Eagle, Shardok, test,
auth, docker, or Unity Windows builds — no expunge, no cache invalidation,
no rebuild. The sync script and its expunge/cache-key logic are now scoped
to mactools only and removed from all non-Mac CI workflows.

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

* Revert BAZEL_NO_APPLE_CPP_TOOLCHAIN; keep Apple CC with stable environ

BAZEL_NO_APPLE_CPP_TOOLCHAIN=1 broke builds because apple_support
registers platforms (e.g. macos_x86_64) that require Apple CC toolchains
for resolution — even in non-Mac builds.

Instead, keep Apple CC enabled but ensure its repo rule never
re-evaluates on non-Mac builds by keeping DEVELOPER_DIR pinned in
common:macos. The sync script only runs for mactools builds and
overrides DEVELOPER_DIR there.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 16:08:28 -08:00
e8780134ee Cache Git LFS objects in CI to reduce bandwidth usage (#6315)
Add actions/cache for .git/lfs in all workflows that fetch LFS objects
(unity_build, mac_build, ios_testflight, ios_addressables_build).
The cache key is based on .gitattributes so it updates when LFS tracking
rules change. Subsequent runs restore from cache and git lfs pull only
fetches new/changed objects, avoiding re-downloading the full 6+ GB.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 15:20:27 -08:00
be48f54f2c Update golang.org/x/sys from v0.28.0 to v0.30.0 (#6314)
Match the version that Gazelle's MVS already resolved transitively,
silencing the "implicitly updated to higher versions" debug warning.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:52:22 -08:00
f2487fc8ee Exclude slow MCTS basic test from default test suite (#6312)
Tag shardok_mcts_ai_basic_test as "manual" so it's skipped by
wildcard test patterns. MCTS is not in active use and this test
takes ~75s. It can still be run explicitly when needed.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:39:38 -08:00
93ad8c4ae1 Reintegrate SparklePlugin into main workspace (#6308) (#6311)
The grpc 1.78.0 upgrade eliminated the rules_swift version conflict
that required SparklePlugin to live in a separate Bazel workspace.
Move it back into the main workspace under src/main/objc/.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 13:16:02 -08:00
8cb75d48e2 Add giant beast type using 3x-scaled peasant (#6308)
* Add giant beast type using 3x-scaled peasant model

Reuse Polytope peasant prefabs at 3x scale (animalScale 45) with a single
wandering giant per province. Uses HumanMapAnims controller for idle/walk/
attack animations.

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

* Fix giant test method to use correct province name (Elekes)

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

* Wire up GiantEffect prefab in Gameplay scene

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 13:05:59 -08:00
97bf29d4a2 Fix Bazel Xcode version caching in CI (#6309)
* Fix Bazel Xcode version caching causing CI build failures

When Xcode updates on self-hosted runners, Bazel's cached
local_config_xcode still references the old version, causing
"xcode-locator <old_version> failed" errors.

Add sync_bazel_xcode.sh which detects Xcode version changes
and runs `bazel sync --configure` to refresh the config without
nuking the build cache. Added to all 8 CI workflows that use Bazel.

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

* Use rm of cached repo instead of bazel sync --configure

bazel sync --configure requires WORKSPACE mode and fails with
bzlmod. Instead, delete the stale local_config_xcode from the
output base directly — the next bazel build regenerates it.

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

* Use bazel clean --expunge instead of targeted repo deletion

Deleting just local_config_xcode is insufficient — the stale Xcode
version is also embedded in cached actions and other toolchain repos.
The only reliable fix is a full expunge. Since Xcode updates are
infrequent, the one-time rebuild cost is acceptable.

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

* Use action_env to bake Xcode version into cache keys

Instead of expunging the cache (which doesn't help with the remote
cache anyway), write the Xcode build version to .bazelrc.xcode via
--action_env. This makes the version part of every action's cache
key, so stale entries in both local and remote caches are naturally
ignored after an Xcode update — no deletion needed anywhere.

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

* Add expunge back alongside action_env for belt-and-suspenders fix

action_env alone isn't enough — local_config_xcode is a cached
repository rule that bakes in the old Xcode version before any
actions run. Need expunge to clear the local toolchain config,
plus action_env to prevent stale remote cache hits afterward.

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

* Add Xcode sync to mac_build build-and-sign job

The sync step was only in the deploy job, but build-and-sign calls
bazel via build_protos.sh before that. This runs on the unity-mac
runner which also has the stale Xcode cache.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 12:43:14 -08:00
38c3fbd6bd Add psychopath to beast effects coverage doc (#6310)
It uses the Butcher 2D sprite via ButcherBeastNames HashSet,
but was missing from the documentation table.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:49:46 -08:00
47f936df05 Upgrade grpc from 1.74.1 to 1.78.0 (#6307)
grpc 1.78.0 dropped its rules_swift dependency, resolving the version
conflict (rules_swift 3.x vs 2.x) that forced SparklePlugin into a
separate workspace. This removes the rules_swift single_version_override.

Includes a patch for a known BCR bug (grpc/grpc#41438) where grpc 1.78.0
requests Python 3.14.0b2 but rules_python >= 1.6.0 replaced it with 3.14.
The patch backports the upstream fix (commit 459279b).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:27:13 -08:00
85a3f4bc39 Upgrade dragon beast to 3D model with full animation suite (#6306)
Replace the 2D PSD-based DragonRed sprite with a 3D FBX model from 3dFoin
Dragon. The dragon now alternates between flying (circling at altitude with
fly/flyAttack/flyBreathFire/flyFast/flyHit actions) and grounded (wandering
with walk/run/attack/breathFire/whipTail/hit/stand/idle actions) modes.

- Add DragonMapAnims.controller with 15 animation states
- Configure dragon_skin.FBX for Generic animation with avatar
- Rewrite DragonEffect.cs with 4-mode state machine
- Delete old 2D DungeonMonsters2D dragon assets
- Add Dragon/ to LFS rules and clang-format excludes

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:25:37 -08:00
ce49304406 Add Polytope 3D character archetypes for human beast animations (#6304)
* Add 5 Polytope character archetypes for human beast animations

Replace the single Butcher sprite for all 34 human-type beasts with
5 thematic 3D archetypes using Polytope Studio Lowpoly Medieval
Characters: Knight (6 beasts), Soldier (8), Archer (3), Militia (8),
and Peasant (9). All share a HumanMapAnims controller that retargets
Clown animation clips via Unity's Humanoid system.

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

* Rename humanEffectPrefab to butcherEffectPrefab; route psychopath to it

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

* Move butcherEffectPrefab under Human Effect Prefabs header

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

* Wire up Polytope prefabs in scene; rename HumanEffect to ButcherEffect

Wire all 6 human effect prefabs (butcher, knight, soldier, archer,
militia, peasant) in Gameplay.unity scene. Rename HumanEffect.prefab
to ButcherEffect.prefab to match the field rename.

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

* Exclude third-party asset packs from clang-format hook

Skip DungeonMonsters2D, Polytope Studio, RRFreelance-Characters,
and Raccoon directories — these are vendor code that should not
be reformatted.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 07:36:59 -08:00
c9afc4a6b8 Convert existing asset packs to Git LFS (#6303)
* LFS-track all files under third-party asset pack directories

Track all files under DungeonMonsters2D/, Raccoon/, Polytope Studio/,
and RRFreelance-Characters/ via Git LFS. These are imported third-party
assets that are never manually edited.

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

* Convert DungeonMonsters2D and Raccoon assets to Git LFS

Re-add all files under DungeonMonsters2D/ and Raccoon/ through
the LFS filter so they're stored as LFS objects going forward.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 07:18:02 -08:00
90f20e25b2 Add psychopath beast type (#6301)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 06:58:27 -08:00
d6c3abd505 Reduce raccoon animal scale from 15 to 5 (#6300)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 21:05:46 -08:00
ee31265ff6 Clean up warmup-binary artifacts after deploy (#6299)
The warmup-binary artifacts from docker_build were accumulating and
exceeding the 500 MB storage threshold. GitHub's retention-days cleanup
wasn't keeping up with deploy frequency. Add explicit artifact deletion
after deploy, matching what mac_build already does.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 20:58:47 -08:00
e289913e18 Add raccoon beast animation (Sketchfab 3D model) (#6298)
* Add raccoon beast animation using Sketchfab 3D model

Adds Raccoon.fbx (WildMesh 3D, CC BY 4.0) with textures, wires up
raccoonEffectPrefab in ProvinceBeastsController, and updates both
attributions.json files and BEAST_EFFECTS.md.

Editor steps still needed: create RaccoonMapAnims controller, create
RaccoonEffect prefab (duplicate HoneyBadgerEffect), wire in Gameplay.unity.

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

* Wire up raccoon animation with Blender-converted FBX

Convert GLB to FBX via Blender (original FBX had no animation data).
Add RaccoonMapAnims controller, RaccoonEffect prefab, materials with
textures, scene wiring, and fix province name (Hella, ID 19).

Known issue: gray sphere artifact under each raccoon.

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

* Remove Icosphere/hair artifacts from raccoon FBX and update scene

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

* Smooth 3D animal turning with Quaternion.Slerp

Animals now rotate smoothly toward their target instead of snapping.
UpdateFacing is called every frame during walking, and uses Slerp
with a configurable turnSpeed (default 5) for gradual rotation.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 20:58:19 -08:00
62cba309d8 Replace Unity attributions.json with symlink to canonical copy (#6297)
Eliminates the duplicate attributions.json by making the Unity copy
a symlink to src/main/resources/net/eagle0/attributions.json, ensuring
a single source of truth that can never diverge.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 15:00:13 -08:00
25d1d2b268 Note controller override in honey badger doc entry (#6296)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 14:14:11 -08:00
cd7e21cfa4 Add honey badger beast animation (3D model) (#6293)
* Add honey badger 3D model and wire up AnimalEffect

Import HoneyBadger FBX (63 animations) and texture from Sketchfab.
Add honeyBadgerEffectPrefab field and switch case in
ProvinceBeastsController. Still needs Unity Editor setup: Animator
Controller, effect prefab, and scene wiring.

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

* Fix honey badger test province name (ID 1 is Shumal, not Onmaa)

Onmaa is province ID 14, already used by TestWildPig.

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

* Wire up HoneyBadgerEffect prefab and animator controller

- HoneyBadgerMapAnims controller with idle/walk/eat/attack states
  mapped to HoneyBadger FBX clips
- HoneyBadgerEffect prefab with AnimalEffect referencing the model
- Wired into Gameplay.unity ProvinceBeastsController
- Includes Unity-generated .meta files for imported assets

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

* Fix HoneyBadger FBX avatar setup to enable animations

avatarSetup: 0 (No Avatar) prevented the Animator from driving the
skeleton. Changed to avatarSetup: 1 (Create From This Model) to match
how the Animal Pack Deluxe models are configured.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 14:01:27 -08:00
5bb6b4ca9d Add attribution for new beast animation asset packs (#6294)
* Add attribution for recently added Unity asset packs

Add Animal pack deluxe (janpec), 2D Monster Pack Basic Bundle/PSB
(SP1/DungeonMonsters2D), and Honey Badger 3D model (WildMesh 3D) to
ASSET_AUDIT.md. Update 3D model count in summary table.

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

* Add 3D model attributions to in-app/website credits

Add Animal pack deluxe, 2D Monster Pack, and Honey Badger
to both server and Unity client attributions.json files.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 13:33:55 -08:00
9030c455e0 Add no-chained-commands rule to CLAUDE.md (#6295)
Prevents Claude from combining bash commands with &&, ||, or ;.
Each command must be a separate tool call, which makes permission
rules work correctly per-command.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 11:41:27 -08:00
49c14be159 Add clown beast animation with both Clown Pack models (#6292)
* Add clown beast animation using both Clown Pack models

- Add per-prefab animator controller overrides to AnimalEffect
  (animatorControllers[] array, indexed to match animalPrefabs[])
- Create ClownMapAnims and FatClownMapAnims controllers mapping
  idle/walk/eat/attack states to each model's animation clips
- Create ClownEffect prefab using both Clown and Fat Clown models
- Add clown case to ProvinceBeastsController, remove from HumanBeastNames
- Wire up in Gameplay.unity scene
- Update BEAST_EFFECTS.md

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

* Fix ClownEffect prefab (recreated via Unity editor)

The hand-written prefab YAML was rejected by Unity's PrefabImporter.
Recreated by duplicating the working OgreEffect prefab in the editor
and configuring the AnimalEffect fields there.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 10:08:18 -08:00
e63735f428 Update beast effects doc for ogre/troll coverage (#6291)
* Update BEAST_EFFECTS.md: ogre/troll now have custom animation

Reflects the addition of the Orc-Ogre pack AnimalEffect for ogre and
troll beast types (PR #6287). Removes them from the "no custom
animation" list and adds them to the custom animations table.

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

* Add complete beast coverage details to BEAST_EFFECTS.md

- Add missing animal effect entries (crab, frog, rabbit, salamander,
  scorpion, stag, wild goat, wild pig) to custom animations table
- Add human-type beast breakdown by likelihood with thematic clusters
  for potential visual differentiation beyond the generic Butcher prefab

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 08:48:57 -08:00
f4b9a9268c Refactor BeastUtils to use pattern matching instead of asInstanceOf (#6290)
Replace unsafe asInstanceOf casts with pattern matching via helper
methods. This is more idiomatic Scala and will give clearer error
messages if the map contains unexpected types.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 08:39:22 -08:00
272badda47 Balance beast danger levels and add powerExponent (#6288)
Fixes two issues with beast balance:

1. Demons and vampires were impossible to defeat - reduced maxCountMultiplier
   from 0.5 to 0.15 so an elite battalion (1000 troops, 100/100 stats) can
   just barely defeat them.

2. Clowns had a 39% chance of being deadlier than demons due to their huge
   power variance (0.8-50). Added a powerExponent field to beasts.tsv that
   controls how the random roll translates to power. Default is 4 (quartic),
   clowns use 20 which reduces the chance of deadly clowns to ~10%.

The casualties formula is: casualties = beastsPower² / totalPower
Where beastsPower = count × relativePower

This means overwhelming force results in minimal casualties (intended),
but also means high beast power causes quadratically more damage.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-26 08:34:46 -08:00
080329e369 Fix NullReferenceException when clicking map before model loads (#6289)
ProvinceWasSelected accessed Model.AvailableCommandsByProvince and
Model.Provinces without checking if Model was null. This caused a
crash when the user clicked a province before the game model was
received from the server on first load.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 08:32:31 -08:00
f9afcea9f7 Add ogre/troll beast animation using Orc-Ogre 3D asset pack (#6287)
- Add animatorController override field to AnimalEffect so it can swap
  the prefab's controller at runtime (needed because the Orc-Ogre pack
  uses state names like Ogre_Idle1 instead of the expected idle/walk/etc)
- Create OgreMapAnims.controller with idle/walk/eat/attack states mapped
  to Orc-Ogre FBX animation clips
- Create OgreEffect.prefab using AnimalEffect + controller override
- Add ogre/troll cases to ProvinceBeastsController.GetEffectPrefab()
- Wire OgreEffect in Gameplay.unity scene

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 08:15:49 -08:00
cec058c369 Wire up animations for 8 new beast types (#6286)
* Wire up animations for 8 new beast types

Add effect prefabs and scene wiring for crab, frog, rabbit,
salamander, scorpion, stag, wild goat, and wild pig using
Animal Pack Deluxe 3D models with AnimalEffect controller.

Multi-variant prefabs: frog (3), scorpion (2), rabbit (2),
stag (2), wild goat (2), wild pig (2).

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

* Fix ContextMenu test labels to use real province names

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

* Fix animal effect prefab references to use root GameObjects

Each Animal Pack prefab contains many child objects (bones, meshes, etc).
The effect prefabs were incorrectly referencing the first child object
instead of the root prefab object (the one with m_Father: {fileID: 0}).

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

* Tune animal effect scales per beast type

Adjusted animalScale values from the Unity editor after visual testing:
- Frog, salamander, scorpion, crab: 50 (small creatures need more zoom)
- Rabbit, stag, wild goat, wild pig: 20 (medium animals)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:35:57 -08:00
679b5ef1ce Add 8 new beast types with matching asset pack animations (#6285)
New beasts from Animal Pack Deluxe:
- crab (0.04): coastal swarm, low power, agriculture damage
- frog (0.10): plague swarm, very high count, minimal power
- rabbit (0.20): crop-destroying swarm, high agriculture damage
- salamander (0.02): rare, poisonous, moderate power
- scorpion (0.15): venomous swarm, like spiders
- stag (0.04): territorial wild deer, moderate power
- wild goat (0.10): mountain crop raiders, agriculture damage
- wild pig (0.10): aggressive crop destroyers

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:07:36 -08:00
f44b7351b4 Add spawn likelihood to uncovered beast types in docs (#6284)
Order beasts without custom animations by how commonly they appear,
making it easier to prioritize which to add next.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:01:52 -08:00
03e82ae635 Update beast effects docs with full animation coverage (#6283)
Document all three effect types (MonsterEffect, AnimalEffect,
DragonEffect), list all beasts with custom animations vs vulture
fallbacks, and add 3D rendering tips.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 21:25:18 -08:00
3e4aa6d6d2 Update animal effect prefab scales from 20 to 15 (#6282)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 21:21:37 -08:00
6bfbf38fb4 Add animal wandering effects for bear, boar, crocodile, snake, wolf (#6281)
* Add animal wandering effect for bear, boar, crocodile, snake, wolf

New AnimalEffect.cs drives Animal Pack Deluxe 3D prefabs using their
lowercase state names (idle, walk, run, eat, attack) and Y-rotation
for facing direction. Wolverine reuses the wolf prefab.

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

* Add animal effect prefabs and scene wiring for bear, boar, crocodile, snake, wolf

Wire AnimalEffect prefabs to ProvinceBeastsController and include the
Animal Pack Deluxe asset pack. RatEffect now has both MonsterEffect
(2D sprites) and AnimalEffect (3D model) for a mixed group.
Add LFS tracking for .tga and .fbx files.

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

* Fix animal facing direction to use full angle rotation

3D models need to rotate Y by the actual movement angle, not just
0/180 degrees. Use atan2 of the XY direction vector so animals face
their actual travel direction.

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

* Fix animal rendering and remove die animation

Use sortingOrder=103 on 3D mesh renderers instead of Z offset hack
to render animals above the map. Guard against die animation state.
Default scale to 15. Remove unused run state.

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

* Disable depth test on animal renderers to prevent map clipping

When 3D animals rotate to face away, their geometry extends into
positive Z and clips behind the map plane. Setting ZTest=Always
ensures they always render on top regardless of orientation.

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

* Fix animal depth clipping with renderQueue and ZWrite/ZTest overrides

Use renderQueue=4000 (Overlay), disable ZWrite, and set ZTest=Always
via SetFloat (compatible with more shader types) to prevent 3D animal
meshes from clipping behind the map when rotated.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 21:08:55 -08:00
28560940cb Add Old Marek commentary when King's heroes depart in tutorial (#6280)
The first hero departure notification in the tutorial has no narrative
context. Old Marek now comments when a non-player faction loses a hero,
noting that Bregos has always inspired loyalty and something deeper must
be at work after the upheaval with Tarn.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 20:40:20 -08:00
38d097461d Add wandering monster animations for beast events (#6279)
* Add wandering monster animations for beast events on Eagle map

Replace generic vulture effects with animated DungeonMonsters2D monsters
for skeleton, zombie, rat, spider, demon, orc, and human-type beasts.
Each MonsterEffect spawns a group of 3 monsters that wander randomly,
idle, and occasionally attack within a province.

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

* Add ContextMenu test actions for monster effects

MonsterEffect: Test All Idle/Move/Attack/SpecialAttack
ProvinceBeastsController: Test spawn for each beast type in Motcia

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

* Spread test beast spawns across different provinces

Also add "Test All Beast Types" to spawn all 8 at once.

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

* Fix monster sprite facing direction

DungeonMonsters2D prefabs default to facing left, so invert the
X scale flip logic.

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

* Remove malformed AnimationEvents from SkeletonArcher anims

The asset pack shipped with empty functionName fields on these events,
causing "AnimationEvent has no function name specified" errors at runtime.

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

* Wire humanEffectPrefab in Gameplay scene

The HumanEffect prefab was created but never assigned to the
ProvinceBeastsController Inspector field, so human-type beasts
fell through to generic vultures.

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

* Add vampire beast type and remove unused DungeonMonsters2D assets

- Add VampireEffect prefab, code mapping, scene wiring, and test entry
- Remove Bat, Ghost, GhostKnight, and four Golem variants (animations,
  characters, PSBs) that aren't mapped to any beast type

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

* Remove DragonEffect component from monster effect prefabs

These were created by duplicating the dragon prefab, which left a
DragonEffect component that spawned an extra dragon alongside the
intended monsters.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 20:32:09 -08:00
ce6bc0b975 Update Eagle appearance trigger for Hedrick and Sadar (#6278)
* Update Eagle appearance trigger for Hedrick and Sadar expansion

Replace Bridget (faction 4) with Hedrick (faction 5) as the tutorial
antagonist, and add a second trigger path: Sadar controlling 4+ provinces.
The Eagle now appears when either Hedrick is eliminated OR the player
faction grows strong enough to warrant attention.

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

* Lower weak King province hero loyalty to 20

Makes the heroes in the King's weak provinces much more likely to
defect, as they barely have any loyalty to the King.

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

* Adjust weak King province hero loyalty to 25

Loyalty 20 was causing heroes to depart too quickly.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 20:00:05 -08:00
8ce0a18d09 Fix horseshoe print orientation and duel accepted animation (#6277)
Horseshoe prints were facing forward (open end leading) instead of
trailing behind the horse. Added 180° rotation for mounted units.

Duel accepted animation was never playing because DuelAccepted wasn't
matched as a result of the pending DuelChallenge command. Added it to
IsResultVariant and cached source/target grid indices in
PendingCommandSound so the animation plays even when units have been
removed from the model by later duel combat results in the same batch.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 19:31:18 -08:00
2befe8b67f Add tutorial-specific initial chronicle text (#6276)
* Add tutorial-specific initial chronicle text

The tutorial was using the same initial chronicle text ID as regular
games, but the text content references "The Eagle" character which
doesn't exist in the tutorial scenario. When the LLM tries to generate
a chronicle update, it looks up the previous chronicle entry's text
as a dependency, causing "Unknown dependency for LLM request" errors.

This adds a tutorial-specific chronicle text that describes the
actual tutorial scenario: Sadar Rakon defending Onmaa against
King Bregos Fyar's army led by Ikhaan Tarn.

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

* Update tutorial chronicle text wording

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 19:27:20 -08:00
76cf6f0624 Fix SupportField highlight in tutorial dialogue (#6272)
* Register SupportField dynamically for tutorial dialogue highlight

The SupportField highlight in the tutorial_rebuild_support and
tutorial_support_deadline dialogues wasn't appearing because the
static Inspector reference on TutorialTargetRegistry was not wired up.
Dynamically register the field from EagleGameController, matching the
pattern used for GoToBattleButton and CommandPanel.

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

* Fix Elena's reinforcement dialogue referencing Tarn incorrectly

Tarn and the King are still allies at this point, so "half of them
had already fled before Tarn's men even arrived" doesn't make sense.

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

* Vary Ranil's siege dialogue to avoid repeating Marek's phrasing

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

* Fix highlight not rendering inside layout groups

The dialogue highlight was invisible when targeting UI elements inside
a layout group (e.g. SupportField). The highlight container was being
treated as a layout child, which collapsed its rendering. Adding
LayoutElement with ignoreLayout=true makes it overlay correctly.

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

* Make Reset Tutorials also reset dialogue and trigger state

ResetAllProgress previously only cleared the old tutorial system's
PlayerPrefs state. Now it also clears DialogueManager's completed
script IDs and TutorialTriggerRegistry's one-shot flags, so all
narrative dialogues can replay without restarting the game.

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

* Fix NRE: add RectTransform before LayoutElement

LayoutElement is a UI component that auto-creates a RectTransform,
so the subsequent AddComponent<RectTransform>() returned null.
Reorder so RectTransform is added first.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 19:08:47 -08:00
b0c409d62c Fix support=0 not being applied to weak King provinces (#6275)
The conditional `if po.support > 0` prevented explicitly setting
support to 0. Now support always uses the JSON value directly.
Provinces 37 and 40 already have their support values specified.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 19:01:34 -08:00
b23ee1485b Simplify tutorial battle: no attackers can flee (#6274)
Remove the special case that allowed Ikhaan Tarn to flee.
Now all units in the tutorial battle must fight to the end.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-25 17:37:59 -08:00
6882 changed files with 524005 additions and 929840 deletions
+17 -2
View File
@@ -1,4 +1,4 @@
bazel-1.0.0.bazelrc
# bazel-1.0.0.bazelrc
# for now: filter out annoying TASTY warnings
common --ui_event_filters=-INFO
@@ -29,6 +29,10 @@ common --host_cxxopt="--std=c++23"
common --javacopt="-Xlint:-options"
# std::filesystem and other modern C++ deps require macOS 10.15+.
common:macos --macos_minimum_os=10.15
common:macos --host_macos_minimum_os=10.15
# suppress warnings due to https://developer.apple.com/forums/thread/733317
# Use host_linkopt for macOS-specific flags to avoid passing them to Linux cross-compilation
common:macos --host_linkopt=-Wl,-no_warn_duplicate_libraries
@@ -37,9 +41,20 @@ common:macos --host_linkopt=-Wl,-no_warn_duplicate_libraries
# See: https://github.com/grpc/grpc/issues/37619
common:macos --features=-module_maps
# Fix Xcode version caching issue - avoids need for `bazel clean --expunge` after Xcode updates
# Pin DEVELOPER_DIR so Apple repo rules use full Xcode instead of Command Line
# Tools. The sync script writes .bazelrc.xcode with an Xcode build-version
# marker so in-place Xcode updates refresh Bazel's generated Apple toolchains.
common:macos --repo_env=DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
# Local machine or CI overrides. This lets Bazel-only runners use Command Line
# Tools without installing full Xcode. This must stay before .bazelrc.xcode so
# generated Xcode settings win when both files exist.
try-import %workspace%/.bazelrc.local
# Xcode config for macOS builds. Generated by scripts/sync_bazel_xcode.sh.
# Bakes the Xcode build version into action cache keys and sets DEVELOPER_DIR.
try-import %workspace%/.bazelrc.xcode
common --java_language_version=25
common --java_runtime_version=remotejdk_25
common --tool_java_language_version=25
+11
View File
@@ -14,6 +14,17 @@ src/main/csharp/**/GUI[[:space:]]Pro[[:space:]]Kit*/**/*.ttf !filter !diff !merg
src/main/csharp/**/Modern[[:space:]]UI[[:space:]]Pack/**/*.ttf !filter !diff !merge
*.herodata filter=lfs diff=lfs merge=lfs -text
*.ogg filter=lfs diff=lfs merge=lfs -text
*.tga filter=lfs diff=lfs merge=lfs -text
*.fbx filter=lfs diff=lfs merge=lfs -text
*.FBX filter=lfs diff=lfs merge=lfs -text
*.pdf filter=lfs diff=lfs merge=lfs -text
# Third-party asset packs: track all files via LFS (never manually edited)
src/main/csharp/**/DungeonMonsters2D/** filter=lfs diff=lfs merge=lfs -text
src/main/csharp/**/Raccoon/** filter=lfs diff=lfs merge=lfs -text
src/main/csharp/**/Polytope[[:space:]]Studio/** filter=lfs diff=lfs merge=lfs -text
src/main/csharp/**/RRFreelance-Characters/** filter=lfs diff=lfs merge=lfs -text
src/main/csharp/**/Dragon/** filter=lfs diff=lfs merge=lfs -text
*.jpg filter=lfs diff=lfs merge=lfs -text
# Unity Smart Merge - use UnityYAMLMerge for Unity files
# Requires configuring unityyamlmerge in ~/.gitconfig:
+41 -4
View File
@@ -6,8 +6,44 @@ on:
- cron: '0 */6 * * *'
workflow_dispatch:
permissions:
contents: read
actions: write
jobs:
cleanup-expired:
runs-on: ubuntu-latest
steps:
- name: Delete expired artifacts and artifacts older than 3 days
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "Fetching all artifacts..."
gh api "repos/${{ github.repository }}/actions/artifacts" \
--paginate -q '.artifacts[] | "\(.id)\t\(.created_at)\t\(.expired)\t\(.name)"' > /tmp/all_artifacts.txt
total=$(wc -l < /tmp/all_artifacts.txt)
echo "Found $total total artifacts"
cutoff=$(date -u -d '3 days ago' '+%Y-%m-%dT%H:%M:%SZ')
echo "Deleting expired artifacts and artifacts created before $cutoff"
deleted=0
while IFS=$'\t' read -r id created_at expired name; do
if [[ "$expired" == "true" || "$created_at" < "$cutoff" ]]; then
gh api -X DELETE "repos/${{ github.repository }}/actions/artifacts/$id" 2>/dev/null && deleted=$((deleted + 1))
if [ $((deleted % 50)) -eq 0 ]; then
echo "Deleted $deleted artifacts so far..."
fi
fi
done < /tmp/all_artifacts.txt
echo "Cleanup complete. Deleted $deleted artifacts out of $total total."
rm -f /tmp/all_artifacts.txt
check-storage:
needs: cleanup-expired
runs-on: ubuntu-latest
steps:
@@ -15,11 +51,12 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
# Calculate total artifact storage
# Calculate active artifact storage. The artifacts API can list expired
# artifacts until they are explicitly deleted, so do not count them.
total_bytes=$(gh api "repos/${{ github.repository }}/actions/artifacts" \
--paginate -q '.artifacts[].size_in_bytes' | awk '{sum+=$1} END {print sum}')
--paginate -q '.artifacts[] | select(.expired == false) | .size_in_bytes' | awk '{sum+=$1} END {print sum}')
total_mb=$((total_bytes / 1024 / 1024))
total_mb=$(( ${total_bytes:-0} / 1024 / 1024 ))
echo "Total artifact storage: ${total_mb} MB"
# Fail if over 500MB
@@ -29,7 +66,7 @@ jobs:
echo "Largest artifacts:"
# Save to temp file to avoid SIGPIPE/broken pipe errors with head
gh api "repos/${{ github.repository }}/actions/artifacts" \
--paginate -q '.artifacts[] | "\(.size_in_bytes)\t\(.name)\t\(.created_at)"' > /tmp/artifacts.txt
--paginate -q '.artifacts[] | select(.expired == false) | "\(.size_in_bytes)\t\(.name)\t\(.created_at)"' > /tmp/artifacts.txt
sort -rn /tmp/artifacts.txt | head -20 | \
awk -F'\t' '{printf "%d MB\t%s\t%s\n", $1/1024/1024, $2, $3}'
rm -f /tmp/artifacts.txt
+16 -5
View File
@@ -11,6 +11,7 @@ on:
- 'src/main/protobuf/net/eagle0/eagle/internal/auth_internal.proto'
- 'src/main/resources/net/eagle0/attributions.json'
- 'ci/BUILD.bazel'
- 'ci/github_actions/ensure_bazel_installed.sh'
- '.bazelrc'
- '.github/workflows/auth_build.yml'
workflow_dispatch:
@@ -24,17 +25,25 @@ on:
permissions:
contents: read
concurrency:
group: auth-build-deploy
cancel-in-progress: false
jobs:
build-auth:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
outputs:
image_tag: ${{ steps.push-auth.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Build Auth Server Docker image
id: build-auth
run: |
@@ -127,10 +136,12 @@ jobs:
FASTMAIL_FROM_NAME: ${{ secrets.FASTMAIL_FROM_NAME }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Deploy auth service to production
uses: appleboy/ssh-action@v1.0.3
uses: appleboy/ssh-action@v1.2.5
with:
host: ${{ secrets.DO_DROPLET_IP }}
username: deploy
@@ -138,7 +149,7 @@ jobs:
script_stop: true
envs: AUTH_IMAGE,DISCORD_CLIENT_ID,DISCORD_CLIENT_SECRET,GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,GH_OAUTH_CLIENT_ID,GH_OAUTH_CLIENT_SECRET,APPLE_SIGNIN_CLIENT_ID,APPLE_TEAM_ID,APPLE_SIGNIN_KEY_ID,APPLE_SIGNIN_PRIVATE_KEY,TWITCH_CLIENT_ID,TWITCH_CLIENT_SECRET,JWT_PRIVATE_KEY,FASTMAIL_API_TOKEN,FASTMAIL_FROM_EMAIL,FASTMAIL_FROM_NAME
script: |
set -x
set -e
cd /opt/eagle0
# Export env vars for docker compose (appleboy/ssh-action sets them but doesn't export)
+8 -5
View File
@@ -1,19 +1,22 @@
name: Bazel Cache Cleanup
on:
schedule:
# Run weekly on Sunday at 00:00 UTC
- cron: '0 0 * * 0'
# Disabled: bazel clean fails when another runner shares the output_base
# on /Volumes/remote_cache (unlinkat "Directory not empty" race).
# See https://github.com/nolen777/eagle0/issues/TBD for details.
# schedule:
# - cron: '0 0 * * 0'
workflow_dispatch: # Allow manual trigger
jobs:
cleanup:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Show disk usage before cleanup
+47 -7
View File
@@ -9,6 +9,7 @@ on:
- 'MODULE.bazel'
- 'BUILD.bazel'
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- '.github/workflows/bazel_test.yml'
- '!src/main/csharp/**'
- '!src/test/csharp/**'
@@ -19,6 +20,7 @@ on:
- 'MODULE.bazel'
- 'BUILD.bazel'
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- '.github/workflows/bazel_test.yml'
- '!src/main/csharp/**'
- '!src/test/csharp/**'
@@ -40,14 +42,32 @@ jobs:
git config --local core.sparseCheckout false 2>/dev/null || true
git config --local --unset extensions.worktreeConfig 2>/dev/null || true
rm -f .git/info/sparse-checkout .git/config.worktree 2>/dev/null || true
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Check BUILD.bazel dependencies
run: ./scripts/check_build_deps.sh --strict
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 'lts/*'
- name: Check JavaScript syntax
@@ -62,10 +82,30 @@ jobs:
git config --local core.sparseCheckout false 2>/dev/null || true
git config --local --unset extensions.worktreeConfig 2>/dev/null || true
rm -f .git/info/sparse-checkout .git/config.worktree 2>/dev/null || true
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Run tests
run: bazel test --build_event_json_file=test.json //src/test/... //src/main/go/...
- name: Collect failed test logs
@@ -102,16 +142,16 @@ jobs:
ls -lh failed_test_logs/ 2>/dev/null || echo "No logs collected"
- name: Archive test results
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: test.json
path: test.json
retention-days: 5
retention-days: 3
- name: Archive failed test logs
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: failed-test-logs
path: failed_test_logs/
if-no-files-found: ignore
retention-days: 5
retention-days: 3
+6 -2
View File
@@ -11,14 +11,18 @@ permissions:
jobs:
cleanup:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
clean: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Clean up unreferenced blobs
env:
ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
+10 -6
View File
@@ -27,13 +27,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Build sysroot
run: ./tools/sysroot/build_sysroot.sh
- name: Upload sysroot artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: ubuntu-noble-sysroot-amd64
path: tools/sysroot/output/
@@ -81,21 +83,23 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
- name: Set up QEMU for ARM64 emulation
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@v4
with:
platforms: arm64
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Build ARM64 sysroot
run: ./tools/sysroot/build_sysroot_arm64.sh
- name: Upload sysroot artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: ubuntu-noble-sysroot-arm64
path: tools/sysroot/output/
+81 -9
View File
@@ -18,6 +18,7 @@ on:
- '!src/main/protobuf/net/eagle0/eagle/internal/auth_internal.proto'
- 'src/main/resources/**'
- 'ci/BUILD.bazel'
- 'ci/github_actions/ensure_bazel_installed.sh'
- 'MODULE.bazel'
- '.bazelrc'
- 'docker-compose.prod.yml'
@@ -40,14 +41,14 @@ concurrency:
permissions:
contents: read
actions: read
actions: write # Required to delete artifacts after deploy
jobs:
# Single consolidated build job - builds all images with one bazel invocation
# This uses 1 runner slot instead of 4, and Bazel parallelizes internally
# NOTE: Must run on a runner with the bazel label to ensure consistent Bazel cache
build-all:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
outputs:
eagle_image_tag: ${{ steps.push-images.outputs.eagle_image_tag }}
admin_image_tag: ${{ steps.push-images.outputs.admin_image_tag }}
@@ -68,15 +69,39 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
- name: Ensure Git LFS available for checkout
if: steps.check-latest.outputs.skip != 'true'
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- name: Checkout repository
if: steps.check-latest.outputs.skip != 'true'
uses: actions/checkout@v4
uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
if: steps.check-latest.outputs.skip != 'true'
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Fetch LFS files needed for admin server
if: steps.check-latest.outputs.skip != 'true'
run: git lfs pull --include="src/main/go/net/eagle0/admin_server/static/tiles/*"
env:
GITHUB_TOKEN: ${{ github.token }}
run: ./ci/github_actions/fetch_lfs.sh --include="src/main/go/net/eagle0/admin_server/static/tiles/*"
- name: Build all Docker images
if: steps.check-latest.outputs.skip != 'true'
@@ -117,7 +142,7 @@ jobs:
- name: Upload warmup binary
if: steps.check-latest.outputs.skip != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: warmup-binary
path: scripts/bin/warmup
@@ -202,7 +227,7 @@ jobs:
echo "=== All images pushed successfully ==="
deploy:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
needs: [build-all]
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
environment: production
@@ -244,9 +269,26 @@ jobs:
NOTIFY_SECRET: ${{ secrets.EAGLE_NOTIFY_SECRET }}
GITHUB_TOKEN_FOR_ADMIN: ${{ secrets.ADMIN_GITHUB_TOKEN }}
steps:
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false
- name: Setup SSH key
@@ -257,11 +299,25 @@ jobs:
ssh-keyscan -H "$DO_DROPLET_IP" >> ~/.ssh/known_hosts 2>/dev/null || true
- name: Download warmup binary
uses: actions/download-artifact@v4
id: download-warmup
continue-on-error: true
uses: actions/download-artifact@v8
with:
name: warmup-binary
path: scripts/bin/
- name: Build warmup binary fallback
if: steps.download-warmup.outcome != 'success'
run: |
echo "::warning::warmup-binary artifact was unavailable; rebuilding warmup binary before deploy"
./ci/github_actions/ensure_bazel_installed.sh
bazel build \
--platforms=//:linux_x86_64 \
--extra_toolchains=@llvm_toolchain_linux//:all \
//ci:warmup_tar
mkdir -p scripts/bin
tar -xf bazel-bin/ci/warmup_tar.tar -C scripts/bin --strip-components=1
- name: Copy config files to droplet
run: |
# Create directory structure on remote
@@ -280,7 +336,7 @@ jobs:
- name: Deploy to production droplet
run: |
ssh -i ~/.ssh/deploy_key deploy@"$DO_DROPLET_IP" bash -s << DEPLOY_SCRIPT
set -ex
set -e
cd /opt/eagle0
# =================================================================
@@ -471,3 +527,19 @@ jobs:
# Remove images older than 24h (keeps recent images for rollback)
docker image prune -a -f --filter "until=24h" || true
DEPLOY_SCRIPT
cleanup:
needs: [build-all, deploy]
if: always()
runs-on: ubuntu-latest
steps:
- name: Delete warmup-binary artifact
env:
GH_TOKEN: ${{ github.token }}
run: |
ARTIFACT_ID=$(gh api "repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts" \
-q '.artifacts[] | select(.name == "warmup-binary") | .id')
if [ -n "$ARTIFACT_ID" ]; then
echo "Deleting warmup-binary artifact (ID: $ARTIFACT_ID)"
gh api -X DELETE "repos/${{ github.repository }}/actions/artifacts/$ARTIFACT_ID" || true
fi
+22 -1
View File
@@ -11,6 +11,7 @@ on:
- 'MODULE.bazel'
- 'BUILD.bazel'
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- '.github/workflows/eagle_build.yml'
concurrency:
@@ -25,9 +26,29 @@ jobs:
runs-on: [self-hosted, bazel]
steps:
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Build Eagle server
run: bazel build //src/main/scala/net/eagle0/eagle:eagle_server
+25 -2
View File
@@ -5,10 +5,12 @@ on:
branches: [ "main" ]
paths:
- ".github/workflows/installer_build.yml"
- "ci/github_actions/ensure_bazel_installed.sh"
- "src/main/go/net/eagle0/clients/win/installer/**"
pull_request:
paths:
- ".github/workflows/installer_build.yml"
- "ci/github_actions/ensure_bazel_installed.sh"
- "src/main/go/net/eagle0/clients/win/installer/**"
workflow_dispatch:
@@ -21,11 +23,32 @@ jobs:
runs-on: [self-hosted, bazel]
steps:
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
clean: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Build Go installer for Windows
env:
MANIFEST_PUBLIC_KEY: ${{ secrets.MANIFEST_PUBLIC_KEY }}
@@ -50,7 +73,7 @@ jobs:
- name: Archive installer binary
if: success() || failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: eagle-installer
path: ./installer-output/
@@ -1,98 +0,0 @@
name: iOS Addressables Build
on:
push:
branches: [ "main" ]
paths:
- ".github/workflows/ios_addressables_build.yml"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/AddressableAssetsData/**"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Music/**"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Editor/BuildScript.cs"
- "ci/github_actions/build_ios_addressables.sh"
- "ci/github_actions/upload_addressables.sh"
pull_request:
paths:
- ".github/workflows/ios_addressables_build.yml"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/AddressableAssetsData/**"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Music/**"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Editor/BuildScript.cs"
- "ci/github_actions/build_ios_addressables.sh"
- "ci/github_actions/upload_addressables.sh"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
env:
# Runner-specific build directory to allow parallel builds on multiple runners
EAGLE0_BUILD_DIR: /tmp/eagle0-${{ github.run_id }}
jobs:
build-ios-addressables:
runs-on: [self-hosted, macOS, unity-mac]
steps:
- name: Prune stale PR refs
run: |
# Self-hosted runners persist .git between runs. When a PR is updated,
# old local refs (refs/remotes/pull/*/merge) may point to commits whose
# objects were never fetched or have been pruned. Remove these stale refs
# before checkout to prevent "missing object" errors.
if [ -d ".git" ]; then
echo "Pruning stale PR refs..."
git for-each-ref --format='%(refname)' refs/remotes/pull/ 2>/dev/null | \
xargs -r git update-ref -d 2>/dev/null || true
fi
- uses: actions/checkout@v4
with:
lfs: false # Fetch LFS after checkout to avoid stale ref issues
clean: false # Library/ persists between runs on self-hosted runners
- name: Clean stale files
run: |
git clean -ffd
rm -rf src/main/csharp/net/eagle0/clients/unity/eagle0/Library/Bee/
- name: Fetch LFS files
run: |
git lfs install
git lfs pull
- name: Ensure Unity version installed
run: ./ci/github_actions/ensure_unity_installed.sh ios
- name: Build iOS Addressables
run: ./ci/github_actions/build_ios_addressables.sh "$EAGLE0_BUILD_DIR/editor_ios_addressables.log"
- name: Upload Addressables to CDN
if: success() && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
env:
ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
run: ./ci/github_actions/upload_addressables.sh iOS
- name: Purge CDN cache for iOS addressables
if: success() && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
env:
DO_CDN_PAT: ${{ secrets.DO_CDN_PAT }}
run: |
curl -s -X DELETE "https://api.digitalocean.com/v2/cdn/endpoints/8c98df29-6f0c-4704-8e82-ca40a2b81aa8/cache" \
-H "Authorization: Bearer $DO_CDN_PAT" \
-H "Content-Type: application/json" \
-d '{"files": ["addressables/iOS/*"]}' \
--fail || echo "Warning: CDN purge failed (non-fatal)"
- name: Archive Build Log
if: success() || failure()
uses: actions/upload-artifact@v4
with:
name: editor_ios_addressables.log
path: ${{ env.EAGLE0_BUILD_DIR }}/editor_ios_addressables.log
retention-days: 5
- name: Cleanup build directory
if: always()
run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"
+189 -9
View File
@@ -1,6 +1,8 @@
name: iOS TestFlight
on:
schedule:
- cron: '0 5 * * *' # 9 PM Pacific (UTC-8) / 10 PM PDT (UTC-7)
workflow_dispatch:
inputs:
skip_upload:
@@ -11,6 +13,7 @@ on:
permissions:
contents: read
actions: write
env:
# Runner-specific build directory to allow parallel builds on multiple runners
@@ -19,8 +22,93 @@ env:
KEYCHAIN_NAME: ios-build-${{ github.run_id }}.keychain
jobs:
check-changes:
# Skip nightly builds when nothing has changed since the last successful
# scheduled run. Manual workflow_dispatch always builds.
runs-on: ubuntu-latest
outputs:
should_build: ${{ steps.check.outputs.should_build }}
steps:
- name: Check for relevant changes since last successful run
id: check
uses: actions/github-script@v8
with:
script: |
if (context.eventName === 'workflow_dispatch') {
core.setOutput('should_build', 'true');
console.log('Manual trigger — building');
return;
}
const { data: { workflow_runs: runs } } = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'ios_testflight.yml',
status: 'success',
event: 'schedule',
per_page: 1,
});
if (runs.length === 0) {
core.setOutput('should_build', 'true');
console.log('No previous successful scheduled run — building');
return;
}
const lastSha = runs[0].head_sha;
console.log(`Last successful scheduled run: ${lastSha}`);
console.log(`Current SHA: ${context.sha}`);
if (lastSha === context.sha) {
core.setOutput('should_build', 'false');
console.log('No changes since last successful run — skipping');
return;
}
// Paths that can affect the iOS Unity build.
const relevantPrefixes = [
'src/main/csharp/', // Unity project
'src/main/protobuf/', // Generates C# code
'src/main/resources/', // Game data & maps
'scripts/', // Build scripts
'ci/', // CI scripts & workflows
'.github/workflows/ios_testflight.yml',
'MODULE.bazel',
'.bazelrc',
];
const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({
owner: context.repo.owner,
repo: context.repo.repo,
basehead: `${lastSha}...${context.sha}`,
per_page: 1, // We only need the file list, not patches
});
// If the diff is too large, build to be safe
if (comparison.files === undefined) {
core.setOutput('should_build', 'true');
console.log('Could not retrieve file list — building to be safe');
return;
}
const relevant = comparison.files.filter(f =>
relevantPrefixes.some(p => f.filename.startsWith(p))
);
if (relevant.length > 0) {
core.setOutput('should_build', 'true');
console.log(`${relevant.length} relevant file(s) changed:`);
relevant.slice(0, 20).forEach(f => console.log(` ${f.filename}`));
if (relevant.length > 20) console.log(` ... and ${relevant.length - 20} more`);
} else {
core.setOutput('should_build', 'false');
console.log(`${comparison.files.length} file(s) changed, none in relevant paths — skipping`);
}
build-unity:
runs-on: [self-hosted, macOS, testflight]
needs: check-changes
if: needs.check-changes.outputs.should_build == 'true'
runs-on: [self-hosted, macOS, testflight, halfdan]
steps:
- name: Prune stale PR refs
@@ -34,8 +122,26 @@ jobs:
git for-each-ref --format='%(refname)' refs/remotes/pull/ 2>/dev/null | \
xargs -r git update-ref -d 2>/dev/null || true
fi
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false # Fetch LFS after checkout to avoid stale ref issues
clean: false # Library/ persists between runs on self-hosted runners
fetch-depth: 0
@@ -46,9 +152,9 @@ jobs:
rm -rf src/main/csharp/net/eagle0/clients/unity/eagle0/Library/Bee/
- name: Fetch LFS files
run: |
git lfs install
git lfs pull
env:
GITHUB_TOKEN: ${{ github.token }}
run: ./ci/github_actions/fetch_lfs.sh
- name: Ensure Unity version installed
run: ./ci/github_actions/ensure_unity_installed.sh ios
@@ -78,17 +184,81 @@ jobs:
- name: Archive Build Log
if: success() || failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: editor_ios.log
path: ${{ env.EAGLE0_BUILD_DIR }}/editor_ios.log
retention-days: 5
retention-days: 3
- name: Package generated iOS project
if: success()
run: |
tar -czf "$RUNNER_TEMP/eagle0-ios-project.tar.gz" -C "$EAGLE0_BUILD_DIR" eagle0iOS
- name: Upload generated iOS project
if: success()
uses: actions/upload-artifact@v7
with:
name: eagle0-ios-project-${{ github.run_id }}
path: ${{ runner.temp }}/eagle0-ios-project.tar.gz
retention-days: 1
- name: Cleanup build directory
if: always()
run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"
archive-and-upload:
needs: build-unity
runs-on: [self-hosted, macOS, testflight]
runs-on: [self-hosted, macOS, testflight, halfdan]
steps:
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false
- name: Clean build directory
run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"
- name: Download generated iOS project
uses: actions/download-artifact@v8
with:
name: eagle0-ios-project-${{ github.run_id }}
path: ${{ runner.temp }}
- name: Extract generated iOS project
run: |
mkdir -p "$EAGLE0_BUILD_DIR"
tar -xzf "$RUNNER_TEMP/eagle0-ios-project.tar.gz" -C "$EAGLE0_BUILD_DIR"
- name: Delete generated iOS project artifact
env:
GH_TOKEN: ${{ github.token }}
run: |
artifact_id=$(gh api "repos/${{ github.repository }}/actions/artifacts" \
--paginate \
--jq '.artifacts[] | select(.name == "eagle0-ios-project-${{ github.run_id }}") | .id')
if [ -n "$artifact_id" ]; then
gh api -X DELETE "repos/${{ github.repository }}/actions/artifacts/$artifact_id"
fi
- name: Install Signing Certificate
env:
IOS_CERTIFICATE: ${{ secrets.IOS_CERTIFICATE }}
@@ -140,10 +310,20 @@ jobs:
- name: Archive and Export IPA
env:
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APP_STORE_CONNECT_API_KEY_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_ID }}
APP_STORE_CONNECT_API_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_API_ISSUER_ID }}
APP_STORE_CONNECT_API_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY }}
run: |
# Write API key to file for xcodebuild
API_KEY_PATH=$(mktemp)
echo "$APP_STORE_CONNECT_API_KEY" > "$API_KEY_PATH"
export APP_STORE_CONNECT_API_KEY_PATH="$API_KEY_PATH"
chmod +x ./ci/github_actions/archive_ios.sh
./ci/github_actions/archive_ios.sh "$EAGLE0_BUILD_DIR/eagle0iOS" "$EAGLE0_BUILD_DIR/archive" "$APPLE_TEAM_ID" "$PROFILE_UUID"
rm -f "$API_KEY_PATH"
- name: Upload to TestFlight
if: ${{ github.event.inputs.skip_upload != 'true' }}
env:
@@ -168,7 +348,7 @@ jobs:
- name: Upload IPA artifact
# Only keep artifact if we skipped TestFlight upload (for debugging)
if: success() && github.event.inputs.skip_upload == 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: eagle0-ios-${{ github.run_id }}
path: ${{ env.EAGLE0_BUILD_DIR }}/archive/eagle0.ipa
+85 -16
View File
@@ -20,6 +20,7 @@ on:
- "scripts/notarize_wait.sh"
- "ci/github_actions/build_mac.sh"
- "ci/github_actions/build_unity_mac.sh"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/github_actions/upload_addressables.sh"
- "ci/github_actions/ensure_unity_installed.sh"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt"
@@ -32,12 +33,14 @@ on:
- "src/main/go/net/eagle0/build/mac_build_handler/**"
- "scripts/build_mac_plugin.sh"
- "scripts/build_sparkle_plugin.sh"
- "src/main/objc/net/eagle0/clients/unity/sparkle/**"
- "scripts/inject_sparkle.sh"
- "scripts/codesign_mac_app.sh"
- "scripts/notarize_submit.sh"
- "scripts/notarize_wait.sh"
- "ci/github_actions/build_mac.sh"
- "ci/github_actions/build_unity_mac.sh"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/mac/**"
workflow_dispatch:
inputs:
@@ -63,7 +66,7 @@ env:
jobs:
build-and-sign:
runs-on: [self-hosted, macOS, unity-mac]
runs-on: [self-hosted, macOS, unity-mac, halfdan]
outputs:
submission_id: ${{ steps.notarize-submit.outputs.submission_id }}
should_deploy: ${{ steps.check-deploy.outputs.should_deploy }}
@@ -80,8 +83,26 @@ jobs:
git for-each-ref --format='%(refname)' refs/remotes/pull/ 2>/dev/null | \
xargs -r git update-ref -d 2>/dev/null || true
fi
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false # Fetch LFS after checkout to avoid stale ref issues
clean: false # Library/ persists between runs on self-hosted runners
fetch-depth: 0 # For version numbering from git history
@@ -108,19 +129,27 @@ jobs:
fi
- name: Fetch LFS files
run: |
git lfs install
git lfs pull
env:
GITHUB_TOKEN: ${{ github.token }}
run: ./ci/github_actions/fetch_lfs.sh
- name: Ensure Unity version installed
run: ./ci/github_actions/ensure_unity_installed.sh mac
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Sync Bazel Xcode config
run: ./scripts/sync_bazel_xcode.sh
- name: Build Mac Unity
run: ./ci/github_actions/build_unity_mac.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC"
- name: Save build SHA for Bee/ cache invalidation
if: success()
run: git rev-parse HEAD > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha
run: |
mkdir -p src/main/csharp/net/eagle0/clients/unity/eagle0/Library
git rev-parse HEAD > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha
- name: Upload Addressables to CDN
if: success() && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
@@ -225,7 +254,7 @@ jobs:
- name: Upload signed app
if: success() && steps.check-deploy.outputs.should_deploy == 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: signed-mac-app-${{ github.run_id }}
path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app.zip
@@ -233,11 +262,11 @@ jobs:
- name: Archive Build Log
if: success() || failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: editor_mac.log
path: ${{ env.EAGLE0_BUILD_DIR }}/editor_mac.log
retention-days: 5
retention-days: 3
- name: Cleanup build directory
if: always()
run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"
@@ -245,18 +274,35 @@ jobs:
wait-notarization:
needs: build-and-sign
if: needs.build-and-sign.outputs.should_deploy == 'true'
runs-on: [self-hosted, macOS, notarize]
runs-on: [self-hosted, macOS, notarize, halfdan]
steps:
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
sparse-checkout: scripts
- name: Clean download directory
run: rm -rf ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
- name: Download signed app
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
name: signed-mac-app-${{ github.run_id }}
path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
@@ -284,7 +330,7 @@ jobs:
ditto -c -k --keepParent eagle0.app eagle0.app.zip
- name: Upload notarized app
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: notarized-mac-app-${{ github.run_id }}
path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC/eagle0.app.zip
@@ -296,20 +342,37 @@ jobs:
deploy:
needs: [build-and-sign, wait-notarization]
if: needs.build-and-sign.outputs.should_deploy == 'true'
runs-on: [self-hosted, macOS, unity-mac]
runs-on: [self-hosted, macOS, notarize, halfdan]
outputs:
deployed_version: ${{ steps.deploy-mac.outputs.deployed_version }}
steps:
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
fetch-depth: 0 # For version numbering
- name: Clean download directory
run: rm -rf ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
- name: Download notarized app
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
name: notarized-mac-app-${{ github.run_id }}
path: ${{ env.EAGLE0_BUILD_DIR }}/eagle0MAC
@@ -320,6 +383,12 @@ jobs:
ditto -x -k eagle0.app.zip .
rm eagle0.app.zip
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Sync Bazel Xcode config
run: ./scripts/sync_bazel_xcode.sh
- name: Deploy Mac Build
id: deploy-mac
env:
+20 -5
View File
@@ -39,9 +39,9 @@ jobs:
echo "Dry run: ${DRY_RUN}"
echo ""
# List of repositories to clean
# Use tail to skip header row in case --no-header doesn't work
REPOS=$(doctl registry repository list-v2 --format Name --no-header | grep -v '^Name$' | grep -v '^$')
# List repositories via JSON. Text output can wrap table rows and make
# headers/tags/digests look like repository names.
REPOS=$(doctl registry repository list-v2 "${REGISTRY}" --output json | jq -r '.[] | .name // .Name // empty')
for REPO in $REPOS; do
echo "=== Processing repository: ${REPO} ==="
@@ -88,5 +88,20 @@ jobs:
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run == 'false')
run: |
echo "Starting garbage collection..."
doctl registry garbage-collection start --force
echo "Garbage collection started. It may take a few minutes to complete."
set +e
GC_OUTPUT=$(doctl registry garbage-collection start --force 2>&1)
GC_STATUS=$?
set -e
echo "$GC_OUTPUT"
if [ "$GC_STATUS" -eq 0 ]; then
echo "Garbage collection started. It may take a few minutes to complete."
exit 0
fi
if echo "$GC_OUTPUT" | grep -q "automated garbage collection is enabled"; then
echo "Automated garbage collection is enabled for this registry; skipping manual garbage collection."
exit 0
fi
exit "$GC_STATUS"
+86
View File
@@ -0,0 +1,86 @@
name: S3 Archive Cleanup
on:
schedule:
# Run weekly on Sunday at 05:00 UTC
- cron: '0 5 * * 0'
workflow_dispatch: # Allow manual trigger
permissions:
contents: read
jobs:
cleanup:
runs-on: [self-hosted, bazel, halfdan]
steps:
- name: Ensure AWS CLI is available
run: |
if ! command -v aws &> /dev/null; then
brew install awscli
fi
- name: Delete old archived game folders
env:
AWS_ACCESS_KEY_ID: ${{ secrets.DO_SPACES_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.DO_SPACES_SECRET_KEY }}
run: |
set -euo pipefail
S3_ENDPOINT="https://sfo3.digitaloceanspaces.com"
BUCKET="s3://eagle0/eagle/archived/"
# macOS date syntax
CUTOFF=$(date -v-1m +%s)
DELETED=0
SKIPPED=0
NO_DIR_FILE=0
echo "Cutoff date: $(date -r ${CUTOFF} '+%Y-%m-%dT%H:%M:%S')"
echo ""
FOLDERS=$(aws s3 ls "$BUCKET" --endpoint-url "$S3_ENDPOINT" \
| awk '/PRE/{gsub(/\/$/,"",$2); print $2}')
if [ -z "$FOLDERS" ]; then
echo "No archived folders found."
exit 0
fi
TOTAL=$(echo "$FOLDERS" | wc -l | tr -d ' ')
CURRENT=0
for game_id in $FOLDERS; do
CURRENT=$((CURRENT + 1))
DIR_INFO=$(aws s3 ls "${BUCKET}${game_id}/directory.e0i" \
--endpoint-url "$S3_ENDPOINT" 2>/dev/null || true)
if [ -z "$DIR_INFO" ]; then
echo "[$CURRENT/$TOTAL] DELETE $game_id (no directory.e0i)"
aws s3 rm --recursive "${BUCKET}${game_id}/" \
--endpoint-url "$S3_ENDPOINT" > /dev/null 2>&1
DELETED=$((DELETED + 1))
NO_DIR_FILE=$((NO_DIR_FILE + 1))
continue
fi
FILE_DATE=$(echo "$DIR_INFO" | awk '{print $1 " " $2}')
FILE_EPOCH=$(date -j -f '%Y-%m-%d %H:%M:%S' "$FILE_DATE" +%s 2>/dev/null || echo "0")
if [ "$FILE_EPOCH" -lt "$CUTOFF" ]; then
echo "[$CURRENT/$TOTAL] DELETE $game_id (directory.e0i from $FILE_DATE)"
aws s3 rm --recursive "${BUCKET}${game_id}/" \
--endpoint-url "$S3_ENDPOINT" > /dev/null 2>&1
DELETED=$((DELETED + 1))
else
echo "[$CURRENT/$TOTAL] KEEP $game_id (directory.e0i from $FILE_DATE)"
SKIPPED=$((SKIPPED + 1))
fi
done
echo ""
echo "=== Summary ==="
echo "Total folders: $TOTAL"
echo "Deleted: $DELETED"
echo "Kept (recent): $SKIPPED"
+53 -25
View File
@@ -9,6 +9,7 @@ on:
- 'src/main/protobuf/net/eagle0/common/**'
- 'src/main/resources/net/eagle0/shardok/**'
- 'ci/BUILD.bazel'
- 'ci/github_actions/ensure_bazel_installed.sh'
- 'MODULE.bazel'
- '.bazelrc'
- '.github/workflows/shardok_arm64_build.yml'
@@ -29,15 +30,19 @@ permissions:
jobs:
build-shardok-arm64:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
outputs:
image_tag: ${{ steps.push-shardok.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Build Shardok ARM64 binary (cross-compile for Linux ARM64)
run: |
set -ex
@@ -165,7 +170,7 @@ jobs:
echo "Also tagged as: registry.digitalocean.com/eagle0/shardok-server:arm64-latest"
deploy-hetzner:
runs-on: [self-hosted, bazel]
runs-on: [self-hosted, bazel, halfdan]
needs: [build-shardok-arm64]
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
environment: production
@@ -180,33 +185,55 @@ jobs:
# Add host key to known_hosts to avoid prompt
ssh-keyscan -H ${{ secrets.HETZNER_IP }} >> ~/.ssh/known_hosts 2>/dev/null || true
- name: Pull Shardok image tarball for Hetzner
env:
DO_REGISTRY_TOKEN: ${{ secrets.DO_REGISTRY_TOKEN }}
run: |
set -ex
# Hetzner is IPv6-only, while Docker can be redirected to IPv4-only
# DigitalOcean registry/blob endpoints. Pull on the runner and copy
# the Docker-loadable tarball over SSH instead.
CRANE_VERSION="v0.20.2"
CRANE_DIR="${HOME}/.local/bin"
CRANE="${CRANE_DIR}/crane"
if [ ! -x "$CRANE" ] || ! "$CRANE" version 2>/dev/null | grep -q "0.20.2"; then
echo "Installing crane ${CRANE_VERSION}..."
mkdir -p "$CRANE_DIR"
curl -sL "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/go-containerregistry_Darwin_arm64.tar.gz" | tar xzf - -C "$CRANE_DIR" crane
chmod +x "$CRANE"
else
echo "Using cached crane at $CRANE"
fi
AUTH=$(echo -n "${DO_REGISTRY_TOKEN}:${DO_REGISTRY_TOKEN}" | base64)
mkdir -p ~/.docker
echo "{\"auths\":{\"registry.digitalocean.com\":{\"auth\":\"${AUTH}\"}}}" > ~/.docker/config.json
IMAGE_TAR="${RUNNER_TEMP}/shardok-arm64-image.tar"
"$CRANE" pull "${SHARDOK_IMAGE}" "$IMAGE_TAR"
echo "SHARDOK_IMAGE_TAR=$IMAGE_TAR" >> "$GITHUB_ENV"
- name: Copy Shardok image tarball to Hetzner
run: |
set -ex
ssh -i ~/.ssh/hetzner_deploy -o StrictHostKeyChecking=accept-new deploy@${{ secrets.HETZNER_IP }} \
"cat > /tmp/shardok-arm64-image.tar" < "$SHARDOK_IMAGE_TAR"
- name: Deploy to Hetzner
run: |
ssh -i ~/.ssh/hetzner_deploy -o StrictHostKeyChecking=accept-new deploy@${{ secrets.HETZNER_IP }} << 'ENDSSH'
set -ex
cd /opt/eagle0
# Login to registry
echo "${{ secrets.DO_REGISTRY_TOKEN }}" | docker login registry.digitalocean.com -u "${{ secrets.DO_REGISTRY_TOKEN }}" --password-stdin
echo "Deploying Shardok ARM64: ${{ needs.build-shardok-arm64.outputs.image_tag }}"
# Pre-warm NAT64 path to DigitalOcean registry (IPv6-only Hetzner → IPv4 registry)
curl -sf --max-time 10 https://registry.digitalocean.com/v2/ > /dev/null 2>&1 || true
# Pull the new image (retry up to 3 times for NAT64 connectivity flakiness)
for attempt in 1 2 3; do
echo "Pull attempt $attempt..."
if docker pull "${{ needs.build-shardok-arm64.outputs.image_tag }}"; then
break
fi
if [ "$attempt" -eq 3 ]; then
echo "ERROR: docker pull failed after 3 attempts"
exit 1
fi
echo "Pull failed, retrying in 10s..."
sleep 10
done
SHARDOK_IMAGE="${{ needs.build-shardok-arm64.outputs.image_tag }}"
echo "Loading Shardok ARM64 image: $SHARDOK_IMAGE"
docker load -i /tmp/shardok-arm64-image.tar
rm -f /tmp/shardok-arm64-image.tar
docker image inspect "$SHARDOK_IMAGE" > /dev/null
echo "Loaded image ID: $(docker image inspect --format '{{.Id}}' "$SHARDOK_IMAGE")"
echo "Shardok binary SHA256:"
docker run --rm --entrypoint sha256sum "$SHARDOK_IMAGE" /app/shardok-server
# Stop and remove any container using port 40042 or named shardok*
docker ps -q --filter "publish=40042" | xargs -r docker stop
@@ -224,11 +251,12 @@ jobs:
-v /usr/local/share/eagle0:/usr/local/share/eagle0:ro \
-e SHARDOK_RESOURCES_PATH=/app/resources \
-e SHARDOK_MAPS_PATH=/app/resources/maps \
"${{ needs.build-shardok-arm64.outputs.image_tag }}"
"$SHARDOK_IMAGE"
# Wait and verify
sleep 5
docker ps | grep shardok-ai
echo "Running container image ID: $(docker inspect --format '{{.Image}}' shardok-ai)"
# Cleanup old images
docker image prune -f
+24 -3
View File
@@ -5,13 +5,14 @@ on:
pull_request:
paths:
- 'src/main/cpp/**'
- 'src/main/proto/net/eagle0/shardok/**'
- 'src/main/proto/net/eagle0/common/**'
- 'src/main/protobuf/net/eagle0/shardok/**'
- 'src/main/protobuf/net/eagle0/common/**'
- 'src/main/go/net/eagle0/build/**'
- 'WORKSPACE'
- 'MODULE.bazel'
- 'BUILD.bazel'
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- '.github/workflows/shardok_build.yml'
concurrency:
@@ -26,9 +27,29 @@ jobs:
runs-on: [self-hosted, bazel]
steps:
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Build Shardok server
run: bazel build -c opt //src/main/cpp/net/eagle0/shardok:shardok-server
+71 -14
View File
@@ -15,6 +15,8 @@ on:
- "scripts/build_plugins.sh"
- "scripts/build_windows_plugin.sh"
- "ci/github_actions/build_unity.sh"
- "ci/github_actions/test_unity_editmode.sh"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/github_actions/upload_addressables.sh"
- "ci/github_actions/ensure_unity_installed.sh"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt"
@@ -34,6 +36,8 @@ on:
- "scripts/build_plugins.sh"
- "scripts/build_windows_plugin.sh"
- "ci/github_actions/build_unity.sh"
- "ci/github_actions/test_unity_editmode.sh"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/github_actions/upload_addressables.sh"
- "ci/github_actions/ensure_unity_installed.sh"
- "src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt"
@@ -53,7 +57,7 @@ env:
jobs:
windows-unity:
runs-on: [self-hosted, macOS, unity-windows]
runs-on: [self-hosted, macOS, unity-windows, halfdan]
outputs:
deployed_version: ${{ steps.get-version.outputs.deployed_version }}
@@ -69,44 +73,88 @@ jobs:
git for-each-ref --format='%(refname)' refs/remotes/pull/ 2>/dev/null | \
xargs -r git update-ref -d 2>/dev/null || true
fi
- uses: actions/checkout@v4
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
if ! command -v git-lfs >/dev/null 2>&1; then
brew install git-lfs
fi
git-lfs --version
- uses: actions/checkout@v6
env:
GIT_LFS_SKIP_SMUDGE: 1
with:
persist-credentials: false
lfs: false # Fetch LFS after checkout to avoid stale ref issues
clean: false # Library/ persists between runs on self-hosted runners
- name: Clean stale files
run: |
git clean -ffd
LIBRARY_DIR="src/main/csharp/net/eagle0/clients/unity/eagle0/Library"
VERSION_CACHE="$LIBRARY_DIR/.last_unity_version"
PROJECT_VERSION_FILE="src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt"
CURRENT_VERSION=$(grep "m_EditorVersion:" "$PROJECT_VERSION_FILE" | head -1 | sed 's/m_EditorVersion: //')
# Nuke Library/ when Unity version changes to avoid import loops
if [ -f "$VERSION_CACHE" ]; then
CACHED_VERSION=$(cat "$VERSION_CACHE")
if [ "$CACHED_VERSION" != "$CURRENT_VERSION" ]; then
echo "Unity version changed ($CACHED_VERSION -> $CURRENT_VERSION) -- clearing Library/"
rm -rf "$LIBRARY_DIR"
fi
fi
# Only clear Bee/ when C# files were added/deleted/renamed (structural
# changes that stale the DAG). Content-only modifications are handled by
# Bee's incremental compilation. See persist_library.sh for background.
BEE_DIR="src/main/csharp/net/eagle0/clients/unity/eagle0/Library/Bee"
SHA_FILE="src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha"
BEE_DIR="$LIBRARY_DIR/Bee"
SHA_FILE="$LIBRARY_DIR/.last_built_sha"
if [ -f "$SHA_FILE" ] && [ -d "$BEE_DIR" ]; then
LAST_SHA=$(cat "$SHA_FILE")
if git diff --diff-filter=ADR --name-only "$LAST_SHA" HEAD -- '*.cs' '*.csproj' '*.asmdef' 2>/dev/null | grep -q .; then
echo "C# files added/deleted/renamed since $LAST_SHA clearing Bee/"
echo "C# files added/deleted/renamed since $LAST_SHA -- clearing Bee/"
rm -rf "$BEE_DIR"
else
echo "No structural C# changes since $LAST_SHA keeping Bee/"
echo "No structural C# changes since $LAST_SHA -- keeping Bee/"
fi
else
echo "No previous build SHA or no Bee/ clearing Bee/ as safe default"
echo "No previous build SHA or no Bee/ -- clearing Bee/ as safe default"
rm -rf "$BEE_DIR"
fi
- name: Fetch LFS files
run: |
git lfs install
git lfs pull
env:
GITHUB_TOKEN: ${{ github.token }}
run: ./ci/github_actions/fetch_lfs.sh
- name: Ensure Unity version installed
run: ./ci/github_actions/ensure_unity_installed.sh windows
- name: Ensure Bazel installed
run: ./ci/github_actions/ensure_bazel_installed.sh
- name: Run Unity EditMode tests
run: ./ci/github_actions/test_unity_editmode.sh
- name: Build Windows unity
run: ./ci/github_actions/build_unity.sh "${{ env.EAGLE0_BUILD_DIR }}/eagle0WIN"
- name: Save build SHA for Bee/ cache invalidation
if: success()
run: git rev-parse HEAD > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha
run: |
mkdir -p src/main/csharp/net/eagle0/clients/unity/eagle0/Library
git rev-parse HEAD > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_built_sha
- name: Save Unity version for Library/ cache invalidation
if: success()
run: |
mkdir -p src/main/csharp/net/eagle0/clients/unity/eagle0/Library
grep "m_EditorVersion:" src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt | head -1 | sed 's/m_EditorVersion: //' > src/main/csharp/net/eagle0/clients/unity/eagle0/Library/.last_unity_version
- name: Upload Addressables to CDN
if: success() && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
@@ -154,11 +202,20 @@ jobs:
- name: Archive build log
if: success() || failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: editor_win.log
path: ${{ env.EAGLE0_BUILD_DIR }}/editor_win.log
retention-days: 5
retention-days: 3
- name: Archive EditMode test artifacts
if: success() || failure()
uses: actions/upload-artifact@v7
with:
name: unity_editmode_tests
path: |
${{ env.EAGLE0_BUILD_DIR }}/editor_editmode_tests.log
${{ env.EAGLE0_BUILD_DIR }}/editmode-test-results.xml
retention-days: 3
- name: Cleanup build directory
if: always()
run: rm -rf "${{ env.EAGLE0_BUILD_DIR }}"
@@ -174,4 +231,4 @@ jobs:
run: |
curl -X POST "https://admin.eagle0.net/notify-update?platform=windows&version=${{ needs.windows-unity.outputs.deployed_version }}&required=false" \
-H "X-Notify-Secret: $NOTIFY_SECRET" \
--fail --silent --show-error || echo "Warning: Failed to notify clients (non-fatal)"
--fail --silent --show-error || echo "Warning: Failed to notify clients (non-fatal)"
+4
View File
@@ -23,6 +23,8 @@ bazel-bin
bazel-eagle0*
bazel-out
bazel-testlogs
.bazelrc.local
.bazelrc.xcode
.ijwb
.clwb
buildWin.sh
@@ -42,3 +44,5 @@ src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Plugins/Eagle0Protos/
src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/Packages/com.unity.dedicated-server/
node_modules/
tools/map_generator/output/
src/main/csharp/net/eagle0/clients/unity/eagle0/docs/generated/unity_asset_usage_audit_files.csv
src/main/csharp/net/eagle0/clients/unity/eagle0/docs/generated/unity_lfs_asset_audit.csv
+12 -3
View File
@@ -14,7 +14,16 @@ repos:
- id: clang-format
args: [-i, --no-diff]
types_or: ["c++", "c#"]
exclude: ^src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Plugins
exclude: >-
(?x)^src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/(
Plugins|
DungeonMonsters2D|
Dragon|
ithappy|
Polytope\ Studio|
RRFreelance-Characters|
Raccoon
)/
- repo: https://github.com/yoheimuta/protolint
rev: v0.42.2
hooks:
@@ -25,8 +34,8 @@ repos:
hooks:
- id: scalafmt
name: scalafmt
language: system
entry: scalafmt -i -f
language: system
entry: ./scripts/pre-commit-scalafmt.sh
types_or: ["scala"]
- repo: local
hooks:
+380
View File
@@ -0,0 +1,380 @@
# AGENTS.md
## CRITICAL BASH RULES (NEVER VIOLATE)
**NEVER chain bash commands.** Do not use `&&`, `||`, or `;` to combine commands. Each command must be a separate Bash tool call. Use parallel tool calls when commands are independent.
**NEVER prefix a command with `cd`.** Run `git`, `gh`, `bazel`, etc. directly from whatever the cwd already is. The cwd is a subdirectory of the worktree; `git`/`gh` find the repo via `.git` discovery and `bazel` finds the workspace via MODULE.bazel discovery — walking up from a subdir works fine. The shell resets cwd after every command anyway, so a `cd` never persists. (And `cd <dir> && <cmd>` violates the no-chaining rule above and forces an approval prompt every time.) Only `cd` in the rare case a tool genuinely cannot locate its root, and even then as its own Bash call, never a chain.
## CRITICAL GIT RULES (NEVER VIOLATE)
**NEVER use `git -C`.** Just run `git` directly from the cwd — it finds the repo via `.git` discovery. Do not `cd` to the repo root either (see the no-`cd` bash rule above).
**NEVER push directly to main/master.** No exceptions. Not for "small changes." Not for docs. Not ever.
**NEVER merge PRs.** You create PRs. The user merges them. No exceptions.
**ALWAYS use this workflow:**
1. Create a feature branch from origin/main
2. Commit to that branch
3. Create a PR with `gh pr create`
4. Wait for user to merge (DO NOT run `gh pr merge`)
If you catch yourself about to run `git push origin main` or `git push origin <branch>:main`, STOP. You are about to violate a critical rule. Create a PR instead.
If you catch yourself about to run `gh pr merge`, STOP. Only the user merges PRs.
## Worktree Usage
Prefer using the current worktree for small requested fixes. Create a separate worktree only when the user asks for one,
when the current branch/state would make the change unsafe, or when isolating a large/risky change is clearly beneficial.
**NEVER leave the current worktree without explicit user approval.** Do not create, switch to, edit, commit in, or run
git commands from another worktree unless the user has specifically asked for that worktree or approved the move. If the
current worktree is unsafe because of dirty state, report that and ask before using a different worktree.
Codex may edit code and run git commands in the current worktree, even when unrelated files are dirty, as long as it:
- does not revert, reset, clean, or overwrite unrelated changes
- stages only the files relevant to the requested change
- verifies the staged diff before committing
- creates feature branches and PRs as usual
- does not push to main/master or merge PRs
When the user says a Codex-created PR has been merged, delete the corresponding local branch and temporary worktree
automatically, unless there is uncommitted work that would make cleanup unsafe.
## PR Timing
When code changes appear correct locally, create the PR promptly even if long-running builds or tests are still running.
Opening the PR starts CI on the build machines, uploads results to the Bazel remote cache, and can speed up subsequent
local validation. Continue monitoring any already-started local and CI validation after opening the PR.
---
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## Project Overview
Eagle0 is a multi-language gaming system combining strategic turn-based gameplay (Eagle) with tactical hex-based
combat (Shardok). The system integrates LLM-based narrative generation and supports both human and AI players.
## Architecture
**Three-Tier Game System:**
- **Unity Client (C#)**: Real-time strategy game client with integrated tactical combat UI
- **Eagle (Scala)**: Strategic layer managing turn-based gameplay, diplomacy, hero progression, and province control
- **Shardok (C++)**: Tactical layer handling real-time hex-based combat simulation with performance-critical battle
resolution
**Communication Flow:**
```
Unity Client ↔ Eagle (gRPC streaming) ↔ Shardok (internal gRPC)
```
**Key Entry Points:**
- `/src/main/csharp/net/eagle0/clients/unity/eagle0/` - Unity C# game client
- `/src/main/scala/net/eagle0/eagle/Main.scala` - Eagle strategic game server
- `/src/main/cpp/net/eagle0/shardok/shardok_server_main.cpp` - Shardok tactical server
**Protocol Buffer Architecture:**
- Extensive use of protobuf for type-safe communication
- Separate packages: `api/` (client-facing), `internal/` (server state), `views/` (client projections)
- Event sourcing pattern with immutable action history
## Essential Commands
### Building
```bash
# Build Eagle server (Scala strategic layer)
bazel build //src/main/scala/net/eagle0/eagle:eagle_server_deploy.jar
# Build Shardok server (C++ tactical layer)
bazel build -c opt //src/main/cpp/net/eagle0/shardok:shardok-server
# Shardok server includes both AI algorithms
bazel build //src/main/cpp/net/eagle0/shardok:shardok-server
# Build Unity/C# client
./scripts/build_protos.sh # Protocol buffer generation for Unity
./scripts/build_plugins.sh # Native plugins for all platforms
./scripts/build_windows_plugin.sh # Windows-specific plugin build
# Unity builds via CI: ci/github_actions/build_unity.sh
```
### Running Services
```bash
# Eagle server (port 40032)
bazel run //src/main/scala/net/eagle0/eagle:eagle_server -- --eagle-grpc-port 40032
# Or: ./scripts/eagle_run.sh
# Shardok server
bazel run //src/main/cpp/net/eagle0/shardok:shardok-server --compilation_mode=opt
# Or: ./scripts/shardok_run.sh
```
### Testing
```bash
# Run all tests
bazel test //src/test/... //src/main/go/...
# Component-specific tests
bazel test //src/test/scala/... # Scala Eagle tests
bazel test //src/test/cpp/... # C++ Shardok tests
```
### Code Generation
```bash
bazel run gazelle # Update Go build files
./scripts/updateActionResultTypes.sh # Update protocol buffer mappings
```
### Pre-Commit Checklist
**MANDATORY: Before running `git commit`, verify:**
1. **If you modified any BUILD.bazel file:** Run `bazel run gazelle` and stage any changes it makes
2. **If you modified C++ or C# files:** Run `clang-format -i` on the modified files
3. **If you modified Scala files:** scalafmt will run automatically via pre-commit hook
4. **ALWAYS run the full test suite for your language changes before pushing:**
- For Scala changes: `bazel test //src/test/scala/...`
- For C++ changes: `bazel test //src/test/cpp/...`
- This catches exhaustive pattern match errors and other compile-time failures that single-target builds miss
The pre-commit hook runs gazelle but only checks if it succeeds - it does NOT verify the BUILD files are in canonical format. The `gazelle_test` will fail if deps are not alphabetically sorted. **Always run gazelle manually after BUILD file changes.**
### Code Formatting
```bash
# ALWAYS run clang-format after making any C++ or C# code changes
clang-format -i <modified_files>
# Format all C++ files in a directory:
find . -name "*.cpp" -o -name "*.hpp" | xargs clang-format -i
# Format all C# files in a directory:
find . -name "*.cs" | xargs clang-format -i
```
### Static Analysis
```bash
# Run clang-tidy static analysis on C++ files
# Note: This may show some header include errors but will still analyze the main file
bazel run @llvm_toolchain//:clang-tidy -- --checks='readability-*,bugprone-*,clang-analyzer-*' <file_path> -- -I/Users/dancrosby/CodingProjects/github/eagle0 -std=c++23
# Example for AI files:
bazel run @llvm_toolchain//:clang-tidy -- --checks='readability-*,bugprone-*,clang-analyzer-*' /Users/dancrosby/CodingProjects/github/eagle0/src/main/cpp/net/eagle0/shardok/ai/AIUnitScoreCalculator.cpp -- -I/Users/dancrosby/CodingProjects/github/eagle0 -std=c++23
```
## AI Algorithm Selection
Eagle0 supports two AI algorithms for tactical combat decision-making:
### Iterative Deepening AI (Default)
The original minimax-based AI with sophisticated randomness handling:
- **Advantages**: Proven, sophisticated randomness evaluation, comprehensive lookahead
- **Use cases**: Production builds, scenarios requiring precise evaluation
- **Performance**: Single-threaded, thorough evaluation
### Monte Carlo Tree Search AI (MCTS)
Modern MCTS-based AI with multithreading support:
- **Advantages**: Multithreaded, better performance on modern CPUs, anytime algorithm
- **Use cases**: Performance testing, scenarios requiring fast decisions
- **Performance**: Multithreaded, adaptive depth based on time budget
### Switching Between Algorithms
The algorithm is selected at **runtime** via the ShardokAIClient constructor:
```cpp
// Using Iterative Deepening AI (default)
ShardokAIClient client(playerId, isDefender, hexMap, settings);
// OR explicitly:
ShardokAIClient client(playerId, isDefender, hexMap, settings, AIAlgorithmType::ITERATIVE_DEEPENING);
// Using MCTS AI
ShardokAIClient client(playerId, isDefender, hexMap, settings, AIAlgorithmType::MCTS);
```
```bash
# Build the server (includes both AI algorithms)
bazel build //src/main/cpp/net/eagle0/shardok:shardok-server
# Test both algorithms
bazel test //src/test/cpp/net/eagle0/shardok/ai:ai_iterative_deepening_test
bazel test //src/test/cpp/net/eagle0/shardok/ai:ai_mcts_test # If available
# Performance tests
./scripts/ai_perf_test.sh # Uses whatever algorithm the server is configured to use
```
Both implementations are compatible with all existing interfaces and produce the same `SearchResult` structure.
**Note**: Both implementations are documented in `src/main/cpp/net/eagle0/shardok/ai/AI_SCORING_SYSTEM.md`, including
recommendations for improving MCTS randomness handling.
The AI algorithm selection is made at runtime when creating ShardokAIClient instances, allowing different AI strategies
to be used for different players or game situations within the same server process.
## Language-Specific Patterns
**Scala (Strategic Layer):**
- Use `EngineImpl.scala` for core game logic modifications
- Follow event sourcing pattern - all changes through immutable actions
- gRPC streaming for real-time client updates via `EagleServiceImpl.scala`
- LLM integration in `/common/llm_integration/` for narrative generation
**C++ (Tactical Layer):**
- Performance-critical combat in `ShardokEngine.hpp/.cpp`
- FlatBuffers for efficient serialization in `/flatbuffer/` directory
- AI systems in `/ai/` subdirectory with pluggable strategy selectors
- Extensive unit testing with Google Test framework
**Protocol Buffers:**
- Three-layer structure: `api/` (client), `internal/` (server), `views/` (projections)
- Use `shardok_internal_interface.proto` for Eagle-Shardok communication
- Maintain backward compatibility when modifying existing messages
**C# (Unity Client):**
- Located in `/src/main/csharp/net/eagle0/clients/unity/eagle0/`
- Uses Unity 6 (6000.4.9f1) with comprehensive protobuf integration (100+ .proto files)
- Key components: `EagleConnection.cs` (gRPC client), `EagleGameController.cs` (main game logic)
- Real-time bidirectional streaming with server via `PersistentClientConnection.cs`
- Strategic map UI in `Assets/Eagle/`, tactical battle UI in `Assets/Shardok/`
- Seamless transition between strategic gameplay and hex-based tactical combat
- **NEVER add defensive null checks on Unity Inspector fields** - these hide configuration bugs. If a field isn't
linked in the editor, it should throw a NullReferenceException so the problem is immediately obvious. Silently
skipping code when a required field is null makes bugs harder to find.
**Go (Build Tools):**
- Build automation and code generation utilities
- AWS S3 integration for deployment artifacts
## Testing Strategy
- Comprehensive unit tests for both Scala and C++ components
- Integration tests for Eagle-Shardok communication
- Map validation tests ensure game content integrity
- Use `GameSettings_test_utils.cpp` and `ShardokEngineBasedTestData.cpp` for C++ test helpers
### Scala Testing Patterns
**Use `inside()` instead of `asInstanceOf` for type matching in tests:**
Never use `asInstanceOf` in tests. Instead, use ScalaTest's `inside()` pattern for safe type matching:
```scala
// BAD - don't do this
val changedHero = result.changedHeroes.head.asInstanceOf[ChangedHeroC]
changedHero.heroId shouldBe 19
// GOOD - use inside() pattern
import org.scalatest.Inside.inside
inside(result.changedHeroes.head) { case changedHero: ChangedHeroC =>
changedHero.heroId shouldBe 19
changedHero.vigorChange shouldBe StatDelta(17.2)
}
```
The `inside()` pattern:
- Provides better error messages when the type doesn't match
- Is idiomatic ScalaTest
- Works with pattern matching for more complex assertions
## Performance Testing
When making performance-related changes to the AI or engine:
```bash
# 1. Commit your changes to a feature branch
git checkout -b performance-improvement-feature
git add . && git commit -m "Implement performance improvement"
# 2. Run performance tests multiple times on your branch to reduce noise
for i in 1 2 3; do
echo "=== Run $i ==="
./scripts/ai_perf_test.sh 2>&1 | grep -A 20 "AI Search Performance Summary"
done
# Save or note the results
# 3. Switch to main branch and run the same tests
git checkout main
for i in 1 2 3; do
echo "=== Run $i ==="
./scripts/ai_perf_test.sh 2>&1 | grep -A 20 "AI Search Performance Summary"
done
# 4. Compare the results between your branch and main
# Key metrics to compare:
# - Commands evaluated at each depth (e.g., "Depth 3: 169/523 commands")
# - Average search depth achieved
# - Completion rates at each depth
```
**Important notes:**
- Run tests multiple times (3-5) to account for performance variance
- Focus on commands evaluated at each depth rather than total commands
- Commands at different depths aren't directly comparable (depth 3 is more valuable than depth 2)
- **Always test performance changes** - what seems like an optimization may sometimes have unexpected overhead or
behavior changes.
## Troubleshooting Scala Build Errors
### MissingType Errors
When you see errors like:
```
dotty.tools.dotc.core.MissingType: Cannot resolve reference to type net.eagle0.eagle.internal.game_state.type.GameState
```
**This is NOT a Scala compiler crash.** This is a missing dependency in BUILD.bazel.
**How to fix:**
1. Identify the missing type from the error message (e.g., `game_state.GameState`)
2. Find the Bazel target that provides this type (e.g., `//src/main/protobuf/net/eagle0/eagle/internal:game_state_scala_proto`)
3. Add it to the `deps` of the failing target
4. If the type appears in a public method signature, also add it to `exports` so downstream targets can see it
**Common pattern:** When adding a method to a class that takes or returns a proto type, the proto dependency often needs to be added to both `deps` AND `exports`.
### Bazel Clean
**NEVER run `bazel clean` without asking first.** It rarely fixes actual issues and wastes significant rebuild time. The issues that seem like they need `bazel clean` are usually:
- Missing imports in Scala code
- Missing dependencies in BUILD.bazel
- Missing exports for types used in public signatures
## Game Content
**Maps:** `.e0mj` files in `/src/main/resources/net/eagle0/shardok/maps/`
**Configuration:** Game parameters in `/src/main/resources/net/eagle0/eagle/game_parameters.json`
**Data Files:** TSV format for battalions, heroes, and other game data
**NEVER modify hero names.** Do not change names in `heroes.tsv`, `generated_heroes`, or any other hero data files. The names are carefully chosen and are not to be altered.
## Deployment
- Bazel handles multi-language builds and dependencies
- CI/CD via GitHub Actions with platform-specific build scripts in `/ci/github_actions/`
- Docker containerization available via `ci/eagle_run.Dockerfile`
- Always run "bazel run //:gazelle" after editing any BUILD.bazel files
- *ALWAYS ALWAYS* run "bazel run gazelle" after any change that modifies a BUILD.bazel file
+10 -2
View File
@@ -1,7 +1,15 @@
# CLAUDE.md
## CRITICAL BASH RULES (NEVER VIOLATE)
**NEVER chain bash commands.** Do not use `&&`, `||`, or `;` to combine commands. Each command must be a separate Bash tool call. Use parallel tool calls when commands are independent.
**NEVER prefix a command with `cd`.** Run `git`, `gh`, `bazel`, etc. directly from whatever the cwd already is. The cwd is a subdirectory of the worktree; `git`/`gh` find the repo via `.git` discovery and `bazel` finds the workspace via MODULE.bazel discovery — walking up from a subdir works fine. The shell resets cwd after every command anyway, so a `cd` never persists. (And `cd <dir> && <cmd>` violates the no-chaining rule above and forces an approval prompt every time.) Only `cd` in the rare case a tool genuinely cannot locate its root, and even then as its own Bash call, never a chain.
## CRITICAL GIT RULES (NEVER VIOLATE)
**NEVER use `git -C`.** Just run `git` directly from the cwd — it finds the repo via `.git` discovery. Do not `cd` to the repo root either (see the no-`cd` bash rule above).
**NEVER push directly to main/master.** No exceptions. Not for "small changes." Not for docs. Not ever.
**NEVER merge PRs.** You create PRs. The user merges them. No exceptions.
@@ -220,7 +228,7 @@ to be used for different players or game situations within the same server proce
**C# (Unity Client):**
- Located in `/src/main/csharp/net/eagle0/clients/unity/eagle0/`
- Uses Unity 6 (6000.0.32f1) with comprehensive protobuf integration (100+ .proto files)
- Uses Unity 6 (6000.4.9f1) with comprehensive protobuf integration (100+ .proto files)
- Key components: `EagleConnection.cs` (gRPC client), `EagleGameController.cs` (main game logic)
- Real-time bidirectional streaming with server via `PersistentClientConnection.cs`
- Strategic map UI in `Assets/Eagle/`, tactical battle UI in `Assets/Shardok/`
@@ -344,4 +352,4 @@ dotty.tools.dotc.core.MissingType: Cannot resolve reference to type net.eagle0.e
- CI/CD via GitHub Actions with platform-specific build scripts in `/ci/github_actions/`
- Docker containerization available via `ci/eagle_run.Dockerfile`
- Always run "bazel run //:gazelle" after editing any BUILD.bazel files
- *ALWAYS ALWAYS* run "bazel run gazelle" after any change that modifies a BUILD.bazel file
- *ALWAYS ALWAYS* run "bazel run gazelle" after any change that modifies a BUILD.bazel file
+59 -18
View File
@@ -149,38 +149,54 @@ use_repo(crate, "map_generator_crates")
#
# Platform Support - Apple/iOS
#
# Note: rules_apple is NOT included in the main workspace due to rules_swift
# version conflicts with grpc. SparklePlugin (which needs rules_apple) is built
# in a separate workspace at sparkle_workspace/ to isolate the conflict.
#
bazel_dep(name = "apple_support", version = "1.24.1", repo_name = "build_bazel_apple_support")
# rules_swift is a transitive dep of grpc and flatbuffers with conflicting versions:
# - grpc 1.76.0.bcr.1 requires rules_swift 3.x (compatibility level 3)
# - flatbuffers requires rules_swift 2.x (compatibility level 2)
# We don't use Swift directly, but we need to force a single version.
# Force 3.x since grpc is more complex and harder to downgrade.
single_version_override(
module_name = "rules_swift",
version = "3.1.2",
)
bazel_dep(name = "rules_apple", version = "4.3.3", repo_name = "build_bazel_rules_apple")
# Register Apple CC toolchain for Objective-C compilation
apple_cc_configure = use_extension(
"@build_bazel_apple_support//crosstool:setup.bzl",
"apple_cc_configure_extension",
)
use_repo(apple_cc_configure, "local_config_apple_cc")
use_repo(apple_cc_configure, "local_config_apple_cc", "local_config_apple_cc_toolchains")
#
# Protocol Buffers & RPC
#
bazel_dep(name = "protobuf", version = "33.5", repo_name = "com_google_protobuf")
# Use pre-built protoc binaries instead of compiling from source.
# See: https://protobuf.dev/reference/cpp/cpp-generated/#invocation
prebuilt_protoc = use_extension("@com_google_protobuf//bazel/private:prebuilt_protoc_extension.bzl", "protoc")
use_repo(
prebuilt_protoc,
"prebuilt_protoc.linux_aarch_64",
"prebuilt_protoc.linux_ppcle_64",
"prebuilt_protoc.linux_s390_64",
"prebuilt_protoc.linux_x86_32",
"prebuilt_protoc.linux_x86_64",
"prebuilt_protoc.osx_aarch_64",
"prebuilt_protoc.osx_x86_64",
"prebuilt_protoc.win32",
"prebuilt_protoc.win64",
)
bazel_dep(name = "rules_proto", version = "7.1.0")
bazel_dep(name = "rules_cc", version = "0.2.14")
bazel_dep(name = "grpc", version = "1.74.1")
bazel_dep(name = "grpc", version = "1.78.0")
# Patch grpc 1.78.0 to fix rules_python incompatibility: grpc requests Python
# 3.14.0b2 toolchain but rules_python >= 1.6.0 removed it in favor of 3.14.
# Upstream fix: https://github.com/grpc/grpc/commit/459279b
# TODO: Remove this override once a fixed grpc version is published to BCR.
single_version_override(
module_name = "grpc",
patch_strip = 1,
patches = ["//third_party/patches:grpc_fix_python_version.patch"],
version = "1.78.0",
)
bazel_dep(name = "grpc-java", version = "1.78.0")
bazel_dep(name = "rules_proto_grpc_csharp", version = "5.8.0")
bazel_dep(name = "flatbuffers", version = "25.12.19")
@@ -279,6 +295,9 @@ maven.install(
# Testing
"org.scalamock:scalamock_3:7.4.1",
# Developer tools
"org.scalameta:scalafmt-cli_2.13:3.9.9",
# AWS SDK
"software.amazon.awssdk:s3-transfer-manager:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:s3:%s" % AWS_SDK_VERSION,
@@ -321,6 +340,15 @@ maven.install(
],
)
# json4s' Scala 3 reflection path can load scala.quoted.staging at runtime, but
# its Maven metadata does not bring the staging jar transitively.
maven.artifact(
artifact = "scala3-staging_3",
exclusions = ["org.scala-lang:scala3-compiler_3"],
group = "org.scala-lang",
version = "3.3.6",
)
# Force specific versions for dependencies with conflicts between grpc-java and protobuf
maven.artifact(
artifact = "gson",
@@ -384,8 +412,16 @@ http_archive(
],
)
# Note: Sparkle framework is defined in sparkle_workspace/MODULE.bazel
# (not in main workspace due to rules_swift version conflicts)
# Sparkle framework for macOS auto-updates
SPARKLE_VERSION = "2.6.4"
http_archive(
name = "sparkle",
build_file = "//src/main/objc/net/eagle0/clients/unity/sparkle/external:BUILD.sparkle",
sha256 = "50612a06038abc931f16011d7903b8326a362c1074dabccb718404ce8e585f0b",
strip_prefix = "",
url = "https://github.com/sparkle-project/Sparkle/releases/download/%s/Sparkle-%s.tar.xz" % (SPARKLE_VERSION, SPARKLE_VERSION),
)
# Busybox static binary for Docker health checks (provides nc, wget, etc.)
# Primary: DigitalOcean Spaces (public, reliable)
@@ -475,6 +511,11 @@ register_toolchains(
"@rules_scala//testing:scalatest_toolchain",
)
# Apple CC toolchain for Objective-C compilation (SparklePlugin).
# Registered before LLVM so it has higher priority; Apple constraint matching
# ensures it's only used for Apple-platform targets (objc_library, macos_bundle).
register_toolchains("@local_config_apple_cc_toolchains//:all")
# Set dev_dependency so we can turn this off for swift MacOS builds
register_toolchains(
"@llvm_toolchain//:all",
+185 -236
View File
@@ -4,15 +4,12 @@
"https://bcr.bazel.build/bazel_registry.json": "8a28e4aff06ee60aed2a8c281907fb8bcbf3b753c91fb5a5c57da3215d5b3497",
"https://bcr.bazel.build/modules/abseil-cpp/20210324.2/MODULE.bazel": "7cd0312e064fde87c8d1cd79ba06c876bd23630c83466e9500321be55c96ace2",
"https://bcr.bazel.build/modules/abseil-cpp/20211102.0/MODULE.bazel": "70390338f7a5106231d20620712f7cccb659cd0e9d073d1991c038eb9fc57589",
"https://bcr.bazel.build/modules/abseil-cpp/20220623.1/MODULE.bazel": "73ae41b6818d423a11fd79d95aedef1258f304448193d4db4ff90e5e7a0f076c",
"https://bcr.bazel.build/modules/abseil-cpp/20230125.1/MODULE.bazel": "89047429cb0207707b2dface14ba7f8df85273d484c2572755be4bab7ce9c3a0",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.0.bcr.1/MODULE.bazel": "1c8cec495288dccd14fdae6e3f95f772c1c91857047a098fad772034264cc8cb",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.0/MODULE.bazel": "d253ae36a8bd9ee3c5955384096ccb6baf16a1b1e93e858370da0a3b94f77c16",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.1/MODULE.bazel": "fa92e2eb41a04df73cdabeec37107316f7e5272650f81d6cc096418fe647b915",
"https://bcr.bazel.build/modules/abseil-cpp/20240116.0/MODULE.bazel": "98dc378d64c12a4e4741ad3362f87fb737ee6a0886b2d90c3cdbb4d93ea3e0bf",
"https://bcr.bazel.build/modules/abseil-cpp/20240116.1/MODULE.bazel": "37bcdb4440fbb61df6a1c296ae01b327f19e9bb521f9b8e26ec854b6f97309ed",
"https://bcr.bazel.build/modules/abseil-cpp/20240116.2/MODULE.bazel": "73939767a4686cd9a520d16af5ab440071ed75cec1a876bf2fcfaf1f71987a16",
"https://bcr.bazel.build/modules/abseil-cpp/20240722.0/MODULE.bazel": "88668a07647adbdc14cb3a7cd116fb23c9dda37a90a1681590b6c9d8339a5b84",
"https://bcr.bazel.build/modules/abseil-cpp/20250127.0/MODULE.bazel": "d1086e248cda6576862b4b3fe9ad76a214e08c189af5b42557a6e1888812c5d5",
"https://bcr.bazel.build/modules/abseil-cpp/20250127.1/MODULE.bazel": "c4a89e7ceb9bf1e25cf84a9f830ff6b817b72874088bf5141b314726e46a57c1",
"https://bcr.bazel.build/modules/abseil-cpp/20250512.0/MODULE.bazel": "c4d02dd22cd87458516655a45512060246ee2a4732f1fbe948a5bd9eb614e626",
@@ -25,7 +22,7 @@
"https://bcr.bazel.build/modules/apple_support/1.13.0/MODULE.bazel": "7c8cdea7e031b7f9f67f0b497adf6d2c6a2675e9304ca93a9af6ed84eef5a524",
"https://bcr.bazel.build/modules/apple_support/1.15.1/MODULE.bazel": "a0556fefca0b1bb2de8567b8827518f94db6a6e7e7d632b4c48dc5f865bc7c85",
"https://bcr.bazel.build/modules/apple_support/1.17.1/MODULE.bazel": "655c922ab1209978a94ef6ca7d9d43e940cd97d9c172fb55f94d91ac53f8610b",
"https://bcr.bazel.build/modules/apple_support/1.21.0/MODULE.bazel": "ac1824ed5edf17dee2fdd4927ada30c9f8c3b520be1b5fd02a5da15bc10bff3e",
"https://bcr.bazel.build/modules/apple_support/1.21.1/MODULE.bazel": "5809fa3efab15d1f3c3c635af6974044bac8a4919c62238cce06acee8a8c11f1",
"https://bcr.bazel.build/modules/apple_support/1.23.0/MODULE.bazel": "317d47e3f65b580e7fb4221c160797fda48e32f07d2dfff63d754ef2316dcd25",
"https://bcr.bazel.build/modules/apple_support/1.23.1/MODULE.bazel": "53763fed456a968cf919b3240427cf3a9d5481ec5466abc9d5dc51bc70087442",
"https://bcr.bazel.build/modules/apple_support/1.24.1/MODULE.bazel": "f46e8ddad60aef170ee92b2f3d00ef66c147ceafea68b6877cb45bd91737f5f8",
@@ -67,6 +64,7 @@
"https://bcr.bazel.build/modules/bazel_features/1.23.0/MODULE.bazel": "fd1ac84bc4e97a5a0816b7fd7d4d4f6d837b0047cf4cbd81652d616af3a6591a",
"https://bcr.bazel.build/modules/bazel_features/1.27.0/MODULE.bazel": "621eeee06c4458a9121d1f104efb80f39d34deff4984e778359c60eaf1a8cb65",
"https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d",
"https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9",
"https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87",
"https://bcr.bazel.build/modules/bazel_features/1.32.0/MODULE.bazel": "095d67022a58cb20f7e20e1aefecfa65257a222c18a938e2914fd257b5f1ccdc",
"https://bcr.bazel.build/modules/bazel_features/1.33.0/MODULE.bazel": "8b8dc9d2a4c88609409c3191165bccec0e4cb044cd7a72ccbe826583303459f6",
@@ -102,7 +100,6 @@
"https://bcr.bazel.build/modules/bazel_worker_api/0.0.4/MODULE.bazel": "460aa12d01231a80cce03c548287b433b321d205b0028ae596728c35e5ee442e",
"https://bcr.bazel.build/modules/bazel_worker_java/0.0.4/MODULE.bazel": "82494a01018bb7ef06d4a17ec4cd7a758721f10eb8b6c820a818e70d669500db",
"https://bcr.bazel.build/modules/bazel_worker_java/0.0.4/source.json": "a2d30458fd86cf022c2b6331e652526fa08e17573b2f5034a9dbcacdf9c2583c",
"https://bcr.bazel.build/modules/boringssl/0.0.0-20211025-d4f1ab9/MODULE.bazel": "6ee6353f8b1a701fe2178e1d925034294971350b6d3ac37e67e5a7d463267834",
"https://bcr.bazel.build/modules/boringssl/0.0.0-20230215-5c22014/MODULE.bazel": "4b03dc0d04375fa0271174badcd202ed249870c8e895b26664fd7298abea7282",
"https://bcr.bazel.build/modules/boringssl/0.0.0-20240530-2db0eb3/MODULE.bazel": "d0405b762c5e87cd445b7015f2b8da5400ef9a8dbca0bfefa6c1cea79d528a97",
"https://bcr.bazel.build/modules/boringssl/0.20240913.0/MODULE.bazel": "fcaa7503a5213290831a91ed1eb538551cf11ac0bc3a6ad92d0fef92c5bd25fb",
@@ -110,14 +107,12 @@
"https://bcr.bazel.build/modules/boringssl/0.20241024.0/source.json": "d843092e682b84188c043ac742965d7f96e04c846c7e338187e03238674909a9",
"https://bcr.bazel.build/modules/buildozer/7.1.2/MODULE.bazel": "2e8dd40ede9c454042645fd8d8d0cd1527966aa5c919de86661e62953cd73d84",
"https://bcr.bazel.build/modules/buildozer/7.1.2/source.json": "c9028a501d2db85793a6996205c8de120944f50a0d570438fcae0457a5f9d1f8",
"https://bcr.bazel.build/modules/c-ares/1.15.0/MODULE.bazel": "ba0a78360fdc83f02f437a9e7df0532ad1fbaa59b722f6e715c11effebaa0166",
"https://bcr.bazel.build/modules/c-ares/1.19.1/MODULE.bazel": "73bca21720772370ff91cc8e88bbbaf14897720c6473e87c1ddc0f848284c313",
"https://bcr.bazel.build/modules/c-ares/1.19.1/source.json": "56bfa95b01e4e0012e90eaa9f1bab823c48c3af4454286b889b9cc74f5098da1",
"https://bcr.bazel.build/modules/cel-spec/0.15.0/MODULE.bazel": "e1eed53d233acbdcf024b4b0bc1528116d92c29713251b5154078ab1348cb600",
"https://bcr.bazel.build/modules/cel-spec/0.15.0/source.json": "ab7dccdf21ea2261c0f809b5a5221a4d7f8b580309f285fdf1444baaca75d44a",
"https://bcr.bazel.build/modules/civetweb/1.16/MODULE.bazel": "46a38f9daeb57392e3827fce7d40926be0c802bd23cdd6bfd3a96c804de42fae",
"https://bcr.bazel.build/modules/civetweb/1.16/source.json": "ba8b9585adb8355cb51b999d57172fd05e7a762c56b8d4bac6db42c99de3beb7",
"https://bcr.bazel.build/modules/curl/8.4.0/MODULE.bazel": "0bc250aa1cb69590049383df7a9537c809591fcf876c620f5f097c58fdc9bc10",
"https://bcr.bazel.build/modules/curl/8.7.1/MODULE.bazel": "088221c35a2939c555e6e47cb31a81c15f8b59f4daa8009b1e9271a502d33485",
"https://bcr.bazel.build/modules/curl/8.8.0/MODULE.bazel": "7da3b3e79b0b4ee8f8c95d640bc6ad7b430ce66ef6e9c9d2bc29b3b5ef85f6fe",
"https://bcr.bazel.build/modules/curl/8.8.0/source.json": "d7d138b6878cf38891692fee0649ace35357fd549b425614d571786f054374d4",
@@ -142,36 +137,33 @@
"https://bcr.bazel.build/modules/gazelle/0.47.0/source.json": "aeb2e5df14b7fb298625d75d08b9c65bdb0b56014c5eb89da9e5dd0572280ae6",
"https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb",
"https://bcr.bazel.build/modules/google_benchmark/1.8.4/MODULE.bazel": "c6d54a11dcf64ee63545f42561eda3fd94c1b5f5ebe1357011de63ae33739d5e",
"https://bcr.bazel.build/modules/google_benchmark/1.8.5/MODULE.bazel": "9ba9b31b984022828a950e3300410977eda2e35df35584c6b0b2d0c2e52766b7",
"https://bcr.bazel.build/modules/google_benchmark/1.8.5/source.json": "2c9c685f9b496f125b9e3a9c696c549d1ed2f33b75830a2fb6ac94fab23c0398",
"https://bcr.bazel.build/modules/google_benchmark/1.8.4/source.json": "84590f7bc5a1fd99e1ef274ee16bb41c214f705e62847b42e705010dfa81fe53",
"https://bcr.bazel.build/modules/googleapis-cc/1.0.0/MODULE.bazel": "cf01757e7590c56140a4b81638ff2b3e7074769e6271720bbf738fcda25b6fc2",
"https://bcr.bazel.build/modules/googleapis-cc/1.0.0/source.json": "ab0e3a2ee9968a8848f59872fbbfa3e1f768597d71d2229e6caa319d357967c7",
"https://bcr.bazel.build/modules/googleapis-grpc-cc/1.0.0/MODULE.bazel": "3553358a9d8d96026c9e28d9fb6c268574950d0be7fa9b4c0aeaf3c37c73f2d3",
"https://bcr.bazel.build/modules/googleapis-grpc-cc/1.0.0/source.json": "fa7b79043b3c82bf74f1f2fa45af289e19b247375868d0752db2c114a1c7366c",
"https://bcr.bazel.build/modules/googleapis-python/1.0.0/MODULE.bazel": "0ccd1614a914fb524b3ac267f9c97f9a5cd5412b027f0176b81a725882ec42ff",
"https://bcr.bazel.build/modules/googleapis-python/1.0.0/source.json": "24364f075ec5e6d5e0cfc5d651bd833b119e0cea1a45d51330c93461e3586e42",
"https://bcr.bazel.build/modules/googleapis-rules-registry/1.0.0/MODULE.bazel": "97c6a4d413b373d4cc97065da3de1b2166e22cbbb5f4cc9f05760bfa83619e24",
"https://bcr.bazel.build/modules/googleapis-rules-registry/1.0.0/source.json": "cf611c836a60e98e2e2ab2de8004f119e9f06878dcf4ea2d95a437b1b7a89fe9",
"https://bcr.bazel.build/modules/googleapis/0.0.0-20240326-1c8d509c5/MODULE.bazel": "a4b7e46393c1cdcc5a00e6f85524467c48c565256b22b5fae20f84ab4a999a68",
"https://bcr.bazel.build/modules/googleapis/0.0.0-20240819-fe8ba054a/MODULE.bazel": "117b7c7be7327ed5d6c482274533f2dbd78631313f607094d4625c28203cacdf",
"https://bcr.bazel.build/modules/googleapis/0.0.0-20240819-fe8ba054a/source.json": "b31fc7eb283a83f71d2e5bfc3d1c562d2994198fa1278409fbe8caec3afc1d3e",
"https://bcr.bazel.build/modules/googleapis/0.0.0-20241220-5e258e33.bcr.1/MODULE.bazel": "ee6c30f82ecd476e61f019fb1151aaab380ea419958ff274ef2f0efca7969f5c",
"https://bcr.bazel.build/modules/googleapis/0.0.0-20241220-5e258e33.bcr.1/source.json": "d6f66e3d95ec52821e994015e83ed194f8888c655068e192659e55a8987dfe77",
"https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4",
"https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6",
"https://bcr.bazel.build/modules/googletest/1.14.0/MODULE.bazel": "cfbcbf3e6eac06ef9d85900f64424708cc08687d1b527f0ef65aa7517af8118f",
"https://bcr.bazel.build/modules/googletest/1.15.2/MODULE.bazel": "6de1edc1d26cafb0ea1a6ab3f4d4192d91a312fd2d360b63adaa213cd00b2108",
"https://bcr.bazel.build/modules/googletest/1.16.0/MODULE.bazel": "a175623c69e94fca4ca7acbc12031e637b0c489318cd4805606981d4d7adb34a",
"https://bcr.bazel.build/modules/googletest/1.17.0/MODULE.bazel": "dbec758171594a705933a29fcf69293d2468c49ec1f2ebca65c36f504d72df46",
"https://bcr.bazel.build/modules/googletest/1.17.0/source.json": "38e4454b25fc30f15439c0378e57909ab1fd0a443158aa35aec685da727cd713",
"https://bcr.bazel.build/modules/grpc-java/1.62.2/MODULE.bazel": "99b8771e8c7cacb130170fed2a10c9e8fed26334a93e73b42d2953250885a158",
"https://bcr.bazel.build/modules/grpc-java/1.66.0/MODULE.bazel": "86ff26209fac846adb89db11f3714b3dc0090fb2fb81575673cc74880cda4e7e",
"https://bcr.bazel.build/modules/grpc-java/1.69.0/MODULE.bazel": "53887af6a00b3b406d70175d3d07e84ea9362016ff55ea90b9185f0227bfaf98",
"https://bcr.bazel.build/modules/grpc-java/1.78.0/MODULE.bazel": "48f790fbb95625245295df1283e0dba344a4e30b4a9a9cefbabfa92bd84f3691",
"https://bcr.bazel.build/modules/grpc-java/1.78.0/source.json": "36c3a83c5ddeb864d7a4b97801456c464077f80a8216354ac1a71f7ce8699771",
"https://bcr.bazel.build/modules/grpc-proto/0.0.0-20240627-ec30f58/MODULE.bazel": "88de79051e668a04726e9ea94a481ec6f1692086735fd6f488ab908b3b909238",
"https://bcr.bazel.build/modules/grpc-proto/0.0.0-20240627-ec30f58/source.json": "5035d379c61042930244ab59e750106d893ec440add92ec0df6a0098ca7f131d",
"https://bcr.bazel.build/modules/grpc/1.41.0/MODULE.bazel": "5bcbfc2b274dabea628f0649dc50c90cf36543b1cfc31624832538644ad1aae8",
"https://bcr.bazel.build/modules/grpc/1.56.3.bcr.1/MODULE.bazel": "cd5b1eb276b806ec5ab85032921f24acc51735a69ace781be586880af20ab33f",
"https://bcr.bazel.build/modules/grpc/1.62.1/MODULE.bazel": "2998211594b8a79a6b459c4e797cfa19f0fb8b3be3149760ec7b8c99abfd426f",
"https://bcr.bazel.build/modules/grpc/1.63.1.bcr.1/MODULE.bazel": "d7b9fef03bd175e6825237b521b18a3c29f1ac15f8aa52c8a1a0f3bd8f33d54b",
"https://bcr.bazel.build/modules/grpc/1.66.0.bcr.2/MODULE.bazel": "0fa2b0fd028ce354febf0fe90f1ed8fecfbfc33118cddd95ac0418cc283333a0",
"https://bcr.bazel.build/modules/grpc/1.66.0.bcr.3/MODULE.bazel": "f6047e89faf488f5e3e65cb2594c6f5e86992abec7487163ff6b623526e543b0",
"https://bcr.bazel.build/modules/grpc/1.69.0/MODULE.bazel": "4e26e05c9e1ef291ccbc96aad8e457b1b8abedbc141623831629da2f8168eef6",
"https://bcr.bazel.build/modules/grpc/1.70.1/MODULE.bazel": "b800cd8e3e7555c1e61cba2e02d3a2fcf0e91f66e800db286d965d3b7a6a721a",
"https://bcr.bazel.build/modules/grpc/1.71.0/MODULE.bazel": "7fcab2c05530373f1a442c362b17740dd0c75b6a2a975eec8f5bf4c70a37928a",
"https://bcr.bazel.build/modules/grpc/1.74.1/MODULE.bazel": "09523be10ba2bfd999683671d0f8f22fb5b20ec77ad89b05ef58ff19a1b65c82",
"https://bcr.bazel.build/modules/grpc/1.74.1/source.json": "8508bcf9bae1b7c647a594e13461ce192240fcdbb409c2741444322d47d01f98",
"https://bcr.bazel.build/modules/grpc/1.78.0/MODULE.bazel": "6a72f0b2fe950342fe63b231c76197df6d117a8ea1ac338dac40b053020f586a",
"https://bcr.bazel.build/modules/grpc/1.78.0/source.json": "c988abfe519ef5ace8cd27c80c0a66e68e501e5902b623722fcbf6694b355693",
"https://bcr.bazel.build/modules/helly25_bzl/0.3.1/MODULE.bazel": "3a4be20f6fc13be32ad44643b8252ef5af09eee936f1d943cd4fd7867fa92826",
"https://bcr.bazel.build/modules/helly25_bzl/0.3.1/source.json": "b129ab1828492de2c163785bbeb4065c166de52d932524b4317beb5b7f917994",
"https://bcr.bazel.build/modules/jq.bzl/0.1.0/MODULE.bazel": "2ce69b1af49952cd4121a9c3055faa679e748ce774c7f1fda9657f936cae902f",
@@ -188,18 +180,13 @@
"https://bcr.bazel.build/modules/nlohmann_json/3.6.1/MODULE.bazel": "6f7b417dcc794d9add9e556673ad25cb3ba835224290f4f848f8e2db1e1fca74",
"https://bcr.bazel.build/modules/opencensus-cpp/0.0.0-20230502-50eb5de.bcr.2/MODULE.bazel": "cc18734138dd18c912c6ce2a59186db28f85d8058c99c9f21b46ca3e0aba0ebe",
"https://bcr.bazel.build/modules/opencensus-cpp/0.0.0-20230502-50eb5de.bcr.2/source.json": "7c135f9d42bb3b045669c3c6ab3bb3c208e00b46aca4422eea64c29811a5b240",
"https://bcr.bazel.build/modules/opencensus-cpp/0.0.0-20230502-50eb5de/MODULE.bazel": "02201d2921dadb4ec90c4980eca4b2a02904eddcf6fa02f3da7594fb7b0d821c",
"https://bcr.bazel.build/modules/opencensus-proto/0.4.1.bcr.2/MODULE.bazel": "789706a714855f92c5c8cfcf1ef32bbb64dcd3b7c9066756ad7986ec59709d29",
"https://bcr.bazel.build/modules/opencensus-proto/0.4.1.bcr.2/source.json": "aadf3f53e08b72376506b7c4ea3d167010c9efb160d7d6e1e304ed646bac1b36",
"https://bcr.bazel.build/modules/opencensus-proto/0.4.1/MODULE.bazel": "4a2e8b4d0b544002502474d611a5a183aa282251e14f6a01afe841c0c1b10372",
"https://bcr.bazel.build/modules/openssl/3.3.1.bcr.1/MODULE.bazel": "49c0c07e8fb87b480bccb842cfee1b32617f11dac590f732573c69058699a3d1",
"https://bcr.bazel.build/modules/openssl/3.3.1.bcr.1/source.json": "0c0872e048bbea052a9c541fb47019481a19201ba5555a71d762ad591bf94e1f",
"https://bcr.bazel.build/modules/opentelemetry-cpp/1.14.2/MODULE.bazel": "089a5613c2a159c7dfde098dabfc61e966889c7d6a81a98422a84c51535ed17d",
"https://bcr.bazel.build/modules/opentelemetry-cpp/1.16.0/MODULE.bazel": "b7379a140f538cea3f749179a2d481ed81942cc6f7b05a6113723eb34ac3b3e7",
"https://bcr.bazel.build/modules/opentelemetry-cpp/1.19.0/MODULE.bazel": "3455326c08b28415648a3d60d8e3c811847ebdbe64474f75b25878f25585aea1",
"https://bcr.bazel.build/modules/opentelemetry-cpp/1.19.0/source.json": "4e48137e4c3ecb99401ff99876df8fa330598d7da051869bec643446e8a8ff95",
"https://bcr.bazel.build/modules/opentelemetry-proto/1.1.0/MODULE.bazel": "a49f406e99bf05ab43ed4f5b3322fbd33adfd484b6546948929d1316299b68bf",
"https://bcr.bazel.build/modules/opentelemetry-proto/1.3.1/MODULE.bazel": "0141a50e989576ee064c11ce8dd5ec89993525bd9f9a09c5618e4dacc8df9352",
"https://bcr.bazel.build/modules/opentelemetry-proto/1.4.0.bcr.1/MODULE.bazel": "5ceaf25e11170d22eded4c8032728b4a3f273765fccda32f9e94f463755c4167",
"https://bcr.bazel.build/modules/opentelemetry-proto/1.5.0/MODULE.bazel": "7543d91a53b98e7b5b37c5a0865b93bff12c1ee022b1e322cd236b968894b030",
"https://bcr.bazel.build/modules/opentelemetry-proto/1.5.0/source.json": "046b721ce203e88cdaad44d7dd17a86b7200eab9388b663b234e72e13ff7b143",
@@ -219,7 +206,6 @@
"https://bcr.bazel.build/modules/platforms/0.0.9/MODULE.bazel": "4a87a60c927b56ddd67db50c89acaa62f4ce2a1d2149ccb63ffd871d5ce29ebc",
"https://bcr.bazel.build/modules/platforms/1.0.0/MODULE.bazel": "f05feb42b48f1b3c225e4ccf351f367be0371411a803198ec34a389fb22aa580",
"https://bcr.bazel.build/modules/platforms/1.0.0/source.json": "f4ff1fd412e0246fd38c82328eb209130ead81d62dcd5a9e40910f867f733d96",
"https://bcr.bazel.build/modules/prometheus-cpp/1.2.4/MODULE.bazel": "0fbe5dcff66311947a3f6b86ebc6a6d9328e31a28413ca864debc4a043f371e5",
"https://bcr.bazel.build/modules/prometheus-cpp/1.3.0.bcr.1/MODULE.bazel": "116ad46e97c1d2aeb020fe2899a342a7e703574ce7c0faf7e4810f938c974a9a",
"https://bcr.bazel.build/modules/prometheus-cpp/1.3.0.bcr.1/source.json": "e813cce2d450708cfcb26e309c5172583a7440776edf354e83e6788c768e5cca",
"https://bcr.bazel.build/modules/prometheus-cpp/1.3.0/MODULE.bazel": "ce82e086bbc0b60267e970f6a54b2ca6d0f22d3eb6633e00e2cc2899c700f3d8",
@@ -227,8 +213,6 @@
"https://bcr.bazel.build/modules/protobuf/23.1/MODULE.bazel": "88b393b3eb4101d18129e5db51847cd40a5517a53e81216144a8c32dfeeca52a",
"https://bcr.bazel.build/modules/protobuf/24.4/MODULE.bazel": "7bc7ce5f2abf36b3b7b7c8218d3acdebb9426aeb35c2257c96445756f970eb12",
"https://bcr.bazel.build/modules/protobuf/25.6/MODULE.bazel": "fc0ae073b47c7ede88b825ff79e64f1c058967c7a87a86cdf4abecd9e0516625",
"https://bcr.bazel.build/modules/protobuf/26.0.bcr.1/MODULE.bazel": "8f04d38c2da40a3715ff6bdce4d32c5981e6432557571482d43a62c31a24c2cf",
"https://bcr.bazel.build/modules/protobuf/26.0.bcr.2/MODULE.bazel": "62e0b84ca727bdeb55a6fe1ef180e6b191bbe548a58305ea1426c158067be534",
"https://bcr.bazel.build/modules/protobuf/26.0/MODULE.bazel": "8402da964092af40097f4a205eec2a33fd4a7748dc43632b7d1629bfd9a2b856",
"https://bcr.bazel.build/modules/protobuf/27.0-rc2/MODULE.bazel": "b2b0dbafd57b6bec0ca9b251da02e628c357dab53a097570aa7d79d020f107cf",
"https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c",
@@ -252,7 +236,6 @@
"https://bcr.bazel.build/modules/protoc-gen-validate/1.0.4/MODULE.bazel": "b8913c154b16177990f6126d2d2477d187f9ddc568e95ee3e2d50fc65d2c494a",
"https://bcr.bazel.build/modules/protoc-gen-validate/1.2.1.bcr.1/MODULE.bazel": "4bf09676b62fa587ae07e073420a76ec8766dcce7545e5f8c68cfa8e484b5120",
"https://bcr.bazel.build/modules/protoc-gen-validate/1.2.1.bcr.1/source.json": "c19071ebc4b53b5f1cfab9c66eefaf6e4179eb8a998970d07b1077687e777f29",
"https://bcr.bazel.build/modules/protoc-gen-validate/1.2.1/MODULE.bazel": "52b51f50533ec4fbd5d613cd093773f979ac2e035d954e02ca11de383f502505",
"https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e",
"https://bcr.bazel.build/modules/pybind11_bazel/2.12.0/MODULE.bazel": "e6f4c20442eaa7c90d7190d8dc539d0ab422f95c65a57cc59562170c58ae3d34",
"https://bcr.bazel.build/modules/pybind11_bazel/2.12.0/source.json": "6900fdc8a9e95866b8c0d4ad4aba4d4236317b5c1cd04c502df3f0d33afed680",
@@ -269,8 +252,8 @@
"https://bcr.bazel.build/modules/rules_android/0.6.6/source.json": "a9d8dc2d5a102dc03269a94acc886a4cab82cdcb9ccbc77b0f665d6d17a6ae09",
"https://bcr.bazel.build/modules/rules_apple/3.13.0/MODULE.bazel": "b4559a2c6281ca3165275bb36c1f0ac74666632adc5bdb680e366de7ce845f43",
"https://bcr.bazel.build/modules/rules_apple/3.16.0/MODULE.bazel": "0d1caf0b8375942ce98ea944be754a18874041e4e0459401d925577624d3a54a",
"https://bcr.bazel.build/modules/rules_apple/3.16.0/source.json": "d8b5fe461272018cc07cfafce11fe369c7525330804c37eec5a82f84cd475366",
"https://bcr.bazel.build/modules/rules_apple/3.5.1/MODULE.bazel": "3d1bbf65ad3692003d36d8a29eff54d4e5c1c5f4bfb60f79e28646a924d9101c",
"https://bcr.bazel.build/modules/rules_apple/4.3.3/MODULE.bazel": "c5c2c4adeeac5f3f2f9b7f16abfa8be7ffefa596171d0d92bed4cae9ade0a498",
"https://bcr.bazel.build/modules/rules_apple/4.3.3/source.json": "3cb1d69c8243ffcc42ecbf84ae8b9cccd7b1e2f091b0aee5a3e9c9a45267f312",
"https://bcr.bazel.build/modules/rules_buf/0.1.1/MODULE.bazel": "6189aec18a4f7caff599ad41b851ab7645d4f1e114aa6431acf9b0666eb92162",
"https://bcr.bazel.build/modules/rules_cc/0.0.1/MODULE.bazel": "cb2aa0747f84c6c3a78dad4e2049c154f08ab9d166b1273835a8174940365647",
"https://bcr.bazel.build/modules/rules_cc/0.0.10/MODULE.bazel": "ec1705118f7eaedd6e118508d3d26deba2a4e76476ada7e0e3965211be012002",
@@ -313,7 +296,6 @@
"https://bcr.bazel.build/modules/rules_go/0.59.0/MODULE.bazel": "b7e43e7414a3139a7547d1b4909b29085fbe5182b6c58cbe1ed4c6272815aeae",
"https://bcr.bazel.build/modules/rules_go/0.59.0/source.json": "1df17bb7865cfc029492c30163cee891d0dd8658ea0d5bfdf252c4b6db5c1ef6",
"https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74",
"https://bcr.bazel.build/modules/rules_java/5.1.0/MODULE.bazel": "324b6478b0343a3ce7a9add8586ad75d24076d6d43d2f622990b9c1cfd8a1b15",
"https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86",
"https://bcr.bazel.build/modules/rules_java/5.5.0/MODULE.bazel": "486ad1aa15cdc881af632b4b1448b0136c76025a1fe1ad1b65c5899376b83a50",
"https://bcr.bazel.build/modules/rules_java/6.0.0/MODULE.bazel": "8a43b7df601a7ec1af61d79345c17b31ea1fedc6711fd4abfd013ea612978e39",
@@ -391,18 +373,18 @@
"https://bcr.bazel.build/modules/rules_python/0.23.1/MODULE.bazel": "49ffccf0511cb8414de28321f5fcf2a31312b47c40cc21577144b7447f2bf300",
"https://bcr.bazel.build/modules/rules_python/0.25.0/MODULE.bazel": "72f1506841c920a1afec76975b35312410eea3aa7b63267436bfb1dd91d2d382",
"https://bcr.bazel.build/modules/rules_python/0.28.0/MODULE.bazel": "cba2573d870babc976664a912539b320cbaa7114cd3e8f053c720171cde331ed",
"https://bcr.bazel.build/modules/rules_python/0.29.0/MODULE.bazel": "2ac8cd70524b4b9ec49a0b8284c79e4cd86199296f82f6e0d5da3f783d660c82",
"https://bcr.bazel.build/modules/rules_python/0.31.0/MODULE.bazel": "93a43dc47ee570e6ec9f5779b2e64c1476a6ce921c48cc9a1678a91dd5f8fd58",
"https://bcr.bazel.build/modules/rules_python/0.32.2/MODULE.bazel": "01052470fc30b49de91fb8483d26bea6f664500cfad0b078d4605b03e3a83ed4",
"https://bcr.bazel.build/modules/rules_python/0.33.2/MODULE.bazel": "3e036c4ad8d804a4dad897d333d8dce200d943df4827cb849840055be8d2e937",
"https://bcr.bazel.build/modules/rules_python/0.37.1/MODULE.bazel": "3faeb2d9fa0a81f8980643ee33f212308f4d93eea4b9ce6f36d0b742e71e9500",
"https://bcr.bazel.build/modules/rules_python/0.37.2/MODULE.bazel": "b5ffde91410745750b6c13be1c5dc4555ef5bc50562af4a89fd77807fdde626a",
"https://bcr.bazel.build/modules/rules_python/0.4.0/MODULE.bazel": "9208ee05fd48bf09ac60ed269791cf17fb343db56c8226a720fbb1cdf467166c",
"https://bcr.bazel.build/modules/rules_python/0.40.0/MODULE.bazel": "9d1a3cd88ed7d8e39583d9ffe56ae8a244f67783ae89b60caafc9f5cf318ada7",
"https://bcr.bazel.build/modules/rules_python/1.0.0/MODULE.bazel": "898a3d999c22caa585eb062b600f88654bf92efb204fa346fb55f6f8edffca43",
"https://bcr.bazel.build/modules/rules_python/1.3.0/MODULE.bazel": "8361d57eafb67c09b75bf4bbe6be360e1b8f4f18118ab48037f2bd50aa2ccb13",
"https://bcr.bazel.build/modules/rules_python/1.4.1/MODULE.bazel": "8991ad45bdc25018301d6b7e1d3626afc3c8af8aaf4bc04f23d0b99c938b73a6",
"https://bcr.bazel.build/modules/rules_python/1.6.0/MODULE.bazel": "7e04ad8f8d5bea40451cf80b1bd8262552aa73f841415d20db96b7241bd027d8",
"https://bcr.bazel.build/modules/rules_python/1.6.0/source.json": "e980f654cf66ec4928672f41fc66c4102b5ea54286acf4aecd23256c84211be6",
"https://bcr.bazel.build/modules/rules_python/1.6.3/MODULE.bazel": "a7b80c42cb3de5ee2a5fa1abc119684593704fcd2fec83165ebe615dec76574f",
"https://bcr.bazel.build/modules/rules_python/1.6.3/source.json": "f0be74977e5604a6526c8a416cda22985093ff7d5d380d41722d7e44015cc419",
"https://bcr.bazel.build/modules/rules_robolectric/4.14.1.2/MODULE.bazel": "d44fec647d0aeb67b9f3b980cf68ba634976f3ae7ccd6c07d790b59b87a4f251",
"https://bcr.bazel.build/modules/rules_robolectric/4.14.1.2/source.json": "37c10335f2361c337c5c1f34ed36d2da70534c23088062b33a8bdaab68aa9dea",
"https://bcr.bazel.build/modules/rules_rust/0.45.1/MODULE.bazel": "a69d0db3a958fab2c6520961e1b2287afcc8b36690fd31bbc4f6f7391397150d",
@@ -420,8 +402,10 @@
"https://bcr.bazel.build/modules/rules_shell/0.5.0/MODULE.bazel": "8c8447370594d45539f66858b602b0bb2cb2d3401a4ebb9ad25830c59c0f366d",
"https://bcr.bazel.build/modules/rules_shell/0.6.1/MODULE.bazel": "72e76b0eea4e81611ef5452aa82b3da34caca0c8b7b5c0c9584338aa93bae26b",
"https://bcr.bazel.build/modules/rules_shell/0.6.1/source.json": "20ec05cd5e592055e214b2da8ccb283c7f2a421ea0dc2acbf1aa792e11c03d0c",
"https://bcr.bazel.build/modules/rules_swift/3.1.2/MODULE.bazel": "72c8f5cf9d26427cee6c76c8e3853eb46ce6b0412a081b2b6db6e8ad56267400",
"https://bcr.bazel.build/modules/rules_swift/3.1.2/source.json": "e85761f3098a6faf40b8187695e3de6d97944e98abd0d8ce579cb2daf6319a66",
"https://bcr.bazel.build/modules/rules_swift/1.16.0/MODULE.bazel": "4a09f199545a60d09895e8281362b1ff3bb08bbde69c6fc87aff5b92fcc916ca",
"https://bcr.bazel.build/modules/rules_swift/2.1.1/MODULE.bazel": "494900a80f944fc7aa61500c2073d9729dff0b764f0e89b824eb746959bc1046",
"https://bcr.bazel.build/modules/rules_swift/2.4.0/MODULE.bazel": "1639617eb1ede28d774d967a738b4a68b0accb40650beadb57c21846beab5efd",
"https://bcr.bazel.build/modules/rules_swift/2.4.0/source.json": "a6577f57f9febbdc015a01f2a8f3487422032f134d6c61d18ed8e8ca3b9acc7c",
"https://bcr.bazel.build/modules/stardoc/0.5.0/MODULE.bazel": "f9f1f46ba8d9c3362648eea571c6f9100680efc44913618811b58cc9c02cd678",
"https://bcr.bazel.build/modules/stardoc/0.5.1/MODULE.bazel": "1a05d92974d0c122f5ccf09291442580317cdd859f07a8655f1db9a60374f9f8",
"https://bcr.bazel.build/modules/stardoc/0.5.3/MODULE.bazel": "c7f6948dae6999bf0db32c1858ae345f112cacf98f174c7a8bb707e41b974f1c",
@@ -432,8 +416,8 @@
"https://bcr.bazel.build/modules/stardoc/0.7.1/MODULE.bazel": "3548faea4ee5dda5580f9af150e79d0f6aea934fc60c1cc50f4efdd9420759e7",
"https://bcr.bazel.build/modules/stardoc/0.7.2/MODULE.bazel": "fc152419aa2ea0f51c29583fab1e8c99ddefd5b3778421845606ee628629e0e5",
"https://bcr.bazel.build/modules/stardoc/0.7.2/source.json": "58b029e5e901d6802967754adf0a9056747e8176f017cfe3607c0851f4d42216",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/MODULE.bazel": "75aab2373a4bbe2a1260b9bf2a1ebbdbf872d3bd36f80bff058dccd82e89422f",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/source.json": "5fba48bbe0ba48761f9e9f75f92876cafb5d07c0ce059cc7a8027416de94a05b",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/MODULE.bazel": "5e463fbfba7b1701d957555ed45097d7f984211330106ccd1352c6e0af0dcf91",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/source.json": "32bd87e5f4d7acc57c5b2ff7c325ae3061d5e242c0c4c214ae87e0f1c13e54cb",
"https://bcr.bazel.build/modules/tar.bzl/0.2.1/MODULE.bazel": "52d1c00a80a8cc67acbd01649e83d8dd6a9dc426a6c0b754a04fe8c219c76468",
"https://bcr.bazel.build/modules/tar.bzl/0.5.1/MODULE.bazel": "7c2eb3dcfc53b0f3d6f9acdfd911ca803eaf92aadf54f8ca6e4c1f3aee288351",
"https://bcr.bazel.build/modules/tar.bzl/0.6.0/MODULE.bazel": "a3584b4edcfafcabd9b0ef9819808f05b372957bbdff41601429d5fd0aac2e7c",
@@ -442,23 +426,18 @@
"https://bcr.bazel.build/modules/toolchains_llvm/1.6.0/source.json": "6bd3ef95a288dd2bb1582eca332af850c9a5428a23bb92cb1c57c2dfe6cb7369",
"https://bcr.bazel.build/modules/toolchains_protoc/0.5.0/MODULE.bazel": "e649dcd74790d8b186517588c827a777dfa67acfc4cbd733721c4be143ea107f",
"https://bcr.bazel.build/modules/toolchains_protoc/0.5.0/source.json": "9152bf33827a44f796f94f486252fc0128d9efc2413246ebb09a234bb628a846",
"https://bcr.bazel.build/modules/upb/0.0.0-20211020-160625a/MODULE.bazel": "6cced416be2dc5b9c05efd5b997049ba795e5e4e6fafbe1624f4587767638928",
"https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43",
"https://bcr.bazel.build/modules/upb/0.0.0-20230516-61a97ef/MODULE.bazel": "c0df5e35ad55e264160417fd0875932ee3c9dda63d9fccace35ac62f45e1b6f9",
"https://bcr.bazel.build/modules/upb/0.0.0-20230907-e7430e6/MODULE.bazel": "3a7dedadf70346e678dc059dbe44d05cbf3ab17f1ce43a1c7a42edc7cbf93fd9",
"https://bcr.bazel.build/modules/xds/0.0.0-20240423-555b57e/MODULE.bazel": "cea509976a77e34131411684ef05a1d6ad194dd71a8d5816643bc5b0af16dc0f",
"https://bcr.bazel.build/modules/xds/0.0.0-20240423-555b57e/source.json": "7227e1fcad55f3f3cab1a08691ecd753cb29cc6380a47bc650851be9f9ad6d20",
"https://bcr.bazel.build/modules/yq.bzl/0.1.1/MODULE.bazel": "9039681f9bcb8958ee2c87ffc74bdafba9f4369096a2b5634b88abc0eaefa072",
"https://bcr.bazel.build/modules/yq.bzl/0.1.1/source.json": "2d2bad780a9f2b9195a4a370314d2c17ae95eaa745cefc2e12fbc49759b15aa3",
"https://bcr.bazel.build/modules/zlib/1.2.11/MODULE.bazel": "07b389abc85fdbca459b69e2ec656ae5622873af3f845e1c9d80fe179f3effa0",
"https://bcr.bazel.build/modules/zlib/1.2.12/MODULE.bazel": "3b1a8834ada2a883674be8cbd36ede1b6ec481477ada359cd2d3ddc562340b27",
"https://bcr.bazel.build/modules/zlib/1.2.13/MODULE.bazel": "aa6deb1b83c18ffecd940c4119aff9567cd0a671d7bba756741cb2ef043a29d5",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.1/MODULE.bazel": "6a9fe6e3fc865715a7be9823ce694ceb01e364c35f7a846bf0d2b34762bc066b",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.3/MODULE.bazel": "af322bc08976524477c79d1e45e241b6efbeb918c497e8840b8ab116802dda79",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/MODULE.bazel": "eec517b5bbe5492629466e11dae908d043364302283de25581e3eb944326c4ca",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/source.json": "22bc55c47af97246cfc093d0acf683a7869377de362b5d1c552c2c2e16b7a806",
"https://bcr.bazel.build/modules/zlib/1.3.1/MODULE.bazel": "751c9940dcfe869f5f7274e1295422a34623555916eb98c174c1e945594bf198",
"https://bcr.bazel.build/modules/zlib/1.3/MODULE.bazel": "6a9c02f19a24dcedb05572b2381446e27c272cd383aed11d41d99da9e3167a72"
"https://bcr.bazel.build/modules/zlib/1.3.1/MODULE.bazel": "751c9940dcfe869f5f7274e1295422a34623555916eb98c174c1e945594bf198"
},
"selectedYankedVersions": {},
"moduleExtensions": {
@@ -1159,168 +1138,12 @@
},
"@@googleapis+//:extensions.bzl%switched_rules": {
"general": {
"bzlTransitiveDigest": "vG6fuTzXD8MMvHWZEQud0MMH7eoC4GXY0va7VrFFh04=",
"usagesDigest": "tB2/BAROtqvrfaBweAJxJpqqnx85mOx/aupy9bEK4Ss=",
"bzlTransitiveDigest": "liqpEiZfQn8ycdEspyJt6J+baY9GQOl+9/prJJz2wTA=",
"usagesDigest": "AtKnJVSfl4DFbEt1Zhzwc971VYZMgmyRYK8WMKrwA7o=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"com_google_googleapis_imports": {
"repoRuleId": "@@googleapis+//:repository_rules.bzl%switched_rules",
"attributes": {
"rules": {
"proto_library_with_info": [
"",
""
],
"moved_proto_library": [
"",
""
],
"java_proto_library": [
"",
""
],
"java_grpc_library": [
"",
""
],
"java_gapic_library": [
"",
""
],
"java_gapic_test": [
"",
""
],
"java_gapic_assembly_gradle_pkg": [
"",
""
],
"py_proto_library": [
"",
""
],
"py_grpc_library": [
"",
""
],
"py_gapic_library": [
"",
""
],
"py_test": [
"",
""
],
"py_gapic_assembly_pkg": [
"",
""
],
"py_import": [
"",
""
],
"go_proto_library": [
"",
""
],
"go_grpc_library": [
"",
""
],
"go_library": [
"",
""
],
"go_test": [
"",
""
],
"go_gapic_library": [
"",
""
],
"go_gapic_assembly_pkg": [
"",
""
],
"cc_proto_library": [
"",
""
],
"cc_grpc_library": [
"",
""
],
"cc_gapic_library": [
"",
""
],
"php_proto_library": [
"",
"php_proto_library"
],
"php_grpc_library": [
"",
"php_grpc_library"
],
"php_gapic_library": [
"",
"php_gapic_library"
],
"php_gapic_assembly_pkg": [
"",
"php_gapic_assembly_pkg"
],
"nodejs_gapic_library": [
"",
"typescript_gapic_library"
],
"nodejs_gapic_assembly_pkg": [
"",
"typescript_gapic_assembly_pkg"
],
"ruby_proto_library": [
"",
""
],
"ruby_grpc_library": [
"",
""
],
"ruby_ads_gapic_library": [
"",
""
],
"ruby_cloud_gapic_library": [
"",
""
],
"ruby_gapic_assembly_pkg": [
"",
""
],
"csharp_proto_library": [
"",
""
],
"csharp_grpc_library": [
"",
""
],
"csharp_gapic_library": [
"",
""
],
"csharp_gapic_assembly_pkg": [
"",
""
]
}
}
}
},
"generatedRepoSpecs": {},
"recordedRepoMappingEntries": []
}
},
@@ -1420,34 +1243,6 @@
"recordedRepoMappingEntries": []
}
},
"@@rules_apple+//apple:extensions.bzl%non_module_deps": {
"general": {
"bzlTransitiveDigest": "UsflLeiazyu2v5pvibcvOeIdDV95S25rT96h4XU1nhY=",
"usagesDigest": "M3VqFpeTCo4qmrNKGZw0dxBHvTYDrfV3cscGzlSAhQ4=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"xctestrunner": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/google/xctestrunner/archive/b7698df3d435b6491b4b4c0f9fc7a63fbed5e3a6.tar.gz"
],
"strip_prefix": "xctestrunner-b7698df3d435b6491b4b4c0f9fc7a63fbed5e3a6",
"sha256": "ae3a063c985a8633cb7eb566db21656f8db8eb9a0edb8c182312c7f0db53730d"
}
}
},
"recordedRepoMappingEntries": [
[
"rules_apple+",
"bazel_tools",
"bazel_tools"
]
]
}
},
"@@rules_dotnet+//dotnet:extensions.bzl%dotnet": {
"general": {
"bzlTransitiveDigest": "fd+R6GHICVvxgxz6YGDAcp7EbUx26nq9MWH1unOHz9I=",
@@ -2398,7 +2193,7 @@
"@@rules_python+//python/uv:uv.bzl%uv": {
"general": {
"bzlTransitiveDigest": "8vT1ddXtljNxYD0tJkksqzeKE6xqx4Ix+tXthAppjTI=",
"usagesDigest": "p80sy6cYQuWxx5jhV3fOTu+N9EyIUFG9+F7UC/nhXic=",
"usagesDigest": "icnInV8HDGrRQf9x8RMfxWfBHgT3OgRlYovS/9POEJw=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
@@ -3733,6 +3528,160 @@
]
]
}
},
"@@rules_swift+//swift:extensions.bzl%non_module_deps": {
"general": {
"bzlTransitiveDigest": "gITmwZkwiDAjxHDTZA8AxJiD5JGajyGl/ExE3dyszB0=",
"usagesDigest": "9w18ec4dj90mX/JqpR2tBU2YVc1GU9yNxi/d7q6lLVA=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"com_github_apple_swift_protobuf": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-protobuf/archive/1.20.2.tar.gz"
],
"sha256": "3fb50bd4d293337f202d917b6ada22f9548a0a0aed9d9a4d791e6fbd8a246ebb",
"strip_prefix": "swift-protobuf-1.20.2/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_protobuf/BUILD.overlay"
}
},
"com_github_grpc_grpc_swift": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/grpc/grpc-swift/archive/1.16.0.tar.gz"
],
"sha256": "58b60431d0064969f9679411264b82e40a217ae6bd34e17096d92cc4e47556a5",
"strip_prefix": "grpc-swift-1.16.0/",
"build_file": "@@rules_swift+//third_party:com_github_grpc_grpc_swift/BUILD.overlay"
}
},
"com_github_apple_swift_docc_symbolkit": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-docc-symbolkit/archive/refs/tags/swift-5.10-RELEASE.tar.gz"
],
"sha256": "de1d4b6940468ddb53b89df7aa1a81323b9712775b0e33e8254fa0f6f7469a97",
"strip_prefix": "swift-docc-symbolkit-swift-5.10-RELEASE",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_docc_symbolkit/BUILD.overlay"
}
},
"com_github_apple_swift_nio": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio/archive/2.42.0.tar.gz"
],
"sha256": "e3304bc3fb53aea74a3e54bd005ede11f6dc357117d9b1db642d03aea87194a0",
"strip_prefix": "swift-nio-2.42.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_nio/BUILD.overlay"
}
},
"com_github_apple_swift_nio_http2": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-http2/archive/1.26.0.tar.gz"
],
"sha256": "f0edfc9d6a7be1d587e5b403f2d04264bdfae59aac1d74f7d974a9022c6d2b25",
"strip_prefix": "swift-nio-http2-1.26.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_nio_http2/BUILD.overlay"
}
},
"com_github_apple_swift_nio_transport_services": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-transport-services/archive/1.15.0.tar.gz"
],
"sha256": "f3498dafa633751a52b9b7f741f7ac30c42bcbeb3b9edca6d447e0da8e693262",
"strip_prefix": "swift-nio-transport-services-1.15.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_nio_transport_services/BUILD.overlay"
}
},
"com_github_apple_swift_nio_extras": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-extras/archive/1.4.0.tar.gz"
],
"sha256": "4684b52951d9d9937bb3e8ccd6b5daedd777021ef2519ea2f18c4c922843b52b",
"strip_prefix": "swift-nio-extras-1.4.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_nio_extras/BUILD.overlay"
}
},
"com_github_apple_swift_log": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-log/archive/1.4.4.tar.gz"
],
"sha256": "48fe66426c784c0c20031f15dc17faf9f4c9037c192bfac2f643f65cb2321ba0",
"strip_prefix": "swift-log-1.4.4/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_log/BUILD.overlay"
}
},
"com_github_apple_swift_nio_ssl": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-ssl/archive/2.23.0.tar.gz"
],
"sha256": "4787c63f61dd04d99e498adc3d1a628193387e41efddf8de19b8db04544d016d",
"strip_prefix": "swift-nio-ssl-2.23.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_nio_ssl/BUILD.overlay"
}
},
"com_github_apple_swift_collections": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-collections/archive/1.0.4.tar.gz"
],
"sha256": "d9e4c8a91c60fb9c92a04caccbb10ded42f4cb47b26a212bc6b39cc390a4b096",
"strip_prefix": "swift-collections-1.0.4/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_collections/BUILD.overlay"
}
},
"com_github_apple_swift_atomics": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-atomics/archive/1.1.0.tar.gz"
],
"sha256": "1bee7f469f7e8dc49f11cfa4da07182fbc79eab000ec2c17bfdce468c5d276fb",
"strip_prefix": "swift-atomics-1.1.0/",
"build_file": "@@rules_swift+//third_party:com_github_apple_swift_atomics/BUILD.overlay"
}
},
"build_bazel_rules_swift_index_import": {
"repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive",
"attributes": {
"build_file": "@@rules_swift+//third_party:build_bazel_rules_swift_index_import/BUILD.overlay",
"canonical_id": "index-import-5.8",
"urls": [
"https://github.com/MobileNativeFoundation/index-import/releases/download/5.8.0.1/index-import.tar.gz"
],
"sha256": "28c1ffa39d99e74ed70623899b207b41f79214c498c603915aef55972a851a15"
}
},
"build_bazel_rules_swift_local_config": {
"repoRuleId": "@@rules_swift+//swift/internal:swift_autoconfiguration.bzl%swift_autoconfiguration",
"attributes": {}
}
},
"recordedRepoMappingEntries": [
[
"rules_swift+",
"bazel_tools",
"bazel_tools"
]
]
}
}
},
"facts": {
+38 -7
View File
@@ -1,5 +1,6 @@
load("@rules_oci//oci:defs.bzl", "oci_image", "oci_load", "oci_push")
load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
load("//ci:jar_split.bzl", "jar_split")
#
# Deployment artifacts (tools needed on the host, not in containers)
@@ -50,11 +51,37 @@ pkg_tar(
# Push: bazel run //ci:eagle_server_push
#
# Package the deploy JAR
# Split the Eagle server runtime classpath into a stable third-party layer
# (Scala stdlib, gRPC, Netty, ScalaPB, AWS SDK, ...) and a small first-party
# layer that changes every commit. Most pushes then only re-upload the small
# app layer instead of the whole ~150-300MB fat JAR.
jar_split(
name = "eagle_server_jars",
binary = "//src/main/scala/net/eagle0/eagle:eagle_server",
)
filegroup(
name = "eagle_server_deps_jars",
srcs = [":eagle_server_jars"],
output_group = "deps",
)
filegroup(
name = "eagle_server_app_jars",
srcs = [":eagle_server_jars"],
output_group = "app",
)
pkg_tar(
name = "eagle_server_jar_layer",
srcs = ["//src/main/scala/net/eagle0/eagle:eagle_server_deploy.jar"],
package_dir = "/app",
name = "eagle_server_deps_layer",
srcs = [":eagle_server_deps_jars"],
package_dir = "/app/lib/deps",
)
pkg_tar(
name = "eagle_server_app_layer",
srcs = [":eagle_server_app_jars"],
package_dir = "/app/lib/app",
)
# Package the game resources needed at runtime
@@ -82,8 +109,11 @@ oci_image(
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+DebugNonSafepoints", # Required for JFR to see through inlined methods
"-XX:FlightRecorderOptions=stackdepth=256",
"-jar",
"/app/eagle_server_deploy.jar",
# Classpath glob is expanded by the JVM itself (exec-form, no shell).
# Deps dir first keeps third-party precedence; app last shadows nothing.
"-cp",
"/app/lib/deps/*:/app/lib/app/*",
"net.eagle0.eagle.Main",
],
env = {
"JAVA_OPTS": "-Xmx2g -XX:+UseG1GC",
@@ -91,7 +121,8 @@ oci_image(
exposed_ports = ["40032/tcp"],
tars = [
":busybox_layer",
":eagle_server_jar_layer",
":eagle_server_deps_layer",
":eagle_server_app_layer",
":eagle_resources_layer",
],
workdir = "/app",
+44 -2
View File
@@ -40,6 +40,19 @@ if [ -f "$INFO_PLIST" ]; then
/usr/libexec/PlistBuddy -c "Set :ITSAppUsesNonExemptEncryption false" "$INFO_PLIST" 2>/dev/null \
|| /usr/libexec/PlistBuddy -c "Add :ITSAppUsesNonExemptEncryption bool false" "$INFO_PLIST"
echo "Set ITSAppUsesNonExemptEncryption=false in Info.plist"
# Remove UIApplicationSceneManifest if present.
# Unity 6 generates this key, which opts the app into the iOS scene-based
# lifecycle. This breaks Application.deepLinkActivated because iOS routes
# deep link URLs through UISceneDelegate instead of UIApplicationDelegate,
# and Unity doesn't implement the scene delegate path.
# See: https://issuetracker.unity3d.com/issues/in-135632
if /usr/libexec/PlistBuddy -c "Print :UIApplicationSceneManifest" "$INFO_PLIST" 2>/dev/null; then
echo "Found UIApplicationSceneManifest in Info.plist — removing to fix deep link handling"
/usr/libexec/PlistBuddy -c "Delete :UIApplicationSceneManifest" "$INFO_PLIST"
else
echo "No UIApplicationSceneManifest in Info.plist (deep links should work)"
fi
fi
# Unity always generates "Unity-iPhone" as the main app scheme
@@ -88,6 +101,16 @@ EOF
echo "Exporting IPA..."
# Restore keychain search list before export.
# xcodebuild archive can reset the user keychain search list during long
# builds, dropping the temporary CI keychain that holds the signing cert.
# Re-add it here so xcodebuild -exportArchive can find the certificate.
if [ -n "${KEYCHAIN_NAME:-}" ]; then
echo "Restoring keychain search list (adding $KEYCHAIN_NAME)"
security list-keychains -d user -s "$KEYCHAIN_NAME" login.keychain
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_NAME"
fi
# Debug: List available keychains and signing identities
echo "=== Debug: Available keychains ==="
security list-keychains -d user
@@ -97,11 +120,24 @@ echo "=== Debug: Export options plist ==="
cat "$EXPORT_OPTIONS_PLIST"
echo "=== End debug ==="
# Export IPA (removed -allowProvisioningUpdates as we're using manual signing)
# Export IPA with App Store Connect API key authentication.
# Without the API key, xcodebuild falls back to the Xcode-Token in the
# keychain, which expires periodically and breaks headless CI builds.
EXPORT_AUTH_ARGS=()
if [ -n "${APP_STORE_CONNECT_API_KEY_PATH:-}" ] && [ -n "${APP_STORE_CONNECT_API_KEY_ID:-}" ] && [ -n "${APP_STORE_CONNECT_API_ISSUER_ID:-}" ]; then
echo "Using App Store Connect API key for export authentication"
EXPORT_AUTH_ARGS=(
-authenticationKeyPath "$APP_STORE_CONNECT_API_KEY_PATH"
-authenticationKeyID "$APP_STORE_CONNECT_API_KEY_ID"
-authenticationKeyIssuerID "$APP_STORE_CONNECT_API_ISSUER_ID"
)
fi
xcodebuild -exportArchive \
-archivePath "$ARCHIVE_PATH" \
-exportPath "$EXPORT_PATH" \
-exportOptionsPlist "$EXPORT_OPTIONS_PLIST"
-exportOptionsPlist "$EXPORT_OPTIONS_PLIST" \
"${EXPORT_AUTH_ARGS[@]}"
# Find and rename the IPA to a consistent name
IPA_FILE=$(find "$EXPORT_PATH" -name "*.ipa" | head -1)
@@ -111,3 +147,9 @@ fi
echo "Export complete: $EXPORT_PATH/eagle0.ipa"
ls -la "$EXPORT_PATH"
# Clean up DerivedData for Unity-iPhone builds.
# Each build creates a new ~3.6GB folder (Unity-iPhone-<random>) that
# accumulates and wastes disk space on the build runner.
echo "Cleaning up Unity-iPhone DerivedData..."
find ~/Library/Developer/Xcode/DerivedData -maxdepth 1 -name 'Unity-iPhone-*' -type d -exec rm -rf {} + 2>/dev/null || true
@@ -1,49 +0,0 @@
#!/usr/bin/env bash
# Build iOS Addressables only (no player build)
# This switches Unity to iOS target and builds addressables for CDN upload
set -euxo pipefail
# Read Unity version from project file
UNITY_VERSION=$(grep "m_EditorVersion:" src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt | head -1 | sed 's/m_EditorVersion: //')
# Use runner-specific build directory if EAGLE0_BUILD_DIR is set, otherwise default
BUILD_BASE="${EAGLE0_BUILD_DIR:-/tmp/eagle0}"
WORKSPACE=$(pwd)
echo "Building protos"
./scripts/build_protos.sh
UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"
LOG_PATH=${1:-"${BUILD_BASE}/editor_ios_addressables.log"}
echo "Building iOS Addressables"
mkdir -p "$(dirname "$LOG_PATH")"
# Build Addressables for iOS target
# Uses BuildiOSAddressables which explicitly switches build target
# Capture exit code to show log on failure
set +e
${UNITY_INSTALL_PATH}/${UNITY_VERSION}/Unity.app/Contents/MacOS/Unity \
-nographics \
-batchmode \
-quit \
-executeMethod BuildScript.BuildiOSAddressables \
-logFile "$LOG_PATH" \
-projectPath "$WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0"
UNITY_EXIT_CODE=$?
set -e
if [ $UNITY_EXIT_CODE -ne 0 ]; then
echo ""
echo "Unity build failed with exit code $UNITY_EXIT_CODE"
echo "=== Unity Editor Log (last 200 lines) ==="
tail -200 "$LOG_PATH" || echo "Could not read log file at $LOG_PATH"
echo "=== End of Unity Editor Log ==="
exit $UNITY_EXIT_CODE
fi
echo "iOS Addressables build complete"
echo "Bundles should be in: $WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0/ServerData/iOS/"
+22
View File
@@ -38,3 +38,25 @@ if [ $UNITY_EXIT_CODE -ne 0 ]; then
echo "=== End of Unity Editor Log ==="
exit $UNITY_EXIT_CODE
fi
if [ ! -f "$LOG_PATH" ]; then
echo ""
echo "ERROR: Unity exited successfully but did not write an editor log at $LOG_PATH"
exit 1
fi
# Fail the build if any prefab references are broken — this produces a player
# that launches but has null Inspector fields, which is hard to debug.
if grep -q "Missing Prefab" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has missing prefab references (likely stale Library cache):"
grep "Missing Prefab" "$LOG_PATH"
exit 1
fi
if grep -q "Build asset version error" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has asset version mismatches (likely stale Library cache):"
grep "Build asset version error" "$LOG_PATH" | head -5
exit 1
fi
+16
View File
@@ -53,6 +53,22 @@ if [ $UNITY_EXIT_CODE -ne 0 ]; then
exit $UNITY_EXIT_CODE
fi
# Fail the build if any prefab references are broken — this produces a player
# that launches but has null Inspector fields, which is hard to debug.
if grep -q "Missing Prefab" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has missing prefab references (likely stale Library cache):"
grep "Missing Prefab" "$LOG_PATH"
exit 1
fi
if grep -q "Build asset version error" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has asset version mismatches (likely stale Library cache):"
grep "Build asset version error" "$LOG_PATH" | head -5
exit 1
fi
echo "iOS Unity build complete"
echo "Xcode project generated at: $BUILD_PATH"
ls -la "$BUILD_PATH"
+22
View File
@@ -38,3 +38,25 @@ if [ $UNITY_EXIT_CODE -ne 0 ]; then
echo "=== End of Unity Editor Log ==="
exit $UNITY_EXIT_CODE
fi
if [ ! -f "$LOG_PATH" ]; then
echo ""
echo "ERROR: Unity exited successfully but did not write an editor log at $LOG_PATH"
exit 1
fi
# Fail the build if any prefab references are broken — this produces a player
# that launches but has null Inspector fields, which is hard to debug.
if grep -q "Missing Prefab" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has missing prefab references (likely stale Library cache):"
grep "Missing Prefab" "$LOG_PATH"
exit 1
fi
if grep -q "Build asset version error" "$LOG_PATH"; then
echo ""
echo "ERROR: Build has asset version mismatches (likely stale Library cache):"
grep "Build asset version error" "$LOG_PATH" | head -5
exit 1
fi
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
set -euo pipefail
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
write_developer_dir_override() {
if [ "$(uname -s)" != "Darwin" ]; then
return
fi
local developer_dir=""
if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then
developer_dir="/Applications/Xcode.app/Contents/Developer"
elif [ -d "/Library/Developer/CommandLineTools" ]; then
developer_dir="/Library/Developer/CommandLineTools"
else
developer_dir="$(xcode-select -p 2>/dev/null || true)"
fi
if [ -z "$developer_dir" ] || [ ! -d "$developer_dir" ]; then
echo "ERROR: no usable Apple developer directory found"
echo "Install Command Line Tools with: xcode-select --install"
echo "Full Xcode is only required for workflows that build/sign Apple apps."
exit 1
fi
export DEVELOPER_DIR="$developer_dir"
if [ -f .bazelrc.local ] && [ -z "${CI:-}" ]; then
echo "Keeping existing .bazelrc.local outside CI"
else
{
echo "# Generated by ci/github_actions/ensure_bazel_installed.sh; do not edit."
printf 'common:macos --repo_env=DEVELOPER_DIR=%s\n' "$developer_dir"
} > .bazelrc.local
fi
if [ -n "${GITHUB_ENV:-}" ]; then
echo "DEVELOPER_DIR=$developer_dir" >> "$GITHUB_ENV"
fi
echo "Using Apple developer directory at $developer_dir"
}
write_developer_dir_override
if [ -n "${GITHUB_PATH:-}" ]; then
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
fi
if command -v bazel >/dev/null 2>&1; then
echo "Using bazel at $(command -v bazel)"
bazel --version
exit 0
fi
if ! command -v bazelisk >/dev/null 2>&1; then
if ! command -v brew >/dev/null 2>&1; then
echo "ERROR: neither bazel nor bazelisk is on PATH, and Homebrew is unavailable"
exit 1
fi
echo "Installing bazelisk with Homebrew"
brew install bazelisk
fi
BAZEL_BIN_DIR="${RUNNER_TEMP:-/tmp}/bazel-bin"
mkdir -p "$BAZEL_BIN_DIR"
ln -sf "$(command -v bazelisk)" "$BAZEL_BIN_DIR/bazel"
if [ -n "${GITHUB_PATH:-}" ]; then
echo "$BAZEL_BIN_DIR" >> "$GITHUB_PATH"
fi
export PATH="$BAZEL_BIN_DIR:$PATH"
echo "Using bazelisk as bazel at $BAZEL_BIN_DIR/bazel"
bazel --version
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# Fetch LFS files from Gitea mirror with retry.
#
# Gitea's mirror-sync API is async — the webhook fires on push but the
# actual sync may still be in progress when CI starts. Retry with backoff
# to bridge the gap.
#
# Usage:
# ./ci/github_actions/fetch_lfs.sh # full pull
# ./ci/github_actions/fetch_lfs.sh --include="path/to/*" # selective pull
set -euo pipefail
COMMON_PATHS="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="${COMMON_PATHS}:${PATH}"
MAX_ATTEMPTS=5
RETRY_DELAY=15
if [ -n "${GITHUB_PATH:-}" ]; then
for path in /opt/homebrew/bin /usr/local/bin; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
fi
done
fi
if ! git lfs version >/dev/null 2>&1; then
if ! command -v brew >/dev/null 2>&1; then
echo "ERROR: git-lfs is unavailable, and Homebrew is not on PATH"
exit 1
fi
echo "Installing git-lfs with Homebrew"
brew install git-lfs
fi
echo "Using git-lfs at $(command -v git-lfs)"
git lfs version
git lfs install
echo "LFS objects before pull:"
git lfs ls-files | wc -l
GIT_LFS_PULL=(git lfs pull)
if [ -n "${GITHUB_TOKEN:-}" ]; then
BASIC_AUTH=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 | tr -d '\n')
GIT_LFS_PULL=(git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $BASIC_AUTH" lfs pull)
fi
for i in $(seq 1 $MAX_ATTEMPTS); do
if "${GIT_LFS_PULL[@]}" "$@"; then
echo "LFS objects after pull:"
git lfs ls-files | wc -l
exit 0
fi
if [ "$i" -lt "$MAX_ATTEMPTS" ]; then
echo "LFS pull attempt $i/$MAX_ATTEMPTS failed, retrying in ${RETRY_DELAY}s..."
sleep $RETRY_DELAY
fi
done
echo "LFS pull failed after $MAX_ATTEMPTS attempts"
exit 1
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
set -euxo pipefail
# Read Unity version from project file
UNITY_VERSION=$(grep "m_EditorVersion:" src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt | head -1 | sed 's/m_EditorVersion: //')
# Use runner-specific build directory if EAGLE0_BUILD_DIR is set, otherwise default
BUILD_BASE="${EAGLE0_BUILD_DIR:-/tmp/eagle0}"
WORKSPACE=$(pwd)
UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"
LOG_PATH="${BUILD_BASE}/editor_editmode_tests.log"
RESULTS_PATH="${BUILD_BASE}/editmode-test-results.xml"
mkdir -p "$BUILD_BASE"
echo "Building protos"
./scripts/build_protos.sh
echo "Running Unity EditMode tests"
set +e
"${UNITY_INSTALL_PATH}/${UNITY_VERSION}/Unity.app/Contents/MacOS/Unity" \
-nographics \
-batchmode \
-quit \
-executeMethod eagle0.Tests.DynamicTextBindingTestRunner.Run \
-testResults "$RESULTS_PATH" \
-logFile "$LOG_PATH" \
-projectPath "$WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0"
UNITY_EXIT_CODE=$?
set -e
if [ $UNITY_EXIT_CODE -ne 0 ]; then
echo ""
echo "Unity EditMode tests failed with exit code $UNITY_EXIT_CODE"
echo "=== Unity EditMode Test Log (last 200 lines) ==="
tail -200 "$LOG_PATH" || echo "Could not read log file at $LOG_PATH"
echo "=== End of Unity EditMode Test Log ==="
exit $UNITY_EXIT_CODE
fi
if [ ! -f "$LOG_PATH" ]; then
echo ""
echo "ERROR: Unity exited successfully but did not write an editor log at $LOG_PATH"
exit 1
fi
if [ ! -f "$RESULTS_PATH" ]; then
echo ""
echo "ERROR: Unity exited successfully but did not write test results at $RESULTS_PATH"
exit 1
fi
echo "Unity EditMode tests complete"
+57
View File
@@ -0,0 +1,57 @@
"""Split a JVM binary's runtime classpath into first-party and third-party jar sets.
This exists so the Docker image can place rarely-changing third-party jars in a
lower OCI layer and frequently-changing first-party jars in a small top layer,
so most pushes only re-upload the small layer.
"""
def _unique_name(jar):
# short_path is unique per jar and stable across commits (it depends only on
# the jar's own package/coordinate, not on unrelated targets), so the deps
# layer's tar entries stay byte-identical and its blob digest stays cached.
path = jar.short_path
if path.startswith("../"):
path = path[3:]
return path.replace("+", "_").replace("/", "_").replace("~", "_")
def _impl(ctx):
info = ctx.attr.binary[JavaInfo]
app = []
deps = []
seen = {}
for jar in sorted(info.transitive_runtime_jars.to_list(), key = lambda f: f.path):
workspace = jar.owner.workspace_name if jar.owner else ""
bucket = "app" if workspace == "" else "deps"
out_name = _unique_name(jar)
key = bucket + "/" + out_name
if key in seen:
fail("jar_split: duplicate output name %r for %s and %s" % (
key,
seen[key],
jar.path,
))
seen[key] = jar.path
link = ctx.actions.declare_file(ctx.label.name + "/" + key)
ctx.actions.symlink(output = link, target_file = jar)
(app if bucket == "app" else deps).append(link)
return [
DefaultInfo(files = depset(app + deps)),
OutputGroupInfo(app = depset(app), deps = depset(deps)),
]
jar_split = rule(
implementation = _impl,
doc = "Partitions a JVM binary's transitive runtime jars into 'app' " +
"(first-party, empty workspace) and 'deps' (third-party) output groups.",
attrs = {
"binary": attr.label(
mandatory = True,
providers = [[JavaInfo]],
doc = "A jvm binary/library target whose runtime classpath to split.",
),
},
)
+281
View File
@@ -0,0 +1,281 @@
# Allied Victory: Battle Resolution Flow
How allied victories work end-to-end, from Shardok tactical resolution through Eagle strategic
processing to player-facing aftermath decisions.
## 1. Battle Setup (Eagle -> Shardok)
When Eagle sends a battle to Shardok via `RequestBattlesAction`, each player gets specific victory
conditions:
| Player | Victory Conditions |
|-------------|-----------------------------------------------------------------------|
| Attacker(s) | `HoldsCriticalTiles`, `LastPlayerStanding`, `LastAllianceStanding` |
| Defender | `LastPlayerStanding`, `WinAfterMaxRounds` |
This is set in `RequestBattlesAction.shardokPlayers`.
Alliance information is sent separately in `PlayerSetupInfo.allies`. Eagle reads each player's
`factionRelationships` and includes all non-HOSTILE factions as allies
(`ShardokInterfaceGrpcClient.scala:75-80`).
## 2. Victory Condition Evaluation (Shardok)
Victory conditions are checked in `UpdateGameStatusAction.cpp` in priority order:
### Check 1: LastPlayerStanding (any time)
If exactly **one** player has surviving units and has `LastPlayerStanding`:
- That player is the sole winner.
- This applies to solo victories only (1 survivor).
### Check 2: LastAllianceStanding (any time)
If **multiple** players survive, check if they form a winning alliance:
- ALL survivors must have `LastAllianceStanding` condition
- ALL survivors must be **mutually** allied (every pair checks both directions)
- If yes: all survivors are winners
This triggers for AssaultProvince battles when allied attackers eliminate all defenders. Since the
defender does **not** have `LastAllianceStanding`, the check correctly requires that only the
allied attackers remain alive.
### Check 3: WinAfterMaxRounds (end-of-round only)
If the round counter exceeds `max_rounds`:
- Find the player with `WinAfterMaxRounds` (always the defender)
- That player wins, even if they have no surviving units
- Eagle validates exactly 1 player has this condition (`internalRequire` in `RequestBattlesAction`)
### Check 4: HoldsCriticalTiles (end-of-round only)
**Single-player castle control**: If one player with `HoldsCriticalTiles` occupies ALL critical
tiles with hero-bearing units, that player wins. Additionally, any other player who:
- Has `HoldsCriticalTiles`
- Is **mutually** allied with the castle holder
is also added to `winning_shardok_ids` as a co-winner.
**Allied castle control**: If multiple players collectively occupy all critical tiles with
hero-bearing units, AND:
- All occupants have `HoldsCriticalTiles`
- All occupants are mutually allied
Then all occupants are winners together.
## 3. EndGameCondition Assignment Per Player (Shardok -> Eagle)
Shardok assigns each player a `Victory` or `Loss`. All winners receive `Victory`; there is no
`AllyVictory` distinction. The `EndGameCondition` proto reserves fields 2 (`ally_victory`) and
3 (`draw`) for backwards compatibility but Eagle rejects both.
`GameOverResponsePopulator` validates that any player allied to a winner is also in
`winning_shardok_ids`. If an ally is missing from the winners list, it throws an internal error.
**Known issue**: This validation is too strict for `LastPlayerStanding`. When one allied attacker
is the sole survivor, their dead co-attacker is allied to the winner but legitimately not in
`winning_shardok_ids` (they're dead). The throw should be changed to `Loss` for dead allies, or
the check should only apply when the ally has surviving units.
| Condition | Criterion |
|-----------|-----------|
| `Victory(type)` | Player is in `winning_shardok_ids` |
| `Loss(type)` | Player is not in `winning_shardok_ids` |
The `type` is the VictoryCondition that caused the game to end (e.g., `HoldsCriticalTiles`).
### When do multiple players get Victory?
In standard AssaultProvince battles:
1. **Allied attackers jointly hold all castles** -> both get `Victory(HoldsCriticalTiles)`.
2. **One attacker holds all castles alone, ally has `HoldsCriticalTiles` and is mutually allied**
-> both get `Victory(HoldsCriticalTiles)`. The ally is added to `winning_shardok_ids` by
`UpdateGameStatusAction`.
3. **Allied attackers eliminate all defenders** -> both get `Victory(LastAllianceStanding)`.
This triggers because both have `LastAllianceStanding` and are mutually allied.
4. **One attacker holds all castles, co-attacker is NOT allied** -> only the castle holder
gets `Victory(HoldsCriticalTiles)`; the non-allied co-attacker gets `Loss`.
## 4. Eagle Processes Battle Results
`ResolveBattleAction.scala` receives `BattleResolution` containing each player's
`EndGameCondition` and resolved units.
### Winner/Loser Partition
Players are split by `isVictory` (line 383-386):
- `winningResolvedPlayers`: Victory
- `losingResolvedPlayers`: Loss
### The `unitReturned` Function (line 765-788)
Determines which units go home vs stay at the battle province:
| Unit Status | Returned? | Notes |
|---------------|-----------|-------|
| `Fled` | Always | Sent to their army's flee province |
| `NeverEntered`| Conditional | Only if: attacker AND has flee province AND did NOT win (`!isVictory`) |
| `Captured` | Never | |
| `Normal` | Never | |
| `Retreated` | Never | |
| `Outlawed` | Never | Becomes unaffiliated hero |
Key point: `NeverEntered` units from **winning** factions stay at the battle province rather than
being sent home. This is important for bounced co-attackers who are allied with the actual winner.
### Withdrawn/Fled Unit Routing (line 690-706)
For units that ARE returned, `armyFromResolvedArmy` builds a returning army with
`fleeProvinceId = None`. If the army has no `fleeProvinceId`, it becomes "shattered" (units
become outlaws in the battle province). If the original army had a `fleeProvinceId` set, returned
units are sent there as incoming armies.
### Battle Resolution Branching (line 397-552)
Three branches based on who won:
#### Branch A: Defender Won
Triggered when: `winningShardokPlayers.exists(_.isDefender)`
- Executes `ProvinceHeldAction`
- All non-defender, non-returned, non-outlawed units are **captured**
- Province stays with the defending faction
#### Branch B: Single Attacker Won
Triggered when: exactly 1 attacking winner
- Executes `ProvinceConqueredAction` immediately
- Winning attacker's non-fled units occupy the province
- Losing defenders' non-fled units are captured
- Province transfers to the attacker
#### Branch C: Multiple Allied Attackers Won
Triggered when: 2+ attacking winners
- Executes `MultiVictorBattleSetupAction`
- Creates `PendingConquestInfo` with aftermath claimants
- Province enters the **Battle Aftermath** phase
## 5. Battle Aftermath (Multi-Victor Only)
When multiple allied attackers win, the province enters an aftermath decision phase where players
decide who keeps it.
### Claimant Setup
Each attacking winner becomes an `AftermathClaimant` with:
- `units`: their non-fled, non-outlawed units still at the battle province
- `armySize`: total troop count of those units
- `broughtGold` / `broughtFood`: supplies their armies carried
Claimants are **sorted by army size descending** (largest army decides first).
### Decision Phase
Claimants are presented with a choice **one at a time**, in order:
**If no one has chosen "Keep" yet:**
- **Keep Province**: claim the province for your faction
- **Withdraw To**: pick an adjacent province to march your army to, optionally carrying up to
the gold/food you brought
**If someone already chose "Keep":**
- **Withdraw To** is the only option (can't have two keepers)
**Last undecided claimant:**
- If no one has chosen "Keep" yet, the last claimant **automatically keeps** (no command shown,
resolved by `AutoResolveBattleAftermathAction`)
- This guarantees someone always claims the province
### Finalization
Once all claimants have decided (`FinalizeAftermathAction`):
1. The keeper's units run through `ProvinceConqueredAction` -- province transfers to their faction
2. Withdrawing claimants' units become incoming armies to their chosen adjacent province,
arriving next round, carrying the specified supplies
3. `PendingConquestInfo` is cleared from the province
## 6. Summary: Who Gets What
### Two allied attackers jointly hold all castles
- Shardok: Both get `Victory(HoldsCriticalTiles)` (both in `winning_shardok_ids`)
- Eagle: Both are attacking winners -> MultiVictorBattleSetupAction
- Players: Largest army picks first: Keep or Withdraw. Last player auto-keeps if no one chose Keep.
### One attacker holds all castles, allied attacker doesn't
- Shardok: Castle-holder gets `Victory(HoldsCriticalTiles)`. Mutually-allied co-attacker with
`HoldsCriticalTiles` is added to `winning_shardok_ids` -> also gets `Victory(HoldsCriticalTiles)`.
- Eagle: Both are attacking winners -> MultiVictorBattleSetupAction -> Battle Aftermath.
- Players: Largest army picks first: Keep or Withdraw.
### Allied attackers eliminate all defenders
- Shardok: Both attackers have `LastAllianceStanding` and are mutually allied -> both get
`Victory(LastAllianceStanding)`.
- Eagle: Both are attacking winners -> MultiVictorBattleSetupAction -> Battle Aftermath.
- Players: Largest army picks first: Keep or Withdraw.
### Non-allied co-attackers: one holds all castles
- Shardok: Castle-holder gets `Victory(HoldsCriticalTiles)`, non-allied co-attacker gets
`Loss(HoldsCriticalTiles)`.
- Eagle: Single attacker won -> ProvinceConqueredAction. Non-allied co-attacker's units are
captured along with the defender's.
### One allied attacker is sole survivor (LastPlayerStanding)
- Shardok: Sole survivor gets `Victory(LastPlayerStanding)`. Dead ally should get `Loss`.
- **BUG**: `GameOverResponsePopulator` currently throws because dead ally is allied to winner
but not in `winning_shardok_ids`. Needs fix — see known issue in Section 3.
- Eagle (once fixed): Single attacker won -> ProvinceConqueredAction. Dead ally's units were
already destroyed in battle.
### Single attacker wins (any condition, no co-attackers)
- No alliance considerations. ProvinceConqueredAction immediately.
### Defender wins (WinAfterMaxRounds or LastPlayerStanding)
- ProvinceHeldAction. All non-returned attacker units are captured.
## 7. Edge Cases and Known Issues
### BUG: Dead ally causes crash via LastPlayerStanding
When one allied attacker is the sole survivor (both the co-attacker and defender are dead),
`LastPlayerStanding` fires and only the survivor is in `winning_shardok_ids`. The
`GameOverResponsePopulator` then sees the dead co-attacker is allied to the winner but not in
`winning_shardok_ids`, and throws `ShardokInternalErrorException`. Fix: dead allies should
receive `Loss`, not trigger a validation error.
### Non-allied co-attackers eliminate all defenders
Two non-allied attackers who both survive after eliminating the defender cannot win via
`LastAllianceStanding` (they aren't mutually allied). The game continues until max rounds,
at which point the defender wins via `WinAfterMaxRounds`. They must capture all critical tiles.
### Non-allied co-attackers: one holds all castles
Only the castle holder wins. The non-allied co-attacker gets `Loss` and their units are captured
along with the defender's. The mutual-alliance check in `UpdateGameStatusAction` prevents
non-allied players from being added to `winning_shardok_ids`.
## Key File References
| Component | File |
|-----------|------|
| Victory condition checking | `src/main/cpp/net/eagle0/shardok/library/actions/UpdateGameStatusAction.cpp` |
| Per-player EndGameCondition | `src/main/cpp/net/eagle0/shardok/server/GameOverResponsePopulator.cpp` |
| Battle setup (victory conditions) | `src/main/scala/.../library/actions/impl/action/RequestBattlesAction.scala` |
| Alliance communication | `src/main/scala/.../shardok_interface/ShardokInterfaceGrpcClient.scala:75-80` |
| Battle result processing | `src/main/scala/.../library/actions/impl/action/ResolveBattleAction.scala` |
| Unit return logic | `ResolveBattleAction.scala:765-788` (`unitReturned`) |
| Multi-victor setup | `src/main/scala/.../library/actions/impl/action/MultiVictorBattleSetupAction.scala` |
| Aftermath availability | `src/main/scala/.../library/actions/availability/AvailableBattleAftermathDecisionCommandFactory.scala` |
| Aftermath command | `src/main/scala/.../library/actions/impl/command/BattleAftermathDecisionCommand.scala` |
| Auto-resolve last claimant | `src/main/scala/.../library/actions/impl/action/AutoResolveBattleAftermathAction.scala` |
| Finalize aftermath | `src/main/scala/.../library/actions/impl/action/FinalizeAftermathAction.scala` |
| EndGameCondition enum | `src/main/scala/.../model/state/shardok_battle/EndGameCondition.scala` |
+25 -1
View File
@@ -12,7 +12,7 @@ This document catalogs all media assets in the Unity project for licensing revie
|----------|-------|-------|
| Images | 10,637 | Mostly PNG icons and UI sprites |
| Audio | 1,778 | 26 music tracks + 1,752 sound effects |
| 3D Models | 52 | Bridge pack only |
| 3D Models | 66+ | Bridge pack, Animal pack deluxe, Honey Badger |
| Fonts | 16 | TTF files |
---
@@ -55,6 +55,30 @@ These are commercial Unity Asset Store purchases tied to your account:
- **Contents:** Bridge construction pieces
- **License:** Unity Asset Store
### Animal pack deluxe
- **Location:** `Assets/Animal pack deluxe/`
- **Publisher:** janpec
- **Asset Store Link:** https://assetstore.unity.com/packages/3d/characters/animals/animal-pack-deluxe-99702
- **Contents:** 26 rigged and animated 3D animal models (bear, boar, crocodile, wolf, frog, crab, rabbit, scorpion, snake, stag, deer, rat, goat, pig, etc.) with idle, walk, run, eat, attack, and die animations
- **Used for:** Beast province effects on the strategic map (AnimalEffect)
- **License:** Unity Asset Store
### 2D Monster Pack: Basic Bundle (+PSB)
- **Location:** `Assets/DungeonMonsters2D/`
- **Publisher:** SP1
- **Asset Store Link:** https://assetstore.unity.com/packages/2d/characters/2d-monster-pack-basic-bundle-psb-328637
- **Contents:** 2D animated monster sprites with PSB (Photoshop) source files. Characters: SkeletonWarrior, SkeletonArcher, SkeletonMage, Zombie, ZombieWarrior, Demon, Succubus, Imp, Spider, Rat, Vampire, DragonRed, Butcher
- **Used for:** Beast province effects (MonsterEffect, DragonEffect) and human-type beast effects on the strategic map
- **License:** Unity Asset Store
### Honey Badger 3D Model
- **Location:** `Assets/HoneyBadger/`
- **Creator:** WildMesh 3D (@WildMesh_3D)
- **Source:** https://sketchfab.com/3d-models/realistic-honey-badger-3d-model-09751ed5383c4afb924cfb6485d313f1
- **Contents:** Rigged 3D honey badger model (FBX) with 63 animations and PBR texture
- **Used for:** Honey badger beast province effect (AnimalEffect)
- **License:** Purchased via Sketchfab/Patreon
### Fantasy Interface Sounds
- **Location:** `Assets/Fantasy Interface Sounds/`
- **Count:** 320 WAV files
+167 -28
View File
@@ -17,28 +17,26 @@ ProvinceBeastsController
|------|---------|
| `Assets/Eagle/ProvinceBeastsController.cs` | Routes beast names to prefabs, positions effects |
| `Assets/Eagle/BeastsEffect.cs` | Generic effect (circling birds via particle system) |
| `Assets/Eagle/DragonEffect.cs` | Dragon-specific effect (animated PSD Importer prefab) |
| `Assets/Eagle/Effects/BeastsEffect.prefab` | Generic effect prefab |
| `Assets/Eagle/Effects/DragonEffect.prefab` | Dragon effect prefab |
| `Assets/Eagle/DragonEffect.cs` | Dragon-specific effect (3D model with flying/ground modes) |
| `Assets/Eagle/MonsterEffect.cs` | Wandering 2D monster group (DungeonMonsters2D prefabs) |
| `Assets/Eagle/AnimalEffect.cs` | Wandering 3D animal group (Animal Pack Deluxe prefabs) |
| `Assets/Eagle/Effects/` | All effect prefabs |
## Adding a new beast type
### 1. Create the effect MonoBehaviour
### 1. Create the effect MonoBehaviour (or reuse an existing one)
Create `Assets/Eagle/<BeastName>Effect.cs`. Two approaches:
Three effect scripts exist for different asset types:
**Particle-based** (like `BeastsEffect.cs`): Good for simple effects like swarms, packs, or atmospheric particles. Build particle systems programmatically in `Awake()`.
**MonsterEffect** (2D sprites, DungeonMonsters2D): Spawns a group of wandering 2D monsters. Uses PascalCase animator states (`Idle`, `Move`) and triggers (`AttackTrigger`, `SpecialATrigger`). Flips sprite X scale for facing direction. Best for DungeonMonsters2D prefabs.
**Animated prefab** (like `DragonEffect.cs`): Good for a single creature with bone-driven animation. Requires:
- A PSD Importer `.psb` file with the creature art
- `com.unity.2d.animation` and `com.unity.2d.psdimporter` packages (already installed)
- An Animator Controller with animation clips
- The effect script instantiates the animated prefab and drives its position/animation
**AnimalEffect** (3D models, Animal Pack Deluxe): Spawns a group of wandering 3D animals. Uses lowercase animator states (`idle`, `walk`, `eat`, `attack`) with `Animator.Play()`. Rotates model on Y axis for facing. Sets `sortingOrder=103`, `renderQueue=4000`, and `ZTest=Always` to render above the map. Best for Animal Pack Deluxe prefabs.
Your MonoBehaviour should:
- Use `[RequireComponent(typeof(RectTransform))]` for UI canvas positioning
- Accept tuning parameters as public fields (circle radius, speed, scale, etc.)
- Clean up materials in `OnDestroy()` to avoid leaks
**DragonEffect** (single animated 3D creature): Spawns a 3D dragon that alternates between flying (circling at altitude with fly actions) and grounded (wandering with ground actions) modes. Uses `Animator.Play()` with DragonMapAnims controller. Best for large creatures with flight capabilities.
**Particle-based** (like `BeastsEffect.cs`): Good for simple effects like swarms or atmospheric particles.
To create a new effect script, use `[RequireComponent(typeof(RectTransform))]` for UI canvas positioning and accept tuning parameters as public fields.
### 2. Create the prefab
@@ -83,21 +81,161 @@ Use `[ContextMenu]` methods on `ProvinceBeastsController` to test:
Beast names come from `BeastInfo.SingularName` in the proto, which uses the canonical `singularName` from `src/main/resources/net/eagle0/eagle/beasts.tsv`. The switch in `GetEffectPrefab` uses exact string matching on this canonical name (e.g. `"dragon"`, `"wolf"`, `"skeleton"`).
## Existing beast types in the game
Human-type beasts (pirates, bandits, etc.) are matched via a `HumanBeastNames` HashSet in `ProvinceBeastsController` rather than individual switch cases.
See `src/main/resources/net/eagle0/eagle/beasts.tsv` for the full list. Some candidates for custom effects:
## Beast animation coverage
| singularName | Notes |
|---|---|
| dragon | Has custom effect (animated 2D dragon) |
| wolf | Common, could use pack/howling effect |
| bear | Could use large creature effect |
| skeleton | Could reuse DungeonMonsters2D Skeleton asset |
| demon | Could reuse DungeonMonsters2D Demon asset |
| spider | Could reuse DungeonMonsters2D Spider asset |
| rat | Could reuse DungeonMonsters2D Rat asset |
| vampire | Could reuse DungeonMonsters2D Vampire asset |
| zombie | Could reuse DungeonMonsters2D Zombie asset |
### Custom animations
| Beast | Effect Type | Asset Pack | Prefabs Used |
|---|---|---|---|
| dragon | DragonEffect | 3dFoin Dragon | dragon_skin.FBX (w/ DragonMapAnims controller) |
| skeleton | MonsterEffect | DungeonMonsters2D | SkeletonWarrior, SkeletonArcher, SkeletonMage |
| zombie | MonsterEffect | DungeonMonsters2D | Zombie, ZombieWarrior |
| rat | MonsterEffect + AnimalEffect | DungeonMonsters2D + Animal Pack Deluxe | Rat (2D), Rat (3D) |
| spider | MonsterEffect | DungeonMonsters2D | Spider |
| demon | MonsterEffect | DungeonMonsters2D | Demon, Succubus |
| orc | MonsterEffect | DungeonMonsters2D | Imp |
| vampire | MonsterEffect | DungeonMonsters2D | Vampire |
| knight types (6 names) | AnimalEffect | Polytope Studio | PT_Male_Knight_01/02, PT_Female_Knight_01/02 (w/ HumanMapAnims controller) |
| soldier types (8 names) | AnimalEffect | Polytope Studio | PT_Male_Soldier_01/02, PT_Female_Soldier_01/02 (w/ HumanMapAnims controller) |
| archer types (3 names) | AnimalEffect | Polytope Studio | PT_Male_Archer_01/02, PT_Female_Archer_01/02 (w/ HumanMapAnims controller) |
| militia types (8 names) | AnimalEffect | Polytope Studio | PT_Male_Militia_01/02, PT_Female_Militia_01/02 (w/ HumanMapAnims controller) |
| peasant types (9 names) | AnimalEffect | Polytope Studio | PT_Male_Peasant_01, PT_Female_Peasant_01_a (w/ HumanMapAnims controller) |
| clown | AnimalEffect | Clown Pack | Clown, Fat Clown (w/ per-prefab controller overrides) |
| giant | AnimalEffect | Polytope Studio | PT_Male/Female_Peasant at 3x scale (w/ HumanMapAnims controller) |
| ogre, troll | AnimalEffect | Orc-Ogre Pack | OrcOgre_Animated (w/ OgreMapAnims controller) |
| bear | AnimalEffect | Animal Pack Deluxe | Brown_bear |
| boar | AnimalEffect | Animal Pack Deluxe | Wild_boar |
| crocodile | AnimalEffect | Animal Pack Deluxe | Crocodile |
| snake | AnimalEffect | Animal Pack Deluxe | Viper |
| crab | AnimalEffect | Animal Pack Deluxe | Crab |
| frog | AnimalEffect | Animal Pack Deluxe | Common_frog, Common_frog_v2, Common_frog_v3 |
| rabbit | AnimalEffect | Animal Pack Deluxe | Wild_rabbit, Wild_rabbit_v2 |
| salamander | AnimalEffect | Animal Pack Deluxe | Fire_salamander |
| scorpion | AnimalEffect | Animal Pack Deluxe | Scorpion, Yellow_fattail_scorpion |
| stag | AnimalEffect | Animal Pack Deluxe | Deer, Deer_male |
| wild goat | AnimalEffect | Animal Pack Deluxe | Goat, Ibex |
| wild pig | AnimalEffect | Animal Pack Deluxe | Iron_age_pig, Iron_age_pig_v2 |
| wolf, wolverine | AnimalEffect | Animal Pack Deluxe | Wolf |
| honey badger | AnimalEffect | HoneyBadger (Sketchfab) | HoneyBadger (w/ HoneyBadgerMapAnims controller) |
| raccoon | AnimalEffect | Raccoon (Sketchfab) | Raccoon (w/ RaccoonMapAnims controller) |
| tiger | AnimalEffect | ithappy Animals FREE | Tiger_001 (w/ TigerMapAnims controller) |
| elephant | AnimalEffect | Animal Pack Deluxe v2 | African_elephant, Indian_elephant (w/ ElephantMapAnims controller) |
| mammoth | AnimalEffect | Animal Pack Deluxe v2 | African_elephant, Indian_elephant (w/ ElephantMapAnims controller) |
| hippopotamus | AnimalEffect | Africa Animals Pack Low Poly V2 | Hippopotamus (w/ HippopotamusMapAnims controller) |
| lion | AnimalEffect | Africa Animals Pack Low Poly V1 | Lion, Lioness (w/ LionMapAnims controller) |
| velociraptor | AnimalEffect | Dino Pack Low Poly V1 | VelociraptorColor1, VelociraptorColor2 (w/ VelociraptorMapAnims controller) |
| black panther | AnimalEffect | Africa Animals Pack Low Poly V1 | BlackPanther (w/ BlackPantherMapAnims controller) |
| rhinoceros | AnimalEffect | Africa Animals Pack Low Poly V1 | Rhinoceros (w/ RhinocerosMapAnims controller) |
| gorilla | AnimalEffect | Africa Animals Pack Low Poly V2 | Gorilla (w/ GorillaMapAnims controller) |
| hyena | AnimalEffect | Africa Animals Pack Low Poly V2 | Hyena (w/ HyenaMapAnims controller) |
| leopard | AnimalEffect | Africa Animals Pack Low Poly V2 | Leopard (w/ LeopardMapAnims controller) |
| warthog | AnimalEffect | Africa Animals Pack Low Poly V2 | Phacochoerus (w/ WarthogMapAnims controller) |
| emu | AnimalEffect | Australia Animals Pack V1 | Emu (w/ EmuMapAnims controller) |
| kangaroo | AnimalEffect | Australia Animals Pack V1 | Kangaroo (w/ KangarooMapAnims controller) |
| tasmanian devil | AnimalEffect | Australia Animals Pack V1 | TasmanianDevil (w/ TasmanianDevilMapAnims controller) |
| hippogryph | DragonEffect | Heroic Fantasy Creatures Full Pack Vol 2 | Hippogriff_PBR (w/ HippogryphMapAnims controller) |
### Human-type beasts
34 human-type beast names use 3D Polytope Studio characters grouped into 5 archetypes. Each archetype uses a shared `HumanMapAnims.controller` that retargets Clown animation clips (idle, walk, attack, damage) via Unity's Humanoid system. One additional human type (psychopath) uses the 2D Butcher sprite from DungeonMonsters2D.
| Archetype | Polytope Type | Beast Names (count) |
|---|---|---|
| **Knight** (heavy armor) | Knight M/F x2 | cultist, heretic, cannibal, terrorist, cossack, desperado (6) |
| **Soldier** (medium armor) | Soldier M/F x2 | bandit, brigand, robber, highwayman, marauder, dacoit, freebooter, mobster (8) |
| **Archer** (light armor, ranged) | Archer M/F x2 | thief, pirate, buccaneer (3) |
| **Militia** (light armed) | Militia M/F x2 | hooligan, street tough, ruffian, scalawag, ne'er-do-well, crook, miscreant, asshole (8) |
| **Peasant** (unarmed) | Peasant M/F | agitator, instigator, rabble-rouser, separatist, particularist, nihilist, proud boy, rebel, traitor (9) |
Asset packs: Polytope Studio - Lowpoly Medieval Characters (Soldiers, Knights, Militia, Archers, Peasants)
| **Butcher** (armed loner) | DungeonMonsters2D Butcher | psychopath (1) |
### No custom animation (falls back to generic vultures)
Ordered by spawn likelihood (most common first):
| Beast | Likelihood | Notes |
|---|---|---|
| chimpanzee | 0.04 | Primate |
| unknown | 0.00 | Intentional fallback |
## Using low-poly animal packs (Africa Animals, Dino Pack)
Assets from these packs (by the same author) require extra setup because they ship with **Legacy** animation import and include physics components that conflict with AnimalEffect. The workflow below applies to all of them:
- Africa Animals Pack Low Poly V1 (Lion, Lioness, Black Panther, Crocodile, Elephant, Giraffe, Rhinoceros, Tiger, Zebra)
- Africa Animals Pack Low Poly V2 (Hippopotamus, Antelope, Gorilla, Hyena, Leopard, Phacochoerus/Warthog)
- Dino Pack Low Poly V1 (Velociraptor, Brontosaurus, Pteranodon, Stegosaurus, T-Rex, Triceratops)
- Australia Animals Pack V1 (Chlamydosaurus/Frilled Lizard, Echidna, Emu, Kangaroo, Koala, Platypus, Tasmanian Devil)
### Per-animal setup steps
1. **Switch FBX import to Generic animation type.**
In the `.fbx.meta` file (location varies by pack):
- Change `animationType: 1` to `animationType: 2`
- Change `avatarSetup: 0` to `avatarSetup: 1` (newer format) — older metas without `avatarSetup` will auto-create an avatar at runtime
- Set `loopTime: 1` on looping clips (idle, walk, eat, run) but NOT one-shot clips (attack, death, hurt)
Unity will re-import the FBX with Mecanim-compatible clips when it next opens.
2. **Create an AnimatorController** in `Assets/Eagle/Effects/` named `<Animal>MapAnims.controller`.
Use the same 4-state pattern (idle, walk, eat, attack) as ElephantMapAnims. Reference the animation clips by their fileIDs from the FBX meta's `internalIDToNameTable` (type 74 entries) or `fileIDToRecycleName` (older format, type 7400000+). These IDs are stable across import type changes. Note: if the FBX names its idle clip `idle1`, create the controller state as `idle` but reference the `idle1` clip by fileID.
3. **Create an AnimalEffect prefab** in `Assets/Eagle/Effects/` named `<Animal>Effect.prefab`.
Reference the pack's prefab as the animal prefab, and wire up the new AnimatorController. Multiple color/sex variants from the same or similar FBX can share one controller (e.g., Lion and Lioness). AnimalEffect will automatically strip the pack's legacy Animation, Rigidbody, and Collider components at spawn time, and add an Animator if the prefab doesn't already have one.
4. **Register in ProvinceBeastsController** with a case in `GetEffectPrefab()` and a test ContextMenu method.
5. **Mark the effect prefab as Addressable** with the `beast-effects` label in the Unity editor (Window > Asset Management > Addressables > Groups).
### Notes
- The packs include both SingleTexture and TextureAtlas variants; use SingleTexture for best visual quality.
- Hippos have water-specific animations (idlewater, deathwater) that could be used for future water-province effects.
- The packs' prefabs include Rigidbody/BoxCollider components intended for gameplay use. AnimalEffect strips these automatically since it controls position directly.
### Available animals not yet set up as beasts
These animals exist in the imported packs and could be set up as in-game beasts using the workflow above:
**Africa Animals Pack V1** (already imported):
| Animal | Good fit for | Notes |
|---|---|---|
| Giraffe (x2 variants) | giraffe beast | Tall model, may need larger scale |
| Zebra | zebra beast | Herd animal; good with higher animalCount |
(Black Panther, Rhinoceros, Crocodile, Elephant, and Tiger already have effects.)
**Africa Animals Pack V2** (already imported):
| Animal | Good fit for | Notes |
|---|---|---|
| Antelope | antelope/gazelle beast | Fast-moving; good with higher moveSpeed |
(Gorilla, Hyena, Leopard, Warthog, and Hippopotamus already have effects.)
**Dino Pack Low Poly V1** (already imported):
| Animal | Good fit for | Notes |
|---|---|---|
| Brontosaurus | brontosaurus/sauropod beast | Very large; needs big scale, low count |
| Pteranodon | pteranodon/flying beast | Has fly animation; could use DragonEffect-style flight |
| Stegosaurus | stegosaurus beast | Large herbivore |
| T-Rex | tyrannosaurus beast | Iconic predator; good as a solo beast |
| Triceratops | triceratops beast | Large herbivore; good for tough beast |
(Velociraptor already has an effect.)
**Australia Animals Pack V1** (already imported):
| Animal | Good fit for | Notes |
|---|---|---|
| Koala | koala beast | Peaceful; good for low-threat province events |
| Echidna | echidna beast | Small, spiny |
| Chlamydosaurus (Frilled Lizard) | lizard beast | Has threat display animation |
| Platypus (Ornitorinco) | platypus beast | Semi-aquatic; unique |
(Emu, Kangaroo, and Tasmanian Devil already have effects.)
None of the remaining animals above are currently in `beasts.tsv`.
## Tips
@@ -105,3 +243,4 @@ See `src/main/resources/net/eagle0/eagle/beasts.tsv` for the full list. Some can
- Use `ParticleSystemScalingMode.Hierarchy` so effects scale with the map zoom
- Set appropriate `sortingOrder` on renderers (existing effects use 102-104)
- For animated prefabs, set `AnimatorCullingMode.AlwaysAnimate` since UI elements may be considered offscreen by the culling system
- For 3D models (AnimalEffect), set `renderQueue=4000` and `ZTest=Always` on materials to prevent clipping behind the map
+7 -6
View File
@@ -42,16 +42,17 @@ Time-to-first-token (TTFT) was measured from request initiation to the first tex
### For Narrative Text Generation (Default)
**Gemini 2.5 Flash-Lite** is recommended as the default:
- Fastest TTFT (~0.6s) - nearly 3x faster than alternatives
- Cheapest pricing ($0.10/$0.40 per 1M tokens)
- Quality is acceptable for short narrative snippets
**Gemini 3.1 Flash-Lite** is recommended as the default:
- Priced at $0.25/$1.50 per 1M input/output tokens
- Significantly faster than 2.5 Flash-Lite on throughput and TTFT
- Meaningfully smarter than 2.5 Flash-Lite, while remaining one of the cheapest options
- Quality is more than sufficient for short narrative snippets
### Alternative Options
| Priority | Model | When to Use |
|----------|-------|-------------|
| Speed + Cost | Gemini 2.5 Flash-Lite | Default for most use cases |
| Speed + Cost | Gemini 3.1 Flash-Lite | Default for most use cases |
| Speed + Quality | gpt-4.1-mini | When you need OpenAI quality with good speed |
| Instruction Following | claude-3-5-haiku | Complex multi-step prompts, consistent tone |
| Maximum Quality | claude-sonnet-4 or gpt-5.2 | When output quality is paramount |
@@ -70,7 +71,7 @@ LLM settings can be changed at runtime via the admin console:
1. Navigate to Admin Console → Settings
2. Change `LlmProvider` to select vendor (gemini, openai, claude)
3. Change the corresponding model name setting:
- `GeminiModelName` (default: gemini-2.5-flash-lite)
- `GeminiModelName` (default: gemini-3.1-flash-lite-preview)
- `OpenAiModelName` (default: gpt-4.1-mini)
- `ClaudeModelName` (default: claude-3-5-haiku-20241022)
@@ -0,0 +1,77 @@
# Shardok AI Experiment Tooling Plan
## Summary
Build a reusable workflow for Shardok AI battle baselines and scoring experiments. The goal is to
turn the current one-off benchmark process into repeatable commands that extract real battles, run
baseline and candidate configurations, capture detailed per-command traces, and write comparable
reports.
This work starts with the target-aware archery scoring experiment: attacker `EXPERIMENTAL` against
defender `STANDARD`.
## Key Changes
- Add simulator trace support to `ai_battle_simulator_main`.
- New flag: `--trace-jsonl=<path>`.
- Emit one JSONL row per AI-selected command.
- Include run label, config path, state file, phase, sequence, round, player, side, command type,
actor unit, target coords, chosen index, available command count, search depth, commands
evaluated, completion reason, forced commands posted afterward, and pre/post side troop totals.
- Keep existing summary output unchanged.
- Add reusable benchmark tooling under
`src/main/cpp/net/eagle0/shardok/ai_battle_simulator/benchmarks/`.
- `real_battle_suite.py`: shared helpers for reading `game.db`, materializing battle/state/result
blobs, extracting configs, running simulator binaries, parsing summaries, and collecting
real-game metadata.
- `run_real_battle_experiment.py`: CLI orchestration for baseline/candidate runs.
- Outputs: `summary.csv`, `comparison.csv`, `report.md`, generated configs, and per-run trace
JSONL files.
- Add a clean EXPERIMENTAL switch for target-aware archery value.
- Use a new experiment id.
- Change only archery-availability scoring.
- Replace the flat archery-possible value with a target-sensitive value based on the best enemy
unit value.
- Do not include the previous fear-value change from experiment `27`.
## Execution Plan
- Create a feature branch from fetched `origin/main`.
- Commit this plan document first.
- Implement simulator trace output and reusable benchmark tooling.
- Add the target-aware archery-only EXPERIMENTAL switch.
- Run the new tool first on battle `6248`, then on the all-40 saved-battle suite if local runtime is
acceptable.
- Compare baseline attacker `STANDARD` / defender `STANDARD` with candidate attacker
`EXPERIMENTAL` / defender `STANDARD`.
- Record the results under the existing benchmark results area and call out battle `6248` in the
generated report.
- Push the branch and create a PR after local validation.
## Tests
- Build:
- `bazel build //src/main/cpp/net/eagle0/shardok/ai_battle_simulator:ai_battle_simulator_main`
- `bazel build //src/main/cpp/net/eagle0/shardok/ai_battle_simulator:real_battle_config_extractor`
- `bazel build //src/main/cpp/net/eagle0/shardok/ai_battle_simulator:real_battle_smoke_metadata`
- Unit/integration:
- `bazel test //src/test/cpp/net/eagle0/shardok/ai_battle_simulator:ai_battle_simulator_test`
- Add or extend a simulator test that verifies trace output is created and contains required
command fields.
- `python3 -m py_compile` on the new benchmark scripts.
- Validation:
- Run the new tool on battle `6248`.
- Run the new tool on all 40 battles if feasible locally.
- Run `bazel test //src/test/cpp/...` before push if local time allows; otherwise open the PR
promptly and continue validation while CI starts.
## Assumptions
- "Experiment 3" means target-aware archery value from the previous recommendation list.
- The first experiment compares attacker-only candidate behavior against unchanged defender
`STANDARD`.
- JSONL is the trace format because command diagnostics will evolve over time.
- Python benchmark scripts follow the existing executable-script pattern rather than adding Python
Bazel targets.
+82
View File
@@ -0,0 +1,82 @@
# Shardok AI Scoring Benchmarks
The current STANDARD scoring experiment results are recorded in
`src/main/cpp/net/eagle0/shardok/ai_battle_simulator/benchmarks/experimental_results/`.
They use 40 saved Shardok battles extracted from `game_389ffb1901903118.zip`.
The corrected all-40 run uses:
- `max_rounds = 31`
- `random_seed = 1`
- iterative-deepening timeout propagation fix from PR #6923
- AI setup placement
- forced single-option commands
- defender scoring fixed to `STANDARD` for every row
- archery/start-fire capability derived like production setup
- per-unit flee capability preserved by real-battle extraction
- zero-troop combat heroes preserved as live units
- `NO_PROFESSION` treated as a valid hero profession state, not as "no hero"
Shardok siege battles do not have a draw result. If the attacker has not won after 31 rounds, the
defender wins. The simulator records those cutoffs as `max_rounds_reached` defender wins.
All 40 saved battle payloads now produce valid simulator configs. A battle side can have zero
remaining troops as long as it has a hero; this is common for `NO_PROFESSION` heroes with no
commanded battalion.
An all-40 real-vs-sim comparison records whether the saved-game attacker/defender were human or AI
players. Factions `3` and `4` are human players; all other factions in this save are AI players.
The comparison uses broad winner side from the saved Shardok result payload, because exact replay
is not available from the compact result rows. Real end-of-battle troop totals come from the
all-factions Shardok `ActionResultView` stream's final `changed_player_totals`.
An AI-vs-AI smoke check also reruns a subset where neither side used faction `3` or `4`.
## Current Results
These artifacts are the current baseline for future scoring comparisons.
| Dataset | Valid battles | Invalid rows | Attacker wins | Defender wins | Notes |
| --- | ---: | ---: | ---: | ---: | --- |
| All-40 timeout-fix STANDARD baseline | 40 | 0 | 18 | 22 | `standard_scoring_all40_post_bugfix_baseline.*`; regenerated after fixing iterative-deepening timeout score propagation |
| All-40 real saved game | 40 known | 0 unknown | 19 | 21 | `standard_scoring_all40_real_vs_sim.*`; sim matches 39/40 known winners |
| AI-vs-AI smoke | 31 | 0 | 10 | 21 | 31/31 winner-side matches |
The remaining real-vs-sim winner-side miss is `11754` (real attacker, sim defender), which had an
AI attacker but a human defender in the saved game. The real attacker won with `2119` troops
remaining; the STANDARD-vs-STANDARD simulation replaces the human defender with AI and the defender
wins with `1000` troops remaining, so this row is not a comparable AI-vs-AI smoke miss. Battle
`6248`, previously the remaining AI-vs-AI miss, now matches as an attacker win after expected-impact
archery scoring was promoted to STANDARD.
The closest six valid baseline rows are used for the scalar and behavior experiment batches. The
single-run harness still has some nondeterminism even with `random_seed = 1`, so near-margin changes
should be repeated before being promoted.
## Experiment Tooling
`src/main/cpp/net/eagle0/shardok/ai_battle_simulator/benchmarks/run_real_battle_experiment.py`
is the reusable real-battle experiment runner. It can read a saved-game zip or extracted `game.db`,
generate baseline/candidate simulator configs, run both sides, and write `summary.csv`,
`comparison.csv`, `report.md`, generated configs, and per-command trace JSONL files.
The repository keeps the current STANDARD baseline artifacts, but omits generated configs/traces
for abandoned experiment batches. Regenerate those locally with the runner when a new comparison
needs command-level traces.
`src/main/cpp/net/eagle0/shardok/ai_battle_simulator/benchmarks/run_standard_baselines.py`
regenerates the tracked STANDARD-vs-STANDARD baseline artifacts from a saved-game zip or extracted
`game.db`, including the all-40 baseline, real-vs-sim comparison, and AI-vs-AI smoke files.
The simulator supports `--trace-jsonl=<path>` and `--run-label=<label>` for detailed command traces.
Each row records the selected command, search depth, forced command count, and pre/post side troop
totals.
Expected-impact archery replaced the old flat archery-position value in STANDARD. A unit that can
shoot now gets half of the expected volley impact; a unit that is merely positioned for a future
volley gets one quarter. Promoting that behavior flips `6248` to match the real AI-vs-AI attacker
win without introducing an AI-vs-AI winner-side miss in the current saved-battle baseline.
The latest baseline refresh was generated after the iterative-deepening evaluator stopped letting
timeout fallback scores compete with completed command evaluations. Future STANDARD-vs-EXPERIMENTAL
comparisons should compare against these checked-in timeout-fix baseline artifacts.
+18 -9
View File
@@ -6,6 +6,16 @@ Be able to support a small (10-50 user) private alpha, including with strangers.
Larger set of goals in [The Big Eagle TODO](https://docs.google.com/document/d/17RTt3-4Wl2AAVMRLodaC3a84E4de6xuQTWBPvCRM484/edit?pli=1&tab=t.0), but most of that is not necessary for MVP.
## Current priority order
1. Finish tutorial & first-session onboarding, especially the clear first-session goal and guided first scenario.
2. Fix the basic Shardok AI issues that can make tactical battles feel broken or unfair.
3. Publish a known issues doc so alpha testers do not repeatedly report the same rough edges.
4. Verify the existing game-ended flow, then mark the win condition done if "all other factions defeated" works end-to-end.
5. Add mid-game progression events where the King recognizes the player as they gain power.
6. Add account-linking when provider switching or account recovery becomes important for alpha support.
7. Leave terms of service and Windows code signing deferred until they matter for public release or broader distribution.
## Required
### Gameplay Productionization
@@ -17,7 +27,7 @@ Larger set of goals in [The Big Eagle TODO](https://docs.google.com/document/d/1
- [x] ~~Fix long disconnects on deployments~~
- [x] Fix the Mac installer
- [x] ~~Still not reconnecting after deployments~~
- [ ] Notify about client updates, button to come directly back
- [x] Notify about client updates, button to come directly back
- [x] Generatedtext healing
- [x] Kill outstanding shardok requests when game is deleted
@@ -51,7 +61,7 @@ Larger set of goals in [The Big Eagle TODO](https://docs.google.com/document/d/1
### Basic Gameplay
- [ ] Tutorial
- [ ] Tutorial & first-session onboarding
- [x] In the Your Warlord panel, say what the profession is
- [x] ~~And separate panels for each profession when you encounter one~~
- [x] ~~Command tutorial for each command the first time it's clicked~~
@@ -62,17 +72,16 @@ Larger set of goals in [The Big Eagle TODO](https://docs.google.com/document/d/1
- [x] ~~Time to swear brotherhood~~
- [x] ~~When you get large, or~~
- [x] ~~When you get a good candidate~~
- [ ] Shardok tutorial!
- [x] ~~Shardok tutorial!~~
- [x] ~~Narrative hook in first few minutes - why should I care about my warlord?~~
- [ ] Clear first-session goal ("try to capture your first province" or similar)
- [x] ~~Early small victory to build momentum~~
- [ ] Guided first scenario vs. overwhelming sandbox?
- [ ] Basic Shardok AI stuff fixed
- [ ] Lobby fixes
- [x] ~~Lobby fixes~~
- [ ] Have goals / ending
- [ ] Win condition: all other factions defeated
- [ ] Mid-game progression: King recognizes you as you gain power (generated events)
- [ ] First-session onboarding (beyond mechanics tutorial)
- [ ] Narrative hook in first few minutes - why should I care about my warlord?
- [ ] Clear first-session goal ("try to capture your first province" or similar)
- [ ] Early small victory to build momentum
- [ ] Guided first scenario vs. overwhelming sandbox?
## Nice to have
+335
View File
@@ -0,0 +1,335 @@
# SQLite Action Result Decomposition
Follow-up to [SQLITE_HISTORY_DESIGN.md](SQLITE_HISTORY_DESIGN.md). This document plans the second wave of the SQLite migration: decomposing the `ActionResult` proto blob in `action_results.payload` into native relational tables, deleting the proto representation entirely for everything in scope.
## Status — option B adopted (updated 2026-05-17)
**This section supersedes the original plan below. Where the body conflicts with this section, this section wins.** The full-relational design is kept below for historical context and as the migration target if a structured-query need on deep aggregates ever materializes.
The original plan (decompose every field into relational tables; "decision locked") was implemented for `ChangedProvince` first — ~37 child tables, ~1500 lines (PR #6721) — and then **rejected on cost/benefit**. We adopted **option B**: apply the "stopping rule" (originally carved out only for `Quest`) *consistently*. Shipped and merged as Phase 4.5b in **PR #6725**:
- Keep the per-entity **top-level table with scalar / entity-reference columns + indexes** (the 4.5a tables). That is the part that earns its keep — "which actions changed province/hero/faction X, by how much" is one-line SQL.
- Store the **rest of the aggregate as one `<entity>_proto BLOB` column** on that row: lossless round-trip / replay, no child tables for the deep nesting.
- Scalar columns are pure query denormalization; **the proto blob is authoritative**. A later fully-relational pass (if ever needed) is a pure read-blob → write-columns migration — which is why the blob must survive any future proto deletion.
Rationale: the deep army/unit/hero/claimant nesting is never analytics-queried — the exact property that justified blobbing `Quest`. Exploding it into ~37 tables was code volume without query value. The blob also means deep-aggregate field changes need **no SQL migration** (only promoted scalar columns do), which is the right shape for the volatile parts of the model. This rescinds "Decisions locked #1" and revises principle 7, the Scope, the Sequencing table, and "Deleting the proto" (all updated in place below).
## Refinement — "refined option B" for shallow entities (updated 2026-05-19)
**This section further supersedes the body and the Status section above where they conflict; it wins.** It records the pattern actually shipped for `ChangedHero` in Phase 4.5c.1 (#6727), which is a refinement of option B, not the whole-entity-blob shape the body still describes for that entity.
Option B as originally stated keeps **one `<entity>_proto BLOB`** per row for the entire non-scalar residual. For a *shallow* entity that is more blob than it needs. Refined option B decomposes the residual into three tiers instead of one blob:
- **Tier 1 — scalar / entity-reference columns + indexes.** The queryable surface (deltas, touched entities, enum ordinals). Always present; unchanged from 4.5a.
- **Tier 2 — typed columns for sealed value-oneofs.** A sealed choice over simple values (e.g. `ChangedHeroC`'s `loyalty` / `vigor` `StatChange`, subtypes `StatDelta`/`StatAbsolute`/`StatNoChange`) becomes a **pair of nullable columns** (`loyalty_delta` / `loyalty_absolute`, …). The *column name is the discriminator*; at most one of each pair is non-NULL; both NULL ⇒ the no-change case. No `kind` column.
- **Tier 3 — per-row leaf-proto blobs in a child table.** A repeated/optional nested aggregate becomes a child table keyed by `(action_seq, entity_id, n)` storing the **leaf** proto's bytes one row per element (e.g. `action_changed_heroes_new_backstory_events` holding `EventForHeroBackstory` blobs) — *not* a whole-entity blob.
**Consequence (changes Decisions #1#3 and 4.5i):** an entity fully covered by Tiers 13 has **no whole-entity blob**. It round-trips losslessly from columns + per-leaf blobs, so its per-entity proto and converter (`changed_hero.proto` / `ChangedHeroConverter`) become genuinely dead code, deletable in 4.5i. Only the **leaf** protos used as Tier-3 blob payloads (`event_for_hero_backstory.proto`) are retained as a wire format. The whole-entity `<entity>_proto BLOB` is now reserved for **deep** entities where Tiers 23 would be more work than value (`ChangedProvince`, the "new entity" snapshots).
Per-entity decision (supersedes Decisions #2): classify each entity as **all-scalar** (Tier 1 only, no blob — e.g. likely `ChangedFaction`), **refined** (Tiers 13, no whole-entity blob, proto deletable — `ChangedHero`), or **deep** (Tier 1 + whole-entity `<entity>_proto BLOB`, proto retained — `ChangedProvince`, new-entity snapshots). Default to **refined** for shallow entities; fall back to **deep** only when the residual is too varied to be worth Tiers 23. Wherever the body or Status says "the proto blob is authoritative," for a *refined* entity read "the columns + per-leaf-proto blobs are authoritative."
## Why
The first wave (Phases 14) stores each action as a single proto blob in `action_results.payload`. That blob is opaque to SQL — any query about action contents (changed provinces, heroes affected, etc.) requires deserializing every row. The `action_result_type`, `round_id`, and date columns we denormalized are the only handles SQL has into actions.
Two observations make full decomposition more attractive than the original design admitted:
1. **The proto exists for storage only.** 92 Scala files reference `ChangedProvince`, but exactly one imports the proto type — `ChangedProvinceConverter.scala`. Everything else (action handlers, AI, utils) operates on `ChangedProvinceC`. The proto is **not** in any client-facing RPC contract — it lives under `eagle.internal`. Same is true for `ChangedHero`, `ChangedFaction`, `ChangedBattalion`, `Notification`, `GeneratedTextRequest`, and `ActionResult` itself. Replacing proto serialization with SQL writes does **not** lose forward/backward compatibility, because there are no external consumers depending on the proto wire format.
2. **`ActionResultC` has no polymorphism at the top level.** It's a 34-field flat struct — `Option`s and `Vector`s, but no `sealed trait` discriminator at the action level. Every action has the same shape; the `actionResultType` enum tells you *which fields* are populated. This means the entire structure is relationalizable without per-action-type tables.
The work is bounded, the proto becomes dead code at the end of it, and it has to happen before alpha — once we have users, every schema change costs a real migration. Doing it pre-alpha lets us nuke save dirs as part of deployment.
## Scope
**In:** `action_results.payload` (the whole-`ActionResult` blob) is gone by the end. Per-entity scalar / entity-reference columns make the *queryable* surface (deltas, touched entities) native SQL. **Under refined option B (see Status):** `internal/action_result.proto` and *deep* entities' sub-message protos (`changed_province.proto`, …) are retained as blob payloads; *refined* entities' protos (`changed_hero.proto`) are decomposed away and deleted, with only their Tier-3 leaf protos (`event_for_hero_backstory.proto`) kept. (The original plan deleted all of them, then a draft of option B kept all of them; neither holds — it's now per-entity.)
**Out:**
- `state_snapshots.payload` — stays as proto-blob `GameState`. These are caches for replay, not authoritative data; querying inside a snapshot adds nothing over querying the action deltas that produced it. Cost/benefit doesn't justify decomposing them.
- Shardok tables — already designed in Phase 3, no changes here. The shardok protos (`ShardokActionResult`, etc.) are owned by the Shardok subsystem and are part of an actual RPC contract; they stay.
- Client text — already SQLite-backed (`SqliteClientTextStore`).
## Principles
1. **One table per non-trivial aggregate type.** Every `Vector[X]` or `Option[X]` where `X` is a Scala case class with multiple fields gets its own table.
2. **Vectors of primitives → join tables.** `Vector[Int]` becomes a two-column table: `(parent_key, value)`. No JSON arrays, no comma-separated strings — those defeat the point.
3. **Optional aggregates → presence by row existence.** `Option[X]` for aggregate `X` is a row that may or may not exist with the matching parent key. The natural primary key on `(action_seq)` enforces 0-or-1-row semantics for `Option[X]` aggregates and `(action_seq, n)` for vectors.
4. **Sealed traits get a discriminator column.** When a Scala sealed trait has a few subtypes with diverging fields, prefer one wide table with `kind TEXT NOT NULL` + nullable per-subtype columns over per-subtype tables. When subtypes diverge significantly (>5 unrelated fields each), use per-subtype tables. Decide per case.
5. **`ON DELETE CASCADE` everywhere.** Every child table has `FOREIGN KEY (action_seq) REFERENCES action_results(action_seq) ON DELETE CASCADE`. `truncateTo` becomes a single `DELETE FROM action_results WHERE action_seq >= ?` and the cascades do the rest.
6. **Schema migrations are now real.** Once we have a relational schema, evolving it means SQL migrations. We introduce a real migration runner (see "Schema evolution" below). The `metadata` table's `schema_version` becomes load-bearing.
7. **(Revised under option B — see Status.) The proto blob is the retained authoritative store for each entity's deep aggregates; scalar / entity-reference columns are denormalized projections of it.** The original principle assumed full decomposition and proto deletion. Instead each entity keeps one proto-blob source of truth and denormalizes only the queryable columns from the same write — so there is no dual *relational* representation to keep in sync.
## Top-level: `action_results`
The `payload BLOB` column goes away. Scalar fields become columns; aggregate fields move to related tables.
```sql
CREATE TABLE action_results (
action_seq INTEGER PRIMARY KEY,
action_result_type INTEGER NOT NULL,
-- existing scalar denormalizations
round_id INTEGER NOT NULL,
date_year INTEGER,
date_month INTEGER,
-- new scalar columns (formerly inside payload)
acting_hero_id INTEGER,
acting_faction_id INTEGER,
province_id INTEGER,
province_id_acted INTEGER,
new_round_phase INTEGER,
new_round_id INTEGER,
last_command_type_for_acting_province INTEGER,
resolved_battle TEXT,
new_victor_faction_id INTEGER,
game_ended INTEGER, -- 0/1/NULL
new_random_seed INTEGER,
new_game_type INTEGER
);
-- Vectors of bare IDs become join tables:
CREATE TABLE action_destroyed_battalion_ids (
action_seq INTEGER NOT NULL,
battalion_id INTEGER NOT NULL,
PRIMARY KEY (action_seq, battalion_id),
FOREIGN KEY (action_seq) REFERENCES action_results(action_seq) ON DELETE CASCADE
);
CREATE TABLE action_removed_hero_ids (
action_seq INTEGER NOT NULL,
hero_id INTEGER NOT NULL,
PRIMARY KEY (action_seq, hero_id),
FOREIGN KEY (action_seq) REFERENCES action_results(action_seq) ON DELETE CASCADE
);
CREATE TABLE action_removed_faction_ids (...);
CREATE TABLE action_affected_faction_ids (...);
-- Singleton optional aggregates: a row exists if and only if Option is Some.
CREATE TABLE action_new_battles (
action_seq INTEGER PRIMARY KEY,
-- ShardokBattle fields here, columns or sub-tables as needed
FOREIGN KEY (action_seq) REFERENCES action_results(action_seq) ON DELETE CASCADE
);
CREATE TABLE action_new_chronicle_entries (action_seq INTEGER PRIMARY KEY, ...);
CREATE TABLE action_new_eagle_map_info (action_seq INTEGER PRIMARY KEY, ...);
```
Each `Vector[Aggregate]` field on `ActionResultC` gets its own table (covered below).
### Indexes
We keep the existing indexes (`round_id`, `(date_year, date_month)`) and add a few that obvious queries need:
- `idx_action_results_acting_hero_id`
- `idx_action_results_acting_faction_id`
- `idx_action_results_province_id`
Plus indexes on the per-entity join tables on the entity-id side, so cross-game queries like "all actions touching hero X" become single-index lookups:
- `idx_action_changed_provinces_province_id`
- `idx_action_changed_heroes_hero_id`
- `idx_action_changed_faction_faction_id`
- `idx_action_changed_battalions_battalion_id`
## Changed-entity tables (four parallel structures)
### `action_changed_provinces`
`ChangedProvinceC` has ~50 fields: scalar deltas, nested aggregates, ID vectors. The scalar fields become columns on `action_changed_provinces`; aggregate fields become child tables.
```sql
CREATE TABLE action_changed_provinces (
action_seq INTEGER NOT NULL,
province_id INTEGER NOT NULL,
-- resource changes
gold_delta INTEGER,
food_delta INTEGER,
-- stat changes
new_price_index REAL,
economy_delta REAL,
agriculture_delta REAL,
infrastructure_delta REAL,
economy_devastation_delta REAL,
agriculture_devastation_delta REAL,
infrastructure_devastation_delta REAL,
support_delta REAL,
-- round properties
set_has_acted INTEGER, -- 0/1/NULL
set_ruler_is_traveling INTEGER,
-- ruling faction changes
clear_ruling_faction_id INTEGER NOT NULL DEFAULT 0,
new_ruling_faction_id INTEGER,
-- misc scalar fields
new_locked_improvement_kind TEXT, -- 'none', 'new'
new_locked_improvement_value INTEGER, -- ImprovementType if kind='new'
new_province_orders INTEGER, -- ProvinceOrderType enum
clear_defending_army INTEGER NOT NULL DEFAULT 0,
cleared_pending_conquest_info INTEGER NOT NULL DEFAULT 0,
removed_deferred_change_index INTEGER,
PRIMARY KEY (action_seq, province_id),
FOREIGN KEY (action_seq) REFERENCES action_results(action_seq) ON DELETE CASCADE
);
CREATE INDEX idx_action_changed_provinces_province_id
ON action_changed_provinces(province_id);
```
The vector and optional-aggregate fields of `ChangedProvinceC` become per-aggregate child tables, all keyed by `(action_seq, province_id)`:
- `action_changed_provinces_new_unaffiliated_heroes(action_seq, province_id, n, ...)` — one row per added hero, with `UnaffiliatedHero` fields as columns
- `action_changed_provinces_changed_unaffiliated_heroes(...)` — same shape
- `action_changed_provinces_removed_unaffiliated_hero_ids(action_seq, province_id, hero_id)` — join table for ID vector
- `action_changed_provinces_new_captured_heroes(...)``CapturedHero` fields
- `action_changed_provinces_recruitment_attempted_captured_hero_ids(...)` — join table
- `action_changed_provinces_removed_captured_hero_ids(...)` — join table
- `action_changed_provinces_new_ruling_faction_hero_ids(...)` — join table
- `action_changed_provinces_removed_ruling_faction_hero_ids(...)` — join table
- `action_changed_provinces_new_battalion_ids(...)` — join table
- `action_changed_provinces_removed_battalion_ids(...)` — join table
- `action_changed_provinces_new_incoming_armies(...)``MovingArmy` decomposition
- `action_changed_provinces_removed_incoming_army_ids(...)` — join table
- `action_changed_provinces_new_withdrawing_armies(...)``MovingArmy` decomposition
- `action_changed_provinces_removed_withdrawing_army_ids(...)` — join table
- `action_changed_provinces_new_hostile_armies(...)``HostileArmyGroup` decomposition
- `action_changed_provinces_removed_hostile_army_faction_ids(...)` — join table
- `action_changed_provinces_hostile_army_status_changes(action_seq, province_id, faction_id, new_status)` — small flat aggregate
- `action_changed_provinces_new_defending_army``Option[Army]` (singleton row if present)
- `action_changed_provinces_new_incoming_shipments(...)``MovingSupplies` decomposition
- `action_changed_provinces_removed_incoming_shipment_ids(...)` — join table
- `action_changed_provinces_new_incoming_end_turn_actions(...)``IncomingEndTurnAction` decomposition
- `action_changed_provinces_removed_incoming_end_turn_actions(...)` — same shape (these are values, not IDs)
- `action_changed_provinces_new_battle_revelations(...)``BattleRevelation` decomposition
- `action_changed_provinces_removed_battle_revelations(...)` — same shape
- `action_changed_provinces_new_pending_conquest_info``Option[PendingConquestInfo]` (singleton row)
- `action_changed_provinces_new_province_events``Vector[ProvinceEvent]`
- `action_changed_provinces_new_deferred_change``Option[DeferredChange]` (singleton, with discriminator since `DeferredChangeT` is sealed)
That's a lot of tables — ~25 just under `ChangedProvince`. The schema is mechanical once the principles are set; what makes it tractable is that every table follows the same shape: parent FK, `n` (vector index) where ordering matters, the aggregate's fields as columns, child aggregates as their own tables.
### `action_changed_heroes`, `action_changed_factions`, `action_changed_battalions`
Same pattern. Each gets its top-level table keyed by `(action_seq, entity_id)`, plus child tables for nested aggregates and ID vectors. Indexes on the entity id (`hero_id`, `faction_id`, `battalion_id`) so cross-game queries are fast.
`ChangedHeroC` is a *refined* entity (see "Refinement" in Status): no whole-entity blob. Its sealed `StatChange` (`StatDelta`/`StatAbsolute`/`StatNoChange`) `loyalty` and `vigor` oneofs are Tier-2 column pairs (`loyalty_delta`/`loyalty_absolute`, `vigor_delta`/`vigor_absolute`; column name discriminates, both-NULL ⇒ `StatNoChange`). Its `newBackstoryEvents: Vector[EventForHeroBackstory]` is Tier-3: per-event `EventForHeroBackstory` blobs, one row each, in `action_changed_heroes_new_backstory_events`. Columns + per-event blobs round-trip losslessly, so `changed_hero.proto`/`ChangedHeroConverter` become deletable (4.5i) and only `event_for_hero_backstory.proto` is retained as a blob format.
## "New" entity tables
`ActionResultC.newProvinces: Vector[ProvinceT]`, `newHeroes`, `newFactions`, `newBattalions`. These are *full snapshots* of new entities at creation.
These are bigger and recursive: `ProvinceT` itself has fields including its armies, heroes, battalions, events, etc. Decomposing fully duplicates the structure already covered by the existing `state_snapshots` blob (which we're explicitly keeping). The decomposition still needs to happen because we're dropping the proto entirely — and these vectors live in `ActionResultC`, which we're decomposing.
**Decision**: go fully relational here too. Each "new entity" gets its top-level table (`action_new_provinces` etc.) keyed by `(action_seq, entity_id)`, with the same per-aggregate-field decomposition pattern as the changed-entity tables. Where a "new entity" type contains its own nested aggregates, those aggregates either share child tables with the `changed_*` family (preferred where the field shape is identical, e.g., `MovingArmy`, `UnaffiliatedHero`) or get their own (where they diverge).
This is the most expensive single chunk of the decomposition — explicitly called out so we know what we're committing to in PR 4.5f.
## Notifications and generated text requests
```sql
CREATE TABLE action_new_notifications (action_seq INTEGER NOT NULL, n INTEGER NOT NULL, ...);
CREATE TABLE action_removed_notifications (action_seq INTEGER NOT NULL, n INTEGER NOT NULL, ...);
CREATE TABLE action_new_generated_text_requests (...);
CREATE TABLE action_client_text_visibility_extensions (...);
```
`NotificationT` and `GeneratedTextRequestT` are both sealed traits. Use the discriminator-column pattern: `kind TEXT NOT NULL` plus nullable per-subtype columns, unless a subtype's fields are too divergent to share a row.
## Schema evolution
We can't punt on this any more. With this many tables, the next field addition can't be "edit the proto." It needs a real migration mechanism.
Conventions:
- `metadata['schema_version']` is a small integer, currently `1`.
- A `Migrations` object holds an ordered `Vector[(Int, Connection => Unit)]` of migration steps.
- On `SqliteHistory.loaded`, the schema version is read; any pending migrations are applied in a single transaction; the version is bumped.
- New games start at the latest version.
- Migration steps are append-only — never edit an existing step.
This is the standard Rails / Flyway / etc. pattern, scaled down to one file.
## Read path: reconstructing `ActionResultC`
The current pattern:
```scala
val proto = ActionResult.parseFrom(payloadBlob)
val scala = ActionResultProtoConverter.fromProto(proto)
```
The new pattern:
```scala
val scala = ActionResultDbReader.read(connection, actionSeq) // assembles from action_results + child tables
```
`ActionResultDbReader.read` is one query per child table (or a single multi-result query with carefully ordered joins, though that has aggregation pitfalls). Per-table queries are simpler to write and SQLite query planning handles them well.
For bulk reads (`since`, `all`, `sinceDate`, etc.), the existing `replayFrom` helper iterates action seqs in order, and currently parses one proto per action. The new equivalent runs one batched query per child table for the relevant action_seq range, materializing rows into a map keyed by action_seq, then walks the range emitting `ActionResultC` instances assembled from the maps. This is more code than the proto version but doesn't change the algorithmic shape.
## Write path
`withNewResults` becomes:
1. INSERT into `action_results` (scalar fields).
2. For each non-empty aggregate: INSERT N rows into the corresponding child table.
All inside a single transaction. Per-action insert count is bounded by what the action does — most actions touch 03 provinces, 05 heroes, 010 changed entities total, plus 02 notifications. So the typical insert is ~520 rows. With WAL and a single per-batch transaction, this is cheap.
## Replay performance
Today's `replayFrom` parses one proto per action. Decomposed, each action requires per-child-table queries. For a 25-action replay between snapshots, that's still small absolute work — maybe 100500 rows fetched from a handful of indexed tables. Should be faster than proto parsing once the JIT warms up, but won't matter either way at typical sizes.
## Deleting the proto
> **Superseded by refined option B (see Status).** Whole-`ActionResult` `payload` is removed in 4.5h. After that it depends on per-entity classification: *refined* entities' per-entity sub-message protos + converters (e.g. `changed_hero.proto`) **do** become dead code and are deleted in 4.5i; *deep* entities' whole-entity blob protos, the leaf protos used as Tier-3 blob payloads (e.g. `event_for_hero_backstory.proto`), and `Quest` are *retained*. The original full-deletion plan below is kept for historical context.
Once `SqliteHistory` writes and reads exclusively from the new tables:
1. Delete `ActionResultProtoConverter.scala`, the `Changed{Province,Hero,Faction,Battalion}Converter.scala` files, the `Notification`/`GeneratedTextRequest`/etc. converters.
2. Delete the proto definitions: `action_result.proto`, `changed_province.proto`, `changed_hero.proto`, `changed_faction.proto`, `notification.proto`, `generated_text_request.proto`, anything else in this scope.
3. Delete the corresponding `_scala_proto` Bazel targets.
4. Gazelle should drop the unused deps from downstream targets.
This is satisfying but should land *last*, after everything's stable. The proto files are dead code at that point — keeping them around for a PR or two while we verify migration is fine.
## Sequencing
**Phase 4** (cutover) lands as planned: `GamesManager` swaps to `SqliteHistory`, save dirs get nuked, action data is the single proto-blob `payload`. Days of work, validates the lifecycle integration without conflating with schema design.
**Phase 4.5** (this design) starts after Phase 4 is verified stable. Subdivided into small PRs. **Re-planned for option B (see Status):** each entity gets the 4.5a scalar/entity-ref columns + a `<entity>_proto BLOB`; no child-table explosion. Each decomposition PR splits into `.1` (schema + backfill over existing `payload`) and `.2` (live `withNewResults` write path + read path), per the precedent set by 4.5b.
| PR | Work | State |
|---|---|---|
| 4.5a | Schema-migration scaffolding + four changed-entity top-level tables (scalar columns) | ✅ merged |
| 4.5b | `ChangedProvince`: scalar columns + `changed_province_proto BLOB` + v3 backfill (option B, #6725) | ✅ merged |
| 4.5c.1 | `ChangedHero` (**refined option B**, see Status): 4.5a scalars + loyalty/vigor Tier-2 column pairs + `newBackstoryEvents` as per-event `EventForHeroBackstory` Tier-3 blobs in `action_changed_heroes_new_backstory_events`; **no whole-entity blob**`changed_hero.proto`/`ChangedHeroConverter` become deletable, `event_for_hero_backstory.proto` retained. Schema v4 + backfill over existing `payload` (#6727) | ✅ merged |
| 4.5c.2 | `ChangedHero`: live `withNewResults` write path + read path | planned |
| 4.5d | `ChangedFaction`: same pattern (mostly scalar already; small/empty blob — see Decisions #2) | planned |
| 4.5e | `ChangedBattalion`: `changed_battalion_proto BLOB` (sole field is the contained `BattalionT`) + battalion_id index from 4.5a | planned |
| 4.5f | "New entity" vectors (`newProvinces`/`newHeroes`/`newFactions`/`newBattalions`): one table per type keyed by `(action_seq, entity_id)` + a couple of queryable handles + `<entity>_proto BLOB`. Biggest win for B — these are the deepest snapshots | planned |
| 4.5g | Notifications + generated text requests: `(action_seq, n, kind, <entity>_proto BLOB)``kind` discriminator queryable, payload blobbed (quest-hybrid shape) | planned |
| 4.5h | Top-level `ActionResultC` scalar/entity-ref columns on `action_results` (acting_hero_id, acting_faction_id, province_id, …) + **drop `payload BLOB`**. Read path = scalar columns + per-entity proto blobs (close to today's proto parse; simpler than the original per-table-join plan) | planned |
| 4.5i | Delete proto files/targets that became dead code. *Refined* entities' per-entity protos + converters (e.g. `changed_hero.proto`/`ChangedHeroConverter`) **are deleted** here. *Deep* entities' protos + leaf Tier-3 protos (e.g. `event_for_hero_backstory.proto`) + `Quest` are **retained** as blob payloads. No longer near-nothing — scope scales with how many entities went *refined* | planned |
Each PR nukes save dirs as part of its rollout (still pre-alpha). Each PR is independently reviewable and revertable. Under option B the per-PR cost is far lower than the original estimate (~110-line writer per entity, no child-table schema), so the remaining sequence is roughly **1 week**, not 34.
After 4.5: Phase 5 (idle-game eviction) and Phase 6 (final cleanup) proceed as the parent design doc lays out.
## What we gain at the end
- **Single source of truth.** Action data lives in tables; no proto representation for the things in scope.
- **Native SQL analytics.** Cross-game queries like "actions touching province X" or "all riots in year Y" are one-line SELECTs. No backfill code needed.
- **Inspectable saves.** `sqlite3 game.db` shows readable data. Debugging is normal SQL work, not "parse this binary blob."
- **Cleaner replay path.** No proto parsing during replay. The `ActionResultProtoConverter` (currently called per replayed action in `replayFrom`) goes away entirely.
- **Less code.** ~7 proto files deleted; their generated Scala targets deleted; their converter classes deleted; the dual proto/Scala representation collapses to one.
- **Schema migrations as a first-class concept.** Future field additions are SQL migrations, which is the right shape for a system that owns its storage.
## What we lose
- **The "edit one proto" workflow** for adding fields. Adding `newFooDelta: Double` to `ChangedProvinceC` is now a Scala edit + SQL migration step + converter update. More steps. Pre-alpha this is cheap; post-alpha (when migrations apply to real data) it's a careful PR but still bounded.
- **A safety net for unrecognized fields.** Proto silently keeps unknown fields on parse; SQL doesn't. We accept this because we control both ends.
## Decisions locked
1. **Refined option B is the pattern (see "Refinement" in Status; rescinds both "fully relational, no blob fallback" and the original whole-entity-blob-per-entity rule).** Per entity, three tiers: scalar/entity-ref columns (Tier 1) + typed columns for sealed value-oneofs (Tier 2) + per-row leaf-proto blobs in child tables (Tier 3). A whole-entity `<entity>_proto BLOB` is used **only for deep entities** where Tiers 23 cost more than they're worth. No child-table explosion for deep aggregates.
2. **Classify each entity: all-scalar / refined / deep (supersedes the old "is a blob needed").** *All-scalar* → Tier 1 only, no blob (likely `ChangedFaction`). *Refined* → Tiers 13, no whole-entity blob, per-entity proto deletable (`ChangedHero`). *Deep* → Tier 1 + whole-entity `<entity>_proto BLOB`, proto retained (`ChangedProvince`, new-entity snapshots). Default to *refined* for shallow entities; fall back to *deep* only when the residual is too varied for Tiers 23.
3. **What's retained vs. deleted depends on the classification.** `action_results.payload` (the whole-`ActionResult` blob) still goes away in 4.5h. *Refined* entities' per-entity sub-message protos + converters become dead code, deleted in 4.5i; only the **leaf** protos they use as Tier-3 blob payloads (e.g. `event_for_hero_backstory.proto`) are retained. *Deep* entities' protos + `Quest` stay as whole-entity blob payloads. So 4.5i is no longer near-nothing.
4. **Sub-phase ordering** as in the Sequencing table; each decomposition PR splits into `.1` (schema + backfill) and `.2` (live write + read).
5. **Phase 4 landed separately, before 4.5a** (historical, unchanged). Cutover validated the lifecycle integration with the simpler schema before decomposition began.
+291
View File
@@ -0,0 +1,291 @@
# SQLite Game History Design
## Why
The current persistence layer is file-based: action results are chunked into `.e0a` files, individual results spill to `.e0i` files for crash recovery, state snapshots live in `.e0s` files, and a `directory.e0i` index tracks chunks. This shape has produced three workarounds in recent history:
1. A `games.e0es` cache (PR #6706) to avoid re-reading the running-games list.
2. Dual-storage in `PersistedActionResult` (proto bytes + parsed proto) to amortize serialization across save flushes.
3. Lazy `gameState` (PR #6692) to avoid eager proto conversion on every replayed step, after PR #6691 fixed the `stateAfter` OOM that materialized ~4500 `PersistedActionResult` instances during a stale-LLM-replay path.
Each is a workaround for the same root cause: file-based random access is expensive, so we cache aggressively, and the cache layers are fragile (one misplaced `.map(_.gameState)` reintroduces the OOM).
The alternative — SQLite as a per-game container, with proto bytes stored as BLOB columns indexed by action sequence number — gives us random access by construction, removes the need for all three workarounds, and makes idle-game eviction cheap (rehydrate from the DB instead of reparsing files). The pattern is already in production here: `SqliteClientTextStore` does exactly this for the client text cache. We extend the same pattern to game history.
## Goal & non-goals
**In scope:**
- Per-game SQLite container (`game.db`) holding action history, state snapshots, and shardok results.
- A new `SqliteHistory` class implementing the existing `FullGameHistory` trait, drop-in replacement for `PersistedHistory` at the call site.
**Out of scope (deferred or rejected):**
- **Migration of existing saves.** Pre-alpha there are only two users and a handful of test games. Cheaper to nuke the existing save directories at cutover than to write and verify a migration importer. New games created post-cutover land in `game.db` directly; existing games are gone.
- The top-level `games.e0es` running-games registry. Stays as-is; its cache (PR #6706) already works.
- Idle-game eviction. Enabled by this work but lands in a follow-up phase after `SqliteHistory` is the authoritative path.
- A shared cross-game analytics DB. Per-game design supports ad-hoc cross-game queries via iterate-and-aggregate; build the centralized analytics DB only if/when those queries become hot.
## File layout
`game.db` lives in the existing per-game save directory, alongside `text_store.db`:
```
${EAGLE_SAVE_DIR}/${gameIdHex}/
├── game.db # NEW — action history, snapshots, shardok results
└── text_store.db # existing — client text (SqliteClientTextStore)
```
Existing `.e0a` / `.e0s` / `.e0i` / `directory.e0i` files do not coexist with `game.db`: at cutover we nuke save directories one time. There is no migration path and no legacy-file fallback.
### Why `game.db` and `text_store.db` are separate files (not tables in one DB)
It's tempting to combine them — one file per game, one connection per game, one cloud-upload story. The reason not to: **writer-lock contention.** SQLite serializes writers per-database file. `SqliteClientTextStore` writes frequently during LLM streaming (one `UPDATE` per token append on `texts.text`). `SqliteHistory` writes per-action during turn commits. Combining them means an in-flight LLM token append can block a turn commit, or vice versa. Separate DBs have separate writer locks and never contend. Subsystem ownership (each package owning its own schema, independent migration paths if the schemas evolve) is a bonus.
`Persister` integration follows the `SqliteClientTextStore` pattern: `game.db` is uploaded to / downloaded from cloud storage as a single opaque blob, keyed by the filename. On first load, if `game.db` is missing locally, try `persister.retrieveAsStream("game.db")`. If both are missing, this is a new game and we create an empty DB.
## Schema
```sql
-- Action results, one row per action_result_index.
CREATE TABLE action_results (
action_seq INTEGER PRIMARY KEY, -- 0-based, dense, never sparse
action_result_type INTEGER NOT NULL, -- denormalized for filtering
round_id INTEGER NOT NULL, -- denormalized for recentResultsForRound
date_year INTEGER, -- denormalized for sinceDate; NULL pre-game-start
date_month INTEGER, -- denormalized for sinceDate; NULL pre-game-start
payload BLOB NOT NULL -- ActionResult proto bytes
) WITHOUT ROWID;
CREATE INDEX idx_action_results_round ON action_results(round_id);
CREATE INDEX idx_action_results_date ON action_results(date_year, date_month);
-- action_seq is the PK so no index needed there.
-- State snapshots at chunk boundaries (and the starting state at seq 0).
-- boundary_action_seq is the action_seq AFTER which the snapshot reflects state.
-- The starting state lives at boundary_action_seq = 0 (state before any actions).
CREATE TABLE state_snapshots (
boundary_action_seq INTEGER PRIMARY KEY,
payload BLOB NOT NULL -- GameState proto bytes
) WITHOUT ROWID;
-- Shardok per-battle results.
CREATE TABLE shardok_results (
shardok_game_id TEXT NOT NULL,
action_seq INTEGER NOT NULL, -- 0-based within this shardok game
payload BLOB NOT NULL, -- ShardokActionResult proto bytes
PRIMARY KEY (shardok_game_id, action_seq)
) WITHOUT ROWID;
-- Shardok per-game state (one row per shardok_game_id).
CREATE TABLE shardok_state (
shardok_game_id TEXT PRIMARY KEY,
game_state BLOB NOT NULL, -- ShardokGameState proto bytes
last_eagle_round_id INTEGER NOT NULL
) WITHOUT ROWID;
-- Shardok per-player results (filtered ActionResultView per faction).
CREATE TABLE shardok_player_results (
shardok_game_id TEXT NOT NULL,
faction_id INTEGER NOT NULL,
seq INTEGER NOT NULL,
payload BLOB NOT NULL, -- ShardokActionResultView proto bytes
PRIMARY KEY (shardok_game_id, faction_id, seq)
) WITHOUT ROWID;
-- Shardok per-player available commands (latest only, keyed by game + faction).
CREATE TABLE shardok_player_commands (
shardok_game_id TEXT NOT NULL,
faction_id INTEGER NOT NULL,
payload BLOB, -- ShardokAvailableCommands proto bytes; NULL = no commands
PRIMARY KEY (shardok_game_id, faction_id)
) WITHOUT ROWID;
-- Schema version and starting state.
CREATE TABLE metadata (
key TEXT PRIMARY KEY,
value BLOB NOT NULL
);
-- Seeded with: schema_version=1
```
### Column rationale
- **`action_seq`** as `INTEGER PRIMARY KEY` (the SQLite rowid alias) — densest possible storage and no separate index; range scans for `since(start)` are O(log n + result count).
- **`WITHOUT ROWID`** on tables with synthetic keys to skip the implicit rowid column.
- **Denormalized `action_result_type`, `round_id`, `date_year`, `date_month`** — these are the predicates the existing read paths use (`recentResultsForRound`, `sinceDate`). Keeping them as columns avoids parsing the proto blob to filter.
- **No `created_at` timestamp** — wall-clock time isn't queried by the History trait, and game date (year/month) is what matters semantically.
- **`payload BLOB`** — the proto bytes are the source of truth for the structured action result. Polymorphic action types make a relational schema painful for limited gain; the denormalized columns above cover the queries we need.
- **Snapshots keyed by `boundary_action_seq`** — `stateAfter(N)` finds `MAX(boundary_action_seq) WHERE boundary_action_seq <= N`, returns that snapshot, replays forward `N - boundary_action_seq` actions. Snapshot at `0` is the game's starting state.
### Snapshot strategy
Match the existing `resultsPerSaveFile = 25` boundary: write a `state_snapshots` row every 25 actions. That gives the same replay-window cost as the current chunk-file design (`stateAfter(N)` replays at most 25 actions to reach an arbitrary point), and matches the cadence developers are already calibrated to.
Snapshots are GameState proto bytes, identical in shape to today's chunk-file `startingState`. The migration importer derives them directly from the chunk files. New games write a snapshot after every 25th `withNewResults` action.
## Connection lifecycle
Mirror `SqliteClientTextStore`:
- One `Connection` per loaded game, opened when `GamesManager` loads the game, closed when the game is evicted (future eviction work) or the server shuts down.
- `Class.forName("org.sqlite.JDBC")` + `DriverManager.getConnection("jdbc:sqlite:${path}")` on open.
- `PRAGMA journal_mode = WAL` on every connection open. WAL gives us crash-safe writes and lets readers proceed concurrently with the single writer — important because gRPC stream readers (humanPlayerClientConnectionState) query history mid-turn.
- `PRAGMA synchronous = NORMAL` (the WAL-recommended setting; durability is preserved through WAL checkpoint).
- `PRAGMA foreign_keys = ON` (defensive; we have no FKs today but cheap to enable).
- Auto-commit on by default. Transactions explicitly opened for `withNewResults` (batch of action inserts + optional snapshot) and `truncateTo` (deletes across all tables).
### Threading
The current `PersistedHistory` is an immutable case class; `withNewResults` returns a new instance. `SqliteHistory` cannot be pure-immutable (the DB is mutable state) but should present the same interface: methods that "change" the history return `this` after a successful write. The underlying `Connection` is shared.
JDBC `Connection` is not thread-safe in general; SQLite's JDBC driver serializes operations per-connection. Existing call sites already serialize writes through the `EngineApplier` flow, so single-threaded write access is preserved. Reads from gRPC stream readers can use the same connection — SQLite serializes them transparently, and WAL prevents read-write blocking.
## Read paths
How each `FullGameHistory` method maps to SQL:
| Method | Query |
|---|---|
| `count` | `SELECT COALESCE(MAX(action_seq), -1) + 1 FROM action_results` (cached as a counter after the first read) |
| `last` | `SELECT payload FROM action_results ORDER BY action_seq DESC LIMIT 1` + state from `stateAfter(count)` |
| `all` | `SELECT payload FROM action_results ORDER BY action_seq` — used by `GameAdminServiceImpl.getActionDetail` to fetch one action by index. See follow-up note below. |
| `since(start)` | `SELECT payload FROM action_results WHERE action_seq >= ? ORDER BY action_seq` |
| `sinceDate(date)` | `SELECT payload FROM action_results WHERE (date_year, date_month) >= (?, ?) ORDER BY action_seq` |
| `recentResultsForRound(round, pred)` | `SELECT payload FROM action_results WHERE round_id = ? AND action_seq > ? ORDER BY action_seq` where `?` is the cutoff matching current `recentHistory` semantics (last N actions, or all actions for the current round) |
| `stateAfter(N)` | Find latest snapshot ≤ N, replay forward via `replayApplier` (same logic as `replayScalaOnlyToState`) |
For methods that return `Vector[ActionResultWithResultingState]` (with resulting state per row): we **do not** materialize per-row gameStates. Instead, fold the actions through `replayApplier` starting from the latest snapshot ≤ start, producing the states on the fly. This matches what `formAwrs` does today, with one critical difference: no `PersistedActionResult` wrapper is allocated, and no proto-conversion is performed per step. This is the same shape as `replayScalaOnlyToState`, generalized to produce intermediate states.
### `all()` follow-up
`GameAdminServiceImpl.getActionDetail` is the one production caller. It fetches a single action by index from the full vector. Either of these is cheaper than materializing the whole history:
- Replace the call site with `history.since(index).headOption`.
- Add a new `actionAt(index): Option[ActionResultWithResultingState]` method and drop `all()` from the trait entirely.
`SqliteHistory.all` will work — it's just `SELECT * ORDER BY action_seq` — but it's expensive (materializes the full history into memory), so we should switch the admin caller in a small follow-up PR. Not blocking the SQLite work.
### `recentResultsForRound` semantics
Today this filters `recentHistory` (the in-memory tail) by `roundId`. In SQLite there's no in-memory/persisted split — all results live in the DB. The semantics shift slightly: return all results matching `round_id` after a configurable cutoff. The cutoff should match today's behavior (results since the start of the current round, or some bounded recent window). Default to "all results with the given `round_id`," which is correct as long as `round_id` uniquely identifies a round across the game's history (it does, per the current `RoundId` model).
## Write paths
### `withNewResults(newResults)`
In a transaction:
1. `INSERT INTO action_results (action_seq, action_result_type, round_id, date_year, date_month, payload) VALUES ...` — one row per new result. Use `addBatch()` for multiple.
2. For each new result whose `action_seq % 25 == 0` (snapshot boundary), `INSERT INTO state_snapshots(boundary_action_seq, payload) VALUES (?, ?)` with the GameState proto bytes.
3. Commit.
The denormalized columns (`action_result_type`, `round_id`, `date_year`, `date_month`) are extracted from the action's resulting state at insert time. They are immutable once written; if the schema interpretation changes, a migration is required.
The "individual result for crash recovery" pattern (`.e0i` files) is replaced by: the action result is durably written when the transaction commits. WAL gives us atomicity per transaction. No separate crash-recovery file is needed.
### `saveNow`
Becomes a no-op in normal operation — writes are already durable per `withNewResults` commit. We keep the method on the trait for API compatibility but the implementation just returns `this`. (We could call `PRAGMA wal_checkpoint(TRUNCATE)` here to roll the WAL into the main DB file, useful before cloud upload; defer this until we measure WAL growth.)
### `truncateTo(targetActionCount)`
In a transaction:
1. `DELETE FROM action_results WHERE action_seq >= ?`
2. `DELETE FROM state_snapshots WHERE boundary_action_seq > ?`
3. Shardok cleanup: `DELETE FROM shardok_results / shardok_state / shardok_player_results / shardok_player_commands WHERE shardok_game_id NOT IN (...)` (the set of battles still outstanding at the truncate point; mirrors `deleteOrphanedShardokFiles`).
4. Commit.
`truncateTo(0)` resets the game; everything after the starting-state snapshot is deleted.
## Shardok results
The shardok subsystem currently lives in `.e0s` files (one per battle, full per-battle state). It's loaded selectively at game-load time, only for outstanding battles (see `PersistedHistory.apply` line 248-256).
Moving to SQLite, the four shardok tables above capture:
- `shardok_results` — the per-battle result stream
- `shardok_state` — current per-battle state (one row per battle)
- `shardok_player_results` — per-faction filtered views
- `shardok_player_commands` — current available commands per faction
`withNewShardokResults` writes to all four in a transaction. `shardokCount`, `shardokGameState`, etc., become single-row indexed lookups.
The selective-load optimization disappears with SQLite: we don't proactively read anything; queries hit the DB on demand. The "load only outstanding battles" logic is replaced by "query by `shardok_game_id` when needed."
## Crash recovery
WAL replaces the `.e0i` individual-result-file mechanism. On startup:
- WAL is automatically replayed by SQLite if the previous shutdown was unclean. No application code needed.
- A successful commit means durable; an interrupted commit means rolled back. No half-written state visible.
The current "orphaned individual results on load" path (`loadIndividualResults` in `PersistedHistory.apply`) is gone.
## Cutover
No migration path. At cutover:
1. Stop the server.
2. Nuke the contents of `${EAGLE_SAVE_DIR}` (and `${EAGLE_ARCHIVE_DIR}` if there's anything there).
3. Deploy.
4. New games created post-deploy land in `game.db` directly.
Pre-alpha there are only two users and a handful of test games; a one-time nuke is cheaper than a verified migration importer. Trade-off accepted by the user explicitly.
### Testing strategy (no migration)
Without migration, we don't need equivalence-vs-`PersistedHistory` testing. The correctness gate becomes:
1. **Adapt `PersistedHistoryTest`** to run against `SqliteHistory` instead. The 890-line existing test suite covers the trait surface exhaustively. Same assertions, new implementation under test.
2. **Property-style end-to-end test**: create a synthetic game, run N batches of `withNewResults`, verify that `since(start)`, `stateAfter(N)`, `sinceDate(date)`, `recentResultsForRound`, `truncateTo`, etc., all produce expected values. Run with a deterministic random seed.
3. **Manual smoke test in dev**: start a fresh game, play several turns, restart the server, verify saves persist and replay correctly.
## Cloud-storage integration
`Persister.save(key, bytes)` and `persister.retrieveAsStream(key)` already handle local-vs-S3 transparently. `SqliteClientTextStore` integrates by treating `text_store.db` as a single binary blob: upload after writes, download before reads.
`SqliteHistory` will do the same with `game.db`:
- **On load:** if local `game.db` missing, try to download via `persister.retrieveAsStream("game.db")`. Fall back to migration from `.e0a` if both are missing.
- **On save:** after a meaningful change (turn boundary? configurable cadence?), upload the current `game.db` file to S3. Need to decide the upload trigger — too frequent and we burn S3 PUTs; too rare and crash recovery is lossy.
**Open question:** the right upload cadence. Today, chunk saves trigger cloud upload at chunk boundaries (every 25 actions). The simplest match: keep that cadence, upload `game.db` once per chunk boundary. We could be smarter (only upload if WAL has been checkpointed; only upload deltas) but those are optimizations.
## What the trait-level cutover looks like
`GamesManager` currently has roughly:
```scala
val history: FullGameHistory = PersistedHistory(gameId, persister).getOrElse(...)
```
Becomes:
```scala
val history: FullGameHistory = SqliteHistory.loaded(gameId, persister)
```
Every other consumer of `FullGameHistory` is unchanged.
## Decisions locked
1. **Per-game `game.db`** (not shared across games).
2. **`game.db` and `text_store.db` stay separate files** (not combined into one DB). Writer-lock contention is the deciding factor.
3. **No migration** of existing saves. Nuke save directories at cutover. Pre-alpha trade-off accepted by the user.
4. **No feature flag.** Cutover is unconditional. Failures are loud.
5. **Cloud upload cadence**: match the existing 25-action chunk cadence. Upload `game.db` once per snapshot boundary.
6. **`recentResultsForRound`**: return all results for the given round (no recent-window cap). The `round_id` predicate bounds the scan naturally.
7. **WAL checkpointing**: rely on SQLite's auto-checkpoint. Add explicit `PRAGMA wal_checkpoint` only if WAL file growth becomes a problem.
8. **Schema versioning**: seed `metadata` with `schema_version = 1`. Schema migration mechanism deferred until we need a v2.
9. **`history.all`**: keep on the trait for now; admin call site moved to `since(i).headOption` (or a new `actionAt(i)` method) in a small follow-up PR. Not blocking.
## Phase plan (revised)
| Phase | Work | Estimate |
|---|---|---|
| 0 | This design doc | 2-3 days (in flight) |
| 1 | `SqliteHistory` schema + write paths + tests adapted from `PersistedHistoryTest` | ~1 week |
| 2 | Read paths + full test parity | ~1 week |
| 3 | Shardok results integration | 3-5 days |
| 4 | Cutover in `GamesManager` (nuke `${EAGLE_SAVE_DIR}` as part of deploy) | 2-3 days |
| 5 | Idle-game eviction | 3-5 days |
| 6 | Post-alpha cleanup (delete `PersistedHistory`, `PersistedActionResult`, `PartialGameUtils`, the chunk-file save code, `games.e0es` cache if no longer needed) | 1-2 days |
**Total: ~3-4 weeks** (down from 5-6 — migration and equivalence-testing dropped).
The follow-up to migrate `GameAdminServiceImpl.getActionDetail` off `history.all` is a small, independent PR that can land any time.
+1 -1
View File
@@ -32,7 +32,7 @@ When a new player starts their first game in tutorial mode, they experience:
- 1x Heavy Cavalry (600 troops, 80 training/armament)
- 1x Heavy Infantry (500 troops, 80 training/armament)
- 1x Longbowmen (300 troops, 80 training/armament)
- **Origin Province**: 32
- **Origin Province**: 31
### Flee Trigger
Attacker flees when ANY of these conditions are met:
+322
View File
@@ -0,0 +1,322 @@
# Tutorial System Architecture
This document describes how the Unity client's tutorial system is wired together: the classes involved, the trigger catalog, the step lifecycle, and the expected first-session flow. It complements two existing docs:
- **`TUTORIAL_CONTENT.md`** — human-facing copy for tutorial steps and dialogues
- **`TUTORIAL_BATTLE_SYSTEM.md`** — the scripted first-battle scenario (Tarn vs. John Ranil)
It also overlaps slightly with the in-tree `Assets/Tutorial/TUTORIAL_PLAN.md`, which is an older implementation plan.
All paths below are relative to `src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/`.
---
## Current State (important)
There are **two parallel subsystems** that share the same trigger plumbing:
| Subsystem | Status | Lives in |
|-----------|--------|----------|
| Step-based tutorial UI (modals, overlays, hints) | **Dormant** | `Tutorial/TutorialManager.cs`, `Tutorial/UI/*`, `Tutorial/Content/*` |
| Narrative dialogue system | **Live** | `Tutorial/Dialogue/*`, `Resources/Dialogues/*.json` |
`TutorialContentDefinitions.RegisterAll()` returns early at line 17 with the comment *"Old tutorial content suppressed — replaced by narrative dialogue system."* As a result:
- `OnboardingSequence` is never assigned, so `StartOnboarding()` no-ops at the "No onboarding sequence assigned" branch.
- No contextual tutorial sequences are registered with the trigger registry.
- The trigger registry still fires events normally, but nothing on the step-UI side is listening.
- `DialogueManager` consumes those same events and matches them against scripts in `Resources/Dialogues/` (`tutorial_strategic.json`, `tutorial_battle.json`).
**In practice today, the entire active tutorial experience runs through the dialogue system.** The step-UI machinery is preserved for future use — content definitions still exist below the early return in `TutorialContentDefinitions.cs` for reference.
---
## Class Map
### Orchestration
- **`Tutorial/TutorialManager.cs`** — Singleton. Owns `OnboardingSequence`, the active step queue, the trigger registry, and the dialogue manager handle. Initialized by `EagleGameController.SetUpGame()` and `ShardokGameController.SetUpGame()`.
- **`Tutorial/TutorialState.cs`** — PlayerPrefs persistence. Tracks `OnboardingCompleted`, `OnboardingStepReached`, completed sequence IDs (HashSet for O(1) lookup), dismissed hints, and a global "tutorials disabled" preference.
- **`Tutorial/TutorialTargetRegistry.cs`** — Maps string IDs to `RectTransform`s for highlighting. Static targets are Inspector-assigned (`ProvinceInfoPanel`, `SupportField`, `CommitButton`, etc.); dynamic targets register at runtime (e.g., hero rows from `HeroesAndBattalionsPanelController`).
### Triggers
- **`Tutorial/Triggers/TutorialTriggerRegistry.cs`** (~1100 lines) — Routes game events to both the step UI (when sequences are registered) and `DialogueManager`. Maintains one-shot session flags so the same first-encounter trigger doesn't fire twice.
### Content (step UI — dormant)
- **`Tutorial/Content/TutorialStep.cs`** — Per-step record: `DisplayMode`, `CompletionType`, target path, copy, panel anchor, highlight options.
- **`Tutorial/Content/TutorialSequence.cs`** — `ScriptableObject` holding ordered `TutorialStep`s plus `IsOnboarding` flag and lifecycle callbacks.
- **`Tutorial/Content/TutorialContentDefinitions.cs`** — Static class that *would* register all sequences. Currently short-circuits before any registration.
### UI (step UI — dormant)
- **`Tutorial/UI/TutorialUIManager.cs`** — Coordinates which presenter renders each step.
- **`Tutorial/UI/TutorialCanvasBuilder.cs`** — Builds the Canvas at runtime (no prefab dependency).
- **`Tutorial/UI/TutorialModalPanel.cs`** — Full-screen blocking modal.
- **`Tutorial/UI/TutorialOverlayController.cs`** + **`TutorialOverlayBuilder.cs`** — Dimmer with highlighted cutout, gold border, pulsing animation, and adjacent tooltip text.
- **`Tutorial/UI/TutorialHintIndicator.cs`** — Stub for pulsing-dot mode.
### Dialogue (live)
- **`Tutorial/Dialogue/DialogueManager.cs`** — Loads all `Resources/Dialogues/*.json` scripts at startup, indexes by trigger ID, drives the panel.
- **`Tutorial/Dialogue/DialogueScript.cs`** / **`DialogueStep.cs`** — JSON-shaped records for scripts and steps.
- **`Tutorial/Dialogue/DialoguePanelController.cs`** — Renders the speaker headshot, body text, instruction line, optional highlight target, and Continue button.
- **Scripts:** `Assets/Resources/Dialogues/tutorial_strategic.json`, `tutorial_battle.json`.
---
## Step Lifecycle (Step-UI System)
1. **Triggered**`TutorialTriggerRegistry` raises an event (e.g., `game_started`, `battle_entered`).
2. **Queued or shown** — If no active sequence, show immediately. If an active step is hidden (`DisplayMode.None`), interrupt it. If both new and active are command tutorials, interrupt for responsiveness. Otherwise queue.
3. **Rendered**`TutorialUIManager.ShowCurrentStep()` dispatches to the modal/overlay/hint presenter based on `DisplayMode`.
4. **Awaiting completion** — One of:
- `ButtonClick` — user dismisses
- `GameEvent` — wait for a named event (e.g., `province_selected`)
- `Timer` — auto-advance after delay
- `UIInteraction` — wait for the highlighted target to be interacted with
- `Condition` — custom predicate (rare)
5. **Advance**`AdvanceStep()` moves to the next step or completes the sequence; completion writes to `TutorialState`.
Hidden steps (`DisplayMode.None`) deliberately don't block — they exist so contextual tutorials can fire while the onboarding sequence is waiting on an async event.
---
## Display Modes
| Mode | Renderer | Notes |
|------|----------|-------|
| **Modal** | `TutorialModalPanel` | Full blocking dialog with dim background |
| **Overlay** | `TutorialOverlayController` | Dimmer with cutout + tooltip near a target |
| **Tooltip** | `TutorialOverlayController` | Currently same renderer as overlay |
| **Hint** | `TutorialHintIndicator` | Pulsing dot only (stub) |
| **None** | (invisible) | Waits for a completion event |
Panels can be anchored via `TutorialPanelAnchor` (`Center` / `Left` / `Right` / `Top` / `Bottom`).
---
## Trigger Catalog
All triggers are raised via `TutorialTriggerRegistry`. Today these flow to `DialogueManager.TriggerDialogue()` and are matched against the dialogue JSON; if step-UI sequences are re-registered, they will also route there. File:line citations are for the registry unless noted; line numbers may drift.
### Bootstrap / first-session
| Trigger | Fires from | When |
|---------|-----------|------|
| `game_started` | `EagleGameController.SetUpGame()` | First time entering a tutorial game |
| `first_battle_available` | `OnModelUpdated()` ~L204 | A `RunningShardokGameModel` first appears |
| `battle_entered` | `OnBattleEntered()` ~L793 | User clicks **Battle!** |
| `tutorial_battle_ended` | `CheckTutorialBattleEnded()` ~L594 | Tutorial battle removed from running models |
| `tutorial_rebuild_support` | `CheckTutorialRebuildSupport()` ~L616 | Captured-heroes phase done |
| `tutorial_taxes_collected` | `CheckTaxesCollected()` ~L680 | New Year action with positive tax delta |
| `tutorial_in_town` | `CheckInTown()` ~L500 | Return command becomes available |
### Strategic-map contextual
| Trigger | Site | When |
|---------|------|------|
| `province_selected` | `EagleGameController.ProvinceWasSelected()` | Province click |
| `command_issued` | `EagleGameController.PostCommittedCommand()` | User commits |
| `diplomacy_available` | `CheckStrategicCommandsAvailable()` ~L243 | Diplomacy command appears |
| `weather_control_available` | `CheckStrategicCommandsAvailable()` ~L249 | Weather command appears |
| `hero_recruitment_available` | `CheckHeroRecruitmentAvailable()` ~L266 | Free heroes detected |
| `tutorial_ready_to_join` | `CheckReadyToJoinHero()` ~L479 | Free hero with `WouldJoin` |
| `profession_<X>_encountered` | `CheckProfessionTutorial()` ~L726 | First time seeing each profession |
### Strategic guidance (state-derived, conditions checked each model update)
| Trigger | Site | Condition |
|---------|------|-----------|
| `guidance_loyalty_danger` | `CheckLoyaltyDanger()` ~L339 | November + hero loyalty < 70 |
| `guidance_neighbor_danger` | `CheckNeighborDanger()` ~L383 | Hostile faction adjacent |
| `guidance_recruit_heroes` | `CheckRecruitHeroesGuidance()` ~L420 | Province with support ≥40 has free heroes |
| `guidance_expand` | `CheckExpandGuidance()` ~L449 | One stable province, hasn't expanded |
| `guidance_sworn_kinship` | `CheckSwornKinshipGuidance()` ~L549 | Good candidate or 4+ provinces |
| `tutorial_loyalty_warning` | `CheckTutorialLoyaltyWarning()` ~L634 | November + hero loyalty < 70 |
| `tutorial_support_deadline` | `CheckTutorialSupportDeadline()` ~L654 | December + province support < 40 |
### Strategic action-result triggers (fired from `OnStrategicActionResult()`)
| Trigger | Site | When |
|---------|------|------|
| `hero_stat_gained` | ~L281 | `HeroStatGained` action result |
| `hero_profession_gained` | ~L284 | `ProfessionGained` action result |
| `tutorial_faction_appears` | ~L287 | `TutorialFactionAppears` action — the Fracture Covenant landing |
| `tutorial_hero_faction_appears` | ~L290 | `TutorialHeroFactionAppears` action (no dialogue script today) |
| `tutorial_hero_departed` | ~L299 | First `HeroesDeparted` action against another player (King's hero abandons service) |
| `tutorial_hero_departed_again` | ~L302 | Second `HeroesDeparted` in a *different* month than the first |
### Tactical (battle) — abilities and spells
Combat triggers are *paced*: `_combatTutorialPending` ensures only one fires per action, with priority `archery > duel > melee > charge > fire`.
| Trigger | Site | When |
|---------|------|------|
| `shardok_placement_started` | `OnBattleEntered()` ~L796 | Battle in setup phase |
| `shardok_battle_started` | `OnBattleEntered()` ~L793 | Battle begins |
| `shardok_battle_running` | `OnTacticalCommandsAvailable()` ~L948 | Player's first turn |
| `archery_available` | `OnTacticalCommandsAvailable()` ~L990 | Archery available |
| `melee_available` | `OnTacticalCommandsAvailable()` ~L991 | Melee available |
| `duel_available` | `OnTacticalCommandsAvailable()` ~L1005 | Duel available (non-Tarn target) |
| `ability_charge_available` | `OnTacticalCommandsAvailable()` ~L1001 | Charge for Old Marek |
| `start_fire_available` | `OnTacticalCommandsAvailable()` ~L1021 | Start Fire on enemy |
| `hide_available` | `OnTacticalCommandsAvailable()` ~L985 | Hedrick can hide |
| `thunderstorm` | `OnTacticalCommandsAvailable()` ~L1056 | Weather is thunderstorm |
| `spell_lightning_available` | `OnTacticalCommandsAvailable()` ~L960 | Lightning available |
| `spell_meteor_available` | `OnTacticalCommandsAvailable()` ~L963 | Meteor available |
| `spell_holywave_available` | `OnTacticalCommandsAvailable()` ~L965 | Holy Wave available |
| `spell_raisedead_available` | `OnTacticalCommandsAvailable()` ~L969 | Raise Dead available |
| `spell_lightning_cast` / `spell_meteor_cast` / `spell_holywave_cast` / `spell_raisedead_cast` | `CheckTacticalActionType()` ~L830-838 | Spell action observed |
| `ability_charge_used` | `CheckTacticalActionType()` ~L842 | Charge attack executed |
| `terrain_fire_encountered` | `CheckTacticalActionType()` ~L864 | Fire damage / spread |
| `terrain_water_encountered` | `CheckTacticalActionType()` ~L867 | Water crossing |
| `engineer_near_enemy` | `CheckEngineerNearEnemy()` ~L1105 | John Ranil within 3 hexes of enemy |
| `tutorial_reinforcement_engineer` / `tutorial_reinforcement_paladin` | `CheckTacticalActionType()` ~L857 | Reinforcement arrival |
| `friendly_hero_captured` | `CheckHeroRemovals()` ~L919 | Friendly hero unit removed |
| `enemy_hero_captured` | `CheckHeroRemovals()` ~L928 | Enemy hero unit removed |
| `battle_action` | `ShardokGameController.OnBattleAction()` | Any action result |
| `turn_ended` | `ShardokGameController.OnTurnEnded()` ~L1137 | Battle turn ends |
| `shardok_battle_reset` | `ShardokGameController.cs:627` (fired *directly* to `DialogueManager`, bypassing the registry) | Battle retry; the registry's battle flags and the battle dialogue scripts' completed-set are reset alongside, so per-battle tutorials re-fire |
### One-shot semantics
Most contextual triggers are guarded by booleans on the registry (e.g., a `_diplomacyShown` flag). These are session-local — they don't persist via `TutorialState`, but the registry has `ResetBattleTriggerFlags()` for replays. The strategic completion list *does* persist across sessions.
---
## Highlight Targets
Steps reference UI by string ID through `TutorialTargetRegistry`:
1. Static targets are wired in the Inspector on the registry.
2. Dynamic targets register at runtime (`RegisterTarget(id, rectTransform)`).
3. Lookup falls back to `GameObject.Find()` if not registered.
Step options:
- `TargetGameObjectPath` — primary highlight
- `AdditionalHighlightTargets[]` — multiple at once
- `HighlightBoundsFromChildren` — use children's bounding box
- `HighlightPulsing` — strobe animation
Dialogue scripts use the same registry via `highlightTarget` (and `persistHighlight: true` to keep the highlight after the dialogue closes).
---
## Sequences vs. Contextual Dispatch
- **Onboarding sequence** (`IsOnboarding = true`) — Single linear sequence, started by `StartOnboarding()`. Resumes from `OnboardingStepReached`. Counts only visible steps for progress.
- **Contextual** (`IsOnboarding = false`) — Single- or multi-step, dispatched on demand by `TriggerContextualTutorial()`.
- Dispatch rules in `TriggerContextualTutorial()`:
1. No active sequence → show immediately.
2. Active step is hidden (`None`) → interrupt.
3. Both are command tutorials → interrupt.
4. Otherwise → queue.
---
## Dialogue System (Currently Live)
`DialogueManager` is a parallel system, not a step-UI subclass. It loads every `TextAsset` in `Resources/Dialogues/` at startup, parses them as `DialogueScript` objects, and indexes by `trigger`.
Script shape (see `tutorial_strategic.json`):
```json
{
"scripts": [{
"id": "tutorial_opening",
"trigger": "game_started",
"panelPosition": null,
"steps": [{
"speakerName": "Old Marek the Learned",
"speakerImagePath": "fixed/old_marek_the_learned.png",
"dialogueText": "...",
"instructionText": "Click Battle! to enter tactical combat.",
"highlightTarget": "GoToBattleButton",
"persistHighlight": true,
"highlightProvince": "Onmaa",
"completionEvent": null
}]
}]
}
```
When a registry trigger fires, `OnGameEvent()` calls `DialogueManager.TriggerDialogue(triggerId)`. If a script matches and hasn't completed, it queues (or shows immediately) and the panel renders speaker headshot + body + instruction. Steps can pause for a `completionEvent` (e.g., wait for the player to click the highlighted button), allowing the dialogue to chain across game state changes.
Dialogue panel position defaults sensibly per scene (`top` during combat) and can be overridden per script.
---
## Persistence
`TutorialState` (PlayerPrefs JSON):
- `OnboardingCompleted` (bool)
- `OnboardingStepReached` (int)
- `CompletedTutorials` (List → HashSet at load)
- `DismissedHints` (List → HashSet at load)
- `AllTutorialsDisabled` (bool)
Reset paths:
- `TutorialState.Reset()` clears everything.
- Entering a tutorial game (`GameType.Tutorial`) resets so it can be replayed.
- Settings → "Reset Tutorials" calls `TutorialManager.ResetAllProgress()`, which also calls `DialogueManager.ResetCompletedScripts()`.
`DialogueManager` tracks completed scripts in memory only — they reset whenever `TutorialState` does.
---
## Bootstrap
1. `TutorialManager` is in the scene as a singleton; `Awake` loads state and creates the trigger registry. `RegisterAll()` is called here but currently no-ops.
2. `ConnectionHandler` sets `IsTutorialGame` and `IsMultiplayerGame` when the game is created/joined.
3. `EagleGameController.SetUpGame()` calls `TutorialManager.Instance.Initialize(this, null)`. If `IsTutorialGame && !OnboardingCompleted`, it would call `StartOnboarding()` — currently a no-op because `OnboardingSequence` is null.
4. The first model update raises `game_started`. `DialogueManager` matches `tutorial_opening` from `tutorial_strategic.json` and the dialogue runs.
5. `ShardokGameController.SetUpGame()` calls `TutorialManager.Instance.Initialize(null, this)` when battle starts; raises `battle_entered` and battle-only triggers from there.
---
## Expected Tutorial Flow (today)
Driven by `tutorial_strategic.json` + `tutorial_battle.json`. Old Marek the Learned narrates almost everything.
### Narrative arc
You play **Sadar Rakon**, formerly Ikhaan Tarn's most trusted lieutenant. Tarn's behavior grew erratic, the King wouldn't listen, so Sadar broke off and raised the **Reclamation**. He's been pushed back to **Onmaa** for a last stand against Tarn's superior royal army. After surviving, the real twist arrives: a new invasion — **The Fracture Covenant**, led by a mysterious figure called *The Eagle* — lands ships on the western coast and starts taking provinces. Heroes from the King's own service mysteriously begin to desert. The Reclamation's framing pivots from "rebellion" to "the only force that can stop the actual invasion."
### Strategic-map flow (`tutorial_strategic.json`)
| # | Trigger | What happens |
|---|---------|--------------|
| 1 | `game_started` | **Opening monologue** (3 steps): Sadar's backstory, the Reclamation, last stand at Onmaa. Ends highlighting the **Battle!** button (`persistHighlight`) |
| 2 | `tutorial_battle_ended` | **Aftermath**: Tarn has *vanished*; you've captured his lieutenants. Recruit them or hold them |
| 3 | `tutorial_rebuild_support` | **Rebuild Onmaa** (3 steps): Marek frames it; **John Ranil** introduces *Improve* (engineer bonus); **Elena Fyar** introduces *Give Alms* (paladin bonus). Goal: 40 support by January |
| 4 | `tutorial_loyalty_warning` | November-ish, low-loyalty hero may leave at year end → use *Give Gold* / *Feast* |
| 5 | `tutorial_support_deadline` | December nag if support < 40: have Elena give alms now |
| 6 | `guidance_expand` (script `tutorial_expansion`) | Once support is stable: keep developing, taxes coming in January |
| 7 | `tutorial_taxes_collected` | January: gold/food collected. Now expand — March your warlord + most heroes to a neighbor, leave 12 behind |
| 8 | `tutorial_ready_to_join` | A free hero in `{provinceName}` is ready to recruit → Travel + Recruit |
| 9 | `tutorial_in_town` | When you Travel: explains Trade / Arm Troops / Divine / Recruit / Manage Prisoners; *Return* ends the turn |
| 10 | `tutorial_faction_appears` | **The twist**: Fracture Covenant lands at Ingia and Soria. *The Eagle* commands them. Tarn may be with them |
| 11 | `tutorial_hero_departed` | First King's hero abandons service — "something deeper is at work" |
| 12 | `tutorial_hero_departed_again` | Second one in a different month — "something is wrong, I can feel it" (foreshadowing) |
### Tactical battle flow (`tutorial_battle.json`)
| # | Trigger | What happens |
|---|---------|--------------|
| 1 | `shardok_placement_started` | **Placement** (3 steps): identify Tarn's units (knights, heavy infantry, dragoons), color legend (red/blue/black), placement instructions, highlight Commit |
| 2 | `shardok_battle_running` | **Turn 1 strategy** (2 steps): victory conditions for both sides, advice to hold castles and End Turn |
| 3 | `archery_available` | First archery opportunity → purple outlines, longbows vs. armor |
| 4 | `melee_available` | First melee opportunity → right-click adjacent enemy |
| 5 | `ability_charge_available` | Charge mechanics (Marek hams it up: "old scholar without a horse") |
| 6 | `start_fire_available` | Start Fire on enemy hex, fire spread mechanics |
| 7 | `thunderstorm` | Weather: archery disabled, fires extinguished |
| 8 | `tutorial_reinforcement_paladin` | **Elena Fyar arrives** mid-battle (2-step exchange) → Paladin profession intro (Holy Wave) |
| 9 | `tutorial_reinforcement_engineer` | **John Ranil arrives** (2-step exchange) → Engineer profession intro |
| 10 | `engineer_near_enemy` | Once Ranil is close to enemy: Fortify + Reduce (siege bombardment) |
| 11 | `duel_available` | Champion duel mechanics (Marek warns *not* to duel Tarn himself) |
| 12 | `hide_available` | Hedrick the Hedge-merchant: forest/swamp Hide + ambush |
| 13 | `enemy_hero_captured` / `friendly_hero_captured` | Capture mechanics, with `{heroName}` substitution |
| 14 | `shardok_battle_reset` | If you lose and replay: Marek "had the strangest sensation… as though we'd already fought this battle, and lost" — fourth-wall-adjacent retry framing |
Most remaining "Tutorial / first-session onboarding" items in `SMALL_EAGLE_TODO.md` (Shardok tutorial, narrative hook, first-session goal, early small victory, guided first scenario vs. sandbox) map to *adding new dialogue scripts* against existing trigger IDs, or — if the step-UI is revived — to populating `TutorialContentDefinitions.RegisterAll()` and removing the early return.
---
## Notable Behaviors and Gotchas
- **`IsTutorialGame` gates everything.** Outside tutorial games, both subsystems short-circuit early.
- **Combat tutorials are deliberately paced.** Don't expect every available-ability trigger to fire on its first eligible turn — the registry intentionally spaces them.
- **One-shot flags are session-local.** A trigger that "already fired" will not re-fire even if `TutorialState` is reset, until the registry is recreated.
- **`TutorialTargetRegistry` lookups silently fall back to `GameObject.Find`.** Typos in target IDs will render with no highlight rather than throwing.
- **`TutorialContentDefinitions.RegisterAll()` returning early is load-bearing.** If the step UI is revived without auditing trigger overlap, dialogue and step-UI tutorials may double-fire on the same trigger.
- **`Tutorial/TUTORIAL_PLAN.md`** in the Unity project is an older implementation plan and partially overlaps this doc.
+19
View File
@@ -0,0 +1,19 @@
# Two-Stage Animation Implementation Pattern
Actions with server-determined success/failure outcomes use a two-stage system:
1. **Attempt phase**: Animation + sound plays immediately when the command is issued
2. **Result phase**: A distinct success or failure animation + sound plays when the server responds
## Adding a New Two-Stage Action
To add distinct success/failure animations for an action (using `ExtinguishFire` as an example):
1. **AnimationType enum** (`ShardokGameController.cs`): Add `ExtinguishFireFailed`
2. **AnimationTypeForAction()**: Map `ActionType.ExtinguishFireFailed` to new type
3. **AttemptAnimationType()**: Map `ExtinguishFireFailed` back to `ExtinguishFire`
4. **ActionTypeForSound()**: Map new type to `ActionType.ExtinguishFireFailed`
5. **PlayAnimation()**: Add dispatch case calling the new animator method
6. **Animator**: Add `AnimateExtinguishFailed()` method
7. **SoundManager**: Ensure result sound is mapped (usually already done)
See FearAnimator and FleeAnimator for reference implementations.
+197
View File
@@ -0,0 +1,197 @@
# Unity Scene Separation Plan
## Current State
The Unity client currently has both a large legacy scene and an unfinished split-scene setup.
- `Assets/Gameplay.unity` is still the production-sized monolithic scene. It contains connection/lobby UI, Eagle strategic UI, Shardok tactical UI, shared UI, camera/event-system objects, and miscellaneous persistent controllers.
- `Assets/Scenes/Main.unity`, `Connection.unity`, `Eagle.unity`, `Shardok.unity`, and `Shared.unity` already exist, but they are small shell scenes.
- `ProjectSettings/EditorBuildSettings.asset` includes both `Assets/Gameplay.unity` and the split scenes.
- `Assets/UI/Scripts/BootstrapManager.cs` is explicitly transitional and currently defaults to loading `Gameplay` additively through `useOriginalGameplayScene = true`.
- Additional migration notes exist under `Assets/SCENE_SEPARATION_PLAN.md`, `Assets/Scenes/README.md`, and `Assets/NEXT_STEPS.md`, but there is no repo-level plan in `docs/`.
This means the project is partway through a scene-separation migration, but runtime still depends on the monolithic scene.
## Recommendation
Finish the split-scene architecture. Keep one small bootstrap scene and load mode-specific UI scenes additively.
The target architecture should be:
- `Main`: startup/bootstrap only. Owns scene loading and truly persistent app services.
- `Shared`: shared UI and app-wide interaction infrastructure, such as the event system, error panels, confirmation modals, connection status overlays, settings, and update notifications.
- `Connection`: login, account selection, lobby, custom battle creation, and game-selection UI.
- `Eagle`: strategic map, strategic command panels, province/hero/battalion UI, notifications, and Eagle-specific effects.
- `Shardok`: tactical battle UI, hex grid, battle command UI, unit rows, tactical effects, and battle-only camera/input helpers.
Do not treat large prefabs as inherently bad. A large prefab is acceptable when it represents a coherent, reusable feature root. The problematic pattern is a large scene that owns unrelated application states and long-lived object references.
## Goals
- Reduce merge conflicts and accidental Unity serialization churn.
- Make login/lobby, Eagle, and Shardok changes independently editable.
- Make scene lifecycle explicit: load only the mode currently needed.
- Avoid cross-scene inspector references that are hard to reason about.
- Preserve a safe fallback until each migrated section is validated.
## Non-Goals
- Do not refactor gameplay logic and scene structure in the same change.
- Do not delete `Gameplay.unity` until all migrated scenes are verified in Editor, local builds, and CI.
- Do not move large vendor asset packs as part of this work.
- Do not split every small widget into its own scene. Prefer prefabs for reusable UI components and scenes for application modes.
## Target Runtime Flow
```text
Main
Load Shared
Load Connection
Connection -> Eagle
Unload Connection
Ensure Shared remains loaded
Load Eagle
Eagle -> Shardok
Keep Eagle loaded unless the battle UI must exclusively own the viewport
Load Shardok additively
Shardok -> Eagle
Unload Shardok
Keep Eagle and Shared loaded
Eagle -> Connection
Unload Shardok if loaded
Unload Eagle
Load Connection
```
## Ownership Rules
Use these rules during migration to avoid ambiguous object lifetimes.
- `Main` owns `GameSceneManager`, app bootstrap, and any service object that must survive across login, lobby, Eagle, and Shardok.
- `Shared` owns exactly one active `EventSystem` and shared modal/overlay UI.
- `Connection` owns `ConnectionHandler` and connection/lobby panel instances.
- `Eagle` owns `EagleGameController` and strategic-mode scene roots.
- `Shardok` owns `ShardokGameController` and tactical-mode scene roots.
- Cross-mode communication should happen through model/controller APIs, not direct serialized references to objects in another loadable scene.
- If a scene needs an object from another scene, prefer resolving it during scene initialization and failing loudly when required dependencies are missing.
## Migration Plan
### Phase 1: Make Bootstrap Explicit
- Make `Main.unity` the intended startup scene.
- Update `BootstrapManager` so the split-scene path is the default in development builds.
- Keep a temporary fallback flag for loading `Gameplay.unity`.
- Ensure build settings order is intentional: `Main` first, then loadable scenes. Leave `Gameplay` present only while fallback is still required.
- Add logging that states which startup path was chosen.
Validation:
- Enter Play Mode from `Main.unity`.
- Confirm `Shared` and `Connection` load without duplicate `EventSystem` objects.
- Confirm fallback still loads `Gameplay.unity` if explicitly enabled.
### Phase 2: Migrate Shared Infrastructure
- Move shared error UI, update UI, settings UI, connection status overlays, and global modal roots into `Shared.unity`.
- Keep only one event system active when additive scenes are loaded.
- Remove duplicated shared UI from `Gameplay.unity` only after migrated UI is validated.
Validation:
- Trigger an error modal from Connection, Eagle, and Shardok flows.
- Open/close settings from each mode that supports it.
- Verify no duplicate event-system warnings.
### Phase 3: Migrate Connection and Lobby
- Move `ConnectionCanvas`, login controls, account selector, lobby, custom battle UI, and game-selection rows into `Connection.unity`.
- Make `ConnectionHandler` initialize after the scene is loaded rather than assuming objects exist in `Gameplay.unity`.
- Replace show/hide transitions that activate large inactive subtrees with scene transitions where appropriate.
Validation:
- Start unauthenticated, authenticate, list available games, create/drop a custom battle, and enter a game.
- Return from an active game to the lobby.
- Test stored account flows.
### Phase 4: Migrate Eagle Strategic UI
- Move strategic map, command panel roots, hero/battalion/province UI, Eagle notifications, and strategic effects into `Eagle.unity`.
- Keep reusable row/panel widgets as prefabs under `Assets/Eagle/`.
- Remove direct dependencies on connection-scene objects.
Validation:
- Load a game from the lobby.
- Select provinces, heroes, battalions, command buttons, and notifications.
- Issue at least one representative command from each major command-panel family.
- Confirm generated/dynamic text listeners clean up when leaving the scene.
### Phase 5: Migrate Shardok Tactical UI
- Move Shardok canvas, hex grid, battle panels, tactical rows, battle effects, and battle-only input/camera roots into `Shardok.unity`.
- Decide whether Eagle remains visible/loaded under Shardok. Prefer keeping Eagle loaded if returning from battle must preserve strategic UI state.
- Ensure Shardok scene unload disposes generated text listeners, subscriptions, object pools, and pending animation state.
Validation:
- Enter battle from Eagle.
- Select units, issue movement/attack/fire/extinguish/end-turn commands.
- Resolve a battle and return to Eagle.
- Start a second battle in the same session to catch stale singleton/listener state.
### Phase 6: Remove Legacy Scene Dependency
- Flip the default so `Gameplay.unity` is not loaded during normal startup.
- Remove `Gameplay.unity` from build settings once no supported flow needs it.
- Keep `Gameplay.unity` in the repo temporarily as a reference snapshot if useful, then delete it in a separate cleanup PR.
- Remove transitional helpers whose only purpose was loading or testing the legacy scene.
Validation:
- Local Editor smoke test through login, Eagle, Shardok, and return flows.
- Unity edit-mode test suite if available.
- CI Unity build.
- TestFlight build before deleting the legacy scene.
## Review Checklist For Each Migration PR
- The PR moves one coherent subsystem, not multiple unrelated UI areas.
- Scene files remain small enough to review.
- Prefab changes are limited to the migrated subsystem.
- No required Inspector field is hidden behind a defensive null check.
- No duplicate `EventSystem`, camera, global canvas, or singleton is active.
- Leaving and re-entering the migrated scene works in one app session.
- The old `Gameplay.unity` object is removed only after the new scene object is verified.
## Risks
- Serialized cross-scene references will break when objects move. Prefer runtime lookup/initialization through explicit scene controllers.
- Singletons may survive scene unload and hold stale references. Audit `OnDestroy`, `Dispose`, and listener cleanup for every moved controller.
- Additive scenes can accidentally create duplicate input/event/camera objects. Keep these centralized in `Shared` or `Main`.
- Loading Shardok additively over Eagle can expose hidden assumptions about active canvases, cameras, and selected input targets.
- Unity scene YAML changes are easy to corrupt manually. Prefer moving objects in the Unity Editor and reviewing diffs carefully.
## Open Decisions
- Whether Shardok should overlay Eagle additively or unload most Eagle UI while battle is active.
- Whether the primary persistent game connection object belongs in `Main` or should be recreated per selected game.
- Whether `Shared` should always load at startup or only after successful connection.
- How long to keep `Gameplay.unity` after the split scene flow is fully validated.
## Suggested First PR
The first implementation PR should not move Eagle or Shardok. It should:
1. Make `Main.unity` the startup scene in build settings.
2. Make the split-scene bootstrap path explicit and logged.
3. Load `Shared` plus `Connection` by default.
4. Keep a fallback flag for loading `Gameplay.unity`.
5. Validate login/lobby startup in Editor and CI.
That gives a controlled base for subsequent subsystem migrations.
+173
View File
@@ -0,0 +1,173 @@
# URP Migration Plan
## Why
Unity is removing Built-In Render Pipeline (BiRP) support after Unity 6.7. We're currently on Unity 6.4. Each Unity minor version ships roughly quarterly, giving us a few release cycles before BiRP is dropped. This document lays out the migration plan.
## Strategy: Long-Lived Feature Branch
All URP conversion work happens on a **long-lived `urp-migration` branch**. Main stays fully functional on BiRP throughout the migration.
- **Main branch**: Continues using BiRP. All gameplay, AI, and server development proceeds normally.
- **URP branch**: Accumulates rendering pipeline changes across all phases.
- **Regular rebasing**: Periodically rebase/merge `main` into the URP branch to stay current. Shader and material changes rarely conflict with gameplay code, so merge conflicts should be manageable.
- **Merge to main**: Only when everything renders correctly and visual QA passes.
This avoids the "everything is pink" problem of switching the pipeline on main before shaders are converted.
## Current State
| Category | Count | Notes |
|---|---|---|
| Shaders | 47 | 7 custom Eagle, 1 hex mesh, 20 Polytope, 13 TextMesh Pro, 6 other third-party |
| Materials | 325 | Mix of Standard shader, custom, and third-party |
| ShaderGraph files | 4 | All TextMesh Pro (URP + HDRP variants already exist) |
| Scenes with baked lighting | 6 | Gameplay, Connection, Eagle, Shardok, Shared, Map Editor |
| Post-processing | 1 profile | PPP_Orc.asset (Post Processing Stack v2, FXAA/TAA, AO) |
| C# rendering scripts | 16 | Material/shader property manipulation only |
| Rendering path | Forward | Matches URP default |
### Positive Findings
- **No OnRenderImage, Graphics.Blit, CommandBuffer, or GL.\* usage** in C# code
- Forward rendering already in use (matches URP default)
- TextMesh Pro already has URP ShaderGraph variants in the project
- No custom render passes or ScriptableRenderFeatures
- Shader property manipulation (SetTexture, SetFloat, SetColor) is URP-compatible
### Known Risk Areas
- **GrabPass shaders** (HeatShimmerShader, PT_Water_Shader) have no direct URP equivalent
- **ProvinceMapShader** is complex (province ID lookup, border rendering, ocean animation, faction highlighting, UI clipping)
- **Surface shaders** (`#pragma surface surf Standard`) must be rewritten as HLSL or ShaderGraph
- **Polytope Studio shaders** (20 shaders) have no vendor-provided URP variants
- **Post Processing Stack v2** must be replaced with URP's integrated Volume system
- **Tessellation** (PT_Water_Shader) is not natively supported in URP
## Shader Inventory
### Custom Eagle Shaders (7) -- HIGH PRIORITY
| Shader | Complexity | Key Issues |
|---|---|---|
| ProvinceMapShader | High | Province ID texture lookup, border rendering, ocean animation, faction highlighting, `UnityUI.cginc` dependency, stencil/clipping |
| ProvinceWeatherMapShader | Medium | Weather overlay rendering |
| ProvinceWeatherShader | Medium | Province weather effects |
| ProvinceParticleShader | Low | Custom particle rendering |
| HeatShimmerShader | High | **GrabPass** for screen distortion, province masking |
| ClipRectParticleUnlit | Low | UI-clipped particle shader |
| maskShader | Low | UI masking |
### Hex Mesh Shader (1) -- MODERATE PRIORITY
Uses `#pragma surface surf Standard` with GPU instancing. Straightforward conversion to URP Lit or ShaderGraph.
### Third-Party Shaders (39)
| Source | Count | Complexity | Notes |
|---|---|---|---|
| Polytope Studio | 20 | Moderate-High | PBR, Toon, vegetation (custom lighting), water (**GrabPass + tessellation**). No vendor URP pack available. |
| TextMesh Pro | 13 | Low | URP ShaderGraph variants already exist in project |
| RRFreelance | 3 | Low | Standard surface shaders, direct conversion |
| Clown.fat | 2 | Moderate | Custom ToonRamp lighting model |
| GUI Pro Kit | 1 | Low | Hidden particle shader |
### GrabPass Shaders (Require Special Handling)
GrabPass does not exist in URP. These must be reimplemented using `ScriptableRenderPass` + `Renderer Features` or Blit-based alternatives:
1. **HeatShimmerShader** -- Screen distortion effect (currently has a shimmer-disabled TODO, may be deprioritized)
2. **PT_Water_Shader** -- Water refraction/transparency (PT_Water_Shader_WebGl exists without GrabPass as a reference)
## Phased Approach
### Phase 1: Pipeline Setup + Auto-Conversion (Days 1-3)
- Install URP package
- Create URP Pipeline Asset and Renderer Asset
- Configure basic pipeline settings (forward rendering, shadow settings)
- Run Unity's **Render Pipeline Converter** (Edit > Rendering > Render Pipeline Converter)
- Auto-converts Standard shader materials and some built-in shaders
- Handles a significant portion of the 325 materials
- Will NOT touch custom shaders
- Create a test scene to validate basic rendering
- Migrate viewport clipping system (`RendererViewportClipper`, `ViewportClipper`, `PopupClipper`) to use URP-compatible global shader properties
### Phase 2: Custom Eagle Shaders (Weeks 1-3)
This is the critical path. Without these, the game is unplayable.
**Week 1-2: ProvinceMapShader**
- Convert from BiRP Cg/HLSL to URP HLSL
- Replace `UnityCG.cginc` includes with `Core.hlsl` / `Common.hlsl`
- Replace `UnityUI.cginc` with custom URP-compatible UI clipping
- Preserve province ID texture lookup, border rendering, ocean animation, faction highlighting
- Validate stencil operations and render queue ordering
**Week 2-3: Remaining Eagle shaders**
- ProvinceWeatherMapShader + ProvinceWeatherShader
- ProvinceParticleShader + ClipRectParticleUnlit
- maskShader
- Hex Mesh Shader (convert surface shader to URP Lit)
- HeatShimmerShader (reimplement without GrabPass, or defer if shimmer remains disabled)
### Phase 3: Third-Party Shaders (Weeks 4-6)
**Polytope Studio (20 shaders)**
- Convert PBR shaders (Armors, NPC, Weapons, Props, Rock) from surface shaders to URP Lit / ShaderGraph
- Convert Toon shaders to custom URP shader or ShaderGraph with custom lighting
- Convert vegetation shaders (custom `StandardCustom` lighting) to ShaderGraph
- PT_Water_Shader: Reimplement without GrabPass and tessellation (use PT_Water_Shader_WebGl as reference for non-GrabPass approach)
**Other third-party**
- Clown.fat ToonRamp shaders: Convert custom lighting model to ShaderGraph
- RRFreelance shaders: Direct Standard-to-URP-Lit conversion
- GUI Pro Kit particle shader: Convert to URP particle shader
### Phase 4: Materials, Lighting & Post-Processing (Weeks 7-8)
**Materials**
- Batch-update any remaining materials not handled by the auto-converter
- Verify all 325 materials render correctly
- Fix any visual differences from lighting model changes
**Lighting**
- Rebake lightmaps for all 6 scenes (Gameplay, Connection, Eagle, Shardok, Shared, Map Editor)
- Configure URP shadow cascade settings to match current quality levels
- Verify HDR rendering
**Post-Processing**
- Remove Post Processing Stack v2 dependency (`com.unity.postprocessing: 3.5.1`)
- Replace with URP integrated Volume system
- Recreate PPP_Orc effects (FXAA/TAA, Ambient Occlusion) using URP Volume overrides
### Phase 5: Testing & Validation (Weeks 9-11)
- Visual QA across all 6 scenes
- Verify beast/character rendering (vertex colors, animations)
- Verify weather effects (blizzard, drought, flood)
- Verify particle systems (fire & explosion effects, UI particles)
- Verify UI rendering (GUI Pro Kit, Modern UI Pack, TextMesh Pro)
- Performance profiling (URP has different performance characteristics)
- Test on target platforms
- Bug fixes and visual polish
## Effort Estimates
| Phase | Best Case | Realistic | Worst Case |
|---|---|---|---|
| 1. Pipeline Setup | 1-2 days | 2-3 days | 3-5 days |
| 2. Custom Eagle Shaders | 1.5 weeks | 2-3 weeks | 3-4 weeks |
| 3. Third-Party Shaders | 1.5 weeks | 2-3 weeks | 3-4 weeks |
| 4. Materials & Lighting | 3-5 days | 1-1.5 weeks | 2 weeks |
| 5. Testing & Validation | 1 week | 1.5-2 weeks | 2-3 weeks |
| **Total** | **6-8 weeks** | **8-12 weeks** | **12-16 weeks** |
The biggest variable is Polytope Studio shader conversion. If vendor URP packs become available, Phase 3 shrinks significantly.
## Key Reminders
- **Don't leave GrabPass rewrites and ProvinceMapShader for the end** -- they're the riskiest pieces and should be tackled early.
- The migration window (~1 year) is comfortable. Spreading the work across this window is fine, but front-load the hard shader work.
- C# code changes should be minimal -- the codebase avoids direct rendering API usage.
- `UnityUI.cginc` has no direct URP equivalent. Custom implementation will be needed for UI clipping in shaders.
+119 -51
View File
@@ -4,17 +4,36 @@ This document describes which quests the AI attempts to complete proactively to
## Overview
The AI attempts to complete quests via `FulfillQuestsCommandSelector`, which is invoked by `MidGameAIClient.chosenFulfillEasyQuestsCommand`. The AI only considers quests from unaffiliated heroes in provinces ruled by a faction leader.
The AI attempts to complete most quests via `FulfillQuestsCommandSelector`, which is invoked by `MidGameAIClient.chosenFulfillEasyQuestsCommand`.
Important scope limits:
- The selector only considers quests from unaffiliated heroes in provinces owned by the acting faction.
- It further filters to provinces ruled by that faction's leader.
- It only emits a command when the corresponding command is currently available.
- Handler order is fixed. The first handler that produces a valid command wins.
## Quests the AI Actively Completes
This section lists quests with direct `QuestCommandChooser` handlers in `FulfillQuestsCommandSelector`.
### Diplomacy Quests
| Quest | Handler | Conditions |
|-------|---------|------------|
| `AllianceQuest` | `AllianceQuestCommandChooser` | Target faction must meet trust conditions for alliance and not already be in an alliance |
| `TruceWithFactionQuest` | `TruceWithFactionQuestCommandChooser` | Target faction must meet trust conditions for truce |
| `TruceCountQuest` | `TruceCountQuestCommandChooser` | Picks a random faction that meets trust conditions and isn't already in a truce/alliance |
| `AllianceQuest` | `AllianceQuestCommandChooser` | Target faction must meet trust conditions for alliance and not already be in an alliance |
| `BetrayAllyQuest` | `BetrayAllyQuestCommandChooser` | Break alliance with target faction. Only if factions don't share a border. Sends weakest non-leader hero. |
### Province Development Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `ImproveAgricultureQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Agriculture type |
| `ImproveEconomyQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Economy type |
| `ImproveInfrastructureQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Infrastructure type |
| `TotalDevelopmentQuest` | `TotalDevelopmentQuestCommandChooser` | Improve the lowest stat in the target province |
### Resource Giving Quests
@@ -24,72 +43,99 @@ The AI attempts to complete quests via `FulfillQuestsCommandSelector`, which is
| `AlmsAcrossRealmQuest` | `AlmsAcrossRealmQuestCommandChooser` | Gives food from the province with the largest surplus |
| `GiveToHeroesInProvinceQuest` | `GiveToHeroesInProvinceQuestCommandChooser` | Gives gold to the hero with the lowest loyalty in the specified province |
| `GiveToHeroesAcrossRealmQuest` | `GiveToHeroesAcrossRealmQuestCommandChooser` | Gives gold from the province with the most gold available |
| `SpendOnFeastsInProvinceQuest` | `SpendOnFeastsQuestCommandChooser` | Spend gold on feasts in the quest holder's province |
| `SpendOnFeastsAcrossRealmQuest` | `SpendOnFeastsQuestCommandChooser` | Spend gold on the most expensive currently available feast |
| `SendSuppliesQuest` | `SendSuppliesQuestCommandChooser` | Send food to the target province |
### Province Development Quests
### Prisoner Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `ImproveAgricultureQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Agriculture type |
| `ImproveEconomyQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Economy type |
| `ImproveInfrastructureQuest` | `ImproveQuestCommandChooser` | Issues an Improve command with Infrastructure type |
| `ReleasePrisonerQuest` | `ReleasePrisonerQuestCommandChooser` | Release a specific prisoner |
| `ExilePrisonerQuest` | `ExilePrisonerQuestCommandChooser` | Exile a specific prisoner |
| `ExecutePrisonerQuest` | `ExecutePrisonerQuestCommandChooser` | Execute a specific prisoner |
| `ReturnPrisonerQuest` | `ReturnPrisonerQuestCommandChooser` | Return a prisoner to their faction |
| `ReleaseAllPrisonersQuest` | `ReleaseAllPrisonersQuestCommandChooser` | Release all prisoners |
### Province Order Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `DevelopProvincesQuest` | `DevelopProvincesQuestCommandChooser` | Switches provinces to Develop order. Prefers provinces without hostile neighbors. |
| `MobilizeProvincesQuest` | `MobilizeProvincesQuestCommandChooser` | Switches provinces to Mobilize order. Prefers provinces with hostile neighbors. Skipped if a DevelopProvincesQuest also exists (conflict avoidance). |
### Weather/Epidemic Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `StartEpidemicQuest` | `StartEpidemicQuestCommandChooser` | Start an epidemic in a province. Skipped if the target province belongs to the acting faction. |
| `StartBlizzardQuest` | `ControlWeatherQuestCommandChooser` | Start a blizzard via ControlWeather command. Skipped if the target province belongs to the acting faction. |
| `StartDroughtQuest` | `ControlWeatherQuestCommandChooser` | Start a drought via ControlWeather command. Skipped if the target province belongs to the acting faction. |
### Military Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `GrandArmyQuest` | `GrandArmyQuestCommandChooser` | Uses OrganizeTroops to top off existing battalions and hire Light Infantry. Only executes if resources are sufficient to fully meet the troop target. |
| `BattalionDiversityQuest` | `BattalionDiversityQuestCommandChooser` | Hires one battalion of a missing type to reach 3+ distinct types. Only attempts if the province already has 2+ existing types, has sufficient development (`meetsRequirements`), and gold/food surplus. |
| `UpgradeBattalionQuest` | `UpgradeBattalionQuestCommandChooser` | Walks a priority tree per turn: arm-completes (with optional travel and/or food sale setup) → train-completes → march in a pre-qualified neighbor battalion → organize/top-off of the target type → march in an unqualified neighbor battalion → develop Economy/Agriculture → train progress → develop Infrastructure → arm progress. Only toggles Travel when it directly enables an arm-completes finisher. |
### Reconnaissance Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `ReconSpecificProvincesQuest` | `ReconSpecificProvincesQuestCommandChooser` | Recon specific target provinces. Prefers not-yet-reconned targets. |
| `ReconProvincesQuest` | `ReconProvincesQuestCommandChooser` | Issues a Recon command to reconnoiter a province |
### Beast Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `FightBeastsAloneQuest` | `FightBeastsAloneQuestCommandChooser` | Send an expendable non-leader hero to fight beasts without a battalion. Hero must have power at most `MaxExpendableHeroPowerRatio` (default 0.75) times the quest-giving hero's power. Picks the weakest eligible hero. |
### Special Event Quests
| Quest | Handler | Notes |
|-------|---------|-------|
| `ApprehendOutlawQuest` | `ApprehendOutlawQuestCommandChooser` | Apprehend a specific outlaw hero when present in the province |
### Other Quests
| Quest | Handler | Conditions |
|-------|---------|------------|
| `RestProvinceQuest` | `RestProvinceQuestCommandChooser` | Use the Rest command in a specific province |
| `SwearBrotherhoodWithHeroQuest` | `SwearBrotherhoodQuestCommandChooser` | Swear brotherhood with a specific hero |
| `DismissSpecificVassalQuest` | `DismissSpecificVassalCommandChooser` | Only if province has more than 2 heroes AND the unaffiliated hero's power >= target hero's power * `RequiredPowerMultiplierForDismiss` |
## Quests the AI Does Not Attempt to Complete
## Quests the AI Handles Indirectly
The following quests have no handler in `FulfillQuestsCommandSelector` and must be completed naturally through gameplay:
These are not in `FulfillQuestsCommandSelector`, but other AI command-selection code can still bias toward completing them.
### Combat/Military Quests
- `DefeatFactionQuest` - Defeat a specific faction
- `GrandArmyQuest` - Accumulate a large number of troops
- `UpgradeBattalionQuest` - Upgrade a battalion to minimum armament/training
- `WinBattleOutnumberedQuest` - Win a battle while outnumbered
- `WinBattlesQuest` - Win a number of battles
- `RescueImprisonedLeaderQuest` - Rescue an imprisoned leader from another faction
| Quest | Handler | Notes |
|-------|---------|-------|
| `SuppressRiotByForceQuest` | `CommandChoiceHelpers.handleRiotSelectedCommand` | When this quest exists and the faction has battalions, the AI prefers CrackDown over Give when handling riots. |
### Expansion Quests
- `ExpandToProvincesQuest` - Expand to control a certain number of provinces
- `SpecificExpansionQuest` - Conquer a specific province
- `BorderSecurityQuest` - Have troops in a border province
## Quests the AI Does Not Yet Attempt to Complete
### Prisoner Quests
- `ExecutePrisonerQuest` - Execute a specific prisoner
- `ExilePrisonerQuest` - Exile a specific prisoner
- `ReleasePrisonerQuest` - Release a specific prisoner
- `ReturnPrisonerQuest` - Return a prisoner to their faction
- `ReleaseAllPrisonersQuest` - Release all prisoners
The following quests have no handler and must be completed naturally through gameplay. They are listed in rough priority order for future implementation.
### Province Order Quests
- `DevelopProvincesQuest` - Maintain provinces in Develop order for months
- `MobilizeProvincesQuest` - Maintain provinces in Mobilize order for months
- `RestProvinceQuest` - Use the Rest command in a specific province
### Planned for Implementation
### Reconnaissance Quests
- `ReconProvincesQuest` - Reconnoiter a number of provinces
- `ReconSpecificProvincesQuest` - Reconnoiter specific provinces
None currently planned.
### Economic Quests
- `TotalDevelopmentQuest` - Achieve total development level in a province
- `WealthQuest` - Accumulate gold and food
- `SpendOnFeastsQuest` - Spend gold on feasts
- `SendSuppliesQuest` - Send food to a specific province
- `RepairDevastationQuest` - Repair devastation
### Not Planned
### Special Event Quests
- `SuppressRiotByForceQuest` - Suppress a riot by force
- `FightBeastsAloneQuest` - Fight beasts alone
- `StartBlizzardQuest` - Start a blizzard in a province
- `StartEpidemicQuest` - Start an epidemic in a province
- `ApprehendOutlawQuest` - Apprehend an outlaw hero
These quests are too situational, passive, or risky to actively pursue. They may be completed naturally through gameplay.
### Miscellaneous
- `BattalionDiversityQuest` - Have diverse battalion types
- `SwearBrotherhoodWithHeroQuest` - Swear brotherhood with a specific hero
- `BetrayAllyQuest` - Betray an allied faction
- `BorderSecurityQuest` - Have troops in a border province. Involves taking provinces; better left to organic expansion.
- `DefeatFactionQuest` - Defeat a specific faction. Too risky to pursue proactively.
- `SpecificExpansionQuest` - Conquer a specific province. Too risky.
- `ExpandToProvincesQuest` - Expand to control a certain number of provinces. Too risky.
- `WinBattleOutnumberedQuest` - Win a battle while outnumbered. Can't reliably engineer.
- `WinBattlesQuest` - Win a number of battles. Passive.
- `RescueImprisonedLeaderQuest` - Rescue an imprisoned leader. Complex multi-step.
- `WealthQuest` - Accumulate gold and food. Happens passively.
- `RepairDevastationQuest` - Repair devastation. Happens passively.
## Implementation Details
@@ -102,12 +148,34 @@ Each chooser extends either:
- `DeterministicQuestCommandChooser` - For quests with deterministic command selection
The AI prioritizes quests in the order they appear in `FulfillQuestsCommandSelector.choosers`:
1. Alliance
2. TruceWithFaction
3. Improve (Agriculture/Economy/Infrastructure)
1. TruceWithFaction
2. Improve (Agriculture/Economy/Infrastructure)
3. TotalDevelopment
4. AlmsToProvince
5. GiveToHeroesInProvince
6. AlmsAcrossRealm
7. GiveToHeroesAcrossRealm
8. TruceCount
9. DismissSpecificVassal
10. ReleasePrisoner
11. ExilePrisoner
12. ExecutePrisoner
13. ReturnPrisoner
14. ReleaseAllPrisoners
15. ApprehendOutlaw
16. SpendOnFeastsInProvince / SpendOnFeastsAcrossRealm
17. RestProvince
18. DevelopProvinces
19. MobilizeProvinces
20. SendSupplies
21. StartEpidemic
22. ControlWeather (StartBlizzard/StartDrought)
23. GrandArmy
24. FightBeastsAlone
25. BattalionDiversity
26. UpgradeBattalion
27. ReconSpecificProvinces
28. ReconProvinces
29. SwearBrotherhood
30. Alliance
31. BetrayAlly
+1 -1
View File
@@ -12,7 +12,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/webview/webview_go v0.0.0-20240831120633-6173450d4dd6
golang.org/x/sys v0.28.0
golang.org/x/sys v0.30.0
google.golang.org/grpc v1.68.0
google.golang.org/protobuf v1.36.3
)
+2 -2
View File
@@ -43,8 +43,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/webview/webview_go v0.0.0-20240831120633-6173450d4dd6 h1:VQpB2SpK88C6B5lPHTuSZKb2Qee1QWwiFlC5CKY4AW0=
github.com/webview/webview_go v0.0.0-20240831120633-6173450d4dd6/go.mod h1:yE65LFCeWf4kyWD5re+h4XNvOHJEXOCOuJZ4v8l5sgk=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+829
View File
File diff suppressed because it is too large Load Diff
+4 -8
View File
@@ -2,9 +2,6 @@
#
# Build the SparklePlugin native library for Unity using Bazel
#
# The SparklePlugin is built in a separate Bazel workspace (sparkle_workspace/)
# to avoid rules_swift version conflicts between grpc and rules_apple.
#
# Usage: build_sparkle_plugin.sh [output_dir]
set -euo pipefail
@@ -14,14 +11,13 @@ PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
OUTPUT_DIR="${1:-$PROJECT_ROOT/src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Plugins/macOS}"
echo "=== Building SparklePlugin with Bazel (from sparkle_workspace) ==="
echo "=== Building SparklePlugin with Bazel ==="
# Build in the separate sparkle_workspace to avoid dependency conflicts
cd "$PROJECT_ROOT/sparkle_workspace"
bazel build //:SparklePlugin
cd "$PROJECT_ROOT"
bazel build //src/main/objc/net/eagle0/clients/unity/sparkle:SparklePlugin
# Get the zip path from bazel
ZIP_PATH=$(bazel cquery --output=files //:SparklePlugin 2>/dev/null)
ZIP_PATH=$(bazel cquery --output=files //src/main/objc/net/eagle0/clients/unity/sparkle:SparklePlugin 2>/dev/null)
echo "=== Extracting SparklePlugin.bundle ==="
mkdir -p "$OUTPUT_DIR"
+3 -1
View File
@@ -4,8 +4,10 @@
set -e
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
# Run gazelle
bazel run //:gazelle 2>/dev/null
bazel run //:gazelle
# Check if any BUILD files were modified
if ! git diff --quiet -- '*.bazel' '**/BUILD' 'WORKSPACE*'; then
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# Pre-commit hook wrapper for scalafmt.
# Runs the repository-pinned scalafmt CLI through Bazel.
set -e
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
if [ "$#" -eq 0 ]; then
exit 0
fi
repo_root="$(git rev-parse --show-toplevel)"
files=()
for file in "$@"; do
case "$file" in
/*) files+=("$file") ;;
*) files+=("$repo_root/$file") ;;
esac
done
bazel run //tools:scalafmt -- --config "$repo_root/.scalafmt.conf" -i "${files[@]}"
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Keeps Bazel macOS builds in sync with the installed Xcode version.
#
# Needed on macOS runners and developer machines because Bazel's generated
# local_config_xcode/local_config_apple_cc repositories bake in the discovered
# Xcode version. If Xcode is upgraded in place, the DEVELOPER_DIR path stays the
# same, so Bazel can otherwise keep using stale Xcode metadata.
#
# 1. Writes .bazelrc.xcode with macOS-scoped flags:
# - action_env for remote cache key invalidation
# - DEVELOPER_DIR pointing to the active Xcode
#
# 2. Runs `bazel clean --expunge` when the version actually changes, because
# local_config_apple_cc (a cached repository rule) bakes in the old version
# and can only be refreshed by clearing the output base.
#
# .bazelrc imports the generated file via: try-import %workspace%/.bazelrc.xcode
set -euo pipefail
DEVELOPER_DIR=""
if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then
DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"
else
DEVELOPER_DIR=$(xcode-select -p 2>/dev/null || true)
fi
XCODE_BUILD_VERSION=$(DEVELOPER_DIR="$DEVELOPER_DIR" xcodebuild -version 2>/dev/null | awk '/Build version/ {print $3}' || true)
if [ -z "$XCODE_BUILD_VERSION" ]; then
echo "ERROR: Could not detect full Xcode build version."
echo "mactools/Sparkle builds require full Xcode, not just Command Line Tools."
echo "Install Xcode at /Applications/Xcode.app or select it with xcode-select."
exit 1
fi
BAZELRC_XCODE=".bazelrc.xcode"
EXPECTED_LINE="common:macos --action_env=XCODE_BUILD_VERSION=${XCODE_BUILD_VERSION}"
# Check if the file already has the right version (first line is the version marker)
if [ -f "$BAZELRC_XCODE" ]; then
CURRENT_FIRST_LINE=$(head -1 "$BAZELRC_XCODE")
if [ "$CURRENT_FIRST_LINE" = "$EXPECTED_LINE" ]; then
exit 0
fi
fi
# Xcode version changed (or first run) — expunge local cache to clear
# stale local_config_apple_cc, then write the new config
OLD_VERSION="unknown"
if [ -f "$BAZELRC_XCODE" ]; then
OLD_VERSION=$(sed -n 's/.*XCODE_BUILD_VERSION=//p' "$BAZELRC_XCODE" | head -1)
fi
echo "Xcode build version changed: ${OLD_VERSION} -> ${XCODE_BUILD_VERSION}"
echo "Running bazel clean --expunge to clear stale toolchain config..."
bazel clean --expunge 2>/dev/null || true
cat > "$BAZELRC_XCODE" << EOF
${EXPECTED_LINE}
common:macos --repo_env=DEVELOPER_DIR=${DEVELOPER_DIR}
EOF
if [ -n "${GITHUB_ENV:-}" ]; then
echo "DEVELOPER_DIR=${DEVELOPER_DIR}" >> "$GITHUB_ENV"
fi
echo "Updated ${BAZELRC_XCODE} — next macOS Bazel build will rebuild with Xcode ${XCODE_BUILD_VERSION}"
-1
View File
@@ -1 +0,0 @@
7.7.1
-2
View File
@@ -1,2 +0,0 @@
# Bazel symlinks
bazel-*
-28
View File
@@ -1,28 +0,0 @@
module(name = "sparkle_workspace")
# Minimal dependencies for building SparklePlugin
# This workspace is isolated from the main workspace to avoid
# rules_swift version conflicts between grpc and rules_apple
bazel_dep(name = "apple_support", version = "1.21.1", repo_name = "build_bazel_apple_support")
bazel_dep(name = "rules_apple", version = "4.3.3", repo_name = "build_bazel_rules_apple")
# Register Apple CC toolchain for Objective-C compilation
apple_cc_configure = use_extension(
"@build_bazel_apple_support//crosstool:setup.bzl",
"apple_cc_configure_extension",
)
use_repo(apple_cc_configure, "local_config_apple_cc")
# Sparkle framework for macOS auto-updates
http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
SPARKLE_VERSION = "2.6.4"
http_archive(
name = "sparkle",
build_file = "//:external/BUILD.sparkle",
sha256 = "50612a06038abc931f16011d7903b8326a362c1074dabccb718404ce8e585f0b",
strip_prefix = "",
url = "https://github.com/sparkle-project/Sparkle/releases/download/%s/Sparkle-%s.tar.xz" % (SPARKLE_VERSION, SPARKLE_VERSION),
)
-451
View File
@@ -1,451 +0,0 @@
{
"lockFileVersion": 13,
"registryFileHashes": {
"https://bcr.bazel.build/bazel_registry.json": "8a28e4aff06ee60aed2a8c281907fb8bcbf3b753c91fb5a5c57da3215d5b3497",
"https://bcr.bazel.build/modules/abseil-cpp/20210324.2/MODULE.bazel": "7cd0312e064fde87c8d1cd79ba06c876bd23630c83466e9500321be55c96ace2",
"https://bcr.bazel.build/modules/abseil-cpp/20211102.0/MODULE.bazel": "70390338f7a5106231d20620712f7cccb659cd0e9d073d1991c038eb9fc57589",
"https://bcr.bazel.build/modules/abseil-cpp/20230125.1/MODULE.bazel": "89047429cb0207707b2dface14ba7f8df85273d484c2572755be4bab7ce9c3a0",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.0.bcr.1/MODULE.bazel": "1c8cec495288dccd14fdae6e3f95f772c1c91857047a098fad772034264cc8cb",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.0/MODULE.bazel": "d253ae36a8bd9ee3c5955384096ccb6baf16a1b1e93e858370da0a3b94f77c16",
"https://bcr.bazel.build/modules/abseil-cpp/20230802.1/MODULE.bazel": "fa92e2eb41a04df73cdabeec37107316f7e5272650f81d6cc096418fe647b915",
"https://bcr.bazel.build/modules/abseil-cpp/20240116.1/MODULE.bazel": "37bcdb4440fbb61df6a1c296ae01b327f19e9bb521f9b8e26ec854b6f97309ed",
"https://bcr.bazel.build/modules/abseil-cpp/20240116.1/source.json": "9be551b8d4e3ef76875c0d744b5d6a504a27e3ae67bc6b28f46415fd2d2957da",
"https://bcr.bazel.build/modules/apple_support/1.11.1/MODULE.bazel": "1843d7cd8a58369a444fc6000e7304425fba600ff641592161d9f15b179fb896",
"https://bcr.bazel.build/modules/apple_support/1.15.1/MODULE.bazel": "a0556fefca0b1bb2de8567b8827518f94db6a6e7e7d632b4c48dc5f865bc7c85",
"https://bcr.bazel.build/modules/apple_support/1.21.1/MODULE.bazel": "5809fa3efab15d1f3c3c635af6974044bac8a4919c62238cce06acee8a8c11f1",
"https://bcr.bazel.build/modules/apple_support/1.23.1/MODULE.bazel": "53763fed456a968cf919b3240427cf3a9d5481ec5466abc9d5dc51bc70087442",
"https://bcr.bazel.build/modules/apple_support/1.23.1/source.json": "d888b44312eb0ad2c21a91d026753f330caa48a25c9b2102fae75eb2b0dcfdd2",
"https://bcr.bazel.build/modules/bazel_features/1.1.1/MODULE.bazel": "27b8c79ef57efe08efccbd9dd6ef70d61b4798320b8d3c134fd571f78963dbcd",
"https://bcr.bazel.build/modules/bazel_features/1.11.0/MODULE.bazel": "f9382337dd5a474c3b7d334c2f83e50b6eaedc284253334cf823044a26de03e8",
"https://bcr.bazel.build/modules/bazel_features/1.15.0/MODULE.bazel": "d38ff6e517149dc509406aca0db3ad1efdd890a85e049585b7234d04238e2a4d",
"https://bcr.bazel.build/modules/bazel_features/1.17.0/MODULE.bazel": "039de32d21b816b47bd42c778e0454217e9c9caac4a3cf8e15c7231ee3ddee4d",
"https://bcr.bazel.build/modules/bazel_features/1.18.0/MODULE.bazel": "1be0ae2557ab3a72a57aeb31b29be347bcdc5d2b1eb1e70f39e3851a7e97041a",
"https://bcr.bazel.build/modules/bazel_features/1.19.0/MODULE.bazel": "59adcdf28230d220f0067b1f435b8537dd033bfff8db21335ef9217919c7fb58",
"https://bcr.bazel.build/modules/bazel_features/1.21.0/MODULE.bazel": "675642261665d8eea09989aa3b8afb5c37627f1be178382c320d1b46afba5e3b",
"https://bcr.bazel.build/modules/bazel_features/1.27.0/MODULE.bazel": "621eeee06c4458a9121d1f104efb80f39d34deff4984e778359c60eaf1a8cb65",
"https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d",
"https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9",
"https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87",
"https://bcr.bazel.build/modules/bazel_features/1.30.0/source.json": "b07e17f067fe4f69f90b03b36ef1e08fe0d1f3cac254c1241a1818773e3423bc",
"https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7",
"https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8",
"https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e",
"https://bcr.bazel.build/modules/bazel_skylib/1.2.0/MODULE.bazel": "44fe84260e454ed94ad326352a698422dbe372b21a1ac9f3eab76eb531223686",
"https://bcr.bazel.build/modules/bazel_skylib/1.2.1/MODULE.bazel": "f35baf9da0efe45fa3da1696ae906eea3d615ad41e2e3def4aeb4e8bc0ef9a7a",
"https://bcr.bazel.build/modules/bazel_skylib/1.3.0/MODULE.bazel": "20228b92868bf5cfc41bda7afc8a8ba2a543201851de39d990ec957b513579c5",
"https://bcr.bazel.build/modules/bazel_skylib/1.4.1/MODULE.bazel": "a0dcb779424be33100dcae821e9e27e4f2901d9dfd5333efe5ac6a8d7ab75e1d",
"https://bcr.bazel.build/modules/bazel_skylib/1.4.2/MODULE.bazel": "3bd40978e7a1fac911d5989e6b09d8f64921865a45822d8b09e815eaa726a651",
"https://bcr.bazel.build/modules/bazel_skylib/1.5.0/MODULE.bazel": "32880f5e2945ce6a03d1fbd588e9198c0a959bb42297b2cfaf1685b7bc32e138",
"https://bcr.bazel.build/modules/bazel_skylib/1.6.1/MODULE.bazel": "8fdee2dbaace6c252131c00e1de4b165dc65af02ea278476187765e1a617b917",
"https://bcr.bazel.build/modules/bazel_skylib/1.7.0/MODULE.bazel": "0db596f4563de7938de764cc8deeabec291f55e8ec15299718b93c4423e9796d",
"https://bcr.bazel.build/modules/bazel_skylib/1.7.1/MODULE.bazel": "3120d80c5861aa616222ec015332e5f8d3171e062e3e804a2a0253e1be26e59b",
"https://bcr.bazel.build/modules/bazel_skylib/1.7.1/source.json": "f121b43eeefc7c29efbd51b83d08631e2347297c95aac9764a701f2a6a2bb953",
"https://bcr.bazel.build/modules/buildozer/7.1.2/MODULE.bazel": "2e8dd40ede9c454042645fd8d8d0cd1527966aa5c919de86661e62953cd73d84",
"https://bcr.bazel.build/modules/buildozer/7.1.2/source.json": "c9028a501d2db85793a6996205c8de120944f50a0d570438fcae0457a5f9d1f8",
"https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb",
"https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4",
"https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6",
"https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/source.json": "41e9e129f80d8c8bf103a7acc337b76e54fad1214ac0a7084bf24f4cd924b8b4",
"https://bcr.bazel.build/modules/googletest/1.14.0/MODULE.bazel": "cfbcbf3e6eac06ef9d85900f64424708cc08687d1b527f0ef65aa7517af8118f",
"https://bcr.bazel.build/modules/jsoncpp/1.9.5/MODULE.bazel": "31271aedc59e815656f5736f282bb7509a97c7ecb43e927ac1a37966e0578075",
"https://bcr.bazel.build/modules/jsoncpp/1.9.5/source.json": "4108ee5085dd2885a341c7fab149429db457b3169b86eb081fa245eadf69169d",
"https://bcr.bazel.build/modules/libpfm/4.11.0/MODULE.bazel": "45061ff025b301940f1e30d2c16bea596c25b176c8b6b3087e92615adbd52902",
"https://bcr.bazel.build/modules/nlohmann_json/3.6.1/MODULE.bazel": "6f7b417dcc794d9add9e556673ad25cb3ba835224290f4f848f8e2db1e1fca74",
"https://bcr.bazel.build/modules/nlohmann_json/3.6.1/source.json": "f448c6e8963fdfa7eb831457df83ad63d3d6355018f6574fb017e8169deb43a9",
"https://bcr.bazel.build/modules/platforms/0.0.10/MODULE.bazel": "8cb8efaf200bdeb2150d93e162c40f388529a25852b332cec879373771e48ed5",
"https://bcr.bazel.build/modules/platforms/0.0.11/MODULE.bazel": "0daefc49732e227caa8bfa834d65dc52e8cc18a2faf80df25e8caea151a9413f",
"https://bcr.bazel.build/modules/platforms/0.0.11/source.json": "f7e188b79ebedebfe75e9e1d098b8845226c7992b307e28e1496f23112e8fc29",
"https://bcr.bazel.build/modules/platforms/0.0.4/MODULE.bazel": "9b328e31ee156f53f3c416a64f8491f7eb731742655a47c9eec4703a71644aee",
"https://bcr.bazel.build/modules/platforms/0.0.5/MODULE.bazel": "5733b54ea419d5eaf7997054bb55f6a1d0b5ff8aedf0176fef9eea44f3acda37",
"https://bcr.bazel.build/modules/platforms/0.0.6/MODULE.bazel": "ad6eeef431dc52aefd2d77ed20a4b353f8ebf0f4ecdd26a807d2da5aa8cd0615",
"https://bcr.bazel.build/modules/platforms/0.0.7/MODULE.bazel": "72fd4a0ede9ee5c021f6a8dd92b503e089f46c227ba2813ff183b71616034814",
"https://bcr.bazel.build/modules/platforms/0.0.8/MODULE.bazel": "9f142c03e348f6d263719f5074b21ef3adf0b139ee4c5133e2aa35664da9eb2d",
"https://bcr.bazel.build/modules/platforms/0.0.9/MODULE.bazel": "4a87a60c927b56ddd67db50c89acaa62f4ce2a1d2149ccb63ffd871d5ce29ebc",
"https://bcr.bazel.build/modules/protobuf/21.7/MODULE.bazel": "a5a29bb89544f9b97edce05642fac225a808b5b7be74038ea3640fae2f8e66a7",
"https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c",
"https://bcr.bazel.build/modules/protobuf/29.0-rc2/MODULE.bazel": "6241d35983510143049943fc0d57937937122baf1b287862f9dc8590fc4c37df",
"https://bcr.bazel.build/modules/protobuf/29.0-rc3/MODULE.bazel": "33c2dfa286578573afc55a7acaea3cada4122b9631007c594bf0729f41c8de92",
"https://bcr.bazel.build/modules/protobuf/29.0-rc3/source.json": "c16a6488fb279ef578da7098e605082d72ed85fc8d843eaae81e7d27d0f4625d",
"https://bcr.bazel.build/modules/protobuf/3.19.0/MODULE.bazel": "6b5fbb433f760a99a22b18b6850ed5784ef0e9928a72668b66e4d7ccd47db9b0",
"https://bcr.bazel.build/modules/protobuf/3.19.6/MODULE.bazel": "9233edc5e1f2ee276a60de3eaa47ac4132302ef9643238f23128fea53ea12858",
"https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e",
"https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/source.json": "be4789e951dd5301282729fe3d4938995dc4c1a81c2ff150afc9f1b0504c6022",
"https://bcr.bazel.build/modules/re2/2023-09-01/MODULE.bazel": "cb3d511531b16cfc78a225a9e2136007a48cf8a677e4264baeab57fe78a80206",
"https://bcr.bazel.build/modules/re2/2023-09-01/source.json": "e044ce89c2883cd957a2969a43e79f7752f9656f6b20050b62f90ede21ec6eb4",
"https://bcr.bazel.build/modules/rules_android/0.1.1/MODULE.bazel": "48809ab0091b07ad0182defb787c4c5328bd3a278938415c00a7b69b50c4d3a8",
"https://bcr.bazel.build/modules/rules_android/0.1.1/source.json": "e6986b41626ee10bdc864937ffb6d6bf275bb5b9c65120e6137d56e6331f089e",
"https://bcr.bazel.build/modules/rules_apple/4.3.3/MODULE.bazel": "c5c2c4adeeac5f3f2f9b7f16abfa8be7ffefa596171d0d92bed4cae9ade0a498",
"https://bcr.bazel.build/modules/rules_apple/4.3.3/source.json": "3cb1d69c8243ffcc42ecbf84ae8b9cccd7b1e2f091b0aee5a3e9c9a45267f312",
"https://bcr.bazel.build/modules/rules_cc/0.0.1/MODULE.bazel": "cb2aa0747f84c6c3a78dad4e2049c154f08ab9d166b1273835a8174940365647",
"https://bcr.bazel.build/modules/rules_cc/0.0.10/MODULE.bazel": "ec1705118f7eaedd6e118508d3d26deba2a4e76476ada7e0e3965211be012002",
"https://bcr.bazel.build/modules/rules_cc/0.0.11/MODULE.bazel": "9f249c5624a4788067b96b8b896be10c7e8b4375dc46f6d8e1e51100113e0992",
"https://bcr.bazel.build/modules/rules_cc/0.0.13/MODULE.bazel": "0e8529ed7b323dad0775ff924d2ae5af7640b23553dfcd4d34344c7e7a867191",
"https://bcr.bazel.build/modules/rules_cc/0.0.15/MODULE.bazel": "6704c35f7b4a72502ee81f61bf88706b54f06b3cbe5558ac17e2e14666cd5dcc",
"https://bcr.bazel.build/modules/rules_cc/0.0.16/MODULE.bazel": "7661303b8fc1b4d7f532e54e9d6565771fea666fbdf839e0a86affcd02defe87",
"https://bcr.bazel.build/modules/rules_cc/0.0.2/MODULE.bazel": "6915987c90970493ab97393024c156ea8fb9f3bea953b2f3ec05c34f19b5695c",
"https://bcr.bazel.build/modules/rules_cc/0.0.6/MODULE.bazel": "abf360251023dfe3efcef65ab9d56beefa8394d4176dd29529750e1c57eaa33f",
"https://bcr.bazel.build/modules/rules_cc/0.0.8/MODULE.bazel": "964c85c82cfeb6f3855e6a07054fdb159aced38e99a5eecf7bce9d53990afa3e",
"https://bcr.bazel.build/modules/rules_cc/0.0.9/MODULE.bazel": "836e76439f354b89afe6a911a7adf59a6b2518fafb174483ad78a2a2fde7b1c5",
"https://bcr.bazel.build/modules/rules_cc/0.1.2/MODULE.bazel": "557ddc3a96858ec0d465a87c0a931054d7dcfd6583af2c7ed3baf494407fd8d0",
"https://bcr.bazel.build/modules/rules_cc/0.1.2/source.json": "53fcb09b5816c83ca60d9d7493faf3bfaf410dfc2f15deb52d6ddd146b8d43f0",
"https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6",
"https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/MODULE.bazel": "40c97d1144356f52905566c55811f13b299453a14ac7769dfba2ac38192337a8",
"https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/source.json": "c8b1e2c717646f1702290959a3302a178fb639d987ab61d548105019f11e527e",
"https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74",
"https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86",
"https://bcr.bazel.build/modules/rules_java/6.5.2/MODULE.bazel": "1d440d262d0e08453fa0c4d8f699ba81609ed0e9a9a0f02cd10b3e7942e61e31",
"https://bcr.bazel.build/modules/rules_java/7.10.0/MODULE.bazel": "530c3beb3067e870561739f1144329a21c851ff771cd752a49e06e3dc9c2e71a",
"https://bcr.bazel.build/modules/rules_java/7.12.2/MODULE.bazel": "579c505165ee757a4280ef83cda0150eea193eed3bef50b1004ba88b99da6de6",
"https://bcr.bazel.build/modules/rules_java/7.2.0/MODULE.bazel": "06c0334c9be61e6cef2c8c84a7800cef502063269a5af25ceb100b192453d4ab",
"https://bcr.bazel.build/modules/rules_java/7.6.1/MODULE.bazel": "2f14b7e8a1aa2f67ae92bc69d1ec0fa8d9f827c4e17ff5e5f02e91caa3b2d0fe",
"https://bcr.bazel.build/modules/rules_java/7.6.5/MODULE.bazel": "481164be5e02e4cab6e77a36927683263be56b7e36fef918b458d7a8a1ebadb1",
"https://bcr.bazel.build/modules/rules_java/8.3.2/MODULE.bazel": "7336d5511ad5af0b8615fdc7477535a2e4e723a357b6713af439fe8cf0195017",
"https://bcr.bazel.build/modules/rules_java/8.5.1/MODULE.bazel": "d8a9e38cc5228881f7055a6079f6f7821a073df3744d441978e7a43e20226939",
"https://bcr.bazel.build/modules/rules_java/8.5.1/source.json": "db1a77d81b059e0f84985db67a22f3f579a529a86b7997605be3d214a0abe38e",
"https://bcr.bazel.build/modules/rules_jvm_external/4.4.2/MODULE.bazel": "a56b85e418c83eb1839819f0b515c431010160383306d13ec21959ac412d2fe7",
"https://bcr.bazel.build/modules/rules_jvm_external/5.1/MODULE.bazel": "33f6f999e03183f7d088c9be518a63467dfd0be94a11d0055fe2d210f89aa909",
"https://bcr.bazel.build/modules/rules_jvm_external/5.2/MODULE.bazel": "d9351ba35217ad0de03816ef3ed63f89d411349353077348a45348b096615036",
"https://bcr.bazel.build/modules/rules_jvm_external/6.3/MODULE.bazel": "c998e060b85f71e00de5ec552019347c8bca255062c990ac02d051bb80a38df0",
"https://bcr.bazel.build/modules/rules_jvm_external/6.3/source.json": "6f5f5a5a4419ae4e37c35a5bb0a6ae657ed40b7abc5a5189111b47fcebe43197",
"https://bcr.bazel.build/modules/rules_kotlin/1.9.6/MODULE.bazel": "d269a01a18ee74d0335450b10f62c9ed81f2321d7958a2934e44272fe82dcef3",
"https://bcr.bazel.build/modules/rules_kotlin/1.9.6/source.json": "2faa4794364282db7c06600b7e5e34867a564ae91bda7cae7c29c64e9466b7d5",
"https://bcr.bazel.build/modules/rules_license/0.0.3/MODULE.bazel": "627e9ab0247f7d1e05736b59dbb1b6871373de5ad31c3011880b4133cafd4bd0",
"https://bcr.bazel.build/modules/rules_license/0.0.7/MODULE.bazel": "088fbeb0b6a419005b89cf93fe62d9517c0a2b8bb56af3244af65ecfe37e7d5d",
"https://bcr.bazel.build/modules/rules_license/1.0.0/MODULE.bazel": "a7fda60eefdf3d8c827262ba499957e4df06f659330bbe6cdbdb975b768bb65c",
"https://bcr.bazel.build/modules/rules_license/1.0.0/source.json": "a52c89e54cc311196e478f8382df91c15f7a2bfdf4c6cd0e2675cc2ff0b56efb",
"https://bcr.bazel.build/modules/rules_pkg/0.7.0/MODULE.bazel": "df99f03fc7934a4737122518bb87e667e62d780b610910f0447665a7e2be62dc",
"https://bcr.bazel.build/modules/rules_pkg/1.0.1/MODULE.bazel": "5b1df97dbc29623bccdf2b0dcd0f5cb08e2f2c9050aab1092fd39a41e82686ff",
"https://bcr.bazel.build/modules/rules_pkg/1.0.1/source.json": "bd82e5d7b9ce2d31e380dd9f50c111d678c3bdaca190cb76b0e1c71b05e1ba8a",
"https://bcr.bazel.build/modules/rules_proto/4.0.0/MODULE.bazel": "a7a7b6ce9bee418c1a760b3d84f83a299ad6952f9903c67f19e4edd964894e06",
"https://bcr.bazel.build/modules/rules_proto/5.3.0-21.7/MODULE.bazel": "e8dff86b0971688790ae75528fe1813f71809b5afd57facb44dad9e8eca631b7",
"https://bcr.bazel.build/modules/rules_proto/6.0.2/MODULE.bazel": "ce916b775a62b90b61888052a416ccdda405212b6aaeb39522f7dc53431a5e73",
"https://bcr.bazel.build/modules/rules_proto/6.0.2/source.json": "17a2e195f56cb28d6bbf763e49973d13890487c6945311ed141e196fb660426d",
"https://bcr.bazel.build/modules/rules_python/0.10.2/MODULE.bazel": "cc82bc96f2997baa545ab3ce73f196d040ffb8756fd2d66125a530031cd90e5f",
"https://bcr.bazel.build/modules/rules_python/0.22.1/MODULE.bazel": "26114f0c0b5e93018c0c066d6673f1a2c3737c7e90af95eff30cfee38d0bbac7",
"https://bcr.bazel.build/modules/rules_python/0.23.1/MODULE.bazel": "49ffccf0511cb8414de28321f5fcf2a31312b47c40cc21577144b7447f2bf300",
"https://bcr.bazel.build/modules/rules_python/0.25.0/MODULE.bazel": "72f1506841c920a1afec76975b35312410eea3aa7b63267436bfb1dd91d2d382",
"https://bcr.bazel.build/modules/rules_python/0.28.0/MODULE.bazel": "cba2573d870babc976664a912539b320cbaa7114cd3e8f053c720171cde331ed",
"https://bcr.bazel.build/modules/rules_python/0.31.0/MODULE.bazel": "93a43dc47ee570e6ec9f5779b2e64c1476a6ce921c48cc9a1678a91dd5f8fd58",
"https://bcr.bazel.build/modules/rules_python/0.4.0/MODULE.bazel": "9208ee05fd48bf09ac60ed269791cf17fb343db56c8226a720fbb1cdf467166c",
"https://bcr.bazel.build/modules/rules_python/1.3.0/MODULE.bazel": "8361d57eafb67c09b75bf4bbe6be360e1b8f4f18118ab48037f2bd50aa2ccb13",
"https://bcr.bazel.build/modules/rules_python/1.3.0/source.json": "25932f917cd279c7baefa6cb1d3fa8750a7a29de522024449b19af6eab51f4a0",
"https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c",
"https://bcr.bazel.build/modules/rules_shell/0.3.0/MODULE.bazel": "de4402cd12f4cc8fda2354fce179fdb068c0b9ca1ec2d2b17b3e21b24c1a937b",
"https://bcr.bazel.build/modules/rules_shell/0.3.0/source.json": "c55ed591aa5009401ddf80ded9762ac32c358d2517ee7820be981e2de9756cf3",
"https://bcr.bazel.build/modules/rules_swift/1.16.0/MODULE.bazel": "4a09f199545a60d09895e8281362b1ff3bb08bbde69c6fc87aff5b92fcc916ca",
"https://bcr.bazel.build/modules/rules_swift/2.4.0/MODULE.bazel": "1639617eb1ede28d774d967a738b4a68b0accb40650beadb57c21846beab5efd",
"https://bcr.bazel.build/modules/rules_swift/2.4.0/source.json": "a6577f57f9febbdc015a01f2a8f3487422032f134d6c61d18ed8e8ca3b9acc7c",
"https://bcr.bazel.build/modules/stardoc/0.5.1/MODULE.bazel": "1a05d92974d0c122f5ccf09291442580317cdd859f07a8655f1db9a60374f9f8",
"https://bcr.bazel.build/modules/stardoc/0.5.3/MODULE.bazel": "c7f6948dae6999bf0db32c1858ae345f112cacf98f174c7a8bb707e41b974f1c",
"https://bcr.bazel.build/modules/stardoc/0.7.0/MODULE.bazel": "05e3d6d30c099b6770e97da986c53bd31844d7f13d41412480ea265ac9e8079c",
"https://bcr.bazel.build/modules/stardoc/0.7.2/MODULE.bazel": "fc152419aa2ea0f51c29583fab1e8c99ddefd5b3778421845606ee628629e0e5",
"https://bcr.bazel.build/modules/stardoc/0.7.2/source.json": "58b029e5e901d6802967754adf0a9056747e8176f017cfe3607c0851f4d42216",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/MODULE.bazel": "5e463fbfba7b1701d957555ed45097d7f984211330106ccd1352c6e0af0dcf91",
"https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/source.json": "32bd87e5f4d7acc57c5b2ff7c325ae3061d5e242c0c4c214ae87e0f1c13e54cb",
"https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43",
"https://bcr.bazel.build/modules/zlib/1.2.11/MODULE.bazel": "07b389abc85fdbca459b69e2ec656ae5622873af3f845e1c9d80fe179f3effa0",
"https://bcr.bazel.build/modules/zlib/1.2.12/MODULE.bazel": "3b1a8834ada2a883674be8cbd36ede1b6ec481477ada359cd2d3ddc562340b27",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.3/MODULE.bazel": "af322bc08976524477c79d1e45e241b6efbeb918c497e8840b8ab116802dda79",
"https://bcr.bazel.build/modules/zlib/1.3.1.bcr.3/source.json": "2be409ac3c7601245958cd4fcdff4288be79ed23bd690b4b951f500d54ee6e7d",
"https://bcr.bazel.build/modules/zlib/1.3.1/MODULE.bazel": "751c9940dcfe869f5f7274e1295422a34623555916eb98c174c1e945594bf198"
},
"selectedYankedVersions": {},
"moduleExtensions": {
"@@rules_java~//java:rules_java_deps.bzl%compatibility_proxy": {
"general": {
"bzlTransitiveDigest": "C4xqrMy1wN4iuTN6Z2eCm94S5XingHhD6uwrIXvCxVI=",
"usagesDigest": "pwHZ+26iLgQdwvdZeA5wnAjKnNI3y6XO2VbhOTeo5h8=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"compatibility_proxy": {
"bzlFile": "@@rules_java~//java:rules_java_deps.bzl",
"ruleClassName": "_compatibility_proxy_repo_rule",
"attributes": {}
}
},
"recordedRepoMappingEntries": [
[
"rules_java~",
"bazel_tools",
"bazel_tools"
]
]
}
},
"@@rules_kotlin~//src/main/starlark/core/repositories:bzlmod_setup.bzl%rules_kotlin_extensions": {
"general": {
"bzlTransitiveDigest": "eecmTsmdIQveoA97hPtH3/Ej/kugbdCI24bhXIXaly8=",
"usagesDigest": "aJF6fLy82rR95Ff5CZPAqxNoFgOMLMN5ImfBS0nhnkg=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"com_github_jetbrains_kotlin_git": {
"bzlFile": "@@rules_kotlin~//src/main/starlark/core/repositories:compiler.bzl",
"ruleClassName": "kotlin_compiler_git_repository",
"attributes": {
"urls": [
"https://github.com/JetBrains/kotlin/releases/download/v1.9.23/kotlin-compiler-1.9.23.zip"
],
"sha256": "93137d3aab9afa9b27cb06a824c2324195c6b6f6179d8a8653f440f5bd58be88"
}
},
"com_github_jetbrains_kotlin": {
"bzlFile": "@@rules_kotlin~//src/main/starlark/core/repositories:compiler.bzl",
"ruleClassName": "kotlin_capabilities_repository",
"attributes": {
"git_repository_name": "com_github_jetbrains_kotlin_git",
"compiler_version": "1.9.23"
}
},
"com_github_google_ksp": {
"bzlFile": "@@rules_kotlin~//src/main/starlark/core/repositories:ksp.bzl",
"ruleClassName": "ksp_compiler_plugin_repository",
"attributes": {
"urls": [
"https://github.com/google/ksp/releases/download/1.9.23-1.0.20/artifacts.zip"
],
"sha256": "ee0618755913ef7fd6511288a232e8fad24838b9af6ea73972a76e81053c8c2d",
"strip_version": "1.9.23-1.0.20"
}
},
"com_github_pinterest_ktlint": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_file",
"attributes": {
"sha256": "01b2e0ef893383a50dbeb13970fe7fa3be36ca3e83259e01649945b09d736985",
"urls": [
"https://github.com/pinterest/ktlint/releases/download/1.3.0/ktlint"
],
"executable": true
}
},
"rules_android": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"sha256": "cd06d15dd8bb59926e4d65f9003bfc20f9da4b2519985c27e190cddc8b7a7806",
"strip_prefix": "rules_android-0.1.1",
"urls": [
"https://github.com/bazelbuild/rules_android/archive/v0.1.1.zip"
]
}
}
},
"recordedRepoMappingEntries": [
[
"rules_kotlin~",
"bazel_tools",
"bazel_tools"
]
]
}
},
"@@rules_python~//python/uv:uv.bzl%uv": {
"general": {
"bzlTransitiveDigest": "Xpqjnjzy6zZ90Es9Wa888ZLHhn7IsNGbph/e6qoxzw8=",
"usagesDigest": "qI5PVlIum/YAnGJg5oXGHzDkMFWt2aNSUZY4G8PBbic=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"uv": {
"bzlFile": "@@rules_python~//python/uv/private:uv_toolchains_repo.bzl",
"ruleClassName": "uv_toolchains_repo",
"attributes": {
"toolchain_type": "'@@rules_python~//python/uv:uv_toolchain_type'",
"toolchain_names": [
"none"
],
"toolchain_implementations": {
"none": "'@@rules_python~//python:none'"
},
"toolchain_compatible_with": {
"none": [
"@platforms//:incompatible"
]
},
"toolchain_target_settings": {}
}
}
},
"recordedRepoMappingEntries": [
[
"rules_python~",
"platforms",
"platforms"
]
]
}
},
"@@rules_swift~//swift:extensions.bzl%non_module_deps": {
"general": {
"bzlTransitiveDigest": "l+Zu+SMObRQy3DG2LEw0eGVPkYRnyVj+M1QyR5AAFmM=",
"usagesDigest": "l2vIL7SL4tJqHIVLWd78Y/ym+r0II64lmvoX8o+0Bb0=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
"generatedRepoSpecs": {
"com_github_apple_swift_protobuf": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-protobuf/archive/1.20.2.tar.gz"
],
"sha256": "3fb50bd4d293337f202d917b6ada22f9548a0a0aed9d9a4d791e6fbd8a246ebb",
"strip_prefix": "swift-protobuf-1.20.2/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_protobuf/BUILD.overlay"
}
},
"com_github_grpc_grpc_swift": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/grpc/grpc-swift/archive/1.16.0.tar.gz"
],
"sha256": "58b60431d0064969f9679411264b82e40a217ae6bd34e17096d92cc4e47556a5",
"strip_prefix": "grpc-swift-1.16.0/",
"build_file": "@@rules_swift~//third_party:com_github_grpc_grpc_swift/BUILD.overlay"
}
},
"com_github_apple_swift_docc_symbolkit": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-docc-symbolkit/archive/refs/tags/swift-5.10-RELEASE.tar.gz"
],
"sha256": "de1d4b6940468ddb53b89df7aa1a81323b9712775b0e33e8254fa0f6f7469a97",
"strip_prefix": "swift-docc-symbolkit-swift-5.10-RELEASE",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_docc_symbolkit/BUILD.overlay"
}
},
"com_github_apple_swift_nio": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio/archive/2.42.0.tar.gz"
],
"sha256": "e3304bc3fb53aea74a3e54bd005ede11f6dc357117d9b1db642d03aea87194a0",
"strip_prefix": "swift-nio-2.42.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_nio/BUILD.overlay"
}
},
"com_github_apple_swift_nio_http2": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-http2/archive/1.26.0.tar.gz"
],
"sha256": "f0edfc9d6a7be1d587e5b403f2d04264bdfae59aac1d74f7d974a9022c6d2b25",
"strip_prefix": "swift-nio-http2-1.26.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_nio_http2/BUILD.overlay"
}
},
"com_github_apple_swift_nio_transport_services": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-transport-services/archive/1.15.0.tar.gz"
],
"sha256": "f3498dafa633751a52b9b7f741f7ac30c42bcbeb3b9edca6d447e0da8e693262",
"strip_prefix": "swift-nio-transport-services-1.15.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_nio_transport_services/BUILD.overlay"
}
},
"com_github_apple_swift_nio_extras": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-extras/archive/1.4.0.tar.gz"
],
"sha256": "4684b52951d9d9937bb3e8ccd6b5daedd777021ef2519ea2f18c4c922843b52b",
"strip_prefix": "swift-nio-extras-1.4.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_nio_extras/BUILD.overlay"
}
},
"com_github_apple_swift_log": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-log/archive/1.4.4.tar.gz"
],
"sha256": "48fe66426c784c0c20031f15dc17faf9f4c9037c192bfac2f643f65cb2321ba0",
"strip_prefix": "swift-log-1.4.4/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_log/BUILD.overlay"
}
},
"com_github_apple_swift_nio_ssl": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-nio-ssl/archive/2.23.0.tar.gz"
],
"sha256": "4787c63f61dd04d99e498adc3d1a628193387e41efddf8de19b8db04544d016d",
"strip_prefix": "swift-nio-ssl-2.23.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_nio_ssl/BUILD.overlay"
}
},
"com_github_apple_swift_collections": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-collections/archive/1.0.4.tar.gz"
],
"sha256": "d9e4c8a91c60fb9c92a04caccbb10ded42f4cb47b26a212bc6b39cc390a4b096",
"strip_prefix": "swift-collections-1.0.4/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_collections/BUILD.overlay"
}
},
"com_github_apple_swift_atomics": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"urls": [
"https://github.com/apple/swift-atomics/archive/1.1.0.tar.gz"
],
"sha256": "1bee7f469f7e8dc49f11cfa4da07182fbc79eab000ec2c17bfdce468c5d276fb",
"strip_prefix": "swift-atomics-1.1.0/",
"build_file": "@@rules_swift~//third_party:com_github_apple_swift_atomics/BUILD.overlay"
}
},
"build_bazel_rules_swift_index_import": {
"bzlFile": "@@bazel_tools//tools/build_defs/repo:http.bzl",
"ruleClassName": "http_archive",
"attributes": {
"build_file": "@@rules_swift~//third_party:build_bazel_rules_swift_index_import/BUILD.overlay",
"canonical_id": "index-import-5.8",
"urls": [
"https://github.com/MobileNativeFoundation/index-import/releases/download/5.8.0.1/index-import.tar.gz"
],
"sha256": "28c1ffa39d99e74ed70623899b207b41f79214c498c603915aef55972a851a15"
}
},
"build_bazel_rules_swift_local_config": {
"bzlFile": "@@rules_swift~//swift/internal:swift_autoconfiguration.bzl",
"ruleClassName": "swift_autoconfiguration",
"attributes": {}
}
},
"recordedRepoMappingEntries": [
[
"rules_swift~",
"bazel_tools",
"bazel_tools"
]
]
}
}
}
}
-3
View File
@@ -1,3 +0,0 @@
# This file marks sparkle_workspace as a separate Bazel workspace.
# It prevents Bazel from looking up to the parent directory's workspace.
# The actual dependencies are defined in MODULE.bazel (bzlmod).
@@ -66,6 +66,14 @@ cc_library(
],
)
cc_library(
name = "shardok_latency_trace",
srcs = ["ShardokLatencyTrace.cpp"],
hdrs = ["ShardokLatencyTrace.hpp"],
copts = COPTS,
visibility = ["//visibility:public"],
)
cc_library(
name = "repeated_proto_utils",
srcs = [],
@@ -88,6 +88,11 @@ StdLibraryGenerator::StdLibraryGenerator() : RandomGenerator() {
engine.seed(static_cast<std::mt19937_64::result_type>(std::time(nullptr)));
}
StdLibraryGenerator::StdLibraryGenerator(const std::mt19937_64::result_type seed)
: RandomGenerator() {
engine.seed(seed);
}
auto StdLibraryGenerator::IntBetween(const int min, const int max) -> int {
std::uniform_int_distribution<int> unifInt(min, max - 1);
return unifInt(engine);
@@ -51,6 +51,7 @@ private:
public:
StdLibraryGenerator();
explicit StdLibraryGenerator(std::mt19937_64::result_type seed);
auto IntBetween(int min, int max) -> int override; // inclusive, exclusive (min<=return<max)
};
@@ -0,0 +1,101 @@
#include "ShardokLatencyTrace.hpp"
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <sstream>
namespace net::eagle0::common {
namespace {
auto ReadEnvEnabled() -> bool {
const char* value = std::getenv("EAGLE0_SHARDOK_LATENCY_TRACE");
if (value == nullptr) { return false; }
const std::string text(value);
return text == "1" || text == "true" || text == "TRUE" || text == "yes" || text == "YES";
}
auto TraceEnabled() -> bool {
static const bool enabled = ReadEnvEnabled();
return enabled;
}
auto ReadGameFilter() -> std::string {
const char* value = std::getenv("EAGLE0_SHARDOK_LATENCY_GAME_ID");
return value == nullptr ? "" : std::string(value);
}
auto GameFilter() -> const std::string& {
static const std::string filter = ReadGameFilter();
return filter;
}
auto JsonEscape(std::string_view value) -> std::string {
std::ostringstream out;
for (const char c : value) {
switch (c) {
case '"': out << "\\\""; break;
case '\\': out << "\\\\"; break;
case '\n': out << "\\n"; break;
case '\r': out << "\\r"; break;
case '\t': out << "\\t"; break;
default: out << c; break;
}
}
return out.str();
}
auto LogMutex() -> std::mutex& {
static auto mutex = new std::mutex();
return *mutex;
}
} // namespace
auto ShardokLatencyTraceEnabledForGame(std::string_view gameId) -> bool {
if (!TraceEnabled()) { return false; }
const std::string& filter = GameFilter();
return filter.empty() || filter == gameId;
}
void EmitShardokLatencyTrace(
std::string_view event,
std::string_view gameId,
const ShardokLatencyFields& fields,
std::chrono::steady_clock::duration duration) {
if (!ShardokLatencyTraceEnabledForGame(gameId)) { return; }
const auto durationMs =
std::chrono::duration_cast<std::chrono::microseconds>(duration).count() / 1000.0;
std::ostringstream out;
out << "{\"event\":\"shardok_latency\","
<< "\"component\":\"shardok\","
<< "\"span\":\"" << JsonEscape(event) << "\","
<< "\"game_id\":\"" << JsonEscape(gameId) << "\","
<< "\"duration_ms\":" << durationMs;
for (const auto& [key, value] : fields) {
out << ",\"" << JsonEscape(key) << "\":\"" << JsonEscape(value) << "\"";
}
out << "}";
std::scoped_lock lock(LogMutex());
std::cerr << out.str() << std::endl;
}
ScopedShardokLatencyTrace::ScopedShardokLatencyTrace(
std::string event,
std::string gameId,
ShardokLatencyFields fields)
: event_(std::move(event)),
gameId_(std::move(gameId)),
fields_(std::move(fields)) {
if (ShardokLatencyTraceEnabledForGame(gameId_)) { start_ = std::chrono::steady_clock::now(); }
}
ScopedShardokLatencyTrace::~ScopedShardokLatencyTrace() {
if (!start_.has_value()) { return; }
EmitShardokLatencyTrace(event_, gameId_, fields_, std::chrono::steady_clock::now() - *start_);
}
} // namespace net::eagle0::common
@@ -0,0 +1,42 @@
#pragma once
#include <chrono>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace net::eagle0::common {
using ShardokLatencyFields = std::vector<std::pair<std::string, std::string>>;
auto ShardokLatencyTraceEnabledForGame(std::string_view gameId) -> bool;
void EmitShardokLatencyTrace(
std::string_view event,
std::string_view gameId,
const ShardokLatencyFields& fields,
std::chrono::steady_clock::duration duration);
class ScopedShardokLatencyTrace {
public:
ScopedShardokLatencyTrace(
std::string event,
std::string gameId,
ShardokLatencyFields fields = {});
~ScopedShardokLatencyTrace();
ScopedShardokLatencyTrace(const ScopedShardokLatencyTrace&) = delete;
auto operator=(const ScopedShardokLatencyTrace&) -> ScopedShardokLatencyTrace& = delete;
ScopedShardokLatencyTrace(ScopedShardokLatencyTrace&&) = delete;
auto operator=(ScopedShardokLatencyTrace&&) -> ScopedShardokLatencyTrace& = delete;
private:
std::string event_;
std::string gameId_;
ShardokLatencyFields fields_;
std::optional<std::chrono::steady_clock::time_point> start_;
};
} // namespace net::eagle0::common
@@ -13,6 +13,7 @@
#include <cstring>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
@@ -147,6 +148,9 @@ public:
static auto FromPath(const string& path) -> byte_vector {
std::ifstream inputFileStream(path, std::ios::binary | std::ios::ate);
if (!inputFileStream.is_open()) {
throw std::runtime_error("Failed to open file: " + path);
}
const std::streamsize size = inputFileStream.tellg();
inputFileStream.seekg(0, std::ios::beg);
byte_vector serializedGame((size_t(size)));
@@ -21,7 +21,14 @@ namespace shardok::mcts {
AbstractMCTSAI::AbstractMCTSAI(MCTSPlayerId playerId, MCTSConfig config)
: playerId_(playerId),
config_(config) {}
config_(config),
randomEngine_(config.randomSeed == 0 ? std::random_device{}() : config.randomSeed) {}
void AbstractMCTSAI::SetConfig(const MCTSConfig& newConfig) {
config_ = newConfig;
std::lock_guard lock(randomEngineMutex_);
randomEngine_.seed(newConfig.randomSeed == 0 ? std::random_device{}() : newConfig.randomSeed);
}
auto AbstractMCTSAI::Search(
const MCTSGameEngine& engine,
@@ -350,22 +357,19 @@ auto AbstractMCTSAI::MCTSExpansion(MCTSNode* node, const MCTSGameEngine& engine)
// fair UCB comparison with non-chance actions like END_TURN
{
double expectedImmediate = 0.0;
double totalProbability = 0.0;
for (size_t i = 0; i < node->children.size(); i++) {
for (size_t i = 0; i < node->outcomeProbabilities.size(); i++) {
const double prob = node->outcomeProbabilities[i];
const double childImmediate = node->children[i]->immediateScore;
const double childImmediate = i < node->children.size()
? node->children[i]->immediateScore
: node->unvisitedOutcomeScore;
expectedImmediate += prob * childImmediate;
totalProbability += prob;
}
// Normalize by total probability of expanded outcomes
if (totalProbability > 0.0) {
node->immediateScore = expectedImmediate / totalProbability;
// CRITICAL: Always update lookaheadScore to the expected value.
// Without this, chance nodes keep their initial lookaheadScore from the parent
// state (before the action), while regular actions use the child state (after).
// This gives chance nodes an unfair initial UCB advantage.
node->lookaheadScore = node->immediateScore;
}
node->immediateScore = expectedImmediate;
// CRITICAL: Always update lookaheadScore to the expected value.
// Without this, chance nodes keep their initial lookaheadScore from the parent
// state (before the action), while regular actions use the child state (after).
// This gives chance nodes an unfair initial UCB advantage.
node->lookaheadScore = node->immediateScore;
}
return node->children.back().get();
@@ -396,8 +400,14 @@ auto AbstractMCTSAI::MCTSExpansion(MCTSNode* node, const MCTSGameEngine& engine)
const auto& action = nodeActions[actionIndex];
const double actionWeight =
actionIndex < actionWeights.size() ? actionWeights[actionIndex] : 1.0;
double totalActionWeight = 0.0;
for (const double weight : actionWeights) { totalActionWeight += std::max(0.0, weight); }
const double rawActionWeight =
actionIndex < actionWeights.size() ? std::max(0.0, actionWeights[actionIndex]) : 1.0;
const double actionWeight = totalActionWeight > 0.0
? rawActionWeight / totalActionWeight
: 1.0 / static_cast<double>(nodeActions.size());
// Check if this action requires a chance node
if (action->requiresChanceNode()) {
@@ -417,15 +427,16 @@ auto AbstractMCTSAI::MCTSExpansion(MCTSNode* node, const MCTSGameEngine& engine)
// Get outcome information from engine
const auto outcomeInfo = engine.getBinaryOutcomeInfo(*node->gameState, *action);
// Set up outcome metadata (2 outcomes for binary actions)
// Set up outcome metadata.
chanceNode->outcomeProbabilities = outcomeInfo.getProbabilities();
chanceNode->outcomeRolls = outcomeInfo.getRepresentativeRolls();
chanceNode->totalActions = 2; // Binary: success and failure
chanceNode->totalActions = chanceNode->outcomeProbabilities.size();
// Chance node immediate score will be computed as expected value during backpropagation
// For now, initialize to parent's score as a reasonable default
chanceNode->immediateScore = engine.evaluateState(*node->gameState, playerId_);
chanceNode->lookaheadScore = chanceNode->immediateScore;
chanceNode->unvisitedOutcomeScore = chanceNode->immediateScore;
// Set parent and add to children
chanceNode->parent = node;
@@ -602,29 +613,20 @@ auto AbstractMCTSAI::MCTSBackpropagation(
// Chance nodes: compute expected value (weighted average of outcomes)
// lookaheadScore = sum(probability[i] * childValue[i])
double expectedValue = 0.0;
double totalProbability = 0.0;
int visitedChildCount = 0;
for (size_t i = 0; i < node->children.size(); i++) {
const auto& child = node->children[i];
if (child->visitCount == 0) continue; // Unvisited outcomes don't contribute
bool hasVisitedChild = false;
for (size_t i = 0; i < node->outcomeProbabilities.size(); i++) {
const double probability = node->outcomeProbabilities[i];
const double childValue = child->lookaheadScore;
double childValue = node->unvisitedOutcomeScore;
if (i < node->children.size() && node->children[i]->visitCount > 0) {
childValue = node->children[i]->lookaheadScore;
hasVisitedChild = true;
}
expectedValue += probability * childValue;
totalProbability += probability;
visitedChildCount++;
}
// Use expected value if we have visited outcomes, else use average
if (visitedChildCount > 0) {
// CRITICAL: Normalize by total probability to get correct expected value
// when not all outcomes have been visited yet
if (totalProbability > 0.0 && totalProbability < 1.0) {
// Normalize to account for unvisited outcomes
// This gives the correct expected value among visited outcomes
expectedValue /= totalProbability;
}
if (hasVisitedChild) {
node->lookaheadScore = expectedValue;
} else {
// No outcomes visited yet, fall back to average
@@ -705,23 +707,21 @@ auto AbstractMCTSAI::SelectSimulationAction(
"MCTS tree building or game state");
}
thread_local std::mt19937 gen(std::random_device{}());
switch (config_.simulationPolicy) {
case MCTSSimulationPolicy::RANDOM: {
std::uniform_int_distribution<size_t> dis(0, actions.size() - 1);
return dis(gen);
return SampleDistribution(dis);
}
case MCTSSimulationPolicy::FILTERED_RANDOM: {
if (const auto filteredIndices = engine.filterActions(actions, state);
!filteredIndices.empty()) {
std::uniform_int_distribution<size_t> dis(0, filteredIndices.size() - 1);
return filteredIndices[dis(gen)];
return filteredIndices[SampleDistribution(dis)];
}
// Fall back to random
std::uniform_int_distribution<size_t> dis(0, actions.size() - 1);
return dis(gen);
return SampleDistribution(dis);
}
case MCTSSimulationPolicy::BEST_IMMEDIATE: {
@@ -790,7 +790,7 @@ auto AbstractMCTSAI::SelectSimulationAction(
// Select based on weights
std::discrete_distribution<> dis(weights.begin(), weights.end());
return scores[dis(gen)].first;
return scores[SampleDistribution(dis)].first;
}
case MCTSSimulationPolicy::WEIGHTED_HEURISTIC: {
@@ -820,13 +820,13 @@ auto AbstractMCTSAI::SelectSimulationAction(
// Select based on heuristic weights using discrete_distribution
std::discrete_distribution<> dis(validWeights.begin(), validWeights.end());
return validIndices[dis(gen)];
return validIndices[SampleDistribution(dis)];
}
}
// Default to random
std::uniform_int_distribution<size_t> dis(0, actions.size() - 1);
return dis(gen);
return SampleDistribution(dis);
}
auto AbstractMCTSAI::FindNodeAtDepthWithHash(
@@ -7,6 +7,8 @@
#include <chrono>
#include <memory>
#include <mutex>
#include <random>
#include <unordered_map>
#include <vector>
@@ -41,7 +43,7 @@ public:
// Configuration
[[nodiscard]] auto GetConfig() const -> const MCTSConfig& { return config_; }
void SetConfig(const MCTSConfig& newConfig) { config_ = newConfig; }
void SetConfig(const MCTSConfig& newConfig);
[[nodiscard]] auto FindNodeAtDepthWithHash(
const MCTSNode* root,
@@ -51,6 +53,8 @@ public:
private:
MCTSPlayerId playerId_;
MCTSConfig config_;
mutable std::mt19937 randomEngine_;
mutable std::mutex randomEngineMutex_;
// Transposition table: maps state hash -> minimum depth at which state was reached
// Used to detect and penalize longer paths to the same game state
@@ -85,6 +89,13 @@ private:
const std::vector<std::unique_ptr<MCTSAction>>& actions,
bool isMaximizing) const -> size_t;
template<typename Distribution>
[[nodiscard]] auto SampleDistribution(Distribution& distribution) const ->
typename Distribution::result_type {
std::lock_guard lock(randomEngineMutex_);
return distribution(randomEngine_);
}
// Logging
static auto LogSearchResults(
const MCTSNode* rootNode,
@@ -103,4 +114,4 @@ private:
} // namespace mcts
} // namespace shardok
#endif // EAGLE0_ABSTRACT_MCTSAI_HPP
#endif // EAGLE0_ABSTRACT_MCTSAI_HPP
@@ -6,6 +6,7 @@ cc_library(
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__subpackages__",
"//src/main/cpp/net/eagle0/shardok/ai_testing_common:__pkg__",
"//src/test/cpp/net/eagle0/common/mcts:__subpackages__",
"//src/test/cpp/net/eagle0/shardok/ai/mcts:__subpackages__",
],
@@ -54,6 +54,7 @@ struct MCTSNode {
// Chance node specific fields (only used when nodeType == CHANCE)
std::vector<double> outcomeProbabilities; // Probability of each outcome
std::vector<double> outcomeRolls; // Representative roll for each outcome
double unvisitedOutcomeScore = 0.0; // Default value for outcomes not expanded yet
// Game context
MCTSPlayerId playerId;
@@ -274,4 +275,4 @@ struct MCTSNode {
} // namespace mcts
} // namespace shardok
#endif // EAGLE0_ABSTRACT_MCTSNODE_HPP
#endif // EAGLE0_ABSTRACT_MCTSNODE_HPP
@@ -51,10 +51,11 @@ struct MCTSConfig {
// When evaluating a leaf at playerFlips < maxSimulationFlips,
// simulate forward to this phase for fair comparison
// (default 0 = evaluate leaves as-is, backward compatible)
uint32_t randomSeed = 0; // 0 = seed nondeterministically
std::string debugDumpPath = ""; // If non-empty, dump MCTS tree to this file path
};
} // namespace mcts
} // namespace shardok
#endif // EAGLE0_MCTS_TYPES_HPP
#endif // EAGLE0_MCTS_TYPES_HPP
@@ -54,6 +54,12 @@ static auto IsDeterministic(const CommandType type) -> bool {
}
}
static auto RandomnessSampleForRepeat(const int repeatIteration, const int maxRepeatCount)
-> double {
if (maxRepeatCount <= 1) { return 0.5; }
return static_cast<double>(repeatIteration) / static_cast<double>(maxRepeatCount - 1);
}
// Helper function to sort commands by score
static auto CommandSorter(
const AICommandEvaluator::IndexAndScore& l,
@@ -85,15 +91,15 @@ auto AICommandEvaluator::PerformLookahead(
const ScoreValue currentUtility,
const AIStrategy& attackerStrategy,
const CoordsSet& allCastleCoords,
std::chrono::steady_clock::time_point deadline) const -> std::future<ScoreValue> {
std::chrono::steady_clock::time_point deadline) const -> std::future<EvaluationResult> {
// Check transposition table before expensive computation
auto cachedScore =
g_transpositionTable.probe(innerEngine->GetCurrentGameState(), remainingLookahead, pid);
if (cachedScore.has_value()) {
// Return cached result immediately
std::promise<ScoreValue> p;
p.set_value(*cachedScore);
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = *cachedScore, .completed = true});
return p.get_future();
}
const auto nextUtility = currentUtility;
@@ -105,8 +111,8 @@ auto AICommandEvaluator::PerformLookahead(
// table
g_transpositionTable.store(innerEngine->GetCurrentGameState(), 1, pid, nextUtility);
std::promise<ScoreValue> p;
p.set_value(nextUtility);
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = nextUtility, .completed = true});
return p.get_future();
}
@@ -131,16 +137,18 @@ auto AICommandEvaluator::PerformLookahead(
innerEngine,
pid,
nextUtility,
remainingLookahead]() mutable -> ScoreValue {
const auto [index, type, lookaheadScore, immediateScore] =
bestCommandFuture.get();
remainingLookahead]() mutable -> EvaluationResult {
const auto bestCommand = bestCommandFuture.get();
if (!bestCommand.completed) {
return EvaluationResult{.score = nextUtility, .completed = false};
}
ScoreValue resultScore;
if (auto& nextCommand =
innerEngine->GetAvailableCommandsForAIPlayer(pid)->at(index);
if (auto& nextCommand = innerEngine->GetAvailableCommandsForAIPlayer(pid)->at(
bestCommand.index);
nextCommand->GetCommandType() !=
net::eagle0::shardok::common::END_TURN_COMMAND) {
resultScore = immediateScore;
resultScore = bestCommand.immediateScore;
} else {
resultScore = nextUtility;
}
@@ -152,7 +160,7 @@ auto AICommandEvaluator::PerformLookahead(
pid,
resultScore);
return resultScore;
return EvaluationResult{.score = resultScore, .completed = true};
});
}
@@ -160,8 +168,8 @@ auto AICommandEvaluator::PerformLookahead(
g_transpositionTable
.store(innerEngine->GetCurrentGameState(), remainingLookahead, pid, nextUtility);
std::promise<ScoreValue> p;
p.set_value(nextUtility);
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = nextUtility, .completed = true});
return p.get_future();
}
@@ -180,10 +188,10 @@ auto AICommandEvaluator::EvaluateWithRandomness(
// Check if we've exceeded the deadline
if (std::chrono::steady_clock::now() > deadline) {
// Return with a default score and an empty future that resolves immediately
std::promise<ScoreValue> p;
p.set_value(0.0); // Default timeout score
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = 0.0, .completed = false});
returnValue.immediateScore = 0.0;
returnValue.completed = false;
returnValue.lookaheadScore = p.get_future();
return returnValue;
}
@@ -198,11 +206,12 @@ auto AICommandEvaluator::EvaluateWithRandomness(
allCastleCoords);
returnValue.immediateScore = innerUtility;
returnValue.completed = true;
if (remainingLookahead <= 0) {
std::promise<ScoreValue> p;
std::promise<EvaluationResult> p;
returnValue.lookaheadScore = p.get_future();
p.set_value(innerUtility);
p.set_value(EvaluationResult{.score = innerUtility, .completed = true});
} else {
auto lookaheadLambda = [this,
pid,
@@ -213,7 +222,7 @@ auto AICommandEvaluator::EvaluateWithRandomness(
attackerStrategy,
innerUtility,
&allCastleCoords,
deadline]() -> ScoreValue {
deadline]() -> EvaluationResult {
auto lookaheadFuture = PerformLookahead(
pid,
isDefender,
@@ -231,7 +240,7 @@ auto AICommandEvaluator::EvaluateWithRandomness(
auto launchPolicy = remainingLookahead == 1 ? std::launch::async : std::launch::deferred;
returnValue.lookaheadScore = std::async(launchPolicy, lookaheadLambda);
#else
std::promise<ScoreValue> p;
std::promise<EvaluationResult> p;
returnValue.lookaheadScore = p.get_future();
auto lambdaResult = lookaheadLambda();
p.set_value(lambdaResult);
@@ -316,7 +325,8 @@ auto AICommandEvaluator::FindBestCommand(
size_t index;
CommandType type;
ScoreValue immediateScore;
std::vector<std::future<ScoreValue>> lookaheadFutures;
bool immediateCompleted = true;
std::vector<std::future<EvaluationResult>> lookaheadFutures;
};
std::vector<CommandEvaluation> commandEvaluations(commandCount);
@@ -330,12 +340,12 @@ auto AICommandEvaluator::FindBestCommand(
commandEvaluations[index].type = guessedCommandType;
if (guessedCommandType == net::eagle0::shardok::common::END_TURN_COMMAND) {
std::promise<ScoreValue> p;
std::promise<EvaluationResult> p;
commandEvaluations[index].lookaheadFutures.push_back(p.get_future());
p.set_value(currentUtility);
p.set_value(EvaluationResult{.score = currentUtility, .completed = true});
commandEvaluations[index].immediateScore = currentUtility;
} else if (IsDeterministic(guessedCommandType)) {
auto [immediateScore, lookaheadScore] = EvaluateWithRandomness(
auto evaluation = EvaluateWithRandomness(
pid,
isDefender,
originalIndex,
@@ -347,14 +357,16 @@ auto AICommandEvaluator::FindBestCommand(
allCastleCoords,
deadline);
commandEvaluations[index].immediateScore = immediateScore;
commandEvaluations[index].lookaheadFutures.push_back(std::move(lookaheadScore));
commandEvaluations[index].immediateScore = evaluation.immediateScore;
commandEvaluations[index].immediateCompleted = evaluation.completed;
commandEvaluations[index].lookaheadFutures.push_back(
std::move(evaluation.lookaheadScore));
} else if (guessedDescriptor->HasOdds()) {
const auto successChancePercentile = guessedDescriptor->GetOddsPercentile();
const double successChance = static_cast<double>(successChancePercentile) / 100.0;
// Success attempt uses 1.0 - (successChance / 2) as the roll
auto [successImmediateScore, successLookaheadScore] = EvaluateWithRandomness(
auto successEvaluation = EvaluateWithRandomness(
pid,
isDefender,
originalIndex,
@@ -368,7 +380,7 @@ auto AICommandEvaluator::FindBestCommand(
deadline);
// Failure attempt uses the average of (1 - successChance) and 0 as the roll
auto [failureImmediateScore, failureLookaheadScore] = EvaluateWithRandomness(
auto failureEvaluation = EvaluateWithRandomness(
pid,
isDefender,
originalIndex,
@@ -381,24 +393,35 @@ auto AICommandEvaluator::FindBestCommand(
allCastleCoords,
deadline);
commandEvaluations[index].immediateScore =
std::lerp(failureImmediateScore, successImmediateScore, successChance);
commandEvaluations[index].immediateCompleted =
failureEvaluation.completed && successEvaluation.completed;
commandEvaluations[index].immediateScore = std::lerp(
failureEvaluation.immediateScore,
successEvaluation.immediateScore,
successChance);
auto successSF = successLookaheadScore.share();
auto failureSF = failureLookaheadScore.share();
auto successSF = successEvaluation.lookaheadScore.share();
auto failureSF = failureEvaluation.lookaheadScore.share();
commandEvaluations[index].lookaheadFutures.push_back(std::async(
std::launch::deferred,
[successSF, failureSF, successChance]() -> double {
return std::lerp(failureSF.get(), successSF.get(), successChance);
[successSF, failureSF, successChance]() -> EvaluationResult {
const auto failure = failureSF.get();
const auto success = successSF.get();
if (!failure.completed || !success.completed) {
return EvaluationResult{.score = 0.0, .completed = false};
}
return EvaluationResult{
.score = std::lerp(failure.score, success.score, successChance),
.completed = true};
}));
} else {
ScoreValue sum = 0.0;
for (int repeatIteration = 0; repeatIteration < maxRepeatCount; repeatIteration++) {
const int sampleCount = std::max(1, maxRepeatCount);
for (int repeatIteration = 0; repeatIteration < sampleCount; repeatIteration++) {
// In each iteration, use a double from [0, 1] as the random roll
auto sequence = std::vector{
static_cast<double>(repeatIteration) /
static_cast<double>(maxRepeatCount - 1)};
auto [immediateScore, lookaheadScore] = EvaluateWithRandomness(
auto sequence =
std::vector{RandomnessSampleForRepeat(repeatIteration, sampleCount)};
auto evaluation = EvaluateWithRandomness(
pid,
isDefender,
originalIndex,
@@ -410,10 +433,12 @@ auto AICommandEvaluator::FindBestCommand(
allCastleCoords,
deadline);
sum += immediateScore;
commandEvaluations[index].lookaheadFutures.push_back(std::move(lookaheadScore));
if (!evaluation.completed) { commandEvaluations[index].immediateCompleted = false; }
sum += evaluation.immediateScore;
commandEvaluations[index].lookaheadFutures.push_back(
std::move(evaluation.lookaheadScore));
}
commandEvaluations[index].immediateScore = sum / maxRepeatCount;
commandEvaluations[index].immediateScore = sum / sampleCount;
}
}
@@ -427,19 +452,33 @@ auto AICommandEvaluator::FindBestCommand(
// Wait for all futures and compute final scores
for (auto& eval : evals) {
ScoreValue totalLookaheadScore = 0.0;
bool completed = eval.immediateCompleted;
for (auto& future : eval.lookaheadFutures) {
totalLookaheadScore += future.get();
const auto lookahead = future.get();
if (!lookahead.completed) { completed = false; }
totalLookaheadScore += lookahead.score;
}
ScoreValue avgLookaheadScore =
eval.lookaheadFutures.empty()
? eval.immediateScore
: totalLookaheadScore / eval.lookaheadFutures.size();
if (!completed) { continue; }
allResults.push_back(IndexAndScore{
.index = eval.index,
.type = eval.type,
.lookaheadScore = avgLookaheadScore,
.immediateScore = eval.immediateScore});
.immediateScore = eval.immediateScore,
.completed = true});
}
if (allResults.empty()) {
return IndexAndScore{
.index = 0,
.type = net::eagle0::shardok::common::UNKNOWN_COMMAND,
.lookaheadScore = 0.0,
.immediateScore = 0.0,
.completed = false};
}
// Find the best command using the existing sorter
auto bestIt = std::ranges::max_element(allResults, CommandSorter);
@@ -457,12 +496,12 @@ auto AICommandEvaluator::EvaluateCommand(
const ScoreValue currentUtility,
const CoordsSet& allCastleCoords,
const size_t commandIndex,
std::chrono::steady_clock::time_point deadline) const -> std::future<ScoreValue> {
std::chrono::steady_clock::time_point deadline) const -> std::future<EvaluationResult> {
const CommandListSPtr guessedDescriptors = guessedEngine.GetAvailableCommandsForAIPlayer(pid);
if (commandIndex >= guessedDescriptors->size()) {
std::promise<ScoreValue> p;
p.set_value(currentUtility);
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = currentUtility, .completed = true});
return p.get_future();
}
@@ -470,11 +509,11 @@ auto AICommandEvaluator::EvaluateCommand(
if (const auto guessedCommandType = guessedDescriptor->GetCommandType();
guessedCommandType == net::eagle0::shardok::common::END_TURN_COMMAND) {
std::promise<ScoreValue> p;
p.set_value(currentUtility);
std::promise<EvaluationResult> p;
p.set_value(EvaluationResult{.score = currentUtility, .completed = true});
return p.get_future();
} else if (IsDeterministic(guessedCommandType)) {
auto [immediateScore, lookaheadScore] = EvaluateWithRandomness(
auto evaluation = EvaluateWithRandomness(
pid,
isDefender,
commandIndex,
@@ -485,13 +524,13 @@ auto AICommandEvaluator::EvaluateCommand(
attackerStrategy,
allCastleCoords,
deadline);
return std::move(lookaheadScore);
return std::move(evaluation.lookaheadScore);
} else if (guessedDescriptor->HasOdds()) {
const auto successChancePercentile = guessedDescriptor->GetOddsPercentile();
const double successChance = static_cast<double>(successChancePercentile) / 100.0;
// Success attempt
auto [successImmediateScore, successLookaheadScore] = EvaluateWithRandomness(
auto successEvaluation = EvaluateWithRandomness(
pid,
isDefender,
commandIndex,
@@ -504,7 +543,7 @@ auto AICommandEvaluator::EvaluateCommand(
deadline);
// Failure attempt
auto [failureImmediateScore, failureLookaheadScore] = EvaluateWithRandomness(
auto failureEvaluation = EvaluateWithRandomness(
pid,
isDefender,
commandIndex,
@@ -517,20 +556,29 @@ auto AICommandEvaluator::EvaluateCommand(
deadline);
// Return weighted average of success and failure
auto successSF = successLookaheadScore.share();
auto failureSF = failureLookaheadScore.share();
return std::async(std::launch::deferred, [successSF, failureSF, successChance]() -> double {
return std::lerp(failureSF.get(), successSF.get(), successChance);
});
auto successSF = successEvaluation.lookaheadScore.share();
auto failureSF = failureEvaluation.lookaheadScore.share();
return std::async(
std::launch::deferred,
[successSF, failureSF, successChance]() -> EvaluationResult {
const auto failure = failureSF.get();
const auto success = successSF.get();
if (!failure.completed || !success.completed) {
return EvaluationResult{.score = 0.0, .completed = false};
}
return EvaluationResult{
.score = std::lerp(failure.score, success.score, successChance),
.completed = true};
});
} else {
// For non-deterministic commands without odds, use multiple attempts
std::vector<std::future<ScoreValue>> lookaheadFutures;
lookaheadFutures.reserve(maxRepeatCount);
std::vector<std::future<EvaluationResult>> lookaheadFutures;
const int sampleCount = std::max(1, maxRepeatCount);
lookaheadFutures.reserve(sampleCount);
for (int repeatIteration = 0; repeatIteration < maxRepeatCount; repeatIteration++) {
auto sequence = std::vector{
static_cast<double>(repeatIteration) / static_cast<double>(maxRepeatCount - 1)};
auto [immediateScore, lookaheadScore] = EvaluateWithRandomness(
for (int repeatIteration = 0; repeatIteration < sampleCount; repeatIteration++) {
auto sequence = std::vector{RandomnessSampleForRepeat(repeatIteration, sampleCount)};
auto evaluation = EvaluateWithRandomness(
pid,
isDefender,
commandIndex,
@@ -542,17 +590,25 @@ auto AICommandEvaluator::EvaluateCommand(
allCastleCoords,
deadline);
lookaheadFutures.push_back(std::move(lookaheadScore));
lookaheadFutures.push_back(std::move(evaluation.lookaheadScore));
}
// Return a future that computes the average when needed
return std::async(
std::launch::deferred,
[lookaheadFutures = std::move(lookaheadFutures),
maxRepeatCount]() mutable -> double {
sampleCount]() mutable -> EvaluationResult {
ScoreValue total = 0.0;
for (auto& future : lookaheadFutures) { total += future.get(); }
return total / maxRepeatCount;
bool completed = true;
for (auto& future : lookaheadFutures) {
const auto result = future.get();
if (!result.completed) { completed = false; }
total += result.score;
}
if (!completed) { return EvaluationResult{.score = 0.0, .completed = false}; }
return EvaluationResult{
.score = total / static_cast<ScoreValue>(sampleCount),
.completed = true};
});
}
}
@@ -38,6 +38,11 @@ public:
BattalionTypeGetter battalionTypeGetter); // Pass by value
/// Evaluates the score for a particular command index with lookahead.
struct EvaluationResult {
ScoreValue score;
bool completed;
};
[[nodiscard]] auto EvaluateCommand(
PlayerId pid,
bool isDefender,
@@ -48,7 +53,7 @@ public:
ScoreValue currentUtility,
const CoordsSet& allCastleCoords,
size_t commandIndex,
std::chrono::steady_clock::time_point deadline) const -> std::future<ScoreValue>;
std::chrono::steady_clock::time_point deadline) const -> std::future<EvaluationResult>;
/// Find the best command among all available commands at the given depth.
struct IndexAndScore {
@@ -56,6 +61,7 @@ public:
CommandType type;
ScoreValue lookaheadScore;
ScoreValue immediateScore;
bool completed;
};
[[nodiscard]] auto FindBestCommand(
@@ -76,7 +82,8 @@ private:
struct ImmediateAndLookaheadScore {
ScoreValue immediateScore;
std::future<ScoreValue> lookaheadScore;
bool completed;
std::future<EvaluationResult> lookaheadScore;
};
/// Recursive lookahead calculator
@@ -89,7 +96,7 @@ private:
ScoreValue currentUtility,
const AIStrategy& attackerStrategy,
const CoordsSet& allCastleCoords,
std::chrono::steady_clock::time_point deadline) const -> std::future<ScoreValue>;
std::chrono::steady_clock::time_point deadline) const -> std::future<EvaluationResult>;
/// Evaluate single command execution with randomness handling
[[nodiscard]] auto EvaluateWithRandomness(
@@ -32,6 +32,32 @@ CoordsSet AICommandFilter::BuildEnemyLocations(const GameStateW& gameState, Play
return enemyLocations;
}
std::vector<size_t> AICommandFilter::FilterLoopingCommands(
const CommandListSPtr& commands,
const GameStateW& gameState) {
std::vector<size_t> filteredIndices;
filteredIndices.reserve(commands->size());
for (size_t i = 0; i < commands->size(); ++i) {
const auto& cmd = (*commands)[i];
bool shouldFilter = false;
if (cmd->GetCommandType() == CommandType::METEOR_TARGET_COMMAND ||
cmd->GetCommandType() == CommandType::METEOR_CANCEL_COMMAND) {
const int unitId = cmd->GetActorUnitId();
const Unit* unit = gameState->units()->Get(unitId);
if (unit->attached_hero().profession_info().cast_target().row() > -1) {
shouldFilter = true;
}
}
if (!shouldFilter) { filteredIndices.push_back(i); }
}
return filteredIndices;
}
std::vector<size_t> AICommandFilter::FilterCommands(
const CommandListSPtr& commands,
PlayerId pid,
@@ -49,15 +75,47 @@ std::vector<size_t> AICommandFilter::FilterCommands(
// Calculate minimum distance to enemies once for all filters
const double minDistToEnemies = MinDistanceToEnemyUnits(gameState, pid, enemyLocations);
bool hasAvailablePlacementCommand = false;
for (const auto& cmd : *commands) {
if (cmd->GetCommandType() == CommandType::PLACE_UNIT_COMMAND ||
cmd->GetCommandType() == CommandType::PLACE_HIDDEN_UNIT_COMMAND) {
hasAvailablePlacementCommand = true;
break;
}
}
bool playerHasReserveUnits = false;
for (const Unit* unit : *gameState->units()) {
if (unit->player_id() == pid &&
unit->status() == net::eagle0::shardok::storage::fb::UnitStatus_RESERVE_UNIT) {
playerHasReserveUnits = true;
break;
}
}
for (size_t i = 0; i < commands->size(); ++i) {
const auto& cmd = (*commands)[i];
if (cmd->GetCommandType() == CommandType::END_PLAYER_SETUP_COMMAND &&
hasAvailablePlacementCommand && playerHasReserveUnits) {
continue;
}
// Always allow END_TURN commands
if (cmd->GetCommandType() == CommandType::END_TURN_COMMAND) {
filteredIndices.push_back(i);
continue;
}
// Setup placement commands should always remain available. The movement/spell heuristics
// below are combat-oriented and can otherwise filter every placement for an in-reserve
// unit, making MCTS think ending setup is the only good option.
if (cmd->GetCommandType() == CommandType::PLACE_UNIT_COMMAND ||
cmd->GetCommandType() == CommandType::PLACE_HIDDEN_UNIT_COMMAND) {
filteredIndices.push_back(i);
continue;
}
// Filter obviously bad moves
bool shouldFilter = false;
@@ -138,6 +196,17 @@ bool AICommandFilter::IsWastefulAction(
break;
}
case CommandType::METEOR_TARGET_COMMAND:
case CommandType::METEOR_CANCEL_COMMAND: {
// Filter out re-target/cancel when the mage already has a target.
// Re-targeting exists for human misclick correction; the AI commits
// to its first target choice and doesn't need to reconsider.
const int unitId = cmd.GetActorUnitId();
const Unit* unit = gameState->units()->Get(unitId);
if (unit->attached_hero().profession_info().cast_target().row() > -1) { return true; }
break;
}
case CommandType::START_FIRE_COMMAND: {
// Fire spell filtering - be very restrictive for attackers
// Fire only affects adjacent tiles and lasts multiple rounds
@@ -386,6 +455,35 @@ bool AICommandFilter::IsWastefulAction(
break;
}
case CommandType::FEAR_COMMAND: {
// Solo attackers gain nothing from Fear: the target is stunned for a round but
// there is no teammate to capitalize, and the caster ends its turn no closer to
// killing units or capturing castles. Defenders, by contrast, benefit from stalling,
// so this restriction only applies to the attacking side.
//
// Exception: if the victim is standing on a fire tile, stunning locks them in place
// while the fire modifier keeps chewing through their unit value — the burn does the
// work that a follow-up attacker would normally provide.
if (isDefender) { break; }
if (CountPlayerUnits(gameState, pid) > 1) { break; }
const int targetRow = cmd.GetTargetRow();
const int targetCol = cmd.GetTargetColumn();
if (targetRow < 0 || targetCol < 0) {
throw ShardokInternalErrorException(
"FEAR_COMMAND missing required target information");
}
const Coords victimLocation(
static_cast<int8_t>(targetRow),
static_cast<int8_t>(targetCol));
const auto* victimTerrain = GetTerrain(gameState->hex_map(), victimLocation);
if (!victimTerrain->modifier().fire().present()) {
return true; // Solo attacker fear with no fire-follow-up is a wasted action
}
break;
}
case CommandType::EXTINGUISH_FIRE_COMMAND: {
// Extinguish fire filtering - don't extinguish fires on enemy-occupied tiles
const int targetRow = cmd.GetTargetRow();
@@ -602,4 +700,4 @@ bool AICommandFilter::WouldAbandonCriticalCastle(
return false;
}
} // namespace shardok
} // namespace shardok
@@ -44,6 +44,18 @@ public:
const APDCache& apdCache,
const BattalionTypeGetter& battalionTypeLookup);
/**
* Lightweight filter for the root of the search tree.
* Only removes commands that are genuinely never useful (e.g. meteor
* re-targeting when a target is already set), as opposed to the full
* heuristic filter which aggressively prunes for lookahead performance.
* The full filter could miss good moves at the root that only look
* bad locally but prove worthwhile with deeper search.
*/
static std::vector<size_t> FilterLoopingCommands(
const CommandListSPtr& commands,
const GameStateW& gameState);
private:
// Helper to build enemy locations once for efficiency
static CoordsSet BuildEnemyLocations(const GameStateW& gameState, PlayerId pid);
@@ -15,11 +15,11 @@ enum class AIAlgorithmType {
// Enum for scoring calculator selection
enum class ScoringCalculatorType {
STANDARD, // Default: Unbounded raw scores
NORMALIZED, // Normalized scores in [0, 1] range for ML training
MCTS_OPTIMIZED // Bounded linear scores tuned for MCTS
STANDARD, // Default: Unbounded raw scores
MCTS_OPTIMIZED, // Bounded linear scores tuned for MCTS
EXPERIMENTAL // Standard-derived scorer selected by experiment id
};
} // namespace shardok
#endif // EAGLE0_AI_CONFIG_HPP
#endif // EAGLE0_AI_CONFIG_HPP
@@ -84,6 +84,7 @@ auto AIDefenderStrategySelector::BestDefenderStrategy(
// * the defender has way, way fewer troops
// other considerations we should have but do not presently:
// * the attacker is close to the defender / castles
if (canFlee && roundsRemaining > 2 &&
defenderTroops < MAXIMUM_RATIO_FOR_DEFENDER_TO_FLEE * attackerTroops &&
attackerNonUndeadUnitNotRequiringWaterCrossingCount >= criticalTileCoords.size()) {
@@ -0,0 +1,23 @@
//
// Temporary AI experiment switches used by benchmark-only EXPERIMENTAL runs.
//
#ifndef EAGLE0_AI_EXPERIMENT_CONFIG_HPP
#define EAGLE0_AI_EXPERIMENT_CONFIG_HPP
#include <cstdlib>
#include <string>
namespace shardok {
inline auto CurrentAIExperimentId() -> int {
const char* rawValue = std::getenv("SHARDOK_SCORING_EXPERIMENT_ID");
if (rawValue == nullptr || std::string(rawValue).empty()) { return 0; }
return std::atoi(rawValue);
}
inline auto IsAIExperiment(const int id) -> bool { return CurrentAIExperimentId() == id; }
} // namespace shardok
#endif // EAGLE0_AI_EXPERIMENT_CONFIG_HPP
@@ -5,7 +5,6 @@
#include "AIUnitScoreCalculator.hpp"
#include <algorithm>
#include <cstdlib>
#include "AIAttackLocations.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
@@ -33,7 +32,9 @@ constexpr double kMeteorCastRoundMultiplier = 1.5;
constexpr double kMeteorCastInsufficientVigorMultiplier = 0.5;
constexpr double kMeteorCastleMultiplier = 2.0;
constexpr double kLightningPossibleValue = 0.05;
constexpr double kArcheryPossibleValue = 38;
constexpr double kExpectedArcheryVolleyTargetValueFraction = 0.16;
constexpr double kImmediateArcheryThreatMultiplier = 0.5;
constexpr double kFutureArcheryThreatMultiplier = 0.25;
constexpr double kReduceFortifiedPossibleValue = 50;
constexpr double kReduceUnfortifiedPossibleValue = 12;
constexpr double kFearPossibleValue = 38;
@@ -101,9 +102,24 @@ auto ContextFreeUnitValue(const Unit *unit) -> ScoreValue {
return battalionValue + heroValue;
}
auto archeryValue(const Unit * /*unit*/) -> double {
// TODO: make this depend on the value of the targets
return kArcheryPossibleValue;
auto bestEnemyUnitValue(const vector<const Unit *> &enemyUnits) -> double {
double bestTargetValue = 0.0;
for (const Unit *enemyUnit : enemyUnits) {
bestTargetValue = std::max(bestTargetValue, ContextFreeUnitValue(enemyUnit));
}
return bestTargetValue;
}
auto expectedImpactArcheryValue(const vector<const Unit *> &enemyUnits, const bool canShootNow)
-> double {
const double expectedVolleyImpact =
kExpectedArcheryVolleyTargetValueFraction * bestEnemyUnitValue(enemyUnits);
return expectedVolleyImpact *
(canShootNow ? kImmediateArcheryThreatMultiplier : kFutureArcheryThreatMultiplier);
}
auto archeryValue(const vector<const Unit *> &enemyUnits, const bool canShootNow) -> double {
return expectedImpactArcheryValue(enemyUnits, canShootNow);
}
auto reduceValue(const Unit *unit, const Terrain *unitTerrain) -> double {
@@ -116,10 +132,7 @@ auto reduceValue(const Unit *unit, const Terrain *unitTerrain) -> double {
return 0.0;
}
auto fearValue(const Unit * /*unit*/) -> double {
// TODO: make this depend on the value of the targets
return kFearPossibleValue;
}
auto fearValue(const vector<const Unit *> &) -> double { return kFearPossibleValue; }
auto lightningValue(const Unit *unit) -> double {
// TODO: make this depend on the value of the targets
@@ -265,11 +278,13 @@ auto GetRangedAttackBonus(
const vector<const Unit *> &attackerUnits,
const vector<const Unit *> &defenderUnits,
const int meteorRange,
const double minVigorToCast) -> double {
const double minVigorToCast,
const ActionPoints archeryActionPointCost) -> double {
vector<double> rangedAttackValues{};
const auto &enemyUnits = isAttacker ? defenderUnits : attackerUnits;
const auto &friendlyUnits = isAttacker ? attackerUnits : defenderUnits;
const bool canShootNow = unit->remaining_action_points() >= archeryActionPointCost;
const auto &unitLocation = unit->location();
@@ -306,19 +321,19 @@ auto GetRangedAttackBonus(
unit->attached_hero().profession_info().profession() ==
net::eagle0::shardok::storage::fb::Profession_NECROMANCER &&
unit->attached_hero().control_info().controlled_unit_id() != -1) {
rangedAttackValues.push_back(fearValue(unit));
rangedAttackValues.push_back(fearValue(enemyUnits));
}
if (attackLocations.ArcheryLocations().Contains(unitLocation) &&
unit->volleys_remaining() > 0) {
rangedAttackValues.push_back(archeryValue(unit));
rangedAttackValues.push_back(archeryValue(enemyUnits, canShootNow));
}
// Longbowmen in castle can archer adjacent
if (attackLocations.AdjacentLocations().Contains(unitLocation) &&
unit->volleys_remaining() > 0 && terrain->modifier().castle().present() &&
unit->battalion().type() == net::eagle0::shardok::storage::fb::BattalionTypeId_LONGBOWMEN) {
rangedAttackValues.push_back(archeryValue(unit));
rangedAttackValues.push_back(archeryValue(enemyUnits, canShootNow));
}
if (rangedAttackValues.empty()) return 0.0;
@@ -338,7 +353,8 @@ auto UnitValue(
const CoordsSet &locationsInDangerFromEnemy,
const ActionPointDistances *distances,
int meteorRange,
double meteorCastVigorCost) -> ScoreValue {
double meteorCastVigorCost,
ActionPoints archeryActionPointCost) -> ScoreValue {
const auto &location = unit->location();
if (location.row() < 0) return 0; // unplaced unit
@@ -382,7 +398,8 @@ auto UnitValue(
attackerUnits,
defenderUnits,
meteorRange,
meteorCastVigorCost);
meteorCastVigorCost,
archeryActionPointCost);
// scouting values
// attack range
@@ -32,7 +32,8 @@ auto GetRangedAttackBonus(
const vector<const Unit *> &attackerUnits,
const vector<const Unit *> &defenderUnits,
int meteorRange,
double minVigorToCast) -> double;
double minVigorToCast,
ActionPoints archeryActionPointCost = 0) -> double;
auto UnitValue(
const Unit *unit,
@@ -47,7 +48,8 @@ auto UnitValue(
const CoordsSet &locationsInDangerFromEnemy,
const ActionPointDistances *distances,
int meteorRange,
double meteorCastVigorCost) -> ScoreValue;
double meteorCastVigorCost,
ActionPoints archeryActionPointCost = 0) -> ScoreValue;
} // namespace shardok
@@ -156,7 +156,9 @@ The system uses recursive lookahead with:
- `kProfessionValue`: 200
### Ranged Attack Values
- `kArcheryPossibleValue`: 38
- Archery position value: expected-impact based. A unit that can shoot now gets half of
`0.16 * best target unit value`; a unit in archery range that cannot shoot yet gets one
quarter of that expected volley value.
- `kMeteorDirectTargetingEnemy`: 2 per soldier
- `kMeteorSplashTargetingEnemy`: 1 per soldier
- `kLightningPossibleValue`: 0.05 per soldier
@@ -762,4 +764,4 @@ MCTSAI ai(playerId, isDefender, strategy, castleCoords, apdCache, alCache, confi
- Higher `immediateScoreTieBreakThreshold` to emphasize direct paths
- `BEST_IMMEDIATE` simulation for most predictable behavior
The configuration system allows fine-tuning MCTS behavior for different scenarios while maintaining compatibility with the existing AI infrastructure.
The configuration system allows fine-tuning MCTS behavior for different scenarios while maintaining compatibility with the existing AI infrastructure.
+11 -1
View File
@@ -11,6 +11,13 @@ cc_library(
],
)
cc_library(
name = "ai_experiment_config",
hdrs = ["AIExperimentConfig.hpp"],
copts = COPTS,
visibility = ["//src/main/cpp/net/eagle0/shardok/ai:__subpackages__"],
)
cc_library(
name = "ai_attacker_strategy_selector",
srcs = ["AIAttackerStrategySelector.cpp"],
@@ -84,6 +91,7 @@ cc_library(
],
deps = [
":ai_attack_locations",
":ai_experiment_config",
":ai_score_utilities",
":ai_strategy",
":ai_water_crossing_calculator",
@@ -196,6 +204,7 @@ cc_library(
],
deps = [
":ai_command_filter",
":ai_experiment_config",
":ai_strategy",
":transposition_table",
"//src/main/cpp/net/eagle0/common:sequence_random_generator",
@@ -272,6 +281,7 @@ cc_library(
],
deps = [
":ai_attack_locations",
":ai_experiment_config",
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances",
"//src/main/cpp/net/eagle0/shardok/library/util:hex_map_utils",
],
@@ -348,6 +358,7 @@ cc_library(
":ai_attacker_strategy_selector",
":ai_command_evaluator",
":ai_defender_strategy_selector",
":ai_experiment_config",
":ai_time_budget",
":ai_water_crossing_command_chooser",
"//src/main/cpp/net/eagle0/common:time_utils",
@@ -385,7 +396,6 @@ cc_library(
"//src/main/cpp/net/eagle0/shardok/ai/mcts:shardok_mcts_ai", # MCTS with abstraction layer
"//src/main/cpp/net/eagle0/shardok/ai/score:ai_score_calculator_interface",
"//src/main/cpp/net/eagle0/shardok/ai/score:mcts_optimized_ai_score_calculator", # Bounded linear scorer for MCTS
"//src/main/cpp/net/eagle0/shardok/ai/score:normalized_ai_score_calculator", # Normalized [0,1] scorer for ML training
"//src/main/cpp/net/eagle0/shardok/ai/score:standard_ai_score_calculator", # Standard unbounded scorer (default)
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances",
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances:action_point_distances_cache",
@@ -11,7 +11,9 @@
#include "AIAttackerStrategySelector.hpp"
#include "AICommandEvaluator.hpp"
#include "AICommandFilter.hpp"
#include "TranspositionTable.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIExperimentConfig.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/score/AIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
@@ -59,6 +61,12 @@ auto IterativeDeepeningAI::IterativeSearch(
return result;
}
// Lightweight root filter: only remove genuinely never-useful commands
// (e.g. meteor re-targeting). The full aggressive filter is reserved for
// lookahead where pruning is a performance optimization, not a decision.
const std::vector<size_t> rootFilteredIndices =
AICommandFilter::FilterLoopingCommands(commands, state);
// Check if we're in SET_UP phase and enforce maximum depth limit
bool isSetupPhase =
(state->status()->state() ==
@@ -90,7 +98,8 @@ auto IterativeDeepeningAI::IterativeSearch(
std::vector<size_t> sortedIndices = GetCommandsSortedByPreviousDepth(
currentDepth,
scoresByDepth,
highestDepthCompleted);
highestDepthCompleted,
rootFilteredIndices);
size_t evaluatedCount = 0;
bool allEvaluated = true;
@@ -122,6 +131,10 @@ auto IterativeDeepeningAI::IterativeSearch(
// Now wait for all futures and collect results
for (auto& [cmdIndex, future] : futures) {
auto cmdResult = future.get();
if (!cmdResult.searchCompleted) {
allEvaluated = false;
continue;
}
// Ensure scoresByDepth[cmdIndex] has enough space
if (scoresByDepth[cmdIndex].size() <= currentDepth) {
@@ -213,7 +226,7 @@ auto IterativeDeepeningAI::IterativeSearch(
}
// If all evaluated commands had unchanged scores, we've hit END_TURN in lookahead
if (scoresUnchanged && unchangedCount == evaluatedCount) {
if (!IsAIExperiment(26) && scoresUnchanged && unchangedCount == evaluatedCount) {
completionReason = EvaluationCompletionReason::RAN_OUT_OF_COMMANDS;
break;
}
@@ -243,7 +256,9 @@ auto IterativeDeepeningAI::IterativeSearch(
completionReason = EvaluationCompletionReason::RAN_OUT_OF_COMMANDS;
}
// Select best result from highest depth achieved for each command
// Select best result from the highest completed depth achieved for each command. Commands that
// timed out at a depth are not recorded for that depth, so partial deeper work can help without
// letting timeout fallback scores compete.
result = SelectBestResult(scoresByDepth, highestDepthCompleted);
result.minimumDepthCompleted = result.depthAchieved >= timeBudget.minDepthRequired;
result.searchCompleted = result.minimumDepthCompleted;
@@ -334,7 +349,9 @@ auto IterativeDeepeningAI::SearchCommandAtDepthWithEngine(
// Deduct adjusted time from remaining budget
timeBudget.remainingBudget -= adjustedElapsedMs;
result.bestScore = commandScore;
result.bestScore = commandScore.score;
result.searchCompleted = commandScore.completed;
result.minimumDepthCompleted = commandScore.completed;
std::promise<SearchResult> p;
p.set_value(result);
@@ -344,15 +361,15 @@ auto IterativeDeepeningAI::SearchCommandAtDepthWithEngine(
auto IterativeDeepeningAI::GetCommandsSortedByPreviousDepth(
const size_t currentDepth,
const std::vector<std::vector<ScoreValue>>& scoresByDepth,
const std::vector<size_t>& highestDepthCompleted) -> std::vector<size_t> {
std::vector<size_t> indices(scoresByDepth.size());
std::iota(indices.begin(), indices.end(), 0);
const std::vector<size_t>& highestDepthCompleted,
const std::vector<size_t>& filteredIndices) -> std::vector<size_t> {
if (currentDepth == 1) {
// For depth 1, return natural order
return indices;
// For depth 1, preserve the upstream command-factory priority order.
return filteredIndices;
}
std::vector<size_t> indices = filteredIndices;
// Sort by score at previous depth
const size_t prevDepth = currentDepth - 1;
std::ranges::sort(indices, [&](const size_t a, const size_t b) {
@@ -384,10 +401,20 @@ auto IterativeDeepeningAI::SelectBestResult(
result.bestScore = -std::numeric_limits<ScoreValue>::infinity();
result.searchCompleted = false;
size_t selectionDepth = 0;
if (IsAIExperiment(24)) {
selectionDepth = std::numeric_limits<size_t>::max();
for (const size_t depth : highestDepthCompleted) {
if (depth > 0) { selectionDepth = std::min(selectionDepth, depth); }
}
if (selectionDepth == std::numeric_limits<size_t>::max()) { selectionDepth = 0; }
}
// Find the command with best score at its highest evaluated depth
for (size_t i = 0; i < scoresByDepth.size(); ++i) {
if (highestDepthCompleted[i] > 0) {
const size_t depth = highestDepthCompleted[i];
const size_t depth = selectionDepth > 0 ? selectionDepth : highestDepthCompleted[i];
if (highestDepthCompleted[i] < depth || scoresByDepth[i].size() <= depth) { continue; }
if (ScoreValue score = scoresByDepth[i][depth]; score > result.bestScore) {
result.bestScore = score;
result.bestCommandIndex = i;
@@ -399,4 +426,4 @@ auto IterativeDeepeningAI::SelectBestResult(
return result;
}
} // namespace shardok
} // namespace shardok
@@ -101,7 +101,8 @@ private:
[[nodiscard]] static std::vector<size_t> GetCommandsSortedByPreviousDepth(
size_t currentDepth,
const std::vector<std::vector<ScoreValue>>& scoresByDepth,
const std::vector<size_t>& highestDepthCompleted);
const std::vector<size_t>& highestDepthCompleted,
const std::vector<size_t>& filteredIndices);
[[nodiscard]] static SearchResult SelectBestResult(
const std::vector<std::vector<ScoreValue>>& scoresByDepth,
@@ -110,4 +111,4 @@ private:
} // namespace shardok
#endif // EAGLE0_ITERATIVEDEEPENINGAI_HPP
#endif // EAGLE0_ITERATIVEDEEPENINGAI_HPP
@@ -32,7 +32,6 @@
#include "IterativeDeepeningAI.hpp"
#include "mcts/ShardokMCTSAI.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/score/MCTSOptimizedAIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/score/NormalizedAIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/score/StandardAIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/view_filters/GameStateGuesser.hpp"
@@ -299,12 +298,12 @@ auto ShardokAIClient::StandardChooseCommandIndex(
// Create scorer for actual scoring during search - type selected at construction
std::unique_ptr<AIScoreCalculator> scorer;
switch (scoringCalculatorType) {
case ScoringCalculatorType::NORMALIZED:
scorer = MakeNormalizedAIScoreCalculator(settingsGetter, apdCache, alCache);
break;
case ScoringCalculatorType::MCTS_OPTIMIZED:
scorer = MakeMCTSOptimizedAIScoreCalculator(settingsGetter, apdCache, alCache);
break;
case ScoringCalculatorType::EXPERIMENTAL:
scorer = MakeExperimentalAIScoreCalculator(settingsGetter, apdCache, alCache);
break;
case ScoringCalculatorType::STANDARD:
default: scorer = MakeStandardAIScoreCalculator(settingsGetter, apdCache, alCache); break;
}
@@ -21,6 +21,22 @@
namespace shardok::mcts {
namespace {
auto IsDefenderPlayer(const GameStateW& gameState, const PlayerId playerId) -> bool {
for (const auto* pi : *gameState->player_infos()) {
if (pi->player_id() == playerId) { return pi->is_defender(); }
}
return false;
}
auto LegalActionsCacheKey(const uint64_t stateHash, const bool rootIsDefender) -> uint64_t {
constexpr uint64_t kDefenderRoleHash = 0x9e3779b97f4a7c15ULL;
return rootIsDefender ? stateHash ^ kDefenderRoleHash : stateHash;
}
} // namespace
// Shared cache for legal actions (uses lock-free parallel hash map for thread safety)
// Using 8 submaps to reduce contention with 16 MCTS threads
gtl::parallel_flat_hash_map<
@@ -223,13 +239,14 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// Time hash computation
const auto hashStart = std::chrono::high_resolution_clock::now();
const uint64_t stateHash = shardokState->hash();
const uint64_t cacheKey = LegalActionsCacheKey(stateHash, isDefender_);
const auto hashEnd = std::chrono::high_resolution_clock::now();
timeInHashComputation_.fetch_add(
std::chrono::duration_cast<std::chrono::microseconds>(hashEnd - hashStart).count(),
std::memory_order_relaxed);
// Check transposition table for cached legal actions
if (auto it = legalActionsCache_.find(stateHash); it != legalActionsCache_.end()) {
if (auto it = legalActionsCache_.find(cacheKey); it != legalActionsCache_.end()) {
cacheHits_.fetch_add(1, std::memory_order_relaxed);
// Use cached engine
@@ -304,7 +321,7 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
const std::vector<size_t> filteredIndices = AICommandFilter::FilterCommands(
commands,
currentPlayer,
isDefender_,
IsDefenderPlayer(shardokState->getShardokState(), currentPlayer),
shardokState->getShardokState(),
*apdCache_,
[this](BattalionTypeId typeId) {
@@ -362,7 +379,7 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// This avoids duplicating heavy protocol buffer objects
// Use lazy_emplace_l to ensure thread-safe insertion (locks the bucket during construction)
legalActionsCache_.lazy_emplace_l(
stateHash,
cacheKey,
[&](typename decltype(legalActionsCache_)::value_type& v) {
// Update existing entry
v.second.filteredIndices = filteredIndices;
@@ -370,7 +387,7 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
},
[&](const typename decltype(legalActionsCache_)::constructor& ctor) {
// Create new entry
ctor(stateHash, LegalActionsCache{filteredIndices, engine});
ctor(cacheKey, LegalActionsCache{filteredIndices, engine});
});
return actions;
@@ -416,14 +433,8 @@ std::vector<double> ShardokGameEngine::getActionWeights(
// Determine if current player is defender (not root player!)
// During simulation we need to use the correct perspective for action weighting
bool currentPlayerIsDefender = false;
const auto& gameState = shardokState->getShardokState();
for (const auto* pi : *gameState->player_infos()) {
if (pi->player_id() == currentPlayer) {
currentPlayerIsDefender = pi->is_defender();
break;
}
}
const bool currentPlayerIsDefender = IsDefenderPlayer(gameState, currentPlayer);
// Use AIHeuristicWeighting for fast O(1) context-aware command weighting
std::vector<double> weights;
@@ -110,8 +110,19 @@ bool ShardokGameState::equals(const MCTSGameState& other) const {
}
MCTSPlayerId ShardokGameState::getWinner() const {
// Note: FlatBuffer doesn't have a winner field
// In practice, this would need to determine winner from victory conditions
if (!state_->status() ||
state_->status()->state() !=
net::eagle0::shardok::storage::fb::GameStatus_::State_VICTORY) {
return -1;
}
const auto* winningIds = state_->status()->winning_shardok_ids();
if (!winningIds || winningIds->empty()) { return -1; }
for (const PlayerId winningPid : *winningIds) {
if (winningPid >= 0) { return winningPid; }
}
return -1; // No winner
}
@@ -41,31 +41,6 @@ cc_library(
],
)
cc_library(
name = "normalized_ai_score_calculator",
srcs = ["NormalizedAIScoreCalculator.cpp"],
hdrs = ["NormalizedAIScoreCalculator.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai:__subpackages__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__subpackages__",
],
deps = [
":ai_score_calculator_interface",
":ai_victory_condition_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_strategy",
"//src/main/cpp/net/eagle0/shardok/ai:ai_unit_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_water_crossing_calculator",
"//src/main/cpp/net/eagle0/shardok/ai/score/private:abstract_ai_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai/score/private:ai_score_calculator_shared_utilities",
"//src/main/cpp/net/eagle0/shardok/library:engine",
"//src/main/cpp/net/eagle0/shardok/library:game_state_w",
"//src/main/cpp/net/eagle0/shardok/library/map:coords_set",
"//src/main/cpp/net/eagle0/shardok/library/settings:game_settings",
],
)
cc_library(
name = "standard_ai_score_calculator",
srcs = ["StandardAIScoreCalculator.cpp"],
@@ -79,6 +54,7 @@ cc_library(
deps = [
":ai_score_calculator_interface",
":ai_victory_condition_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_experiment_config",
"//src/main/cpp/net/eagle0/shardok/ai:ai_strategy",
"//src/main/cpp/net/eagle0/shardok/ai:ai_unit_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_water_crossing_calculator",
@@ -59,6 +59,7 @@ public:
MCTSOptimizedAIScoreCalculator(
int maxRounds,
ActionPoints braveWaterCost,
ActionPoints archeryActionPointCost,
int meteorRange,
double meteorCastVigorCost,
int minimumFleeOddsThreshold,
@@ -69,6 +70,7 @@ public:
: AbstractAIScoreCalculator(
maxRounds,
braveWaterCost,
archeryActionPointCost,
meteorRange,
meteorCastVigorCost,
minimumFleeOddsThreshold,
@@ -236,6 +238,7 @@ auto MakeMCTSOptimizedAIScoreCalculator(
return std::make_unique<MCTSOptimizedAIScoreCalculator>(
settingsGetter.Backing().max_rounds(),
settingsGetter.Backing().brave_water_action_point_cost(),
settingsGetter.Backing().archery_action_point_cost(),
settingsGetter.Backing().meteor_range(),
settingsGetter.Backing().meteor_cast_vigor_cost(),
settingsGetter.Backing().ai_minimum_flee_odds_threshold(),
@@ -5,7 +5,7 @@
We need a scoring algorithm that makes MCTS perform well by providing score differences in the right range:
- **Standard Scorer**: Returns unbounded relative scores. Small differences get amplified in MCTS UCB formula, causing over-exploitation (commits to 1-2 high-scoring nodes too early).
- **Normalized Scorer**: Returns scores in [0,1] range with power transformation (exponent=0.1). Differences are too compressed (~0.02-0.05), causing over-exploration (all nodes explored equally, AI makes bad choices).
- **Retired bounded-ratio scorer**: Returned scores in [0,1] range with power transformation (exponent=0.1). Differences were too compressed (~0.02-0.05), causing over-exploration (all nodes explored equally, AI made bad choices).
### MCTS Requirements
@@ -32,9 +32,9 @@ This means individual scores should differ by **0.5 to 2.0** between meaningfull
- Range: 0 (all captured) to -3000 (all held, far away)
### Terminal States
- Victory: INT_MAX (or 1.0 for normalized)
- Defeat: INT_MIN (or 0.0 for normalized)
- Flee/Draw: 0 (or 0.5 for normalized)
- Victory: INT_MAX
- Defeat: INT_MIN
- Flee/Draw: 0
- Captured unit: -10,000
- Captured VIP: -25,000
@@ -257,7 +257,7 @@ This progression is ideal:
This avoids both pathologies:
- Not over-exploiting (like Standard scorer which overcommitted to tiny early differences)
- Not over-exploring (like Normalized scorer which explored equally even with large advantages)
- Not over-exploring like the retired bounded-ratio scorer, which explored equally even with large advantages
## Why MCTS Needs Stronger Signal Than Minimax
@@ -281,11 +281,11 @@ This gives MCTS the right balance: explore when moves are similar, exploit when
## Implementation Notes
1. **Use same calculation structure**: Inherit from AbstractAIScoreCalculator like Standard and Normalized
1. **Use same calculation structure**: Inherit from AbstractAIScoreCalculator like Standard
2. **Reuse unit scoring**: Use existing CalculateUnitsScoreComponents and victory condition calculators
3. **Only change combination**: Override CombineAttackerScores, CombineDefenderScores, etc.
4. **Bounded terminals**: Use ±1000 instead of INT_MAX/MIN for numerical stability
5. **No transformation**: Unlike Normalized, don't apply power transformation - linear scaling is sufficient
5. **No transformation**: Do not apply power transformation - linear scaling is sufficient
6. **Scale constants tuned for MCTS**: 10x larger than naive normalization to provide appropriate signal strength
## Testing with Integration Tests
@@ -383,6 +383,5 @@ Once the scorer passes integration tests with IterativeDeepeningAI, then integra
- `BoundedLinearAIScoreCalculator`
- `MCTSOptimizedAIScoreCalculator`
- `LinearNormalizedAIScoreCalculator`
Recommend: **`MCTSOptimizedAIScoreCalculator`** to clearly indicate purpose.
@@ -1,252 +0,0 @@
//
// Normalized [0,1] implementation of AIScoreCalculator
//
#include "NormalizedAIScoreCalculator.hpp"
#include <cmath>
#include <unordered_map>
#include "private/AIScoreCalculatorSharedUtilities.hpp"
#include "private/AbstractAIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIAttackLocations.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIScoreUtilities.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIStrategy.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIUnitScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/score/AIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
namespace shardok {
using net::eagle0::shardok::storage::fb::BattalionTypeId;
// Bring shared utilities into scope
using score_calculator_internal::UnitsScoreComponents;
/// Normalized implementation of AIScoreCalculator that produces scores in [0, 1] range.
/// Inherits from AbstractAIScoreCalculator to share common functionality.
class NormalizedAIScoreCalculator : public AbstractAIScoreCalculator {
public:
NormalizedAIScoreCalculator(
int maxRounds,
ActionPoints braveWaterCost,
int meteorRange,
double meteorCastVigorCost,
int minimumFleeOddsThreshold,
int desperateFleeThreshold,
std::vector<BattalionTypeSPtr> battalionTypes,
const APDCache &apdCache,
const ALCache &alCache)
: AbstractAIScoreCalculator(
maxRounds,
braveWaterCost,
meteorRange,
meteorCastVigorCost,
minimumFleeOddsThreshold,
desperateFleeThreshold,
std::move(battalionTypes),
apdCache,
alCache) {}
[[nodiscard]] auto GuessedStateScore(
bool isDefender,
const GameStateW &state,
const AIStrategy &aiStrategy,
const CoordsSet &allCastleCoords) const -> ScoreValue override;
// Implement pure virtual methods from AbstractAIScoreCalculator
[[nodiscard]] auto InterpretDefenderOutcome(GameOutcome outcome) const -> ScoreValue override;
[[nodiscard]] auto InterpretAttackerOutcome(GameOutcome outcome) const -> ScoreValue override;
[[nodiscard]] auto AttackerFleeStrategyScoreForState(const GameStateW &gameState) const
-> ScoreValue override;
[[nodiscard]] auto CombineAttackerScores(
const UnitsScoreComponents &components,
double victoryConditionScore,
int roundsRemaining) const -> ScoreValue override;
[[nodiscard]] auto CombineDefenderScatterScores(const UnitsScoreComponents &components) const
-> ScoreValue override;
[[nodiscard]] auto CombineDefenderHoldCastlesScores(
const UnitsScoreComponents &components,
double victoryConditionScore,
int roundsRemaining) const -> ScoreValue override;
private:
[[nodiscard]] auto DefenderFleeStrategyScoreForState(const GameStateW &gameState) const
-> ScoreValue override;
/// Applies power transformation to spread out compressed scores for MCTS.
/// Maps [0,1] → [0,1] but pushes values away from 0.5 toward the extremes.
/// Terminal states (0.0, 1.0) are unchanged.
[[nodiscard]] auto TransformForMCTS(ScoreValue score) const -> ScoreValue;
};
// Implementation of NormalizedAIScoreCalculator methods
auto NormalizedAIScoreCalculator::InterpretDefenderOutcome(GameOutcome outcome) const
-> ScoreValue {
switch (outcome) {
case GameOutcome::DEFENDER_VICTORY: return 1.0;
case GameOutcome::ATTACKER_VICTORY: return 0.0;
case GameOutcome::DRAW: return 0.5;
case GameOutcome::FLEE_OUTCOME: return 0.5;
}
throw ShardokInternalErrorException("Unknown GameOutcome");
}
auto NormalizedAIScoreCalculator::InterpretAttackerOutcome(GameOutcome outcome) const
-> ScoreValue {
switch (outcome) {
case GameOutcome::ATTACKER_VICTORY: return 1.0;
case GameOutcome::DEFENDER_VICTORY: return 0.0;
case GameOutcome::DRAW: return 0.5;
case GameOutcome::FLEE_OUTCOME: return 0.5;
}
throw ShardokInternalErrorException("Unknown GameOutcome");
}
auto NormalizedAIScoreCalculator::CombineDefenderScatterScores(
const UnitsScoreComponents &components) const -> ScoreValue {
// For defender, we flip the perspective: defenderValue is (1), attackerValue is (2)
const double defenderValue = components.defenderUnitsValue;
const double attackerValue = components.attackerUnitsValue;
// No victory condition for scatter strategy
const double denominator = defenderValue + attackerValue;
if (denominator == 0.0) { return 0.5; }
return defenderValue / denominator;
}
auto NormalizedAIScoreCalculator::CombineDefenderHoldCastlesScores(
const UnitsScoreComponents &components,
const double victoryConditionScore,
const int /*roundsRemaining*/) const -> ScoreValue {
// For defender, flip perspective
const double defenderValue = components.defenderUnitsValue;
const double attackerValue = components.attackerUnitsValue;
// Apply normalization
double numerator;
double denominator;
if (victoryConditionScore >= 0) {
numerator = defenderValue + victoryConditionScore;
denominator = defenderValue + attackerValue + victoryConditionScore;
} else {
numerator = defenderValue;
denominator = defenderValue + attackerValue - victoryConditionScore;
}
if (denominator == 0.0) { return 0.5; }
return numerator / denominator;
}
auto NormalizedAIScoreCalculator::DefenderFleeStrategyScoreForState(
const GameStateW & /*gameState*/) const -> ScoreValue {
// FLEE strategy doesn't fit the [0,1] model well - return 0.5
return 0.5;
}
auto NormalizedAIScoreCalculator::AttackerFleeStrategyScoreForState(
const GameStateW & /*gameState*/) const -> ScoreValue {
// FLEE strategy doesn't fit the [0,1] model well - return 0.5
return 0.5;
}
auto NormalizedAIScoreCalculator::CombineAttackerScores(
const UnitsScoreComponents &components,
const double victoryConditionScore,
const int /*roundsRemaining*/) const -> ScoreValue {
const double attackerUnitsValue = components.attackerUnitsValue;
const double defenderUnitsValue = components.defenderUnitsValue;
// Apply normalization formula
double numerator;
double denominator;
if (victoryConditionScore >= 0) {
// Positive victory condition: add to numerator
numerator = attackerUnitsValue + victoryConditionScore;
denominator = attackerUnitsValue + defenderUnitsValue + victoryConditionScore;
} else {
// Negative victory condition: subtract from denominator (making it larger)
numerator = attackerUnitsValue;
denominator = attackerUnitsValue + defenderUnitsValue - victoryConditionScore;
}
// Handle edge case of all zeros
if (denominator == 0.0) { return 0.5; }
return numerator / denominator;
}
auto NormalizedAIScoreCalculator::TransformForMCTS(ScoreValue score) const -> ScoreValue {
// Power transformation exponent - lower values spread scores more toward extremes
// Tuned for MCTS: balances exploration vs exploitation
// - Too low (e.g., 0.3): over-exploitation like standard scorer
// - Too high (e.g., 0.9): over-exploration like untransformed normalized
// - 0.6-0.7: sweet spot for MCTS
constexpr double EXPONENT = 0.1;
if (score > 0.5) {
// Map [0.5, 1.0] → [0.5, 1.0] with power curve
// (score - 0.5) * 2.0 maps to [0, 1], apply power, then scale back
return 0.5 + 0.5 * std::pow((score - 0.5) * 2.0, EXPONENT);
} else {
// Map [0.0, 0.5] → [0.0, 0.5] with power curve (symmetric)
return 0.5 - 0.5 * std::pow((0.5 - score) * 2.0, EXPONENT);
}
}
auto NormalizedAIScoreCalculator::GuessedStateScore(
const bool isDefender,
const GameStateW &state,
const AIStrategy &aiStrategy,
const CoordsSet &allCastleCoords) const -> ScoreValue {
const int roundsRemaining = GetMaxRounds() - state->current_round();
ScoreValue rawScore;
if (isDefender) {
rawScore = DefenderScoreForState(state, aiStrategy, allCastleCoords, roundsRemaining);
} else {
rawScore = AttackerScoreForState(state, aiStrategy, allCastleCoords, roundsRemaining);
}
// Apply power transformation to spread out scores for MCTS
return TransformForMCTS(rawScore);
}
// Factory function implementation
auto MakeNormalizedAIScoreCalculator(
const SettingsGetter &settingsGetter,
const APDCache &apdCache,
const ALCache &alCache) -> std::unique_ptr<AIScoreCalculator> {
// Extract all battalion types into a vector indexed by BattalionTypeId
std::vector<BattalionTypeSPtr> battalionTypes(BattalionTypeId::BattalionTypeId_MAX + 1);
for (int typeId = BattalionTypeId::BattalionTypeId_MIN;
typeId <= BattalionTypeId::BattalionTypeId_MAX;
typeId++) {
auto battalionTypeId = static_cast<BattalionTypeId>(typeId);
battalionTypes[battalionTypeId] = settingsGetter.GetBattalionType(battalionTypeId);
}
return std::make_unique<NormalizedAIScoreCalculator>(
settingsGetter.Backing().max_rounds(),
settingsGetter.Backing().brave_water_action_point_cost(),
settingsGetter.Backing().meteor_range(),
settingsGetter.Backing().meteor_cast_vigor_cost(),
settingsGetter.Backing().ai_minimum_flee_odds_threshold(),
settingsGetter.Backing().ai_desperate_flee_threshold(),
std::move(battalionTypes),
apdCache,
alCache);
}
} // namespace shardok
@@ -1,44 +0,0 @@
//
// Normalized [0,1] implementation of AIScoreCalculator
//
#ifndef EAGLE0_NORMALIZEDAISCORECALCULATOR_HPP
#define EAGLE0_NORMALIZEDAISCORECALCULATOR_HPP
#include <memory>
#include "src/main/cpp/net/eagle0/shardok/ai/AIAttackLocations.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
namespace shardok {
// Forward declarations
class AIScoreCalculator;
using APDCache = std::shared_ptr<ActionPointDistancesCache>;
using ALCache = std::unique_ptr<AttackLocationsCache>;
/// Factory function to create a NormalizedAIScoreCalculator.
/// Returns a unique_ptr to AIScoreCalculator to hide the implementation.
///
/// The normalized scorer produces scores in the range [0, 1] where:
/// - 0.0 = complete defender victory
/// - 1.0 = complete attacker victory
/// - 0.5 = neutral/draw state
///
/// Terminal states (victory/defeat) always return 1.0 or 0.0.
/// Non-terminal states use asymmetric normalization:
/// - If victory condition >= 0:
/// score = (attackerUnits + victoryCondition) / (attackerUnits + defenderUnits +
/// victoryCondition)
/// - If victory condition < 0:
/// score = attackerUnits / (attackerUnits + defenderUnits - victoryCondition)
[[nodiscard]] auto MakeNormalizedAIScoreCalculator(
const SettingsGetter& settingsGetter,
const APDCache& apdCache,
const ALCache& alCache) -> std::unique_ptr<AIScoreCalculator>;
} // namespace shardok
#endif // EAGLE0_NORMALIZEDAISCORECALCULATOR_HPP
@@ -4,14 +4,17 @@
#include "StandardAIScoreCalculator.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <unordered_map>
#include "private/AIScoreCalculatorSharedUtilities.hpp"
#include "private/AbstractAIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIAttackGroups.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIAttackLocations.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIExperimentConfig.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIScoreUtilities.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIStrategy.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIUnitScoreCalculator.hpp"
@@ -67,6 +70,68 @@ struct AttackerScorePerformanceLogger {
}
};
struct StandardScoringExperiment {
double attackerUnitsScale = 1.0;
double defenderUnitsScale = 1.0;
double victoryConditionScale = 1.0;
double unitsBaseMultiplierScale = 1.0;
double attackerRoundMultiplier = 1.0;
double defenderRoundAdvantageScale = 1.0;
};
auto ExperimentalScoringId() -> int { return CurrentAIExperimentId(); }
auto ScoringExperimentForId(const int id) -> StandardScoringExperiment {
StandardScoringExperiment experiment;
switch (id) {
case 1: experiment.attackerUnitsScale = 1.05; break;
case 2: experiment.attackerUnitsScale = 1.10; break;
case 3: experiment.attackerUnitsScale = 0.95; break;
case 4: experiment.attackerUnitsScale = 0.90; break;
case 5: experiment.defenderUnitsScale = 0.95; break;
case 6: experiment.defenderUnitsScale = 0.90; break;
case 7: experiment.defenderUnitsScale = 1.05; break;
case 8: experiment.defenderUnitsScale = 1.10; break;
case 9: experiment.victoryConditionScale = 1.10; break;
case 10: experiment.victoryConditionScale = 1.25; break;
case 11: experiment.victoryConditionScale = 0.90; break;
case 12: experiment.victoryConditionScale = 0.75; break;
case 13: experiment.unitsBaseMultiplierScale = 0.90; break;
case 14: experiment.unitsBaseMultiplierScale = 1.10; break;
case 15: experiment.attackerRoundMultiplier = 0.90; break;
case 16: experiment.attackerRoundMultiplier = 0.75; break;
case 17: experiment.defenderRoundAdvantageScale = 0.50; break;
case 18: experiment.defenderRoundAdvantageScale = 0.0; break;
case 19:
experiment.attackerUnitsScale = 1.10;
experiment.victoryConditionScale = 1.10;
break;
case 20:
experiment.defenderUnitsScale = 0.90;
experiment.victoryConditionScale = 1.10;
break;
default: break;
}
return experiment;
}
auto AdjustDefenderUnitsForExperiment(
double defenderUnitsValue,
const int roundsRemaining,
const int maxRounds,
const StandardScoringExperiment &experiment) -> double {
const double currentRound = static_cast<double>(maxRounds - roundsRemaining);
const double standardAdvantage = 1.0 + currentRound / 31.0;
if (standardAdvantage <= 0.0) { return defenderUnitsValue * experiment.defenderUnitsScale; }
const double unadjustedDefenderValue = defenderUnitsValue / standardAdvantage;
const double adjustedAdvantage =
1.0 + experiment.defenderRoundAdvantageScale * currentRound / 31.0;
return unadjustedDefenderValue * adjustedAdvantage * experiment.defenderUnitsScale;
}
std::atomic<int> AttackerScorePerformanceLogger::callCount{0};
std::atomic<double> AttackerScorePerformanceLogger::intervalTime{0.0};
std::atomic<double> AttackerScorePerformanceLogger::totalTime{0.0};
@@ -95,23 +160,27 @@ public:
StandardAIScoreCalculator(
int maxRounds,
ActionPoints braveWaterCost,
ActionPoints archeryActionPointCost,
int meteorRange,
double meteorCastVigorCost,
int minimumFleeOddsThreshold,
int desperateFleeThreshold,
std::vector<BattalionTypeSPtr> battalionTypes,
const APDCache &apdCache,
const ALCache &alCache)
const ALCache &alCache,
StandardScoringExperiment experiment = {})
: AbstractAIScoreCalculator(
maxRounds,
braveWaterCost,
archeryActionPointCost,
meteorRange,
meteorCastVigorCost,
minimumFleeOddsThreshold,
desperateFleeThreshold,
std::move(battalionTypes),
apdCache,
alCache) {}
alCache),
experiment_(experiment) {}
[[nodiscard]] auto GuessedStateScore(
bool isDefender,
@@ -151,6 +220,8 @@ private:
[[nodiscard]] auto DefenderFleeStrategyScoreForState(const GameStateW &gameState) const
-> ScoreValue override;
StandardScoringExperiment experiment_;
};
// Implementation of StandardAIScoreCalculator methods
@@ -159,7 +230,7 @@ auto StandardAIScoreCalculator::InterpretDefenderOutcome(GameOutcome outcome) co
switch (outcome) {
case GameOutcome::DEFENDER_VICTORY: return INT_MAX;
case GameOutcome::ATTACKER_VICTORY: return INT_MIN;
case GameOutcome::DRAW: return 0;
case GameOutcome::DRAW: return INT_MAX;
case GameOutcome::FLEE_OUTCOME: return 0;
}
throw ShardokInternalErrorException("Unknown GameOutcome");
@@ -169,7 +240,7 @@ auto StandardAIScoreCalculator::InterpretAttackerOutcome(GameOutcome outcome) co
switch (outcome) {
case GameOutcome::ATTACKER_VICTORY: return INT_MAX;
case GameOutcome::DEFENDER_VICTORY: return INT_MIN;
case GameOutcome::DRAW: return 0;
case GameOutcome::DRAW: return INT_MIN;
case GameOutcome::FLEE_OUTCOME: return 0;
}
throw ShardokInternalErrorException("Unknown GameOutcome");
@@ -241,10 +312,20 @@ auto StandardAIScoreCalculator::CombineAttackerScores(
const UnitsScoreComponents &components,
const double victoryConditionScore,
const int roundsRemaining) const -> ScoreValue {
const double unitsDifference = components.attackerUnitsValue - components.defenderUnitsValue;
const double unitsMultiplier =
static_cast<double>(roundsRemaining) / static_cast<double>(GetMaxRounds());
return UNITS_BASE_MULTIPLIER * unitsMultiplier * unitsDifference + victoryConditionScore;
const double attackerUnitsValue =
components.attackerUnitsValue * experiment_.attackerUnitsScale;
const double defenderUnitsValue = AdjustDefenderUnitsForExperiment(
components.defenderUnitsValue,
roundsRemaining,
GetMaxRounds(),
experiment_);
const double unitsDifference = attackerUnitsValue - defenderUnitsValue;
// Keep tactical unit value relevant late in the battle. The previous time decay could make
// attackers undervalue decisive combat near the round limit.
const double unitsMultiplier = experiment_.attackerRoundMultiplier;
return UNITS_BASE_MULTIPLIER * experiment_.unitsBaseMultiplierScale * unitsMultiplier *
unitsDifference +
victoryConditionScore * experiment_.victoryConditionScale;
}
auto StandardAIScoreCalculator::GuessedStateScore(
@@ -261,10 +342,11 @@ auto StandardAIScoreCalculator::GuessedStateScore(
}
// Factory function implementation
auto MakeStandardAIScoreCalculator(
auto MakeStandardAIScoreCalculatorWithExperiment(
const SettingsGetter &settingsGetter,
const APDCache &apdCache,
const ALCache &alCache) -> std::unique_ptr<AIScoreCalculator> {
const ALCache &alCache,
const StandardScoringExperiment &experiment) -> std::unique_ptr<AIScoreCalculator> {
// Extract all battalion types into a vector indexed by BattalionTypeId
std::vector<BattalionTypeSPtr> battalionTypes(BattalionTypeId::BattalionTypeId_MAX + 1);
for (int typeId = BattalionTypeId::BattalionTypeId_MIN;
@@ -277,13 +359,37 @@ auto MakeStandardAIScoreCalculator(
return std::make_unique<StandardAIScoreCalculator>(
settingsGetter.Backing().max_rounds(),
settingsGetter.Backing().brave_water_action_point_cost(),
settingsGetter.Backing().archery_action_point_cost(),
settingsGetter.Backing().meteor_range(),
settingsGetter.Backing().meteor_cast_vigor_cost(),
settingsGetter.Backing().ai_minimum_flee_odds_threshold(),
settingsGetter.Backing().ai_desperate_flee_threshold(),
std::move(battalionTypes),
apdCache,
alCache);
alCache,
experiment);
}
auto MakeStandardAIScoreCalculator(
const SettingsGetter &settingsGetter,
const APDCache &apdCache,
const ALCache &alCache) -> std::unique_ptr<AIScoreCalculator> {
return MakeStandardAIScoreCalculatorWithExperiment(
settingsGetter,
apdCache,
alCache,
StandardScoringExperiment{});
}
auto MakeExperimentalAIScoreCalculator(
const SettingsGetter &settingsGetter,
const APDCache &apdCache,
const ALCache &alCache) -> std::unique_ptr<AIScoreCalculator> {
return MakeStandardAIScoreCalculatorWithExperiment(
settingsGetter,
apdCache,
alCache,
ScoringExperimentForId(ExperimentalScoringId()));
}
} // namespace shardok
@@ -26,6 +26,12 @@ using ALCache = std::unique_ptr<AttackLocationsCache>;
const APDCache& apdCache,
const ALCache& alCache) -> std::unique_ptr<AIScoreCalculator>;
/// Factory function to create the environment-selected experimental scorer.
[[nodiscard]] auto MakeExperimentalAIScoreCalculator(
const SettingsGetter& settingsGetter,
const APDCache& apdCache,
const ALCache& alCache) -> std::unique_ptr<AIScoreCalculator>;
} // namespace shardok
#endif // EAGLE0_STANDARDAISCORECALCULATOR_HPP
@@ -40,7 +40,7 @@ constexpr double kMaxProximityBuf = 1.5;
constexpr double kDistanceDebufRatio = 8.0;
/// Structure to hold separated attacker/defender unit scores
/// Used by NormalizedAIScoreCalculator to apply asymmetric normalization
/// Used by scorers that combine attacker and defender unit values separately.
struct UnitsScoreComponents {
double attackerUnitsValue;
double defenderUnitsValue;
@@ -157,7 +157,8 @@ auto AbstractAIScoreCalculator::CalculateUnitsScoreComponents(
locationsCausingDanger,
notBravingApd,
GetMeteorRange(),
GetMeteorCastVigorCost());
GetMeteorCastVigorCost(),
GetArcheryActionPointCost());
attackerUnitsValue += distanceMultiplier * uv;
}
@@ -188,7 +189,8 @@ auto AbstractAIScoreCalculator::CalculateUnitsScoreComponents(
locationsCausingDangerForAttacker,
defenderNotBravingApd,
GetMeteorRange(),
GetMeteorCastVigorCost());
GetMeteorCastVigorCost(),
GetArcheryActionPointCost());
double distanceMultiplier = 1.0;
@@ -251,7 +253,7 @@ auto AbstractAIScoreCalculator::CalculateUnitsScoreComponents(
braveWaterCost)
: nullptr,
cachedHexMap);
if (thisDistance < closestDistanceToEnemy) {
if (thisDistance < closestDistanceToFriendly) {
closestDistanceToFriendly = thisDistance;
}
}
@@ -506,9 +508,7 @@ auto AbstractAIScoreCalculator::AttackerScoreForState(
const ScoreValue victoryConditionTotal =
CalculateAttackerVictoryConditionScore(gameState, attackerStrategy, castleCoords);
// Combine scores using subclass-specific logic
// Standard: uses difference and multiplier
// Normalized: uses normalization formula
// Combine scores using subclass-specific logic.
return CombineAttackerScores(components, victoryConditionTotal, roundsRemaining);
}
@@ -44,6 +44,7 @@ protected:
AbstractAIScoreCalculator(
int maxRounds,
ActionPoints braveWaterCost,
ActionPoints archeryActionPointCost,
int meteorRange,
double meteorCastVigorCost,
int minimumFleeOddsThreshold,
@@ -53,6 +54,7 @@ protected:
const ALCache &alCache)
: maxRounds_(maxRounds),
braveWaterCost_(braveWaterCost),
archeryActionPointCost_(archeryActionPointCost),
meteorRange_(meteorRange),
meteorCastVigorCost_(meteorCastVigorCost),
minimumFleeOddsThreshold_(minimumFleeOddsThreshold),
@@ -70,6 +72,9 @@ protected:
[[nodiscard]] auto GetApdCache() const -> const APDCache & { return apdCache_; }
[[nodiscard]] auto GetAlCache() const -> const ALCache & { return alCache_; }
[[nodiscard]] auto GetBraveWaterCost() const -> ActionPoints { return braveWaterCost_; }
[[nodiscard]] auto GetArcheryActionPointCost() const -> ActionPoints {
return archeryActionPointCost_;
}
[[nodiscard]] auto GetMaxRounds() const -> int { return maxRounds_; }
[[nodiscard]] auto GetMeteorRange() const -> int { return meteorRange_; }
[[nodiscard]] auto GetMeteorCastVigorCost() const -> double { return meteorCastVigorCost_; }
@@ -146,9 +151,8 @@ protected:
-> ScoreValue = 0;
// Pure virtual method for combining units score and victory condition score
// This is where Standard and Normalized diverge in their scoring approach
// Standard: uses difference and applies multiplier
// Normalized: uses normalization formula with separate attacker/defender values
// This is where concrete scorers combine unit value and victory condition pressure.
// Standard uses the raw unit-value difference; MCTS-optimized uses bounded scaling.
[[nodiscard]] virtual auto CombineAttackerScores(
const UnitsScoreComponents &components,
double victoryConditionScore,
@@ -158,6 +162,7 @@ private:
// Scalar settings extracted from SettingsGetter
int maxRounds_;
ActionPoints braveWaterCost_;
ActionPoints archeryActionPointCost_;
int meteorRange_;
double meteorCastVigorCost_;
int minimumFleeOddsThreshold_;
@@ -54,30 +54,38 @@ std::unique_ptr<BattleConfigProto> AiBattleConfigLoader::CreateDefaultPerfConfig
// Basic setup matching Unity's "Perf" configuration
config->set_map_name("Alah");
config->set_month(month);
config->set_max_rounds(40);
config->set_random_seed(0); // Use system random
config->set_max_rounds(31);
config->set_random_seed(1);
config->set_use_configured_placements(false);
config->set_apply_forced_commands(true);
// Attacker configuration - 6 Longbowmen units with professions 1-6
PlayerConfig* attacker = config->mutable_attacker();
attacker->set_ai_algorithm(AIAlgorithmType::ITERATIVE_DEEPENING);
attacker->set_scoring_calculator(
net::eagle0::shardok::ai_battle_simulator::ScoringCalculatorType::STANDARD);
for (int profession = 1; profession <= 6; ++profession) {
UnitConfig* unit = attacker->add_units();
unit->set_profession(profession);
unit->set_battalion_type_id(4); // Longbowmen (battalion type 4)
unit->set_starting_position_index(0); // Attackers use position 0
unit->set_battalion_type_id(4); // Longbowmen (battalion type 4)
unit->set_starting_position_index(0); // Attackers use position 0
unit->set_can_flee(true);
unit->mutable_battalion()->set_size(1000); // Match client battalion size
}
// Defender configuration - 6 Light Infantry units with NO_PROFESSION (profession 14)
PlayerConfig* defender = config->mutable_defender();
defender->set_ai_algorithm(AIAlgorithmType::ITERATIVE_DEEPENING);
defender->set_scoring_calculator(
net::eagle0::shardok::ai_battle_simulator::ScoringCalculatorType::STANDARD);
for (int i = 0; i < 6; ++i) {
UnitConfig* unit = defender->add_units();
unit->set_profession(14); // NO_PROFESSION to match client battles
unit->set_battalion_type_id(0); // Light Infantry (battalion type 0)
unit->set_starting_position_index(-1); // Defenders use position -1
unit->set_profession(14); // NO_PROFESSION to match client battles
unit->set_battalion_type_id(0); // Light Infantry (battalion type 0)
unit->set_starting_position_index(-1); // Defenders use position -1
unit->set_can_flee(true);
unit->mutable_battalion()->set_size(1000); // Match client battalion size
}

Some files were not shown because too many files have changed in this diff Show More