From 9b67a780eba62f8354d738cb64901f8637f18e62 Mon Sep 17 00:00:00 2001
From: Quintine <15965533+Quintine@users.noreply.github.com>
Date: Sun, 20 Sep 2026 11:45:47 +1000
Subject: [PATCH] Connect early Juice of Sapho battle aggressor
During the existing public pre-plan opportunity, the holder can discard canonical unreserved Sapho to become aggressor before their readiness or any binding plan/Voice/inspection/Truthtrance commitment. Unchosen preparation prompts remain available. No new confirmation-only or holder-dependent response window is introduced. Later intervention and its allocation/privacy protocol remain unfinished.
A battle/turn/revision-bound history and independent event list preserve accepted priority while keeping attacker, defender and chooser stable. Legitimately recovered cards can change priority again at a fresh event. Reads, actions and normalization reject corrupt histories/custody. Shared tie priority respects Habbanya in either physical slot and reaches pre-commit Stone/Voice checks, public views, bot calculations and actual ordinary/Stone resolution. The final quote previously assumed original attacker priority and now consumes the validated aggressor. Harkonnen capture still follows actual winner/loser.
Owner controls, public aggressor/tie text, automatic notices and internal guidance are connected. Focused tests exercise actual tied results in Basic/Advanced, both Habbanya sides, mixed-force Stone finishability before opposing commitments, a real allied Prescience boundary, stale/late/cross-owner rejection, private rival noninterference, receipt corruption, saved recovered-card revision, actual policies at all four AI levels and authenticated SQLite races/seat restoration. Independent review found no material defect. A prior scheduling test now explicitly readies its human holder to save the card instead of allowing the new legal AI play.
Types, lint and 4866 offline tests, production build and 43 HTTP/session tests pass on the unchanged source fingerprint below. Two genuine CHOAM/Richese samples completed with 1279 accepted actions, 34 periodic JSON restores and no rejected candidates. One movement Sapho play occurred; neither sample used aggressor. Targeted tests and browser evidence, not those samples, establish the new effect. Full expansion and module acceptance remain incomplete.
In a new isolated browser room, genuine Advanced faction setup was followed by conserved battle staging. The human Guild used the actual aggressor button, restored the spent card and priority after refresh, readied, selected Master Bewt with zero dial/support, and declined a Traitor call. The staged Emperor opponent used real engine ready/plan/vote actions with Caid and zero dial/support. Guild won the 3-3 tie, retained four forces and 30 spice, and Emperor lost four forces. Final refresh and private JSON views restored the same outcome; the original seat row is unchanged. Screenshot capture timed out, so visual screenshot acceptance is not claimed.
All 1072 original games and original seat/recovery/entry/handover records are unchanged; 1106 rooms remain including isolated QA and HTTP fixtures. SQLite quick-check and foreign keys pass. The healthy server was reused without reset/restart or automation.
The Mirror audit now records why every genuine CHOAM/Richese setup includes unresolved copy candidates: an ordinary-copy-only gate would need hidden eligibility or altered inventory. Mirror stays gated pending the existing disposal ruling and copied-choice work. No mode/publication gate is opened.
Verified source tree: 2fb3160efd713a3f7068aedb474868ba6863bccc420848a56e69e1df1d84441b
---
components/game-table.tsx | 5 ++
components/juice-of-sapho.tsx | 18 +++--
components/residual-poison.tsx | 1 +
docs/CURRENT_STATUS.md | 39 +++++----
docs/IMPLEMENTATION_STATUS.md | 18 +++++
docs/JUICE_OF_SAPHO_RUNTIME.md | 7 +-
docs/MIRROR_WEAPON_ENGINE_AUDIT.md | 11 +++
docs/RULE_DECISIONS.md | 4 +-
docs/SAPHO_AGGRESSOR.md | 62 +++++++++++++++
docs/SAPHO_BATTLE_ORDER.md | 4 +
game/battle-resolution-quote.ts | 8 +-
game/card-presentation.ts | 4 +-
game/engine.ts | 58 ++++++++++++--
game/reference.ts | 11 ++-
game/sapho-aggressor.ts | 72 +++++++++++++++++
tests/fixture-sapho-aggressor.ts | 44 +++++++++++
tests/juice-of-sapho-bots.test.ts | 2 +-
tests/sapho-aggressor-recovery.test.ts | 37 +++++++++
tests/sapho-aggressor.test.ts | 92 ++++++++++++++++++++++
tests/sapho-battle-order-controls.test.tsx | 18 ++++-
tests/sapho-battle-order.test.ts | 3 +
21 files changed, 467 insertions(+), 51 deletions(-)
create mode 100644 docs/SAPHO_AGGRESSOR.md
create mode 100644 game/sapho-aggressor.ts
create mode 100644 tests/fixture-sapho-aggressor.ts
create mode 100644 tests/sapho-aggressor-recovery.test.ts
create mode 100644 tests/sapho-aggressor.test.ts
diff --git a/components/game-table.tsx b/components/game-table.tsx
index b05a8851..4ca147eb 100644
--- a/components/game-table.tsx
+++ b/components/game-table.tsx
@@ -4328,6 +4328,11 @@ export function GameTable({
{g.battle.locationName ?? combatName(g.battle.territory)}
Only the native faction may reveal Traitors or Face
diff --git a/components/juice-of-sapho.tsx b/components/juice-of-sapho.tsx
index 8730c57f..a231369b 100644
--- a/components/juice-of-sapho.tsx
+++ b/components/juice-of-sapho.tsx
@@ -23,9 +23,9 @@ function unavailableReason(game: GameView) {
return 'Movement order can change only before the current combined shipment and movement turn begins. First requires all remaining turns to be unstarted and the Advanced Guild to have finished or be absent. Completed turns stay completed. Already-held positions and committed cards are unavailable.';
if (game.phase === 6)
return game.battle
- ? 'Finish the current battle and its aftermath before changing the order of remaining battle choices. This does not change the current battle’s aggressor.'
+ ? 'Become aggressor only during your open pre-plan opportunity, before declaring ready or committing a plan. Already-held priority and committed cards are unavailable. Finish the current battle and its aftermath before changing remaining battle-choice order.'
: 'You need an unresolved battle and an available first or last position. Completed battles stay resolved, and a card committed elsewhere cannot be used.';
- return 'These controls support Once Around bidding, movement order and remaining battle-choice order. Battle aggressor and other phase or auction modes remain unfinished.';
+ return 'These controls support Once Around bidding, movement order, remaining battle-choice order and pre-plan aggressor. Later battle intervention and other phase or auction modes remain unfinished.';
}
export function JuiceOfSapho({
@@ -47,7 +47,7 @@ export function JuiceOfSapho({
return (
- Juice of Sapho: change turn order
+ Juice of Sapho: change order or become aggressor
- {once
+ {aggressor
+ ? 'Become this battle’s aggressor before plans. You win ordinary ties; a Habbanya Stronghold advantage still takes precedence. The participants and later battle choices stay unchanged.'
+ : once
? `Bid ${option.mode} in the current Once Around lot. Each eligible player still has only one bidding opportunity.`
: battle
? `Choose your remaining battles ${option.mode}. Completed battles stay resolved. This changes who chooses next, not the aggressor or tie advantage of a battle. Other players may still choose battles against you before your turn.`
@@ -78,8 +81,8 @@ export function JuiceOfSapho({
if (!busy) act({ type: 'card', card: card.id, ...option });
}}
>
- {once ? 'Bid' : battle ? 'Choose battles' : 'Take your movement turn'} {option.mode} and
- discard Juice of Sapho
+ {aggressor ? 'Become aggressor and discard Juice of Sapho' :
+ `${once ? 'Bid' : battle ? 'Choose battles' : 'Take your movement turn'} ${option.mode} and discard Juice of Sapho`}
);
@@ -90,8 +93,7 @@ export function JuiceOfSapho({
)}
- Battle aggressor and other phase or auction modes are still
- unfinished.
+ Later aggressor intervention and other phase or auction modes are still unfinished.
Both combatants have an opportunity to use available preparations before
either commits a leader. Continue when you are ready to choose leaders.
+ {' '}A held Juice of Sapho can make you aggressor during this opportunity.
{combatants.map((player) => (
diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md
index d43485ed..a5356002 100644
--- a/docs/CURRENT_STATUS.md
+++ b/docs/CURRENT_STATUS.md
@@ -6,12 +6,11 @@ gated.** Prototypes do not open completion or publication gates.
## Current checkpoint and work
-Latest delivered rules checkpoint: `62e87d2`, [Harass allocation](HARASS_ALLOCATION.md).
-Types, lint, **4,850 offline tests**, production build and 43 HTTP checks passed.
-Eight genuine card-variant games completed in 9,956 accepted actions with 266
-periodic save/restore checks and no rejected candidates. Focused and browser
-cases exercised ambiguous allocation. All 1,038 opening games and original
-seat/recovery records were unchanged; 1,072 rooms remained after isolated QA.
+Latest delivered checkpoint: `bfa24b0`, [optional table sounds](TABLE_SOUNDS.md).
+Types, lint, **4,856 offline tests** and production build passed. Browser controls
+verified mute, keyboard volume, refresh and cross-tab preferences; physical audio
+and screenshot acceptance remain open. All 1,072 games and original seat/recovery
+records were preserved, and the server remained healthy after the outage.
Earlier evidence remains in the [implementation history](IMPLEMENTATION_STATUS.md).
The connected [Harass & Withdraw prototype](HARASS_WITHDRAW_RUNTIME.md) supports either
@@ -24,22 +23,20 @@ card-specific discard precedence are explicitly labeled inferences. The Stone
Burner timing question is pending; no user answer is assumed. Reinforcements
remains unfinished. This does not open variant, mode or publication gates.
-Current checkpoint: [optional table sounds](TABLE_SOUNDS.md) connects local mute,
-volume, a test sample and short public phase/automatic-action cues. Initial and
-background updates stay silent; preferences survive refresh and synchronize
-between tabs. This adds no gameplay actions, private eligibility checks or game
-storage. Final source-bound checks and delivery are recorded in the private
-report and Git message; physical audio and screenshot acceptance remain open.
+Current checkpoint: [early Sapho aggressor](SAPHO_AGGRESSOR.md) connects the
+printed battle-priority effect during the existing shared pre-plan opportunity.
+Physical attacker/defender/chooser stay stable; Habbanya takes precedence in either
+slot. Shared priority feeds Stone admission, ordinary/Stone resolution, public
+controls and all four AI profiles. Battle-bound history survives private saved
+continuation. Later intervention remains unfinished; no new ruling is assumed.
+Final checks, samples, browser evidence and delivery belong to the source-bound
+private report and Git message.
-On 20 September, the stopped server was started after backing up all 1,072 rooms.
-Following another reported outage, the server responded normally and every saved
-game still matched that baseline. The isolated browser seat restored successfully.
-No database reset or recurring automation was needed.
-
-Next: prototype ordinary Mirror Weapon copies using the existing shared resolver,
-while retaining explicit gates for unresolved copied Tooth/Artillery disposal and
-Stone Burner choices. Sapho battle aggressor is the next independent candidate.
-The remaining Leader Skill bands retain their existing pending rulings.
+The [Mirror admission review](MIRROR_WEAPON_ENGINE_AUDIT.md) found that every genuine
+Richese setup contains the unresolved copied weapons. Ordinary-only activation
+cannot safely depend on hidden custody or alter the printed deck. Mirror remains
+gated pending the existing disposal ruling and copied-choice work. Continue with
+independent missing faction/card functions, then integrated play and refinement.
## Authoritative navigation
diff --git a/docs/IMPLEMENTATION_STATUS.md b/docs/IMPLEMENTATION_STATUS.md
index f86cb14a..4817815c 100644
--- a/docs/IMPLEMENTATION_STATUS.md
+++ b/docs/IMPLEMENTATION_STATUS.md
@@ -1,5 +1,23 @@
# Dune implementation status
+## 20 September 2026 — Sapho early battle aggressor
+
+[Early aggressor](SAPHO_AGGRESSOR.md) connects the held physical card, existing
+pre-plan opportunity, shared tie priority, controls, four AI profiles and private
+saved continuation. It preserves participant slots and chooser, respects Habbanya
+in either slot, and checks Stone finishability before commitments. Later battle
+intervention and its unresolved allocation/response protocol remain unfinished.
+Independent review found no material rules/privacy blocker after final integration.
+Focused engine/control/SQLite evidence is paired with final source-bound checks,
+browser/sample reports, preservation and verified Git delivery in the private
+checkpoint report and commit message. Public mode and publication gates stay closed.
+
+The Mirror admission audit supersedes its earlier ordinary-slice recommendation:
+every genuine CHOAM/Richese setup includes the unresolved copy candidates. A
+synthetic restricted deck, hidden eligibility gate or reveal-time rejection cannot
+establish playable full-game support. Existing user/source rulings remain pending.
+
+
## 20 September 2026 — Optional table sound prototype
[Table sound controls](TABLE_SOUNDS.md) add local mute, keyboard volume and a test
diff --git a/docs/JUICE_OF_SAPHO_RUNTIME.md b/docs/JUICE_OF_SAPHO_RUNTIME.md
index c7d5056b..535a1a6b 100644
--- a/docs/JUICE_OF_SAPHO_RUNTIME.md
+++ b/docs/JUICE_OF_SAPHO_RUNTIME.md
@@ -4,8 +4,9 @@ Updated 14 September 2026. **Partial card implementation; complete Richese/Advan
The [Battle-phase ordering prototype](SAPHO_BATTLE_ORDER.md) adds first/last
remaining battle choices. Its separate chooser, phase priority and saved-boundary
-contract supersede the earlier absence of that mode below. Aggressor remains
-unimplemented.
+contract supersede the earlier absence of that mode below. The
+[early aggressor prototype](SAPHO_AGGRESSOR.md) now uses the existing shared
+pre-plan opportunity; later aggressor intervention remains unfinished.
## Implemented contract
@@ -26,7 +27,7 @@ The [battle-order follow-up](SAPHO_BATTLE_ORDER.md) connects first/last at a cle
boundary between actual battles. It does not implement the separate aggressor
mode discussed below.
-Battle aggressor, normal/Black Market cyclic bidding, other ordered actions and partly completed movement remain unfinished. Once Around first after an already completed bid and first/Guild competing priority are guarded. Reacquiring and replaying Sapho while an existing movement protection remains is also guarded. Silent submission is simultaneous and receives no fabricated order or tie change.
+Later battle aggressor intervention, normal/Black Market cyclic bidding, other ordered actions and partly completed movement remain unfinished. Once Around first after an already completed bid and first/Guild competing priority are guarded. Reacquiring and replaying Sapho while an existing movement protection remains is also guarded. Silent submission is simultaneous and receives no fabricated order or tie change.
The battle audit in [the battle review](JUICE_OF_SAPHO_BATTLE_REVIEW.md) found a real Stone Burner counterexample: a plan admitted with original aggressor tie priority can become allocation-ambiguous after late Sapho. A complete implementation needs the actual allocation continuation (and a usable, possession-independent late intervention boundary), not rejection based on an opponent's hidden plan. No aggressor handler has been enabled around that defect.
diff --git a/docs/MIRROR_WEAPON_ENGINE_AUDIT.md b/docs/MIRROR_WEAPON_ENGINE_AUDIT.md
index 5070edf5..df956555 100644
--- a/docs/MIRROR_WEAPON_ENGINE_AUDIT.md
+++ b/docs/MIRROR_WEAPON_ENGINE_AUDIT.md
@@ -61,6 +61,17 @@ Portable Snooper is concurrently being integrated by the parent. Consume its fin
## Genuine unresolved boundaries and recommended scope
+**20 September admission review:** the ordinary-copy arithmetic remains useful,
+but cannot alone open a genuine setup. CHOAM's Treachery deck supplies Poison
+Tooth and Artillery even without Ix, while the full Richese cache supplies Stone
+Burner. A public configuration gate therefore cannot isolate ordinary copies.
+Rejecting according to a concealed opposing hand/plan would leak information;
+rejecting after commitments could strand the battle. Do not remove physical
+cards or manufacture a restricted deck to claim complete-game support. Mirror
+remains gated pending the existing copied-disposal ruling and copied-choice work.
+This qualifies the earlier ordinary-slice recommendation below; it does not
+invalidate the existing focused arithmetic evidence or answer the user question.
+
- **Copied compulsory disposal:** the FAQ names physical Tooth/Artillery, while Mirror copies a weapon. The retrieved primary sources do not explicitly say whether their disposal exception also applies to the physical Mirror. Separate combat effects from cleanup and obtain a ruling before certifying those pairings. This does not justify blocking ordinary projectile/poison/Lasgun/Poison Blade/selected-role copies.
- **Stone Burner foundation:** the full effect is presently unsupported. Basic undialed counts follow physical forces minus dialed losses; ties use ordinary aggressor priority unless overridden. Advanced mixed/support-dependent dials can permit different physical casualty allocations, which now affect who wins; the present engine chooses those only for an already determined winner. Stone's original choice and allocation timing must be implemented/audited before its copied form. This is an underlying special-outcome problem, not uncertainty over whether Mirror copies a valid weapon.
- **Higher modules:** inactive leader skills may modify attacks, defenses or card roles. No combined leader-skill certification follows from the matrix. Two physical Mirrors are outside the verified inventory rather than a normal supported interaction.
diff --git a/docs/RULE_DECISIONS.md b/docs/RULE_DECISIONS.md
index 68824263..0f702099 100644
--- a/docs/RULE_DECISIONS.md
+++ b/docs/RULE_DECISIONS.md
@@ -53,8 +53,8 @@ These are unresolved in the cited records. Do not infer an answer from elapsed t
| Harass / Stone Burner | A user question has been sent: keep the combination gated or compare forces remaining after withdrawal. No answer is assumed. The Richese card-family configuration is guarded publicly; hidden Stone Burner custody never controls eligibility. Ambiguous physical allocations and other optional modules remain unfinished. | [Current boundaries](HARASS_WITHDRAW_RUNTIME.md#current-boundaries) |
| Recruits late accounting and rates | A user question has been sent for two free plus one paid Atreides return before Recruits: keep the disputed case gated, or one/two further free returns without refund. No answer is assumed. Late-changing free rates, pending repricing and same-turn recovered-card replay also stay gated. The connected clean-case preview retains the independent seven-force cap after faction-advantage cancellation as an explicit inference, not a direct combined FAQ. | [Source audit](RECRUITS_RULES.md), [runtime scope](RECRUITS_RUNTIME.md) |
| Ambassador/Terror arrival priority | Both optionally react to the same entry, but no publisher/designer priority was found. The order can change Fremen relocation versus Atomics losses. A user question has been sent: keep the overlap gated pending an official ruling, or use explicitly provisional storm order. No answer is assumed; Baliset remains a separate pre-entry prevention effect. | [Reproduction and source boundary](DEFERRED_MOVEMENT_ARRIVAL.md) |
-| Sapho remaining timing | First versus unspent Advanced Guild priority, partly completed combined turns, cyclic auction duration and remaining battle timing stay guarded. Prior questions remain unanswered. | [Source audit](JUICE_OF_SAPHO_SOURCE_UPDATE.md), [battle review](JUICE_OF_SAPHO_BATTLE_REVIEW.md) |
-| Mirror Weapon | Whether copied Tooth/Artillery mandatory-discard rules attach to the physical Mirror remains unanswered; arithmetic helpers do not admit the full battle card. | [Engine audit](MIRROR_WEAPON_ENGINE_AUDIT.md) |
+| Sapho remaining timing | First versus unspent Advanced Guild priority, partly completed combined turns, cyclic auction duration and later battle timing stay guarded. The existing pre-plan opportunity supports [early aggressor](SAPHO_AGGRESSOR.md). Prior questions remain unanswered. | [Source audit](JUICE_OF_SAPHO_SOURCE_UPDATE.md), [battle review](JUICE_OF_SAPHO_BATTLE_REVIEW.md) |
+| Mirror Weapon | Whether copied Tooth/Artillery mandatory-discard rules attach to the physical Mirror remains unanswered. Every genuine Richese setup includes those cards and Stone Burner; an ordinary-copy-only admission gate cannot depend on concealed custody or alter the printed deck. | [Engine audit](MIRROR_WEAPON_ENGINE_AUDIT.md) |
| Semuta Drug | Full-hand take-before-discard and the privacy-neutral immediate reaction protocol remain unresolved. Typed discard continuations already exist; they are not activation. | [Source update](SEMUTA_SOURCE_UPDATE_20260907.md), [privacy review](SEMUTA_PRIVACY_REVIEW.md) |
| Leader Skills edge cases | Capture/replacement eligibility, Banker escrow custody (user question sent), Smuggler survival settlement, Mentat empty-hand fallback (private historical observations persist after death), Diplomat lower retreat ordering, modified-defense inheritance and remaining simultaneous optional timing need resolution before those cases are enabled. These are recorded source gaps, not answered user rulings. | [Material boundaries](LEADER_SKILLS_RULES.md#material-boundaries-not-settled-by-the-sources), [Diplomat boundary](DIPLOMAT_DEFENSE.md#evidence-and-remaining-scope) |
| Suk Graduate / Atreides | Whether rescued dialed casualties count toward the seven-loss Kwisatz Haderach threshold remains unresolved. The user question has been sent; Advanced Atreides rescue stays guarded. | [Source and runtime boundary](SUK_GRADUATE_RULES.md) |
diff --git a/docs/SAPHO_AGGRESSOR.md b/docs/SAPHO_AGGRESSOR.md
new file mode 100644
index 00000000..130b5c8d
--- /dev/null
+++ b/docs/SAPHO_AGGRESSOR.md
@@ -0,0 +1,62 @@
+# Juice of Sapho: early battle aggressor
+
+20 September 2026. Connected partial prototype. The physical face and source
+precedence remain in the [Sapho audit](JUICE_OF_SAPHO_ENGINE_AUDIT.md); the
+[battle review](JUICE_OF_SAPHO_BATTLE_REVIEW.md) separates scheduling, physical
+participants and tie priority. This checkpoint implements the printed aggressor
+effect during an existing opportunity. It does not adjudicate late timing.
+
+## Connected behavior
+
+The holder can play the canonical, unreserved card while their shared `preLeader`
+opportunity is open, before their readiness declaration and before either plan.
+The other combatant may already be ready. Actual Voice, Prescience, Nexus/full-plan
+inspection and Truthtrance commitments prevent this early use, as do suspended
+interactions and mandatory disposal. Unchosen preparation prompts bind no plan
+content and may remain. No hidden opposing hand or selected plan determines
+eligibility. No holder-only pause or new confirmation window is introduced.
+
+`scope:'battleAggressor', mode:'aggressor'` binds the battle, turn and use revision.
+It discards the physical card once and records public priority, without swapping
+attacker/defender slots, chooser, forces, leaders or later battle scheduling.
+An already held position is unavailable. A recovered card can change priority
+again at a fresh opportunity; no extra once-per-battle limit is invented.
+
+The validated use history and independent event list survive JSON continuation.
+Reads, actions and automatic normalization reject mismatched history, event,
+combatants, turn or physical card custody. Legacy battles retain their original
+attacker priority and do not reopen closed preparation.
+
+The shared tie helper checks both combatants for the effective Habbanya advantage
+before falling back to aggressor. Engine plan/Voice/prescience checks, public
+projections, AI calculations and the final battle quote use that priority.
+Ordinary strength ties and Stone Burner's physical-token ties therefore agree.
+Early use precedes all commitments, so Stone's existing public finishability
+guard can evaluate the changed priority before accepting a plan. The unresolved
+late mixed-allocation hazard from the battle review is not bypassed.
+
+The hand panel exposes the real action, the table names aggressor and tie winner,
+and automatic notices mark a successful use. All four AI profiles can use the
+same private options and finish through the existing preparation and battle path.
+Timing strategy and complete Richese-game acceptance remain later work.
+
+## Evidence and limits
+
+Focused tests cover actual ordinary/Stone outcomes in Basic and Advanced,
+Habbanya on either physical side, rejected stale/late/cross-owner submissions,
+unchanged rejected input, public eligibility with changed private rival holdings,
+receipt corruption, conserved recovered-card reuse and all four AI continuations.
+The mixed Emperor/Guild regression changes Stone's pre-commit finishability before
+any hidden opposing plan exists. Authenticated in-memory SQLite races consume one
+card; fresh stores restore each private seat through the same battle. Fixtures use
+genuine CHOAM/Richese setup followed by explicit conserved board/hand staging;
+they are not full genuine-game evidence or proof of every module combination.
+
+The owner-only control and public table text have rendering regressions. Browser,
+required checks, complete-game samples, preservation and verified Git evidence
+belong to the source-bound checkpoint report and commit message.
+
+Later pre-reveal, post-reveal and final-intervention opportunities remain
+unfinished, including their privacy-neutral response protocol and Stone allocation
+work. These are development boundaries, not extra printed prohibitions. Other
+Sapho timing questions and all mode/publication gates remain unchanged.
diff --git a/docs/SAPHO_BATTLE_ORDER.md b/docs/SAPHO_BATTLE_ORDER.md
index 3e88d8aa..eb1fd26f 100644
--- a/docs/SAPHO_BATTLE_ORDER.md
+++ b/docs/SAPHO_BATTLE_ORDER.md
@@ -27,6 +27,10 @@ Burner allocation work. No new confirmation-only window is introduced here.
## Connected behavior
+20 September follow-up: [early aggressor](SAPHO_AGGRESSOR.md) now connects the
+separate pre-plan effect. References below to unavailable intervention concern
+later or suspended battle timing; chooser ordering retains the contract here.
+
The existing Richese development configuration supplies the physical card. Its
holder receives private `battleOrder` first/last options at a clean boundary.
The command binds the current opportunity and discards the exact unreserved card
diff --git a/game/battle-resolution-quote.ts b/game/battle-resolution-quote.ts
index bcd3188c..78083e82 100644
--- a/game/battle-resolution-quote.ts
+++ b/game/battle-resolution-quote.ts
@@ -28,6 +28,7 @@ import {
type StoneBurnerComparison,
} from './stone-burner';
import { matchingTraitor } from './traitors';
+import { battleTieOwner } from './sapho-aggressor';
import { HARASS_WITHDRAW_CARD, isHarassWithdraw, quoteHarassWithdraw, type HarassWithdrawContext, type HarassWithdrawQuote, type HarassWithdrawSelection } from './harass-withdraw';
import { auditCount } from './choam-auditor';
import { sukGraduateSkill, type SukGraduateSkill } from './suk-graduate';
@@ -96,6 +97,8 @@ export type ResolutionCombatant = ResolutionParticipant & {
aid?: { donor: string; amount: number };
};
export type BattleResolutionInput = {
+ /** Stable physical slots remain unchanged when Sapho changes aggressor. */
+ aggressor?: string;
advanced: boolean;
/** Preserve physical counter choices in Basic Homeworlds without granting Advanced strength. */
typedCasualties?: boolean;
@@ -383,8 +386,9 @@ function calculate(input: BattleResolutionInput): BattleResolutionQuote {
withdrawals.set(side.id, quoteHarassWithdraw(side.harassWithdraw, side.plan.dial, side.plan.support, side.harassSelection));
}
}
- const tie =
- d.stronghold === 'habbanya_ridge_sietch' ? 'defender' : 'attacker';
+ const tie = battleTieOwner(a.id, d.id, input.aggressor ?? a.id,
+ [a, d].filter(side => side.stronghold === 'habbanya_ridge_sietch').map(side => side.id)) === a.id
+ ? 'attacker' : 'defender';
const stone =
isStoneBurner(aw) || isStoneBurner(dw)
? stoneBurnerComparison(
diff --git a/game/card-presentation.ts b/game/card-presentation.ts
index c1c604ac..951f0af7 100644
--- a/game/card-presentation.ts
+++ b/game/card-presentation.ts
@@ -34,7 +34,7 @@ export function richeseCardActionBlock(card: VisibleCard): string | null {
if (definition?.card.effect === 'nullentropyBox')
return 'Use the Nullentropy Box panel to pay for a private search.';
if (definition?.card.effect === 'juiceOfSapho')
- return 'Use the Juice of Sapho panel to choose an available Once Around, movement or battle-choice order change.';
+ return 'Use the Juice of Sapho panel to choose an available order change or become battle aggressor before plans.';
if (definition?.card.effect === 'distrans')
return 'Choose a recipient and card in the Distrans transfer panel.';
return definition && definition.card.effect !== 'karama'
@@ -86,7 +86,7 @@ export function cardPresentation(card: VisibleCard): CardPresentation {
gameplay: richese.gameplay,
availability:
richese.card.effect === 'juiceOfSapho'
- ? 'Richese effect integration and verification are incomplete. Supported controls cover Once Around first before bidding begins, Once Around last before your bid, and bounded movement order changes. Battle aggressor and other phase or auction modes remain unfinished; expansion starts remain disabled.'
+ ? 'Richese effect integration and verification are incomplete. Supported controls cover Once Around first before bidding begins, Once Around last before your bid, bounded movement and battle-choice ordering, and aggressor during the shared pre-plan opportunity. Later aggressor intervention and other phase or auction modes remain unfinished; expansion starts remain disabled.'
: richese.card.effect === 'stoneBurner'
? 'Stone Burner has development battle controls. Combined allocation timing and Ix timing remain guarded; full expansion starts stay disabled.'
: 'Richese effect integration and verification are incomplete. Karama, Distrans, Nullentropy Box, Ornithopter, Residual Poison, Portable Snooper and Stone Burner have card handlers in development fixtures; full expansion starts remain disabled.',
diff --git a/game/engine.ts b/game/engine.ts
index 0876a795..35fed59f 100644
--- a/game/engine.ts
+++ b/game/engine.ts
@@ -59,6 +59,7 @@ import { homeworldAllianceBlock } from './homeworld-alliance';
import { quoteHomeworldSubstitution } from './homeworld-substitution';
import { combatArmy, combatLocations, combatLocationName, homeworldBattleLocation, quoteCombatBoard, quoteCombatBoardContinuation } from './combat-location';
import { battleChooserEvent, quoteBattleChoosers, reorderBattleChoosers, validateBattleChooserOrder, BattleChooserOrderError, type BattleChooserOrder } from './battle-chooser-order';
+import { battleTieOwner, changeSaphoAggressor, saphoAggressorEvent, validateSaphoAggressor, SaphoAggressorError, type SaphoAggressorState } from './sapho-aggressor';
import { quoteHomeworldCombatLoss } from './homeworld-combat-loss';
import { quoteHomeworldBattleRules } from './homeworld-battle-rules';
import type { HomeworldForces } from './homeworld-custody';
@@ -618,6 +619,8 @@ export type Battle = {
/** Scheduling owner; physical combat slots and aggressor remain independent. */
chooser?: string;
chooserEvent?: string;
+ saphoAggressor?: SaphoAggressorState;
+ saphoAggressorEvents?: string[];
/** Only newly created supported battles enter the pre-plan Mentat question. */
mentatQuestionVersion?: 1;
mentatQuestionEvent?: string;
@@ -7340,9 +7343,28 @@ function battleSupportBudget(g: Game, p: Player) {
}
function battleTieWinner(g: Game) {
const b = g.battle!;
- return strongholdEffect(g, b.defender) === 'habbanya_ridge_sietch'
- ? b.defender
- : b.attacker;
+ const owners = [b.attacker, b.defender].filter(id => strongholdEffect(g, id) === 'habbanya_ridge_sietch');
+ return saphoAggressorRule(() => battleTieOwner(b.attacker, b.defender, battleAggressor(g), owners));
+}
+function saphoAggressorRule(calculate: () => T): T {
+ try { return calculate(); }
+ catch (error) { if (error instanceof SaphoAggressorError) throw new RuleError(error.message); throw error; }
+}
+function battleAggressor(g: Game) {
+ const b = g.battle!;
+ return saphoAggressorRule(() => validateSaphoAggressor(b.saphoAggressor, b.saphoAggressorEvents, b, g.turn));
+}
+function saphoAggressorIntegrity(g: Game) {
+ const b = g.battle;
+ if (!b) return;
+ battleAggressor(g);
+ if (!b.saphoAggressor) return;
+ requireRule(g.status === 'playing' && g.phase === 6 && b.preLeader?.event === b.event &&
+ g.players.some(p => p.id === b.attacker) && g.players.some(p => p.id === b.defender),
+ 'The saved Sapho aggressor needs its original battle preparation.');
+ const cards = physicalTreacheryCards(g).filter(card => card.id === 'richese-juice-of-sapho');
+ requireRule(cards.length === 1 && richeseCardDefinition(cards[0])?.card.effect === 'juiceOfSapho',
+ 'The played Sapho aggressor card has lost its unique physical custody.');
}
function strongholdCopyChoices(g: Game, player: string): StrongholdId[] {
const controllers = strongholdControllers(
@@ -12143,7 +12165,7 @@ type SaphoOption = {
scope: 'onceAround' | 'movement' | 'battleOrder';
event: string;
mode: 'first' | 'last';
-};
+} | { scope: 'battleAggressor'; event: string; mode: 'aggressor' };
function saphoMovementIntegrity(g: Game) {
const last = g.saphoMovementLast;
if (last === undefined || last === null) return;
@@ -12245,6 +12267,15 @@ function saphoOptions(g: Game, p: Player): SaphoOption[] {
)
return [];
const options: SaphoOption[] = [];
+ const battle = g.battle;
+ if (g.phase === 6 && battle?.event && battle.preLeader?.event === battle.event &&
+ !battle.preLeader.closed && !battle.preLeader.ready.includes(p.id) &&
+ !battle.revealed && Object.keys(battle.plans).length === 0 &&
+ !battle.voice && !battle.prescience && !battle.fullPlan && !battle.nexusInspection && !battle.truthPromises?.length &&
+ !g.pendingTreacheryDiscard && [battle.attacker, battle.defender].includes(p.id) &&
+ battleAggressor(g) !== p.id)
+ options.push({scope: 'battleAggressor',
+ event: saphoAggressorEvent(battle.event, g.turn, battle.saphoAggressor?.uses.length ?? 0), mode: 'aggressor'});
if (saphoBattleBoundary(g)) {
const order = projectedBattleOrder(g)!;
if (order.remaining.includes(p.id)) {
@@ -12293,7 +12324,7 @@ function playSapho(g: Game, p: Player, action: Action) {
Object.keys(action).every((key) =>
['type', 'card', 'scope', 'event', 'mode'].includes(key),
),
- 'Choose only Juice of Sapho, one supported scope, its event and first or last.',
+ 'Choose only Juice of Sapho, one supported scope, its event and an available mode.',
);
const option = saphoOptions(g, p).find(
(choice) =>
@@ -12305,7 +12336,16 @@ function playSapho(g: Game, p: Player, action: Action) {
option,
'This Juice of Sapho opportunity is unavailable, already completed or expired.',
);
- if (option.scope === 'onceAround') {
+ if (option.scope === 'battleAggressor') {
+ const b = g.battle!;
+ const next = saphoAggressorRule(() => changeSaphoAggressor(b.saphoAggressor,
+ b.saphoAggressorEvents, b, g.turn, p.id, option.event));
+ discard(g, p, 'richese-juice-of-sapho');
+ b.saphoAggressor = next;
+ (b.saphoAggressorEvents ??= []).push(option.event);
+ log(g, `${p.name} discarded Juice of Sapho to become this battle’s aggressor before plans. They now win ordinary ties; a Habbanya Stronghold advantage still takes precedence. Battle participants and later battle choices stay unchanged.`,
+ {faction: p.faction, name: 'Juice of Sapho'});
+ } else if (option.scope === 'onceAround') {
const lot = g.richeseAuction!;
// Discarding this card frees a slot even when a full hand excluded its holder
// at opening. Only this still-open finite lot gains that unacted bidder.
@@ -14247,6 +14287,7 @@ function gholaOptions(g: Game, p: Player) {
}
function marketGholaIntegrity(g: Game) {
battleOrderIntegrity(g);
+ saphoAggressorIntegrity(g);
nexusCardsIntegrity(g);
nexusEmperorSecretIntegrity(g);
nexusTraitorIntegrity(g);
@@ -15443,6 +15484,7 @@ function currentBattleResolutionQuote(g: Game, canceledVoter?: string) {
try {
const quote = quoteBattleResolution({
advanced: g.advanced,
+ aggressor: battleAggressor(g),
typedCasualties: !!g.homeworlds,
...(homeworldBattleLocation(g, b.territory) ? { homeworld: currentHomeworldBattleRules(g, b.territory)! } : {}),
turn: g.turn,
@@ -15688,7 +15730,7 @@ function resolveBattle(g: Game) {
log(
g,
stoneResult
- ? `${faction(winner!.faction).name} won in ${combatLocationName(g, b.territory)} by Stone Burner’s undialed physical tokens (aggressor ${stoneResult.attacker.join(' or ')}, defender ${stoneResult.defender.join(' or ')}; ${strongholdEffect(g, battleTieWinner(g)) === 'habbanya_ridge_sietch' ? 'Habbanya Stronghold advantage wins ties' : 'aggressor wins ties'}). Leader strength and Kwisatz Haderach’s bonus do not affect this comparison; the winner loses its dialed forces normally.`
+ ? `${faction(winner!.faction).name} won in ${combatLocationName(g, b.territory)} by Stone Burner’s undialed physical tokens (${a.name} ${stoneResult.attacker.join(' or ')}, ${d.name} ${stoneResult.defender.join(' or ')}; ${strongholdEffect(g, battleTieWinner(g)) === 'habbanya_ridge_sietch' ? 'Habbanya Stronghold advantage wins ties' : 'aggressor wins ties'}). Leader strength and Kwisatz Haderach’s bonus do not affect this comparison; the winner loses its dialed forces normally.`
: `${faction(winner!.faction).name} won in ${combatLocationName(g, b.territory)} (${av}–${dv}${av === dv ? (strongholdEffect(g, winner!.id) === 'habbanya_ridge_sietch' ? ', Habbanya Stronghold advantage wins ties' : ', aggressor wins ties') : ''}).`,
stoneResult
? { faction: (isStoneBurner(aw) ? a : d).faction, name: 'Stone Burner' }
@@ -20410,6 +20452,7 @@ export function applyAction(state: Game, id: string, action: Action): Game {
ornithopterIntegrity(g);
lateDefenseIntegrity(g);
stoneBurnerIntegrity(g);
+ saphoAggressorIntegrity(g);
strongholdIntegrity(g);
auditorIntegrity(g);
if (g.pendingNullentropy) {
@@ -25125,6 +25168,7 @@ export function viewGame(state: Game, id: string) {
preLeader: b.preLeader ?? null,
territory: b.territory,
attacker: b.attacker,
+ aggressor: battleAggressor(g),
chooser: b.chooser ?? b.attacker,
defender: b.defender,
revealed: b.revealed,
diff --git a/game/reference.ts b/game/reference.ts
index 0e2148d1..26139079 100644
--- a/game/reference.ts
+++ b/game/reference.ts
@@ -352,15 +352,16 @@ export const RULE_TOPICS: RuleTopic[] = [
coverage: 'Partial',
developmentStage: 'Prototyped',
summary:
- 'Choose an available first or last position in Once Around bidding, movement or remaining battle choices, then discard Sapho. Battle aggressor and other timing modes remain unfinished.',
+ 'Choose an available order change or become battle aggressor before plans, then discard Sapho. Later intervention and other timing modes remain unfinished.',
steps: [
'In a current Once Around auction, first is available before anyone bids. Last is available before your own bid, including after Richese. You still get only one bidding opportunity and must outbid the current high bid to win.',
'Discarding Sapho frees a hand slot. A full-hand holder can join a still-open lot through this order change. A completed bid or pass cannot be repeated, and a finished lot cannot reopen.',
'The movement controls change complete shipment and movement turns at a boundary before the current player begins. First moves you ahead of the remaining unstarted turns, including after earlier players have fully finished. In Advanced, the Guild must have finished or be absent. Last stays after the Guild even if the Guild later chooses to wait.',
'Between completed battles, choose first or last among remaining battle choosers. The priority lasts for the rest of the Battle phase. You still need a real unresolved battle. Others may choose battles against you before your own turn; last is not immunity. This scope changes the chooser, not each battle’s aggressor or tie advantage.',
+ 'During your open pre-plan preparation, use Sapho to become the current battle’s aggressor before declaring ready. You win ordinary ties, while the Habbanya Stronghold advantage still takes precedence. Physical participants, plans and later battle-choice order do not swap. The accepted priority survives refresh.',
'Finish existing shipment, movement, card preparation and pending decisions before changing order. Your hand panel lists only currently available choices. A reserved card or a position you already hold cannot be selected.',
'Completed bids and turns stay completed. Storm order, committed funding and movement counters do not reset. Refreshing preserves the same remaining opportunities and any declared last position.',
- 'These are the supported development controls, not additional printed restrictions. Battle aggressor, ordinary cyclic auction scope, other phase ordering and intervention during a partly completed combined turn remain unfinished. Silent bids are simultaneous; their storm-order tie rule is unchanged.',
+ 'These are the supported development controls, not additional printed restrictions. Later aggressor intervention, ordinary cyclic auction scope, other phase ordering and intervention during a partly completed combined turn remain unfinished. Silent bids are simultaneous; their storm-order tie rule is unchanged.',
],
example:
'Atreides bids 2. Before taking its bid, the Emperor uses Sapho to go last. Richese bids 3, then the Emperor must bid at least 4 to win. Atreides does not receive another bid.',
@@ -381,7 +382,7 @@ export const RULE_TOPICS: RuleTopic[] = [
area: 'Player controls',
status: 'Partial',
detail:
- 'Owner-only first/last actions, public remaining battle order, owner-relative battle targets, readable inspector and timing explanations. No aggressor or cyclic-auction controls yet.',
+ 'Owner-only first/last and pre-plan aggressor actions, public aggressor/tie priority and remaining battle order, owner-relative targets, readable inspector and timing explanations. Later aggressor and cyclic-auction controls remain unfinished.',
},
{
area: 'AI',
@@ -411,6 +412,8 @@ export const RULE_TOPICS: RuleTopic[] = [
'tests/sapho-battle-order-bots.test.ts',
'tests/sapho-battle-order-controls.test.tsx',
'tests/sapho-battle-order-recovery.test.ts',
+ 'tests/sapho-aggressor.test.ts',
+ 'tests/sapho-aggressor-recovery.test.ts',
],
},
],
@@ -1007,7 +1010,7 @@ export const RULE_TOPICS: RuleTopic[] = [
steps: [
...definition.gameplay,
definition.card.effect === 'juiceOfSapho'
- ? 'Use the Juice of Sapho panel for an available first or last Once Around or movement position. Battle aggressor and other timing modes remain unfinished; consult the timing guide.'
+ ? 'Use the Juice of Sapho panel for an available order change or pre-plan aggressor. Later intervention and other timing modes remain unfinished; consult the timing guide.'
: definition.card.effect === 'karama'
? 'This physical Karama uses the existing generic handler in development fixtures. Full Richese starts and complete interaction verification remain unavailable.'
: definition.card.effect === 'distrans'
diff --git a/game/sapho-aggressor.ts b/game/sapho-aggressor.ts
new file mode 100644
index 00000000..fb3f9ddd
--- /dev/null
+++ b/game/sapho-aggressor.ts
@@ -0,0 +1,72 @@
+export type SaphoAggressorUse = { event: string; player: string };
+export type SaphoAggressorState = {
+ version: 1;
+ battle: string;
+ turn: number;
+ attacker: string;
+ defender: string;
+ uses: SaphoAggressorUse[];
+};
+type BattleIdentity = { event?: string; attacker: string; defender: string };
+export class SaphoAggressorError extends Error {}
+function check(value: unknown, message: string): asserts value {
+ if (!value) throw new SaphoAggressorError(message);
+}
+/** Habbanya's printed exception applies to either stable combat slot. */
+export function battleTieOwner(attacker: string, defender: string, aggressor: string,
+ habbanyaOwners: readonly string[]): string {
+ check(attacker !== defender && [attacker, defender].includes(aggressor) &&
+ habbanyaOwners.length <= 1 && habbanyaOwners.every(id => [attacker, defender].includes(id)),
+ 'The battle tie priority needs distinct combatants and at most one Habbanya owner.');
+ return habbanyaOwners[0] ?? aggressor;
+}
+export function saphoAggressorEvent(battle: string, turn: number, revision: number) {
+ return `saphoAggressor:${JSON.stringify([battle, turn, revision])}`;
+}
+/** Preserve physical slots. Only explicit, battle-bound uses change tie priority. */
+export function validateSaphoAggressor(
+ state: SaphoAggressorState | undefined,
+ events: readonly string[] | undefined,
+ battle: BattleIdentity,
+ turn: number,
+): string {
+ check(!!state === !!events, 'The saved Sapho aggressor needs its independent use events.');
+ if (!state) return battle.attacker;
+ check(state && typeof state === 'object' && !Array.isArray(state) &&
+ Object.keys(state).sort().join(',') === 'attacker,battle,defender,turn,uses,version' &&
+ state.version === 1 && state.battle === battle.event &&
+ typeof state.battle === 'string' && state.battle.length > 0 &&
+ Number.isSafeInteger(turn) && turn >= 1 && state.turn === turn &&
+ state.attacker === battle.attacker && state.defender === battle.defender &&
+ typeof state.attacker === 'string' && state.attacker.length > 0 &&
+ typeof state.defender === 'string' && state.defender.length > 0 &&
+ state.attacker !== state.defender && Array.isArray(state.uses) && state.uses.length > 0 &&
+ Array.isArray(events) && events.length === state.uses.length,
+ 'The saved Sapho aggressor does not match this battle.');
+ let aggressor = state.attacker;
+ for (const [index, use] of state.uses.entries()) {
+ check(use && typeof use === 'object' && !Array.isArray(use) &&
+ Object.keys(use).sort().join(',') === 'event,player' &&
+ use.event === saphoAggressorEvent(state.battle, turn, index) && events[index] === use.event &&
+ [state.attacker, state.defender].includes(use.player) && use.player !== aggressor,
+ 'The saved Sapho aggressor use is stale or invalid.');
+ aggressor = use.player;
+ }
+ return aggressor;
+}
+export function changeSaphoAggressor(
+ state: SaphoAggressorState | undefined,
+ events: readonly string[] | undefined,
+ battle: BattleIdentity,
+ turn: number,
+ player: string,
+ event: string,
+): SaphoAggressorState {
+ const aggressor = validateSaphoAggressor(state, events, battle, turn);
+ check(typeof battle.event === 'string' && battle.event.length > 0 &&
+ [battle.attacker, battle.defender].includes(player) && player !== aggressor &&
+ event === saphoAggressorEvent(battle.event, turn, state?.uses.length ?? 0),
+ 'This Sapho aggressor opportunity is unavailable or expired.');
+ return { version: 1, battle: battle.event, turn, attacker: battle.attacker,
+ defender: battle.defender, uses: [...(state?.uses ?? []), { event, player }] };
+}
diff --git a/tests/fixture-sapho-aggressor.ts b/tests/fixture-sapho-aggressor.ts
new file mode 100644
index 00000000..2448fa07
--- /dev/null
+++ b/tests/fixture-sapho-aggressor.ts
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict';
+import {applyAction, viewGame, type Game, type Action} from '../game/engine';
+import {saphoBattleOrderGame, chooseSaphoBattleAction, resolveSaphoBattle, SAPHO_BATTLE_CARD} from './fixture-sapho-battle-order';
+export function saphoAggressorGame(options: Parameters[0] = {}, configure?: (game: Game) => void) {
+ const game = saphoBattleOrderGame({holder:'b',geometry:'separate',...options});
+ configure?.(game);
+ const choice = chooseSaphoBattleAction(game);
+ let opened = applyAction(game,choice.player,choice.action);
+ if(opened.decision?.kind==='fullPlanOffer') opened=applyAction(opened,opened.decision.player,{type:'decision',decline:true});
+ return opened;
+}
+export function aggressorAction(game: Game, owner = game.battle!.defender): Action {
+ const option = viewGame(game,owner).saphoOptions.find(o=>o.scope==='battleAggressor');
+ assert.ok(option,'The owner must have a real pre-plan aggressor action.');
+ return {type:'card',card:SAPHO_BATTLE_CARD,...option};
+}
+export function prepareAggressorPlans(state: Game) {
+ let g=state;
+ for(const id of [g.battle!.attacker,g.battle!.defender])
+ if(!g.battle!.preLeader!.ready.includes(id))
+ g=applyAction(g,id,{type:'battlePreparationReady',event:g.battle!.event});
+ while(g.battle?.preparation)
+ g=applyAction(g,g.battle.preparation.owner,{type:'declineBattlePower'});
+ if(g.decision?.kind==='fullPlanOffer') g=applyAction(g,g.decision.player,{type:'decision',decline:true});
+ assert.equal(g.decision,null); assert.equal(g.response,null);
+ return g;
+}
+export function revealEqualAggressorPlans(state: Game, stoneOwner?: string) {
+ let g=prepareAggressorPlans(state);
+ for(const id of [g.battle!.attacker,g.battle!.defender]) {
+ const leader=g.players.find(p=>p.id===id)!.leaders.find(l=>l.strength===3&&!l.dead)!;
+ assert.ok(leader);
+ g=applyAction(g,id,{type:'battlePlan',leader:leader.id,dial:0,support:0,
+ ...(id===stoneOwner?{weapon:'richese-stone-burner'}:{})});
+ }
+ if(stoneOwner) g=applyAction(g,stoneOwner,{type:'decision',event:g.battle!.event,mode:'ignore'});
+ return g;
+}
+export function finishAggressorBattle(state: Game) {
+ let g=state;
+ const combatants=[g.battle!.attacker,g.battle!.defender];
+ for(const id of combatants) g=applyAction(g,id,{type:'traitorCall',call:false});
+ return g.battle?resolveSaphoBattle(g):g;
+}
diff --git a/tests/juice-of-sapho-bots.test.ts b/tests/juice-of-sapho-bots.test.ts
index bdcdf016..e49bc103 100644
--- a/tests/juice-of-sapho-bots.test.ts
+++ b/tests/juice-of-sapho-bots.test.ts
@@ -218,7 +218,7 @@ void test('Sapho presentation directs players to the bounded controls and explic
assert.match(richeseCardActionBlock(card)!, /Juice of Sapho panel/);
const presentation = cardPresentation(card);
assert.match(presentation.availability!, /Once Around first/);
- assert.match(presentation.availability!, /Battle aggressor.*unfinished/);
+ assert.match(presentation.availability!, /Later aggressor intervention.*unfinished/);
assert.match(presentation.gameplay!.join(' '), /Discard Juice of Sapho/);
assert.equal(richeseCardActionBlock({ ...card, id: 'forged' }), null);
});
diff --git a/tests/sapho-aggressor-recovery.test.ts b/tests/sapho-aggressor-recovery.test.ts
new file mode 100644
index 00000000..0dd30a55
--- /dev/null
+++ b/tests/sapho-aggressor-recovery.test.ts
@@ -0,0 +1,37 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {viewGame,type Game} from '../game/engine';
+import {unitStore} from './fixture-nexus-room-store';
+import {saphoAggressorGame,aggressorAction} from './fixture-sapho-aggressor';
+import {nextSaphoBattleAction,saphoBattleCustody,SAPHO_BATTLE_CARD} from './fixture-sapho-battle-order';
+const clock={now:()=>87000,sleep:async()=>{}};
+for(const advanced of [false,true]) void test(`authenticated ${advanced?'Advanced':'Basic'} aggressor races once, reconnects privately and completes the same battle`,async t=>{
+ const f=unitStore();t.after(()=>f.sqlite.close());
+ const made=await f.rooms.createRoom('Aggressor recovery','emperor',advanced,['choam']);const code=made.view.code;
+ const tokens=[made.token,(await f.rooms.joinRoom(code,'Guild','guild')).token!,
+ (await f.rooms.joinRoom(code,'Atreides','atreides')).token!, (await f.rooms.joinRoom(code,'Richese','richese')).token!];
+ const auths=await Promise.all(tokens.map(token=>f.rooms.authenticate(code,token)));
+ const ids=auths.map(a=>a.playerId) as [string,string,string,string];
+ let game=saphoAggressorGame({advanced,seatIds:ids,holder:ids[1]});game.code=code;
+ game.version=(await f.rooms.readRoom(code)).version;
+ f.sqlite.prepare('UPDATE rooms SET state=?,version=? WHERE code=?').run(JSON.stringify(game),game.version,code);
+ const seats=f.sqlite.prepare('SELECT * FROM seats ORDER BY player_id').all();
+ const action=aggressorAction(game,ids[1]);const event=game.battle!.event;
+ const outcomes=await Promise.allSettled([f.rooms.act(code,auths[1],game.version,action,clock),f.restart().act(code,auths[1],game.version,action,clock)]);
+ assert.equal(outcomes.filter(r=>r.status==='fulfilled').length,1);
+ game=await f.restart().readRoom(code);assert.equal(game.battle!.saphoAggressor!.uses.length,1);
+ assert.equal(game.discard.filter(c=>c.id===SAPHO_BATTLE_CARD).length,1);
+ const rows=()=>f.sqlite.prepare('SELECT * FROM rooms WHERE code=?').all(code);
+ for(let step=0;step<100&&game.battle;step++){
+ for(const [index,token] of tokens.entries()){
+ const rooms=f.restart(),auth=await rooms.authenticate(code,token),view=await rooms.readSeatView(code,auth);
+ assert.deepEqual(view,viewGame(JSON.parse(JSON.stringify(game)) as Game,ids[index]));
+ assert.equal(view.battle!.aggressor,ids[1]);
+ for(const rival of view.players.filter(p=>p.id!==auth.playerId))for(const field of ['hand','spice','traitors','prediction'])assert.equal(field in rival,false);
+ }
+ const before=rows();await assert.rejects(()=>f.restart().act(code,auths[1],game.version,action,clock));assert.deepEqual(rows(),before);
+ const next=nextSaphoBattleAction(game);assert.ok(next);const index=ids.indexOf(next.player);
+ await f.restart().act(code,auths[index],game.version,next.action,clock);game=await f.restart().readRoom(code);saphoBattleCustody(game);
+ }
+ assert.equal(game.battle,null);assert.equal(game.lastBattleContext!.event,event);assert.deepEqual(f.sqlite.prepare('SELECT * FROM seats ORDER BY player_id').all(),seats);
+});
diff --git a/tests/sapho-aggressor.test.ts b/tests/sapho-aggressor.test.ts
new file mode 100644
index 00000000..96e0c3cb
--- /dev/null
+++ b/tests/sapho-aggressor.test.ts
@@ -0,0 +1,92 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {applyAction,viewGame,normalizeAutomaticGame,type Game,type Action} from '../game/engine';
+import {botActions} from '../game/bots';
+import {DIFFICULTIES} from '../game/bot-profiles';
+import {createStrongholdCards} from '../game/stronghold-cards';
+import {territory} from '../game/board';
+import {saphoBattleCustody,takeSaphoBattleCard,SAPHO_BATTLE_CARD} from './fixture-sapho-battle-order';
+import {saphoAggressorGame,aggressorAction,prepareAggressorPlans,revealEqualAggressorPlans,finishAggressorBattle} from './fixture-sapho-aggressor';
+function reject(g:Game,id:string,action:Action){const before=JSON.stringify(g);assert.throws(()=>applyAction(g,id,action));assert.equal(JSON.stringify(g),before);}
+const restore=(g:Game)=>{const next=JSON.parse(JSON.stringify(g)) as Game; for(const p of g.players) assert.deepEqual(viewGame(next,p.id),viewGame(g,p.id));saphoBattleCustody(next);return next;};
+void test('Sapho changes actual ordinary and Stone ties in both modes without swapping physical slots or chooser',()=>{
+ for(const advanced of [false,true]) for(const stone of [false,true]) {
+ let g=saphoAggressorGame({advanced}); const original=structuredClone(g.battle!); const order=[...g.order];
+ if(stone) takeSaphoBattleCard(g,'a','richese-stone-burner');
+ const action=aggressorAction(g); const before=JSON.stringify(g);
+ g=applyAction(g,'b',action); assert.notEqual(JSON.stringify(g),before);
+ assert.equal(g.battle!.attacker,original.attacker);assert.equal(g.battle!.defender,original.defender);assert.equal(g.battle!.chooser,original.chooser);assert.deepEqual(g.order,order);
+ for(const p of g.players){const view=viewGame(g,p.id);assert.equal(view.battle!.aggressor,'b');assert.equal(view.battle!.tieWinner,'b');assert.equal(view.players.find(q=>q.id!=='r'&&q.id!==p.id)!.hand,undefined);}
+ assert.equal(g.discard.filter(c=>c.id===SAPHO_BATTLE_CARD).length,1);reject(g,'b',action);g=restore(g);
+ g=revealEqualAggressorPlans(g,stone?'a':undefined); g=restore(g);g=finishAggressorBattle(g);
+ assert.equal(g.lastBattleContext!.winner,'b');assert.equal(g.lastBattleContext!.event,original.event);saphoBattleCustody(g);
+ }
+});
+void test('Habbanya takes precedence in either stable slot despite an opposing Sapho aggressor',()=>{
+ for(const owner of ['a','b']) {
+ let g=saphoAggressorGame({advanced:true});g.battle!.territory='habbanya_ridge_sietch';
+ for(const p of g.players.slice(0,2)){p.forces={[`habbanya_ridge_sietch:${territory('habbanya_ridge_sietch').sectors[0]}`]:4};}
+ g.strongholdCards=createStrongholdCards();g.strongholdCards.claimedTurn=1;g.strongholdCards.owners.habbanya_ridge_sietch=owner;
+ g=applyAction(g,'b',aggressorAction(g));assert.equal(viewGame(g,'a').battle!.aggressor,'b');assert.equal(viewGame(g,'a').battle!.tieWinner,owner);
+ g=finishAggressorBattle(revealEqualAggressorPlans(g));assert.equal(g.lastBattleContext!.winner,owner);
+ }
+});
+void test('early scope excludes noncombatants, readiness, later commitments and stale actions without writes',()=>{
+ const opening=saphoAggressorGame();const action=aggressorAction(opening);
+ reject(opening,'r',action);reject(opening,'a',action);reject(opening,'b',{...action,event:'old'});reject(opening,'b',{...action,mode:'last'});reject(opening,'b',{...action,extra:true});
+ const ready=applyAction(opening,'b',{type:'battlePreparationReady',event:opening.battle!.event});assert.deepEqual(viewGame(ready,'b').saphoOptions,[]);reject(ready,'b',action);
+ const planned=prepareAggressorPlans(opening);assert.deepEqual(viewGame(planned,'b').saphoOptions,[]);reject(planned,'b',action);
+ const revealed=revealEqualAggressorPlans(opening);reject(revealed,'b',action);
+ for(const field of ['voice','prescience','nexusInspection','fullPlan','truthPromises'] as const){const g=structuredClone(opening);Object.assign(g.battle!,{[field]:field==='truthPromises'?[{}]:{}});assert.throws(()=>applyAction(g,'b',action));}
+ const earlier=applyAction(opening,'a',{type:'battlePreparationReady',event:opening.battle!.event});assert.ok(aggressorAction(earlier));
+});
+void test('saved receipts fail closed and legitimate recovered-card reuse has a fresh opportunity',()=>{
+ let g=saphoAggressorGame();const first=aggressorAction(g);g=applyAction(g,'b',first);
+ for(const mutate of [(x:Game)=>{delete x.battle!.saphoAggressor;},(x:Game)=>{delete x.battle!.saphoAggressorEvents;},(x:Game)=>{x.battle!.saphoAggressor!.turn++;},(x:Game)=>{x.battle!.saphoAggressor!.uses[0].player='a';},(x:Game)=>{x.battle!.saphoAggressorEvents![0]='old';},(x:Game)=>{x.discard=x.discard.filter(c=>c.id!==SAPHO_BATTLE_CARD);}] ) {
+ const bad=structuredClone(g);mutate(bad);const before=JSON.stringify(bad);assert.throws(()=>viewGame(bad,'b'));assert.throws(()=>normalizeAutomaticGame(bad));assert.throws(()=>applyAction(bad,'b',{type:'ready'}));assert.equal(JSON.stringify(bad),before);
+ }
+ // A conserved relocation models later legal recovery without claiming the recovery action itself.
+ takeSaphoBattleCard(g,'a');const second=aggressorAction(g,'a');assert.notEqual(second.event,first.event);reject(g,'a',{...second,event:first.event});
+ g=applyAction(g,'a',second);assert.equal(viewGame(restore(g),'b').battle!.aggressor,'a');assert.equal(g.battle!.saphoAggressor!.uses.length,2);saphoBattleCustody(g);
+});
+void test('an unchosen allied Prescience prompt allows early Sapho but an actual inspection closes that scope',()=>{
+ const g=saphoAggressorGame({},g=>{g.players[1].ally='c';g.players[2].ally='b';});
+ const action=aggressorAction(g);assert.equal(g.battle!.preparation?.kind,'prescience');
+ const inspecting=normalizeAutomaticGame(applyAction(g,'c',{type:'prescience',field:'weapon'}));
+ assert.equal(inspecting.battle!.preparation?.kind,'prescienceAnswer');
+ assert.equal(inspecting.battle!.preLeader!.closed,false);
+ assert.deepEqual(viewGame(inspecting,'b').saphoOptions,[]);reject(inspecting,'b',action);
+});
+void test('early priority feeds Stone pre-commit finishability before any hidden opposing plan exists',()=>{
+ const initial=saphoAggressorGame({advanced:true,holder:'a'},g=>{
+ g.order=['b','a','c','r'];g.active='b';
+ const a=g.players[0],b=g.players[1];a.forces={'carthag:11':2};a.reserves=18;
+ a.elites!.forces={'carthag:11':1};a.elites!.reserves=4;
+ b.forces={'carthag:11':1};b.reserves=19;takeSaphoBattleCard(g,'b','richese-stone-burner');
+ });
+ assert.equal(initial.battle!.attacker,'b');
+ const plan={type:'battlePlan',dial:0,support:0,leader:initial.players[1].leaders[0].id,weapon:'richese-stone-burner'};
+ // Original Guild tie priority makes every opposing allocation finishable.
+ assert.doesNotThrow(()=>applyAction(prepareAggressorPlans(initial),'b',plan));
+ let changed=applyAction(initial,'a',aggressorAction(initial,'a'));
+ changed=prepareAggressorPlans(changed);assert.equal(viewGame(changed,'b').battle!.tieWinner,'a');
+ // The Emperor's possible mixed allocation now spans both sides of the tie.
+ // Reject the Stone commitment before seeing or accepting an opposing plan.
+ reject(changed,'b',plan);assert.equal(Object.keys(changed.battle!.plans).length,0);
+});
+void test('rival private cards and spice never affect the early option or AI, and every profile completes the battle',()=>{
+ for(const advanced of [false,true]) for(const level of DIFFICULTIES){
+ let g=saphoAggressorGame({advanced});const original=viewGame(g,'b');const expected=original.saphoOptions;
+ const changed=structuredClone(g);changed.players[0].spice=0;takeSaphoBattleCard(changed,'a','richese-stone-burner');assert.deepEqual(viewGame(changed,'b').saphoOptions,expected);
+ const view=viewGame(g,'b');view.players.find(p=>p.id==='b')!.bot=level;
+ const actions=botActions(view);assert.equal(actions[0].scope,'battleAggressor');
+ for(const p of view.players.filter(p=>p.id!=='b'))for(const key of ['hand','spice','traitors','faceDancers'])Object.defineProperty(p,key,{get(){throw new Error('Unauthorized rival field');}});
+ assert.deepEqual(botActions(view),actions);g=applyAction(g,'b',actions[0]);const event=g.battle!.event;
+ for(const p of g.players)p.bot=level;
+ for(let step=0;g.battle&&step<100;step++){
+ const next=g.players.map(p=>({player:p.id,action:botActions(viewGame(g,p.id))[0]})).find(next=>next.action);
+ assert.ok(next);g=applyAction(g,next.player,next.action);g=restore(g);
+ }
+ assert.equal(g.battle,null);assert.equal(g.lastBattleContext!.event,event);saphoBattleCustody(g);
+ }
+});
diff --git a/tests/sapho-battle-order-controls.test.tsx b/tests/sapho-battle-order-controls.test.tsx
index 559c676b..da94bd59 100644
--- a/tests/sapho-battle-order-controls.test.tsx
+++ b/tests/sapho-battle-order-controls.test.tsx
@@ -8,6 +8,7 @@ import { applyAction, viewGame, type GameView } from '../game/engine';
import { JuiceOfSapho } from '../components/juice-of-sapho';
import { botBattleChoices } from '../game/bot-battle-choices';
import { saphoBattleOrderGame, saphoBattleOrderAction } from './fixture-sapho-battle-order';
+import { saphoAggressorGame, aggressorAction } from './fixture-sapho-aggressor';
const aliases = registerHooks({
resolve(specifier, context, next) {
@@ -25,6 +26,21 @@ aliases.deregister();
const panel = (game: GameView, busy = false) => renderToStaticMarkup(createElement(JuiceOfSapho, { game, act() {}, busy }));
const table = (game: GameView) => renderToStaticMarkup(createElement(GameTable, { game, send: async () => {}, onExit() {}, busy: false }));
+void test('early aggressor control explains ties and the table keeps its public physical identities', () => {
+ const g = saphoAggressorGame();
+ const view = viewGame(g, 'b');
+ assert.match(panel(view), /Become aggressor and discard Juice of Sapho/);
+ assert.match(panel(view), /Habbanya Stronghold advantage still takes precedence/);
+ assert.match(panel(view, true), /