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.

Docs: implementation plan for the Civ-style advisors (Refs #1484) (#1508)

Eyal Golan176be4b7bf18
diff --git a/docs/superpowers/plans/2026-10-23-advisors.md b/docs/superpowers/plans/2026-10-23-advisors.md
new file mode 100644
index 000000000..2addc3bae
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-23-advisors.md
@@ -0,0 +1,3797 @@
+# Civ-style advisors Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Three advisors (David Ben-Gurion, Golda Meyerson, Moshe Dayan) teach each mechanic the first time the player meets it and warn as the game goes on, in a side popup, replacing the first-turn guide and How to play; the talking clips plug in last, once the owner picks how they are made.
+
+**Architecture:** A Unity-side data file, `unity/Assets/Resources/Advisors/advisor-messages.yaml`, lists the advisors, their messages and the encyclopedia's pages; `AdvisorCatalog` loads and checks it. Small pure classes decide what shows: `AdvisorSignals` reads the state the screen shows, `AdvisorQueue` orders, caps and filters, `AdvisorLayout` places the popup, `AdvisorSettings` keeps the help level and the seen marks in the settings file. `AdvisorPresenter` draws the popup and hides it under every modal layer through one hook at the end of `ScreenNav.DisableCovered`. Media is one optional row per message: a picture file (a clip or a still) under `StreamingAssets/advisors/`, a narration file per language and timed caption keys; `AdvisorMedia` plays whatever the row names, so the production route can change without touching code.
+
+**Tech Stack:** C# in Unity 6000.3.25f1 (UI Toolkit, NUnit EditMode tests), YamlDotNet (already a Unity plugin), the netstandard2.1 sim (xUnit, `dotnet test sim/Statecraft.sln`) for one read-only helper, `scripts/check.sh`.
+
+**Spec:** [docs/superpowers/specs/2026-10-23-advisors-design.md](../specs/2026-10-23-advisors-design.md) (merged as 945026bb, #1484). Read it first; section numbers below are the spec's. Every file:line below was read on origin/main `030263e4` (#1324 merged).
+
+## Global Constraints
+
+- **Approval.** The owner, 23 October 2026, verbatim: "spec approved". The open questions of spec section 18 take their stated defaults: OQ-1 and OQ-2, no aide name ships (a narrator is named by office only); OQ-3, CRF 28; OQ-4, no Hebrew advisor line or narration ships before a native reviewer approves it; OQ-5, the 1951 photograph under D-P with its risk note; OQ-6, keep the first version's stills; OQ-7, no line names Dayan's 1948-49 posts; OQ-8, Off does not keep the capture prompt; OQ-9, S2 ports whatever `guide.move.text` is on main; OQ-10, S4 adds `end.outcome.defeat_war`; OQ-11, no folded tab; OQ-12, no new key.
+- **Media is not settled.** Spec sections 11 and 12 still describe the still-photo clips, which the owner has since rejected. Owner rulings since: talking advisors. Route A: the leader's stylized face speaking the aide's voice, labelled "stylized portrayal, fictional dialogue and voice", made locally with LivePortrait. Route B: Tal Heuberger's fictional figures speaking through ElevenLabs, with Tal's permission. Both are being tested now. So:
+ - every media-dependent piece reads one data row: a picture file under `unity/Assets/StreamingAssets/advisors/` (`.mp4` plays as a silent clip, `.jpg` or `.png` shows as a still), a narration file per language in the same folder (`.wav`, played as separate audio), caption cues as string keys with start times (live text), and a disclosure label key;
+ - nothing outside Task 26 names a route, a tool or a file that Task 26 makes;
+ - spec 12's player rules stay: never autoplays, the picture is silent, the narration is a separate file, captions are live text, one press stops both, lazy, nothing at boot.
+- **Presentation only.** No change to the sim's state, the save or a golden hash. With no settings file (automated runs, EditMode tests by default) the advisors never show by themselves, so the smoke runs, the golden check and the browser checks do not change. The one sim addition is spec section 5's read-only helper (Task 15): it adds two functions, changes no state and draws no random number, and `dotnet test sim/Statecraft.sln` must show the goldens unchanged.
+- **Hebrew (OQ-4 default).** Read as follows; the owner can overrule it on the PR:
+ - every advisor line (popup text, encyclopedia page text, caption cue, narration) carries `he_review: pending` in the data file until a native reviewer approves it, and a pending message or page never shows in Hebrew (`AdvisorQueue.Head`, `EncyclopediaPresenter`); the Hebrew draft still sits in `strings.he.yaml` for the reviewer to read in place, so the keys stay in parity;
+ - UI chrome (button labels, the Settings row, screen titles) follows the existing practice: agent-drafted, under a "For the native reviewer (#564)" comment;
+ - a slice that removes an existing Hebrew screen (S2 removes the first-turn guide, S3 removes How to play) merges only once its replacement's Hebrew lines are approved, so a Hebrew player never loses onboarding.
+- **Copy.** `docs/WRITING_UI.md`, `docs/WRITING_UI_HE.md` (HE-03: the player is addressed gender-neutrally; Meyerson speaks in her own feminine forms) and `docs/UX_GLOSSARY.yaml`. A popup line is one or two sentences, at most 35 words (the validator counts). No date, place or number that the game's content does not already source. Deport is never suggested. No em dashes in any string, comment or doc. Contributors are "they". Each slice's PR lists every new advisor line for the owner's content review (spec 17).
+- **Names.** "David Ben-Gurion", "Golda Meyerson (later Meir)" on her first appearance in a profile and "Golda Meyerson" after it, "Moshe Dayan"; Hebrew "דוד בן-גוריון", "גולדה מאירסון (לימים מאיר)", "משה דיין" (spec 3.1, 14). The UI label is "Advisor" for all three.
+- **TDD.** Each task writes its test first, runs it and sees the named failure, then implements. Every test below is code.
+- **The Unity command.** Run Unity only like this; `$FILTER` is the task's test classes (echo it first), and the full run drops `-testFilter`:
+
+```bash
+uv run tools/build_sim_for_unity.py
+export UNITY_MCP_SERVER_PATH="$(mktemp)" # an existing empty file
+UNITY="/Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/MacOS/Unity"
+FILTER="AdvisorCatalogTests"; echo "FILTER=$FILTER"
+uv run tools/machine_lock.py --shared --wait-unity --timeout 14400 -- "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false \
+ -TF_BUILD false -projectPath unity -runTests -testPlatform EditMode -testFilter "$FILTER" \
+ -testResults "$PWD/unity-editmode.xml" -logFile "$PWD/unity-editmode.log"
+grep -o 'total="[0-9]*"' unity-editmode.xml | head -1 # must be > 0: "0 tests" is a broken command, not a pass
+git checkout -- unity/ProjectSettings unity/Assets/Settings
+```
+
+ Never `-quit` with `-runTests`, never `-nographics`, never cancel a lock wait, stop a stuck Unity by its PID only. In a new worktree APFS-clone the Library first (`cp -c -R ~/israel-game/unity/Library <wt>/unity/Library`) and delete it at the end. Never commit the `UNITY_MCP_*` defines. Commit the `.meta` files Unity makes for new files.
+- **Every PR (one slice each).** Before starting: `git fetch`, and check the slice is not already on origin/main. A `changelog.d/advisors-s<N>.md` fragment. `Refs #1484`. `bash scripts/check.sh origin/main` ends with "ALL CHECKS PASSED" (and "Unity compile skipped" is not a pass). A FULL EditMode run on the PR merged with current origin/main, XML total > 0, every failure classed NEW or PRE-EXISTING against main, 0 NEW. English and Hebrew before and after screenshots, same state, camera and zoom, on a `captures/pr-<n>` branch, for every visible change. The load-time gate: nothing new at boot, the first download does not grow beyond code-size noise, `tools/headed.py boot --runs 3 --cpu 4` on base and PR for S1 and S6. Commits by `git -c user.name=eyalgolan -c [email protected]`, ending with `Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>`. Never force-push; plain-merge origin/main.
+
+## Review Focus
+
+1. **A modal layer opening over a playing clip** (the player presses "Decision waiting" mid-Watch, or End turn brings the turn report): the picture and the narration stop at once, the captions clear, and the decision card's own illustration loop on the shared player is not stopped by the advisor. Pinned in Task 24 (`ALayerOverAPlayingClipStopsBothAndLeavesTheCardsLoopAlone`).
+2. **A talking clip drifting from its voice** (Routes A and B are both lip-synced): the picture and the narration start in the same tick only when both are ready, a slow picture holds the narration back rather than starting without it, and a drift past 0.1 s is corrected to the narration's position. Pinned in Task 24 (`PictureAndNarrationStartTogether`, `ADriftIsCorrectedToTheNarration`).
+3. **The language switch while the opening chain or a message shows** (Settings' language buttons rebuild every presenter over the same game, `GameRoot.SwitchLanguage`): the chain does not restart from step 1, the history and the put-off messages survive, and a message that is pending in Hebrew closes and waits instead of showing English. Pinned in Task 7 (`TheLanguageSwitchKeepsTheAdvisorsSession`) and Task 9 (`ALanguageSwitchMidChainKeepsTheStep`).
+4. **The ninth rail disc (Counsel) on a phone** (390x844 and 844x390): the left column still fits above End turn, no disc overlaps another, every disc keeps its 44 px hit area. Pinned in Task 21 (`TheRailFitsWithCounselOnEveryPhone`).
+5. **A "Show me" target under the popup.** On an upright phone the sheet spans the window's width, and Show me on a unit or a city centres the camera on it, which is where the sheet is; on desktop a map target can sit in the right column's slot. The target must stay in view: the popup moves within its slot (to its foot when the target is under its top), and never leaves the window. Pinned in Task 8 (`AShowMeTargetUnderThePopupIsUncovered`, desktop) and Task 10 (the ported `TheMoveStepShowsTheUnitAndAReachableHexOnTheMap`, now checking the unit and a reachable hex clear of the popup at 1920x1080, 1280x720 and 390x844).
+
+---
+
+## Slices, order and estimates
+
+| Slice | Tasks | Needs | Estimate | Main risk |
+|---|---|---|---|---|
+| S1 engine and popup shell (no message shown yet) | 1 to 7 | the spec | 2 days | the cover hook in `ScreenNav.DisableCovered`: every modal layer is pinned by a test |
+| S2 the opening chain replaces the first-turn guide | 8 to 11 | S1; the opening lines' Hebrew approved before merge | 2 days | parity: the guide's 17 tests pass on the chain before the guide is deleted |
+| S3 the encyclopedia replaces How to play | 12, 13 | S2 (it reuses the chain's reopen button); the pages' Hebrew approved before merge | 1.5 days | seven menu pins move in one PR |
+| S4 warnings, advice and the help level | 14 to 20 | S3 (teaching messages open encyclopedia pages); #1493 for the truce row (Task 20) | 3 days | the read-only sim helper (Task 15) keeps every golden |
+| S5 Counsel and disagreement | 21, 22 | S4 | 1 day | the ninth rail disc on phones |
+| S6a the media player, media-neutral | 23 to 25 | S3 | 2 days | lip-sync and the borrowed player |
+| S6b the clips themselves | 26 | the owner's media choice (Route A or B), OQ-4 review | depends on the route | the route's own policy and consent gate (Task 26, Step 1) |
+| S7 real-figure videos | none here | written estate consent (spec 11.3) | - | not planned until consent exists |
+
+The slices run in the table's order: S3's encyclopedia takes over the chain's reopen button that S2 moves, and S4's teaching messages open S3's pages. Each slice is one PR.
+
+## Files
+
+| File | Responsibility | Task |
+|---|---|---|
+| `unity/Assets/Resources/Advisors/advisor-messages.yaml` (new) | advisors, messages, pages, media rows | 1, 9, 13, 16 to 20, 22, 26 |
+| `unity/Assets/Scripts/UI/AdvisorCatalog.cs` (new) | parse and check the data file | 1, 8, 13, 19, 23 |
+| `unity/Assets/Scripts/UI/AdvisorSettings.cs` (new) | help level, seen marks, opening mark in the settings file | 2 |
+| `unity/Assets/Scripts/UI/AdvisorQueue.cs` (new) | order, caps, help level, history, put-off | 3, 21, 22 |
+| `unity/Assets/Scripts/UI/AdvisorLayout.cs` (new) | the popup's slot per HUD tier; moving off a target | 4 |
+| `unity/Assets/Scripts/UI/AdvisorSignals.cs` (new) | event and state signals, `when` conditions | 1, 5, 9, 16 to 20, 22 |
+| `unity/Assets/Scripts/UI/AdvisorPresenter.cs` (new) | the popup, the opening chain, Show me, the cover hook | 5 to 11, 13, 17, 19, 21, 24, 25 |
+| `unity/Assets/Scripts/UI/EncyclopediaPresenter.cs` (new; replaces `HowToPlayPresenter.cs`) | the encyclopedia screen | 12, 13, 25 |
+| `unity/Assets/Scripts/UI/CounselPresenter.cs` (new) | Counsel: concerns, history, disagreement | 21, 22, 25 |
+| `unity/Assets/Scripts/UI/AdvisorMedia.cs` (new) | picture, narration, captions, sync, inline or overlay | 24, 25 |
+| `unity/Assets/Scripts/UI/AdvisorSession.cs`, `AdvisorTargets.cs`, `AdvisorQuotes.cs` (new) | the session; Show me's targets; the verified quotes | 5, 9; 8; 19 |
+| `sim/Statecraft.Sim/Threats.cs` (new) | the read-only city-at-risk helper | 15 |
+| `unity/Assets/UI/Game.uxml`, `Statecraft.uss`, `strings.en.yaml`, `strings.he.yaml` | layer, popup, screens, strings | most tasks |
+| `unity/Assets/Scripts/UI/GameRoot.cs`, `ScreenNav.cs`, `SettingsPresenter.cs` | wiring | 5, 7, 11, 12, 14, 21 |
+
+---
+
+## S1: the engine and the popup shell
+
+### Task 1: The message file and its checks
+
+**Files:**
+- Create: `unity/Assets/Resources/Advisors/advisor-messages.yaml`
+- Create: `unity/Assets/Scripts/UI/AdvisorCatalog.cs`
+- Test: `unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs`
+
+**Interfaces:**
+- Consumes: `UiText.Parse(string yaml, string file)`, `UiText.Has(string)`, `UiText[string]` (`UiText.cs:27`, `:36`, `:38`); the YamlDotNet pattern of `EventVideoMapping.ParseDoc` (`EventVideoMapping.cs:56-64`).
+- Produces: `AdvisorCatalog` with `Advisors`, `Messages`, `Pages` (lists of `AdvisorCatalog.Advisor { Id, Person }`, `AdvisorCatalog.Message`, `AdvisorCatalog.Page`), `Find(string id) -> Message?`, `FindPage(string id) -> Page?`, `AdvisorOf(string id) -> Advisor`, `static Parse(string yaml)`, `static Load()`, `Problems(UiText en, UiText he, AdvisorCatalog.Known known) -> List<string>`, `static Shipped() -> Known`. `Message` has `Id, Advisor, Signal, When (Dictionary<string,double>), Requires (List<string>), Level, Priority, Repeat, CooldownTurns, Actions (List<AdvisorCatalog.Act>), Quote, DisagreesWith, HeReview` and the derived `Teaching`, `Critical`, `ApprovedIn(bool hebrew)`. `Act` has `ShowMe, OpenScreen, Encyclopedia` (strings) and `OpenCard` (bool). Constants `Levels = { "new", "experienced", "warnings", "critical" }`, `Approved = "approved"`, `Pending = "pending"`, `AdvisorIds = { "ben_gurion", "meyerson", "dayan" }`. String keys: `advisor.<id>.text`; pages `advisor.page.<id>.title`, `advisor.page.<id>.text`.
+
+- [ ] **Step 1: Write the failing tests** in `AdvisorCatalogTests.cs`:
+
+```csharp
+#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));
+ }
+}
+```
+
+- [ ] **Step 2: Run** with `FILTER="AdvisorCatalogTests"`; expect compile errors (`AdvisorCatalog` does not exist).
+
+- [ ] **Step 3: Write the data file** `unity/Assets/Resources/Advisors/advisor-messages.yaml`:
+
+```yaml
+# 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: []
+```
+
+- [ ] **Step 4: Write `AdvisorCatalog.cs`:**
+
+```csharp
+#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;
+ }
+ }
+}
+```
+
+`AdvisorSignals` (Task 5) does not exist yet: add its skeleton now so this compiles (Task 5 adds the evaluation):
+
+```csharp
+#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>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;
+ }
+}
+```
+
+Put it in `unity/Assets/Scripts/UI/AdvisorSignals.cs`.
+
+- [ ] **Step 5: Run `AdvisorCatalogTests`; expect PASS** (6 tests, 21 cases with the TestCase rows).
+
+- [ ] **Step 6: Commit.** `git add` the four files and their `.meta`; `git commit -m "ui: the advisors' data file and its checks (Refs #1484)"`
+
+### Task 2: The settings lines
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorSettings.cs`
+- Test: `unity/Assets/Tests/EditMode/AdvisorSettingsTests.cs`
+
+**Interfaces:**
+- Consumes: `SettingsStore.Read`, `Write` (`SettingsStore.cs:31`, `:41`); `FirstTurnGuidePresenter.SeenKey` = `"first_turn_guide"` (`FirstTurnGuidePresenter.cs:35`), copied as a string so S2 can delete the guide.
+- Produces: `AdvisorSettings(SettingsStore? store)`; `HasFile` (bool); `Level` (string, one of `Levels`), `LevelRank` (0 to 3), `SetLevel(string)`; `Seen(string id)`, `MarkSeen(string id)`; `OpeningSeen`, `MarkOpeningSeen()`; constants `LevelKey = "advisor_level"`, `SeenKey = "advisor_seen"`, `OpeningKey = "advisor_opening"`, `GuideSeenKey = "first_turn_guide"`, `Levels = { "new", "experienced", "warnings", "off" }`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#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);
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorSettingsTests"`; expect compile errors.
+
+- [ ] **Step 3: Implement `AdvisorSettings.cs`:**
+
+```csharp
+#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}"); }
+ }
+ }
+}
+```
+
+- [ ] **Step 4: Run `AdvisorSettingsTests`; expect PASS** (4).
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' settings lines (Refs #1484)"`
+
+### Task 3: The queue
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorQueue.cs`
+- Test: `unity/Assets/Tests/EditMode/AdvisorQueueTests.cs`
+
+**Interfaces:**
+- Consumes: `AdvisorCatalog`, `AdvisorCatalog.Message` (Task 1), `AdvisorSettings` (Task 2).
+- Produces: `AdvisorQueue(AdvisorCatalog, AdvisorSettings)`; `Offer(IReadOnlyCollection<string> holding, Func<IReadOnlyDictionary<string,double>, bool> when, int turn)`; `Head(int turn, bool hebrew) -> Message?`; `Position(int turn, bool hebrew) -> (int number, int total)`; `Done(Message, int turn, DateTime date)`; `PutOff(Message, int turn, DateTime date)`; `Drop(Message, int turn, DateTime date)`; `Reset()`; `History` (`IReadOnlyList<AdvisorQueue.Entry>`, newest last; `Entry { string Id; int Turn; DateTime Date; Outcome Outcome }`, `enum Outcome { Shown, PutOff, Missed }`); `PutOffIds` (ids waiting from a Not now).
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#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)");
+ }
+}
+```
+
+The fixture's signal `s` is not a real signal; the queue does not check names (the catalogue does).
+
+- [ ] **Step 2: Run** `FILTER="AdvisorQueueTests"`; expect compile errors.
+
+- [ ] **Step 3: Implement `AdvisorQueue.cs`:**
+
+```csharp
+#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;
+ }
+ }
+}
+```
+
+- [ ] **Step 4: Run `AdvisorQueueTests`; expect PASS** (9 tests, 12 cases).
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' queue (Refs #1484)"`
+
+### Task 4: Where the popup goes
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorLayout.cs`
+- Test: `unity/Assets/Tests/EditMode/AdvisorLayoutTests.cs`
+
+**Interfaces:**
+- Consumes: `HudPresenter.TwoRowClass`, `ThreeRowClass` (`HudPresenter.cs:47`, `:52`).
+- Produces: `enum HudTier { OneRow, TwoRow, ThreeRow }`; `AdvisorLayout.Tier(VisualElement hudRoot) -> HudTier`; `AdvisorLayout.Slot(HudTier tier, Rect window, Rect rightColumn, Rect leftColumn, Rect minimap, Rect? decisionWaiting, Rect? toast, Rect? infoPanel, Rect? mapLabel) -> Rect`; `AdvisorLayout.Place(Rect slot, float height, Rect? avoid) -> Rect`; constants `Width = 400`, `EdgePx = 16`, `GapPx = 12`, `DecisionRowPx = 46`, `BelowPx = 8`.
+
+The numbers are spec 7.1's: the right column is `right: 16px; top: 112px; width: 480px` (`Statecraft.uss:214`), the minimap 380 px tall at its foot (`:433`), so at 1920x1080 the slot is x 1504 to 1904, y 166 to 672.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#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)");
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorLayoutTests"`; expect compile errors.
+
+- [ ] **Step 3: Implement `AdvisorLayout.cs`:**
+
+```csharp
+#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.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;
+ }
+ }
+}
+```
+
+- [ ] **Step 4: Run `AdvisorLayoutTests`; expect PASS** (4).
+- [ ] **Step 5: Commit.** `git commit -m "ui: where the advisor popup goes (Refs #1484)"`
+
+### Task 5: The popup, its buttons and the modal layers
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorPresenter.cs`, `unity/Assets/Scripts/UI/AdvisorSession.cs`
+- Modify: `unity/Assets/Scripts/UI/AdvisorSignals.cs` (the `Holds` and `When` helpers)
+- Modify: `unity/Assets/Scripts/UI/ScreenNav.cs:40-80` (one line at the end of `DisableCovered`)
+- Modify: `unity/Assets/UI/Game.uxml` (the advisor layer, after the first-turn guide's layer at `:444-458`), `unity/Assets/UI/Statecraft.uss` (a new block after the guide's at `:552-576`), both strings files
+- Test: `unity/Assets/Tests/EditMode/AdvisorPopupTests.cs`
+
+**Interfaces:**
+- Consumes: Tasks 1 to 4; `SimBridge.Changed`, `TurnEnded` (`SimBridge.cs:31`, `:33`); the open classes `StartScreenPresenter.OpenClass` (`StartScreenPresenter.cs:26`), `EventCardPresenter.OpenClass` (`EventCardPresenter.cs:24`; on the root only while the card shows uncollapsed, `:228`), `CaptureDialogPresenter.OpenClass` (`CaptureDialogPresenter.cs:28`), `TurnReportPresenter.OpenClass` (`TurnReportPresenter.cs:24`), `OutcomePresenter.OpenClass` (`OutcomePresenter.cs:26`), `EndScreenPresenter.OpenClass` (`EndScreenPresenter.cs:22`), `ScreenNav.ScreenOpenClass` (`ScreenNav.cs:22`) with `HudPresenter.TwoRowClass`; `PortraitCatalog.Get` (`PortraitCatalog.cs:26`); `HudPresenter.FlooredTextSize`, `ScreenPxPerPanelPx` (`HudPresenter.cs:89-95`); `FocusReturn.To` (`FocusReturn.cs:14`); `ScreenNav.Moves`, `OpeningClass`, `ClosingClass` (`ScreenNav.cs:105`, `:25`).
+- Produces: `AdvisorSession(AdvisorCatalog, AdvisorSettings, bool autoShow)` with `Catalog`, `Settings`, `AutoShow`, `Queue`, `Fired` (event signals of `FiredTurn`), `Introduced(string advisor)`; `AdvisorPresenter(VisualElement root, SimBridge bridge, UiText text, AdvisorSession session, PortraitCatalog? portraits = null, AdvisorHooks? hooks = null)`; `AdvisorHooks` (Task 8 fills it; S1 has `EventCardPresenter? Card`); members `IsOpen`, `Shown` (`Message?`), `NewGame()`, `Notice(string signal)`, `GotIt()`, `NotNow()`, `Escape() -> bool`, `static Covered(VisualElement hudRoot) -> bool`, `Dispose()`; constants `OpenClass = "advisor-open"`, `LayerName = "advisor-layer"`, `CriticalClass = "advisor-critical"`, `NoPortraitClass = "advisor-no-portrait"`; element names `advisor-popup`, `advisor-portrait`, `advisor-name`, `advisor-role`, `advisor-text`, `advisor-show-me`, `advisor-more`, `advisor-not-now`, `advisor-got-it`, `advisor-close`, `advisor-count`. Strings: `advisor.ben_gurion.name`, `advisor.meyerson.name_first`, `advisor.meyerson.name`, `advisor.dayan.name`, `advisor.<advisor>.role`, `advisor.show_me`, `advisor.more`, `advisor.not_now`, `advisor.got_it`, `advisor.close`, `advisor.count`.
+
+- [ ] **Step 1: Write the failing tests** in `AdvisorPopupTests.cs`. The rig builds the real Game.uxml with the HUD, ScreenNav and the card, and a fixture catalogue with strings parsed on top of the real English file:
+
+```csharp
+#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.HudRoot.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("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");
+ }
+
+ [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("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");
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorPopupTests"`; expect compile errors.
+
+- [ ] **Step 3: The layer in `Game.uxml`.** After the first-turn guide's layer (`Game.uxml:444-458`), so it draws over the screens and the decision layer and under the turn report, the outcome clips and the start screen:
+
+```xml
+ <!-- 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 head and the actions carry `row`, so `.lang-he .row` (`Statecraft.uss:957-960`) runs them right to left in Hebrew: the portrait sits at the right, where a Hebrew reader starts (spec 7.1).
+
+- [ ] **Step 4: The styles in `Statecraft.uss`,** a block after the guide's:
+
+```css
+/* 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; }
+```
+
+- [ ] **Step 5: The strings.** In `strings.en.yaml`, after the guide's block:
+
+```yaml
+# 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}"
+```
+
+In `strings.he.yaml`, at the same place:
+
+```yaml
+# 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}"
+```
+
+- [ ] **Step 6: `AdvisorSession.cs`:**
+
+```csharp
+#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));
+ }
+}
+```
+
+- [ ] **Step 7: `AdvisorSignals` helpers.** Add to `AdvisorSignals`:
+
+```csharp
+ /// <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;
+ }
+```
+
+- [ ] **Step 8: `AdvisorPresenter.cs`:**
+
+```csharp
+#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 (VisualElement element, float px)[] floored;
+ float flooredFor;
+ bool disposed, hidden = true;
+ /// <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;
+ bridge.Changed += onChanged; bridge.TurnEnded += onTurn;
+ layer.userData = onCover; // ScreenNav.DisableCovered calls it
+ 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;
+ popup.RemoveFromClassList(ScreenNav.ClosingClass);
+ if (!hudRoot.ClassListContains(OpenClass) && ScreenNav.Moves())
+ {
+ popup.AddToClassList(ScreenNav.OpeningClass);
+ popup.RegisterCallback<GeometryChangedEvent>(EndOpening);
+ }
+ hudRoot.AddToClassList(OpenClass);
+ Place();
+ }
+
+ void EndOpening(GeometryChangedEvent e)
+ {
+ popup.UnregisterCallback<GeometryChangedEvent>(EndOpening);
+ popup.RemoveFromClassList(ScreenNav.OpeningClass);
+ }
+
+ void Hide()
+ {
+ if (hidden) return;
+ hidden = true;
+ 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);
+ 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) return;
+ 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 || 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.</summary>
+ public bool Escape()
+ {
+ var focused = layer.focusController?.focusedElement as VisualElement;
+ if (!IsOpen || focused == null || !popup.Contains(focused)) return false;
+ GotIt();
+ return true;
+ }
+
+ /// <summary>Puts the popup in its slot (AdvisorLayout) and applies the text floor. Task 6 fills it in.</summary>
+ internal void Place() { }
+
+ public void Dispose()
+ {
+ if (disposed) return;
+ disposed = true;
+ 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);
+ }
+ }
+}
+```
+
+- [ ] **Step 9: The hook in `ScreenNav.DisableCovered`.** As its last statement (after the end screen's block, `ScreenNav.cs:73-79`):
+
+```csharp
+ // 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();
+```
+
+- [ ] **Step 10: Run** `FILTER="AdvisorPopupTests;AdvisorQueueTests;AdvisorCatalogTests"`; expect PASS (`HidesUnderEveryModalLayerAndComesBack` has 7 cases). Then the classes whose layers call `DisableCovered`, to see the hook changes nothing there: `FILTER="DecisionCardTests;CaptureDialogTests;TurnReportTests;OutcomeClipTests;EndScreenTests;StartScreenTests;HudTests;UiFoundationTests"`; expect the same results as on main.
+
+- [ ] **Step 11: Commit.** `git commit -m "ui: the advisor popup and its modal layers (Refs #1484)"`
+
+### Task 6: The popup at every window, in both languages
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/AdvisorPresenter.cs` (`Place`)
+- Test: `unity/Assets/Tests/EditMode/AdvisorPopupLayoutTests.cs`
+
+**Interfaces:**
+- Consumes: `AdvisorLayout` (Task 4); the elements `right-column`, `left-column`, `minimap`, `map-layer`, `event-reopen`, `toast`, `info-panel` (`Game.uxml:114`, `:121`, `:117`, `:240`, `:584`, `:135`).
+- Produces: `AdvisorPresenter.Place()` and `Place(Rect? avoid) -> Rect?` (internal), `AdvisorPresenter.Slot()` (internal, the slot in the layer's space); the popup follows the layout with a 100 ms timer while it shows, as the guide's ring did (`FirstTurnGuidePresenter.cs:110-113`).
+
+- [ ] **Step 1: Write the failing UnityTest** (the real Game.uxml and PanelSettings at each window, as `FirstTurnGuideTests.EachStep` does, `FirstTurnGuideTests.cs:722-761`):
+
+```csharp
+#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));
+ }
+
+ 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.</summary>
+ internal static IEnumerator Shown(int w, int h, bool hebrew, System.Action<VisualElement, AdvisorPresenter> check)
+ {
+ 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();
+ for (int i = 0; i < 5; i++) yield return null;
+ 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);
+ }
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorPopupLayoutTests"`; expect failures: the popup sits at the layer's top-left (Place is empty).
+
+- [ ] **Step 3: Implement `Place` and `Slot`** in `AdvisorPresenter` (and a `follow` timer made in the constructor, `follow = layer.schedule.Execute(Place).Every(100); follow.Pause();`, resumed in `Show`, paused in `Hide` and `Dispose`):
+
+```csharp
+ /// <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 = 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 = at.width; popup.style.maxHeight = slot.height;
+ return at;
+ }
+
+ 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);
+ }
+ }
+```
+
+- [ ] **Step 4: Run** `FILTER="AdvisorPopupLayoutTests;AdvisorPopupTests"`; expect PASS. If one window fails, read the logged rects and fix the slot inputs, never the test's windows.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisor popup in its slot at every window (Refs #1484)"`
+
+### Task 7: GameRoot builds the advisors
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/GameRoot.cs` (fields near `:70-72`; Begin after the guide's construction at `:512-514`; `nav!.TakesEscape` at `:299`; the start screen's close at `:467`)
+- Test: `unity/Assets/Tests/EditMode/AdvisorGameTests.cs`
+
+**Interfaces:**
+- Consumes: Tasks 1 to 6; `GameRoot.SettingsFile()` (`GameRoot.cs:96`), `FirstCardCheckRequested()`, `showsStart` (`:262`), `portraits`, `card`, `nav`, `newGame`; `Begin(inputs, 0, keep: Bridge)` from `SwitchLanguage` (`:548-556`), which shows no start screen.
+- Produces: `internal AdvisorPresenter? Advisor` and `internal AdvisorSession? AdvisorSession` on GameRoot. The session is kept when Begin rebuilds over the same game (`keep != null`) and new otherwise.
+
+- [ ] **Step 1: Write the failing tests** (the scene harness of `FirstTurnGuideTests.OpenScene`, `FirstTurnGuideTests.cs:76-83`):
+
+```csharp
+#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.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);
+ }
+
+ [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");
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorGameTests"`; expect compile errors (`Advisor`, `AdvisorSession`).
+
+- [ ] **Step 3: Wire GameRoot.** Fields beside `guide` (`GameRoot.cs:70-72`):
+
+```csharp
+ 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; }
+```
+
+In Begin, right after the guide is made (`:512-514`):
+
+```csharp
+ // 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)
+ AdvisorSession = new AdvisorSession(AdvisorCatalog.Load(), new AdvisorSettings(SettingsFile()),
+ autoShow: showsStart && !FirstCardCheckRequested() && SettingsFile() != null);
+ 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;
+```
+
+In the start screen's callback (`:467`): `if (!shown && start?.Resumed == false) { firstTurn?.NewGame(); advisor?.NewGame(); }`. Escape (`:299`): `nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape() || advisor?.Escape() == true;`. In Shutdown's reset line (`:627`), add `advisor = null;`.
+
+- [ ] **Step 4: Run** `FILTER="AdvisorGameTests;FirstTurnGuideTests;HebrewUiTests;GameSceneTests"`; expect PASS, and the guide's 17 unchanged (the shipped file has no message yet).
+- [ ] **Step 5: The slice's gates.** The full EditMode run on the branch merged with origin/main (0 NEW), `bash scripts/check.sh origin/main`, the boot timing on base and PR, `changelog.d/advisors-s1.md`:
+
+```markdown
+- 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).
+```
+
+ No screenshot is needed: nothing shows. Commit, push `feat/advisors-s1`, open the PR (`Refs #1484`, the template's "AI assistance" and a three-line "Self-review").
+
+---
+
+## S2: the opening chain replaces the first-turn guide
+
+### Task 8: Show me: named targets, the gold ring and the selection
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorTargets.cs`
+- Modify: `unity/Assets/Scripts/UI/AdvisorPresenter.cs` (`AdvisorHooks`, `ShowMe`, the ring, `Place(avoid)`), `AdvisorCatalog.cs` (`Shipped().Targets`)
+- Modify: `unity/Assets/UI/Game.uxml` (`advisor-ring`, first child of `advisor-layer`), `Statecraft.uss`
+- Test: `unity/Assets/Tests/EditMode/AdvisorShowMeTests.cs`
+
+**Interfaces:**
+- Consumes: the guide's target rules and helpers, moved here unchanged: `Targets` (`FirstTurnGuidePresenter.cs:282-303`), `Shown` (`:362-368`), `CityHex` (`:372-380`), `UnitToShow` (both overloads, `:385-390`), `MoveStepDistanceM` (`:43`), the ring's placing (`:321-343`, without the dock); `GddHexPanel.HostName`; `MapLabelsPresenter.ToPanel` (used by GameRoot for `MapTarget`).
+- Produces: `AdvisorTargets.Names` (`attention`, `city_housing`, `city_training`, `unit_move`, `decision_waiting`, and `nav_<screen>` for each `ScreenNav.Screens` entry with `-` as `_`), `AdvisorTargets.Find(VisualElement hudRoot, string name, EventCardPresenter? card) -> IReadOnlyList<VisualElement>`, `ShowsCity(string)`, `ShowsUnit(string)`, `Area(IEnumerable<VisualElement>) -> Rect?`, `CityHex`, `UnitToShow` (both), `MoveStepDistanceM`. `AdvisorHooks` gains `Action? ShowCity, ShowUnit`, `Func<Action>? KeepSelection`, `Func<Rect?>? MapTarget` (the shown unit's or city's hex in panel px). `AdvisorPresenter.ShowTarget(string name)` (also for the encyclopedia, Task 12), `ClearTarget()`, `RingClass = "advisor-ring-open"`, `RingOnlyMs = 4000`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#nullable enable
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+/// <summary>Spec 7.3: Show me draws the gold ring round the named part of the real HUD, shows a unit or a city as a click
+/// would and puts the selection back after, moves the popup off its target, and never carries out the advised action.</summary>
+public class AdvisorShowMeTests
+{
+ const string Catalog = "advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\n" +
+ "messages:\n" +
+ " - { id: t.att, advisor: ben_gurion, signal: new_game, level: new, actions: [{ show_me: attention }] }\n" +
+ " - { id: t.city, advisor: meyerson, signal: turn_ended, level: new, actions: [{ show_me: city_housing }] }\n";
+
+ static UiText Text() => UiText.Parse(UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text +
+ "\nadvisor.t.att.text: \"Attention.\"\nadvisor.t.city.text: \"A city.\"\n");
+
+ [Test]
+ public void EveryNameIsKnownAndEverySideMenuButtonHasOne()
+ {
+ foreach (var s in ScreenNav.Screens) CollectionAssert.Contains(AdvisorTargets.Names, AdvisorTargets.Nav(s));
+ using var ui = new UiTestKit();
+ foreach (var (name, element) in new[] { ("attention", "attention"), ("nav_objectives", "nav-objectives"), ("nav_budget", "nav-budget") })
+ Assert.AreEqual(element, AdvisorTargets.Find(ui.Root.Q("root"), name, null).Single().name, name);
+ }
+
+ [Test]
+ public void ShowMeOnACityShowsItAndPutsTheSelectionBackWhenDone()
+ {
+ var calls = new List<string>();
+ using var rig = new AdvisorPopupTests.Rig(catalog: Catalog, text: Text(), hooks: new AdvisorHooks
+ {
+ ShowCity = () => calls.Add("city"), KeepSelection = () => { calls.Add("keep"); return () => calls.Add("back"); },
+ });
+ rig.Advisor.NewGame(); rig.Ui.Press("advisor-got-it");
+ rig.EndTurn();
+ Assert.AreEqual("t.city", rig.Advisor.Shown!.Id, "precondition");
+ rig.Ui.Press("advisor-show-me");
+ CollectionAssert.AreEqual(new[] { "keep", "city" }, calls);
+ Assert.IsTrue(rig.HudRoot.ClassListContains(AdvisorPresenter.RingClass));
+ rig.Ui.Press("advisor-got-it");
+ CollectionAssert.AreEqual(new[] { "keep", "city", "back" }, calls, "Got it puts back what Show me found");
+ Assert.IsFalse(rig.HudRoot.ClassListContains(AdvisorPresenter.RingClass));
+ }
+
+ /// <summary>Review Focus 5 (desktop half): a target the popup's top would cover sends the popup to its slot's foot.</summary>
+ [UnityTest]
+ public IEnumerator AShowMeTargetUnderThePopupIsUncovered()
+ {
+ yield return AdvisorPopupLayoutTests.Shown(1280, 720, false, (root, advisor) =>
+ {
+ var slot = advisor.Slot();
+ var target = new Rect(slot.xMin + 20, slot.yMin + 10, 60, 30); // a map target in the slot's upper part
+ var popup = advisor.Place(target)!.Value;
+ Assert.IsFalse(popup.Overlaps(target), $"{popup} covers {target}");
+ Assert.LessOrEqual(popup.yMax, slot.yMax + 0.5f);
+ });
+ }
+
+ [UnityTest]
+ public IEnumerator TheRingGoesRoundAttentionInsideTheWindow()
+ {
+ yield return AdvisorPopupLayoutTests.Shown(1280, 720, false, (root, advisor) =>
+ {
+ advisor.ShowTarget(AdvisorTargets.Attention); // places the ring at once (its style; the layout follows)
+ var s = root.Q("advisor-ring").style;
+ var ring = new Rect(s.left.value.value, s.top.value.value, s.width.value.value, s.height.value.value);
+ var layer = root.Q(AdvisorPresenter.LayerName); var a = root.Q("attention").worldBound;
+ var target = Rect.MinMaxRect(layer.WorldToLocal(a.min).x, layer.WorldToLocal(a.min).y, layer.WorldToLocal(a.max).x, layer.WorldToLocal(a.max).y);
+ Assert.IsTrue(ring.Contains(target.min) && ring.Contains(target.max), $"{ring} round {target}");
+ Assert.IsTrue(new Rect(Vector2.zero, layer.layout.size).Contains(ring.max), "inside the window");
+ });
+ }
+}
+```
+
+These tests reuse `AdvisorPopupTests.Rig` (its `hooks` parameter) and `AdvisorPopupLayoutTests.Shown` (Tasks 5 and 6).
+
+- [ ] **Step 2: Run** `FILTER="AdvisorShowMeTests"`; expect compile errors (`AdvisorTargets`, `RingClass`, `ShowTarget`).
+
+- [ ] **Step 3: `AdvisorTargets.cs`.** Move the guide's helpers here as they are (CityHex, both UnitToShow, MoveStepDistanceM, Shown), and write `Find` from the guide's `Targets` switch:
+
+```csharp
+ public const string Attention = "attention", CityHousing = "city_housing", CityTraining = "city_training",
+ UnitMove = "unit_move", DecisionWaiting = "decision_waiting";
+
+ public static string Nav(string screen) => "nav_" + screen.Replace('-', '_');
+
+ public static IReadOnlyList<string> Names =>
+ new[] { Attention, CityHousing, CityTraining, UnitMove, DecisionWaiting }.Concat(ScreenNav.Screens.Select(Nav)).ToList();
+
+ public static bool ShowsCity(string name) => name == CityHousing || name == CityTraining;
+ public static bool ShowsUnit(string name) => name == UnitMove;
+
+ /// <summary>The shown elements a name points at, as the HUD has them now (the guide's rules, #1265, #1189).</summary>
+ public static IReadOnlyList<VisualElement> Find(VisualElement hudRoot, string name, EventCardPresenter? card)
+ {
+ var found = new List<VisualElement?>();
+ var host = hudRoot.Q(GddHexPanel.HostName);
+ switch (name)
+ {
+ case Attention: found.Add(hudRoot.Q("attention")); break;
+ case CityHousing: foreach (var n in new[] { "city-housing", "city-jobs-row", "city-workers-row" }) found.Add(host?.Q(n)); break;
+ case CityTraining:
+ if (host != null) found.AddRange(host.Query<VisualElement>().Where(e => e.name.StartsWith("city-train-", StringComparison.Ordinal) && e.name.EndsWith("-row", StringComparison.Ordinal)).ToList());
+ break;
+ case UnitMove: found.Add(hudRoot.Q("info-move")); break;
+ case DecisionWaiting: found.Add(card?.Shown != null && card.Collapsed ? hudRoot.Q("event-reopen") : hudRoot.Q("event-options")); break;
+ default:
+ var screen = ScreenNav.Screens.FirstOrDefault(s => Nav(s) == name);
+ if (screen != null) found.Add(hudRoot.Q("nav-" + screen));
+ break;
+ }
+ return found.Where(e => e != null && Shown(e)).Select(e => e!).ToList();
+ }
+
+ public static Rect? Area(IEnumerable<VisualElement> targets)
+ {
+ Rect? area = null;
+ foreach (var e in targets)
+ {
+ var r = e.worldBound;
+ area = area is Rect a ? Rect.MinMaxRect(Mathf.Min(a.xMin, r.xMin), Mathf.Min(a.yMin, r.yMin), Mathf.Max(a.xMax, r.xMax), Mathf.Max(a.yMax, r.yMax)) : r;
+ }
+ return area;
+ }
+```
+
+ Keep `FirstTurnGuidePresenter`'s own copies until Task 11 deletes it, pointing them at these (`public static (int q, int r)? CityHex(...) => AdvisorTargets.CityHex(...)` and so on), so GameRoot and the guide's tests keep compiling.
+
+- [ ] **Step 4: The ring in the presenter.** In Game.uxml, first inside `advisor-layer`: `<ui:VisualElement name="advisor-ring" class="advisor-ring" picking-mode="Ignore" />`. In Statecraft.uss:
+
+```css
+/* Show me's gold ring (spec 7.3), round the named part of the HUD; the guide's ring, moved. The layer shows for the ring
+ alone too (the encyclopedia's Show me), with the popup hidden. */
+.advisor-ring { display: none; position: absolute; border-width: 3px; border-color: var(--gold-light); border-radius: 6px; }
+.advisor-ring-open .advisor-layer, .advisor-ring-open .advisor-ring { display: flex; }
+.advisor-popup { display: none; }
+.advisor-open .advisor-popup { display: flex; }
+/* Under Attention's ring, End Turn's border is kept clear of it (the guide's rule, FirstTurnGuideTests): 5 px in the
+ one-row bar, 8 in the narrow one. */
+.advisor-ring-open #attention { margin-bottom: 5px; }
+.advisor-ring-open.hud-narrow #attention { margin-bottom: 8px; }
+```
+
+ In `AdvisorPresenter`: `public const string RingClass = "advisor-ring-open"; public const long RingOnlyMs = 4000;` fields `VisualElement ring; string? target; Action? putBack; IVisualElementScheduledItem? ringOnly;`.
+
+```csharp
+ /// <summary>Draws the ring round <paramref name="name"/>'s elements, showing its unit or city first as a click would
+ /// (the selection it finds is put back by ClearTarget). Never carries out the advised action (spec 7.3).</summary>
+ public void ShowTarget(string name)
+ {
+ if (disposed) return;
+ ClearTarget();
+ target = name;
+ if (AdvisorTargets.ShowsCity(name) || AdvisorTargets.ShowsUnit(name))
+ {
+ putBack = hooks.KeepSelection?.Invoke();
+ (AdvisorTargets.ShowsUnit(name) ? hooks.ShowUnit : hooks.ShowCity)?.Invoke();
+ }
+ hudRoot.AddToClassList(RingClass);
+ follow.Resume();
+ if (Shown == null) ringOnly = ring.schedule.Execute(ClearTarget).StartingIn(RingOnlyMs); // the encyclopedia's ring fades by itself
+ Place();
+ }
+
+ public void ClearTarget()
+ {
+ ringOnly?.Pause(); ringOnly = null;
+ target = null;
+ hudRoot.RemoveFromClassList(RingClass);
+ if (!hudRoot.ClassListContains(OpenClass)) follow.Pause();
+ var back = putBack; putBack = null;
+ back?.Invoke();
+ }
+```
+
+ `ShowMe()` calls `ShowTarget(a.ShowMe)` for a `show_me` action (beside `open_screen` and `open_card`); `GotIt`, `NotNow`, `Hide` (when the message leaves, not when a layer covers it) and `Dispose` call `ClearTarget()`. `Place()` becomes `Place(TargetRect())` with:
+
+```csharp
+ Rect? TargetRect()
+ {
+ if (target == null) return null;
+ if (AdvisorTargets.ShowsUnit(target) || AdvisorTargets.ShowsCity(target)) { if (hooks.MapTarget?.Invoke() is Rect m) return m; }
+ if (!(AdvisorTargets.Area(AdvisorTargets.Find(hudRoot, target, hooks.Card)) is Rect a)) { ring.style.display = DisplayStyle.None; return null; }
+ var local = Local(a);
+ var tl = Vector2.Max(local.min - new Vector2(4, 4), Vector2.zero);
+ var br = Vector2.Min(local.max + new Vector2(4, 4), layer.layout.size);
+ ring.style.display = StyleKeyword.Null;
+ ring.style.left = tl.x; ring.style.top = tl.y; ring.style.width = br.x - tl.x; ring.style.height = br.y - tl.y;
+ return local;
+ }
+```
+
+ and `Place()` (Task 6) passes `TargetRect()` as `avoid` to `Place(Rect? avoid)`. In `AdvisorCatalog.Shipped()`, set `Targets = AdvisorTargets.Names`.
+
+- [ ] **Step 5: Run** `FILTER="AdvisorShowMeTests;AdvisorPopupTests;AdvisorPopupLayoutTests;AdvisorCatalogTests;FirstTurnGuideTests"`; expect PASS (the guide's 17 unchanged).
+- [ ] **Step 6: Commit.** `git commit -m "ui: Show me, the advisors' gold ring and named targets (Refs #1484)"`
+
+### Task 9: The opening chain
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/AdvisorPresenter.cs` (chain mode), `AdvisorSession.cs` (`ChainState`), `AdvisorSignals.cs` (`opening`, `cards_waiting_at_least`)
+- Modify: `unity/Assets/Resources/Advisors/advisor-messages.yaml`, both strings files
+- Modify: `unity/Assets/Scripts/UI/GameRoot.cs` (the hooks from the guide's lambdas, `:475-510`)
+- Test: `unity/Assets/Tests/EditMode/AdvisorOpeningTests.cs` (the guide's tests, ported)
+
+**Interfaces:**
+- Consumes: Tasks 1 to 8; `EventCardPresenter.Shown`, `Collapsed`, `Collapse(bool)`, `Reopen()` (`EventCardPresenter.cs:164-200`); the guide's rules (`FirstTurnGuidePresenter.cs:126-265`): shown once on the first new game, never on Continue, never without a settings file, never under the start screen, skippable at any step, the selection put back, End turn closes it as the turn advances, the event step left out while no card waits.
+- Produces: `AdvisorSignals.Opening = "opening"` (an event signal nothing fires: chain messages are never offered to the queue), measure `cards_waiting_at_least` (1 while the card has an event, else 0); `AdvisorPresenter.OpenChain()`, `InChain`, `ChainStep` (index into `Chain`, -1 when closed), `Chain` (`IReadOnlyList<Message>`, the `opening` messages in `requires` order), `ChainIds`; `AdvisorSession.Chain` (`ChainState { int Step = -1; bool CardWasOpen; string? CardEvent; int OpenTurn; bool EventShown; }`). Element names reused: `advisor-got-it` reads Next or Done in the chain, `advisor-close` skips the chain. Strings `advisor.next`, `advisor.done`, `advisor.step` ("Step {0} of {1}").
+
+- [ ] **Step 1: The data.** Add to `advisor-messages.yaml`:
+
+```yaml
+# The opening chain (spec 9.2): shown once on the first new game, step by step, each pointing at the part of the HUD the
+# first-turn guide pointed at; its event step speaks before the card opens, and its Show me opens the card (spec 9.3).
+ - { id: opening.greeting, advisor: ben_gurion, signal: opening, level: new }
+ - { id: opening.attention, advisor: ben_gurion, signal: opening, level: new, requires: [opening.greeting], actions: [{ show_me: attention }] }
+ - { id: opening.city, advisor: meyerson, signal: opening, level: new, requires: [opening.attention], actions: [{ show_me: city_housing }] }
+ - { id: opening.training, advisor: meyerson, signal: opening, level: new, requires: [opening.city], actions: [{ show_me: city_training }] }
+ - { id: opening.move, advisor: dayan, signal: opening, level: new, requires: [opening.training], actions: [{ show_me: unit_move }] }
+ - { id: opening.event, advisor: ben_gurion, signal: opening, level: new, requires: [opening.move], when: { cards_waiting_at_least: 1 }, actions: [{ show_me: decision_waiting }, { open_card: true }] }
+ - { id: opening.objectives, advisor: ben_gurion, signal: opening, level: new, requires: [opening.event], actions: [{ show_me: nav_objectives }] }
+```
+
+ Task 13 adds each step's `encyclopedia` action once its page exists (the checks refuse an action naming a missing page). Every row has `he_review: pending` by default.
+
+- [ ] **Step 2: The lines.** English, each from the guide's reviewed text (`strings.en.yaml:83-95`) in the speaker's voice, 35 words at most:
+
+```yaml
+# The opening chain (spec 9.2; AdvisorPresenter): game dialogue in each advisor's persona, labelled "Advisor", never a
+# quote. Each step carries the first-turn guide's facts (#42), without balance values. The owner reviews every line.
+advisor.opening.greeting.text: "Everything needs doing at once. My colleagues and I will show you the essentials, one at a time."
+advisor.opening.attention.text: "Most orders cost Attention, shown here. It refills at the start of each turn, and Attention left unspent does not carry over."
+advisor.opening.city.text: "This is one of our cities. Its housing and jobs decide how people live. The + and − buttons set how many people work; the order takes effect when the turn ends."
+advisor.opening.training.text: "Civilians without work train here: as recruits at a military camp, or as halutzim, pioneers who build settlements, at a Hakhshara. Each button shows the cost and the training time."
+advisor.opening.move.text: "Select one of our units, press Move and choose a lit hex. The unit moves when the turn ends."
+advisor.opening.event.text: "A decision is waiting. Answering costs Attention, and the choice takes effect when the turn ends. A card left unanswered goes to the responsible minister."
+advisor.opening.objectives.text: "Objectives lists the game's goals, with the date you completed each beside the historical one. Completing one also brings its card."
+advisor.next: "Next"
+advisor.done: "Done"
+# {0} the step, {1} the steps in the chain now.
+advisor.step: "Step {0} of {1}"
+```
+
+ `opening.move` ports whatever `guide.move.text` says on main when this task runs (OQ-9): if the civ-movement slice has changed it, take its new facts. Hebrew drafts, from the guide's Hebrew (`strings.he.yaml:74-87`), plural address (HE-03), under the comment "Agent-drafted, NOT approved: he_review pending in advisor-messages.yaml (spec OQ-4). For the native reviewer (#564).":
+
+```yaml
+advisor.opening.greeting.text: "הכול צריך להיעשות בבת אחת. חבריי ואני נראה לכם את העיקר, צעד אחר צעד."
+advisor.opening.attention.text: "רוב ההוראות עולות תשומת לב, המוצגת כאן. היא מתמלאת מחדש בתחילת כל תור, ותשומת לב שלא ניצלתם אינה עוברת לתור הבא."
+advisor.opening.city.text: "זו אחת הערים שלנו. הדיור והמשרות בה קובעים איך אנשים חיים. הכפתורים + ו־− קובעים כמה אנשים עובדים, וההוראה מתבצעת בסיום התור."
+advisor.opening.training.text: "אזרחים ללא עבודה מתאמנים כאן: כמגויסים במחנה צבאי, או כחלוצים שבונים יישובים בהכשרה. כל כפתור מציג את העלות ואת משך ההכשרה."
+advisor.opening.move.text: "בחרו אחת מהיחידות שלנו, לחצו על תנועה ובחרו משושה מואר. היחידה תנוע בסיום התור."
+advisor.opening.event.text: "החלטה ממתינה. מענה עולה תשומת לב, והבחירה נכנסת לתוקף בסיום התור. כרטיס שלא עניתם עליו עובר לשר האחראי."
+advisor.opening.objectives.text: "במסך היעדים מופיעים יעדי המשחק ולצד כל אחד התאריך שבו השלמתם אותו לעומת התאריך ההיסטורי. השלמת יעד מביאה גם את הכרטיס שלו."
+advisor.next: "הבא"
+advisor.done: "סיום"
+advisor.step: "שלב {0} מתוך {1}"
+```
+
+- [ ] **Step 3: Write the failing tests** by porting `FirstTurnGuideTests.cs` into `AdvisorOpeningTests.cs`. Copy the file, keep its harness (`OpenScene`, `Rig`, `PanelAndGuide` rebuilt as `PanelAndAdvisor`, `EachStep`, `Inside`, `Gap`) and apply these renames everywhere:
+
+| In the guide's tests | In the chain's tests |
+|---|---|
+| `game.Guide`, `rig.Guide`, `guide` | `game.Advisor`, `rig.Advisor`, `advisor` |
+| `guide.IsOpen`, `guide.Step` | `advisor.InChain`, `advisor.ChainStep` |
+| `guide.Open()`, `guide.Close()`, `guide.Next()`, `guide.NewGame()` | `advisor.OpenChain()`, `advisor.CloseChain()`, `advisor.NextStep()`, `advisor.NewGame()` |
+| `FirstTurnGuidePresenter.Steps` | `AdvisorPresenter.ChainIds` (the seven ids) |
+| `FirstTurnGuidePresenter.EventStep` (4) | `AdvisorPresenter.EventStep` (5: the greeting comes first) |
+| `FirstTurnGuidePresenter.SeenKey` | `AdvisorSettings.OpeningKey` |
+| `FirstTurnGuidePresenter.OpenClass` | `AdvisorPresenter.OpenClass` |
+| `CityHex`, `UnitToShow`, `MoveStepDistanceM` | `AdvisorTargets.CityHex`, `.UnitToShow`, `.MoveStepDistanceM` |
+| `"guide-next"`, `"guide-skip"` | `"advisor-got-it"`, `"advisor-close"` |
+| `"guide-count"`, `"guide-title"`, `"guide-text"`, `"guide-panel"`, `"guide-ring"` | `"advisor-count"`, `"advisor-name"`, `"advisor-text"`, `"advisor-popup"`, `"advisor-ring"` |
+| `text["guide." + key + ".title"]`, `.text` | `text["advisor." + m.Advisor + ".name"]` (or `name_first`), `text["advisor." + id + ".text"]` |
+| `text.Format("guide.step", n, t)`, `"guide.next"`, `"guide.done"` | `text.Format("advisor.step", n, t)`, `"advisor.next"`, `"advisor.done"` |
+| `"how-to-play-guide"` | `"how-to-play-guide"` (unchanged until Task 12) |
+| `CountPx, TitlePx, TextPx, ButtonPx` (18, 29, 22, 19) | `AdvisorPresenter.CountPx, NamePx, TextPx, ButtonPx` (15, 24, 22, 19) |
+
+ What changes beyond the renames, written out:
+
+```csharp
+ /// <summary>Spec 9.2: seven steps, the greeting first; the guide's six after it in the guide's order.</summary>
+ [Test]
+ public void HasSevenStepsInOrder()
+ {
+ CollectionAssert.AreEqual(new[] { "opening.greeting", "opening.attention", "opening.city", "opening.training", "opening.move",
+ "opening.event", "opening.objectives" }, AdvisorPresenter.ChainIds(AdvisorCatalog.Load()));
+ Assert.AreEqual(5, AdvisorPresenter.EventStep);
+ var targets = AdvisorCatalog.Load().Messages.Where(m => m.Signal == AdvisorSignals.Opening)
+ .Select(m => m.Actions.FirstOrDefault(a => a.ShowMe != "")?.ShowMe ?? "").ToArray();
+ CollectionAssert.AreEqual(new[] { "", "attention", "city_housing", "city_training", "unit_move", "decision_waiting", "nav_objectives" }, targets,
+ "the guide's targets, in its order");
+ }
+
+ /// <summary>The Hebrew variant runs on a copy of the shipped file with every row approved: the shipped Hebrew is
+ /// pending (OQ-4), and a pending step never shows in Hebrew (ThePendingChainDoesNotOpenInHebrew).</summary>
+ static AdvisorCatalog Approved() =>
+ AdvisorCatalog.Parse(System.IO.File.ReadAllText(AdvisorCatalog.Path).Replace("level: new", "level: new, he_review: approved"));
+
+ [Test]
+ public void ThePendingChainDoesNotOpenInHebrewAndIsNotMarkedSeen()
+ {
+ using var rig = new Rig(He, new SettingsStore(TempDir())); // the shipped, pending catalogue
+ rig.Advisor.NewGame();
+ Assert.IsFalse(rig.Advisor.InChain, "no unreviewed Hebrew shows");
+ Assert.IsFalse(rig.Session.Settings.OpeningSeen, "so it can show once its Hebrew is approved");
+ }
+
+ /// <summary>Review Focus 3: Settings' language switch rebuilds every presenter over the same game; the chain keeps its
+ /// step. Into Hebrew while it is pending, it hides (nothing unreviewed shows); back in English it is where it was.</summary>
+ [Test]
+ public void ALanguageSwitchMidChainKeepsTheStep()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0, startScreen: true);
+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));
+ UiTestKit.Press(Ui.Q<Button>("advisor-got-it")); UiTestKit.Press(Ui.Q<Button>("advisor-got-it"));
+ Assert.AreEqual(2, game.Advisor!.ChainStep, "precondition: the city step");
+ UiTestKit.Press(Ui.Q<Button>("nav-settings")); UiTestKit.Press(Ui.Q<Button>("settings-language-he"));
+ Assert.IsFalse(game.Advisor!.IsOpen, "Hebrew: pending, hidden");
+ Assert.AreEqual(2, game.AdvisorSession!.Chain.Step, "but not forgotten");
+ UiTestKit.Press(Ui.Q<Button>("nav-settings")); UiTestKit.Press(Ui.Q<Button>("settings-language-en"));
+ UiTestKit.Press(Ui.Q<Button>("nav-settings")); // close Settings
+ Assert.IsTrue(game.Advisor!.InChain);
+ Assert.AreEqual(2, game.Advisor.ChainStep, "the same step, not the greeting");
+ }
+```
+
+ `CanBeSkippedAtAnyStepAndReopened(hebrew)` builds its `Rig` with `Approved()` for both languages and walks seven steps; `WithNoCardTheEventStepIsLeftOut` expects six steps (`"opening.greeting", "opening.attention", "opening.city", "opening.training", "opening.move", "opening.objectives"`). `AnsweringTheCardOnItsStepGoesOnToTheNext` is not ported here: Task 10 restates it. The four `[UnityTest]`s (`TheMoveStepShowsTheUnitAndAReachableHexOnTheMap`, `EveryStepPointsAtAVisibleElement`, `TheGuideReadsAtTheItchEmbedSize`, `TheGuideKeepsTheTextFloorOnEveryWindow`) move in Task 10. That leaves 13 of the 17 here, plus the two above.
+
+- [ ] **Step 4: Run** `FILTER="AdvisorOpeningTests"`; expect compile errors (`InChain`, `ChainStep`, `OpenChain`, `ChainIds`, `EventStep`).
+
+- [ ] **Step 5: Implement the chain.** In `AdvisorSignals`: `Opening = "opening"` added to `Events`, and the measure `["cards_waiting_at_least"] = ctx => ctx.Card?.Shown != null ? 1 : 0`. In `AdvisorSession`: `public ChainState Chain { get; } = new ChainState();` with the class from Interfaces. In `AdvisorPresenter`:
+
+```csharp
+ /// <summary>The event step's index in the chain (opening.event; spec 9.3).</summary>
+ public const int EventStep = 5;
+
+ /// <summary>The opening messages in requires order (the chain is a line: each requires the one before).</summary>
+ public static IReadOnlyList<string> ChainIds(AdvisorCatalog c) => Chain(c).Select(m => m.Id).ToList();
+
+ static List<AdvisorCatalog.Message> Chain(AdvisorCatalog c)
+ {
+ var steps = c.Messages.Where(m => m.Signal == AdvisorSignals.Opening).ToList();
+ var line = new List<AdvisorCatalog.Message>();
+ var next = steps.FirstOrDefault(m => m.Requires.Count == 0);
+ while (next != null) { line.Add(next); next = steps.FirstOrDefault(m => m.Requires.Contains(line[line.Count - 1].Id)); }
+ return line;
+ }
+
+ public bool InChain => session.Chain.Step >= 0 && IsOpen;
+ public int ChainStep => InChain ? session.Chain.Step : -1;
+
+ /// <summary>A step is in the tour when its condition holds (the event step while a card waits) and its text may show in
+ /// this language (OQ-4).</summary>
+ bool InTour(AdvisorCatalog.Message m) => m.ApprovedIn(hebrew) && AdvisorSignals.When(Context(), m.When);
+```
+
+ `NewGame()` ends with: `if (session.AutoShow && !session.Settings.OpeningSeen && !hudRoot.ClassListContains(StartScreenPresenter.OpenClass) && Chain(session.Catalog).Any(InTour)) { session.Settings.MarkOpeningSeen(); OpenChain(); }` (a chain with nothing to show in this language is not marked seen). `OpenChain()` (the reopen button's handler too) notes the card as the guide did (`CardWasOpen`, `CardEvent`, `OpenTurn`), collapses an open card (`card.Collapse(takeFocus: false)`: the popup never sits over an open card, spec 4.2), sets `Step` to the first step in the tour and shows it. A chain step shows through `Fill` with three differences: the count reads `advisor.step` over the steps in the tour (the event step counted once shown, the guide's `Counted` rule, `FirstTurnGuidePresenter.cs:228-231`); `advisor-got-it` reads `advisor.next`, or `advisor.done` on the last step; Show me shows only for an `open_card` action, and the step's `show_me` target is drawn as it shows (`ShowTarget`), as the guide drew its ring. `NextStep()` marks the step done (`session.Queue.Done(m, Turn, date)`: seen, into Counsel's history, using turn one's teaching slot) and shows the next step in the tour, or closes the chain. `CloseChain()` (the X, Escape from inside, Done) restores the card as the guide did (`FirstTurnGuidePresenter.cs:212-216`), clears the target (putting the selection back), sets `Step = -1`, and lets the queue's head show. `TurnEnded` with the turn advanced closes the chain, restoring only the card it found (`:197-201`). The `Got it` button calls `NextStep` in the chain, `GotIt` otherwise; the X calls `CloseChain` in the chain. A rebuilt presenter whose session has `Chain.Step >= 0` shows that step again in its constructor (the language switch); the old `putBack` is dropped with the disposed UI, and the resumed step takes its own from the rebuilt hooks.
+
+ In GameRoot, move the guide's `showCity`, `showUnit` and `keepSelection` lambdas (`GameRoot.cs:475-510`) into the advisor's hooks (`ShowCity`, `ShowUnit`, `KeepSelection`), using `AdvisorTargets.CityHex` and `UnitToShow`, and add `MapTarget`: the shown unit's or city's hex projected to the panel (`MapLabelsPresenter.ToPanel(camera.WorldToViewportPoint(ground), camera.rect, root.panel.visualTree.layout.size, Vector2.zero)`, as `FirstTurnGuideTests.cs:428-437` does), as a 1 px rect, or null. The guide keeps its own copies of the lambdas until Task 11.
+
+- [ ] **Step 6: Run** `FILTER="AdvisorOpeningTests;AdvisorPopupTests;AdvisorShowMeTests;FirstTurnGuideTests"`; expect PASS. Both the guide and the chain open on a new game during this task (the guide goes in Task 11); `FirstTurnGuideTests` still passes, as each of its tests reads only the guide.
+- [ ] **Step 7: Commit.** `git commit -m "ui: the advisors' opening chain, the guide's tests ported (Refs #1484)"`
+
+### Task 10: The event step restated, and the chain at every window
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/AdvisorPresenter.cs` (the chain after the card closes)
+- Test: `unity/Assets/Tests/EditMode/AdvisorOpeningTests.cs`
+
+**Interfaces:**
+- Consumes: Task 9; `EventCardPresenter.Reopen`, `Collapse` (`EventCardPresenter.cs:171-197`); the cover hook (Task 5).
+- Produces: the chain's rule when its card closes: answered (no card waits) goes on to the next step; hidden again unanswered (the card waits) shows the event step again.
+
+- [ ] **Step 1: Write the restated test** (spec 9.3's four parts), and port the four `[UnityTest]`s with Task 9's renames: `TheMoveStepShowsTheUnitAndAReachableHexOnTheMap` checks the unit and a reachable hex are clear of `advisor-popup` (not `guide-panel`) at 1920x1080, 1280x720 and 390x844, which is Review Focus 5's phone half; `EveryStepPointsAtAVisibleElement` checks the ring round each step's target and the popup clear of it, with the greeting (no target) expecting no ring; the two text-size tests read the popup's sizes.
+
+```csharp
+ /// <summary>Spec 9.3, restated: (1) the event step shows while the card waits collapsed, its ring on Decision waiting;
+ /// (2) its Show me opens the card; (3) the popup is hidden while the card is open; (4) answering the card goes on to the
+ /// next step, and hiding it again unanswered shows the event step again.</summary>
+ [Test]
+ public void TheEventStepSpeaksBeforeTheCardAndStepsAside()
+ {
+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));
+ game.Begin(Inputs, 0, startScreen: true);
+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));
+ var advisor = game.Advisor!; var card = game.Card!;
+ for (int i = 0; i < AdvisorPresenter.EventStep; i++) UiTestKit.Press(Ui.Q<Button>("advisor-got-it"));
+ Assert.AreEqual(AdvisorPresenter.EventStep, advisor.ChainStep);
+ Assert.IsTrue(card.Shown != null && card.Collapsed, "(1) the card waits collapsed");
+ Assert.AreEqual("event-reopen", AdvisorTargets.Find(Ui.Q("root"), AdvisorTargets.DecisionWaiting, card).Single().name, "(1) the ring's target");
+ Assert.IsTrue(Ui.Q("root").ClassListContains(AdvisorPresenter.RingClass));
+
+ UiTestKit.Press(Ui.Q<Button>("advisor-show-me"));
+ Assert.IsFalse(card.Collapsed, "(2) Show me opens the card");
+ Assert.IsFalse(advisor.IsOpen, "(3) the popup steps aside");
+
+ card.Collapse(); // hidden again, unanswered
+ Assert.AreEqual(AdvisorPresenter.EventStep, advisor.ChainStep, "(4) the event step again");
+ Assert.IsTrue(advisor.IsOpen);
+
+ UiTestKit.Press(Ui.Q<Button>("advisor-show-me"));
+ UiTestKit.Press(Ui.Q("event-options").Query<Button>().First()); // answered
+ Assert.IsNull(card.Shown, "precondition: the opening turn's one card");
+ Assert.AreEqual("opening.objectives", AdvisorPresenter.ChainIds(AdvisorCatalog.Load())[advisor.ChainStep], "(4) on to the next step");
+ Assert.IsTrue(advisor.IsOpen);
+ }
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorOpeningTests"`; expect the restated test to fail at (4): after the card closes the chain sits where it was.
+- [ ] **Step 3: Implement.** In `CoverChanged`, when the layer that closed leaves the chain on its event step: `if (session.Chain.Step == EventStep && hooks.Card?.Shown == null) NextStep(); else ShowStep(session.Chain.Step);` before the queue's `Render`. While the chain is open, the cover hook never drops its step to the history (a chain step is not a queued message).
+- [ ] **Step 4: Run** `FILTER="AdvisorOpeningTests"`; expect PASS: all 17 of the guide's tests, ported or restated, plus the chain's own.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the opening chain's event step and every window (Refs #1484)"`
+
+### Task 11: The first-turn guide goes
+
+**Files:**
+- Delete: `unity/Assets/Scripts/UI/FirstTurnGuidePresenter.cs`, `unity/Assets/Tests/EditMode/FirstTurnGuideTests.cs` (and their `.meta`)
+- Modify: `unity/Assets/UI/Game.uxml` (the `first-turn-guide` layer, `:441-458`; the reopen button's comment, `:375`), `Statecraft.uss` (`:552-576`, the guide's block: `.guide-*` and `.guide-open #attention`), both strings files (`guide.*`, `strings.en.yaml:76-95`, `strings.he.yaml:68-87`; `how_to_play.guide`'s text, `strings.en.yaml:75`), `GameRoot.cs` (`:70-72`, `:455-514`, `:627`, `:765-770`), `EventCardPresenter.cs:170` (the comment names the chain), `AdvisorSettings.cs` (the comment on `GuideSeenKey`)
+- Test: `AdvisorOpeningTests.cs` (the reopen button), `HebrewUiTests` and `UiFoundationTests` unchanged
+
+**Interfaces:**
+- Consumes: Tasks 8 to 10 (every helper the game used from the guide now lives in `AdvisorTargets` or the advisor's hooks).
+- Produces: How to play's `how-to-play-guide` button opens the chain (`advisor.OpenChain()`, closing the screen); its text `how_to_play.guide`: "Show the opening advice again" / HE draft "הצגת עצות הפתיחה שוב".
+
+- [ ] **Step 1: Write the failing test** (the reopen path the guide had, `FirstTurnGuideTests.cs:250-263`):
+
+```csharp
+ [Test]
+ public void HowToPlaysButtonOpensTheChainAgain()
+ {
+ using var rig = new Rig(En, new SettingsStore(TempDir()));
+ rig.Ui.Press("nav-how-to-play");
+ Assert.AreEqual(En["how_to_play.guide"], rig.Ui.Q<Button>("how-to-play-guide").text);
+ rig.Ui.Press("how-to-play-guide");
+ Assert.IsTrue(rig.Advisor.InChain);
+ Assert.AreEqual(0, rig.Advisor.ChainStep);
+ Assert.IsNull(rig.Nav.Current, "the screen closes");
+ Assert.AreEqual("Show the opening advice again", En["how_to_play.guide"]);
+ }
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorOpeningTests"`; expect FAIL (the button still opens the guide; the text is the guide's).
+- [ ] **Step 3: Remove the guide.** Delete the two files and the guide's layer, styles and strings. In GameRoot drop `guide`, `Guide`, `firstTurn` and the guide's call sites; the start screen's callback keeps `advisor?.NewGame()` only; the Escape poll (`:770`) loses `guide?.Escape()` (the popup's Escape works only with the focus inside it, through `nav.TakesEscape`, Task 7). The advisor presenter takes the reopen button: `reopen = root.Q<Button>("how-to-play-guide"); reopen.text = text["how_to_play.guide"]; reopen.clicked += () => { hooks.CloseScreens?.Invoke(); OpenChain(); };` with `CloseScreens = () => nav?.Close()` in GameRoot's hooks (`AdvisorHooks.CloseScreens`, new). `git grep -n -E 'FirstTurnGuide|guide-(ring|dock|panel|skip|next|count|title|text)|"guide\.|guide-open'` must print nothing outside `docs/` and `CHANGELOG.md`.
+- [ ] **Step 4: Run** `FILTER="AdvisorOpeningTests;AdvisorShowMeTests;AdvisorPopupTests;AdvisorGameTests;HebrewUiTests;HowToPlayScreenTests;KeyboardTurnTests;LeftColumnTests"`; expect PASS. Then the slice's gates: the FULL EditMode run (0 NEW), `bash scripts/check.sh origin/main`, screenshots of the chain's seven steps in English at 1280x720 and 390x844 beside the guide's on main, `changelog.d/advisors-s2.md`:
+
+```markdown
+### Changed
+- The first-turn guide is replaced by the advisors' opening chain: on the first new game David Ben-Gurion, Golda
+ Meyerson and Moshe Dayan show the same essentials in a side popup, one step at a time, with the same gold ring; the
+ event step speaks before the card opens. How to play's button opens it again (Refs #1484).
+```
+
+ **Merge gate (Global Constraints, Hebrew):** this PR merges only when the seven `opening.*` lines are `he_review: approved` after a native reviewer's approval; until then it waits, ready. The PR lists the seven English lines for the owner's content review.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors replace the first-turn guide (Refs #1484)"`
+
+---
+
+## S3: the encyclopedia replaces How to play
+
+### Task 12: The encyclopedia screen
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/EncyclopediaPresenter.cs`; `unity/Assets/Tests/EditMode/EncyclopediaScreenTests.cs` (from `HowToPlayScreenTests.cs`)
+- Delete: `unity/Assets/Scripts/UI/HowToPlayPresenter.cs`, `unity/Assets/Tests/EditMode/HowToPlayScreenTests.cs`
+- Modify: `ScreenNav.cs:7` and `:13` (`how-to-play` becomes `encyclopedia`), `HudPresenter.cs:72`, `KeyScroll.cs:21`, `Game.uxml:21` and `:362-378`, `Statecraft.uss` (`.how-to-play-*`), both strings files (`hud.nav.how_to_play`, `how_to_play.*`), `GameRoot.cs:282`
+- Modify (the seven menu pins, spec 9.3): `HebrewUiTests.cs:283`, `:289`; `KeyboardTurnTests.cs:109`; `LeftColumnTests.cs:37`, `:259`; `PromoHudTests.cs:43`; `TopBarTests.cs:628`
+
+**Interfaces:**
+- Consumes: `AdvisorCatalog.Pages` (Task 1), `AdvisorPresenter.ShowTarget`, `OpenChain` (Tasks 8, 9), `ScreenNav.Open`, `Close`, `Current` (`ScreenNav.cs:269`, `:284`, `:292`).
+- Produces: `EncyclopediaPresenter(VisualElement root, UiText text, AdvisorCatalog catalog, ScreenNav nav, AdvisorPresenter? advisor)`; `Open(string pageId)` (opens the screen on that page), `ShowingPage` (`string?`); elements `screen-encyclopedia`, `encyclopedia-title`, `encyclopedia-list` (per advisor a heading `encyclopedia-advisor-<id>` and buttons `encyclopedia-page-<id>`), `encyclopedia-page`, `encyclopedia-page-title`, `encyclopedia-page-text`, `encyclopedia-back`, `encyclopedia-show-me`, `encyclopedia-opening`; strings `hud.nav.encyclopedia` "Encyclopedia" / HE "אנציקלופדיה", `encyclopedia.title`, `encyclopedia.back` "Back" / "חזרה", `encyclopedia.opening` "Show the opening advice again" / "הצגת עצות הפתיחה שוב" (replacing `how_to_play.guide`).
+
+- [ ] **Step 1: Write the failing tests** (the two of `HowToPlayScreenTests.cs`, renamed, plus the pages):
+
+```csharp
+ [Test]
+ public void TheSideMenuOpensAndClosesTheScreenInBothLanguages([Values(false, true)] bool hebrew)
+ {
+ var text = hebrew ? He : En;
+ using var ui = new UiTestKit();
+ using var nav = new ScreenNav(ui.Root);
+ using var pedia = new EncyclopediaPresenter(ui.Root, text, Pages(), nav, null);
+ var screen = ui.Q<VisualElement>("screen-encyclopedia");
+ Assert.IsFalse(ScreenNav.IsOpen(screen));
+ ui.Press("nav-encyclopedia");
+ Assert.IsTrue(ScreenNav.IsOpen(screen));
+ Assert.AreEqual("encyclopedia", nav.Current);
+ Assert.AreEqual(text["encyclopedia.title"], ui.Q<Label>("encyclopedia-title").text);
+ ui.Press("nav-encyclopedia");
+ Assert.IsNull(nav.Current);
+ }
+
+ /// <summary>Spec 10: grouped by advisor; a page shows its title and text; Back returns to the list; in Hebrew a pending
+ /// page is left out of the list (OQ-4), and an advisor with no page shown has no heading.</summary>
+ [Test]
+ public void PagesAreGroupedByAdvisorAndPendingOnesHideInHebrew()
+ {
+ using var ui = new UiTestKit();
+ using var nav = new ScreenNav(ui.Root);
+ using var pedia = new EncyclopediaPresenter(ui.Root, FixtureText(En), Pages(), nav, null);
+ ui.Press("nav-encyclopedia");
+ var list = ui.Q<ScrollView>("encyclopedia-list");
+ CollectionAssert.AreEqual(new[] { "encyclopedia-advisor-ben_gurion", "encyclopedia-page-p.bg", "encyclopedia-advisor-dayan", "encyclopedia-page-p.dayan" },
+ list.contentContainer.Children().Select(c => c.name).ToArray());
+ ui.Press("encyclopedia-page-p.bg");
+ Assert.AreEqual("p.bg", pedia.ShowingPage);
+ Assert.AreEqual("Title BG.", ui.Q<Label>("encyclopedia-page-title").text);
+ ui.Press("encyclopedia-back");
+ Assert.IsNull(pedia.ShowingPage);
+
+ using var ui2 = new UiTestKit();
+ using var nav2 = new ScreenNav(ui2.Root);
+ using var he = new EncyclopediaPresenter(ui2.Root, FixtureText(He), Pages(), nav2, null);
+ ui2.Press("nav-encyclopedia");
+ CollectionAssert.AreEqual(new[] { "encyclopedia-advisor-ben_gurion", "encyclopedia-page-p.bg" },
+ ui2.Q<ScrollView>("encyclopedia-list").contentContainer.Children().Select(c => c.name).ToArray(), "p.dayan is pending");
+ }
+
+ static AdvisorCatalog Pages() => AdvisorCatalog.Parse("advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\n" +
+ "messages: []\npages:\n - { id: p.bg, advisor: ben_gurion, show_me: attention, he_review: approved }\n - { id: p.dayan, advisor: dayan }\n");
+
+ static UiText FixtureText(UiText baseText) => UiText.Parse(
+ AssetDatabase.LoadAssetAtPath<TextAsset>(baseText["ui.lang"] == UiLanguage.Hebrew ? UiPaths.StringsHebrew : UiPaths.Strings).text +
+ "\nadvisor.page.p.bg.title: \"Title BG.\"\nadvisor.page.p.bg.text: \"Text BG.\"\nadvisor.page.p.dayan.title: \"Title D.\"\nadvisor.page.p.dayan.text: \"Text D.\"\n");
+```
+
+ `TheGuideFitsLaptopAndPhoneInBothLanguages` becomes `TheEncyclopediaFitsLaptopAndPhoneInBothLanguages` over `screen-encyclopedia`, its list and an open page, at 1280x720 and 390x844.
+
+- [ ] **Step 2: Run** `FILTER="EncyclopediaScreenTests"`; expect compile errors.
+- [ ] **Step 3: Implement.** Rename the screen in the seven pins and the four code sites at once (one commit, so no test sees half of it). In Game.uxml replace `screen-how-to-play` with:
+
+```xml
+ <!-- The advisors' encyclopedia (spec 10, EncyclopediaPresenter): one page per mechanic, grouped by advisor. A normal
+ side-menu screen, so ScreenNav owns opening and closing. -->
+ <ui:VisualElement name="screen-encyclopedia" class="panel screen">
+ <ui:VisualElement class="screen-header"><ui:Label name="encyclopedia-title" text="Encyclopedia" class="title" /></ui:VisualElement>
+ <ui:ScrollView name="encyclopedia-list" class="grow encyclopedia-list" />
+ <ui:VisualElement name="encyclopedia-page" class="grow encyclopedia-page">
+ <ui:Label name="encyclopedia-page-title" class="title encyclopedia-page-title" />
+ <ui:ScrollView name="encyclopedia-page-body" class="grow"><ui:Label name="encyclopedia-page-text" class="encyclopedia-text" /></ui:ScrollView>
+ <ui:VisualElement class="row encyclopedia-actions">
+ <ui:Button name="encyclopedia-back" />
+ <ui:Button name="encyclopedia-show-me" />
+ </ui:VisualElement>
+ </ui:VisualElement>
+ <!-- Opens the advisors' opening chain again (spec 9), which closes this screen. -->
+ <ui:Button name="encyclopedia-opening" class="encyclopedia-opening" />
+ <Statecraft.Game.UI.UiFrame />
+ </ui:VisualElement>
+```
+
+ `EncyclopediaPresenter` fills the list in `Render()` (on construction and on each open): for each advisor in `AdvisorCatalog.AdvisorIds`, the pages with `ApprovedIn(hebrew)`; a heading Label (the advisor's name) only when it has a page shown; one Button per page (its title). Pressing one shows the page pane (the list hidden), with Show me shown when the page has `show_me`; Show me closes the screen and calls `advisor.ShowTarget(page.ShowMe)`; Back shows the list; the opening button calls `nav.Close(); advisor.OpenChain();` (the advisor's own reopen button from Task 11 goes, as its element goes). `KeyScroll`'s main view for `encyclopedia` is `encyclopedia-list`. The rail keeps the book glyph.
+- [ ] **Step 4: Run** `FILTER="EncyclopediaScreenTests;HebrewUiTests;KeyboardTurnTests;LeftColumnTests;PromoHudTests;TopBarTests;UiFoundationTests;HudTests;AdvisorOpeningTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' encyclopedia replaces How to play (Refs #1484)"`
+
+### Task 13: The pages, and Tell me more
+
+**Files:**
+- Modify: `advisor-messages.yaml` (`pages:` and the opening steps' `encyclopedia` actions), both strings files, `AdvisorPresenter.cs` (`more`), `GameRoot.cs` (hooks `OpenPage`)
+- Test: `EncyclopediaScreenTests.cs`, `AdvisorPopupTests.cs`, `AdvisorCatalogTests.TheShippedFileHasNoProblems`
+
+**Interfaces:**
+- Consumes: Task 12; `AdvisorHooks.OpenPage` (new: `Action<string>?`, GameRoot sets `p => encyclopedia.Open(p)`).
+- Produces: 25 pages (below); `Tell me more` shows when a message has an `encyclopedia` action and opens that page.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ /// <summary>Spec 10: the mechanics the guide and How to play taught, the 14 nothing taught, immigration and the national
+ /// meters: 25 pages, grouped by advisor as spec 3.1 splits them.</summary>
+ [Test]
+ public void TheShippedPagesCoverEveryMechanic()
+ {
+ var pages = AdvisorCatalog.Load().Pages.ToDictionary(p => p.Id, p => p.Advisor);
+ var expected = new Dictionary<string, string>
+ {
+ ["turns"] = "ben_gurion", ["attention"] = "ben_gurion", ["events"] = "ben_gurion", ["objectives"] = "ben_gurion",
+ ["defeat"] = "ben_gurion", ["top_bar"] = "ben_gurion", ["why"] = "ben_gurion",
+ ["cities"] = "meyerson", ["immigration"] = "meyerson", ["training"] = "meyerson", ["projects"] = "meyerson",
+ ["pioneer_work"] = "meyerson", ["corridors"] = "meyerson", ["money_debt"] = "meyerson", ["budget"] = "meyerson",
+ ["cabinet"] = "meyerson", ["food"] = "meyerson", ["national_meters"] = "meyerson",
+ ["units_movement"] = "dayan", ["standing_orders"] = "dayan", ["combat"] = "dayan", ["arms"] = "dayan",
+ ["truces"] = "dayan", ["capture"] = "dayan", ["enemy_phase"] = "dayan",
+ };
+ CollectionAssert.AreEquivalent(expected, pages);
+ }
+```
+
+ In `AdvisorPopupTests`, a message with `actions: [{ encyclopedia: p }]` shows `advisor-more`, and pressing it calls the `OpenPage` hook with `p` (a recording lambda).
+
+- [ ] **Step 2: Run** `FILTER="EncyclopediaScreenTests;AdvisorPopupTests"`; expect failures (no pages; `more` hidden).
+- [ ] **Step 3: The pages.** One row each, `he_review: pending`, with the rules each page puts in plain words and its Show me target:
+
+| id | advisor | rules it explains (docs/rules/mvp.md) | show_me |
+|---|---|---|---|
+| turns | ben_gurion | Turns (`:11`), R-TURN | none |
+| attention | ben_gurion | R-GOV-002 (`:367`); the refill and carry-over from `AttentionSystem` (no R-ID, spec 5) | attention |
+| events | ben_gurion | Events (`:409`), R-EVT | decision_waiting |
+| objectives | ben_gurion | Objectives (`:295`), R-OBJ, R-SCORE (`:311`) | nav_objectives |
+| defeat | ben_gurion | Defeat (`:343`), R-END-001 to R-END-003 | none |
+| top_bar | ben_gurion | How to play's line (`strings.en.yaml:65`) | attention |
+| why | ben_gurion | How to play's line (`:67`) | nav_why |
+| cities | meyerson | Cities (`:69`), R-CITY, R-HOUSE (`:91`) | city_housing |
+| immigration | meyerson | R-CITY-004 (`:81`) | city_housing |
+| training | meyerson | Training (`:113`), R-TRAIN | city_training |
+| projects | meyerson | City projects (`:99`), R-PROJ | none |
+| pioneer_work | meyerson | Sites (`:129`), Veteran pioneers (`:139`), Camps (`:157`): R-SITE, R-FIELD, R-SWAMP, R-CAMP | none |
+| corridors | meyerson | Corridors (`:187`), R-COR | none |
+| money_debt | meyerson | Money (`:313`), R-MONEY; R-END-001 | nav_budget |
+| budget | meyerson | `EconomySystem.Allocate` and `Simulation.Execute` (no R-ID, spec 5) | nav_budget |
+| cabinet | meyerson | Government (`:361`), R-MIN (`:371`) | nav_cabinet |
+| food | meyerson | Food (`:323`), R-FOOD | none |
+| national_meters | meyerson | National parameters (`:377`), R-NAT | none |
+| units_movement | dayan | Movement (`:197`), R-MOVE | unit_move |
+| standing_orders | dayan | Standing orders (`:221`), R-ORDER; R-UNIT-005 (`:175`) | none |
+| combat | dayan | Combat (`:231`), R-COMBAT | nav_defence |
+| arms | dayan | Arms (`:333`), R-ARMS | nav_defence |
+| truces | dayan | R-COMBAT-009 (`:255`) | none |
+| capture | dayan | Settlement control (`:33`), R-CTRL; the three answers in R-CTRL-008's order (`:47`), none recommended | none |
+| enemy_phase | dayan | The enemy (`:257`), R-ENEMY | none |
+
+ Each page's English: a title of two to four words and two to four short sentences, written from the cited rule text and nothing else, without balance values (as How to play's lines are, `strings.en.yaml:58`: "These describe the existing sim without balance values, so rule changes stay in the sim"), in the advisor's voice as game dialogue. The nine pages How to play already covers start from its reviewed lines (`how_to_play.turn` to `how_to_play.why`, `strings.en.yaml:60-67`, and their Hebrew, `strings.he.yaml:54-61`). The `capture` page names the three answers in R-CTRL-008's order and recommends none; it never presents Deport as a choice to make. Hebrew drafts for all 25 under the OQ-4 comment. The opening steps get their pages: `opening.attention` `attention`, `opening.city` `cities`, `opening.training` `training`, `opening.move` `units_movement`, `opening.event` keeps its two actions, `opening.objectives` `objectives`.
+- [ ] **Step 4: Tell me more.** In `Fill`: `Display(more, m.Teaching && hooks.OpenPage != null && m.Actions.Any(a => a.Encyclopedia != ""))`, its handler `hooks.OpenPage?.Invoke(m.Actions.First(a => a.Encyclopedia != "").Encyclopedia)`. `ShowMe` ignores `encyclopedia` actions. In `AdvisorCatalog.Problems`, an `encyclopedia` action on a message that is not teaching is a problem ("encyclopedia actions are for teaching messages (spec 7.1)"), with its TestCase row in `AdvisorCatalogTests`.
+- [ ] **Step 5: Run** `FILTER="EncyclopediaScreenTests;AdvisorPopupTests;AdvisorCatalogTests;AdvisorOpeningTests"`; expect PASS. Then the slice's gates and `changelog.d/advisors-s3.md`:
+
+```markdown
+### Changed
+- How to play becomes the advisors' encyclopedia: 25 short pages, grouped by David Ben-Gurion, Golda Meyerson and Moshe
+ Dayan, cover every mechanic, the 14 that nothing explained before included, each with a Show me; an advisor's
+ "Tell me more" opens its page (Refs #1484).
+```
+
+ **Merge gate:** the pages that replace How to play's nine lines (`turns`, `attention`, `cities`, `training`, `units_movement`, `events`, `objectives`, `top_bar`, `why`) are `he_review: approved` before this PR merges. The PR lists all 25 pages' English for the owner.
+- [ ] **Step 6: Commit.** `git commit -m "ui: the encyclopedia's pages and Tell me more (Refs #1484)"`
+
+---
+
+## S4: warnings, advice and the help level
+
+Every message below is drafted in English from the rule text it cites, with no balance value; the Hebrew drafts sit under the OQ-4 comment with `he_review: pending`. A teaching message may carry an `encyclopedia` action (Tell me more, Task 13); a warning or a critical message never does (spec 7.1's button sets: Show me, Not now, Got it). The signal tests mutate a fresh bridge's live state (`bridge.State` is the session's state object): test-only, and each test makes its own bridge.
+
+### Task 14: The help level in Settings
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/SettingsPresenter.cs` (constructor `:50`; a row like the sound row, `:86-98`), `GameRoot.cs:287` (pass the session's settings), `Game.uxml` (a row after the sound row, `:402-410`), `Statecraft.uss`, both strings files
+- Test: `unity/Assets/Tests/EditMode/AdvisorLevelSettingTests.cs`
+
+**Interfaces:**
+- Consumes: `AdvisorSettings.Levels`, `Level`, `SetLevel` (Task 2); `SettingsPresenter.SelectedClass` (`SettingsPresenter.cs:21`).
+- Produces: `SettingsPresenter(..., AdvisorSettings? advisors = null)`; buttons `settings-advisors-new`, `-experienced`, `-warnings`, `-off`; label `settings-advisors-label`; strings `settings.advisors`, `settings.advisors.new`, `.experienced`, `.warnings`, `.off`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+
+/// <summary>Spec 6: four help levels in Settings, the one set marked, kept in the settings file, applied at once.</summary>
+public class AdvisorLevelSettingTests
+{
+ 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");
+
+ [Test]
+ public void PickingALevelKeepsItAndMarksIt()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "statecraft-level-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var store = new SettingsStore(dir);
+ var advisors = new AdvisorSettings(store);
+ using var ui = new UiTestKit();
+ using var settings = new SettingsPresenter(ui.Root, En, store, advisors: advisors);
+ Assert.IsTrue(ui.Q<Button>("settings-advisors-new").ClassListContains(SettingsPresenter.SelectedClass), "the default");
+ ui.Press("settings-advisors-warnings");
+ Assert.AreEqual("warnings", advisors.Level, "the live setting, so the queue filters at once");
+ Assert.AreEqual("warnings", store.Read(AdvisorSettings.LevelKey));
+ Assert.IsTrue(ui.Q<Button>("settings-advisors-warnings").ClassListContains(SettingsPresenter.SelectedClass));
+ Assert.IsFalse(ui.Q<Button>("settings-advisors-new").ClassListContains(SettingsPresenter.SelectedClass));
+ Assert.AreEqual(En["settings.advisors.off"], ui.Q<Button>("settings-advisors-off").text);
+ }
+ finally { if (Directory.Exists(dir)) Directory.Delete(dir, true); }
+ }
+
+ /// <summary>"New to strategy games" is the longest choice: at a phone's width, in both languages, every choice stays in
+ /// the Settings screen.</summary>
+ [UnityTest]
+ public IEnumerator TheRowFitsOnAPhoneInBothLanguages()
+ {
+ var problems = new List<string>();
+ foreach (var hebrew in new[] { false, true })
+ foreach (var (w, h) in new[] { (390, 844), (844, 390), (1280, 720) })
+ {
+ var rt = new RenderTexture(w, h, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
+ var go = new GameObject("LevelRow"); 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 nav = new ScreenNav(root);
+ var settings = new SettingsPresenter(root, hebrew ? He : En, null, advisors: new AdvisorSettings(null));
+ nav.Open("settings");
+ try
+ {
+ for (int i = 0; i < 6; i++) yield return null;
+ var screen = root.Q("screen-settings").worldBound;
+ foreach (var level in AdvisorSettings.Levels)
+ {
+ var b = root.Q("settings-advisors-" + level).worldBound;
+ if (!(b.width > 0) || b.xMin < screen.xMin - 0.5f || b.xMax > screen.xMax + 0.5f)
+ problems.Add($"{(hebrew ? "he" : "en")} {w}x{h}: {level} {b} leaves the screen {screen}");
+ }
+ }
+ finally
+ {
+ settings.Dispose(); nav.Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorLevelSettingTests"`; expect compile errors (`advisors:`).
+- [ ] **Step 3: Implement.** The row in Game.uxml, after the sound row:
+
+```xml
+ <!-- How much the advisors say (spec 6, AdvisorSettings): four levels, the one set carries .settings-choice-selected. -->
+ <ui:VisualElement class="row settings-row">
+ <ui:Label name="settings-advisors-label" text="Advisors" class="settings-name" />
+ <ui:VisualElement class="row settings-choices settings-advisors">
+ <ui:Button name="settings-advisors-new" class="settings-switch" />
+ <ui:Button name="settings-advisors-experienced" class="settings-switch" />
+ <ui:Button name="settings-advisors-warnings" class="settings-switch" />
+ <ui:Button name="settings-advisors-off" class="settings-switch" />
+ </ui:VisualElement>
+ </ui:VisualElement>
+```
+
+ `.settings-advisors { flex-wrap: wrap; flex-shrink: 1; }` (`.settings-choices` does not shrink, `Statecraft.uss:504`; this row's labels are longer than any other's). In `SettingsPresenter`, as the sound row: label text, each button's text `settings.advisors.<level>`, its click `advisors.SetLevel(level)` and the selected class moved; with `advisors == null` the row hides (`style.display = None` on its row). GameRoot passes `advisors: AdvisorSession.Settings` (made before `SettingsPresenter`, so move the session's creation above `:287`). Strings: English "Advisors", "New to strategy games", "Experienced", "Warnings only", "Off"; Hebrew drafts "יועצים", "חדשים במשחקי אסטרטגיה", "מנוסים", "אזהרות בלבד", "כבוי", under "For the native reviewer (#564)".
+- [ ] **Step 4: Run** `FILTER="AdvisorLevelSettingTests;SettingsScreenTests;HebrewUiTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' help level in Settings (Refs #1484)"`
+
+### Task 15: The read-only city-at-risk helper (sim)
+
+**Files:**
+- Create: `sim/Statecraft.Sim/Threats.cs`, `sim/Statecraft.Sim.Tests/ThreatsTests.cs`
+- Modify: `sim/Statecraft.Sim/Simulation.cs:51-56` (the turn's end, shared)
+
+**Interfaces:**
+- Consumes: `EnemyAI.Order(Content, GameState, List<Cause>, DateTime?)` (`EnemyAI.cs:46`), `GameState.Clone` (`GameState.cs:113`), `Combat.Attack` (`Combat.cs:15`), `Movement.PlayerSide` (`Movement.cs:20`), `Content.SettlementHexes`, `Content.IsGdd`; the fixture of `EnemyAITests` (`EnemyAITests.cs:13-21`) and `CombatTests.With` (`CombatTests.cs:24`).
+- Produces: `public static DateTime Simulation.TurnEnd(Content c, GameState s)`; `public static IReadOnlyList<string> Threats.CitiesAtRisk(Content c, GameState s)` (city ids, ordinal).
+
+ Why in the sim and not in Unity (spec 5): the enemy's orders are the sim's (R-ENEMY-001), so the warning runs the sim's own step 1 on a copy, never a Unity copy of its logic; and the truce test inside `EnemyAI.Order` needs the turn's end, which only `Simulation.Step` computes today. `TurnEnd` moves that computation into one method `Step` calls, so the two cannot drift. No state changes, no random number: every golden stays.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+using Xunit;
+
+/// <summary>Spec 5's one sim helper for the advisors: the cities the enemy will likely attack or enter this turn, from
+/// resolver step 1 run on a copy (R-ENEMY-001: the orders come from the state alone). Read-only.</summary>
+public class ThreatsTests
+{
+ const string Types = Fixture.GddUnitTypes
+ + " - { id: soldier, kind: unit, side: israel, class: infantry, movement_points: 3 }\n"
+ + " - { id: enemy, kind: unit, side: egypt, class: infantry, movement_points: 3 }\n";
+
+ static Content Load() => ContentLoader.Load(Fixture.Write(Fixture.Gdd(new Dictionary<string, string>
+ {
+ ["unit_types.yaml"] = Types, ["map/hexes.json"] = MovementTests.Board(), ["corridors.yaml"] = "corridors: []\n"
+ })));
+
+ static Unit Soldier(int id, int q, int r, int strength) => new Unit(id, "soldier", q, r, side: "israel", strength: strength);
+ static Unit Enemy(int id, int q, int r, int strength) => new Unit(id, "enemy", q, r, side: "egypt", strength: strength);
+
+ // R-ENEMY-001, R-ENEMY-003: the helper names town_a (the fixture's city, on 1,0) exactly when the turn's own step 1
+ // orders an attack on its hex, and it changes nothing.
+ [Theory]
+ [InlineData(20, 1, true)]
+ [InlineData(1, 20, false)]
+ public void NamesTheCityTheEnemyAttacksAndChangesNothing(int enemy, int defender, bool atRisk)
+ {
+ var c = Load();
+ var s = CombatTests.With(c, Soldier(1, 1, 0, defender), Enemy(2, 2, 0, enemy));
+ var hash = s.Hash();
+ var risk = Threats.CitiesAtRisk(c, s);
+ Assert.Equal(hash, s.Hash());
+ Assert.Equal(atRisk ? new[] { "town_a" } : Array.Empty<string>(), risk);
+ var turn = Simulation.Step(c, s, Array.Empty<Command>());
+ Assert.Equal(atRisk, turn.Why.Any(w => w.Key == WhyKeys.AttackOrdered && w.Message.EndsWith("hex 1,0", StringComparison.Ordinal)));
+ }
+
+ [Fact]
+ public void NothingOnceTheGameIsOver()
+ {
+ var c = Load();
+ var s = CombatTests.With(c, Soldier(1, 1, 0, 1), Enemy(2, 2, 0, 20));
+ s.GameOver = GameOverCodes.DefeatWar;
+ Assert.Empty(Threats.CitiesAtRisk(c, s));
+ }
+
+ // The turn's end is Step's own: a turn run after TurnEnd is called ends on that date.
+ [Fact]
+ public void TurnEndIsTheDateTheTurnEndsOn()
+ {
+ var c = Load();
+ var s = CombatTests.With(c);
+ var end = Simulation.TurnEnd(c, s);
+ Assert.Equal(end, Simulation.Step(c, s, Array.Empty<Command>()).State.Date);
+ }
+}
+```
+
+- [ ] **Step 2: Run** `dotnet test sim/Statecraft.sln --filter ThreatsTests`; expect compile errors.
+- [ ] **Step 3: Implement.** In `Simulation.cs`, add after `Step`:
+
+```csharp
+ /// <summary>The date the turn starting on <paramref name="s"/>'s date ends on: its turn length from the war state,
+ /// cut at the next era's start or the game's end when it comes first (spec 4.1, 4.5). Step's own rule; the advisors'
+ /// city warning (Threats) reads it too.</summary>
+ public static DateTime TurnEnd(Content c, GameState s)
+ {
+ var len = SecuritySystem.TurnLengthFor(c, s.Date, s.Rung);
+ var boundary = c.Eras.Select(e => e.From).Where(f => f > s.Date).Concat(new[] { c.End }).Min();
+ return SimTime.AdvanceTo(s.Date, len, boundary);
+ }
+```
+
+ and in `Step` replace the three lines that compute `end`, `boundary` and `next` (`:54-56`) with `var next = TurnEnd(c, s);`, keeping `var len = ...` (`:51`), which `adjusted` and `yf` still read, and the comment. `Threats.cs`:
+
+```csharp
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The advisors' one sim helper (docs/superpowers/specs/2026-10-23-advisors-design.md, section 5): the player's
+ /// cities the enemy is likely to attack or enter this turn. It runs resolver step 1 (EnemyAI.Order, R-ENEMY-001) on a
+ /// copy of the state and reads the copy: an attack order on a city's hex, or an enemy unit standing on one. It changes
+ /// nothing and draws no random number. "Likely": the player's own orders this turn can still change the board.</summary>
+ public static class Threats
+ {
+ public static IReadOnlyList<string> CitiesAtRisk(Content c, GameState s)
+ {
+ if (!c.IsGdd || s.GameOver != null) return Array.Empty<string>();
+ var copy = s.Clone();
+ EnemyAI.Order(c, copy, new List<Cause>(), Simulation.TurnEnd(c, s));
+ var cityAt = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (var h in c.SettlementHexes) if (s.Cities.ContainsKey(h.Id)) cityAt[Hex(h.Q, h.R)] = h.Id;
+ var risk = new SortedSet<string>(StringComparer.Ordinal);
+ foreach (var u in copy.Units.Values)
+ {
+ if (u.Side == "" || u.Side == Movement.PlayerSide) continue;
+ if (u.Order == Combat.Attack && cityAt.TryGetValue(u.OrderTarget, out var attacked)) risk.Add(attacked);
+ if (cityAt.TryGetValue(Hex(u.Q, u.R), out var entered)) risk.Add(entered);
+ }
+ return risk.ToList();
+ }
+
+ static string Hex(int q, int r) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);
+ }
+}
+```
+
+- [ ] **Step 4: Run** `dotnet test sim/Statecraft.sln`; expect PASS, 0 warnings, and the goldens unchanged: `STATECRAFT_UPDATE_GOLDEN=1 dotnet test sim/Statecraft.sln`, then `git status` shows no change under `sim/Statecraft.Sim.Tests/golden/`; revert anything it wrote. `uv run scripts/oss/rule_ids.py` passes (the test cites existing IDs only).
+- [ ] **Step 5: Commit.** `git commit -m "sim: a read-only helper for the advisors' city warning (Refs #1484)"`
+
+### Task 16: The critical warnings and the defeat lines
+
+**Files:**
+- Modify: `AdvisorSignals.cs`, `advisor-messages.yaml`, both strings files (also `end.outcome.defeat_war`, OQ-10)
+- Test: `unity/Assets/Tests/EditMode/AdvisorSignalsTests.cs`
+
+**Interfaces:**
+- Consumes: `Threats.CitiesAtRisk` (Task 15); `GameState.ExhaustedTurns`, `Debt`, `FoodUnmet`, `GameOver` (`GameState.cs:100`, `:41`, `:98`, `:63`); `GameOverCodes.DefeatWar`, `DefeatEconomy` (`GameState.cs:19-21`); `Content.RulesAt(date).Mvp.DebtCeiling` (`Content.cs:1247`, `:509`, `:608`); `EndScreenPresenter.Lines` (`EndScreenPresenter.cs:78-81`).
+- Produces: state signals `city_at_risk`, `exhausted`, `in_debt`, `food_short`, `defeat_war`, `defeat_economy`; measure `debt_ratio_at_least` (the debt over `debt_ceiling`, 0 outside the GDD loop); messages `ben_gurion.city_at_risk`, `ben_gurion.exhausted`, `meyerson.debt_ceiling`, `meyerson.food_short`, `ben_gurion.defeat_war`, `ben_gurion.defeat_economy`; string `end.outcome.defeat_war`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+#nullable enable
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+
+/// <summary>Spec 5 and 6: each signal on built states, and the critical warnings at every help level.</summary>
+public class AdvisorSignalsTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static SimBridge Bridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
+ static bool Holds(SimBridge b, string signal) => AdvisorSignals.States[signal](new AdvisorContext(b, null));
+ static double Ceiling(SimBridge b) => C.RulesAt(b.State.Date).Mvp!.DebtCeiling!.Value;
+
+ [Test]
+ public void TheEconomySignalsReadTheShownState()
+ {
+ var b = Bridge();
+ foreach (var s in new[] { "exhausted", "in_debt", "food_short", "defeat_war", "defeat_economy" }) Assert.IsFalse(Holds(b, s), "a new game: " + s);
+ b.State.ExhaustedTurns = 1; b.State.Debt = Ceiling(b) * 0.85; b.State.FoodUnmet = 3;
+ Assert.IsTrue(Holds(b, "exhausted")); Assert.IsTrue(Holds(b, "in_debt")); Assert.IsTrue(Holds(b, "food_short"));
+ Assert.AreEqual(0.85, AdvisorSignals.Measures["debt_ratio_at_least"](new AdvisorContext(b, null)), 1e-9);
+ b.State.GameOver = GameOverCodes.DefeatWar;
+ Assert.IsTrue(Holds(b, "defeat_war")); Assert.IsFalse(Holds(b, "defeat_economy"));
+ }
+
+ [Test]
+ public void TheCityAtRiskSignalIsTheSimsHelper()
+ {
+ var b = Bridge();
+ Assert.AreEqual(Threats.CitiesAtRisk(C, b.State).Count > 0, Holds(b, "city_at_risk"));
+ }
+
+ /// <summary>Spec 6: "Off" keeps every critical warning, and two in one turn both show, one after the other.</summary>
+ [Test]
+ public void OffStillShowsEveryCriticalWarning()
+ {
+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ using var rig = new AdvisorPopupTests.Rig(catalog: System.IO.File.ReadAllText(AdvisorCatalog.Path), text: text);
+ rig.Session.Settings.SetLevel("off");
+ rig.Bridge.State.ExhaustedTurns = 1; rig.Bridge.State.Debt = Ceiling(rig.Bridge) * 0.9;
+ rig.Advisor.Notice(AdvisorSignals.TurnEnded);
+ var shown = new System.Collections.Generic.List<string>();
+ while (rig.Advisor.Shown is AdvisorCatalog.Message m) { shown.Add(m.Id); rig.Ui.Press("advisor-got-it"); }
+ CollectionAssert.IsSubsetOf(new[] { "ben_gurion.exhausted", "meyerson.debt_ceiling" }, shown);
+ Assert.IsTrue(shown.All(id => rig.Session.Catalog.Find(id)!.Critical), "Off: nothing but critical");
+ }
+
+ [Test]
+ public void TheEndScreenNamesTheWarLoss()
+ {
+ foreach (var file in new[] { UiPaths.Strings, UiPaths.StringsHebrew })
+ Assert.IsTrue(UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(file).text).Has("end.outcome.defeat_war"), file);
+ Assert.AreEqual("The enemy holds a city.", En["end.outcome.defeat_war"], "Q-DEF-4 (b)'s line (PlayerText.cs:27)");
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorSignalsTests"`; expect failures (no such signals; no string).
+- [ ] **Step 3: Implement.** In `AdvisorSignals.States`:
+
+```csharp
+ // Spec 6's critical warnings and the defeat lines (R-END-001 to R-END-003, docs/rules/mvp.md:343-351).
+ ["city_at_risk"] = ctx => Threats.CitiesAtRisk(ctx.Content, ctx.State).Count > 0,
+ ["exhausted"] = ctx => ctx.State.ExhaustedTurns > 0,
+ ["in_debt"] = ctx => ctx.State.Debt > 0,
+ ["food_short"] = ctx => ctx.State.FoodUnmet > 0,
+ ["defeat_war"] = ctx => ctx.State.GameOver == GameOverCodes.DefeatWar,
+ ["defeat_economy"] = ctx => ctx.State.GameOver == GameOverCodes.DefeatEconomy,
+```
+
+ and in `Measures`: `["debt_ratio_at_least"] = ctx => ctx.Content.RulesAt(ctx.State.Date).Mvp?.DebtCeiling is double ceiling && ceiling > 0 ? ctx.State.Debt / ceiling : 0`. Data (0.8 is the advisor's own presentation value, labelled for the owner in the file's comment):
+
+```yaml
+# Spec 6's critical warnings (shown at every help level, Off included) and the defeat lines. debt_ratio_at_least 0.8: a
+# presentation value for "close to the ceiling", for the owner to confirm; the ceiling itself is the sim's (R-END-001).
+ - { id: ben_gurion.city_at_risk, advisor: ben_gurion, signal: city_at_risk, level: critical, priority: 3, repeat: every, cooldown_turns: 1, actions: [{ open_screen: defence }] }
+ - { id: ben_gurion.exhausted, advisor: ben_gurion, signal: exhausted, level: critical, priority: 3, repeat: every, cooldown_turns: 1, actions: [{ open_screen: budget }] }
+ - { id: meyerson.debt_ceiling, advisor: meyerson, signal: in_debt, when: { debt_ratio_at_least: 0.8 }, level: critical, priority: 2, repeat: every, cooldown_turns: 3, actions: [{ open_screen: budget }] }
+ - { id: meyerson.food_short, advisor: meyerson, signal: food_short, level: warnings, priority: 2, repeat: every, cooldown_turns: 2 }
+ - { id: ben_gurion.defeat_war, advisor: ben_gurion, signal: defeat_war, level: warnings }
+ - { id: ben_gurion.defeat_economy, advisor: ben_gurion, signal: defeat_economy, level: warnings }
+```
+
+ English (R-END-001 to R-END-003, R-NAT-001's Food link):
+
+```yaml
+advisor.ben_gurion.city_at_risk.text: "The enemy is likely to attack one of our cities this turn. If an enemy unit holds any of our cities at the end of a turn, the war is lost."
+advisor.ben_gurion.exhausted.text: "Money and Food have both run out. If they stay exhausted for a few turns in a row, the economy collapses and the game is lost."
+advisor.meyerson.debt_ceiling.text: "Our debt is close to the ceiling. At the ceiling, Money counts as exhausted, and if Food runs out as well the economy starts to break."
+advisor.meyerson.food_short.text: "This turn the country needed more Food than it had. A Food shortage also lowers Social cohesion."
+advisor.ben_gurion.defeat_war.text: "An enemy unit held one of our cities at the end of the turn, and that ends the game."
+advisor.ben_gurion.defeat_economy.text: "Money and Food stayed exhausted for too many turns in a row, and that ends the game."
+end.outcome.defeat_war: "The enemy holds a city."
+```
+
+ Hebrew drafts (pending):
+
+```yaml
+advisor.ben_gurion.city_at_risk.text: "סביר שהאויב יתקוף באחת מהערים שלנו בתור הזה. אם יחידת אויב מחזיקה באחת מהערים שלנו בסוף תור, המלחמה אבודה."
+advisor.ben_gurion.exhausted.text: "הכסף והמזון אזלו שניהם. אם יישארו אזולים כמה תורות ברציפות, הכלכלה תקרוס והמשחק יסתיים בהפסד."
+advisor.meyerson.debt_ceiling.text: "החוב שלנו קרוב לתקרה. בתקרה הכסף נחשב אזול, ואם גם המזון ייגמר הכלכלה תתחיל להישבר."
+advisor.meyerson.food_short.text: "בתור הזה המדינה נזקקה ליותר מזון ממה שהיה לה. מחסור במזון גם מוריד את הלכידות החברתית."
+advisor.ben_gurion.defeat_war.text: "יחידת אויב החזיקה באחת מהערים שלנו בסוף התור, וזה מסיים את המשחק."
+advisor.ben_gurion.defeat_economy.text: "הכסף והמזון נשארו אזולים יותר מדי תורות ברציפות, וזה מסיים את המשחק."
+end.outcome.defeat_war: "האויב מחזיק בעיר."
+```
+
+ `end.outcome.defeat_war`'s Hebrew is a defeat text, which the 18 October ruling sends to native review (`docs/oss/DECISIONS.md:75`); mark it so.
+- [ ] **Step 4: Run** `FILTER="AdvisorSignalsTests;AdvisorCatalogTests;EndScreenTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' critical warnings and the war-loss line (Refs #1484)"`
+
+### Task 17: Ben-Gurion's teaching
+
+**Files:**
+- Modify: `unity/Assets/Scripts/UI/SimBridge.cs` (`:188-189`, the Attention refusal), `AdvisorPresenter.cs` (subscribe), `AdvisorSignals.cs`, `advisor-messages.yaml`, both strings files
+- Test: `AdvisorSignalsTests.cs`
+
+**Interfaces:**
+- Consumes: `SimBridge.Queue`'s Attention refusal (`SimBridge.cs:188-189`); `GameState.Objectives` (`GameState.cs:83`).
+- Produces: `public event Action? SimBridge.RefusedForAttention` (raised just before that refusal); event signal `attention_refused`; state signal `objective_done`; messages `ben_gurion.turns` (signal `turn_ended`), `ben_gurion.attention_out`, `ben_gurion.objective_done`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ [Test]
+ public void AnOrderRefusedForAttentionRaisesItsOwnEvent()
+ {
+ var b = Bridge();
+ var ev = C.Events.First(e => e.Id == b.State.PendingEvents[0]);
+ var order = new ChooseEventOption(ev.Id, ev.Options[0].Id);
+ Assume.That(b.Price(order), Is.GreaterThan(0), "the opening card's answer costs Attention");
+ b.State.Attention = 0;
+ int raised = 0; b.RefusedForAttention += () => raised++;
+ Assert.IsNotNull(b.Queue(order));
+ Assert.AreEqual(1, raised);
+ Assert.IsNotNull(b.Queue(new SetPolicy("no_such_policy", 1)), "a refusal for another reason");
+ Assert.AreEqual(1, raised, "raises nothing");
+ }
+
+ [Test]
+ public void AnObjectiveDoneHolds()
+ {
+ var b = Bridge();
+ Assert.IsFalse(Holds(b, "objective_done"));
+ b.State.Objectives[C.Objectives[0].Id] = b.State.Date;
+ Assert.IsTrue(Holds(b, "objective_done"));
+ }
+```
+
+- [ ] **Step 2: Run**; expect compile errors (`RefusedForAttention`).
+- [ ] **Step 3: Implement.** In `SimBridge.Queue`: `if (!CanPay(c)) { RefusedForAttention?.Invoke(); return Refuse(text.Format("order.no_attention", Price(c), LeftFor(c))); }`. In `AdvisorPresenter`'s constructor subscribe `bridge.RefusedForAttention += onAttention` (`onAttention = () => Notice(AdvisorSignals.AttentionRefused)`), unsubscribe in `Dispose`. `AttentionRefused = "attention_refused"` joins `Events`; `["objective_done"] = ctx => ctx.State.Objectives.Count > 0` joins `States`. Data:
+
+```yaml
+ - { id: ben_gurion.turns, advisor: ben_gurion, signal: turn_ended, level: new, actions: [{ show_me: nav_why }, { encyclopedia: turns }] }
+ - { id: ben_gurion.attention_out, advisor: ben_gurion, signal: attention_refused, level: experienced, actions: [{ show_me: attention }, { encyclopedia: attention }] }
+ - { id: ben_gurion.objective_done, advisor: ben_gurion, signal: objective_done, level: new, actions: [{ show_me: nav_objectives }, { encyclopedia: objectives }] }
+```
+
+ English (How to play's end-turn and Why lines, `strings.en.yaml:66-67`; R-GOV-002; the guide's objectives line):
+
+```yaml
+advisor.ben_gurion.turns.text: "End turn carried out our orders and moved the country on. Why? shows each change and its cause."
+advisor.ben_gurion.attention_out.text: "That order needs more Attention than is left this turn. Attention refills at the start of the next turn; a card left unanswered goes to the responsible minister."
+advisor.ben_gurion.objective_done.text: "An objective is complete, and its card comes with it. The Objectives screen shows the date you completed it beside the historical one."
+```
+
+ Hebrew drafts (pending):
+
+```yaml
+advisor.ben_gurion.turns.text: "סיום התור ביצע את ההוראות שלנו וקידם את המדינה. במסך למה? מופיע כל שינוי והסיבה לו."
+advisor.ben_gurion.attention_out.text: "ההוראה הזו דורשת יותר תשומת לב ממה שנשאר בתור הזה. תשומת הלב מתמלאת בתחילת התור הבא; כרטיס שלא עניתם עליו עובר לשר האחראי."
+advisor.ben_gurion.objective_done.text: "יעד הושלם, והכרטיס שלו מגיע איתו. במסך היעדים מופיע התאריך שבו השלמתם אותו לצד התאריך ההיסטורי."
+```
+
+- [ ] **Step 4: Run** `FILTER="AdvisorSignalsTests;AdvisorCatalogTests;SimBridgeGuardTests;SimBridgeGddTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: Ben-Gurion's teaching messages (Refs #1484)"`
+
+### Task 18: Meyerson's teaching and the budget warning
+
+**Files:**
+- Modify: `AdvisorSignals.cs`, `advisor-messages.yaml`, both strings files, `BudgetPresenter.cs:160-170` (an event when its badge flips), `GameRoot.cs:279` (keep the budget presenter, wire the event)
+- Test: `AdvisorSignalsTests.cs`, `BudgetScreenTests.cs`
+
+**Interfaces:**
+- Consumes: `GameState.UnlockedProjects`, `Corridors`, `Units`, `ActiveSituations` (`GameState.cs:79`, `:77`, `:68`, `:38`); `Projects.IsPioneer`, `Projects.IsBusy` (`Projects.cs:31`, `:121`); `SimBridge.Vacancies` (`SimBridge.cs:85`); `SimBridge.BudgetUnsubmitted` (`:89`, #1352, merged).
+- Produces: state signals `project_unlocked`, `idle_pioneer`, `corridor_started`, `cabinet_vacancy`, `situation_active` (and `in_debt`, Task 16); event signal `budget_unsubmitted`; `public event Action<bool>? BudgetPresenter.UnsubmittedChanged`; messages `meyerson.projects`, `meyerson.pioneer_work`, `meyerson.corridors`, `meyerson.money_debt`, `meyerson.cabinet`, `meyerson.national_meters`, `meyerson.budget_unsubmitted`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ [Test]
+ public void MeyersonsSignalsReadTheShownState()
+ {
+ var b = Bridge();
+ var c = new AdvisorContext(b, null);
+ Assert.AreEqual(b.State.UnlockedProjects.Count > 0, Holds(b, "project_unlocked"));
+ Assert.AreEqual(b.State.Corridors.Count > 0, Holds(b, "corridor_started"));
+ Assert.AreEqual(b.Vacancies.Count > 0, Holds(b, "cabinet_vacancy"));
+ Assert.AreEqual(b.State.ActiveSituations.Count > 0, Holds(b, "situation_active"));
+ var idle = b.State.Units.Values.Any(u => u.Side == "" && Projects.IsPioneer(u.Type) && !Projects.IsBusy(b.State, u.Id));
+ Assert.AreEqual(idle, Holds(b, "idle_pioneer"));
+ b.State.UnlockedProjects.Add("any"); b.State.ActiveSituations.Add("any");
+ Assert.IsTrue(Holds(b, "project_unlocked")); Assert.IsTrue(Holds(b, "situation_active"));
+ }
+```
+
+ In `BudgetScreenTests`, a test that editing a share without submitting raises `UnsubmittedChanged(true)` once, and Submit raises `UnsubmittedChanged(false)` (use that file's existing edit and submit helpers).
+
+- [ ] **Step 2: Run** `FILTER="AdvisorSignalsTests;BudgetScreenTests"`; expect failures.
+- [ ] **Step 3: Implement.** The signals:
+
+```csharp
+ ["project_unlocked"] = ctx => ctx.State.UnlockedProjects.Count > 0,
+ // A halutz with no project (R-SITE-001, D-D6: one project per unit): pioneer work is waiting to be given.
+ ["idle_pioneer"] = ctx => ctx.State.Units.Values.Any(u => u.Side == "" && Projects.IsPioneer(u.Type) && !Projects.IsBusy(ctx.State, u.Id)),
+ ["corridor_started"] = ctx => ctx.State.Corridors.Count > 0,
+ ["cabinet_vacancy"] = ctx => ctx.Bridge.Vacancies.Count > 0,
+ ["situation_active"] = ctx => ctx.State.ActiveSituations.Count > 0,
+```
+
+ `BudgetUnsubmitted = "budget_unsubmitted"` joins `Events`. In `BudgetPresenter` keep the last value and raise `UnsubmittedChanged(unsubmitted)` when it flips, after the badge is set (`:167-169`). GameRoot: `var budget = Own(new BudgetPresenter(root, bridge, text));` and, once the advisor exists, `budget.UnsubmittedChanged += on => { if (on) advisor?.Notice(AdvisorSignals.BudgetUnsubmitted); };`. Data:
+
+```yaml
+ - { id: meyerson.projects, advisor: meyerson, signal: project_unlocked, level: new, actions: [{ encyclopedia: projects }] }
+ - { id: meyerson.pioneer_work, advisor: meyerson, signal: idle_pioneer, level: experienced, actions: [{ encyclopedia: pioneer_work }] }
+ - { id: meyerson.corridors, advisor: meyerson, signal: corridor_started, level: experienced, actions: [{ encyclopedia: corridors }] }
+ - { id: meyerson.money_debt, advisor: meyerson, signal: in_debt, level: new, actions: [{ show_me: nav_budget }, { encyclopedia: money_debt }] }
+ - { id: meyerson.cabinet, advisor: meyerson, signal: cabinet_vacancy, level: new, actions: [{ show_me: nav_cabinet }, { encyclopedia: cabinet }] }
+ - { id: meyerson.national_meters, advisor: meyerson, signal: situation_active, level: new, actions: [{ encyclopedia: national_meters }] }
+ - { id: meyerson.budget_unsubmitted, advisor: meyerson, signal: budget_unsubmitted, level: warnings, repeat: every, cooldown_turns: 1, actions: [{ open_screen: budget }] }
+```
+
+ English (R-PROJ-001; R-SITE-001, R-CAMP-001, R-FIELD-001, R-SWAMP-001, R-COR-001; R-COR-001; R-SITE-001's borrowing and R-END-001; R-MIN-001; R-NAT-001; #1352's rule, `changelog.d/1109-budget-badge.md`):
+
+```yaml
+advisor.meyerson.projects.text: "A city project is open to us. A project is paid for at once, borrowing what the Treasury lacks, and it needs no workers."
+advisor.meyerson.pioneer_work.text: "One of our halutz units has no project. Halutzim build settlements, camps, fields, drained swamps and roads, one project to a unit."
+advisor.meyerson.corridors.text: "A corridor is built segment by segment, in any order, with one halutz unit to a segment, so several units can build one corridor at once."
+advisor.meyerson.money_debt.text: "We are borrowing. What the Treasury cannot pay is added to the debt, and a debt at its ceiling counts as Money exhausted."
+advisor.meyerson.cabinet.text: "A cabinet seat is empty. Each minister's competence works on the systems their office runs; the Cabinet screen shows the seat."
+advisor.meyerson.national_meters.text: "The country's measures have moved into a new situation. Housing, jobs and Food all move Social cohesion, which the top bar shows."
+advisor.meyerson.budget_unsubmitted.text: "The budget has changes that are not submitted. They will not apply when the turn ends unless you press Submit."
+```
+
+ Hebrew drafts (pending), Meyerson speaking in the plural "we" and the player addressed in the plural (HE-03):
+
+```yaml
+advisor.meyerson.projects.text: "פרויקט עירוני פתוח בפנינו. פרויקט משולם מיד, בהלוואה על מה שחסר באוצר, ואינו דורש עובדים."
+advisor.meyerson.pioneer_work.text: "לאחת מיחידות החלוצים שלנו אין משימה. חלוצים בונים יישובים, מחנות, שדות, ביצות מיובשות ודרכים, משימה אחת ליחידה."
+advisor.meyerson.corridors.text: "מסדרון נבנה קטע אחר קטע, בכל סדר, יחידת חלוצים אחת לכל קטע, כך שכמה יחידות יכולות לבנות מסדרון אחד יחד."
+advisor.meyerson.money_debt.text: "אנחנו לווים. מה שהאוצר אינו יכול לשלם נוסף לחוב, וחוב שהגיע לתקרה נחשב כסף אזול."
+advisor.meyerson.cabinet.text: "מושב בממשלה ריק. הכשירות של כל שר פועלת על המערכות שמשרדו מפעיל; מסך הממשלה מראה את המושב."
+advisor.meyerson.national_meters.text: "מדדי המדינה עברו למצב חדש. דיור, תעסוקה ומזון משפיעים כולם על הלכידות החברתית, שהסרגל העליון מציג."
+advisor.meyerson.budget_unsubmitted.text: "בתקציב יש שינויים שלא הוגשו. הם לא ייכנסו לתוקף בסיום התור אלא אם תלחצו על הגשה."
+```
+
+ Use the UI's own Hebrew words where they exist: check `strings.he.yaml` for the Budget screen's Submit button and the Cabinet screen's title, and use those exact words.
+- [ ] **Step 4: Run** `FILTER="AdvisorSignalsTests;AdvisorCatalogTests;BudgetScreenTests;LeftColumnTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: Meyerson's teaching messages and the unsubmitted-budget warning (Refs #1484)"`
+
+### Task 19: Immigration, with the verified quote
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorQuotes.cs`
+- Modify: `AdvisorPresenter.cs` (`Fill`), `AdvisorCatalog.cs` (the quote's strings checked; `Shipped().Quotes`), `AdvisorSignals.cs`, `GameRoot.cs:385` (the hex click), `Game.uxml` (two labels in `advisor-body`), `Statecraft.uss`, `advisor-messages.yaml`, both strings files
+- Test: `AdvisorPopupTests.cs`, `AdvisorSignalsTests.cs`, `AdvisorCatalogTests.cs`
+
+**Interfaces:**
+- Consumes: spec 3.3's Q1, its English and Hebrew text and its source; `GameRoot.OnHexClicked` (`GameRoot.cs:572`), `InfoPanelPresenter.Selected`, `ShowsUnit` (`InfoPanelPresenter.cs:138`, `:141`); `City.Refugees` (`GddState.cs:56`).
+- Produces: `AdvisorQuotes.Ids = { "q1", "q2", "q3", "q4" }` (spec 3.3's usable rows); strings `advisor.quote.<id>.text` and `.source` (checked only for a quote a message uses); elements `advisor-quote`, `advisor-quote-source`; event signal `city_shown`; measure `refugees_at_least` (refugees in all the player's cities); message `meyerson.immigration`.
+
+- [ ] **Step 1: Write the failing tests.** In `AdvisorPopupTests`:
+
+```csharp
+ /// <summary>Spec 3.2: a real quote shows only from the verified list, styled as a quote with its source under it; the
+ /// advisor's own line stays plain game dialogue.</summary>
+ [Test]
+ public void AQuoteShowsWithItsSourceAndOnlyThere()
+ {
+ using var rig = new Rig(catalog: Fixture.Replace("level: new, actions: [{ open_screen: budget }]", "level: new, quote: q1"));
+ rig.Advisor.NewGame();
+ Assert.AreEqual(En["advisor.quote.q1.text"], rig.Ui.Q<Label>("advisor-quote").text);
+ Assert.AreEqual(En["advisor.quote.q1.source"], rig.Ui.Q<Label>("advisor-quote-source").text);
+ Assert.AreEqual("Teach.", rig.Ui.Q<Label>("advisor-text").text, "the advisor's own line stays plain");
+ rig.Ui.Press("advisor-got-it");
+ rig.EndTurn();
+ Assert.AreEqual(DisplayStyle.None, rig.Ui.Q<Label>("advisor-quote").style.display.value, "a message without a quote shows none");
+ }
+```
+
+ In `AdvisorSignalsTests`: `refugees_at_least` equals the sum of `Refugees` over `b.State.Cities`. In `AdvisorCatalogTests`: a fixture message with `quote: q1` and no `advisor.quote.q1.source` string is named ("no advisor.quote.q1.source").
+
+- [ ] **Step 2: Run** `FILTER="AdvisorPopupTests;AdvisorSignalsTests;AdvisorCatalogTests"`; expect failures.
+- [ ] **Step 3: Implement.** `AdvisorQuotes`:
+
+```csharp
+namespace Statecraft.Game.UI
+{
+ /// <summary>Spec 3.3's verified quotes (Codex cx285, checked 23 October 2026): only these may show, each styled as a
+ /// quote with its source line, and only as that list allows (Q1 and Q2 attributed to the Declaration, never to a person).
+ /// Its text and source are advisor.quote.&lt;id&gt;.text and .source.</summary>
+ public static class AdvisorQuotes
+ {
+ public static readonly string[] Ids = { "q1", "q2", "q3", "q4" };
+ }
+}
+```
+
+ `AdvisorCatalog.Shipped()`: `Quotes = AdvisorQuotes.Ids`; in `Problems`, for a message with a quote, `Text(p, en, he, at, "advisor.quote." + m.Quote + ".text", 0)` and the same for `.source`. Game.uxml, inside `advisor-body` after `advisor-text`: `<ui:Label name="advisor-quote" class="advisor-quote" /><ui:Label name="advisor-quote-source" class="muted advisor-quote-source" />`; Statecraft.uss: `.advisor-quote { white-space: normal; font-size: 20px; -unity-font-style: italic; margin: 2px 12px 0 12px; border-left-width: 2px; border-color: var(--gold-dim); padding-left: 8px; } .lang-he .advisor-quote { border-left-width: 0; border-right-width: 2px; padding-left: 0; padding-right: 8px; } .advisor-quote-source { white-space: normal; font-size: 15px; margin: 2px 12px 6px 12px; }`. `Fill` shows both labels only for a message with a quote. The signal: `CityShown = "city_shown"` joins `Events`; `["refugees_at_least"] = ctx => ctx.State.Cities.Values.Sum(x => x.Refugees)` joins `Measures`. GameRoot's hex handler (`:385`) becomes `(q, r) => { OnHexClicked(map, unitLayer, info, q, r); if (!info.ShowsUnit && info.Selected is (int sq, int sr) && bridge.Content.SettlementHexes.Any(h => h.Q == sq && h.R == sr && bridge.State.Cities.ContainsKey(h.Id))) advisor?.Notice(AdvisorSignals.CityShown); }`. Data and strings:
+
+```yaml
+ - { id: meyerson.immigration, advisor: meyerson, signal: city_shown, when: { refugees_at_least: 1 }, level: new, quote: q1, actions: [{ show_me: city_housing }, { encyclopedia: immigration }] }
+```
+
+```yaml
+# Spec 3.3, Q1: the Declaration's words, attributed to the Declaration (never to a person), from the Knesset's official
+# English text (American spelling, one edition throughout).
+advisor.quote.q1.text: "“THE STATE OF ISRAEL will be open for Jewish immigration and for the Ingathering of the Exiles;”"
+advisor.quote.q1.source: "Declaration of the Establishment of the State of Israel, 14 May 1948"
+advisor.meyerson.immigration.text: "Refugees wait in our cities and become civilians a share at a time, each turn. There is no hard cap: people beyond a city's housing still live there."
+```
+
+```yaml
+# Q1 in the Declaration's official Hebrew (spec 3.3); the source line is agent-drafted. For the native reviewer (#564).
+advisor.quote.q1.text: "«מדינת ישראל תהא פתוחה לעליה יהודית ולקיבוץ גלויות;»"
+advisor.quote.q1.source: "ההכרזה על הקמת מדינת ישראל, 14 במאי 1948"
+advisor.meyerson.immigration.text: "פליטים ממתינים בערים שלנו והופכים לאזרחים חלק אחר חלק, בכל תור. אין תקרה קשיחה: מי שמעבר לדיור של העיר עדיין גר בה."
+```
+
+- [ ] **Step 4: Run** `FILTER="AdvisorPopupTests;AdvisorSignalsTests;AdvisorCatalogTests;HebrewUiTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: immigration teaching with the Declaration's verified line (Refs #1484)"`
+
+### Task 20: Dayan's teaching and warning
+
+**Files:**
+- Modify: `AdvisorSignals.cs`, `GameRoot.cs:385` (a unit shown), `advisor-messages.yaml`, both strings files
+- Test: `AdvisorSignalsTests.cs`
+
+**Interfaces:**
+- Consumes: `Unit.Order` (`GddState.cs:127`); `GameSession.Last` (`GameSession.cs:16`) and its `Why` (`Cause.Key`, `Cause.EnemyOrder`, `Cause.cs:18`, `:22`); `WhyKeys.Engagement` (`UnitLines.cs:28`); `GameState.Arms` (`GameState.cs:102`); `SettlementControl.AwaitingChoice` (`SettlementControl.cs:14`); `Combat.TruceUntil` (public in #1493, not yet merged).
+- Produces: event signal `unit_shown`; state signals `standing_order`, `combat_seen`, `arms_out`, `capture_waiting`, `enemy_moved`, and `truce_active` once #1493 has merged; messages `dayan.standing_orders`, `dayan.combat`, `dayan.arms_out`, `dayan.capture`, `dayan.enemy_phase`, `dayan.truce` (with `truce_active`).
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ [Test]
+ public void DayansSignalsReadTheShownStateAndTheLastTurn()
+ {
+ var b = Bridge();
+ Assert.AreEqual(b.State.Units.Values.Any(u => u.Side == Movement.PlayerSide && u.Order != ""), Holds(b, "standing_order"));
+ Assert.IsFalse(Holds(b, "combat_seen"), "no turn yet");
+ Assert.IsFalse(Holds(b, "enemy_moved"), "no turn yet");
+ b.EndTurn();
+ var why = b.Session.Last!.Why;
+ Assert.AreEqual(why.Any(w => w.Key == WhyKeys.Engagement), Holds(b, "combat_seen"));
+ Assert.AreEqual(why.Any(w => w.EnemyOrder != ""), Holds(b, "enemy_moved"));
+ b.State.Arms = 0;
+ Assert.AreEqual(C.IsGdd, Holds(b, "arms_out"));
+ Assert.AreEqual(b.State.Settlements.Values.Any(x => x.State == SettlementControl.AwaitingChoice), Holds(b, "capture_waiting"));
+ }
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorSignalsTests"`; expect failures.
+- [ ] **Step 3: Implement.**
+
+```csharp
+ ["standing_order"] = ctx => ctx.State.Units.Values.Any(u => u.Side == Movement.PlayerSide && u.Order != ""),
+ ["combat_seen"] = ctx => ctx.Bridge.Session.Last?.Why.Any(w => w.Key == WhyKeys.Engagement) == true,
+ ["arms_out"] = ctx => ctx.Content.IsGdd && ctx.State.Arms == 0,
+ ["capture_waiting"] = ctx => ctx.State.Settlements.Values.Any(x => x.State == SettlementControl.AwaitingChoice),
+ ["enemy_moved"] = ctx => ctx.Bridge.Session.Last?.Why.Any(w => w.EnemyOrder != "") == true,
+```
+
+ and, only if #1493 is on main when this task runs, `["truce_active"] = ctx => Combat.TruceUntil(ctx.State) != null` with the `dayan.truce` row; otherwise leave both out and say so in the PR (the truces page, Task 13, still teaches it). `UnitShown = "unit_shown"` joins `Events`; GameRoot's hex handler adds `if (info.ShowsUnit) advisor?.Notice(AdvisorSignals.UnitShown);`. Data:
+
+```yaml
+ - { id: dayan.standing_orders, advisor: dayan, signal: unit_shown, level: new, actions: [{ encyclopedia: standing_orders }] }
+ - { id: dayan.combat, advisor: dayan, signal: combat_seen, level: new, actions: [{ show_me: nav_why }, { encyclopedia: combat }] }
+ - { id: dayan.arms_out, advisor: dayan, signal: arms_out, level: warnings, repeat: every, cooldown_turns: 3, actions: [{ open_screen: defence }] }
+ - { id: dayan.capture, advisor: dayan, signal: capture_waiting, level: experienced, actions: [{ encyclopedia: capture }] }
+ - { id: dayan.enemy_phase, advisor: dayan, signal: enemy_moved, level: new, actions: [{ encyclopedia: enemy_phase }] }
+ - { id: dayan.truce, advisor: dayan, signal: truce_active, level: experienced, actions: [{ encyclopedia: truces }] }
+```
+
+ English (R-ORDER-001 and R-UNIT-005; the Why lines; R-ARMS-001; R-CTRL-008, recommending none; R-ENEMY-001 and the turn report's enemy lines, #1293; R-COMBAT-009 and R-ENEMY-006):
+
+```yaml
+advisor.dayan.standing_orders.text: "A unit keeps its standing order, fortify or hold, turn after turn until you give another; moving clears fortify. Send home is the only way a unit goes home."
+advisor.dayan.combat.text: "Our units fought this turn. Why? lists each engagement and its result."
+advisor.dayan.arms_out.text: "Our Arms stock is empty. One Arms equips one recruit group."
+advisor.dayan.capture.text: "A captured settlement waits for your answer. The dialog shows what each answer costs, as the game computes it; the choice is yours."
+advisor.dayan.enemy_phase.text: "The enemy moved after our orders this turn. Its units follow the same rules as ours, and the turn report lists what each did."
+advisor.dayan.truce.text: "A truce we accepted is in force. Until its window ends our units cannot attack, and the enemy's standing attacks end too."
+```
+
+ Hebrew drafts (pending):
+
+```yaml
+advisor.dayan.standing_orders.text: "יחידה שומרת על פקודת הקבע שלה, התבצרות או החזקה, תור אחר תור עד שתתנו אחרת; תנועה מבטלת התבצרות. שחרור הביתה הוא הדרך היחידה של יחידה לחזור הביתה."
+advisor.dayan.combat.text: "היחידות שלנו לחמו בתור הזה. במסך למה? מופיע כל קרב ותוצאתו."
+advisor.dayan.arms_out.text: "מלאי הנשק שלנו ריק. יחידת נשק אחת מציידת קבוצת מגויסים אחת."
+advisor.dayan.capture.text: "יישוב שנכבש ממתין לתשובה שלכם. החלון מציג כמה עולה כל תשובה, כפי שהמשחק מחשב; הבחירה שלכם."
+advisor.dayan.enemy_phase.text: "האויב נע אחרי ההוראות שלנו בתור הזה. יחידותיו פועלות לפי אותם כללים כמו שלנו, ודוח התור מפרט מה עשתה כל אחת."
+advisor.dayan.truce.text: "הפוגה שקיבלנו בתוקף. עד שחלונה מסתיים היחידות שלנו אינן יכולות לתקוף, וגם התקפות הקבע של האויב מסתיימות."
+```
+
+ Use the unit card's own Hebrew words for fortify, hold and Send home (`unit.order.*` in `strings.he.yaml`).
+- [ ] **Step 4: Run** `FILTER="AdvisorSignalsTests;AdvisorCatalogTests"`; expect PASS. Then the slice's gates (FULL EditMode, `bash scripts/check.sh origin/main`, `dotnet test sim/Statecraft.sln` with the goldens unchanged, screenshots of one critical warning and one teaching message in English and Hebrew at 1280x720 and 390x844, using a test-only approved copy for the Hebrew shot and saying so), `changelog.d/advisors-s4.md`:
+
+```markdown
+- The advisors speak as the game goes on: David Ben-Gurion warns when one of the player's cities is likely to be
+ attacked this turn and when Money and Food have run out; Golda Meyerson warns of debt near its ceiling, a Food
+ shortage and an unsubmitted budget; each advisor teaches a mechanic the first time the player meets it. Settings
+ sets how much they say (New to strategy games, Experienced, Warnings only, Off); critical warnings show at every
+ level. The end screen names the war loss (Refs #1484).
+```
+
+ The PR lists every new advisor line for the owner's content review.
+- [ ] **Step 5: Commit.** `git commit -m "ui: Dayan's teaching and the Arms warning (Refs #1484)"`
+
+---
+
+## S5: Counsel and disagreement
+
+### Task 21: The Counsel screen and history
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/CounselPresenter.cs`, `unity/Assets/Tests/EditMode/CounselScreenTests.cs`
+- Modify: `ScreenNav.cs:13` (`counsel` before `encyclopedia`), `HudPresenter.cs:72`, `KeyScroll.cs:21`, `Game.uxml` (the rail button after `nav-timeline`, `:20`; the screen after the encyclopedia's), `Statecraft.uss`, both strings files, `GameRoot.cs`, `AdvisorQueue.cs` (`Concern`), `AdvisorPresenter.cs` (`ShowNow`)
+- Modify (the rail pins): `HebrewUiTests.cs:283`, `KeyboardTurnTests.cs:109`, `LeftColumnTests.cs:37`, `:259`, `PromoHudTests.cs:43`, `TopBarTests.cs:628`
+
+**Interfaces:**
+- Consumes: `AdvisorQueue.History`, `PutOffIds` (Task 3), `AdvisorSession` (Task 5), `ScreenNav.OnOpened` (`ScreenNav.cs:94`).
+- Produces: `AdvisorQueue.Concern(string advisor, int turn, bool hebrew) -> Message?` (the advisor's highest message waiting now, caps ignored); `AdvisorPresenter.ShowNow(string id)` (shows a message from Counsel, ignoring the turn's caps, never its help level); `CounselPresenter(VisualElement root, UiText text, AdvisorSession session, SimBridge bridge, AdvisorPresenter advisor)`; elements `screen-counsel`, `counsel-title`, `counsel-advisor-<id>` (name, `counsel-concern-<id>`), `counsel-history` (rows `counsel-row-<n>`, newest first, each with its date and a `counsel-show-<n>` button for a put-off message); strings `hud.nav.counsel` "Counsel" / "עצה", `counsel.title` "Counsel" / "עצה", `counsel.nothing` "Nothing pressing." / "אין דבר דחוף.", `counsel.history` "Earlier advice" / "עצות קודמות", `counsel.show` "Show" / "הצגה", `counsel.put_off` "Put off" / "נדחה". The rail glyph: `people`.
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ /// <summary>Spec 7.4: one card per advisor with their top concern now, then this game's history, newest first, each with
+ /// its date; a put-off message can be shown again from it. The history is the session's: a reload starts it empty.</summary>
+ [Test]
+ public void CounselShowsConcernsAndTheHistoryNewestFirst()
+ {
+ using var rig = new AdvisorPopupTests.Rig();
+ using var counsel = new CounselPresenter(rig.Ui.Root, AdvisorPopupTests.Text(), rig.Session, rig.Bridge, rig.Advisor);
+ rig.Advisor.NewGame(); rig.Ui.Press("advisor-got-it"); // t.teach shown
+ rig.EndTurn(); // t.crit, then t.warn
+ rig.Ui.Press("advisor-got-it"); rig.Ui.Press("advisor-not-now");
+ rig.Ui.Press("nav-counsel");
+ var rows = rig.Ui.Q<ScrollView>("counsel-history").contentContainer.Children().ToList();
+ CollectionAssert.AreEqual(new[] { "t.warn", "t.crit", "t.teach" }, rows.Select(r => (string)r.userData).ToArray(), "newest first");
+ Assert.AreEqual(AdvisorPopupTests.Text()["counsel.nothing"], rig.Ui.Q<Label>("counsel-concern-ben_gurion").text);
+ rig.Ui.Press(rows[0].Q<Button>().name); // Show the put-off warning now
+ Assert.AreEqual("t.warn", rig.Advisor.Shown!.Id);
+ }
+
+ /// <summary>Review Focus 4: a ninth disc on the rail. LeftColumnTests' windows have no phone held sideways; with Counsel
+ /// the column must still fit at 844x390 and on the upright phones, every disc clear of the next.</summary>
+ [UnityTest]
+ public IEnumerator TheRailFitsWithCounselOnEveryPhone()
+ {
+ var problems = new List<string>();
+ foreach (var hebrew in new[] { false, true })
+ foreach (var (w, h) in new[] { (844, 390), (390, 844), (360, 800), (375, 667) })
+ yield return Rendered(w, h, hebrew, root =>
+ {
+ string at = $"{(hebrew ? "he" : "en")} {w}x{h}";
+ var discs = ScreenNav.Screens.Select(s => root.Q("nav-" + s).worldBound).ToList();
+ foreach (var d in discs) if (!root.worldBound.Contains(d.min) || !root.worldBound.Contains(d.max)) problems.Add($"{at}: a disc {d} leaves the window");
+ for (int i = 1; i < discs.Count; i++) if (discs[i].Overlaps(discs[i - 1])) problems.Add($"{at}: {ScreenNav.Screens[i]} overlaps {ScreenNav.Screens[i - 1]}");
+ var endTurn = root.Q("end-turn").worldBound;
+ foreach (var d in discs) if (d.Overlaps(endTurn)) problems.Add($"{at}: a disc {d} overlaps End turn {endTurn}");
+ });
+ Assert.IsEmpty(problems, string.Join("\n", problems));
+ }
+```
+
+ (`Rendered` as `HowToPlayScreenTests.Rendered`, `HowToPlayScreenTests.cs:66-97`, kept in `EncyclopediaScreenTests` since Task 12; make it `internal static` and reuse it.)
+
+- [ ] **Step 2: Run** `FILTER="CounselScreenTests"`; expect compile errors.
+- [ ] **Step 3: Implement.** Add `counsel` to `ScreenNav.Screens` before `encyclopedia` and to every pin (one commit); the rail button `<ui:Button name="nav-counsel" text="Counsel" class="nav-button rail-button"><Statecraft.Game.UI.UiIcon glyph="people" class="nav-disc" /></ui:Button>`; the screen `screen-counsel` (a header, three advisor cards in a row that wraps, the history ScrollView). `CounselPresenter` renders on `ScreenNav.OnOpened`: each card shows the advisor's name and `text["advisor." + concern.Id + ".text"]` or `counsel.nothing`; the history rows from `session.Queue.History` reversed, each `userData = entry.Id`, with the message's text, its date (`date.day_month_year`, as `EndScreenPresenter.cs:76`) and, for an id still in `PutOffIds`, a `counsel.show` button that closes the screen and calls `advisor.ShowNow(id)`. In Hebrew a pending message's row shows `counsel.put_off`'s label only, never its English text. If the rail does not fit at 844x390, tighten the rail's disc spacing for the narrow tier in Statecraft.uss; never drop a disc.
+- [ ] **Step 4: Run** `FILTER="CounselScreenTests;LeftColumnTests;HebrewUiTests;KeyboardTurnTests;PromoHudTests;TopBarTests;UiFoundationTests;HudTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' Counsel screen and history (Refs #1484)"`
+
+### Task 22: Disagreement
+
+**Files:**
+- Modify: `CounselPresenter.cs`, `AdvisorQueue.cs`, `AdvisorSignals.cs` (the `treasury_at_most` measure), `advisor-messages.yaml`, both strings files
+- Test: `CounselScreenTests.cs`
+
+**Interfaces:**
+- Consumes: `Message.DisagreesWith` (checked mutual, Task 1).
+- Produces: Counsel shows a pair side by side (`counsel-disagreement`, two option columns, each the message's text and its Show me) when both messages of a pair are waiting; at most one pair a turn; the popup never shows a disagreeing message by itself (it waits for Counsel); one pair in the data.
+
+- [ ] **Step 1: Write the failing test:**
+
+```csharp
+ /// <summary>Spec 8: two advisors' views of one trade-off, side by side as options in Counsel; the game picks neither, and
+ /// at most one pair shows a turn.</summary>
+ [Test]
+ public void APairShowsSideBySideInCounselAndNeverInThePopup()
+ {
+ var catalog = "advisors:\n - { id: ben_gurion, person: ben_gurion }\n - { id: meyerson, person: golda_meir }\n - { id: dayan, person: dayan }\n" +
+ "messages:\n - { id: d.houses, advisor: meyerson, signal: turn_ended, level: warnings, disagrees_with: d.arms, actions: [{ open_screen: budget }] }\n" +
+ " - { id: d.arms, advisor: dayan, signal: turn_ended, level: warnings, disagrees_with: d.houses, actions: [{ open_screen: defence }] }\n";
+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text + "\nadvisor.d.houses.text: \"Houses.\"\nadvisor.d.arms.text: \"Arms.\"\n");
+ using var rig = new AdvisorPopupTests.Rig(catalog: catalog, text: text);
+ using var counsel = new CounselPresenter(rig.Ui.Root, text, rig.Session, rig.Bridge, rig.Advisor);
+ rig.EndTurn();
+ Assert.IsFalse(rig.Advisor.IsOpen, "a disagreement waits for Counsel");
+ rig.Ui.Press("nav-counsel");
+ var pair = rig.Ui.Q("counsel-disagreement");
+ Assert.AreNotEqual(DisplayStyle.None, pair.style.display.value);
+ CollectionAssert.AreEquivalent(new[] { "Houses.", "Arms." }, pair.Query<Label>(className: "counsel-option-text").ToList().Select(l => l.text).ToArray());
+ Assert.AreEqual(0, rig.Bridge.Queued.Count, "nothing chosen for the player");
+ }
+```
+
+- [ ] **Step 2: Run**; expect FAIL.
+- [ ] **Step 3: Implement.** `AdvisorQueue.Head` skips a message with `DisagreesWith != ""`; `AdvisorQueue.Disagreement(int turn, bool hebrew) -> (Message, Message)?` returns the first pair whose two messages both wait (one pair a turn). `CounselPresenter` renders it above the history, each option the message's text and its Show me (its `open_screen`), neither marked. The data's one pair (spec 8's example), both `level: warnings`, only when the Treasury is short and Arms are out; English drafts, for the owner:
+
+```yaml
+ - { id: meyerson.money_for_housing, advisor: meyerson, signal: arms_out, when: { treasury_at_most: 0 }, level: warnings, repeat: every, cooldown_turns: 4, disagrees_with: dayan.money_for_arms, actions: [{ open_screen: budget }] }
+ - { id: dayan.money_for_arms, advisor: dayan, signal: arms_out, when: { treasury_at_most: 0 }, level: warnings, repeat: every, cooldown_turns: 4, disagrees_with: meyerson.money_for_housing, actions: [{ open_screen: defence }] }
+```
+
+```yaml
+advisor.meyerson.money_for_housing.text: "Option: keep what Money we have for housing and jobs. The Budget screen shows what each share costs."
+advisor.dayan.money_for_arms.text: "Option: put Money into Arms first, so recruit groups can be equipped. The Defence screen shows the price."
+```
+
+ with the measure `["treasury_at_most"] = ctx => ctx.State.Treasury`, and Hebrew drafts (pending). Neither line is phrased as an order (spec 8).
+- [ ] **Step 4: Run** `FILTER="CounselScreenTests;AdvisorQueueTests;AdvisorCatalogTests"`; expect PASS. Then the slice's gates, screenshots of Counsel (English and Hebrew, 1280x720 and 390x844), `changelog.d/advisors-s5.md`:
+
+```markdown
+- A Counsel screen in the side menu: each advisor's top concern now, this game's advice so far (newest first, with its
+ date) and any advice put off with "Not now", which can be shown again. When two advisors see one trade-off
+ differently, Counsel shows both views side by side as options; the game picks neither (Refs #1484).
+```
+
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' disagreements in Counsel (Refs #1484)"`
+
+---
+
+## S6a: the media player, whatever the clips turn out to be
+
+Everything in this slice is tested with fake pictures and fake audio, and with the shipped data carrying no media row: the files arrive in Task 26.
+
+### Task 23: The media row and its checks
+
+**Files:**
+- Modify: `AdvisorCatalog.cs` (`Media`, on `Message` and `Page`; `Problems`; `Shipped().StreamingFile`)
+- Test: `AdvisorCatalogTests.cs`
+
+**Interfaces:**
+- Consumes: Task 1.
+- Produces: `AdvisorCatalog.Media { string Picture; Dictionary<string,string> Narration; Dictionary<string,List<double>> Cues; string Label; string Credit }`; `Message.Media` and `Page.Media` (null when absent); `AdvisorCatalog.MediaFolder = "advisors"` (under StreamingAssets). Cue keys `advisor.<id>.cue.<n>` (pages: `advisor.page.<id>.cue.<n>`), `n` from 1.
+
+ The row, media-neutral (Global Constraints):
+
+```yaml
+ media:
+ picture: opening.greeting.mp4 # StreamingAssets/advisors/: .mp4 a silent clip, .jpg or .png a still
+ narration: { en: opening.greeting.en.wav } # he: only once the Hebrew is approved (OQ-4, spec 11.2)
+ cues: { en: [0.0, 4.2] } # start seconds of advisor.<id>.cue.1, .cue.2, ... in that language
+ label: advisor.media_label # the disclosure line under the picture, in both languages
+ credit: "" # a photograph's credit line key, where its licence asks
+```
+
+- [ ] **Step 1: Write the failing tests** (TestCase rows, as Task 1's):
+
+```csharp
+ [TestCase("{ picture: x.gif, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: lab }", "picture must be .mp4, .jpg or .png")]
+ [TestCase("{ picture: missing.mp4, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: lab }", "no StreamingAssets/advisors/missing.mp4")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.mp3 }, cues: { en: [0.0] }, label: lab }", "narration must be .wav")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.5] }, label: lab }", "cues start at 0")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0, 3.0, 2.0] }, label: lab }", "cues must rise")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav, he: x.he.wav }, cues: { en: [0.0], he: [0.0] }, label: lab }", "Hebrew narration before its approval")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0, 2.0] }, label: lab }", "no advisor.x.cue.2")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: nolabel }", "no nolabel")]
+ public void EachBrokenMediaRowIsNamed(string media, string expected)
+ {
+ var known = new AdvisorCatalog.Known { Signals = new[] { "new_game" }, StreamingFile = f => f.StartsWith("x.", System.StringComparison.Ordinal) };
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new, media: " + media + " }\n");
+ var t = Strings("advisor.x.text", "advisor.x.cue.1", "lab");
+ var problems = c.Problems(t, t, known);
+ Assert.IsTrue(problems.Any(p => p.Contains(expected)), $"expected '{expected}' in:\n{string.Join("\n", problems)}");
+ }
+
+ [Test]
+ public void AGoodMediaRowHasNoProblems()
+ {
+ var known = new AdvisorCatalog.Known { Signals = new[] { "new_game" }, StreamingFile = _ => true };
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new, he_review: approved, " +
+ "media: { picture: x.jpg, narration: { en: x.en.wav, he: x.he.wav }, cues: { en: [0.0, 2.5], he: [0.0, 2.8] }, label: lab } }\n");
+ var t = Strings("advisor.x.text", "advisor.x.cue.1", "advisor.x.cue.2", "lab");
+ Assert.IsEmpty(c.Problems(t, t, known));
+ }
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorCatalogTests"`; expect compile errors (`media`).
+- [ ] **Step 3: Implement** `public const string MediaFolder = "advisors";`, `Media` and a `CheckMedia(p, at, keyStem, media, heReview, en, he, known)` called for messages and pages: the picture's extension and file; each narration `.wav` and its file; `he` narration and cues only with `he_review: approved`; for each language with narration, cues present, first 0, strictly rising, and each `keyStem + ".cue." + n` in both strings files (the same count of cues in both languages, so the keys stay in parity); the label key in both; the credit key in both when set. `Shipped().StreamingFile = f => System.IO.File.Exists(System.IO.Path.Combine(Application.streamingAssetsPath, MediaFolder, f))`.
+- [ ] **Step 4: Run** `FILTER="AdvisorCatalogTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' media rows and their checks (Refs #1484)"`
+
+### Task 24: Picture, narration and captions, in step
+
+**Files:**
+- Create: `unity/Assets/Scripts/UI/AdvisorMedia.cs`, `unity/Assets/Tests/EditMode/AdvisorMediaTests.cs`
+- Modify: `CardVideo.cs` (`Play(..., bool held = false)`, `Release()`, `Time`, `Seek`), `DeclarationRecording.cs:204` (`WebFetch` internal), `AdvisorPresenter.cs` (stop on cover, Got it, Not now, X)
+
+**Interfaces:**
+- Consumes: `CardVideo.Play`, `Stop`, `Current`, `Url` (`CardVideo.cs:53-64`, `:75-80`, `:43`, `:40`); `DeclarationRecording.Fetch`, `IOutput`, `SourceOutput`, `WebFetch` (`DeclarationRecording.cs:43`, `:46-56`, `:241-281`, `:204`); the decision card's player (`GameRoot.cs:254`), borrowed while no card is open (spec 12).
+- Produces: `AdvisorMedia(UiText text, IPicture? clip, IPicture? still, DeclarationRecording.Fetch fetch, DeclarationRecording.IOutput output)`; `Play(AdvisorCatalog.Media media, string keyStem, bool hebrew, VisualElement picture, Label caption, Action ended, Action<string> failed)`; `Stop()`; `Tick()` (internal; every `TickMs = 50`); `Playing`; `const double DriftS = 0.1`; `AdvisorMedia.Url(string file)` (under `AdvisorCatalog.MediaFolder`); `interface IPicture { void Load(string url, VisualElement target, Action<string> failed); bool Ready { get; } void Start(); void Stop(); double Time { get; } void Seek(double t); }`; `ClipPicture(CardVideo video)` (stops the player only while it plays its own URL); `StillPicture()` (a texture fetched by URL; `Time` is the narration's); `AdvisorCaptions.At(IReadOnlyList<double> starts, double position) -> int` (index, -1 before the first). `CardVideo.Play(..., held: true)` prepares and shows nothing until `Release()`.
+
+- [ ] **Step 1: Write the failing tests** with fakes:
+
+```csharp
+#nullable enable
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+/// <summary>Spec 12 and Review Focus 1 and 2: the picture is silent and the narration a separate file; they start in the
+/// same tick only once both are ready; a drift past 0.1 s is corrected to the narration; live captions follow the
+/// narration's position; one press or a covering layer stops both; the card's own loop is never stopped by the advisor.</summary>
+public class AdvisorMediaTests
+{
+ sealed class FakePicture : AdvisorMedia.IPicture
+ {
+ public bool Ready { get; set; }
+ public double Time { get; set; }
+ public bool Started, Stopped; public readonly List<double> Seeks = new List<double>();
+ public void Load(string url, VisualElement target, Action<string> failed) { }
+ public void Start() => Started = true;
+ public void Stop() => Stopped = true;
+ public void Seek(double t) { Seeks.Add(t); Time = t; }
+ }
+
+ sealed class FakeOutput : DeclarationRecording.IOutput
+ {
+ public bool Decoded = true; public bool IsPlaying { get; set; } public float Position { get; set; }
+ public bool Played, Stopped;
+ public bool? Ready(AudioClip clip) => Decoded;
+ public void Play(AudioClip clip) { Played = true; IsPlaying = true; }
+ public void Stop() { Stopped = true; IsPlaying = false; }
+ public void Dispose() { }
+ }
+
+ sealed class Done : DeclarationRecording.IRequest { public ulong Bytes => 0; public void Abort() { } }
+ static DeclarationRecording.Fetch Immediate => (url, done) => { done(AudioClip.Create("n", 4410, 1, 44100, false), null); return new Done(); };
+
+ static readonly AdvisorCatalog.Media Row = new AdvisorCatalog.Media
+ {
+ Picture = "x.mp4", Narration = new Dictionary<string, string> { ["en"] = "x.en.wav" },
+ Cues = new Dictionary<string, List<double>> { ["en"] = new List<double> { 0.0, 2.5 } }, Label = "lab",
+ };
+ static UiText Text => UiText.Parse("ui.lang: en\nadvisor.x.cue.1: \"First.\"\nadvisor.x.cue.2: \"Second.\"\nlab: \"Label.\"\n");
+
+ (AdvisorMedia media, FakePicture pic, FakeOutput output, Label caption) Make()
+ {
+ var pic = new FakePicture(); var output = new FakeOutput(); var caption = new Label();
+ var media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ media.Play(Row, "advisor.x", false, new VisualElement(), caption, () => { }, _ => { });
+ return (media, pic, output, caption);
+ }
+
+ [Test]
+ public void PictureAndNarrationStartTogether()
+ {
+ var (media, pic, output, _) = Make();
+ media.Tick();
+ Assert.IsFalse(pic.Started || output.Played, "the picture is not ready: neither starts");
+ pic.Ready = true;
+ media.Tick();
+ Assert.IsTrue(pic.Started && output.Played, "both in the same tick");
+ }
+
+ [Test]
+ public void ADriftIsCorrectedToTheNarration()
+ {
+ var (media, pic, output, _) = Make();
+ pic.Ready = true; media.Tick();
+ output.Position = 3.0f; pic.Time = 2.8; media.Tick();
+ CollectionAssert.AreEqual(new[] { 3.0 }, pic.Seeks);
+ output.Position = 3.5f; pic.Time = 3.45; media.Tick();
+ Assert.AreEqual(1, pic.Seeks.Count, "within 0.1 s: left alone");
+ }
+
+ [Test]
+ public void CaptionsFollowTheNarrationsPosition()
+ {
+ var (media, pic, output, caption) = Make();
+ pic.Ready = true; media.Tick();
+ output.Position = 0.1f; media.Tick();
+ Assert.AreEqual("First.", caption.text);
+ output.Position = 2.6f; media.Tick();
+ Assert.AreEqual("Second.", caption.text);
+ Assert.AreEqual(-1, AdvisorCaptions.At(new[] { 0.5 }, 0.2));
+ }
+
+ [Test]
+ public void OnePressStopsBoth()
+ {
+ var (media, pic, output, caption) = Make();
+ pic.Ready = true; media.Tick(); output.Position = 0.1f; media.Tick();
+ media.Stop();
+ Assert.IsTrue(pic.Stopped && output.Stopped);
+ Assert.AreEqual("", caption.text);
+ Assert.IsFalse(media.Playing);
+ }
+
+ /// <summary>Review Focus 1: the advisor borrows the card's player only while no card is open; whatever stops the advisor's
+ /// clip never stops the card's own illustration loop on the same player.</summary>
+ [Test]
+ public void ALayerOverAPlayingClipStopsBothAndLeavesTheCardsLoopAlone()
+ {
+ LogAssert.ignoreFailingMessages = true; // the two URLs do not exist: the player's own error log is expected
+ using var video = new CardVideo();
+ var header = new VisualElement();
+ var clip = new ClipPicture(video);
+ clip.Load("advisor-clip.mp4", header, _ => { });
+ video.Play("card-loop.mp4", header, _ => { }); // the card took the player back
+ clip.Stop();
+ Assert.AreEqual("card-loop.mp4", video.Current, "the card's loop is not the advisor's to stop");
+ LogAssert.ignoreFailingMessages = false;
+
+ using var rig = new AdvisorPopupTests.Rig();
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.NewGame();
+ rig.Advisor.Watch(Row, "advisor.x");
+ rig.Advisor.Media.Tick();
+ Assert.IsTrue(rig.Advisor.Media.Playing, "precondition");
+ rig.HudRoot.AddToClassList(EventCardPresenter.OpenClass); ScreenNav.DisableCovered(rig.Ui.Root);
+ Assert.IsTrue(pic.Stopped && output.Stopped, "a layer over it stops picture and narration at once");
+ }
+}
+```
+
+- [ ] **Step 2: Run** `FILTER="AdvisorMediaTests"`; expect compile errors.
+- [ ] **Step 3: Implement.** `CardVideo`: `Play(..., bool held = false)` stores `held`; `OnPrepared` shows the texture and calls `p.Play()` only when not held; `public void Release() { held = false; if (player != null && player.isPrepared) player.Play(); }`; `public double Time => player?.time ?? 0;`; `public void Seek(double t) { if (player != null) player.time = t; }`. The card and the outcome clips pass nothing, so they behave as today (`EventVideoTests`, `OutcomeClipTests` unchanged). `ClipPicture.Load` calls `video.Play(url, target, failed, loop: false, held: true)` and keeps the URL; `Ready => video.Current == url && video.Showing`; `Start => video.Release()`; `Stop => { if (video.Current == url) video.Stop(); }`. `StillPicture` fetches with `UnityWebRequestTexture.GetTexture(url)`, sets the target's background on success, and is `Ready` then; `Time` and `Seek` do nothing (the narration drives the captions). `AdvisorMedia.Play` picks the clip picture for `.mp4`, the still for `.jpg`/`.png`, fetches the narration of the UI's language (`Url(file)`, as `DeclarationRecording.Url` builds its URL with the build id, `DeclarationRecording.cs:91-95`), and schedules `Tick` every `TickMs` on the caption's scheduler. `Tick`: while loading, start both in the same call once `picture.Ready && output.Ready(clip) == true`; while playing, set the caption to the cue at `output.Position` (`text[keyStem + ".cue." + (i + 1)]`, empty before the first), seek the picture when `Math.Abs(picture.Time - output.Position) > DriftS` (a still never drifts), and stop when the narration has been heard and is no longer playing; the load and decode limits are `DeclarationRecording`'s (`StallTimeoutMs`, `DecodeTimeoutMs`, `StartTimeoutMs`, `DeclarationRecording.cs:30`); a failure stops both, logs `ADVISOR MEDIA failed <file>: <why>`, and calls `failed`. `Stop` stops the picture, then the output, releases the clip, clears the caption. In `AdvisorPresenter`: a `Media` property (GameRoot sets it with `ClipPicture(video)` for the card's player and `StillPicture`, or leaves it null where `CardVideo.ForcedOff()`); `Watch(AdvisorCatalog.Media media, string keyStem)` (internal; Task 25 gives it a button, with the message's or page's own key stem); `Media?.Stop()` in `Hide` (a layer or the message leaving), `GotIt`, `NotNow`, the X and `Dispose`.
+- [ ] **Step 4: Run** `FILTER="AdvisorMediaTests;EventVideoTests;OutcomeClipTests;DeclarationRecordingTests;AdvisorPopupTests"`; expect PASS.
+- [ ] **Step 5: Commit.** `git commit -m "ui: the advisors' media player: picture, narration and live captions in step (Refs #1484)"`
+
+### Task 25: Watch, inline or in an overlay
+
+**Files:**
+- Modify: `AdvisorPresenter.cs` (the Watch badge, inline playing), `Game.uxml` (`advisor-watch` on the portrait, `advisor-media` in the popup, the `advisor-overlay` layer after `outcome-layer`), `Statecraft.uss`, `EncyclopediaPresenter.cs`, `CounselPresenter.cs`, `GameRoot.cs:770` (Escape closes the overlay), both strings files
+- Test: `AdvisorMediaTests.cs`
+
+**Interfaces:**
+- Consumes: Tasks 23, 24; `AdvisorLayout.Slot` (Task 4); `.outcome-layer`'s styles (`Statecraft.uss:325-332`).
+- Produces: `AdvisorMedia.Inline(HudTier tier, float slotHeight) -> bool` (`InlineMinPx = 460`, never on three rows); elements `advisor-watch`, `advisor-media`, `advisor-overlay`, `advisor-overlay-media`, `advisor-overlay-caption`, `advisor-overlay-label`, `advisor-overlay-close`; classes `advisor-watching` (on the popup), `advisor-overlay-open` (on the root); `AdvisorPresenter.CloseOverlay() -> bool`; strings `advisor.watch` "Watch" / "צפייה".
+
+- [ ] **Step 1: Write the failing tests:**
+
+```csharp
+ [TestCase(HudTier.OneRow, 506f, true)] // 1920x1080
+ [TestCase(HudTier.OneRow, 400f, false)] // 844x390: a phone held sideways
+ [TestCase(HudTier.TwoRow, 746f, true)] // 960x1080
+ [TestCase(HudTier.ThreeRow, 1164f, false)] // an upright phone: always the overlay
+ public void InlineWhereTheSlotHasRoom(HudTier tier, float slot, bool inline) => Assert.AreEqual(inline, AdvisorMedia.Inline(tier, slot));
+
+ [Test]
+ public void WatchPlaysInThePopupWithCaptionsInTheTextsPlace()
+ {
+ using var rig = new AdvisorPopupTests.Rig();
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = true; // EditMode's panel has no real slot height
+ rig.Advisor.NewGame();
+ rig.Advisor.Watch(Row, "advisor.x");
+ Assert.IsTrue(rig.Ui.Q("advisor-popup").ClassListContains("advisor-watching"));
+ rig.Ui.Press("advisor-got-it");
+ Assert.IsTrue(output.Stopped, "any button stops it");
+ Assert.IsFalse(rig.Ui.Q("advisor-popup").ClassListContains("advisor-watching"));
+ }
+
+ [Test]
+ public void TheOverlayClosesWithItsXOrEscapeAndStopsBoth()
+ {
+ using var rig = new AdvisorPopupTests.Rig();
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = false;
+ rig.Advisor.NewGame();
+ rig.Advisor.Watch(Row, "advisor.x");
+ Assert.IsTrue(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ Assert.IsTrue(rig.Advisor.CloseOverlay());
+ Assert.IsTrue(pic.Stopped && output.Stopped);
+ Assert.IsFalse(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ Assert.IsFalse(rig.Advisor.CloseOverlay(), "nothing to close");
+ }
+```
+
+- [ ] **Step 2: Run**; expect compile errors.
+- [ ] **Step 3: Implement.** The Watch badge shows on the portrait only for a message with media whose files have not failed this session (a failure hides it until reload, as the card's `failed` set does, `EventCardPresenter.cs:394`). Inline (`AdvisorMedia.Inline(AdvisorLayout.Tier(hudRoot), Slot().height)`, or `ForceInline` in tests): the popup gets `advisor-watching`, which hides the head's portrait row and the text and shows `advisor-media` (364x205) and the caption in `advisor-text`'s place; the buttons stay. Otherwise the overlay, styled as `.outcome-layer` (a dim backdrop, the 16:9 picture, the caption under it, the label line, an X; Escape closes it through GameRoot's poll, `:770`, before the other layers). The label key's text (the row's `label`) shows under the picture in both places, and the narrator line comes from it too (OQ-1: by office only). The encyclopedia's page and Counsel's rows get a Watch button for an item with media, always in the overlay (their screens are open). Strings `advisor.watch`.
+- [ ] **Step 4: Run** `FILTER="AdvisorMediaTests;AdvisorPopupTests;AdvisorPopupLayoutTests;EncyclopediaScreenTests;CounselScreenTests"`; expect PASS. Then the slice's gates with the boot timing (base and PR: nothing at boot), and `changelog.d/advisors-s6a.md`:
+
+```markdown
+- The advisors' popup can play a short clip or a still with its narration and live captions, in the popup on desktop
+ and in a centred overlay on phones; it never plays by itself, and any button or a window opening over it stops it.
+ No clip ships yet (Refs #1484).
+```
+
+- [ ] **Step 5: Commit.** `git commit -m "ui: Watch in the advisor popup, or in an overlay (Refs #1484)"`
+
+---
+
+## S6b: the clips (waits for the owner's media choice)
+
+### Task 26: Make and ship the clips of the chosen route
+
+This task starts only when the owner has picked Route A or Route B (or another) in writing. Nothing above depends on that choice; this task fills the data rows Task 23 defined.
+
+**Files:**
+- Create: `unity/Assets/StreamingAssets/advisors/*` (pictures, narration), a maker script under `tools/` for the chosen route (its tests in `tools/tests/`)
+- Modify: `advisor-messages.yaml` (`media:` rows), both strings files (cues, the label), `ASSETS.yaml`, `NOTICE`, `docs/ai-disclosure.md`, the README's AI section, the Steam draft; for the Dayan still, `ASSETS.portraits.yaml` and the portrait's import (spec 11.1)
+
+**Interfaces:**
+- Consumes: Task 23's row format, Task 24's player, `FFMPEG_VIDEO` and `problems()` (`tools/encode_event_videos.py:43-45`, `:111-126`).
+- Produces: shipped media rows; nothing else changes.
+
+- [ ] **Step 1: The route's gate, before any file is made.** Write down which applies, with the owner's words:
+ - **Route A** (the leader's stylized face, speaking the aide's voice, labelled "stylized portrayal, fictional dialogue and voice", made locally with LivePortrait): `docs/CONTENT_POLICY.md:104-112` says a "moving likeness of Ben-Gurion, Meyerson or Dayan is made only after written consent from their estates". A stylized animated face of the real person is a moving likeness, so Route A needs either the estates' written consent or the owner's amendment of those lines (and of D-ADV, `docs/oss/DECISIONS.md:70`) in this PR, quoted. The archival source photographs keep their licences and credits (spec 11.1); no photograph of a real person goes to ElevenLabs (spec 11.2).
+ - **Route B** (Tal Heuberger's fictional figures, speaking through ElevenLabs): Tal Heuberger's written permission, linked; the figures are fictional and resemble none of the three; ElevenLabs' terms (spec 13.2) and the 15 October in-game narration rules (`.github/skills/statecraft-video-script/references/06-ai-voice-music-and-disclosure.md:16-28`) apply.
+ - If neither holds, stop and ask the coordinator.
+- [ ] **Step 2: Make the files.** Pictures as silent H.264 at 960x540 with the encoder's profile (CRF 28, OQ-3), each passing `problems()`; a still where the route makes one. English narration as 16-bit PCM WAV. Hebrew narration only after a native reviewer approves a sample (rule 5, `06-ai-voice-music-and-disclosure.md:20`; OQ-4), and only then `he_review: approved`. Cue times from the narration's pauses, one sentence at a time, at most two lines.
+- [ ] **Step 3: Record them.** An `ASSETS.yaml` row per file: AI-generated, the tool, the voice id, the model, the date, the exact script, the sha256 (spec 13.3); `NOTICE` credits where a licence asks; `docs/ai-disclosure.md`, the README's AI section and the Steam draft in the same PR (rule 8, `:23`). The label string says what the route is (Route A: "Stylized portrayal, fictional dialogue and voice", with the owner's exact words); the narrator is named by office only (OQ-1).
+- [ ] **Step 4: The data and the tests.** The `media:` rows; `AdvisorCatalogTests.TheShippedFileHasNoProblems` now checks the files exist; a tools test runs `problems()` over every `.mp4` in `StreamingAssets/advisors/` (no audio stream, 960x540, faststart).
+- [ ] **Step 5: The gates.** The FULL EditMode run; `bash scripts/check.sh origin/main`; the load-time gate (data.gz, wasm.gz and framework unchanged beyond noise; the clips are in StreamingAssets and fetched only on Watch); `tools/headed.py boot --runs 3 --cpu 4` on base and PR; a WebGL check that a clip and its narration play in step in Chrome and Safari; English screenshots of Watch inline (1280x720) and in the overlay (390x844); `changelog.d/advisors-s6b.md`. The PR quotes the owner's media ruling and the route's gate from Step 1.
+
+S7 (the real figures' own voices and likeness, spec 11.3) is not planned: it waits for written consent from the Ben-Gurion Heritage Institute, Golda Meir's family and Moshe Dayan's heirs, each for their own figure, requested by the owner.
+
+---
+
+## Self-review
+
+- **Spec coverage.** 1 and 2 (Global Constraints; presentation only in every task); 3.1 names and narrators (Task 5's strings, Task 26's label, OQ-1); 3.2 rules (the checks in Task 1: words, em dashes; Tasks 16 to 22's lines; Deport never suggested, Task 20's capture line recommends none); 3.3 quotes (Task 19); 4.1 the file and its load test (Tasks 1, 23); 4.2 the runtime, one at a time, layers, queue order and caps, settings not save, no command (Tasks 3, 5, 7); 5 signals (Tasks 16 to 20; the city warning's sim helper, Task 15; the budget signal reads #1352's merged rule, Task 18; the movement rows read the opening chain and the `unit_shown` signal, and civ-movement's later points can be added as signals then); 6 help levels (Tasks 2, 3, 14; Off keeps every critical warning, Task 16); 7.1 the popup, placement per tier, Hebrew inside mirror, no pointer outside it (Tasks 4 to 6); 7.2 Tell me more (Task 13); 7.3 Show me (Tasks 8, 10); 7.4 Counsel (Task 21); 8 disagreement (Task 22); 9 the guide replaced, tests first, the event step restated, the seen key honoured (Tasks 2, 9 to 11); 10 the encyclopedia's 25 pages (Tasks 12, 13); 11 and 12 media, rewritten media-neutral by the owner's later rulings (Tasks 23 to 26); 13 voice records (Task 26); 14 localisation (every task; OQ-4 gating, Tasks 1, 3, 9, 12); 15 persistence (Task 2); 16 motion, focus, Escape, text floor, performance (Tasks 5, 6; signals read on Changed and TurnEnded only); 17 the slices (the slice table); 18 the defaults (Global Constraints); 20 risks (each has its task above). Spec 11.1's Dayan still is in Task 26 (the spec's S6); until then the popup draws no portrait for Dayan (`NoPortraitClass`, Task 5).
+- **Placeholder scan.** Code steps carry code. Three steps are content drafting from named sources rather than final text, by design, because the owner reviews every line and the native reviewer every Hebrew line: the 25 encyclopedia pages (Task 13: each page's rules and target are listed), the Hebrew wording of UI terms that must match existing strings (Tasks 18, 20 name which strings to read), and the route-specific production (Task 26, gated on a choice not yet made). The opening chain's port (Task 9) is a rename table over the existing file plus the tests that change in meaning, written out.
+- **Names.** `AdvisorCatalog` (`Message`, `Page`, `Act`, `Media`, `Known`, `Problems`, `Shipped`, `Find`, `FindPage`, `AdvisorOf`, `ApprovedIn`, `Teaching`, `Critical`), `AdvisorSettings` (`Level`, `LevelRank`, `SetLevel`, `Seen`, `MarkSeen`, `OpeningSeen`, `MarkOpeningSeen`, `HasFile`), `AdvisorQueue` (`Offer`, `Head`, `Position`, `Done`, `PutOff`, `Drop`, `Reset`, `History`, `PutOffIds`, `Concern`, `Disagreement`), `AdvisorLayout` (`Tier`, `Slot`, `Place`), `AdvisorSignals` (`Events`, `States`, `Measures`, `Names`, `When`, `Holding`), `AdvisorContext`, `AdvisorSession` (`Catalog`, `Settings`, `AutoShow`, `Queue`, `Fired`, `FiredTurn`, `Chain`, `Introduced`), `AdvisorHooks` (`Card`, `OpenScreen`, `ShowCity`, `ShowUnit`, `KeepSelection`, `MapTarget`, `CloseScreens`, `OpenPage`), `AdvisorPresenter` (`IsOpen`, `Shown`, `NewGame`, `Notice`, `GotIt`, `NotNow`, `Escape`, `Covered`, `Place`, `Slot`, `ShowTarget`, `ClearTarget`, `OpenChain`, `CloseChain`, `NextStep`, `InChain`, `ChainStep`, `ChainIds`, `EventStep`, `ShowNow`, `Media`, `Watch`, `CloseOverlay`, `ForceInline`), `AdvisorTargets`, `AdvisorQuotes`, `AdvisorMedia` (`IPicture`, `Play`, `Stop`, `Tick`, `Playing`, `Inline`, `Url`), `AdvisorCatalog.MediaFolder`, `ClipPicture`, `StillPicture`, `AdvisorCaptions.At`, `EncyclopediaPresenter.Open`, `CounselPresenter`, `Threats.CitiesAtRisk`, `Simulation.TurnEnd`, `SimBridge.RefusedForAttention`, `BudgetPresenter.UnsubmittedChanged` are used with the same signatures in every task.
+- **Review Focus.** Each of the five has its test in the owning task: 1 and 2 in Task 24, 3 in Tasks 7 and 9, 4 in Task 21, 5 in Tasks 8 (desktop) and 10 (the phone, through the ported map test).
+- **Assumptions the owner may overrule.** (a) OQ-4 read as: a pending Hebrew line never shows, and the slices that remove the guide and How to play merge only once their Hebrew is approved. (b) Critical warnings are never capped (spec 4.2's one-a-turn rule read as applying to teaching and non-critical warnings, so spec 6's "never silent on a real threat" holds). (c) The opening chain ignores the help level (it is the first game's onboarding, as the guide was) and uses turn one's teaching slot. (d) `debt_ratio_at_least: 0.8` and the disagreement's trigger (Arms out with an empty Treasury) are presentation values for the owner. (e) A message that teaches an existing chain topic (cities, training, moving a unit) is not repeated in S4: the chain and the encyclopedia teach it. (f) S4 follows S3, because its teaching messages open encyclopedia pages.
+- **Conflicts with open work.** #1493 (Defence screen) makes `Combat.TruceUntil` public; Task 20 uses it only if merged. The civ-movement plan edits `Simulation.cs` around `Step`; Task 15's change there is three lines, and whichever lands second merges them. #1143, #1135 and #1227 touch `Game.uxml` and `Statecraft.uss` in other blocks. #1489 and #1496 touch `ScreenNav.cs` and `GameRoot.cs`; Task 5's one line at the end of `DisableCovered` and Task 7's wiring are small enough to merge by hand.