Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Advisors S1: the engine and the side popup, no message yet (Refs #1484) (#1555)

Eyal Golan8ace05ba52fd
diff --git a/changelog.d/advisors-s1.md b/changelog.d/advisors-s1.md
new file mode 100644
index 000000000..9705343e4
--- /dev/null
+++ b/changelog.d/advisors-s1.md
@@ -0,0 +1,3 @@
+- The advisors' engine (spec docs/superpowers/specs/2026-10-23-advisors-design.md, slice S1): their data file and its
+ checks, the help level and seen marks in the settings file, the queue, and the side popup that hides under every modal
+ layer. No message is shown yet (Refs #1484).
diff --git a/unity/Assets/Resources/Advisors.meta b/unity/Assets/Resources/Advisors.meta
new file mode 100644
index 000000000..d66e1e5a1
--- /dev/null
+++ b/unity/Assets/Resources/Advisors.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: eeaafb0ae16d1467381bc5ac931e40f5
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Resources/Advisors/advisor-messages.yaml b/unity/Assets/Resources/Advisors/advisor-messages.yaml
new file mode 100644
index 000000000..c31439cc1
--- /dev/null
+++ b/unity/Assets/Resources/Advisors/advisor-messages.yaml
@@ -0,0 +1,12 @@
+# The advisors (docs/superpowers/specs/2026-10-23-advisors-design.md; docs/oss/DECISIONS.md D-ADV): who they are, what
+# each says and when, and the encyclopedia's pages. A Unity-side file, never game content: it does not feed the content
+# hash or the save. A message's text is advisor.<id>.text in strings.en.yaml and strings.he.yaml; a page's is
+# advisor.page.<id>.title and .text. he_review stays pending until a native reviewer approves the Hebrew (spec OQ-4);
+# a pending message or page never shows in Hebrew. The owner reviews every line before it ships (spec 17).
+# person: the people.yaml id whose portrait the popup shows (PortraitCatalog); none drawn when the catalogue has none.
+advisors:
+ - { id: ben_gurion, person: ben_gurion }
+ - { id: meyerson, person: golda_meir }
+ - { id: dayan, person: dayan }
+messages: []
+pages: []
diff --git a/unity/Assets/Resources/Advisors/advisor-messages.yaml.meta b/unity/Assets/Resources/Advisors/advisor-messages.yaml.meta
new file mode 100644
index 000000000..2a7823654
--- /dev/null
+++ b/unity/Assets/Resources/Advisors/advisor-messages.yaml.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: f8dbc1321e34f41b58948a19c815f41f
+TextScriptImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/UI/AdvisorCatalog.cs b/unity/Assets/Scripts/UI/AdvisorCatalog.cs
new file mode 100644
index 000000000..76af1d709
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorCatalog.cs
@@ -0,0 +1,221 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using UnityEngine;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.NamingConventions;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>Reads and checks Assets/Resources/Advisors/advisor-messages.yaml (spec 4.1): the three advisors, their
+ /// messages (a signal, a condition, a help level, a priority, a repeat rule, up to two actions) and the encyclopedia's
+ /// pages. A Unity-side file, never part of the hashed game content.</summary>
+ public sealed class AdvisorCatalog
+ {
+ public const string ResourcePath = "Advisors/advisor-messages";
+ public const string Path = "Assets/Resources/Advisors/advisor-messages.yaml";
+ public static readonly string[] AdvisorIds = { "ben_gurion", "meyerson", "dayan" };
+ /// <summary>The lowest help level that shows a message, from the chattiest (spec 6); "critical" shows at every level.</summary>
+ public static readonly string[] Levels = { "new", "experienced", "warnings", "critical" };
+ public const string Once = "once", Every = "every", Approved = "approved", Pending = "pending";
+ public const int MaxWords = 35;
+ static readonly Regex IdPattern = new Regex("^[a-z0-9_.]+$", RegexOptions.CultureInvariant);
+
+ public sealed class Advisor { public string Id { get; set; } = ""; public string Person { get; set; } = ""; }
+
+ /// <summary>One button: Show me's named target, a side screen, an encyclopedia page, or the decision card.</summary>
+ public sealed class Act
+ {
+ public string ShowMe { get; set; } = "";
+ public string OpenScreen { get; set; } = "";
+ public string Encyclopedia { get; set; } = "";
+ public bool OpenCard { get; set; }
+ }
+
+ public sealed class Message
+ {
+ public string Id { get; set; } = "";
+ public string Advisor { get; set; } = "";
+ public string Signal { get; set; } = "";
+ public Dictionary<string, double> When { get; set; } = new Dictionary<string, double>();
+ public List<string> Requires { get; set; } = new List<string>();
+ public string Level { get; set; } = "";
+ public int Priority { get; set; } = 1;
+ public string Repeat { get; set; } = Once;
+ public int CooldownTurns { get; set; }
+ public List<Act> Actions { get; set; } = new List<Act>();
+ public string Quote { get; set; } = "";
+ public string DisagreesWith { get; set; } = "";
+ public string HeReview { get; set; } = Pending;
+
+ /// <summary>Teaching (help levels new and experienced) as against advice and warnings (spec 7.1's button sets).</summary>
+ public bool Teaching => Level == "new" || Level == "experienced";
+ public bool Critical => Level == "critical";
+ /// <summary>Its text may show in this language: English always, Hebrew once approved (OQ-4).</summary>
+ public bool ApprovedIn(bool hebrew) => !hebrew || HeReview == Approved;
+ }
+
+ public sealed class Page
+ {
+ public string Id { get; set; } = "";
+ public string Advisor { get; set; } = "";
+ public string ShowMe { get; set; } = "";
+ public List<string> Rules { get; set; } = new List<string>();
+ public string HeReview { get; set; } = Pending;
+ public bool ApprovedIn(bool hebrew) => !hebrew || HeReview == Approved;
+ }
+
+ /// <summary>What the checks accept: the game's signals, conditions, Show me targets, side screens, verified quotes
+ /// and the files in StreamingAssets/advisors (Shipped), or a test's own lists.</summary>
+ public sealed class Known
+ {
+ public IReadOnlyCollection<string> Signals = Array.Empty<string>(), Conditions = Array.Empty<string>(),
+ Targets = Array.Empty<string>(), Screens = Array.Empty<string>(), Quotes = Array.Empty<string>();
+ public Func<string, bool> StreamingFile = _ => false;
+ }
+
+ sealed class Doc
+ {
+ public List<Advisor> Advisors { get; set; } = new List<Advisor>();
+ public List<Message> Messages { get; set; } = new List<Message>();
+ public List<Page> Pages { get; set; } = new List<Page>();
+ }
+
+ public IReadOnlyList<Advisor> Advisors { get; }
+ public IReadOnlyList<Message> Messages { get; }
+ public IReadOnlyList<Page> Pages { get; }
+ readonly Dictionary<string, Message> byId;
+ readonly Dictionary<string, Page> pageById;
+
+ AdvisorCatalog(Doc d)
+ {
+ Advisors = d.Advisors; Messages = d.Messages; Pages = d.Pages;
+ byId = new Dictionary<string, Message>(StringComparer.Ordinal);
+ foreach (var m in d.Messages) byId[m.Id] = m; // a repeated id is a problem (Problems), the last one wins here
+ pageById = new Dictionary<string, Page>(StringComparer.Ordinal);
+ foreach (var p in d.Pages) pageById[p.Id] = p;
+ }
+
+ public Message? Find(string id) => byId.TryGetValue(id, out var m) ? m : null;
+ public Page? FindPage(string id) => pageById.TryGetValue(id, out var p) ? p : null;
+ public Advisor AdvisorOf(string id) => Advisors.First(a => a.Id == id);
+
+ /// <summary>Parses the file. Throws InvalidOperationException naming it on malformed YAML or an unknown key.</summary>
+ public static AdvisorCatalog Parse(string yaml)
+ {
+ try
+ {
+ return new AdvisorCatalog(new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance)
+ .WithDuplicateKeyChecking().Build().Deserialize<Doc>(yaml ?? "") ?? new Doc());
+ }
+ catch (YamlDotNet.Core.YamlException e) { throw new InvalidOperationException($"{Path}: {e.Message}", e); }
+ }
+
+ /// <summary>The shipped file. A missing file is a build error, not a quiet game without advisors.</summary>
+ public static AdvisorCatalog Load()
+ {
+ var asset = Resources.Load<TextAsset>(ResourcePath);
+ if (asset == null) throw new InvalidOperationException($"{Path} is missing");
+ return Parse(asset.text);
+ }
+
+ /// <summary>The game's own lists, for the load test. Later tasks fill Targets (Task 8), Quotes (Task 19) and
+ /// StreamingFile (Task 23).</summary>
+ public static Known Shipped() => new Known
+ {
+ Signals = AdvisorSignals.Names.ToList(), Conditions = AdvisorSignals.Measures.Keys.ToList(),
+ Screens = ScreenNav.Screens,
+ };
+
+ /// <summary>Every problem, one line each (spec 4.1).</summary>
+ public List<string> Problems(UiText en, UiText he, Known known)
+ {
+ var p = new List<string>();
+ foreach (var id in AdvisorIds)
+ if (Advisors.Count(a => a.Id == id) != 1) p.Add($"advisors: '{id}' must be listed once");
+ foreach (var a in Advisors)
+ {
+ if (!AdvisorIds.Contains(a.Id)) p.Add($"advisors: unknown advisor '{a.Id}'");
+ if (a.Person.Trim() == "") p.Add($"advisors: '{a.Id}' names no person");
+ }
+ foreach (var g in Messages.GroupBy(m => m.Id).Where(g => g.Count() > 1)) p.Add($"{g.Key}: listed more than once");
+ foreach (var m in Messages)
+ {
+ var at = m.Id;
+ if (!IdPattern.IsMatch(m.Id)) p.Add($"{at}: an id is lower-case letters, digits, '_' and '.'");
+ if (!AdvisorIds.Contains(m.Advisor)) p.Add($"{at}: unknown advisor '{m.Advisor}'");
+ if (!known.Signals.Contains(m.Signal)) p.Add($"{at}: unknown signal '{m.Signal}'");
+ foreach (var k in m.When.Keys) if (!known.Conditions.Contains(k)) p.Add($"{at}: unknown condition '{k}'");
+ foreach (var r in m.Requires) if (!byId.ContainsKey(r)) p.Add($"{at}: requires unknown message '{r}'");
+ if (!Levels.Contains(m.Level)) p.Add($"{at}: level must be one of {string.Join(", ", Levels)}");
+ if (m.Priority < 1 || m.Priority > 3) p.Add($"{at}: priority must be 1 to 3");
+ if (m.Repeat == Once && m.CooldownTurns != 0) p.Add($"{at}: once has no cooldown_turns");
+ else if (m.Repeat == Every && m.CooldownTurns < 1) p.Add($"{at}: every needs cooldown_turns of at least 1");
+ else if (m.Repeat != Once && m.Repeat != Every) p.Add($"{at}: repeat must be once or every");
+ if (m.Actions.Count > 2) p.Add($"{at}: at most two actions");
+ foreach (var a in m.Actions) CheckAct(p, at, a, known);
+ if (m.Quote != "" && !known.Quotes.Contains(m.Quote)) p.Add($"{at}: quote '{m.Quote}' is not on the verified list (spec 3.3)");
+ if (m.DisagreesWith != "")
+ {
+ var o = Find(m.DisagreesWith);
+ if (o == null || o.Advisor == m.Advisor || o.DisagreesWith != m.Id)
+ p.Add($"{at}: disagrees_with must name another advisor's message that names this one back");
+ }
+ if (m.HeReview != Pending && m.HeReview != Approved) p.Add($"{at}: he_review must be pending or approved");
+ Text(p, en, he, at, "advisor." + m.Id + ".text", MaxWords);
+ }
+ if (Cycle() is string c) p.Add("requires has a cycle: " + c);
+ foreach (var g in Pages.GroupBy(x => x.Id).Where(g => g.Count() > 1)) p.Add($"page {g.Key}: listed more than once");
+ foreach (var page in Pages)
+ {
+ var at = "page " + page.Id;
+ if (!IdPattern.IsMatch(page.Id)) p.Add($"{at}: an id is lower-case letters, digits, '_' and '.'");
+ if (!AdvisorIds.Contains(page.Advisor)) p.Add($"{at}: unknown advisor '{page.Advisor}'");
+ if (page.ShowMe != "" && !known.Targets.Contains(page.ShowMe)) p.Add($"{at}: unknown show_me target '{page.ShowMe}'");
+ if (page.HeReview != Pending && page.HeReview != Approved) p.Add($"{at}: he_review must be pending or approved");
+ Text(p, en, he, at, "advisor.page." + page.Id + ".title", 0);
+ Text(p, en, he, at, "advisor.page." + page.Id + ".text", 0);
+ }
+ return p;
+ }
+
+ void CheckAct(List<string> p, string at, Act a, Known known)
+ {
+ int set = (a.ShowMe != "" ? 1 : 0) + (a.OpenScreen != "" ? 1 : 0) + (a.Encyclopedia != "" ? 1 : 0) + (a.OpenCard ? 1 : 0);
+ if (set != 1) p.Add($"{at}: each action names exactly one of show_me, open_screen, encyclopedia, open_card");
+ if (a.ShowMe != "" && !known.Targets.Contains(a.ShowMe)) p.Add($"{at}: unknown show_me target '{a.ShowMe}'");
+ if (a.OpenScreen != "" && !known.Screens.Contains(a.OpenScreen)) p.Add($"{at}: unknown screen '{a.OpenScreen}'");
+ if (a.Encyclopedia != "" && !pageById.ContainsKey(a.Encyclopedia)) p.Add($"{at}: unknown page '{a.Encyclopedia}'");
+ }
+
+ static void Text(List<string> p, UiText en, UiText he, string at, string key, int maxWords)
+ {
+ foreach (var (t, lang) in new[] { (en, "en"), (he, "he") })
+ {
+ if (!t.Has(key) || string.IsNullOrWhiteSpace(t[key])) { p.Add($"{at}: no {key} in strings.{lang}.yaml"); continue; }
+ if (t[key].IndexOf('\u2014') >= 0) p.Add($"{at}: {key} in strings.{lang}.yaml has an em dash");
+ }
+ if (maxWords > 0 && en.Has(key) && en[key].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length > maxWords)
+ p.Add($"{at}: {key} is over {maxWords} words");
+ }
+
+ /// <summary>The first requires cycle found, as "a -> b -> a", or null.</summary>
+ string? Cycle()
+ {
+ var state = new Dictionary<string, int>(StringComparer.Ordinal); // 1 visiting, 2 done
+ var path = new List<string>();
+ string? Visit(string id)
+ {
+ if (state.TryGetValue(id, out var s)) return s == 1 ? string.Join(" -> ", path.SkipWhile(x => x != id).Append(id)) : null;
+ state[id] = 1; path.Add(id);
+ foreach (var r in Find(id)?.Requires ?? new List<string>()) if (byId.ContainsKey(r) && Visit(r) is string c) return c;
+ path.RemoveAt(path.Count - 1); state[id] = 2;
+ return null;
+ }
+ foreach (var m in Messages) if (Visit(m.Id) is string c) return c;
+ return null;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorCatalog.cs.meta b/unity/Assets/Scripts/UI/AdvisorCatalog.cs.meta
new file mode 100644
index 000000000..4b787c528
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorCatalog.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f87ad3e229c0d495498d446e3a07dbbc
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorLayout.cs b/unity/Assets/Scripts/UI/AdvisorLayout.cs
new file mode 100644
index 000000000..7c30f12d7
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorLayout.cs
@@ -0,0 +1,48 @@
+#nullable enable
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ public enum HudTier { OneRow, TwoRow, ThreeRow }
+
+ /// <summary>Where the advisor popup goes (spec 7.1), in panel px. One and two rows: the right column's upper part,
+ /// 400 px wide, its top under the "Decision waiting" row whether or not it shows (so it never jumps), its foot 12 px
+ /// above the minimap. An upright phone (three rows): a sheet from the left column's edge to the window's right edge,
+ /// under "Decision waiting" and the toast, its foot 12 px above the higher of the info panel and the minimap's label.
+ /// Hebrew: the same place (the HUD does not mirror its panels, Statecraft.uss:943-946).</summary>
+ public static class AdvisorLayout
+ {
+ public const float Width = 400f, EdgePx = 16f, GapPx = 12f, DecisionRowPx = 46f, BelowPx = 8f;
+
+ public static HudTier Tier(VisualElement hudRoot) =>
+ hudRoot.ClassListContains(HudPresenter.ThreeRowClass) ? HudTier.ThreeRow
+ : hudRoot.ClassListContains(HudPresenter.TwoRowClass) ? HudTier.TwoRow : HudTier.OneRow;
+
+ public static Rect Slot(HudTier tier, Rect window, Rect rightColumn, Rect leftColumn, Rect minimap,
+ Rect? decisionWaiting, Rect? toast, Rect? infoPanel, Rect? mapLabel)
+ {
+ float right = window.xMax - EdgePx;
+ if (tier != HudTier.ThreeRow)
+ return Rect.MinMaxRect(right - Width, rightColumn.yMin + DecisionRowPx + BelowPx, right, minimap.yMin - GapPx);
+ float top = rightColumn.yMin;
+ if (decisionWaiting is Rect d) top = Mathf.Max(top, d.yMax + BelowPx);
+ if (toast is Rect t) top = Mathf.Max(top, t.yMax + BelowPx);
+ float floor = minimap.yMin;
+ if (mapLabel is Rect m) floor = Mathf.Min(floor, m.yMin);
+ if (infoPanel is Rect i) floor = Mathf.Min(floor, i.yMin);
+ return Rect.MinMaxRect(leftColumn.xMax + GapPx, top, right, floor - GapPx);
+ }
+
+ /// <summary>The popup's rectangle in its slot: at the top, or at the foot when that keeps it off
+ /// <paramref name="avoid"/> (Show me's target, spec 7.3); never taller than the slot.</summary>
+ public static Rect Place(Rect slot, float height, Rect? avoid)
+ {
+ float h = Mathf.Max(0f, Mathf.Min(height, slot.height));
+ var top = new Rect(slot.xMin, slot.yMin, slot.width, h);
+ if (!(avoid is Rect a) || !top.Overlaps(a)) return top;
+ var foot = new Rect(slot.xMin, slot.yMax - h, slot.width, h);
+ return foot.Overlaps(a) ? top : foot;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorLayout.cs.meta b/unity/Assets/Scripts/UI/AdvisorLayout.cs.meta
new file mode 100644
index 000000000..7018575b8
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorLayout.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8fe83a869f90f4211875db0f924fe5da
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorPresenter.cs b/unity/Assets/Scripts/UI/AdvisorPresenter.cs
new file mode 100644
index 000000000..9ede2b453
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorPresenter.cs
@@ -0,0 +1,336 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>What the advisor popup may reach outside itself. GameRoot fills it; a test leaves out what it does not use.</summary>
+ public sealed class AdvisorHooks
+ {
+ public EventCardPresenter? Card;
+ /// <summary>Opens a side screen by ScreenNav's name (an action's open_screen).</summary>
+ public Action<string>? OpenScreen;
+ }
+
+ /// <summary>The advisors' popup (spec 4.2, 7.1): one message at a time, in the right column's free upper part or a sheet
+ /// under the bar on an upright phone (AdvisorLayout). It waits while any modal layer is open (Covered) and hides at once
+ /// when one opens over it: ScreenNav.DisableCovered, which every layer calls, calls it back. Not modal: it takes no focus
+ /// when it appears, and Escape closes it only while the focus is inside it. Presentation only: it reads the state and
+ /// the bridge, writes only its settings lines, and issues no command.</summary>
+ public sealed class AdvisorPresenter : IDisposable
+ {
+ public const string OpenClass = "advisor-open", LayerName = "advisor-layer", CriticalClass = "advisor-critical",
+ NoPortraitClass = "advisor-no-portrait";
+ /// <summary>Statecraft.uss sizes (.advisor-name, .advisor-role, .advisor-text, Button, .advisor-count), in panel px,
+ /// raised where they would be under the text floor on screen (HudPresenter.FlooredTextSize).</summary>
+ public const float NamePx = 24f, RolePx = 15f, TextPx = 22f, ButtonPx = 19f, CountPx = 15f;
+ /// <summary>The fade out (Statecraft.uss .advisor-popup.window-closing), in ms.</summary>
+ public const long HideMs = 150;
+
+ readonly VisualElement hudRoot, layer, popup, portrait;
+ readonly Label name, role, words, count;
+ readonly Button showMe, more, notNow, gotIt, close;
+ readonly SimBridge bridge; readonly UiText text; readonly AdvisorSession session; readonly PortraitCatalog? portraits;
+ readonly AdvisorHooks hooks; readonly bool hebrew;
+ readonly Action onChanged, onCover, onShowMe, onGotIt, onNotNow;
+ readonly Action<IReadOnlyList<Rejection>> onTurn;
+ readonly EventCallback<GeometryChangedEvent> onLaidOut;
+ readonly (VisualElement element, float px)[] floored;
+ readonly IVisualElementScheduledItem follow;
+ /// <summary>The latest hide's fade end, paused by a Show or Dispose so an earlier one never acts.</summary>
+ IVisualElementScheduledItem? fading;
+ float flooredFor;
+ bool disposed, hidden = true;
+ /// <summary>The frame Escape closed it in (FeedbackPresenter's pattern): GameRoot's poll then knows the key is used.</summary>
+ int escapedAt = -1;
+ /// <summary>The message a layer covered, to show again or drop when the layer closes (spec 4.2).</summary>
+ AdvisorCatalog.Message? covered;
+
+ public AdvisorPresenter(VisualElement root, SimBridge bridge, UiText text, AdvisorSession session,
+ PortraitCatalog? portraits = null, AdvisorHooks? hooks = null)
+ {
+ this.bridge = bridge; this.text = text; this.session = session; this.portraits = portraits;
+ this.hooks = hooks ?? new AdvisorHooks();
+ hebrew = text["ui.lang"] == UiLanguage.Hebrew;
+ hudRoot = root.Q("root") ?? root;
+ layer = root.Q<VisualElement>(LayerName);
+ popup = layer.Q<VisualElement>("advisor-popup");
+ portrait = popup.Q<VisualElement>("advisor-portrait");
+ name = popup.Q<Label>("advisor-name"); role = popup.Q<Label>("advisor-role");
+ words = popup.Q<Label>("advisor-text"); count = popup.Q<Label>("advisor-count");
+ showMe = popup.Q<Button>("advisor-show-me"); more = popup.Q<Button>("advisor-more");
+ notNow = popup.Q<Button>("advisor-not-now"); gotIt = popup.Q<Button>("advisor-got-it"); close = popup.Q<Button>("advisor-close");
+ showMe.text = text["advisor.show_me"]; more.text = text["advisor.more"]; notNow.text = text["advisor.not_now"];
+ gotIt.text = text["advisor.got_it"]; close.text = text["advisor.close"];
+ floored = new (VisualElement, float)[] { (name, NamePx), (role, RolePx), (words, TextPx), (showMe, ButtonPx), (more, ButtonPx), (notNow, ButtonPx), (gotIt, ButtonPx), (count, CountPx) };
+ onShowMe = ShowMe; onGotIt = GotIt; onNotNow = NotNow;
+ showMe.clicked += onShowMe; gotIt.clicked += onGotIt; close.clicked += onGotIt; notNow.clicked += onNotNow;
+ onChanged = Evaluate; onTurn = _ => Notice(AdvisorSignals.TurnEnded); onCover = CoverChanged; onLaidOut = PlaceWhenLaidOut;
+ bridge.Changed += onChanged; bridge.TurnEnded += onTurn;
+ layer.userData = onCover; // ScreenNav.DisableCovered calls it
+ // The slot moves with the layout (a window resized, "Decision waiting" or the toast shown), so the popup follows
+ // it while it shows, as the guide's ring does.
+ follow = layer.schedule.Execute(Place).Every(100);
+ follow.Pause();
+ hudRoot.RemoveFromClassList(OpenClass);
+ }
+
+ /// <summary>A modal layer is open (spec 4.2): the start screen, the open decision card, the capture dialog, the turn
+ /// report, an outcome clip, the end screen; and, on the two-row HUD, any side screen (it takes the full width).</summary>
+ public static bool Covered(VisualElement hudRoot) =>
+ hudRoot.ClassListContains(StartScreenPresenter.OpenClass) || hudRoot.ClassListContains(EventCardPresenter.OpenClass)
+ || hudRoot.ClassListContains(CaptureDialogPresenter.OpenClass) || hudRoot.ClassListContains(TurnReportPresenter.OpenClass)
+ || hudRoot.ClassListContains(OutcomePresenter.OpenClass) || hudRoot.ClassListContains(EndScreenPresenter.OpenClass)
+ || (hudRoot.ClassListContains(HudPresenter.TwoRowClass) && hudRoot.ClassListContains(ScreenNav.ScreenOpenClass));
+
+ /// <summary>Showing a message: on screen and not fading out.</summary>
+ public bool IsOpen => hudRoot.ClassListContains(OpenClass) && !popup.ClassListContains(ScreenNav.ClosingClass);
+
+ /// <summary>The message on screen, or null.</summary>
+ public AdvisorCatalog.Message? Shown { get; private set; }
+
+ int Turn => bridge.State.Turn;
+ AdvisorContext Context() => new AdvisorContext(bridge, hooks.Card);
+
+ /// <summary>A new game (GameRoot: the start screen closing on New Game, or the top bar's New game): nothing waits,
+ /// the history starts empty, and new_game fires.</summary>
+ public void NewGame()
+ {
+ if (disposed) return;
+ session.Queue.Reset(); session.Fired.Clear(); session.FiredTurn = Turn;
+ Shown = null; covered = null;
+ Notice(AdvisorSignals.NewGame);
+ }
+
+ /// <summary>An event signal fired (spec 5): it holds for this turn.</summary>
+ public void Notice(string signal)
+ {
+ if (disposed) return;
+ if (session.FiredTurn != Turn) { session.Fired.Clear(); session.FiredTurn = Turn; }
+ session.Fired.Add(signal);
+ Evaluate();
+ }
+
+ /// <summary>On Changed and TurnEnded only (spec 16): offers what holds, then shows the head of the queue.</summary>
+ void Evaluate()
+ {
+ if (disposed) return;
+ if (session.AutoShow)
+ {
+ var ctx = Context();
+ session.Queue.Offer(AdvisorSignals.Holding(ctx, session), w => AdvisorSignals.When(ctx, w), Turn);
+ }
+ Render();
+ }
+
+ void Render()
+ {
+ if (disposed) return;
+ if (Covered(hudRoot)) { if (Shown != null) covered = Shown; Hide(); return; }
+ var m = session.Queue.Head(Turn, hebrew);
+ if (m == null) { Shown = null; Hide(); return; }
+ Fill(m);
+ Show();
+ }
+
+ void Fill(AdvisorCatalog.Message m)
+ {
+ Shown = m;
+ name.text = text[m.Advisor == "meyerson" && !session.Introduced(m.Advisor) ? "advisor.meyerson.name_first" : "advisor." + m.Advisor + ".name"];
+ role.text = text["advisor." + m.Advisor + ".role"];
+ words.text = text["advisor." + m.Id + ".text"];
+ var picture = portraits?.Get(session.Catalog.AdvisorOf(m.Advisor).Person);
+ popup.EnableInClassList(NoPortraitClass, picture == null);
+ portrait.style.backgroundImage = picture == null ? new StyleBackground(StyleKeyword.Null) : new StyleBackground(picture);
+ popup.EnableInClassList(CriticalClass, m.Critical);
+ Display(showMe, m.Actions.Any(a => a.ShowMe != "" || a.OpenScreen != "" || a.OpenCard));
+ Display(more, false); // Task 13: a page to open
+ Display(notNow, !m.Teaching && !m.Critical);
+ var (number, total) = session.Queue.Position(Turn, hebrew);
+ count.text = total > 1 ? text.Format("advisor.count", number, total) : "";
+ }
+
+ static void Display(VisualElement e, bool shown) => e.style.display = shown ? DisplayStyle.Flex : DisplayStyle.None;
+
+ void Show()
+ {
+ hidden = false;
+ fading?.Pause();
+ popup.RemoveFromClassList(ScreenNav.ClosingClass);
+ if (!hudRoot.ClassListContains(OpenClass))
+ {
+ // The layer was display:none, so it has no size until the next layout: unseen until Place puts it in its slot
+ // (else it would draw at the layer's top-left for a frame or more).
+ popup.style.visibility = Visibility.Hidden;
+ if (ScreenNav.Moves())
+ {
+ popup.AddToClassList(ScreenNav.OpeningClass);
+ popup.RegisterCallback<GeometryChangedEvent>(EndOpening);
+ }
+ }
+ hudRoot.AddToClassList(OpenClass);
+ follow.Resume();
+ layer.UnregisterCallback(onLaidOut);
+ if (Place(null) == null) layer.RegisterCallback(onLaidOut);
+ }
+
+ /// <summary>Once, on the layer's first layout after Show: places the popup, which makes it visible.</summary>
+ void PlaceWhenLaidOut(GeometryChangedEvent e)
+ {
+ if (Place(null) != null) layer.UnregisterCallback(onLaidOut);
+ }
+
+ void EndOpening(GeometryChangedEvent e)
+ {
+ popup.UnregisterCallback<GeometryChangedEvent>(EndOpening);
+ popup.RemoveFromClassList(ScreenNav.OpeningClass);
+ }
+
+ void Hide()
+ {
+ if (hidden) return;
+ hidden = true;
+ follow.Pause();
+ layer.UnregisterCallback(onLaidOut);
+ var focused = layer.focusController?.focusedElement as VisualElement;
+ if (focused != null && layer.Contains(focused)) { focused.Blur(); FocusReturn.To(hudRoot.Q<Button>("end-turn")); }
+ if (!ScreenNav.Moves()) { hudRoot.RemoveFromClassList(OpenClass); return; }
+ popup.AddToClassList(ScreenNav.ClosingClass);
+ fading?.Pause();
+ fading = popup.schedule.Execute(() =>
+ {
+ if (!hidden) return; // shown again meanwhile
+ popup.RemoveFromClassList(ScreenNav.ClosingClass);
+ hudRoot.RemoveFromClassList(OpenClass);
+ }).StartingIn(HideMs);
+ }
+
+ /// <summary>ScreenNav.DisableCovered: a layer opened (hide at once) or closed (the covered message comes back if its
+ /// signal still holds this turn, else it goes to the history; spec 4.2).</summary>
+ void CoverChanged()
+ {
+ if (disposed) return;
+ if (Covered(hudRoot)) { if (Shown != null) covered = Shown; Hide(); return; }
+ if (covered is AdvisorCatalog.Message m)
+ {
+ covered = null;
+ var ctx = Context();
+ if (!(AdvisorSignals.Holding(ctx, session).Contains(m.Signal) && AdvisorSignals.When(ctx, m.When)))
+ session.Queue.Drop(m, Turn, bridge.State.Date);
+ }
+ Render();
+ }
+
+ void ShowMe()
+ {
+ if (Shown == null) return;
+ foreach (var a in Shown.Actions)
+ if (a.OpenScreen != "") hooks.OpenScreen?.Invoke(a.OpenScreen);
+ else if (a.OpenCard && hooks.Card?.Shown != null) hooks.Card.Reopen();
+ }
+
+ /// <summary>Got it, the X, or Escape from inside: seen, and the next message (if any) shows.</summary>
+ public void GotIt()
+ {
+ if (Shown == null || !IsOpen) return; // not while it fades out under a new layer
+ session.Queue.Done(Shown, Turn, bridge.State.Date);
+ Shown = null;
+ Render();
+ }
+
+ /// <summary>Not now: off to the next turn and into Counsel's history (spec 7.1). Not for teaching or critical messages.</summary>
+ public void NotNow()
+ {
+ if (Shown == null || !IsOpen || Shown.Teaching || Shown.Critical) return;
+ session.Queue.PutOff(Shown, Turn, bridge.State.Date);
+ Shown = null;
+ Render();
+ }
+
+ /// <summary>Escape: closes it as the X does, only while the focus is inside it (spec 16). True when it did, and
+ /// also in the frame ScreenNav's Cancel already closed it, so GameRoot's poll does not close the screen under it too.
+ /// That frame check comes first: Got it can bring the next message up at once, and one Escape dismisses one message.</summary>
+ public bool Escape()
+ {
+ if (escapedAt == Time.frameCount) return true;
+ var focused = layer.focusController?.focusedElement as VisualElement;
+ if (!IsOpen || focused == null || !popup.Contains(focused)) return false;
+ escapedAt = Time.frameCount;
+ GotIt();
+ return true;
+ }
+
+ /// <summary>The slot in the layer's space (AdvisorLayout.Slot from the HUD as it is laid out now).</summary>
+ internal Rect Slot()
+ {
+ Rect L(string n) => Local(hudRoot.Q(n)!.worldBound);
+ Rect? Visible(string n) { var e = hudRoot.Q(n); return e != null && e.resolvedStyle.display == DisplayStyle.Flex && e.worldBound.width > 0 ? Local(e.worldBound) : (Rect?)null; }
+ var window = new Rect(Vector2.zero, layer.layout.size);
+ return AdvisorLayout.Slot(AdvisorLayout.Tier(hudRoot), window, L("right-column"), L("left-column"), L("minimap"),
+ Visible("event-reopen"), Visible("toast"), Visible("info-panel"), Visible("map-layer"));
+ }
+
+ Rect Local(Rect world)
+ {
+ var min = layer.WorldToLocal(world.min); var max = layer.WorldToLocal(world.max);
+ return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
+ }
+
+ /// <summary>In its slot, at the top (Task 8 passes Show me's target to keep it off), with the text floor applied.</summary>
+ internal void Place() => Place(null);
+
+ /// <summary>Places the popup and returns where (in the layer's space), or null when it is not shown or not laid out.</summary>
+ internal Rect? Place(Rect? avoid)
+ {
+ if (!hudRoot.ClassListContains(OpenClass) || layer.panel == null || !(layer.layout.width > 0)) return null;
+ ApplyTextFloor();
+ var slot = OnPixels(Slot());
+ var at = AdvisorLayout.Place(slot, popup.resolvedStyle.height > 0 ? popup.resolvedStyle.height : slot.height, avoid);
+ popup.style.left = at.xMin; popup.style.top = at.yMin;
+ popup.style.width = Mathf.Max(0f, at.width); popup.style.maxHeight = Mathf.Max(0f, slot.height);
+ popup.style.visibility = Visibility.Visible;
+ return at;
+ }
+
+ /// <summary>The slot shrunk to whole screen pixels: the layout rounds each edge to the nearest one, which on a small
+ /// window (2.5 panel px a pixel at 844 x 390) would push the popup's edges past the slot's.</summary>
+ Rect OnPixels(Rect r)
+ {
+ float s = layer.panel.scaledPixelsPerPoint;
+ if (!(s > 0f)) return r;
+ var o = layer.worldBound.position;
+ float In(float v, float origin) => Mathf.Ceil((v + origin) * s - 0.01f) / s - origin;
+ float Out(float v, float origin) => Mathf.Floor((v + origin) * s + 0.01f) / s - origin;
+ return Rect.MinMaxRect(In(r.xMin, o.x), In(r.yMin, o.y), Out(r.xMax, o.x), Out(r.yMax, o.y));
+ }
+
+ void ApplyTextFloor()
+ {
+ var scale = HudPresenter.ScreenPxPerPanelPx(layer.panel);
+ if (scale == flooredFor) return;
+ flooredFor = scale;
+ foreach (var (element, px) in floored)
+ {
+ var size = HudPresenter.FlooredTextSize(px, scale);
+ element.style.fontSize = size > px ? new StyleLength(size) : new StyleLength(StyleKeyword.Null);
+ }
+ }
+
+ public void Dispose()
+ {
+ if (disposed) return;
+ disposed = true;
+ follow.Pause();
+ fading?.Pause();
+ layer.UnregisterCallback(onLaidOut);
+ bridge.Changed -= onChanged; bridge.TurnEnded -= onTurn;
+ if (layer.userData == (object)onCover) layer.userData = null;
+ showMe.clicked -= onShowMe; gotIt.clicked -= onGotIt; close.clicked -= onGotIt; notNow.clicked -= onNotNow;
+ hudRoot.RemoveFromClassList(OpenClass);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorPresenter.cs.meta b/unity/Assets/Scripts/UI/AdvisorPresenter.cs.meta
new file mode 100644
index 000000000..c1d1c8e7e
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorPresenter.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b2ac67bde6fd54ded8b0321e748f6b13
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorQueue.cs b/unity/Assets/Scripts/UI/AdvisorQueue.cs
new file mode 100644
index 000000000..c84eb5e49
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorQueue.cs
@@ -0,0 +1,124 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The messages waiting to show (spec 4.2): critical first, then the higher priority, then the order the signals
+ /// fired. At most one teaching message and one non-critical warning show by themselves a turn; the rest wait for the
+ /// next turn or Counsel. A critical message is never held back (spec 6: the advisors never stay silent on a real
+ /// threat). Filters by the help level and, in Hebrew, by approval (OQ-4) when it is asked, so a Settings change or a
+ /// language switch applies at once. Keeps this game's history for Counsel (spec 7.4); none of it is saved.</summary>
+ public sealed class AdvisorQueue
+ {
+ public enum Outcome { Shown, PutOff, Missed }
+
+ public readonly struct Entry
+ {
+ public Entry(string id, int turn, DateTime date, Outcome outcome) { Id = id; Turn = turn; Date = date; Outcome = outcome; }
+ public string Id { get; }
+ public int Turn { get; }
+ public DateTime Date { get; }
+ public Outcome Outcome { get; }
+ }
+
+ sealed class Waiting { public AdvisorCatalog.Message M = null!; public int Seq; public int NotBefore; public bool PutOff; }
+
+ readonly AdvisorCatalog catalog; readonly AdvisorSettings settings;
+ readonly List<Waiting> waiting = new List<Waiting>();
+ readonly List<Entry> history = new List<Entry>();
+ readonly Dictionary<string, int> lastShown = new Dictionary<string, int>(StringComparer.Ordinal);
+ int seq, capTurn = int.MinValue, shownThisTurn;
+ bool teachingShown, warningShown;
+
+ public AdvisorQueue(AdvisorCatalog catalog, AdvisorSettings settings) { this.catalog = catalog; this.settings = settings; }
+
+ public IReadOnlyList<Entry> History => history;
+ public IEnumerable<string> PutOffIds => waiting.Where(w => w.PutOff).Select(w => w.M.Id);
+
+ /// <summary>Queues each message whose signal holds now and whose condition holds, unless it is already waiting, is
+ /// filtered out (Eligible) or waits on a message not yet seen.</summary>
+ public void Offer(IReadOnlyCollection<string> holding, Func<IReadOnlyDictionary<string, double>, bool> when, int turn)
+ {
+ foreach (var m in catalog.Messages)
+ {
+ if (!holding.Contains(m.Signal) || waiting.Any(w => w.M == m)) continue;
+ if (!Eligible(m, turn) || !when(m.When)) continue;
+ waiting.Add(new Waiting { M = m, Seq = seq++, NotBefore = turn });
+ }
+ }
+
+ bool Eligible(AdvisorCatalog.Message m, int turn) =>
+ Array.IndexOf(AdvisorCatalog.Levels, m.Level) >= settings.LevelRank
+ && (m.Repeat == AdvisorCatalog.Once ? !settings.Seen(m.Id) : !(lastShown.TryGetValue(m.Id, out var t) && turn < t + m.CooldownTurns))
+ && m.Requires.All(settings.Seen);
+
+ void Caps(int turn)
+ {
+ if (turn == capTurn) return;
+ capTurn = turn; teachingShown = warningShown = false; shownThisTurn = 0;
+ }
+
+ bool UnderCap(AdvisorCatalog.Message m) => m.Critical || !(m.Teaching ? teachingShown : warningShown);
+
+ IEnumerable<AdvisorCatalog.Message> Showable(int turn, bool hebrew)
+ {
+ Caps(turn);
+ return waiting.Where(w => w.NotBefore <= turn && Eligible(w.M, turn) && w.M.ApprovedIn(hebrew) && UnderCap(w.M))
+ .OrderByDescending(w => w.M.Critical).ThenByDescending(w => w.M.Priority).ThenBy(w => w.Seq).Select(w => w.M);
+ }
+
+ public AdvisorCatalog.Message? Head(int turn, bool hebrew) => Showable(turn, hebrew).FirstOrDefault();
+
+ /// <summary>The counter (spec 7.1, "1 of 3"): this one's place among those shown this turn and those still showable.</summary>
+ public (int number, int total) Position(int turn, bool hebrew)
+ {
+ var left = Showable(turn, hebrew).ToList();
+ // At most one more teaching and one more warning can follow by themselves, however many wait.
+ int more = left.Count(m => m.Critical) + (left.Any(m => !m.Critical && m.Teaching) ? 1 : 0) + (left.Any(m => !m.Critical && !m.Teaching) ? 1 : 0);
+ return (shownThisTurn + 1, shownThisTurn + more);
+ }
+
+ /// <summary>Got it or the X: seen (once), or its cooldown starts (every); it uses its kind's slot; into the history.</summary>
+ public void Done(AdvisorCatalog.Message m, int turn, DateTime date)
+ {
+ Take(m, turn);
+ if (m.Repeat == AdvisorCatalog.Once) settings.MarkSeen(m.Id); else lastShown[m.Id] = turn;
+ history.Add(new Entry(m.Id, turn, date, Outcome.Shown));
+ }
+
+ /// <summary>Not now: off to the next turn, and into the history as put off. A critical message has no Not now.</summary>
+ public void PutOff(AdvisorCatalog.Message m, int turn, DateTime date)
+ {
+ if (m.Critical) throw new InvalidOperationException($"{m.Id} is critical: it has no Not now");
+ Take(m, turn);
+ waiting.Add(new Waiting { M = m, Seq = seq++, NotBefore = turn + 1, PutOff = true });
+ history.Add(new Entry(m.Id, turn, date, Outcome.PutOff));
+ }
+
+ /// <summary>A layer covered it and its signal no longer holds when the layer closed (spec 4.2): into the history,
+ /// not shown again now, and not marked seen, so its signal can bring it back later.</summary>
+ public void Drop(AdvisorCatalog.Message m, int turn, DateTime date)
+ {
+ waiting.RemoveAll(w => w.M == m);
+ history.Add(new Entry(m.Id, turn, date, Outcome.Missed));
+ }
+
+ void Take(AdvisorCatalog.Message m, int turn)
+ {
+ Caps(turn);
+ waiting.RemoveAll(w => w.M == m);
+ shownThisTurn++;
+ if (m.Critical) return;
+ if (m.Teaching) teachingShown = true; else warningShown = true;
+ }
+
+ /// <summary>A new or loaded game: nothing waits and the history starts empty (the seen marks stay: they are the player's).</summary>
+ public void Reset()
+ {
+ waiting.Clear(); history.Clear(); lastShown.Clear();
+ capTurn = int.MinValue; shownThisTurn = 0; teachingShown = warningShown = false;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorQueue.cs.meta b/unity/Assets/Scripts/UI/AdvisorQueue.cs.meta
new file mode 100644
index 000000000..d92ae2bba
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorQueue.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6296c6b0213f641bd923059b0634053e
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorSession.cs b/unity/Assets/Scripts/UI/AdvisorSession.cs
new file mode 100644
index 000000000..f088f088b
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSession.cs
@@ -0,0 +1,31 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>What the advisors keep for one game in one sitting: the catalogue, the settings lines, the queue and its
+ /// history, and the event signals fired this turn. GameRoot keeps it across a language switch (Begin's keep) and makes
+ /// a new one for a loaded game; NewGame resets it. Nothing of it is saved (spec 15).</summary>
+ public sealed class AdvisorSession
+ {
+ /// <param name="autoShow">Whether messages show by themselves: only where the start screen shows and a settings file
+ /// remembers what was seen (never in automated runs). Kept with the session, so a language switch (whose Begin
+ /// shows no start screen) does not silence them.</param>
+ public AdvisorSession(AdvisorCatalog catalog, AdvisorSettings settings, bool autoShow)
+ {
+ Catalog = catalog; Settings = settings; AutoShow = autoShow; Queue = new AdvisorQueue(catalog, settings);
+ }
+
+ public bool AutoShow { get; }
+ public AdvisorCatalog Catalog { get; }
+ public AdvisorSettings Settings { get; }
+ public AdvisorQueue Queue { get; }
+ /// <summary>The event signals fired on <see cref="FiredTurn"/>; they hold for that turn only.</summary>
+ public HashSet<string> Fired { get; } = new HashSet<string>(StringComparer.Ordinal);
+ public int FiredTurn { get; set; } = -1;
+ /// <summary>Whether Meyerson has been named in full once this profile (her first appearance, spec 3.1), by her seen marks.</summary>
+ public bool Introduced(string advisor) =>
+ advisor != "meyerson" || System.Linq.Enumerable.Any(Catalog.Messages, m => m.Advisor == advisor && Settings.Seen(m.Id));
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorSession.cs.meta b/unity/Assets/Scripts/UI/AdvisorSession.cs.meta
new file mode 100644
index 000000000..afb80bbee
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSession.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 912c5c06483e340e6b792f96ccb5f1d0
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorSettings.cs b/unity/Assets/Scripts/UI/AdvisorSettings.cs
new file mode 100644
index 000000000..a614c6246
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSettings.cs
@@ -0,0 +1,68 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using UnityEngine;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The advisors' lines in the settings file (spec 15; SettingsStore: presentation only, never the sim or the
+ /// save): the help level, the messages seen (one line, advisor_seen=a,b,c) and the opening chain's mark. The marks
+ /// are also kept in memory, so a failed write (logged) or no file at all (automated runs) only costs persistence.</summary>
+ public sealed class AdvisorSettings
+ {
+ public const string LevelKey = "advisor_level", SeenKey = "advisor_seen", OpeningKey = "advisor_opening";
+ /// <summary>The first-turn guide's line (spec 9.3: honoured, so a player who saw the guide gets no chain by itself).</summary>
+ public const string GuideSeenKey = "first_turn_guide";
+ /// <summary>Spec 6, from the chattiest; a message shows when its level's index (AdvisorCatalog.Levels) is at least this one's.</summary>
+ public static readonly string[] Levels = { "new", "experienced", "warnings", "off" };
+
+ readonly SettingsStore? store;
+ readonly SortedSet<string> seen = new SortedSet<string>(StringComparer.Ordinal);
+ bool openingSeen;
+
+ public AdvisorSettings(SettingsStore? store)
+ {
+ this.store = store;
+ var stored = store?.Read(LevelKey);
+ Level = Array.IndexOf(Levels, stored) >= 0 ? stored! : Levels[0];
+ foreach (var id in (store?.Read(SeenKey) ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) seen.Add(id);
+ openingSeen = store?.Read(OpeningKey) == "seen" || store?.Read(GuideSeenKey) == "seen";
+ }
+
+ /// <summary>A settings file exists to remember the marks in (none in automated runs and EditMode tests).</summary>
+ public bool HasFile => store != null;
+ public string Level { get; private set; }
+ public int LevelRank => Array.IndexOf(Levels, Level);
+
+ public void SetLevel(string level)
+ {
+ if (Array.IndexOf(Levels, level) < 0) throw new ArgumentException("unknown help level: " + level, nameof(level));
+ Level = level;
+ Write(LevelKey, level);
+ }
+
+ public bool Seen(string id) => seen.Contains(id);
+
+ public void MarkSeen(string id)
+ {
+ if (!seen.Add(id)) return;
+ Write(SeenKey, string.Join(",", seen));
+ }
+
+ public bool OpeningSeen => openingSeen;
+
+ public void MarkOpeningSeen()
+ {
+ openingSeen = true;
+ Write(OpeningKey, "seen");
+ }
+
+ void Write(string key, string value)
+ {
+ if (store == null) return;
+ try { store.Write(key, value); }
+ catch (Exception e) { Debug.LogWarning($"The advisors could not save {key}: {e.Message}"); }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorSettings.cs.meta b/unity/Assets/Scripts/UI/AdvisorSettings.cs.meta
new file mode 100644
index 000000000..02b9b8a90
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSettings.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7b65d16cd5e664cf6863170a1cb2a4b2
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/AdvisorSignals.cs b/unity/Assets/Scripts/UI/AdvisorSignals.cs
new file mode 100644
index 000000000..d5ddbe2e5
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSignals.cs
@@ -0,0 +1,44 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The signals a message waits for (spec 5). Event signals are raised by a call (AdvisorPresenter.Notice) and
+ /// hold for the turn they fired on; state signals hold while the shown state says so and are read on Changed and
+ /// TurnEnded only, never each frame (spec 16). A `when` condition measures one number on the state.</summary>
+ public static class AdvisorSignals
+ {
+ public const string NewGame = "new_game", TurnEnded = "turn_ended";
+ public static readonly IReadOnlyCollection<string> Events = new[] { NewGame, TurnEnded };
+ public static readonly IReadOnlyDictionary<string, Func<AdvisorContext, bool>> States = new Dictionary<string, Func<AdvisorContext, bool>>();
+ /// <summary>Each condition's measure; a name ends in _at_least or _at_most, which says how its bound reads.</summary>
+ public static readonly IReadOnlyDictionary<string, Func<AdvisorContext, double>> Measures = new Dictionary<string, Func<AdvisorContext, double>>();
+ public static IEnumerable<string> Names => Events.Concat(States.Keys);
+
+ /// <summary>Whether a message's `when` holds: each named measure against its bound (spec 4.1).</summary>
+ public static bool When(AdvisorContext ctx, IReadOnlyDictionary<string, double> when) =>
+ when.All(kv => kv.Key.EndsWith("_at_least", StringComparison.Ordinal)
+ ? Measures[kv.Key](ctx) >= kv.Value - 1e-9
+ : Measures[kv.Key](ctx) <= kv.Value + 1e-9);
+
+ /// <summary>The signals that hold now: this turn's event signals, and each state signal whose reading is true.</summary>
+ public static HashSet<string> Holding(AdvisorContext ctx, AdvisorSession session)
+ {
+ var holding = new HashSet<string>(session.FiredTurn == ctx.State.Turn ? session.Fired : Enumerable.Empty<string>(), StringComparer.Ordinal);
+ foreach (var kv in States) if (kv.Value(ctx)) holding.Add(kv.Key);
+ return holding;
+ }
+ }
+
+ /// <summary>What a signal reads: the content, the state the screen shows, the bridge and the decision card.</summary>
+ public sealed class AdvisorContext
+ {
+ public AdvisorContext(SimBridge bridge, EventCardPresenter? card) { Bridge = bridge; Card = card; }
+ public SimBridge Bridge { get; }
+ public EventCardPresenter? Card { get; }
+ public Statecraft.Sim.Content Content => Bridge.Content;
+ public Statecraft.Sim.GameState State => Bridge.State;
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorSignals.cs.meta b/unity/Assets/Scripts/UI/AdvisorSignals.cs.meta
new file mode 100644
index 000000000..00fff2e33
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorSignals.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d6decf44eec5f43a38fc419cc2fa2100
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 2ef696b01..995c28ddc 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -70,6 +70,10 @@ namespace Statecraft.Game.UI
FirstTurnGuidePresenter? guide;
/// <summary>Tests: the first-turn guide of the last Begin.</summary>
internal FirstTurnGuidePresenter? Guide => guide;
+ AdvisorPresenter? advisor;
+ /// <summary>Tests: the advisors' popup of the last Begin, and their session (kept across a language switch).</summary>
+ internal AdvisorPresenter? Advisor => advisor;
+ internal AdvisorSession? AdvisorSession { get; private set; }
FeedbackPresenter? feedback;
SharePresenter? share;
InfoPanelPresenter? info;
@@ -297,7 +301,7 @@ namespace Statecraft.Game.UI
// Star, Report and Share as round icons at the map screen's bottom left (#1236): the same actions as Settings' buttons.
Own(new CommunityIconsPresenter(root, text, feedbackPanel, sharePanel));
// Both panels in one hook: the same Escape never closes the screen under the panel too.
- nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape();
+ nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape() || advisor?.Escape() == true;
var names = map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.Name); // the map's parse (issue #321)
// The capture dialog (GDD Phase 6 PR 10, #802): in the decision layer, after the card, which goes first; the
// places' Hebrew names from the same parse.
@@ -465,7 +469,7 @@ namespace Statecraft.Game.UI
start = Own(new StartScreenPresenter(root, newGame!, resumed, shown =>
{
if (cam != null) cam.enabled = !shown;
- if (!shown && start?.Resumed == false) firstTurn?.NewGame();
+ if (!shown && start?.Resumed == false) { firstTurn?.NewGame(); advisor?.NewGame(); }
}, recording, text));
start.Show();
}
@@ -513,6 +517,18 @@ namespace Statecraft.Game.UI
guide = firstTurn = Own(new FirstTurnGuidePresenter(root, text, showsStart && !FirstCardCheckRequested() ? SettingsFile() : null,
card, showCity, () => nav?.Close(), bridge, keepSelection, showUnit));
if (newGame != null) newGame.Started += firstTurn.NewGame; // New Game in the top bar too; both die with this Begin
+ // The advisors (spec 4.2): their session survives a rebuild over the same game (a language switch keeps the
+ // queue, the history and the opening chain's place) and is new for any other Begin. They show by themselves only
+ // where the guide does: the start screen shows and a settings file remembers what was seen.
+ if (keep == null || AdvisorSession == null)
+ {
+ bool autoShow = showsStart && !FirstCardCheckRequested() && SettingsFile() != null;
+ // As the guide's: no settings file for an automated run, which then never reads or writes the player's.
+ AdvisorSession = new AdvisorSession(AdvisorCatalog.Load(), new AdvisorSettings(autoShow ? SettingsFile() : null), autoShow);
+ }
+ advisor = Own(new AdvisorPresenter(root, bridge, text, AdvisorSession, portraits,
+ new AdvisorHooks { Card = card, OpenScreen = s => nav?.Open(s) }));
+ if (newGame != null) newGame.Started += advisor.NewGame;
if (hebrew) Own(new UiDirection(root, bridge));
root.Q("root")?.RemoveFromClassList("loading"); // ready: the bar, panels and screens may show (P2-1)
DiagLog.BootPhase("screens ready");
@@ -625,7 +641,7 @@ namespace Statecraft.Game.UI
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
if (hoveredCity != null) { hoveredCity = null; HandCursor(false); } // the next Begin's pills start unlit
- minimap = null; labels = null; nav = null; start = null; card = null; outcomes = null; report = null; end = null; guide = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;
+ minimap = null; labels = null; nav = null; start = null; card = null; outcomes = null; report = null; end = null; guide = null; advisor = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;
// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at the
// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.
if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
@@ -768,7 +784,8 @@ namespace Statecraft.Game.UI
// takes the Cancel event when it has the focus), and so on the open capture dialog (CaptureDialogPresenter.Escape),
// which shows only while the card does not.
// The report panel (#1169) and the share panel (#1170) are over everything: their Escape goes no further.
- if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true && feedback?.Escape() != true && share?.Escape() != true) { bool done = outcomes?.SkipAll() == true || outcomes?.ClosedThisFrame == true; if (!done) done = end?.Close() == true || end?.ClosedThisFrame == true; if (!done) done = report?.Close() == true || report?.ClosedThisFrame == true; done |= start?.Escape() == true; done |= nav?.Close() == true; if (!done) done = guide?.Escape() == true; if (!done && document.rootVisualElement.focusController?.focusedElement == null && capture?.Escape() != true) card?.Escape(); }
+ // Nor does the advisors' popup's, with the focus inside it (AdvisorPresenter.Escape, also in the frame its Cancel closed it).
+ if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true && feedback?.Escape() != true && share?.Escape() != true && advisor?.Escape() != true) { bool done = outcomes?.SkipAll() == true || outcomes?.ClosedThisFrame == true; if (!done) done = end?.Close() == true || end?.ClosedThisFrame == true; if (!done) done = report?.Close() == true || report?.ClosedThisFrame == true; done |= start?.Escape() == true; done |= nav?.Close() == true; if (!done) done = guide?.Escape() == true; if (!done && document.rootVisualElement.focusController?.focusedElement == null && capture?.Escape() != true) card?.Escape(); }
// PageUp, PageDown, Home and End, with no modifier, scroll the open screen or the open card's text, with or without
// focus (KeyScroll; accessibility audit H3), but not under an End Turn outcome clip, which covers them. The arrows
// stay with the camera (NavigationGuard, B6).
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs b/unity/Assets/Scripts/UI/ScreenNav.cs
index 8ac4a87c6..ee98513f8 100644
--- a/unity/Assets/Scripts/UI/ScreenNav.cs
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs
@@ -78,6 +78,9 @@ namespace Statecraft.Game.UI
over.SetEnabled(now);
if (!was && now) (over.userData as System.Action)?.Invoke(); // EndScreenPresenter: Close takes the focus
}
+ // The advisors' popup (spec 4.2) hides under every layer above and comes back when they close: every layer calls
+ // this method when its class changes, so the popup needs no class of its own here.
+ (r.Q(AdvisorPresenter.LayerName)?.userData as System.Action)?.Invoke();
}
/// <summary>Asks to be told, synchronously, whenever the decision layer comes out from under the start screen, a
diff --git a/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs
new file mode 100644
index 000000000..e4cdbedcc
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs
@@ -0,0 +1,108 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>The advisors' data file (spec 4.1): it parses, and the checks name every broken row, so a bad row fails here
+/// and never at a player's turn.</summary>
+public class AdvisorCatalogTests
+{
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
+
+ const string Head = "advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\n";
+
+ static readonly AdvisorCatalog.Known Fixture = new AdvisorCatalog.Known
+ {
+ Signals = new[] { "new_game", "turn_ended" }, Conditions = new[] { "debt_ratio_at_least" },
+ Targets = new[] { "attention" }, Screens = new[] { "budget" }, Quotes = new[] { "q1" },
+ };
+
+ static UiText Strings(params string[] keys) =>
+ UiText.Parse("ui.lang: en\n" + string.Join("", keys.Select(k => k + ": \"One short line.\"\n")));
+
+ static List<string> ProblemsOf(string messages, params string[] keys) =>
+ AdvisorCatalog.Parse(Head + messages).Problems(Strings(keys), Strings(keys), Fixture);
+
+ [Test]
+ public void ParsesAMessageWithEveryField()
+ {
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: a.one, advisor: meyerson, signal: turn_ended, when: { debt_ratio_at_least: 0.8 }, " +
+ "level: warnings, priority: 2, repeat: every, cooldown_turns: 3, actions: [{ show_me: attention }, { open_screen: budget }], he_review: approved }\n");
+ var m = c.Find("a.one")!;
+ Assert.AreEqual(("meyerson", "turn_ended", "warnings", 2, "every", 3), (m.Advisor, m.Signal, m.Level, m.Priority, m.Repeat, m.CooldownTurns));
+ Assert.AreEqual(0.8, m.When["debt_ratio_at_least"], 1e-9);
+ CollectionAssert.AreEqual(new[] { "attention", "" }, m.Actions.Select(a => a.ShowMe).ToArray());
+ Assert.IsFalse(m.Teaching); Assert.IsFalse(m.Critical);
+ Assert.IsTrue(m.ApprovedIn(hebrew: true));
+ Assert.IsEmpty(ProblemsOf("messages:\n - { id: a.one, advisor: meyerson, signal: turn_ended, level: new, he_review: pending }\n", "advisor.a.one.text"));
+ }
+
+ [TestCase("{ id: Bad Id, advisor: dayan, signal: new_game, level: new }", "lower-case letters")]
+ [TestCase("{ id: x, advisor: golda, signal: new_game, level: new }", "unknown advisor 'golda'")]
+ [TestCase("{ id: x, advisor: dayan, signal: moon, level: new }", "unknown signal 'moon'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, when: { tide_at_least: 1 } }", "unknown condition 'tide_at_least'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: loud }", "level must be one of")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, priority: 4 }", "priority must be 1 to 3")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, repeat: every }", "every needs cooldown_turns")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, cooldown_turns: 2 }", "once has no cooldown_turns")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, requires: [nobody] }", "requires unknown message 'nobody'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, actions: [{ show_me: moon }] }", "unknown show_me target 'moon'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, actions: [{ open_screen: moon }] }", "unknown screen 'moon'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, actions: [{ encyclopedia: moon }] }", "unknown page 'moon'")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, actions: [{ show_me: attention, open_screen: budget }] }", "exactly one of")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, actions: [{ open_card: true }, { open_card: true }, { open_card: true }] }", "at most two actions")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, quote: q9 }", "not on the verified list")]
+ [TestCase("{ id: x, advisor: dayan, signal: new_game, level: new, he_review: maybe }", "he_review must be")]
+ public void EachBrokenRowIsNamed(string row, string expected)
+ {
+ var problems = ProblemsOf("messages:\n - " + row + "\n", "advisor.x.text", "advisor.Bad Id.text");
+ Assert.IsTrue(problems.Any(p => p.Contains(expected)), $"expected '{expected}' in:\n{string.Join("\n", problems)}");
+ }
+
+ [Test]
+ public void TextIsCheckedInBothLanguages()
+ {
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new }\n");
+ var en = UiText.Parse("advisor.x.text: \"" + string.Join(" ", Enumerable.Repeat("word", 36)) + "\"\n");
+ var he = UiText.Parse("other: \"x\"\n");
+ var problems = c.Problems(en, he, Fixture);
+ Assert.IsTrue(problems.Any(p => p.Contains("over 35 words")), string.Join("\n", problems));
+ Assert.IsTrue(problems.Any(p => p.Contains("no advisor.x.text in strings.he.yaml")), string.Join("\n", problems));
+ var dash = UiText.Parse("advisor.x.text: \"One \u2014 two.\"\n");
+ Assert.IsTrue(c.Problems(dash, dash, Fixture).Any(p => p.Contains("em dash")));
+ }
+
+ [Test]
+ public void RequiresHasNoCycleAndDisagreementIsMutual()
+ {
+ var cycle = ProblemsOf("messages:\n - { id: a, advisor: dayan, signal: new_game, level: new, requires: [b] }\n" +
+ " - { id: b, advisor: dayan, signal: new_game, level: new, requires: [a] }\n", "advisor.a.text", "advisor.b.text");
+ Assert.IsTrue(cycle.Any(p => p.Contains("requires has a cycle")), string.Join("\n", cycle));
+ var oneWay = ProblemsOf("messages:\n - { id: a, advisor: dayan, signal: new_game, level: warnings, disagrees_with: b }\n" +
+ " - { id: b, advisor: meyerson, signal: new_game, level: warnings }\n", "advisor.a.text", "advisor.b.text");
+ Assert.IsTrue(oneWay.Any(p => p.Contains("names this one back")), string.Join("\n", oneWay));
+ }
+
+ [Test]
+ public void EveryAdvisorIsListedOnce()
+ {
+ var c = AdvisorCatalog.Parse("advisors:\n - { id: dayan, person: dayan }\n - { id: dayan, person: dayan }\nmessages: []\n");
+ var problems = c.Problems(Strings(), Strings(), Fixture);
+ foreach (var expected in new[] { "'ben_gurion' must be listed once", "'meyerson' must be listed once", "'dayan' must be listed once" })
+ Assert.IsTrue(problems.Any(p => p.Contains(expected)), expected);
+ }
+
+ /// <summary>Spec 4.1's load test: the shipped file, against the game's own signals, targets, screens, quotes and files.</summary>
+ [Test]
+ public void TheShippedFileHasNoProblems()
+ {
+ var c = AdvisorCatalog.Load();
+ CollectionAssert.AreEqual(AdvisorCatalog.AdvisorIds, c.Advisors.Select(a => a.Id).ToArray());
+ var problems = c.Problems(En, He, AdvisorCatalog.Shipped());
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs.meta
new file mode 100644
index 000000000..df88756ce
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5549aadd1671043bfbaef6a1b2d652fd
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorGameTests.cs b/unity/Assets/Tests/EditMode/AdvisorGameTests.cs
new file mode 100644
index 000000000..cbaeb50d7
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorGameTests.cs
@@ -0,0 +1,107 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+
+/// <summary>The advisors in the game as a player boots it: built in every Begin, silent in automated runs, kept across a
+/// language switch, and never touching the sim or the save.</summary>
+public class AdvisorGameTests
+{
+ static GameInputs? inputs;
+ static GameInputs Inputs => inputs ??= GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ static VisualElement Ui => Object.FindFirstObjectByType<UIDocument>().rootVisualElement;
+ readonly List<string> temp = new List<string>();
+ string TempDir() { var d = Path.Combine(Path.GetTempPath(), "statecraft-adv-" + Guid.NewGuid().ToString("N")); temp.Add(d); return d; }
+
+ [TearDown]
+ public void Clean()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ foreach (var d in temp) { try { if (Directory.Exists(d)) Directory.Delete(d, true); } catch (Exception) { } }
+ temp.Clear();
+ }
+
+ internal static GameRoot OpenScene(SaveStore store, SettingsStore? settings)
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = store; root.Settings = settings;
+ return root;
+ }
+
+ [Test]
+ public void EveryBeginBuildsTheAdvisorsAndAutomatedRunsStaySilent()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0); // the tools' Begin: no start screen
+ Assert.IsFalse(game.AdvisorSession!.AutoShow, "no start screen: never by itself");
+ Assert.IsNotNull(game.Advisor);
+ Assert.IsNotNull(Ui.Q(AdvisorPresenter.LayerName).userData, "the cover hook is set");
+ Ui.Q<Button>("end-turn").Focus();
+ game.Bridge!.EndTurn();
+ Assert.IsFalse(game.Advisor!.IsOpen, "no start screen: never by itself");
+ Assert.IsEmpty(game.AdvisorSession!.Queue.History);
+ }
+
+ /// <summary>With the start screen but no settings file to remember what was seen, they never show by themselves.</summary>
+ [Test]
+ public void NoSettingsFileMeansSilentEvenWithTheStartScreen()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), null);
+ game.Begin(Inputs, 0, startScreen: true);
+ Assert.IsFalse(game.AdvisorSession!.AutoShow);
+ }
+
+ /// <summary>The positive control for the two silent cases: the start screen and a settings file, as a player boots it.</summary>
+ [Test]
+ public void TheStartScreenAndASettingsFileLetThemShowByThemselves()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0, startScreen: true);
+ Assert.IsTrue(game.AdvisorSession!.AutoShow);
+ }
+
+ [Test]
+ public void TheLanguageSwitchKeepsTheAdvisorsSession()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0, startScreen: true);
+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));
+ var session = game.AdvisorSession;
+ UiTestKit.Press(Ui.Q<Button>("nav-settings"));
+ UiTestKit.Press(Ui.Q<Button>("settings-language-he"));
+ Assert.AreSame(session, game.AdvisorSession, "the same game in another language: the same session");
+ Assert.IsTrue(game.AdvisorSession!.AutoShow, "and still showing by itself, though the rebuild shows no start screen");
+ game.Begin(Inputs, 0, startScreen: true); // a reload: a new session
+ Assert.AreNotSame(session, game.AdvisorSession);
+ }
+
+ [Test]
+ public void ChangesNeitherTheSimNorTheSave()
+ {
+ var store = new SaveStore(TempDir());
+ var game = OpenScene(store, new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0, startScreen: true);
+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));
+ var bridge = game.Bridge!;
+ bridge.EndTurn();
+ if (Ui.Q("root").ClassListContains(TurnReportPresenter.OpenClass)) UiTestKit.Press(Ui.Q<Button>("turn-report-close"));
+ var hash = bridge.State.Hash(); var save = store.ReadAutosave(); var queued = bridge.Queued.Count;
+ game.Advisor!.Notice(AdvisorSignals.TurnEnded);
+ if (game.Advisor.IsOpen) game.Advisor.GotIt();
+ Assert.AreEqual(hash, bridge.State.Hash());
+ Assert.AreEqual(queued, bridge.Queued.Count);
+ Assert.AreEqual(save, store.ReadAutosave(), "the save file");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorGameTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorGameTests.cs.meta
new file mode 100644
index 000000000..b06507e85
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorGameTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2d083415cecc6477cabdc542155ef22d
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs b/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs
new file mode 100644
index 000000000..4d985a6c0
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs
@@ -0,0 +1,70 @@
+#nullable enable
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using UnityEngine;
+
+/// <summary>Spec 7.1's slot, as plain numbers: the right column's upper part on one and two rows, a sheet under the bar on
+/// an upright phone; and Show me's move off a target (spec 7.3).</summary>
+public class AdvisorLayoutTests
+{
+ static Rect R(float x, float y, float w, float h) => new Rect(x, y, w, h);
+
+ [Test]
+ public void OneRowAt1920x1080IsSpecSevenOnesSlot()
+ {
+ var window = R(0, 0, 1920, 1080);
+ var column = R(1424, 112, 480, 952); // right: 16, top: 112, bottom: 16, width: 480
+ var minimap = R(1682, 684, 222, 380); // 380 tall at the column's foot
+ var slot = AdvisorLayout.Slot(HudTier.OneRow, window, column, R(16, 112, 56, 600), minimap, null, null, null, null);
+ Assert.AreEqual(Rect.MinMaxRect(1504, 166, 1904, 672), slot);
+ }
+
+ [Test]
+ public void TheTopNeverJumpsWhenDecisionWaitingAppears()
+ {
+ var window = R(0, 0, 1920, 1080); var column = R(1424, 112, 480, 952); var minimap = R(1682, 684, 222, 380);
+ var without = AdvisorLayout.Slot(HudTier.OneRow, window, column, R(16, 112, 56, 600), minimap, null, null, null, null);
+ var with = AdvisorLayout.Slot(HudTier.OneRow, window, column, R(16, 112, 56, 600), minimap, R(1700, 112, 204, 44), null, null, null);
+ Assert.AreEqual(without, with);
+ }
+
+ [Test]
+ public void AnUprightPhoneGetsASheetUnderTheBar()
+ {
+ var window = R(0, 0, 1080, 2340); // 390x844 in panel px at match 0.5 is about this shape; the numbers are what matter
+ var column = R(584, 456, 480, 1868); var left = R(16, 456, 60, 900);
+ var minimap = R(842, 1944, 222, 380); var label = R(600, 1900, 464, 30);
+ var waiting = R(860, 456, 204, 44); var toast = R(88, 456, 460, 60); var info = R(16, 1700, 800, 400);
+ var slot = AdvisorLayout.Slot(HudTier.ThreeRow, window, column, left, minimap, waiting, toast, info, label);
+ Assert.AreEqual(88f, slot.xMin, "left: 88px, the left column's edge and 12 px");
+ Assert.AreEqual(1064f, slot.xMax, "right: 16px");
+ Assert.AreEqual(524f, slot.yMin, "under the toast (the lower of it and Decision waiting) and 8 px");
+ Assert.AreEqual(1688f, slot.yMax, "12 px above the higher of the info panel and the minimap's label");
+ }
+
+ [Test]
+ public void PlaceKeepsThePopupInItsSlotAndOffATarget()
+ {
+ var slot = Rect.MinMaxRect(1504, 166, 1904, 672);
+ Assert.AreEqual(Rect.MinMaxRect(1504, 166, 1904, 366), AdvisorLayout.Place(slot, 200, null), "at the slot's top");
+ Assert.AreEqual(Rect.MinMaxRect(1504, 472, 1904, 672), AdvisorLayout.Place(slot, 200, R(1600, 200, 100, 40)), "a target under it: to the slot's foot");
+ Assert.AreEqual(Rect.MinMaxRect(1504, 166, 1904, 366), AdvisorLayout.Place(slot, 200, R(1600, 600, 100, 40)), "a target below it: stays");
+ Assert.AreEqual(Rect.MinMaxRect(1504, 166, 1904, 672), AdvisorLayout.Place(slot, 900, null), "never taller than its slot (the text scrolls)");
+ }
+
+ [Test]
+ public void ADegenerateSlotGivesAnEmptyPopupInsideIt()
+ {
+ var slot = Rect.MinMaxRect(1504, 300, 1904, 200); // a short window: the foot sits above the top, so the height is negative
+ var placed = AdvisorLayout.Place(slot, 200, null);
+ Assert.AreEqual(0f, placed.height);
+ Assert.AreEqual(slot.yMin, placed.yMin);
+ }
+
+ [Test]
+ public void WhenTopAndFootBothMeetTheTargetThePopupStaysAtTheTop()
+ {
+ var slot = Rect.MinMaxRect(1504, 166, 1904, 372);
+ Assert.AreEqual(Rect.MinMaxRect(1504, 166, 1904, 366), AdvisorLayout.Place(slot, 200, R(1600, 200, 100, 150)));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs.meta
new file mode 100644
index 000000000..a510def3c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 88f6941934f4145eba9262c5e78f5caa
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs b/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs
new file mode 100644
index 000000000..e4f54b91b
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs
@@ -0,0 +1,117 @@
+#nullable enable
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+
+/// <summary>Spec 7.1 and 16 at the seven windows: the popup sits in its slot, inside the window, clear of the minimap, the
+/// left column and the top bar; its text keeps the 12 px floor; in Hebrew it is in the same place with its inside mirrored.</summary>
+public class AdvisorPopupLayoutTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static readonly (int w, int h)[] Windows = { (1920, 1080), (1280, 720), (1366, 768), (1024, 768), (960, 1080), (390, 844), (844, 390) };
+
+ [UnityTest]
+ public IEnumerator ThePopupSitsInItsSlotAtEveryWindow()
+ {
+ var problems = new List<string>();
+ foreach (var hebrew in new[] { false, true })
+ foreach (var (w, h) in Windows)
+ yield return Shown(w, h, hebrew, (root, advisor) =>
+ {
+ string at = $"{(hebrew ? "he" : "en")} {w}x{h}";
+ var popup = root.Q("advisor-popup").worldBound;
+ var window = root.worldBound;
+ var slot = advisor.Slot();
+ if (!(popup.width > 0 && popup.height > 0)) { problems.Add($"{at}: not shown"); return; }
+ if (!Inside(popup, window)) problems.Add($"{at}: {popup} leaves the window {window}");
+ if (!Inside(popup, slot)) problems.Add($"{at}: {popup} leaves its slot {slot}");
+ foreach (var other in new[] { "minimap", "left-column", "top-bar" })
+ if (popup.Overlaps(root.Q(other).worldBound)) problems.Add($"{at}: over {other} {root.Q(other).worldBound}");
+ float scale = root.panel.scaledPixelsPerPoint;
+ foreach (var name in new[] { "advisor-name", "advisor-role", "advisor-text", "advisor-got-it" })
+ if (root.Q(name).resolvedStyle.fontSize * scale < HudPresenter.TextFloorPx - 0.01f)
+ problems.Add($"{at}: {name} is under the {HudPresenter.TextFloorPx} px floor");
+ var portrait = root.Q("advisor-portrait").worldBound; var names = root.Q("advisor-name").worldBound;
+ if (portrait.width > 0 && (hebrew ? portrait.xMin < names.xMax : portrait.xMax > names.xMin))
+ problems.Add($"{at}: the portrait is not on the {(hebrew ? "right" : "left")} of the name");
+ });
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+
+ /// <summary>The review of Task 6: on its first show the popup must not draw at the layer's top-left before it is placed,
+ /// and it must place itself once the layer is laid out (no Place() by hand).</summary>
+ [UnityTest]
+ public IEnumerator ThePopupNeverShowsBeforeItIsPlaced()
+ {
+ var problems = new List<string>();
+ yield return Shown(1920, 1080, false, (root, advisor) =>
+ {
+ var popup = root.Q("advisor-popup");
+ bool placed = popup.style.left.keyword == StyleKeyword.Undefined; // a value set by Place
+ bool invisible = popup.style.visibility.keyword == StyleKeyword.Undefined && popup.style.visibility.value == Visibility.Hidden;
+ if (!placed && !invisible) problems.Add($"drawn before it is placed: visibility {popup.style.visibility}, left {popup.style.left}");
+ }, placeByHand: false, justShown: true);
+ yield return Shown(1920, 1080, false, (root, advisor) =>
+ {
+ var popup = root.Q("advisor-popup");
+ if (popup.resolvedStyle.visibility != Visibility.Visible) problems.Add($"not visible once laid out: {popup.resolvedStyle.visibility}");
+ if (!Inside(popup.worldBound, advisor.Slot())) problems.Add($"{popup.worldBound} leaves its slot {advisor.Slot()}");
+ if (popup.worldBound.xMin < 1f && popup.worldBound.yMin < 1f) problems.Add($"at the top-left: {popup.worldBound}");
+ }, placeByHand: false);
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+
+ static bool Inside(Rect inner, Rect outer) =>
+ inner.xMin >= outer.xMin - 0.5f && inner.xMax <= outer.xMax + 0.5f && inner.yMin >= outer.yMin - 0.5f && inner.yMax <= outer.yMax + 0.5f;
+
+ /// <summary>Game.uxml at w x h with the HUD, the card collapsed, and a two-sentence fixture message shown. With
+ /// <paramref name="justShown"/> the check runs right after NewGame, before any frame; with <paramref name="placeByHand"/>
+ /// false the popup is left to place itself.</summary>
+ internal static IEnumerator Shown(int w, int h, bool hebrew, System.Action<VisualElement, AdvisorPresenter> check,
+ bool placeByHand = true, bool justShown = false)
+ {
+ var text = hebrew
+ ? UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text + "\nadvisor.t.teach.text: \"משפט ראשון ארוך למדי כדי לבדוק גלישה. ומשפט שני.\"\n", "strings.he.yaml")
+ : UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text + "\nadvisor.t.teach.text: \"A first sentence long enough to wrap. And a second one.\"\n");
+ var rt = new RenderTexture(w, h, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("AdvisorLayoutTest"); go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ root.Q("root").RemoveFromClassList("loading");
+ if (hebrew) root.Q("root").AddToClassList(UiLanguage.HebrewClass);
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
+ var hud = new HudPresenter(root, bridge, text);
+ var nav = new ScreenNav(root);
+ var card = new EventCardPresenter(root, bridge, text, null);
+ card.Collapse(takeFocus: false);
+ var catalog = AdvisorCatalog.Parse(AdvisorPopupTests.Fixture.Replace("level: new,", "level: new, he_review: approved,"));
+ var advisor = new AdvisorPresenter(root, bridge, text, new AdvisorSession(catalog, new AdvisorSettings(null), autoShow: true),
+ hooks: new AdvisorHooks { Card = card });
+ try
+ {
+ advisor.NewGame();
+ if (justShown) { check(root, advisor); yield break; }
+ for (int i = 0; i < 5; i++) yield return null;
+ if (placeByHand) advisor.Place();
+ for (int i = 0; i < 2; i++) yield return null;
+ check(root, advisor);
+ }
+ finally
+ {
+ advisor.Dispose(); card.Dispose(); nav.Dispose(); hud.Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs.meta
new file mode 100644
index 000000000..cc05af7e1
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 307c6f006ad4c4bdf83e0123d872cabb
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs b/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs
new file mode 100644
index 000000000..fe9faccbe
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs
@@ -0,0 +1,252 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+/// <summary>Spec 4.2 and 7.1: one message at a time in the side popup, with the buttons of its kind; hidden at once under
+/// every modal layer and back when it closes if its signal still holds; no focus taken; never by itself without a
+/// settings file.</summary>
+public class AdvisorPopupTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ internal static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static readonly DateTime Day = new DateTime(1948, 5, 15);
+
+ internal const string Fixture = "advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\n" +
+ "messages:\n" +
+ " - { id: t.teach, advisor: meyerson, signal: new_game, level: new, actions: [{ open_screen: budget }] }\n" +
+ " - { id: t.warn, advisor: dayan, signal: turn_ended, level: warnings, actions: [{ open_screen: defence }] }\n" +
+ " - { id: t.crit, advisor: ben_gurion, signal: turn_ended, level: critical }\n";
+
+ /// <summary>The real English strings plus the fixture's three texts.</summary>
+ internal static UiText Text() => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text +
+ "\nadvisor.t.teach.text: \"Teach.\"\nadvisor.t.warn.text: \"Warn.\"\nadvisor.t.crit.text: \"Critical.\"\n");
+
+ internal sealed class Rig : IDisposable
+ {
+ public readonly UiTestKit Ui = new UiTestKit();
+ public readonly SimBridge Bridge;
+ public readonly ScreenNav Nav;
+ public readonly EventCardPresenter Card;
+ public readonly AdvisorSession Session;
+ public readonly AdvisorPresenter Advisor;
+ readonly List<IDisposable> owned = new List<IDisposable>();
+
+ public Rig(bool autoShow = true, string catalog = Fixture, UiText? text = null, AdvisorHooks? hooks = null)
+ {
+ text ??= Text();
+ Ui.Root.Q("root").RemoveFromClassList("loading");
+ Bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
+ owned.Add(new HudPresenter(Ui.Root, Bridge, text));
+ Nav = Own(new ScreenNav(Ui.Root));
+ Card = Own(new EventCardPresenter(Ui.Root, Bridge, text, null));
+ Card.Collapse(takeFocus: false); // a new game opens on a card: out of the way
+ Session = new AdvisorSession(AdvisorCatalog.Parse(catalog), new AdvisorSettings(null), autoShow);
+ hooks ??= new AdvisorHooks();
+ hooks.Card = Card;
+ Advisor = Own(new AdvisorPresenter(Ui.Root, Bridge, text, Session, hooks: hooks));
+ }
+
+ T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }
+ public VisualElement HudRoot => Ui.Root.Q("root");
+ /// <summary>End turn, then the new turn's card (if one opens) put behind "Decision waiting", as the opening one is.</summary>
+ public void EndTurn()
+ {
+ Bridge.EndTurn();
+ if (Card.Shown != null && !Card.Collapsed) Card.Collapse(takeFocus: false);
+ }
+ public void Dispose() { for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose(); Ui.Dispose(); }
+ }
+
+ static bool Displayed(Button b) => b.style.display.value != DisplayStyle.None;
+
+ [Test]
+ public void ATeachingMessageShowsItsAdvisorTextAndButtons()
+ {
+ using var rig = new Rig();
+ rig.Advisor.NewGame();
+ Assert.IsTrue(rig.Advisor.IsOpen);
+ Assert.AreEqual("t.teach", rig.Advisor.Shown!.Id);
+ var text = Text();
+ Assert.AreEqual(text["advisor.meyerson.name_first"], rig.Ui.Q<Label>("advisor-name").text, "her first appearance");
+ Assert.AreEqual(text["advisor.meyerson.role"], rig.Ui.Q<Label>("advisor-role").text);
+ Assert.AreEqual("Teach.", rig.Ui.Q<Label>("advisor-text").text);
+ Assert.AreEqual(text["advisor.show_me"], rig.Ui.Q<Button>("advisor-show-me").text);
+ Assert.IsTrue(Displayed(rig.Ui.Q<Button>("advisor-show-me")), "it has an action");
+ Assert.IsFalse(Displayed(rig.Ui.Q<Button>("advisor-not-now")), "teaching: Tell me more, not Not now");
+ Assert.IsFalse(Displayed(rig.Ui.Q<Button>("advisor-more")), "no page to open yet (S3)");
+ Assert.IsFalse(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains(AdvisorPresenter.CriticalClass));
+ }
+
+ [Test]
+ public void AWarningHasNotNowAndACriticalOneHasNotAndShowsFirst()
+ {
+ using var rig = new Rig();
+ rig.Advisor.NewGame();
+ rig.Ui.Press("advisor-got-it");
+ rig.EndTurn();
+ Assert.AreEqual("t.crit", rig.Advisor.Shown!.Id, "critical first");
+ Assert.IsTrue(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains(AdvisorPresenter.CriticalClass));
+ Assert.IsFalse(Displayed(rig.Ui.Q<Button>("advisor-not-now")));
+ rig.Ui.Press("advisor-close"); // the X is Got it
+ Assert.AreEqual("t.warn", rig.Advisor.Shown!.Id);
+ Assert.IsTrue(Displayed(rig.Ui.Q<Button>("advisor-not-now")));
+ Assert.AreEqual(Text().Format("advisor.count", 2, 2), rig.Ui.Q<Label>("advisor-count").text);
+ rig.Ui.Press("advisor-not-now");
+ Assert.IsFalse(rig.Advisor.IsOpen);
+ CollectionAssert.AreEqual(new[] { AdvisorQueue.Outcome.Shown, AdvisorQueue.Outcome.Shown, AdvisorQueue.Outcome.PutOff },
+ rig.Session.Queue.History.Select(h => h.Outcome).ToArray());
+ }
+
+ static readonly string[] Layers =
+ {
+ StartScreenPresenter.OpenClass, EventCardPresenter.OpenClass, CaptureDialogPresenter.OpenClass,
+ TurnReportPresenter.OpenClass, OutcomePresenter.OpenClass, EndScreenPresenter.OpenClass, "two-row-screen",
+ };
+
+ /// <summary>Spec 4.2: each modal layer hides it at once, through ScreenNav.DisableCovered, which every one of them calls;
+ /// when the layer closes it comes back, as its signal still holds this turn.</summary>
+ [Test]
+ public void HidesUnderEveryModalLayerAndComesBack([ValueSource(nameof(Layers))] string layer)
+ {
+ using var rig = new Rig();
+ rig.Advisor.NewGame();
+ Assert.IsTrue(rig.Advisor.IsOpen, "precondition");
+ void Set(bool on)
+ {
+ if (layer == "two-row-screen")
+ {
+ rig.HudRoot.EnableInClassList(HudPresenter.TwoRowClass, on);
+ rig.HudRoot.EnableInClassList(ScreenNav.ScreenOpenClass, on);
+ }
+ else rig.HudRoot.EnableInClassList(layer, on);
+ ScreenNav.DisableCovered(rig.Ui.Root);
+ }
+ Set(true);
+ Assert.IsFalse(rig.Advisor.IsOpen, layer + ": hidden");
+ Assert.IsFalse(rig.HudRoot.ClassListContains(AdvisorPresenter.OpenClass));
+ Set(false);
+ Assert.IsTrue(rig.Advisor.IsOpen, layer + ": back, its signal holds this turn");
+ Assert.AreEqual("t.teach", rig.Advisor.Shown!.Id);
+ }
+
+ /// <summary>Spec 4.2: a message whose signal no longer holds when the layer closes goes to the history unseen.</summary>
+ [Test]
+ public void AMessageWhoseSignalEndedUnderALayerGoesToTheHistory()
+ {
+ using var rig = new Rig(catalog: Fixture.Replace("level: warnings", "level: critical"));
+ rig.Advisor.NewGame();
+ rig.HudRoot.AddToClassList(TurnReportPresenter.OpenClass); ScreenNav.DisableCovered(rig.Ui.Root);
+ rig.EndTurn(); // new_game held on turn 1 only
+ rig.HudRoot.RemoveFromClassList(TurnReportPresenter.OpenClass); ScreenNav.DisableCovered(rig.Ui.Root);
+ Assert.AreEqual(AdvisorQueue.Outcome.Missed, rig.Session.Queue.History.First().Outcome);
+ Assert.AreEqual("t.teach", rig.Session.Queue.History.First().Id);
+ Assert.IsFalse(rig.Session.Settings.Seen("t.teach"));
+ Assert.IsTrue(rig.Advisor.Shown!.Critical, "the turn's own (critical) message shows");
+ }
+
+ [Test]
+ public void TakesNoFocusAndEscapeClosesItOnlyFromInside()
+ {
+ using var rig = new Rig();
+ var endTurn = rig.Ui.Q<Button>("end-turn");
+ endTurn.Focus();
+ rig.Advisor.NewGame();
+ Assert.AreSame(endTurn, rig.Ui.Root.focusController.focusedElement, "spec 16: not modal, steals no focus");
+ Assert.IsFalse(rig.Advisor.Escape(), "Escape with the focus outside: not its key");
+ Assert.IsTrue(rig.Advisor.IsOpen);
+ rig.Ui.Q<Button>("advisor-got-it").Focus();
+ Assert.IsTrue(rig.Advisor.Escape());
+ Assert.IsFalse(rig.Advisor.IsOpen);
+ Assert.IsTrue(rig.Session.Settings.Seen("t.teach"), "Escape is the X");
+ }
+
+ /// <summary>Spec 16: one Escape with the focus in the popup closes the popup only, as in the report panel (#1169).
+ /// ScreenNav's Cancel asks it first (TakesEscape, as GameRoot wires it), and GameRoot's Escape poll asks it before it
+ /// closes the screen, also in the frame its Cancel already closed it. (Time.frameCount does not move in an edit-mode
+ /// test, so after this the popup keeps saying "used this frame".)</summary>
+ [Test]
+ public void OneEscapeInThePopupLeavesTheScreenUnderItOpen()
+ {
+ using var rig = new Rig();
+ rig.Nav.TakesEscape = rig.Advisor.Escape;
+ rig.Advisor.NewGame();
+ rig.Nav.Open("budget"); // what Show me opens: the one-row HUD keeps it beside
+ Assert.IsTrue(rig.Advisor.IsOpen, "precondition: a side screen does not cover it on the one-row HUD");
+ var gotIt = rig.Ui.Q<Button>("advisor-got-it");
+ gotIt.Focus();
+ using (var esc = NavigationCancelEvent.GetPooled()) { esc.target = gotIt; gotIt.SendEvent(esc); }
+ Assert.IsFalse(rig.Advisor.IsOpen, "Esc closes the popup");
+ Assert.AreEqual("budget", rig.Nav.Current, "and only the popup");
+ Assert.IsTrue(rig.Advisor.Escape(), "closed this frame: the poll's Escape is used, so it leaves the screen open");
+ Assert.AreEqual("budget", rig.Nav.Current);
+ }
+
+ /// <summary>One Escape dismisses one message: when Got it brings the next message up at once (the focus still on Got
+ /// it), the poll's Escape in the same frame does not dismiss that one too.</summary>
+ [Test]
+ public void OneEscapeDismissesOnlyOneMessage()
+ {
+ using var rig = new Rig();
+ rig.Nav.TakesEscape = rig.Advisor.Escape;
+ rig.Advisor.NewGame();
+ rig.Ui.Press("advisor-got-it");
+ rig.EndTurn();
+ Assert.AreEqual("t.crit", rig.Advisor.Shown!.Id, "precondition: critical first, the warning behind it");
+ var gotIt = rig.Ui.Q<Button>("advisor-got-it");
+ gotIt.Focus();
+ using (var esc = NavigationCancelEvent.GetPooled()) { esc.target = gotIt; gotIt.SendEvent(esc); }
+ Assert.AreEqual("t.warn", rig.Advisor.Shown?.Id, "Cancel dismissed the critical one; the warning is up");
+ Assert.IsTrue(rig.Advisor.Escape(), "the poll in the same frame: the key is used");
+ Assert.IsTrue(rig.Advisor.IsOpen, "and the warning stays up");
+ Assert.AreEqual("t.warn", rig.Advisor.Shown?.Id);
+ Assert.IsFalse(rig.Session.Settings.Seen("t.warn"), "unread, so not seen");
+ }
+
+ /// <summary>OQ-4: in Hebrew a message shows only once its Hebrew is approved.</summary>
+ [TestCase("pending", false)]
+ [TestCase("approved", true)]
+ public void InHebrewOnlyAnApprovedMessageShows(string review, bool shows)
+ {
+ var he = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text +
+ "\nadvisor.t.teach.text: \"Teach.\"\nadvisor.t.warn.text: \"Warn.\"\nadvisor.t.crit.text: \"Critical.\"\n", "strings.he.yaml");
+ using var rig = new Rig(catalog: Fixture.Replace("level: new,", $"level: new, he_review: {review},"), text: he);
+ rig.Advisor.NewGame();
+ Assert.AreEqual(shows, rig.Advisor.IsOpen, "he_review: " + review);
+ }
+
+ [Test]
+ public void NeverShowsByItselfWithoutASettingsFile()
+ {
+ using var rig = new Rig(autoShow: false);
+ rig.Advisor.NewGame();
+ rig.EndTurn();
+ Assert.IsFalse(rig.Advisor.IsOpen);
+ Assert.IsEmpty(rig.Session.Queue.History);
+ }
+
+ [Test]
+ public void NoPortraitHidesTheFrame()
+ {
+ using var rig = new Rig(); // no PortraitCatalog: none for anyone
+ rig.Advisor.NewGame();
+ Assert.IsTrue(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains(AdvisorPresenter.NoPortraitClass));
+ }
+
+ [Test]
+ public void ChangesNeitherTheSimNorTheQueue()
+ {
+ using var rig = new Rig();
+ var hash = rig.Bridge.State.Hash(); var queued = rig.Bridge.Queued.Count;
+ rig.Advisor.NewGame(); rig.Ui.Press("advisor-show-me"); rig.Nav.Close(); rig.Ui.Press("advisor-got-it");
+ Assert.AreEqual(hash, rig.Bridge.State.Hash());
+ Assert.AreEqual(queued, rig.Bridge.Queued.Count, "it issues no command");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs.meta
new file mode 100644
index 000000000..5d33ad84c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorPopupTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 3c5802284a6a345ec8bb765345191300
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs b/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs
new file mode 100644
index 000000000..36981be1a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs
@@ -0,0 +1,132 @@
+#nullable enable
+using System;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+
+/// <summary>Spec 4.2's queue: critical first, then priority, then firing order; one teaching and one warning a turn by
+/// themselves, never capping a critical one; the help level (spec 6); once and every; requires; Not now; Hebrew only
+/// approved (OQ-4).</summary>
+public class AdvisorQueueTests
+{
+ static readonly DateTime Day = new DateTime(1948, 5, 15);
+ const string Head = "advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\nmessages:\n";
+ static AdvisorCatalog Catalog(params string[] rows) => AdvisorCatalog.Parse(Head + string.Join("", rows.Select(r => " - " + r + "\n")));
+ static string Row(string id, string level, int priority = 1, string extra = "") =>
+ $"{{ id: {id}, advisor: dayan, signal: s, level: {level}, priority: {priority}{extra} }}";
+ static readonly string[] Fired = { "s" };
+ static bool Always(System.Collections.Generic.IReadOnlyDictionary<string, double> _) => true;
+
+ [Test]
+ public void CriticalFirstThenPriorityThenFiringOrder()
+ {
+ var q = new AdvisorQueue(Catalog(Row("t1", "new"), Row("w1", "warnings"), Row("w2", "warnings", 3), Row("c1", "critical")), new AdvisorSettings(null));
+ q.Offer(Fired, Always, 1);
+ Assert.AreEqual("c1", q.Head(1, false)!.Id);
+ q.Done(q.Head(1, false)!, 1, Day);
+ Assert.AreEqual("w2", q.Head(1, false)!.Id, "priority 3 before the earlier priority 1");
+ q.Done(q.Head(1, false)!, 1, Day);
+ Assert.AreEqual("t1", q.Head(1, false)!.Id, "the warning's slot is used this turn; the teaching one is next");
+ }
+
+ [Test]
+ public void OneTeachingAndOneWarningShowByThemselvesATurn()
+ {
+ var q = new AdvisorQueue(Catalog(Row("t1", "new"), Row("t2", "new"), Row("w1", "warnings"), Row("w2", "warnings")), new AdvisorSettings(null));
+ q.Offer(Fired, Always, 1);
+ q.Done(q.Head(1, false)!, 1, Day); q.Done(q.Head(1, false)!, 1, Day);
+ Assert.IsNull(q.Head(1, false), "the rest wait for the next turn");
+ Assert.AreEqual((1, 2), q.Position(2, false), "next turn: two more, one of each kind");
+ Assert.IsNotNull(q.Head(2, false));
+ }
+
+ [Test]
+ public void CriticalMessagesAreNeverCapped()
+ {
+ var q = new AdvisorQueue(Catalog(Row("c1", "critical"), Row("c2", "critical"), Row("w1", "warnings")), new AdvisorSettings(null));
+ q.Offer(Fired, Always, 1);
+ q.Done(q.Head(1, false)!, 1, Day);
+ Assert.AreEqual("c2", q.Head(1, false)!.Id);
+ q.Done(q.Head(1, false)!, 1, Day);
+ Assert.AreEqual("w1", q.Head(1, false)!.Id, "two critical ones used no warning slot");
+ }
+
+ [TestCase("new", "t1,e1,w1,c1")]
+ [TestCase("experienced", "e1,w1,c1")]
+ [TestCase("warnings", "w1,c1")]
+ [TestCase("off", "c1")]
+ public void TheHelpLevelFilters(string level, string expected)
+ {
+ var settings = new AdvisorSettings(null); settings.SetLevel(level);
+ var q = new AdvisorQueue(Catalog(Row("t1", "new"), Row("e1", "experienced"), Row("w1", "warnings"), Row("c1", "critical")), settings);
+ q.Offer(Fired, Always, 1);
+ var shown = new System.Collections.Generic.List<string>();
+ for (int turn = 1; turn <= 4; turn++)
+ while (q.Head(turn, false) is AdvisorCatalog.Message m) { shown.Add(m.Id); q.Done(m, turn, Day); }
+ CollectionAssert.AreEquivalent(expected.Split(','), shown);
+ }
+
+ [Test]
+ public void OnceIsNeverAgainAndEveryWaitsItsCooldown()
+ {
+ var settings = new AdvisorSettings(null);
+ var q = new AdvisorQueue(Catalog(Row("o", "warnings"), Row("e", "critical", 1, ", repeat: every, cooldown_turns: 2")), settings);
+ q.Offer(Fired, Always, 1);
+ q.Done(q.Head(1, false)!, 1, Day); q.Done(q.Head(1, false)!, 1, Day);
+ Assert.IsTrue(settings.Seen("o")); Assert.IsFalse(settings.Seen("e"), "an every message is never marked seen");
+ q.Offer(Fired, Always, 2);
+ Assert.IsNull(q.Head(2, false), "o is seen; e cools down until turn 3");
+ q.Offer(Fired, Always, 3);
+ Assert.AreEqual("e", q.Head(3, false)!.Id);
+ }
+
+ [Test]
+ public void RequiresWaitsForTheEarlierMessageAndWhenMustHold()
+ {
+ var q = new AdvisorQueue(Catalog(Row("a", "new"), Row("b", "new", 1, ", requires: [a]"),
+ Row("c", "warnings", 1, ", when: { debt_ratio_at_least: 0.8 }")), new AdvisorSettings(null));
+ q.Offer(Fired, w => !w.ContainsKey("debt_ratio_at_least"), 1);
+ Assert.AreEqual("a", q.Head(1, false)!.Id);
+ q.Done(q.Head(1, false)!, 1, Day);
+ Assert.IsNull(q.Head(1, false), "b waits for the next turn's teaching slot; c's condition did not hold");
+ q.Offer(Fired, Always, 2);
+ CollectionAssert.AreEquivalent(new[] { "b", "c" }, new[] { q.Head(2, false)!.Id, Next(q, 2) });
+ }
+
+ static string Next(AdvisorQueue q, int turn) { q.Done(q.Head(turn, false)!, turn, Day); return q.Head(turn, false)!.Id; }
+
+ [Test]
+ public void NotNowPutsItOffToTheNextTurnAndIntoTheHistory()
+ {
+ var q = new AdvisorQueue(Catalog(Row("w", "warnings")), new AdvisorSettings(null));
+ q.Offer(Fired, Always, 1);
+ q.PutOff(q.Head(1, false)!, 1, Day);
+ Assert.IsNull(q.Head(1, false));
+ CollectionAssert.AreEqual(new[] { "w" }, q.PutOffIds.ToArray());
+ Assert.AreEqual(AdvisorQueue.Outcome.PutOff, q.History.Single().Outcome);
+ Assert.AreEqual("w", q.Head(2, false)!.Id, "back next turn");
+ Assert.Throws<InvalidOperationException>(() => new AdvisorQueue(Catalog(Row("c", "critical")), new AdvisorSettings(null)).PutOff(
+ AdvisorCatalog.Parse(Head + " - " + Row("c", "critical") + "\n").Find("c")!, 1, Day), "a critical message has no Not now");
+ }
+
+ [Test]
+ public void InHebrewOnlyApprovedMessagesShow()
+ {
+ var q = new AdvisorQueue(Catalog(Row("p", "new"), Row("a", "warnings", 1, ", he_review: approved")), new AdvisorSettings(null));
+ q.Offer(Fired, Always, 1);
+ Assert.AreEqual("a", q.Head(1, hebrew: true)!.Id);
+ Assert.AreEqual("p", q.Head(1, hebrew: false)!.Id, "the same queue in English: p fired first");
+ }
+
+ [Test]
+ public void ResetForgetsTheGameButNotTheSeenMarks()
+ {
+ var settings = new AdvisorSettings(null);
+ var q = new AdvisorQueue(Catalog(Row("a", "new"), Row("b", "warnings")), settings);
+ q.Offer(Fired, Always, 1);
+ q.Done(q.Head(1, false)!, 1, Day);
+ q.Reset();
+ Assert.IsEmpty(q.History); Assert.IsNull(q.Head(1, false));
+ Assert.IsTrue(settings.Seen("a"), "seen marks are the player's (spec 15)");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs.meta
new file mode 100644
index 000000000..00252e9ae
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorQueueTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 4d620db1baccc4e4ab92fdf5534342fb
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs b/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs
new file mode 100644
index 000000000..fea41dfc0
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs
@@ -0,0 +1,68 @@
+#nullable enable
+using System;
+using System.IO;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+/// <summary>Spec 15: the help level, the seen marks (one compact line) and the opening chain's mark live in the settings
+/// file, never in the save; a write that fails costs nothing but persistence.</summary>
+public class AdvisorSettingsTests
+{
+ string dir = "";
+ [SetUp] public void Temp() => dir = Path.Combine(Path.GetTempPath(), "statecraft-advisors-" + Guid.NewGuid().ToString("N"));
+ [TearDown] public void Clean() { try { if (Directory.Exists(dir)) Directory.Delete(dir, true); if (File.Exists(dir)) File.Delete(dir); } catch (Exception) { } }
+
+ [Test]
+ public void TheLevelAndTheSeenMarksRoundTrip()
+ {
+ var store = new SettingsStore(dir);
+ var a = new AdvisorSettings(store);
+ Assert.AreEqual("new", a.Level, "spec 6: New to strategy games by default");
+ a.SetLevel("warnings"); a.MarkSeen("b.two"); a.MarkSeen("a.one"); a.MarkSeen("a.one");
+ Assert.AreEqual("warnings", store.Read(AdvisorSettings.LevelKey));
+ Assert.AreEqual("a.one,b.two", store.Read(AdvisorSettings.SeenKey), "one line, ordinal order, no repeats");
+ var b = new AdvisorSettings(store);
+ Assert.AreEqual(("warnings", 2), (b.Level, b.LevelRank));
+ Assert.IsTrue(b.Seen("a.one") && b.Seen("b.two") && !b.Seen("c"));
+ }
+
+ [Test]
+ public void AnUnknownLevelReadsAsNew()
+ {
+ var store = new SettingsStore(dir);
+ store.Write(AdvisorSettings.LevelKey, "chatty");
+ Assert.AreEqual("new", new AdvisorSettings(store).Level);
+ Assert.Throws<ArgumentException>(() => new AdvisorSettings(store).SetLevel("chatty"));
+ }
+
+ /// <summary>Spec 9.3: a player who saw the first-turn guide does not get the opening chain by itself.</summary>
+ [Test]
+ public void TheGuidesSeenLineCountsAsTheOpeningSeen()
+ {
+ var store = new SettingsStore(dir);
+ Assert.IsFalse(new AdvisorSettings(store).OpeningSeen);
+ store.Write(AdvisorSettings.GuideSeenKey, "seen");
+ Assert.IsTrue(new AdvisorSettings(store).OpeningSeen);
+ var fresh = new SettingsStore(dir + "-b");
+ var a = new AdvisorSettings(fresh);
+ a.MarkOpeningSeen();
+ Assert.AreEqual("seen", fresh.Read(AdvisorSettings.OpeningKey));
+ Directory.Delete(dir + "-b", true);
+ }
+
+ /// <summary>No file (automated runs) and a failed write (a full or blocked IndexedDB) both keep the session's marks in
+ /// memory and throw nothing.</summary>
+ [Test]
+ public void WithoutAFileOrWithAFailedWriteTheMarksHoldForTheSession()
+ {
+ var none = new AdvisorSettings(null);
+ Assert.IsFalse(none.HasFile);
+ none.MarkSeen("a"); none.SetLevel("off");
+ Assert.IsTrue(none.Seen("a")); Assert.AreEqual("off", none.Level);
+
+ File.WriteAllText(dir, "a file where the folder should be"); // Directory.CreateDirectory throws
+ var broken = new AdvisorSettings(new SettingsStore(dir));
+ broken.MarkSeen("a"); broken.MarkOpeningSeen(); // logs a warning, throws nothing
+ Assert.IsTrue(broken.Seen("a")); Assert.IsTrue(broken.OpeningSeen);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs.meta
new file mode 100644
index 000000000..d6a220bb4
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: e4493d1060f44478d9eb6130d5e596fb
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 00c360e54..cf7d5f2dd 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -470,6 +470,32 @@
</ui:VisualElement>
</ui:VisualElement>
</ui:VisualElement>
+ <!-- The advisors' popup (spec 7.1, AdvisorPresenter): the right column's upper part, or a sheet under the bar on an
+ upright phone, placed in code (AdvisorLayout). Not modal: the layer takes no pointer outside the popup. It
+ hides under every modal layer (ScreenNav.DisableCovered calls the presenter). -->
+ <ui:VisualElement name="advisor-layer" class="advisor-layer" picking-mode="Ignore">
+ <ui:VisualElement name="advisor-popup" class="panel advisor-popup">
+ <ui:VisualElement class="row advisor-head">
+ <ui:VisualElement name="advisor-portrait" class="advisor-portrait" />
+ <ui:VisualElement class="advisor-names">
+ <ui:Label name="advisor-name" class="title advisor-name" />
+ <ui:Label name="advisor-role" class="muted advisor-role" />
+ </ui:VisualElement>
+ <ui:Button name="advisor-close" class="advisor-close" />
+ </ui:VisualElement>
+ <ui:ScrollView name="advisor-body" class="advisor-body">
+ <ui:Label name="advisor-text" class="advisor-text" />
+ </ui:ScrollView>
+ <ui:VisualElement class="row advisor-actions">
+ <ui:Button name="advisor-show-me" />
+ <ui:Button name="advisor-more" />
+ <ui:Button name="advisor-not-now" />
+ <ui:Button name="advisor-got-it" class="advisor-got-it" />
+ </ui:VisualElement>
+ <ui:Label name="advisor-count" class="muted advisor-count" />
+ <Statecraft.Game.UI.UiFrame filigree="true" />
+ </ui:VisualElement>
+ </ui:VisualElement>
<!-- The turn report (#1037, TurnReportPresenter): after End Turn, each top-bar number that changed and the sim's causes.
A backdrop over the HUD (ScreenNav.DisableCovered disables what it covers), under the outcome clips' layer. -->
<ui:VisualElement name="turn-report" class="turn-report">
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index 0ff36a48a..cb5b10c19 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -577,6 +577,33 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas
/* How to play's button that opens the guide again: under the lines, never squeezed by them. */
.how-to-play-guide { flex-shrink: 0; align-self: flex-start; min-height: 44px; margin-top: 8px; }
.lang-he .how-to-play-guide { align-self: flex-end; }
+/* The advisors' popup (spec 7.1, AdvisorPresenter): placed in code in the free upper part of the right column (AdvisorLayout),
+ 400 px wide; not modal, so the layer takes no pointer. It slides 16 px in from the right while it fades in (0.25 s) and
+ fades out (0.15 s): ScreenNav's opening and closing classes, with a slide instead of the screens' scale (spec 16). */
+.advisor-layer { display: none; position: absolute; left: 0; top: 0; right: 0; bottom: 0; }
+.advisor-open .advisor-layer { display: flex; }
+.advisor-popup {
+ position: absolute; width: 400px; padding: 12px 14px 8px 14px; background-color: var(--navy-solid); border-color: var(--gold);
+ transition-property: translate, opacity; transition-duration: 0.25s, 0.25s; transition-timing-function: ease-out, ease-out;
+}
+.advisor-popup.window-opening { translate: 16px 0; opacity: 0; transition-duration: 0s, 0s; }
+.advisor-popup.window-closing { opacity: 0; transition-property: opacity; transition-duration: 0.15s; }
+.advisor-popup.advisor-critical { border-color: var(--down); border-width: 2px; }
+.advisor-head { align-items: flex-start; }
+.advisor-portrait { width: 96px; height: 120px; flex-shrink: 0; margin-right: 10px; border-width: 1px; border-color: var(--gold); background-size: cover; }
+.lang-he .advisor-portrait { margin-right: 0; margin-left: 10px; }
+.advisor-no-portrait .advisor-portrait { display: none; }
+.advisor-names { flex-grow: 1; flex-shrink: 1; }
+.advisor-name { color: var(--gold-light); font-size: 24px; white-space: normal; }
+.advisor-role { font-size: 15px; letter-spacing: 2px; }
+.advisor-close { min-width: 44px; min-height: 44px; -unity-text-align: middle-center; }
+.advisor-body { flex-shrink: 1; min-height: 0; }
+.advisor-text { white-space: normal; font-size: 22px; margin: 6px 0 8px 0; }
+.advisor-actions { flex-wrap: wrap; }
+.advisor-got-it { margin-left: auto; }
+.lang-he .advisor-got-it { margin-left: 0; margin-right: auto; }
+.advisor-count { font-size: 15px; -unity-text-align: middle-right; }
+.lang-he .advisor-count { -unity-text-align: middle-left; }
/* "Report a bug or idea" (#1169, FeedbackPresenter): the same backdrop over everything, the start screen too; each GitHub
choice with the lines its form opens with under it, wrapped (a user agent is long). */
.feedback-layer { display: none; position: absolute; left: 0; top: 0; right: 0; bottom: 0; justify-content: center; align-items: center; background-color: rgba(5, 9, 18, 0.6); padding: 16px; }
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 23b85b100..08bc499e2 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -93,6 +93,22 @@ guide.event.title: "An event card"
guide.event.text: "An event card asks for a decision. Answering it costs Attention, and your choice takes effect when you end the turn. A card you leave unanswered goes to the responsible minister."
guide.objectives.title: "Objectives"
guide.objectives.text: "Objectives lists the game's goals, with the date you completed each beside the historical one. Completing one also brings its card."
+# The advisors (spec 3.1 and 7.1; AdvisorPresenter). Their names as the popup shows them: Golda Meyerson's first appearance
+# in a profile adds "(later Meir)" (owner, 23 October 2026). "Advisor" is a game role, not an office they held.
+advisor.ben_gurion.name: "David Ben-Gurion"
+advisor.meyerson.name_first: "Golda Meyerson (later Meir)"
+advisor.meyerson.name: "Golda Meyerson"
+advisor.dayan.name: "Moshe Dayan"
+advisor.ben_gurion.role: "Advisor"
+advisor.meyerson.role: "Advisor"
+advisor.dayan.role: "Advisor"
+advisor.show_me: "Show me"
+advisor.more: "Tell me more"
+advisor.not_now: "Not now"
+advisor.got_it: "Got it"
+advisor.close: "X"
+# {0} this message's place this turn, {1} how many can show this turn.
+advisor.count: "{0} of {1}"
# The Settings screen (#40): its title, the tilt-shift option and the button that says what is set.
settings.title: "Settings"
settings.tiltshift: "Blur at the top and bottom of the map"
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index f33264bcd..ba721f4ab 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -85,6 +85,21 @@ guide.event.title: "כרטיס אירוע"
guide.event.text: "כרטיס אירוע מבקש מכם החלטה. מענה עליו עולה תשומת לב, והבחירה שלכם נכנסת לתוקף בסיום התור. כרטיס שלא עניתם עליו עובר לשר האחראי."
guide.objectives.title: "יעדים"
guide.objectives.text: "במסך היעדים מופיעים יעדי המשחק ולצד כל אחד התאריך שבו השלמתם אותו לעומת התאריך ההיסטורי. השלמת יעד מביאה גם את הכרטיס שלו."
+# The advisors (spec 3.1, 14): the names as in people.yaml (name_he) and the spec; "יועצת" for Meyerson, the speaker's own
+# gender. Agent-drafted. For the native reviewer (#564).
+advisor.ben_gurion.name: "דוד בן-גוריון"
+advisor.meyerson.name_first: "גולדה מאירסון (לימים מאיר)"
+advisor.meyerson.name: "גולדה מאירסון"
+advisor.dayan.name: "משה דיין"
+advisor.ben_gurion.role: "יועץ"
+advisor.meyerson.role: "יועצת"
+advisor.dayan.role: "יועץ"
+advisor.show_me: "הראו לי"
+advisor.more: "ספרו לי עוד"
+advisor.not_now: "לא עכשיו"
+advisor.got_it: "הבנתי"
+advisor.close: "X"
+advisor.count: "{0} מתוך {1}"
# The Settings screen (#40). "On" / "Off" as a switch's state, not a command. For the native reviewer (#564).
settings.title: "הגדרות"
settings.tiltshift: "טשטוש בחלק העליון ובחלק התחתון של המפה"