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
This commit is contained in:
Quintine committed 2026-09-20 11:45:47 +10:00
1 parent bfa24b0c4a
commit 9b67a780eb
21 files changed
+467 -51

No files matched your search

+6 -2
View File
@@ -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(
+2 -2
View File
@@ -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.',
+51 -7
View File
@@ -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<T>(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,
+7 -4
View File
@@ -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'
+72
View File
@@ -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 }] };
}