Compose market, early cache and phase bid promises
Verify and publish checkpoint container / container (push) Successful in 12m4s

This commit is contained in:
Quintine committed 2026-11-16 20:51:03 +11:00
1 parent 225b2174ad
commit 6a30fdf376
16 files changed
+1183 -21

No files matched your search

@@ -16,15 +16,23 @@ export function MixedRicheseBidPromises(props: { game: GameView; busy: boolean;
const live = !!auction && own.some(promise => promise.turn === game.turn && promise.event === auction.event &&
!promise.fulfilled && !promise.released);
const action = guide?.action, signature = action && JSON.stringify(action);
const progress = action?.earlyRicheseBidPromiseId !== undefined && auction ?
JSON.stringify([auction.active,auction.bid,auction.bidder,auction.acted,auction.submitted,auction.ownBid]) : null;
const isCurrentGuide = () => {
if (props.game !== game || !auction || game.richeseAuction !== auction ||
!guide || game.richeseBidPromiseGuide !== guide || !action || guide.action !== action ||
JSON.stringify(action) !== signature || action.type !== 'richeseBid' || action.event !== auction.event ||
(progress !== null && JSON.stringify([auction.active,auction.bid,auction.bidder,
auction.acted,auction.submitted,auction.ownBid]) !== progress) ||
typeof action.richeseBidPromiseId !== 'string') return false;
if (action.phaseAnyBidPromiseEvent !== undefined &&
(typeof action.phaseAnyBidPromiseEvent !== 'string' || action.phaseAnyBidLotEvent !== auction.event ||
!game.phaseAnyBidPromises.some(promise => promise.event === action.phaseAnyBidPromiseEvent &&
promise.player === game.me && promise.turn === game.turn && !promise.fulfilled && !promise.released))) return false;
if (action.earlyRicheseBidPromiseId !== undefined &&
(typeof action.earlyRicheseBidPromiseId !== 'string' ||
!game.ownEarlyRicheseBidPromises.some(promise => promise.id === action.earlyRicheseBidPromiseId &&
promise.player === game.me && promise.turn === game.turn && !promise.boundEvent && !promise.fulfilled && !promise.released))) return false;
return game.mixedRicheseBidPromises.some(promise => promise.player === game.me &&
promise.id === action.richeseBidPromiseId && promise.turn === game.turn &&
promise.event === auction.event && !promise.fulfilled && !promise.released);
+9 -2
View File
@@ -14,7 +14,8 @@ export function PhaseAnyBidGuideButton(props: Props) {
const signature = JSON.stringify(action), ordinary = game.auction, special = game.richeseAuction;
const ordinarySignature = ordinary && JSON.stringify([ordinary.bid, ordinary.bidder, ordinary.active, ordinary.remaining]);
const specialSignature = special && JSON.stringify([special.event, special.method, special.active,
special.bid, special.bidder, special.submitted, special.ownBid]);
special.bid, special.bidder, special.submitted, special.ownBid,
...(action.earlyRicheseBidPromiseId !== undefined ? [special.acted] : [])]);
const canAct = () => {
const current = props.game, me = current.players.find(player => player.id === actor);
if (props.busy || current !== game || current.me !== actor || current.turn !== turn ||
@@ -31,6 +32,11 @@ export function PhaseAnyBidGuideButton(props: Props) {
promise.id === action.richeseBidPromiseId && promise.player === actor && promise.turn === turn &&
promise.event === special.event && !promise.fulfilled && !promise.released)) return false;
}
if (action.earlyRicheseBidPromiseId !== undefined &&
(typeof action.earlyRicheseBidPromiseId !== 'string' ||
!current.ownEarlyRicheseBidPromises.some(promise =>
promise.id === action.earlyRicheseBidPromiseId && promise.player === actor && promise.turn === turn &&
!promise.boundEvent && !promise.fulfilled && !promise.released))) return false;
if (action.bidPromiseEvent !== undefined) {
if ((action.type !== 'bid' && action.type !== 'passBid') || typeof action.bidPromiseEvent !== 'string' ||
typeof action.phaseAnyBidLot !== 'number' || current.bidPromiseLot?.turn !== turn ||
@@ -47,7 +53,8 @@ export function PhaseAnyBidGuideButton(props: Props) {
if (action.type !== 'richeseBid' || !special || current.richeseAuction !== special ||
special.event !== action.event || special.event !== action.phaseAnyBidLotEvent ||
JSON.stringify([special.event, special.method, special.active, special.bid, special.bidder,
special.submitted, special.ownBid]) !== specialSignature) return false;
special.submitted, special.ownBid,
...(action.earlyRicheseBidPromiseId !== undefined ? [special.acted] : [])]) !== specialSignature) return false;
return special.method === 'silent' ? !special.submitted.includes(actor) : special.active === actor;
};
return <Button className="game-action min-h-11 whitespace-normal" data-testid="phase-any-bid-guide"
+12 -1
View File
@@ -17,7 +17,10 @@ export type RicheseBidPromisePanelProps = {
guide: { action: Action } | null;
game: { turn: number; me?: string;
phaseAnyBidPromises?: {event: string; player: string; turn: number; fulfilled?: boolean; released?: boolean}[];
richeseAuction: { event: string; method?: 'onceAround' | 'silent' | 'normal' } | null };
ownEarlyRicheseBidPromises?: {id: string; player: string; turn: number; boundEvent?: string; fulfilled?: boolean; released?: boolean}[];
richeseAuction: { event: string; method?: 'onceAround' | 'silent' | 'normal';
active?: string | null; bid?: number; bidder?: string | null; acted?: readonly string[];
submitted?: readonly string[]; ownBid?: number | null } | null };
act: (action: Action) => void;
busy: boolean;
};
@@ -29,16 +32,24 @@ export function RicheseBidPromiseGuide(props: RicheseBidPromisePanelProps) {
const auction = game.richeseAuction, turn = game.turn, action = guide.action;
const auctionEvent = action.event, id = action.richeseBidPromiseId;
const signature = JSON.stringify(action);
const progress = action.earlyRicheseBidPromiseId !== undefined && auction ?
JSON.stringify([auction.active,auction.bid,auction.bidder,auction.acted,auction.submitted,auction.ownBid]) : null;
const isCurrent = () => props.game === game && props.guide === guide &&
props.guide.action === action && JSON.stringify(action) === signature &&
game.turn === turn && !!auction && game.richeseAuction === auction &&
typeof auctionEvent === 'string' && auction.event === auctionEvent &&
(progress === null || JSON.stringify([auction.active,auction.bid,auction.bidder,
auction.acted,auction.submitted,auction.ownBid]) === progress) &&
typeof id === 'string' && action.type === 'richeseBid' &&
(action.phaseAnyBidPromiseEvent === undefined ||
typeof action.phaseAnyBidPromiseEvent === 'string' && action.phaseAnyBidLotEvent === auctionEvent &&
typeof game.me === 'string' && !!game.phaseAnyBidPromises?.some(promise =>
promise.event === action.phaseAnyBidPromiseEvent && promise.player === game.me && promise.turn === turn &&
!promise.fulfilled && !promise.released)) &&
(action.earlyRicheseBidPromiseId === undefined ||
typeof action.earlyRicheseBidPromiseId === 'string' && typeof game.me === 'string' &&
!!game.ownEarlyRicheseBidPromises?.some(promise => promise.id === action.earlyRicheseBidPromiseId &&
promise.player === game.me && promise.turn === turn && !promise.boundEvent && !promise.fulfilled && !promise.released)) &&
props.promises.some(promise => promise.id === id && promise.turn === turn &&
promise.event === auctionEvent && !promise.fulfilled && !promise.released);
const canAct = () => !props.busy && isCurrent();
+10 -1
View File
@@ -17,10 +17,19 @@ open mode gates.
## Current checkpoint and work
**Current Black Market and early cache answers — 16 November. Prototyped /
Partial.** In supported Advanced games, a current Once Around or Silent Black
Market answer can coexist with a waiting first-cache answer and an all-auction
phase answer. A shared native guide reserves the independently required cache
bid, funding and hand space. Other commitment families, Kull, optional modules,
complete games and deployed acceptance remain open. Twenty-one related unit
files pass 178 cases.
[Scope](TRUTHTRANCE_BID_PROMISES.md#current-black-market-and-early-cache-answers--16-november-2026).
**Advanced early cache through Black Market — 16 November. Prototyped /
Partial.** Supported bare Advanced CHOAM-deck games can bind the early cache
question, alone or with a phase-wide answer, through the original Black Market
and Advanced Semuta response. A third independent current-market bid binding,
and Advanced Semuta response. Current-market bid answers now compose as above;
Kull and other module combinations, complete games and deployed acceptance
remain open. Eighteen related unit files pass 214 cases.
[Scope](TRUTHTRANCE_BID_PROMISES.md#advanced-early-cache-and-black-market--16-november-2026).
+8 -1
View File
@@ -1,10 +1,17 @@
# Rule decision index
## Current Black Market and early cache answers — 16 November 2026
The current Once Around or Silent market answer, waiting cache answer and
all-auction phase answer can share a funded plan. Online forecasting and timing
remain provisional.
[Scope](TRUTHTRANCE_BID_PROMISES.md#current-black-market-and-early-cache-answers--16-november-2026).
## Advanced early cache and Black Market — 16 November 2026
Supported Advanced early-cache and all-auction answers preserve the original
Black Market purchase and subsequent cache. Funding forecasts and online
timing are provisional; a separate current-lot third binding remains guarded.
timing are provisional; the current-lot extension is described above.
[Scope](TRUTHTRANCE_BID_PROMISES.md#advanced-early-cache-and-black-market--16-november-2026).
## Sandmaster and concealed Ambassador relocation — 16 November 2026
+32 -3
View File
@@ -1,5 +1,35 @@
# Truthtrance ordinary bid commitments
## Current Black Market and early cache answers — 16 November 2026
**Prototyped / Partial.** In supported bare Advanced CHOAM-deck games, a player
may answer a current Once Around or Silent Black Market bid question while an
early first-cache answer waits, including with an all-auction phase answer and
mixed current-fact expressions. Current and phase Yes answers can share the
market declaration; the independently required cache bid keeps its own funds
and hand space. A current No applies only to that lot, an early No only to the
first cache, and a phase No throughout Bidding. The same event-bound native
action is projected to the relevant guides, bots and auction clock. Its three
receipts and the original pending question queue survive the supported Semuta
reaction. A stale receipt or changed lot cannot authorize an old guide.
The forecast uses owned funds and actual committed aid, reserves the market's
possible card and Harkonnen bonus, and handles paid seller retention. It does
not assume rival Silent bids, a refund or future income. An external change
releases only answers whose own opportunities became impossible. The supplied
Advanced revision (physical p. 36, printed p. 34), publisher R2 pp. 4–6 and
FAQ current-turn question guidance support the underlying actions; online
priority and forecasts remain provisional. Kull, other commitment families,
optional modules, full games and deployed acceptance remain open.
[Native cases](../tests/truth-early-richese-advanced-market-current.test.ts),
[controls](../tests/truth-early-richese-advanced-market-current-controls.test.tsx)
and [joint quotes](../tests/joint-market-early-bids.test.ts) cover both auction
methods with disclosed conserved card staging. [Semuta integrity](../tests/truth-early-richese-advanced-market-integrity.test.ts),
[selective release](../tests/truth-early-richese-advanced-market-release-native.test.ts)
and the [auction clock](../tests/truth-early-richese-advanced-market-current-clock.test.ts)
exercise the original physical continuations. Twenty-one related unit files pass
178 cases.
## Advanced early cache and Black Market — 16 November 2026
**Prototyped / Partial.** Before Bidding in supported bare Advanced CHOAM-deck
@@ -19,9 +49,8 @@ bind both ledgers; Unknown keeps the Truthtrance.
The Advanced revision's Richese section (supplied PDF physical p. 36, printed
p. 34) and publisher R2 pp. 4–6, 10–12 establish the physical cache and market
sequence. The existing online forecast, seller retention and Truthtrance timing
are provisional compositions, not new publisher rulings. A new current-lot
Black Market bid question cannot yet create a third independent binding while
an early-cache receipt waits; constant-fact mixed answers remain available.
are provisional compositions, not new publisher rulings. Current-lot market
answers now compose with the early cache as described above.
Kull, other Advanced modules, full games and deployed acceptance remain open.
[Market cases](../tests/truth-early-richese-advanced-black-market.test.ts),
[guide cases](../tests/truth-early-richese-advanced-market-guides.test.ts),
+137 -7
View File
@@ -39,6 +39,7 @@ import { EarlyRicheseBidError, earlyRicheseBidModeSupported, earlyRicheseBidAnsw
attachEarlyRicheseBids, liveEarlyRicheseBidPromises, reconcileEarlyRicheseBids,
validateEarlyRicheseBidPromises, type EarlyRicheseBidClaim, type EarlyRicheseBidPromise } from './early-richese-bid';
import { quoteJointEarlyRicheseBids } from './joint-early-richese-bids';
import { quoteJointMarketEarlyBids } from './joint-market-early-bids';
import { AuctionClockError, AUCTION_BID_MS, quoteAuctionClock, viewAuctionClock,
type AuctionClock, type AuctionClockView } from './auction-clock';
import { PrintedCardPlayError, printedCardPlayCount, recordPrintedCardPlay,
@@ -2014,6 +2015,8 @@ export type Game = {
jointEarlyPhaseBid?: true;
/** Fresh Advanced pre-Bidding cache/phase answer and its ledgers. */
advancedEarlyCacheTruth?: true;
/** Fresh current market answer and waiting early-cache receipt. */
jointMarketEarlyBid?: true;
resume: NonNullable<Game['pendingNullentropy']>['resume'];
promise:
| { kind: 'shipment'; index: number; value: ShipmentPromise }
@@ -8074,6 +8077,9 @@ function truthtranceDiscardSignature(g: Game, next: TruthDiscardContinuation) {
earlyRicheseBidPromises:g.earlyRicheseBidPromises} : {}),
...(next.advancedEarlyCacheTruth ? {advancedEarlyCacheTruth:true,phaseAnyBidPromises:g.phaseAnyBidPromises,
earlyRicheseBidPromises:g.earlyRicheseBidPromises} : {}),
...(next.jointMarketEarlyBid ? {jointMarketEarlyBid:true,phaseAnyBidPromises:g.phaseAnyBidPromises,
earlyRicheseBidPromises:g.earlyRicheseBidPromises,richeseBidPromises:g.richeseBidPromises,
mixedRicheseBidQuestions:g.mixedRicheseBidQuestions} : {}),
...(next.record.question.kind === 'mixedRevival' ? {
mixedRevivalQuestions: g.mixedRevivalQuestions, revivalExpressionPromises: g.revivalExpressionPromises,
} : {}),
@@ -8172,6 +8178,12 @@ function finishTruthtranceAnswer(g: Game) {
livePhaseBidPromises(g.phaseAnyBidPromises ?? [],record.question.target,g.turn).length &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],record.question.target,g.turn).length
? {jointEarlyPhaseBid:true as const} : {}),
...(g.richeseAuction?.source === 'blackMarket' &&
['phaseAnyBid','richeseBid','mixedRicheseBid'].includes(record.question.kind) &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],record.question.target,g.turn).length &&
(record.question.kind === 'mixedRicheseBid' ||
liveRicheseBidPromises(g.richeseBidPromises ?? [],{turn:g.turn,event:g.richeseAuction.event,
player:record.question.target}).length) ? {jointMarketEarlyBid:true as const} : {}),
resume,
promise,
parentSignature: '',
@@ -9199,6 +9211,17 @@ function treacheryDiscardIntegrity(g: Game) {
'The consumed Truthtrance does not match its completed answer history.',
);
const remaining = c.remaining;
if (c.jointMarketEarlyBid) {
const lot = g.richeseAuction, target = record.question.target;
requireRule(c.jointMarketEarlyBid === true && lot?.source === 'blackMarket' &&
['phaseAnyBid','richeseBid','mixedRicheseBid'].includes(record.question.kind) &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],target,g.turn).length > 0 &&
(liveRicheseBidPromises(g.richeseBidPromises ?? [],{turn:g.turn,event:lot.event,player:target}).length > 0 ||
record.question.kind === 'mixedRicheseBid' && (g.mixedRicheseBidQuestions ?? []).some(row =>
row.turn === g.turn && row.event === lot.event && row.player === target && row.asker === record.asker &&
row.answer === (record.answer === 'yes') && !row.binding)),
'The completed Truthtrance lost its original market and early cache commitments.');
}
requireRule(!c.advancedEarlyCacheTruth || c.advancedEarlyCacheTruth === true &&
advancedEarlyCacheTruthSupported(g,record.question.kind),
'The completed Truthtrance no longer matches its original Advanced cache question.');
@@ -18722,11 +18745,6 @@ function richeseBidTruthAnswers(g: Game, p: Player, claim: RicheseBidClaim): Tru
if (!richeseBidWindow(g) || !lot || claim.turn !== g.turn || claim.event !== lot.event ||
!lot.eligible.includes(p.id) || lot.acted.includes(p.id) ||
!richeseBidFitsHand(lot.source,lot.owner,p.id,p.hand.length,handLimit(p))) return [];
// A separately asked Black Market bid needs a three-ledger planner before
// it can coexist with an unbound first-cache promise. Do not admit a Yes
// that could reserve the same spice or hand space twice.
if (lot.source === 'blackMarket' &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).length) return [];
const base = g.richeseBidPromises ?? [], opportunity = richeseBidOpportunity(g,p);
const context = {turn:g.turn,event:lot.event,player:p.id};
const asker = g.truthtrance?.queue[0]?.player ?? g.players.find(row => row.id !== p.id)?.id ?? g.host;
@@ -18735,6 +18753,9 @@ function richeseBidTruthAnswers(g: Game, p: Player, claim: RicheseBidClaim): Tru
const all = [...base,candidate];
if (answer === 'yes' && richeseBidOtherPromises(g,p,{allowPhaseAny:true})) return false;
const phase = livePhaseBidPromises(g.phaseAnyBidPromises ?? [],p.id,g.turn);
if (lot.source === 'blackMarket' &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).length)
return marketEarlyPossible(g,p,all,phase);
if (phase.length) return richesePhaseJointPossible({...g,richeseBidPromises:all},p,phase);
return !richeseBidRequired(all,context) || !!opportunity && !!richeseBidCompletionRange(all,opportunity);
});
@@ -18808,9 +18829,18 @@ function reconcileRicheseBids(g: Game,voluntary?: {actor:string;action:Action})
if (g.turn !== row.turn || !lot || lot.event !== row.event || lot.outcome)
g.richeseBidPromises = richeseBidRule(() => finishRicheseBidLot(g.richeseBidPromises!,context,change));
else {
const opportunity = richeseBidOpportunity(g,getPlayer(g,row.player));
const owner = getPlayer(g,row.player);
const opportunity = richeseBidOpportunity(g,owner);
const caps = livePhaseBidPromises(g.phaseAnyBidPromises ?? [],row.player,g.turn).filter(item => !item.answer);
const maximum = opportunity ? caps.reduce((value,item) => Math.min(value,item.minimum-1),opportunity.maximum) : 0;
let maximum = opportunity ? caps.reduce((value,item) => Math.min(value,item.minimum-1),opportunity.maximum) : 0;
if (lot.source === 'blackMarket' &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],row.player,g.turn).length) {
// Quote the common funded ceiling independently of Yes minima, so
// an external change can release only the impossible higher answers.
const local = liveRicheseBidPromises(g.richeseBidPromises ?? [],context)
.filter(item => !item.answer);
maximum = Math.min(maximum,marketEarlyQuote(g,owner,local,caps)?.market?.maximum ?? 0);
}
const adjusted = opportunity && maximum >= opportunity.minimum ? {...opportunity,maximum} : null;
g.richeseBidPromises = richeseBidRule(() => reconcileRicheseBidPromises(g.richeseBidPromises!,context,adjusted,change));
}
@@ -18822,6 +18852,8 @@ function projectedRicheseBidGuide(g: Game, player: string): {action:Action} | nu
g.truthtrance || !richeseBidWindow(g)) return null;
const context = {turn:g.turn,event:lot.event,player}, live = liveRicheseBidPromises(g.richeseBidPromises ?? [],context);
if (!live.length) return null;
if (lot.source === 'blackMarket' && liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],player,g.turn).length)
return projectedMarketEarlyGuide(g,player);
if (livePhaseBidPromises(g.phaseAnyBidPromises ?? [],player,g.turn).length)
return projectedJointRicheseBidGuide(g,player);
if (!richeseBidRequired(live,context)) return {action:{type:'richeseBid',event:lot.event,amount:lot.method === 'silent' ? 0 : null,allyPayment:0,richeseBidPromiseId:live[0].id}};
@@ -19181,6 +19213,10 @@ function pendingEarlyCacheMaximum(g: Game,p: Player): number {
function earlyPhaseAnyPossible(g: Game,p: Player,early: readonly EarlyRicheseBidPromise[],
phase: readonly PhaseBidPromise[]): boolean {
const trial = {...g,earlyRicheseBidPromises:[...early]};
const market = g.richeseAuction;
const native = market?.source === 'blackMarket'
? liveRicheseBidPromises(g.richeseBidPromises ?? [],{turn:g.turn,event:market.event,player:p.id}) : [];
if (native.length) return marketEarlyPossible(trial,p,native,phase);
const cache = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase,
cacheMaximum:pendingEarlyCacheMaximum(g,p)});
if (cache.earlyRequired && !cache.cache) return false;
@@ -19190,6 +19226,63 @@ function earlyPhaseAnyPossible(g: Game,p: Player,early: readonly EarlyRicheseBid
return !cache.phaseRequired || phaseAnyBidWitnesses(trial,p,phase)
.some(witness => !!phaseBidCompletionRange(phase,witness));
}
/** Quote a real current market declaration while retaining the first cache. */
function marketEarlyQuote(g: Game,p: Player,native: readonly RicheseBidPromise[],phase: readonly PhaseBidPromise[]) {
const lot = g.richeseAuction;
if (!lot || lot.source !== 'blackMarket') return null;
return quoteJointMarketEarlyBids({context:{turn:g.turn,event:lot.event,player:p.id},native,
early:g.earlyRicheseBidPromises ?? [],phase,opportunity:richeseBidOpportunity(g,p),
cashAvailable:Math.max(0,uncommittedSpice(g,p)+richeseOwnCommitment(lot,g.richeseFunding ?? {},p.id)),
aidAvailable:Math.max(0,aidFor(g,p)?.amount ?? 0),cacheMaximum:pendingEarlyCacheMaximum(g,p),
freeSlots:Math.max(0,handLimit(p)-p.hand.length),marketEntrySlots:lot.owner === p.id ? 0 : 1,
marketWinSlots:lot.owner === p.id ? 0 : 1+Number(p.faction === 'harkonnen')});
}
/** The minimum native market declaration is materialized on a detached
* state before a later cache or ordinary lot is counted. */
function marketEarlyWitnesses(g: Game,p: Player,native: readonly RicheseBidPromise[],
phase: readonly PhaseBidPromise[]): PhaseBidOpportunity[] {
const lot = g.richeseAuction, quote = marketEarlyQuote(g,p,native,phase);
if (!lot || !quote || quote.nativeRequired && !quote.market || !quote.nativeRequired && !quote.canPass) return [];
const result: PhaseBidOpportunity[] = quote.market ? [{turn:g.turn,player:p.id,kind:'current',
minimum:quote.market.minimum,maximum:quote.market.maximum}] : [];
const declarations = quote.nativeRequired ? [quote.market!,...(quote.marketForCache ? [quote.marketForCache] : [])] : [null];
for (const declaration of declarations) {
const trial = structuredClone(g), pending = trial.richeseAuction!;
trial.truthtrance = null;
const amount = declaration ? declaration.minimum : lot.method === 'silent' ? 0 : null;
if (!pending.acted.includes(p.id)) pending.acted.push(p.id);
if (pending.method === 'silent') pending.sealed[p.id] = amount ?? 0;
else if (amount === null) { if (!pending.passed.includes(p.id)) pending.passed.push(p.id); }
else { pending.bid = amount; pending.bidder = p.id; }
if (amount !== null && amount > 0) (trial.richeseFunding ??= {})[p.id] = {
amount,allyPayment:declaration!.allyPayment,donor:declaration!.allyPayment ? p.ally : null};
const owner = getPlayer(trial,p.id), early = trial.earlyRicheseBidPromises ?? [];
const cacheMaximum = pendingEarlyCacheMaximum(trial,owner);
const cache = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase,cacheMaximum});
if (cache.cache) result.push({turn:g.turn,player:p.id,kind:'future',...cache.cache});
const positive = livePhaseBidPromises(phase,p.id,g.turn).find(row => row.answer);
const later = positive && phaseAnyMarketOrdinary(trial,owner);
if (later && positive) {
const neutral = [...livePhaseBidPromises(phase,p.id,g.turn).filter(row => !row.answer),{...positive,minimum:1}];
const locked = declaration?.allyPayment ?? 0;
const joint = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase:neutral,cacheMaximum,
ordinary:{opportunity:later,cashAvailable:Math.max(0,uncommittedSpice(trial,owner)),
aidAvailable:Math.max(0,(aidFor(trial,owner)?.amount ?? 0)-locked),
freeSlots:Math.max(0,handLimit(owner)-owner.hand.length-pendingBlackMarketCards(trial,owner)),
cacheWinSlots:1+Number(owner.faction === 'harkonnen')}});
if (joint.separate) result.push({...later,...joint.separate.ordinary});
}
}
return result;
}
function marketEarlyPossible(g: Game,p: Player,native: readonly RicheseBidPromise[],
phase: readonly PhaseBidPromise[]): boolean {
const quote = marketEarlyQuote(g,p,native,phase);
if (!quote) return false;
if (quote.nativeRequired ? !quote.market : !quote.canPass) return false;
return !quote.phaseRequired || marketEarlyWitnesses(g,p,native,phase)
.some(witness => !!phaseBidCompletionRange(phase,witness));
}
/** Quote the real local declaration before relying on a later phase-wide bid.
* This detached forecast records only the respondent's own Silent submission. */
function jointRicheseFutureWitnesses(g: Game,p: Player,phase: readonly PhaseBidPromise[],
@@ -19223,6 +19316,9 @@ function phaseAnyBidWitnesses(g: Game, p: Player, promises: readonly PhaseBidPro
const context = {turn:g.turn,event:lot.event,player:p.id};
const native = liveRicheseBidPromises(g.richeseBidPromises ?? [],context);
if (native.length) {
if (lot.source === 'blackMarket' &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).length)
return marketEarlyWitnesses(g,p,native,promises);
const opportunity = richeseBidOpportunity(g,p);
const range = opportunity && jointRicheseBidCompletionRange(native,promises,opportunity,{includePhaseYes:false});
const current: PhaseBidOpportunity[] = special && range ? [{...special,...range}] : [];
@@ -19382,6 +19478,31 @@ function reconcilePhaseAnyBids(g: Game,voluntary?: {actor:string;action:Action})
}
}
/** One exact native action is shared by both panels, bots and the clock. */
function projectedMarketEarlyGuide(g: Game,id: string): {action:Action} | null {
const lot = g.richeseAuction, p = getPlayer(g,id);
if (!lot || lot.source !== 'blackMarket' || g.truthtrance || !richeseBidWindow(g) ||
(lot.method === 'silent' ? Object.hasOwn(lot.sealed,id) : lot.active !== id)) return null;
const context = {turn:g.turn,event:lot.event,player:id};
const native = liveRicheseBidPromises(g.richeseBidPromises ?? [],context);
const early = liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],id,g.turn);
const phase = livePhaseBidPromises(g.phaseAnyBidPromises ?? [],id,g.turn);
if (!native.length || !early.length) return null;
const quote = marketEarlyQuote(g,p,native,phase);
if (!quote) return null;
let bid = quote.phaseRequired ? quote.marketForPhase : null;
if (!bid && quote.nativeRequired) {
if (!quote.market) return null;
bid = quote.phaseRequired ? quote.marketForCache ?? quote.market : quote.market;
}
if (quote.phaseRequired && !quote.marketForPhase && !marketEarlyWitnesses(g,p,native,phase)
.some(witness => witness.kind === 'future' && !!phaseBidCompletionRange(phase,witness))) return null;
if (!bid && !quote.canPass) return null;
return {action:{type:'richeseBid',event:lot.event,
amount:bid ? bid.minimum : lot.method === 'silent' ? 0 : null,
allyPayment:bid?.allyPayment ?? 0,richeseBidPromiseId:native[0].id,
earlyRicheseBidPromiseId:early[0].id,
...(phase.length ? {phaseAnyBidPromiseEvent:phase[0].event,phaseAnyBidLotEvent:lot.event} : {})}};
}
function projectedJointRicheseBidGuide(g: Game,id: string): {action:Action} | null {
const lot = g.richeseAuction, p = getPlayer(g,id);
if (!lot || g.truthtrance || !richeseBidWindow(g) ||
@@ -19390,6 +19511,8 @@ function projectedJointRicheseBidGuide(g: Game,id: string): {action:Action} | nu
const native = liveRicheseBidPromises(g.richeseBidPromises ?? [],context);
const phase = livePhaseBidPromises(g.phaseAnyBidPromises ?? [],id,g.turn);
if (!native.length || !phase.length) return null;
if (lot.source === 'blackMarket' && liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],id,g.turn).length)
return projectedMarketEarlyGuide(g,id);
const opportunity = richeseBidOpportunity(g,p);
const current = opportunity && jointRicheseBidCompletionRange(native,phase,opportunity);
const nativeRequired = richeseBidRequired(native,context), phaseRequired = phase.some(row => row.answer);
@@ -45053,6 +45176,13 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
Object.keys(guide.action).every(key => action[key] === guide.action[key]),
'This Richese bid guide is stale or belongs to another lot.');
}
if (action.earlyRicheseBidPromiseId !== undefined) {
requireRule(action.type === 'richeseBid' && state.richeseAuction?.source === 'blackMarket' &&
typeof action.earlyRicheseBidPromiseId === 'string' && action.richeseBidPromiseId !== undefined &&
liveEarlyRicheseBidPromises(state.earlyRicheseBidPromises ?? [],id,state.turn)
.some(row => row.id === action.earlyRicheseBidPromiseId),
'This early cache bid guide is stale or belongs to another player.');
}
let g = applyActionInner(state, id, action, 'live', initiator);
if (state.pendingPublicDealSettlement && !g.bureaucratPayments?.pending) {
const frame = state.pendingPublicDealSettlement;
+104
View File
@@ -0,0 +1,104 @@
import { quoteJointEarlyRicheseBids } from './joint-early-richese-bids';
import { jointRicheseBidCompletionRange } from './joint-richese-bids';
import {
richeseBidRequired,
RicheseBidPromiseError,
type RicheseBidContext,
type RicheseBidOpportunity,
type RicheseBidPromise,
} from './richese-bid-promises';
import { livePhaseBidPromises, phaseBidCompletionRange, type PhaseBidPromise, type PhaseBidRange } from './turn-bid-promises';
import type { EarlyRicheseBidPromise } from './early-richese-bid';
/** Every number is supplied from the engine's current native quote, not a
* prediction of rival bids, refunds or income. The cache is after the market. */
export type JointMarketEarlyBidInput = {
context: RicheseBidContext;
native: readonly RicheseBidPromise[];
early: readonly EarlyRicheseBidPromise[];
phase: readonly PhaseBidPromise[];
opportunity: RicheseBidOpportunity | null;
/** Own cash and unlocked pledged aid available for the market bid. */
cashAvailable: number;
aidAvailable: number;
/** Own cash available for the later cache if the market is declined. */
cacheMaximum: number;
/** Free slots after any pre-existing purchase, before this market bid. */
freeSlots: number;
/** Current sale needs one slot for a buyer and none for paid self-retention. */
marketEntrySlots: number;
/** Slots reserved after a possible market win, including a Harkonnen bonus. */
marketWinSlots: number;
};
/** Inclusive market interval and the ally contribution needed for its
* minimum while preserving the stated cache reservation. */
export type JointMarketBidRange = PhaseBidRange & { allyPayment: number };
export type JointMarketEarlyBidQuote = {
nativeRequired: boolean;
earlyRequired: boolean;
phaseRequired: boolean;
/** A pass/zero satisfies the native answer and retains the early cache. */
canPass: boolean;
/** Legal current bid preserving the independent early-cache Yes. */
market: JointMarketBidRange | null;
/** Current bid also fulfilling every live phase Yes. */
marketForPhase: JointMarketBidRange | null;
/** Current bid leaving the cache able to fulfill every phase Yes. */
marketForCache: JointMarketBidRange | null;
/** A cache bid if this market is declined; phase Yes may remain open. */
cacheAfterPass: PhaseBidRange | null;
/** A cache bid fulfilling every phase Yes if this market is declined. */
phaseCacheAfterPass: PhaseBidRange | null;
};
const whole = (value: unknown): value is number =>
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
/** Intersect three ledgers around the actual one-declaration market lot. The
* caller supplies event eligibility and later ordinary-lot witnesses. When a
* later cache bid must be funded, reserve personal cash and the potential
* first market purchase before exposing a market bid. No cache refund,
* non-owner sale, hidden offer, or pledged future aid is assumed. */
export function quoteJointMarketEarlyBids(input: JointMarketEarlyBidInput): JointMarketEarlyBidQuote {
if (!input || !input.context || !Array.isArray(input.native) || !Array.isArray(input.early) ||
!Array.isArray(input.phase) || !whole(input.cashAvailable) || !whole(input.aidAvailable) ||
!whole(input.cacheMaximum) || !whole(input.freeSlots) || !whole(input.marketEntrySlots) ||
!whole(input.marketWinSlots) || input.marketWinSlots < input.marketEntrySlots)
throw new RicheseBidPromiseError('Retain the original market, funded cache and hand capacity.');
const {context, native, early, phase, opportunity} = input;
const nativeRequired = richeseBidRequired(native,context);
if (opportunity && (opportunity.turn !== context.turn || opportunity.event !== context.event ||
opportunity.player !== context.player))
throw new RicheseBidPromiseError('The bid opportunity belongs to a different market event.');
const cache = quoteJointEarlyRicheseBids({player:context.player,turn:context.turn,
early,phase,cacheMaximum:input.cacheMaximum});
const phaseRequired = livePhaseBidPromises(phase,context.player,context.turn).some(row => row.answer);
const local = opportunity && jointRicheseBidCompletionRange(native,phase,opportunity,{includePhaseYes:false});
const marketRange = (reserve: number | null): JointMarketBidRange | null => {
if (!local || reserve === null || input.cashAvailable < reserve) return null;
const slots = reserve > 0 ? input.marketWinSlots + 1 : input.marketEntrySlots;
if (input.freeSlots < slots) return null;
const maximum = Math.min(local.maximum,Number.MAX_SAFE_INTEGER,
input.cashAvailable - reserve + input.aidAvailable);
if (local.minimum > maximum) return null;
return {minimum:local.minimum,maximum,
allyPayment:Math.max(0,local.minimum - (input.cashAvailable - reserve))};
};
const earlyReserve = cache.earlyRequired ? cache.cache?.minimum ?? null : 0;
const market = marketRange(earlyReserve);
let marketForPhase: JointMarketBidRange | null = null;
if (market && phaseRequired) {
const range = phaseBidCompletionRange(phase,{turn:context.turn,player:context.player,
kind:'current',minimum:market.minimum,maximum:market.maximum});
if (range) marketForPhase = {...range,
allyPayment:Math.max(0,range.minimum - (input.cashAvailable - (earlyReserve ?? 0)))};
}
const marketForCache = phaseRequired && cache.shared ? marketRange(cache.shared.minimum) : null;
const canPass = !nativeRequired && (!cache.earlyRequired || !!cache.cache);
return {nativeRequired,earlyRequired:cache.earlyRequired,phaseRequired,canPass,
market,marketForPhase,marketForCache,
cacheAfterPass:canPass ? cache.cache : null,
phaseCacheAfterPass:canPass && phaseRequired ? cache.shared : null};
}
+1 -1
View File
@@ -3793,7 +3793,7 @@ export const RULE_TOPICS: RuleTopic[] = [
'In a Silent Richese lot the question binds the respondent’s single sealed submission. Zero declines; a positive bid remains hidden until the native simultaneous reveal. Available answers use that bidder’s own funding, without using opponents’ concealed amounts.',
'Before Bidding in supported Basic and bare Advanced Richese games, ask about a minimum bid in the first actual cache auction of this turn. The answer waits for the real event and does not predict its card or method. Current uncommitted personal funds and hand space supply a conservative Yes witness; in Advanced, a Black Market purchase reserves its actual cost and hand space first. You cannot cancel a cache required by your own feasible Yes; another player’s cancellation or opposing action can release an impossible commitment. The Richese owner’s Once Around turn may vanish if everyone else passes.',
'A supported early cache answer and the all-auction phase answer can coexist. A single qualifying cache bid may satisfy both; separate bids need enough currently funded spice and hand space for both purchases. A cache No ends with that lot, while a phase No continues until Bidding ends.',
'In the Advanced preview, a separate current Black Market bid question cannot yet bind a respondent who already has a waiting early-cache answer. The all-auction phase question remains available within its stated limits.',
'In the supported Advanced preview, a current Once Around or Silent Black Market answer can coexist with a waiting early-cache answer and an all-auction phase answer. The shared guide preserves the separate cache funding and hand space; current-lot and phase No answers keep their own scopes.',
'Your waiting cache commitment remains visible until its auction opens or it ends. Once the real lot opens, the ordinary Richese bid guide takes over.',
'The phase-wide guide may wait for a later lot only when the existing funded sale, prepared next card and post-sale space and funds support it. An unbid lot, hypothetical rival raise, cancelable unfunded overbid or Harkonnen bonus slot is not invented as a future opportunity. Before Bidding, current funding and available card count provide a provisional forecast; special auction preparation and combined future commitments remain limited.',
'In supported Basic Ixian or Richese games, a phase-wide ordinary bid can wait through Ixian inspection or a first-position Richese cache. Only ordinary bids count; a potential cache purchase reserves your funds and hand space. If the ordinary auction clock expires and your Yes forbids passing, the normal guide supplies the required legal bid.',
+115
View File
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { quoteJointMarketEarlyBids, type JointMarketEarlyBidInput } from '../game/joint-market-early-bids';
import type { RicheseBidPromise } from '../game/richese-bid-promises';
import type { EarlyRicheseBidPromise } from '../game/early-richese-bid';
import type { PhaseBidPromise } from '../game/turn-bid-promises';
const context = {turn:3,event:'market-event',player:'emperor'};
const native = (minimum:number,answer:boolean,extra:Partial<RicheseBidPromise> = {}):RicheseBidPromise =>
({...context,id:`market-${minimum}-${answer}`,asker:'atreides',minimum,answer,...extra});
const early = (minimum:number,answer:boolean,extra:Partial<EarlyRicheseBidPromise> = {}):EarlyRicheseBidPromise =>
({turn:3,player:'emperor',id:`cache-${minimum}-${answer}`,asker:'atreides',minimum,answer,...extra});
const phase = (minimum:number,answer:boolean,extra:Partial<PhaseBidPromise> = {}):PhaseBidPromise =>
({turn:3,player:'emperor',event:`phase-${minimum}-${answer}`,asker:'atreides',minimum,answer,...extra});
const input = (extra:Partial<JointMarketEarlyBidInput> = {}):JointMarketEarlyBidInput => ({
context,native:[],early:[],phase:[],opportunity:{...context,minimum:1,maximum:10},
cashAvailable:10,aidAvailable:0,cacheMaximum:10,freeSlots:2,marketEntrySlots:1,marketWinSlots:1,...extra,
});
void test('a native Yes and waiting cache Yes reserve independent purchases without any phase receipt',() => {
const result = quoteJointMarketEarlyBids(input({native:[native(6,true)],early:[early(4,true)]}));
assert.equal(result.nativeRequired,true); assert.equal(result.earlyRequired,true); assert.equal(result.phaseRequired,false);
assert.equal(result.canPass,false);
assert.deepEqual(result.market,{minimum:6,maximum:6,allyPayment:0});
assert.equal(result.marketForPhase,null); assert.equal(result.marketForCache,null);
});
void test('all three ledgers intersect their own Yes and No bounds',() => {
const result = quoteJointMarketEarlyBids(input({
native:[native(4,true),native(6,false)],early:[early(4,true),early(6,false)],
phase:[phase(5,true),phase(7,false)],
}));
assert.deepEqual(result.market,{minimum:4,maximum:5,allyPayment:0});
assert.deepEqual(result.marketForPhase,{minimum:5,maximum:5,allyPayment:0});
assert.deepEqual(result.marketForCache,{minimum:4,maximum:5,allyPayment:0});
assert.equal(result.canPass,false);
const blocked = quoteJointMarketEarlyBids(input({native:[native(4,true)],early:[early(4,true)],phase:[phase(4,false)]}));
assert.equal(blocked.market,null); assert.equal(blocked.canPass,false);
});
void test('an unaffordable native and cache pair cannot borrow an assumed refund',() => {
const result = quoteJointMarketEarlyBids(input({native:[native(7,true)],early:[early(4,true)]}));
assert.equal(result.market,null); assert.equal(result.canPass,false);
const aided = quoteJointMarketEarlyBids(input({native:[native(7,true)],early:[early(4,true)],aidAvailable:1}));
assert.deepEqual(aided.market,{minimum:7,maximum:7,allyPayment:1});
});
void test('allied market funding preserves the personal cash required by a higher later phase bid',() => {
const result = quoteJointMarketEarlyBids(input({native:[native(4,true)],early:[early(2,true)],
phase:[phase(6,true)],cashAvailable:8,aidAvailable:2,cacheMaximum:8}));
assert.deepEqual(result.market,{minimum:4,maximum:8,allyPayment:0});
assert.deepEqual(result.marketForPhase,{minimum:6,maximum:8,allyPayment:0});
assert.deepEqual(result.marketForCache,{minimum:4,maximum:4,allyPayment:2});
const noAid = quoteJointMarketEarlyBids(input({native:[native(4,true)],early:[early(2,true)],
phase:[phase(6,true)],cashAvailable:8,aidAvailable:0,cacheMaximum:8}));
assert.equal(noAid.marketForCache,null);
});
void test('paid self-retention needs no incoming hand slot but another buyer does',() => {
const common = {native:[native(6,true)],early:[early(4,true)],freeSlots:1};
const seller = quoteJointMarketEarlyBids(input({...common,marketEntrySlots:0,marketWinSlots:0}));
assert.deepEqual(seller.market,{minimum:6,maximum:6,allyPayment:0});
const other = quoteJointMarketEarlyBids(input(common));
assert.equal(other.market,null);
});
void test('a Harkonnen market win reserves its potential bonus before the later cache',() => {
const common = {native:[native(4,true)],early:[early(4,true)],marketEntrySlots:1,marketWinSlots:2};
const two = quoteJointMarketEarlyBids(input({...common,freeSlots:2}));
assert.equal(two.market,null);
const three = quoteJointMarketEarlyBids(input({...common,freeSlots:3}));
assert.deepEqual(three.market,{minimum:4,maximum:6,allyPayment:0});
const noCache = quoteJointMarketEarlyBids(input({native:[native(4,true)],freeSlots:1,
marketEntrySlots:1,marketWinSlots:2}));
assert.deepEqual(noCache.market,{minimum:4,maximum:10,allyPayment:0},
'After the only required bid, an unavailable bonus slot does not prevent that bid');
});
void test('individual native Yes receipts can be re-quoted against all live No caps',() => {
const low = native(4,true), high = native(8,true), cap = native(9,false);
const common = {early:[early(2,true)],cashAvailable:9,cacheMaximum:9};
const both = quoteJointMarketEarlyBids(input({...common,native:[low,high,cap]}));
assert.equal(both.market,null);
const onlyLow = quoteJointMarketEarlyBids(input({...common,native:[low,cap]}));
assert.deepEqual(onlyLow.market,{minimum:4,maximum:7,allyPayment:0});
const onlyHigh = quoteJointMarketEarlyBids(input({...common,native:[high,cap]}));
assert.equal(onlyHigh.market,null);
});
void test('a cache No can leave a phase Yes for another actually proven auction',() => {
const result = quoteJointMarketEarlyBids(input({native:[native(4,false)],early:[early(4,false)],phase:[phase(6,true)]}));
assert.equal(result.nativeRequired,false); assert.equal(result.canPass,true);
assert.deepEqual(result.market,{minimum:1,maximum:3,allyPayment:0});
assert.equal(result.marketForPhase,null); assert.equal(result.marketForCache,null);
assert.equal(result.phaseCacheAfterPass,null);
});
void test('receipts from other seats, turns and finished events do not constrain the quote',() => {
const result = quoteJointMarketEarlyBids(input({
native:[native(4,true),native(1,false,{id:'old-lot',event:'old'}),native(1,false,{id:'done',fulfilled:true})],
early:[early(2,true),early(1,false,{id:'other',player:'richese'}),early(1,false,{id:'bound',boundEvent:'cache'})],
phase:[phase(5,true),phase(1,false,{event:'old-turn',turn:2}),phase(1,false,{event:'released',released:true})],
}));
assert.deepEqual(result.market,{minimum:4,maximum:8,allyPayment:0});
assert.deepEqual(result.marketForPhase,{minimum:5,maximum:8,allyPayment:0});
});
void test('invalid or stale opportunity and resource inputs fail closed',() => {
for (const cashAvailable of [-1,0.5,Number.NaN,Infinity,Number.MAX_SAFE_INTEGER+1])
assert.throws(() => quoteJointMarketEarlyBids(input({cashAvailable})));
assert.throws(() => quoteJointMarketEarlyBids(input({marketEntrySlots:2,marketWinSlots:1})));
assert.throws(() => quoteJointMarketEarlyBids(input({opportunity:{...context,event:'other',minimum:1,maximum:10}})));
const noOpportunity = quoteJointMarketEarlyBids(input({native:[native(1,false)],opportunity:null}));
assert.equal(noOpportunity.market,null); assert.equal(noOpportunity.canPass,true);
});
@@ -61,7 +61,7 @@ function market(game:Game, f:TruthtranceRichesePromisesFixture, card:string, met
return game;
}
void test('Advanced current Black Market bid question cannot strand a waiting early cache Yes', () => {
void test('Advanced current Black Market answer cannot strand a waiting early cache Yes', () => {
const f = source();
let game = ask(f.game,f.f,f.f.truth,f.f.emperor,'earlyRicheseBid',6,'yes');
const early = game.earlyRicheseBidPromises?.find(row => row.player === f.f.emperor); assert.ok(early);
@@ -70,11 +70,16 @@ void test('Advanced current Black Market bid question cannot strand a waiting ea
const lot = game.richeseAuction!, event = lot.event;
game = act(game,f.f.asker,{type:'card',card:f.second});
game = advance(game,state => state.truthtrance?.stage === 'ask');
const before = structuredClone(game);
const question = {kind:'richeseBid',target:f.f.emperor,turn:game.turn,event,minimum:6};
assert.throws(() => act(game,f.f.asker,{type:'truthAsk',question}),
'The separately asked current-lot promise awaits a three-ledger planner');
assert.deepEqual(game,before,'Rejected question cannot mutate the auction, question or cache receipt');
game = act(game,f.f.asker,{type:'truthAsk',question});
const choices = viewGame(game,f.f.emperor).truthRicheseBidAnswers;
assert.ok(!choices?.includes('yes'),'The two six-spice purchases cannot both be funded from ten');
assert.ok(choices?.includes('no'),'A lower or declined current bid can preserve the cache promise');
const before = structuredClone(game);
assert.throws(() => act(game,f.f.emperor,{type:'truthAnswer',answer:'yes'}));
assert.deepEqual(game,before,'Rejected answer cannot mutate the auction, question or cache receipt');
game = passTruthRicheseFreshDiscard(act(game,f.f.emperor,{type:'truthAnswer',answer:'no'}));
assert.ok(game.richeseBidPromises?.some(row => row.player === f.f.emperor && row.event === event && !row.answer));
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === early.id && !row.boundEvent && !row.released));
assert.equal(player(game,f.f.emperor).spice,10);
assert.deepEqual(inventory(game),f.f.originalCards);
@@ -0,0 +1,99 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { advanceAuctionClock, synchronizeAuctionClock, viewGame, type Game } from '../game/engine';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
/** Original Advanced R/A/E public start. The second original Truthtrance and
* original Semuta move from unopened zones. A real Semuta claim returns the
* first discarded Truthtrance for the third question; no player purse, phase,
* auction, clock or commitment is installed by the fixture. */
function source() {
const f=fixture({advanced:true}); let game:Game=structuredClone(f.earlySource);
const truthAt=game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(truthAt >= 0); const [second]=game.deck.splice(truthAt,1);
player(game,f.asker).hand.push(second);
const semutaAt=game.richeseCache!.findIndex(card => card.effect === 'semutaDrug');
assert.ok(semutaAt >= 0); const [semuta]=game.richeseCache!.splice(semutaAt,1);
player(game,f.richese).hand.push(semuta);
assert.deepEqual(inventory(game),f.originalCards);
function ask(asker:string,card:string,question:Record<string,unknown>,claim=false) {
game=act(game,asker,{type:'card',card});
game=advance(game,state => state.truthtrance?.stage === 'ask');
game=act(game,asker,{type:'truthAsk',question});
game=act(game,f.emperor,{type:'truthAnswer',answer:'yes'});
if (!claim) { game=passTruthRicheseFreshDiscard(game); return; }
const pending=game.pendingTreacheryDiscard; assert.ok(pending?.reaction);
assert.ok(viewGame(game,f.richese).semutaReaction?.canCommit);
game=act(game,f.richese,{type:'semutaCommit',event:pending.batch.event});
if (game.pendingTreacheryDiscard?.reaction?.stage === 'select')
game=act(game,f.richese,{type:'semutaSelect',event:pending.batch.event,card});
assert.ok(player(game,f.richese).hand.some(item => item.id === card));
}
ask(f.asker,f.truth,{kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:4},true);
ask(f.asker,second.id,{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:6});
const phase=game.phaseAnyBidPromises?.find(row => row.player === f.emperor && row.answer); assert.ok(phase);
const early=game.earlyRicheseBidPromises?.find(row => row.player === f.emperor && row.answer); assert.ok(early);
game=advance(game,state => state.decision?.kind === 'richeseBlackMarket');
game=act(game,f.richese,{type:'decision',event:game.richeseBidding!.event,card:f.targetCard,
method:'onceAround',direction:'clockwise'});
while (game.response) {
const actor=game.players.find(seat => !game.response!.passed.includes(seat.id)); assert.ok(actor);
game=act(game,actor.id,{type:'passResponse'});
}
game=advance(game,state => clean(state) && state.richeseAuction?.active === f.emperor);
const lot=game.richeseAuction; assert.ok(lot && lot.source === 'blackMarket' && lot.clockVersion === 1);
ask(f.richese,f.truth,{kind:'richeseBid',target:f.emperor,turn:game.turn,event:lot.event,minimum:4});
const native=game.richeseBidPromises?.find(row => row.player === f.emperor && row.event === lot.event && row.answer);
assert.ok(native); assert.deepEqual(inventory(game),f.originalCards);
return {game,f,event:lot.event,phase,early,native};
}
void test('Advanced Once Around market clock executes the shared three-way guide once',() => {
const s=source(), view=viewGame(s.game,s.f.emperor);
const guide=view.richeseBidPromiseGuide?.action; assert.ok(guide && view.phaseAnyBidGuide);
assert.deepEqual(guide,view.phaseAnyBidGuide.action);
assert.equal(guide.type,'richeseBid'); assert.equal(guide.event,s.event); assert.equal(guide.amount,4);
assert.equal(guide.richeseBidPromiseId,s.native.id);
assert.equal(guide.earlyRicheseBidPromiseId,s.early.id);
assert.equal(guide.phaseAnyBidPromiseEvent,s.phase.event);
assert.equal(player(s.game,s.f.emperor).spice,10);
const armed=synchronizeAuctionClock(s.game,1_000,'advanced-three-ledger');
const expired=advanceAuctionClock(armed,11_000,'advanced-three-ledger');
assert.equal(expired.richeseAuction?.event,s.event);
assert.equal(expired.richeseAuction?.bidder,s.f.emperor);
assert.equal(expired.richeseAuction?.bid,4);
assert.equal(expired.richeseFunding?.[s.f.emperor]?.amount,4);
assert.equal(player(expired,s.f.emperor).spice,10,'A bid is reserved before payment');
assert.ok(expired.richeseBidPromises?.some(row => row.id === s.native.id && row.fulfilled));
assert.ok(expired.phaseAnyBidPromises?.some(row => row.event === s.phase.event && row.fulfilled));
assert.ok(expired.earlyRicheseBidPromises?.some(row => row.id === s.early.id && !row.boundEvent && !row.released));
const again=advanceAuctionClock(expired,11_000,'advanced-three-ledger');
assert.equal(again.richeseAuction?.bid,4);
assert.equal(again.richeseAuction?.acted.filter(id => id === s.f.emperor).length,1);
assert.equal(again.richeseFunding?.[s.f.emperor]?.amount,4);
let game=advance(again,state => player(state,s.f.emperor).hand.some(card => card.id === s.f.targetCard));
assert.equal(player(game,s.f.emperor).spice,6);
game=advance(game,state => clean(state) && state.richeseAuction?.source === 'cache' &&
state.richeseAuction.method === 'silent' && !state.richeseAuction.outcome,[],{position:'first',method:'silent'});
assert.equal(game.earlyRicheseBidPromises?.find(row => row.id === s.early.id)?.boundEvent,game.richeseAuction!.event);
const cache=viewGame(game,s.f.emperor).richeseBidPromiseGuide?.action; assert.ok(cache);
assert.equal(cache.amount,6);
game=act(game,s.f.emperor,cache);
assert.ok(game.richeseBidPromises?.some(row => row.id === s.early.id && row.fulfilled));
const cacheCard=game.richeseAuction!.cardId;
game=advance(game,state => player(state,s.f.emperor).hand.some(card => card.id === cacheCard),
[],{position:'first',method:'silent'});
assert.equal(player(game,s.f.emperor).spice,0);
assert.deepEqual(inventory(game),s.f.originalCards);
});
@@ -0,0 +1,131 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import { viewGame, type Action, type Game } from '../game/engine';
import { PhaseAnyBidGuideButton, PhaseAnyBidPromises } from '../components/phase-any-bid-promises';
import { RicheseBidPromiseGuide, RicheseBidPromisePanel } from '../components/richese-bid-promise-panel';
import { MixedRicheseBidPromises } from '../components/mixed-richese-bid-promises';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
type Props = {children?: ReactNode; [key:string]:unknown};
type Kind = 'richeseBid' | 'mixedRicheseBid';
const elements = (node:ReactNode):ReactElement<Props>[] => Array.isArray(node) ? node.flatMap(elements) :
!isValidElement<Props>(node) ? [] : [node,...elements(node.props.children)];
/** A genuine Advanced public start. Move the second original Truthtrance and
* Semuta from unopened zones, then actually reclaim the first discarded Truth
* with Semuta to ask the third question. No wallet, bid or receipt is staged. */
function source(method:'silent'|'onceAround',kind:Kind) {
const f=fixture({advanced:true}); let game:Game=structuredClone(f.earlySource);
const truthAt=game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(truthAt >= 0); const [second]=game.deck.splice(truthAt,1);
player(game,f.asker).hand.push(second);
const semutaAt=game.richeseCache!.findIndex(card => card.effect === 'semutaDrug');
assert.ok(semutaAt >= 0); const [semuta]=game.richeseCache!.splice(semutaAt,1);
player(game,f.richese).hand.push(semuta);
assert.deepEqual(inventory(game),f.originalCards);
function ask(asker:string,card:string,question:Record<string,unknown>,claim=false) {
game=act(game,asker,{type:'card',card});
game=advance(game,state => state.truthtrance?.stage === 'ask');
game=act(game,asker,{type:'truthAsk',question});
game=act(game,f.emperor,{type:'truthAnswer',answer:'yes'});
if (!claim) { game=passTruthRicheseFreshDiscard(game); return; }
const pending=game.pendingTreacheryDiscard; assert.ok(pending?.reaction);
assert.equal(viewGame(game,f.richese).semutaReaction?.canCommit,true);
game=act(game,f.richese,{type:'semutaCommit',event:pending.batch.event});
if (game.pendingTreacheryDiscard?.reaction?.stage === 'select')
game=act(game,f.richese,{type:'semutaSelect',event:pending.batch.event,card});
assert.ok(player(game,f.richese).hand.some(item => item.id === card));
}
ask(f.asker,f.truth,{kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:4},true);
ask(f.asker,second.id,{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:6});
game=advance(game,state => state.decision?.kind === 'richeseBlackMarket');
game=act(game,f.richese,{type:'decision',event:game.richeseBidding!.event,card:f.targetCard,method,
...(method === 'onceAround' ? {direction:'clockwise'} : {})});
while (game.response) {
const actor=game.players.find(seat => !game.response!.passed.includes(seat.id)); assert.ok(actor);
game=act(game,actor.id,{type:'passResponse'});
}
if (method === 'onceAround') game=advance(game,state => clean(state) && state.richeseAuction?.active === f.emperor);
const lot=game.richeseAuction!;
assert.equal(lot.source,'blackMarket');
const question=kind === 'richeseBid' ? {kind,target:f.emperor,turn:game.turn,event:lot.event,minimum:4} :
{kind,target:f.emperor,turn:game.turn,event:lot.event,mixed:{kind:'and',terms:[
{kind:'fact',fact:{kind:'spice',compare:'gte',value:10}},{kind:'action',action:{minimum:4}},
]}};
ask(f.richese,f.truth,question);
assert.deepEqual(inventory(game),f.originalCards);
return {game,f};
}
for (const method of ['onceAround','silent'] as const) for (const kind of ['richeseBid','mixedRicheseBid'] as const) void test(
`Advanced ${method} ${kind} three-way guides share a live owner-bound action`,() => {
const {game,f}=source(method,kind), view=viewGame(game,f.emperor), sent:Action[]=[];
assert.ok(view.phaseAnyBidGuide && view.richeseBidPromiseGuide);
assert.deepEqual(view.phaseAnyBidGuide.action,view.richeseBidPromiseGuide.action);
const action=view.phaseAnyBidGuide.action, early=view.ownEarlyRicheseBidPromises.find(row => !row.boundEvent && !row.released);
const phase=view.phaseAnyBidPromises.find(row => !row.fulfilled && !row.released);
assert.ok(early && phase); assert.equal(action.type,'richeseBid'); assert.equal(action.amount,4);
assert.equal(action.earlyRicheseBidPromiseId,early.id);
assert.equal(action.phaseAnyBidPromiseEvent,phase.event);
assert.equal(action.phaseAnyBidLotEvent,view.richeseAuction!.event);
const phaseProps={game:view,busy:false,send(value:Action){sent.push(value);}};
const localProps={game:view,promises:view.richeseBidPromises,guide:view.richeseBidPromiseGuide,busy:false,
act(value:Action){sent.push(value);}};
const mixedProps={game:view,busy:false,send(value:Action){sent.push(value);}};
assert.match(renderToStaticMarkup(createElement(PhaseAnyBidPromises,phaseProps)),/data-testid="phase-any-bid-guide"/);
const phaseButton=PhaseAnyBidGuideButton(phaseProps); assert.ok(phaseButton);
const html=kind === 'richeseBid' ? renderToStaticMarkup(createElement(RicheseBidPromisePanel,localProps)) :
renderToStaticMarkup(createElement(MixedRicheseBidPromises,mixedProps));
assert.match(html,kind === 'richeseBid' ? /Your (?:Once Around|Silent) bid promises/ : /Your mixed Richese bid promises/);
const localButton=kind === 'richeseBid' ? RicheseBidPromiseGuide(localProps) :
elements(MixedRicheseBidPromises(mixedProps)).find(node => node.props['data-testid'] === 'mixed-richese-bid-promise-guide');
assert.ok(localButton);
const clickPhase=() => phaseButton.props.onClick();
const clickLocal=() => (localButton.props.onClick as () => void)();
clickPhase(); clickLocal(); assert.deepEqual(sent,[action,action]);
phaseProps.busy=true; localProps.busy=true; mixedProps.busy=true;
clickPhase(); clickLocal(); assert.equal(sent.length,2);
phaseProps.busy=false; localProps.busy=false; mixedProps.busy=false;
const event=view.richeseAuction!.event; view.richeseAuction!.event='stale-market';
clickPhase(); clickLocal(); assert.equal(sent.length,2); view.richeseAuction!.event=event;
const acted=[...view.richeseAuction!.acted];
view.richeseAuction!.acted.push('changed-public-seat');
clickPhase(); clickLocal(); assert.equal(sent.length,2,'Same-event public auction progress invalidates both callbacks');
view.richeseAuction!.acted.splice(0,view.richeseAuction!.acted.length,...acted);
if (method === 'silent') {
const ownBid=view.richeseAuction!.ownBid; view.richeseAuction!.ownBid=1;
clickPhase(); clickLocal(); assert.equal(sent.length,2,'A changed own Silent submission invalidates both callbacks');
view.richeseAuction!.ownBid=ownBid;
}
phase.fulfilled=true; clickPhase(); clickLocal(); assert.equal(sent.length,2); phase.fulfilled=false;
const local=kind === 'richeseBid' ? view.richeseBidPromises.find(row => row.id === action.richeseBidPromiseId) :
view.mixedRicheseBidPromises.find(row => row.id === action.richeseBidPromiseId);
assert.ok(local); local.released=true; clickPhase(); clickLocal(); assert.equal(sent.length,2); local.released=false;
early.released=true; clickPhase(); clickLocal(); assert.equal(sent.length,2,'Closing the waiting cache answer invalidates both callbacks');
early.released=false; early.boundEvent='different-cache';
clickPhase(); clickLocal(); assert.equal(sent.length,2,'Binding the cache to a different event invalidates both callbacks');
delete early.boundEvent;
for (const difficulty of DIFFICULTIES) {
const bot=viewGame(game,f.emperor); bot.players.find(row => row.id === f.emperor)!.bot=difficulty;
const selected=botActions(bot)[0]; assert.deepEqual(selected,action,difficulty);
assert.doesNotThrow(() => act(game,f.emperor,selected),difficulty);
}
const applied=act(game,f.emperor,action);
assert.ok(applied.phaseAnyBidPromises?.some(row => row.event === phase.event && row.fulfilled));
assert.ok(applied.richeseBidPromises?.some(row => row.id === action.richeseBidPromiseId && row.fulfilled));
assert.ok(applied.earlyRicheseBidPromises?.some(row => row.id === early.id && !row.boundEvent && !row.released));
assert.deepEqual(inventory(applied),f.originalCards);
});
@@ -0,0 +1,242 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Action, type Game } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
type TruthtranceRichesePromisesFixture,
} from './fixture-truthtrance-richese-promises';
type Method = 'silent' | 'onceAround';
type EarlyAnswer = 'yes' | 'no';
type Kind = 'earlyRicheseBid' | 'phaseAnyBid';
/** Original public Advanced R/A/E setup. The original second Truthtrance moves
* from the unopened deck to Atreides and the original Semuta from Richese's
* cache to its hand. The actual first Truthtrance is reclaimed by Richese via
* Semuta, then played as the third question; no receipt, wallet, bid, auction,
* phase or card is invented. */
function source() {
const f = fixture({advanced:true}), game = structuredClone(f.earlySource);
const at = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(at >= 0); const [second] = game.deck.splice(at,1);
player(game,f.asker).hand.push(second);
const semutaAt = game.richeseCache!.findIndex(card => card.effect === 'semutaDrug');
assert.ok(semutaAt >= 0); const [semuta] = game.richeseCache!.splice(semutaAt,1);
player(game,f.richese).hand.push(semuta);
assert.deepEqual(inventory(game),f.originalCards);
return {f,game,second:second.id,semuta:semuta.id};
}
function openQuestion(game:Game, asker:string, card:string) {
game = act(game,asker,{type:'card',card});
return advance(game,state => state.truthtrance?.stage === 'ask');
}
function answerEarly(game:Game, f:TruthtranceRichesePromisesFixture, card:string,
kind:Kind, minimum:number, answer:EarlyAnswer, claim:boolean) {
game = openQuestion(game,f.asker,card);
game = act(game,f.asker,{type:'truthAsk',question:{kind,target:f.emperor,turn:game.turn,minimum}});
const view = viewGame(game,f.emperor);
const options = kind === 'earlyRicheseBid' ? view.truthEarlyRicheseBidAnswers : view.truthPhaseAnyBidAnswers;
assert.ok(options?.includes(answer),`${kind} ${answer} must have a funded native witness`);
game = act(game,f.emperor,{type:'truthAnswer',answer});
if (!claim) return passTruthRicheseFreshDiscard(game);
const pending = game.pendingTreacheryDiscard; assert.ok(pending?.reaction);
assert.ok(viewGame(game,f.richese).semutaReaction?.canCommit);
game = act(game,f.richese,{type:'semutaCommit',event:pending.batch.event});
assert.ok(player(game,f.richese).hand.some(item => item.id === card));
return game;
}
function openMarket(game:Game,f:TruthtranceRichesePromisesFixture,method:Method) {
game = advance(game,state => state.decision?.kind === 'richeseBlackMarket');
assert.ok(player(game,f.richese).hand.some(card => card.id === f.targetCard));
game = act(game,f.richese,{type:'decision',event:game.richeseBidding!.event,
card:f.targetCard,method,...(method === 'onceAround' ? {direction:'clockwise'} : {})});
while (game.response) {
const actor = game.players.find(seat => !game.response!.passed.includes(seat.id)); assert.ok(actor);
game = act(game,actor.id,{type:'passResponse'});
}
assert.equal(game.richeseAuction?.source,'blackMarket');
assert.equal(game.richeseAuction?.method,method);
return game;
}
function prebound(method:Method, first:Kind, early:EarlyAnswer, earlyMinimum:number, phaseMinimum:number) {
const s = source(), secondKind:Kind = first === 'earlyRicheseBid' ? 'phaseAnyBid' : 'earlyRicheseBid';
const value = (kind:Kind) => kind === 'earlyRicheseBid' ? early : 'yes';
const minimum = (kind:Kind) => kind === 'earlyRicheseBid' ? earlyMinimum : phaseMinimum;
let game = answerEarly(s.game,s.f,s.f.truth,first,minimum(first),value(first),true);
assert.ok(game.discard.some(card => card.id === s.semuta));
game = answerEarly(game,s.f,s.second,secondKind,minimum(secondKind),value(secondKind),false);
const earlyRow = game.earlyRicheseBidPromises?.find(row => row.player === s.f.emperor); assert.ok(earlyRow);
const phase = game.phaseAnyBidPromises?.find(row => row.player === s.f.emperor); assert.ok(phase);
game = openMarket(game,s.f,method);
assert.equal(player(game,s.f.emperor).spice,10);
assert.deepEqual(inventory(game),s.f.originalCards);
return {...s,game,earlyRow,phase};
}
function askCurrent(game:Game,f:TruthtranceRichesePromisesFixture,minimum:number) {
const lot = game.richeseAuction; assert.ok(lot);
assert.ok(!lot.acted.includes(f.emperor),'Respondent must retain its original market opportunity');
game = openQuestion(game,f.richese,f.truth);
game = act(game,f.richese,{type:'truthAsk',question:{kind:'richeseBid',target:f.emperor,
turn:game.turn,event:lot.event,minimum}});
return game;
}
function reject(game:Game,actor:string,action:Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before,'An invalid action must retain both physical and promise state');
}
function bindCurrent(game:Game,f:TruthtranceRichesePromisesFixture,answer:EarlyAnswer) {
assert.ok(viewGame(game,f.emperor).truthRicheseBidAnswers?.includes(answer),
`A funded current market ${answer} must be available`);
game = passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer}));
const native = game.richeseBidPromises?.find(row => row.player === f.emperor && row.event === game.richeseAuction?.event);
assert.ok(native); assert.equal(native.answer,answer === 'yes');
return {game,native};
}
function reachMarketBid(game:Game,f:TruthtranceRichesePromisesFixture,method:Method) {
return method === 'silent' ? game : advance(game,state => clean(state) && state.richeseAuction?.active === f.emperor);
}
function finishMarket(game:Game,method:Method,event:string) {
while (game.richeseAuction?.event === event && !game.richeseAuction.outcome) {
const lot = game.richeseAuction;
const actor = method === 'silent' ? lot.eligible.find(id => !Object.hasOwn(lot.sealed,id)) : lot.active;
assert.ok(actor);
game = act(game,actor,{type:'richeseBid',event,amount:method === 'silent' ? 0 : null,allyPayment:0});
}
return game;
}
for (const method of ['silent','onceAround'] as const)
for (const first of ['earlyRicheseBid','phaseAnyBid'] as const) void test(
`Advanced ${method} ${first} first: real market Yes and phase Yes reserve the early cache Yes`, () => {
const s = prebound(method,first,'yes',6,4);
let game = askCurrent(s.game,s.f,4);
const current = bindCurrent(game,s.f,'yes'); game = reachMarketBid(current.game,s.f,method);
const lot = game.richeseAuction!, view = viewGame(game,s.f.emperor);
const nativeGuide = view.richeseBidPromiseGuide?.action, phaseGuide = view.phaseAnyBidGuide?.action;
assert.ok(nativeGuide && phaseGuide); assert.deepEqual(nativeGuide,phaseGuide);
assert.equal(nativeGuide.type,'richeseBid'); assert.equal(nativeGuide.event,lot.event);
assert.equal(nativeGuide.amount,4); assert.equal(nativeGuide.richeseBidPromiseId,current.native.id);
assert.equal(nativeGuide.earlyRicheseBidPromiseId,s.earlyRow.id);
assert.equal(nativeGuide.phaseAnyBidPromiseEvent,s.phase.event);
assert.equal(nativeGuide.phaseAnyBidLotEvent,lot.event);
for (const bad of [
{...nativeGuide,richeseBidPromiseId:'stale-native'},
{...nativeGuide,earlyRicheseBidPromiseId:'stale-early'},
{...nativeGuide,phaseAnyBidPromiseEvent:'stale-phase'},
{...nativeGuide,event:'stale-lot'},
]) reject(game,s.f.emperor,bad);
reject(game,s.f.emperor,{type:'richeseBid',event:lot.event,amount:5,allyPayment:0});
for (const difficulty of DIFFICULTIES) {
const bot = viewGame(game,s.f.emperor); bot.players.find(row => row.id === s.f.emperor)!.bot = difficulty;
const action = botActions(bot)[0]; assert.ok(action,difficulty);
assert.doesNotThrow(() => act(game,s.f.emperor,action),difficulty);
}
game = act(game,s.f.emperor,nativeGuide);
assert.equal(player(game,s.f.emperor).spice,10,'The bid is reserved, not prepaid');
assert.ok(game.richeseBidPromises?.some(row => row.id === current.native.id && row.fulfilled));
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && row.fulfilled));
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === s.earlyRow.id && !row.boundEvent && !row.released));
if (method === 'silent') assert.equal(viewGame(game,s.f.asker).richeseAuction?.revealedBids,null);
game = finishMarket(game,method,lot.event);
game = advance(game,state => player(state,s.f.emperor).hand.some(card => card.id === s.f.targetCard));
assert.equal(player(game,s.f.emperor).spice,6);
game = advance(game,state => clean(state) && state.richeseAuction?.source === 'cache' &&
state.richeseAuction.method === 'silent' && !state.richeseAuction.outcome,[],{position:'first',method:'silent'});
assert.equal(game.earlyRicheseBidPromises?.find(row => row.id === s.earlyRow.id)?.boundEvent,game.richeseAuction!.event);
const cache = viewGame(game,s.f.emperor).richeseBidPromiseGuide?.action; assert.ok(cache);
assert.equal(cache.amount,6);
game = act(game,s.f.emperor,cache);
assert.ok(game.richeseBidPromises?.some(row => row.id === s.earlyRow.id && row.fulfilled));
const cacheCard = game.richeseAuction!.cardId;
game = advance(game,state => player(state,s.f.emperor).hand.some(card => card.id === cacheCard),
[],{position:'first',method:'silent'});
assert.equal(player(game,s.f.emperor).spice,0);
assert.deepEqual(inventory(game),s.f.originalCards);
});
for (const method of ['silent','onceAround'] as const) void test(
`Advanced ${method}: unfunded market Yes is unavailable, while No preserves a real phase bid`, () => {
const s = prebound(method,'earlyRicheseBid','yes',6,4);
let game = askCurrent(s.game,s.f,6);
const answers = viewGame(game,s.f.emperor).truthRicheseBidAnswers;
assert.ok(!answers?.includes('yes'),'Market 6 and cache 6 cannot both be funded from 10');
assert.ok(answers?.includes('no'));
reject(game,s.f.emperor,{type:'truthAnswer',answer:'yes'});
const current = bindCurrent(game,s.f,'no'); game = reachMarketBid(current.game,s.f,method);
const lot = game.richeseAuction!, guide = viewGame(game,s.f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'richeseBid'); assert.equal(guide.amount,4);
assert.equal(guide.richeseBidPromiseId,current.native.id);
assert.equal(guide.earlyRicheseBidPromiseId,s.earlyRow.id);
game = act(game,s.f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && row.fulfilled));
assert.ok(game.richeseBidPromises?.some(row => row.id === current.native.id && row.fulfilled));
game = finishMarket(game,method,lot.event);
game = advance(game,state => player(state,s.f.emperor).hand.some(card => card.id === s.f.targetCard));
game = advance(game,state => clean(state) && state.richeseAuction?.source === 'cache' &&
state.richeseAuction.method === 'silent' && !state.richeseAuction.outcome,[],{position:'first',method:'silent'});
const cache = viewGame(game,s.f.emperor).richeseBidPromiseGuide?.action; assert.ok(cache);
assert.equal(cache.amount,6);
game = act(game,s.f.emperor,cache);
assert.ok(game.richeseBidPromises?.some(row => row.id === s.earlyRow.id && row.fulfilled));
assert.deepEqual(inventory(game),s.f.originalCards);
});
for (const method of ['silent','onceAround'] as const) void test(
`Advanced ${method}: current and early No retain a separately funded later phase Yes`, () => {
const s = prebound(method,'phaseAnyBid','no',4,6);
let game = askCurrent(s.game,s.f,6);
const current = bindCurrent(game,s.f,'no'); game = reachMarketBid(current.game,s.f,method);
const lot = game.richeseAuction!, guide = viewGame(game,s.f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'richeseBid');
assert.ok(guide.amount === null || typeof guide.amount === 'number' && guide.amount < 6);
assert.equal(guide.richeseBidPromiseId,current.native.id);
assert.equal(guide.earlyRicheseBidPromiseId,s.earlyRow.id);
game = act(game,s.f.emperor,guide);
assert.ok(game.richeseBidPromises?.some(row => row.id === current.native.id && row.fulfilled));
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && !row.fulfilled && !row.released));
game = finishMarket(game,method,lot.event);
game = advance(game,state => clean(state) && !!state.auction && state.auction.active === s.f.emperor,
[],{position:'first',method:'silent'});
assert.ok(game.richeseBidPromises?.some(row => row.id === s.earlyRow.id && row.fulfilled));
const ordinary = viewGame(game,s.f.emperor).phaseAnyBidGuide?.action; assert.ok(ordinary);
assert.equal(ordinary.type,'bid'); assert.equal(ordinary.amount,6);
game = act(game,s.f.emperor,ordinary);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && row.fulfilled));
assert.deepEqual(inventory(game),s.f.originalCards);
});
void test('Advanced current Yes with an early Yes needs both market and cache funding even without a phase promise', () => {
const s = source();
let game = answerEarly(s.game,s.f,s.f.truth,'earlyRicheseBid',6,'yes',true);
game = openMarket(game,s.f,'silent');
game = askCurrent(game,s.f,4);
const current = bindCurrent(game,s.f,'yes'); game = current.game;
const early = game.earlyRicheseBidPromises?.find(row => row.player === s.f.emperor); assert.ok(early);
const lot = game.richeseAuction!, guide = viewGame(game,s.f.emperor).richeseBidPromiseGuide?.action;
assert.ok(guide); assert.equal(guide.amount,4); assert.equal(guide.richeseBidPromiseId,current.native.id);
assert.equal(guide.earlyRicheseBidPromiseId,early.id);
reject(game,s.f.emperor,{...guide,earlyRicheseBidPromiseId:'stale-early'});
reject(game,s.f.emperor,{type:'richeseBid',event:lot.event,amount:5,allyPayment:0});
game = act(game,s.f.emperor,guide);
assert.ok(game.richeseBidPromises?.some(row => row.id === current.native.id && row.fulfilled));
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === early.id && !row.released));
assert.deepEqual(inventory(game),s.f.originalCards);
});
@@ -0,0 +1,165 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Action, type Game } from '../game/engine';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
type TruthtranceRichesePromisesFixture,
} from './fixture-truthtrance-richese-promises';
type Method = 'silent' | 'onceAround';
type Kind = 'richeseBid' | 'mixedRicheseBid' | 'constantMixed';
/** Public Advanced R/A/E start with original unopened setup/Spice order. Move
* the second original Truth to Atreides, the original Semuta from the cache
* to Richese, and the original Nullentropy Box from the
* cache to Atreides. The actual Semuta reclaims the first used Truth; the
* actual two-spice Box search recovers Semuta for Atreides, who can claim
* Richese's later discard. No promise,
* bid, purse, reaction or physical card is fabricated. */
function source() {
const f = fixture({advanced:true}), game = structuredClone(f.earlySource);
const secondAt = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(secondAt >= 0); const [second] = game.deck.splice(secondAt,1);
player(game,f.asker).hand.push(second);
const take = (effect:string, owner:string) => {
const at = game.richeseCache!.findIndex(card => card.effect === effect); assert.ok(at >= 0);
const [card] = game.richeseCache!.splice(at,1); player(game,owner).hand.push(card); return card.id;
};
const semuta = take('semutaDrug',f.richese), box = take('nullentropyBox',f.asker);
assert.deepEqual(inventory(game),f.originalCards);
return {f,game,second:second.id,semuta,box};
}
function askPre(game:Game,f:TruthtranceRichesePromisesFixture,card:string,
kind:'phaseAnyBid'|'earlyRicheseBid',minimum:number) {
game = act(game,f.asker,{type:'card',card});
game = advance(game,state => state.truthtrance?.stage === 'ask');
game = act(game,f.asker,{type:'truthAsk',question:{kind,target:f.emperor,turn:game.turn,minimum}});
const view = viewGame(game,f.emperor);
const options = kind === 'phaseAnyBid' ? view.truthPhaseAnyBidAnswers : view.truthEarlyRicheseBidAnswers;
assert.ok(options?.includes('yes'));
return act(game,f.emperor,{type:'truthAnswer',answer:'yes'});
}
function parkedMarket(method:Method, kind:Kind) {
const s = source();
let game = askPre(s.game,s.f,s.f.truth,'phaseAnyBid',4);
const first = game.pendingTreacheryDiscard; assert.ok(first?.reaction);
assert.ok(viewGame(game,s.f.richese).semutaReaction?.canCommit,
JSON.stringify(viewGame(game,s.f.richese).semutaReaction));
game = act(game,s.f.richese,{type:'semutaCommit',event:first.batch.event});
assert.ok(player(game,s.f.richese).hand.some(card => card.id === s.f.truth));
assert.ok(game.discard.some(card => card.id === s.semuta));
// Recover the actual used Semuta with the actual Box and exact native cost.
const purse = player(game,s.f.asker).spice;
game = act(game,s.f.asker,{type:'card',card:s.box});
if (game.decision?.kind === 'nullentropy') {
assert.ok(game.pendingNullentropy);
game = act(game,s.f.asker,{type:'decision',event:game.pendingNullentropy.event,card:s.semuta});
}
game = passTruthRicheseFreshDiscard(game);
assert.equal(player(game,s.f.asker).spice,purse-2);
assert.ok(player(game,s.f.asker).hand.some(card => card.id === s.semuta));
assert.ok(game.discard.some(card => card.id === s.box));
game = passTruthRicheseFreshDiscard(askPre(game,s.f,s.second,'earlyRicheseBid',6));
const early = game.earlyRicheseBidPromises?.find(row => row.player === s.f.emperor); assert.ok(early);
const phase = game.phaseAnyBidPromises?.find(row => row.player === s.f.emperor); assert.ok(phase);
game = advance(game,state => state.decision?.kind === 'richeseBlackMarket');
assert.ok(player(game,s.f.richese).hand.some(card => card.id === s.f.targetCard));
game = act(game,s.f.richese,{type:'decision',event:game.richeseBidding!.event,
card:s.f.targetCard,method,...(method === 'onceAround' ? {direction:'clockwise'} : {})});
while (game.response) {
const actor = game.players.find(seat => !game.response!.passed.includes(seat.id)); assert.ok(actor);
game = act(game,actor.id,{type:'passResponse'});
}
const lot = game.richeseAuction; assert.ok(lot && lot.source === 'blackMarket');
game = act(game,s.f.richese,{type:'card',card:s.f.truth});
game = advance(game,state => state.truthtrance?.stage === 'ask');
const base = {target:s.f.emperor,turn:game.turn,event:lot.event};
const question = kind === 'richeseBid' ? {kind:'richeseBid',...base,minimum:4} :
{kind:'mixedRicheseBid',...base,mixed:{kind:kind === 'constantMixed' ? 'or' : 'and',terms:[
{kind:'fact',fact:{kind:'spice',compare:'gte',value:10}},
{kind:'action',action:{minimum:4}},
]}};
game = act(game,s.f.richese,{type:'truthAsk',question});
const view = viewGame(game,s.f.emperor);
const answers = kind === 'richeseBid' ? view.truthRicheseBidAnswers : view.truthMixedRicheseBidAnswers;
assert.ok(answers?.includes('yes'));
const parent = structuredClone({lot:game.richeseAuction,round:game.richeseBidding,
funding:game.richeseFunding,aid:game.aid,turn:game.turn,phase:game.phase,active:game.active,order:game.order});
game = act(game,s.f.emperor,{type:'truthAnswer',answer:'yes'});
const pending = game.pendingTreacheryDiscard; assert.ok(pending?.reaction);
assert.equal(pending.continuation.kind,'truthtranceDiscard');
assert.equal(pending.batch.entries[0].card.id,s.f.truth);
assert.ok(viewGame(game,s.f.asker).semutaReaction?.canCommit,
JSON.stringify(viewGame(game,s.f.asker).semutaReaction));
assert.deepEqual(inventory(game),s.f.originalCards);
return {...s,game,early,phase,lot:lot.event,pending:pending.batch.event,parent};
}
function reject(game:Game,actor:string,action:Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before);
}
for (const method of ['silent','onceAround'] as const)
for (const kind of ['richeseBid','mixedRicheseBid','constantMixed'] as const)
for (const claim of [false,true]) void test(
`Advanced ${method} ${kind} third answer: Semuta ${claim ? 'claim' : 'pass'} binds and resumes original ledgers`, () => {
const s = parkedMarket(method,kind);
const local = s.game.richeseBidPromises?.find(row => row.player === s.f.emperor && row.event === s.lot);
const mixed = s.game.mixedRicheseBidQuestions?.find(row => row.player === s.f.emperor && row.event === s.lot);
if (kind === 'constantMixed') {
assert.ok(mixed && !mixed.binding,'A true fact settles the expression without inventing a bid');
assert.equal(local,undefined);
} else {
assert.ok(local && local.answer);
if (kind === 'mixedRicheseBid') assert.ok(mixed?.binding);
}
const families: Array<'earlyRicheseBidPromises'|'phaseAnyBidPromises'|'richeseBidPromises'|'mixedRicheseBidQuestions'> =
['earlyRicheseBidPromises','phaseAnyBidPromises'];
if (local) families.push('richeseBidPromises');
if (mixed) families.push('mixedRicheseBidQuestions');
for (const family of families) {
const tampered = structuredClone(s.game);
if (family === 'mixedRicheseBidQuestions') tampered.mixedRicheseBidQuestions![0].answer = false;
else tampered[family]![0].minimum++;
assert.throws(() => act(tampered,s.f.asker,{type:'semutaCommit',event:s.pending}),
`The third answer binds its original ${family}`);
}
reject(s.game,s.f.asker,{type:'semutaCommit',event:'stale-discard'});
let game = claim ? act(s.game,s.f.asker,{type:'semutaCommit',event:s.pending}) :
passTruthRicheseFreshDiscard(s.game);
assert.equal(game.pendingTreacheryDiscard,null); assert.equal(game.truthtrance,null);
assert.equal(player(game,s.f.asker).hand.some(card => card.id === s.f.truth),claim);
assert.equal(game.discard.some(card => card.id === s.semuta),claim);
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === s.early.id && !row.boundEvent && !row.released));
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && !row.fulfilled && !row.released));
assert.deepEqual({lot:game.richeseAuction,round:game.richeseBidding,funding:game.richeseFunding,aid:game.aid,
turn:game.turn,phase:game.phase,active:game.active,order:game.order},s.parent);
if (method === 'onceAround')
game = advance(game,state => clean(state) && state.richeseAuction?.active === s.f.emperor);
const view = viewGame(game,s.f.emperor), guide = view.phaseAnyBidGuide?.action; assert.ok(guide);
if (local) {
assert.deepEqual(guide,view.richeseBidPromiseGuide?.action);
assert.equal(guide.richeseBidPromiseId,local.id);
assert.equal(guide.earlyRicheseBidPromiseId,s.early.id);
reject(game,s.f.emperor,{...guide,richeseBidPromiseId:'stale-native'});
reject(game,s.f.emperor,{...guide,earlyRicheseBidPromiseId:'stale-early'});
}
reject(game,s.f.emperor,{...guide,phaseAnyBidPromiseEvent:'stale-phase'});
reject(game,s.f.emperor,{...guide,event:'stale-market'});
game = act(game,s.f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === s.phase.event && row.fulfilled));
if (local) assert.ok(game.richeseBidPromises?.some(row => row.id === local.id && row.fulfilled));
assert.deepEqual(inventory(game),s.f.originalCards);
});
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Game } from '../game/engine';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
/** Real Advanced R/A/E opening and actual market actions. Stage only the
* original second Truthtrance and Semuta into hands, then use Semuta to
* recover the first discarded Truthtrance for the third real question. */
function source(method:'silent'|'onceAround') {
const f=fixture({advanced:true}); let game:Game=structuredClone(f.earlySource);
const truthAt=game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(truthAt >= 0); const [second]=game.deck.splice(truthAt,1);
player(game,f.asker).hand.push(second);
const semutaAt=game.richeseCache!.findIndex(card => card.effect === 'semutaDrug');
assert.ok(semutaAt >= 0); const [semuta]=game.richeseCache!.splice(semutaAt,1);
player(game,f.richese).hand.push(semuta);
assert.deepEqual(inventory(game),f.originalCards);
game=act(game,f.asker,{type:'card',card:f.truth});
game=advance(game,state => state.truthtrance?.stage === 'ask');
game=act(game,f.asker,{type:'truthAsk',question:{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:2}});
game=act(game,f.emperor,{type:'truthAnswer',answer:'yes'});
const firstDiscard=game.pendingTreacheryDiscard; assert.ok(firstDiscard?.reaction);
assert.equal(viewGame(game,f.richese).semutaReaction?.canCommit,true);
game=act(game,f.richese,{type:'semutaCommit',event:firstDiscard.batch.event});
if (game.pendingTreacheryDiscard?.reaction?.stage === 'select')
game=act(game,f.richese,{type:'semutaSelect',event:firstDiscard.batch.event,card:f.truth});
assert.ok(player(game,f.richese).hand.some(card => card.id === f.truth));
const early=game.earlyRicheseBidPromises?.find(row => row.player === f.emperor && row.answer); assert.ok(early);
game=advance(game,state => state.decision?.kind === 'richeseBlackMarket');
const open=(direction:'clockwise'|'counterclockwise') => act(game,f.richese,
{type:'decision',event:game.richeseBidding!.event,card:f.targetCard,method,
...(method === 'onceAround' ? {direction} : {})});
let market=open('clockwise');
// Both directions are genuine physical choices; select one whose first
// actor is not the respondent so the test can perform an external action.
if (method === 'onceAround' && market.richeseAuction?.active === f.emperor)
market=open('counterclockwise');
game=market;
while (game.response) {
const actor=game.players.find(seat => !game.response!.passed.includes(seat.id)); assert.ok(actor);
game=act(game,actor.id,{type:'passResponse'});
}
const lot=game.richeseAuction; assert.ok(lot && lot.source === 'blackMarket');
if (method === 'onceAround') assert.notEqual(lot.active,f.emperor);
const event=lot.event;
function ask(asker:string,card:string,minimum:number) {
game=act(game,asker,{type:'card',card});
game=advance(game,state => state.truthtrance?.stage === 'ask');
game=act(game,asker,{type:'truthAsk',question:{kind:'richeseBid',target:f.emperor,turn:game.turn,event,minimum}});
assert.ok(viewGame(game,f.emperor).truthRicheseBidAnswers?.includes('yes'));
game=passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer:'yes'}));
}
ask(f.asker,second.id,4);
ask(f.richese,f.truth,8);
const low=game.richeseBidPromises?.find(row => row.event === event && row.player === f.emperor && row.minimum === 4);
const high=game.richeseBidPromises?.find(row => row.event === event && row.player === f.emperor && row.minimum === 8);
assert.ok(low && high);
assert.equal(player(game,f.emperor).spice,10);
assert.deepEqual(inventory(game),f.originalCards);
return {game,f,event,early,low,high};
}
for (const method of ['silent','onceAround'] as const) void test(
`Advanced ${method} market releases only the native Yes made impossible by an external loss`,() => {
const s=source(method); let game=structuredClone(s.game);
// Explicit external-loss supplement: cash falls from 10 to 7 while the
// original market remains open. Two must stay reserved for the cache,
// leaving a market ceiling of five. No cards or receipts are staged here.
player(game,s.f.emperor).spice=7;
const lot=game.richeseAuction!;
const actor=method === 'silent' ? s.f.asker : lot.active;
assert.ok(actor && actor !== s.f.emperor);
game=act(game,actor,{type:'richeseBid',event:s.event,amount:method === 'silent' ? 0 : null,allyPayment:0});
const low=game.richeseBidPromises?.find(row => row.id === s.low.id);
const high=game.richeseBidPromises?.find(row => row.id === s.high.id);
assert.ok(low && high);
assert.equal(!!low.fulfilled,false); assert.equal(!!low.released,false,'The affordable native Yes remains binding');
assert.equal(!!high.fulfilled,false); assert.equal(!!high.released,true,'Only the unaffordable native Yes releases');
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === s.early.id && !row.boundEvent && !row.released));
if (method === 'silent') {
assert.equal(viewGame(game,s.f.richese).richeseAuction?.revealedBids,null);
} else assert.equal(game.richeseAuction?.active,s.f.emperor);
const guide=viewGame(game,s.f.emperor).richeseBidPromiseGuide?.action; assert.ok(guide);
assert.equal(guide.type,'richeseBid'); assert.equal(guide.event,s.event); assert.equal(guide.amount,4);
assert.equal(guide.richeseBidPromiseId,s.low.id); assert.equal(guide.earlyRicheseBidPromiseId,s.early.id);
game=act(game,s.f.emperor,guide);
assert.ok(game.richeseBidPromises?.some(row => row.id === s.low.id && row.fulfilled));
assert.ok(game.richeseBidPromises?.some(row => row.id === s.high.id && row.released));
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === s.early.id && !row.boundEvent && !row.released));
assert.deepEqual(inventory(game),s.f.originalCards);
});