Compose early cache and phase-wide bid commitments
Verify and publish checkpoint container / container (push) Successful in 11m28s

This commit is contained in:
Quintine committed 2026-11-16 20:01:53 +11:00
1 parent 05f7fc8f20
commit 3ede19c90a
12 files changed
+990 -22

No files matched your search

+9 -4
View File
@@ -17,6 +17,15 @@ open mode gates.
## Current checkpoint and work
**Joint all-auction and early Richese cache answers — 16 November. Prototyped /
Partial.** Supported Basic games can bind both answers before Bidding; a real
cache declaration can satisfy both, or separately funded bids retain their
own costs and hand slots. The cache-only route and Semuta continuation are
connected. Sixteen related unit files pass 236 cases. Advanced, Kull and other
promise combinations, complete games and
deployed acceptance remain open.
[Scope](TRUTHTRANCE_BID_PROMISES.md#all-auction-and-early-richese-cache-bids--16-november-2026).
**Recovered Sapho at the Testing Station — 16 November. Prototyped /
Partial.** In supported Basic and Advanced Semuta/Discovery previews, an
occupant who recovers the discarded physical Juice of Sapho may reorder the
@@ -26,10 +35,6 @@ Seven related unit files pass 30 cases. The online ordering is provisional;
other modules, complete games and deployed
acceptance remain open.
[Scope](DISCOVERY_PROTOTYPE.md#recovered-sapho-at-the-testing-station--16-november-2026).
The next scoped bid interaction is an early Richese-cache answer combined with
an all-auction answer. It needs a two-stage funded and hand-space forecast before
the existing guards can be relaxed; a local, unverified test draft is retained
under ignored `work/prototype-drafts/` when available.
**Joint all-auction and ordinary bid answers — 16 November. Prototyped /
Partial.** Current ordinary and all-auction Truthtrance bid answers can
+7
View File
@@ -1,5 +1,12 @@
# Rule decision index
## Joint phase-wide and early Richese cache answers — 16 November 2026
The supported Basic early-cache and all-auction answers can share a real
declaration or use separately funded auctions. Forecasting and online timing
remain provisional.
[Scope](TRUTHTRANCE_BID_PROMISES.md#all-auction-and-early-richese-cache-bids--16-november-2026).
## Recovered Sapho at the Testing Station — 16 November 2026
The provisional two-occupant ordering permits a second physical Sapho play
+35 -4
View File
@@ -1,5 +1,36 @@
# Truthtrance ordinary bid commitments
## All-auction and early Richese cache bids — 16 November 2026
**Prototyped / Partial.** In supported Basic Richese games, a player can answer
both the all-auction question and a question about the first real cache in
either order. The waiting cache receipt attaches to the actual lot; the native
shared guide, bots and auction clock then use its original bid and funding.
One bid can satisfy both Yes answers. A cache No lasts for that cache, while
an all-auction No applies across the phase. When separate qualifying bids are
needed, the forecast reserves the cost and hand space of the first purchase,
including a possible Harkonnen bonus, without assuming a rival bid, a refund or
future income. An already-required ordinary bid is reserved before counting a
later cache or ordinary lot. Once an actual ordinary bid fulfills the phase
answer, the waiting cache obligation remains independently binding.
The pending physical cache can also witness a phase Yes when no ordinary lot
remains. Cancellation releases an impossible cache answer while retaining an
independently viable phase Yes. Fresh Semuta discard continuations bind both
waiting ledgers; older saved continuations keep their original signatures.
The FAQ and supplied Advanced revision support current-turn questions and
compliance while possible; this online forecast and ordering are provisional.
Advanced and Kull early-cache admission, other commitments, optional modules,
complete games and deployed acceptance remain open.
[Joint cases](../tests/truth-phase-any-early-richese-joint.test.ts),
[last cache cases](../tests/truth-phase-any-early-richese-last.test.ts),
[Semuta cases](../tests/truth-phase-any-early-richese-semuta.test.ts) and
[cache-only cases](../tests/truth-phase-any-cache-only.test.ts) exercise real
auctions with disclosed conserved staging. The
[legacy current-lot cases](../tests/truth-phase-any-early-richese-current.test.ts)
explicitly stage a no-Semuta saved profile and a wallet shortfall. Sixteen
related unit files pass 236 cases.
## All-auction and current ordinary bids — 16 November 2026
**Prototyped / Partial.** Current ordinary and all-auction bid answers, including
@@ -13,7 +44,7 @@ Supported Advanced Semuta preserves the original commitments and question queue.
The FAQ and supplied Advanced revision support current-turn questions and
compliance while possible; this online forecast and ordering are provisional.
Early-cache and older ordinary-only phase combinations, other commitments,
Older ordinary-only phase combinations, other commitments,
optional modules, complete games and deployed acceptance remain open.
[Runtime](../tests/truth-phase-any-ordinary-joint.test.ts),
[last cache](../tests/truth-phase-any-ordinary-last-cache.test.ts),
@@ -37,7 +68,7 @@ the auction clock. A completed opposing raise releases an impossible local
Yes before checking whether the phase-wide answer remains possible. Supported
Semuta claim/pass preserves both bindings and the original question queue.
The existing online forecast and ordering remain provisional under the source
authority below. Early-cache and legacy ordinary-only phase commitment combinations, other
authority below. Legacy ordinary-only phase commitment combinations, other
financial/action commitments, optional modules, complete games and deployed
acceptance remain open. [Runtime cases](../tests/truth-phase-any-richese-joint.test.ts)
use actual questions and auction actions with explicitly staged original
@@ -64,8 +95,8 @@ known later ordinary lot or the mandatory cache following Black Market may
preserve a Yes when a player passes or bids less now. Forecasts use currently
owned resources and committed funding without assuming future rival bids,
income or refunds. They are conservative, and a missing forecast does not
assert a publisher prohibition. Current Richese and ordinary bid answers now compose as
described above; early-cache, legacy ordinary-only phase and other unsupported financial or
assert a publisher prohibition. Current Richese, ordinary and early-cache answers now compose as
described above; legacy ordinary-only phase and other unsupported financial or
action promise combinations remain separate. Broader
modules, full games and deployed acceptance remain open.
+108 -14
View File
@@ -38,6 +38,7 @@ import { jointRicheseBidCompletionRange } from './joint-richese-bids';
import { EarlyRicheseBidError, earlyRicheseBidAnswerOptions, bindEarlyRicheseBid,
attachEarlyRicheseBids, liveEarlyRicheseBidPromises, reconcileEarlyRicheseBids,
validateEarlyRicheseBidPromises, type EarlyRicheseBidClaim, type EarlyRicheseBidPromise } from './early-richese-bid';
import { quoteJointEarlyRicheseBids } from './joint-early-richese-bids';
import { AuctionClockError, AUCTION_BID_MS, quoteAuctionClock, viewAuctionClock,
type AuctionClock, type AuctionClockView } from './auction-clock';
import { PrintedCardPlayError, printedCardPlayCount, recordPrintedCardPlay,
@@ -2009,6 +2010,8 @@ export type Game = {
jointRichesePhaseBid?: true;
/** Fresh joint ordinary/all-auction answer; absent on older receipts. */
jointOrdinaryPhaseBid?: true;
/** Fresh waiting cache/all-auction answer; absent on older receipts. */
jointEarlyPhaseBid?: true;
resume: NonNullable<Game['pendingNullentropy']>['resume'];
promise:
| { kind: 'shipment'; index: number; value: ShipmentPromise }
@@ -8065,6 +8068,8 @@ function truthtranceDiscardSignature(g: Game, next: TruthDiscardContinuation) {
richeseBidPromises:g.richeseBidPromises,mixedRicheseBidQuestions:g.mixedRicheseBidQuestions} : {}),
...(next.jointOrdinaryPhaseBid ? {jointOrdinaryPhaseBid:true,phaseAnyBidPromises:g.phaseAnyBidPromises,
bidPromises:g.bidPromises,mixedBidQuestions:g.mixedBidQuestions} : {}),
...(next.jointEarlyPhaseBid ? {jointEarlyPhaseBid:true,phaseAnyBidPromises:g.phaseAnyBidPromises,
earlyRicheseBidPromises:g.earlyRicheseBidPromises} : {}),
...(next.record.question.kind === 'mixedRevival' ? {
mixedRevivalQuestions: g.mixedRevivalQuestions, revivalExpressionPromises: g.revivalExpressionPromises,
} : {}),
@@ -8158,6 +8163,10 @@ function finishTruthtranceAnswer(g: Game) {
livePhaseBidPromises(g.phaseAnyBidPromises ?? [],record.question.target,g.turn).length &&
liveBidPromises(g.bidPromises ?? [],record.question.target,bidOpportunity(g)!).length
? {jointOrdinaryPhaseBid:true as const} : {}),
...(['phaseAnyBid','earlyRicheseBid'].includes(record.question.kind) &&
livePhaseBidPromises(g.phaseAnyBidPromises ?? [],record.question.target,g.turn).length &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],record.question.target,g.turn).length
? {jointEarlyPhaseBid:true as const} : {}),
resume,
promise,
parentSignature: '',
@@ -9185,6 +9194,14 @@ function treacheryDiscardIntegrity(g: Game) {
'The consumed Truthtrance does not match its completed answer history.',
);
const remaining = c.remaining;
if (c.jointEarlyPhaseBid) {
const target = record.question.target;
requireRule(c.jointEarlyPhaseBid === true &&
['phaseAnyBid','earlyRicheseBid'].includes(record.question.kind) &&
livePhaseBidPromises(g.phaseAnyBidPromises ?? [],target,g.turn).length > 0 &&
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],target,g.turn).length > 0,
'The completed Truthtrance lost its waiting cache and phase bid commitments.');
}
if (c.jointOrdinaryPhaseBid) {
const lot = bidOpportunity(g), target = record.question.target;
requireRule(c.jointOrdinaryPhaseBid === true && !!lot &&
@@ -18580,11 +18597,13 @@ function earlyRicheseBidMaximum(g: Game, p: Player): number {
}
function earlyRicheseBidTruthAnswers(g: Game,p: Player,claim: EarlyRicheseBidClaim): TruthAnswer[] {
if (!earlyRicheseBidWindow(g) || claim.turn !== g.turn) return [];
if (livePhaseBidPromises(g.phaseAnyBidPromises ?? [],p.id,g.turn).length) return ['unknown'];
if (richeseBidOtherPromises(g,p)) return ['unknown'];
if (richeseBidOtherPromises(g,p,{allowPhaseAny:true})) return ['unknown'];
const asker = g.truthtrance?.queue[0]?.player ?? g.players.find(row => row.id !== p.id)?.id ?? g.host;
const answers = earlyRicheseBidRule(() => earlyRicheseBidAnswerOptions(g.earlyRicheseBidPromises ?? [],claim,p.id,asker,
earlyRicheseBidMaximum(g,p))).map(answer => answer ? 'yes' as const : 'no' as const);
earlyRicheseBidMaximum(g,p))).filter(answer => {
const early = [...(g.earlyRicheseBidPromises ?? []),{...claim,id:'candidate',player:p.id,asker,answer}];
return earlyPhaseAnyPossible(g,p,early,g.phaseAnyBidPromises ?? []);
}).map(answer => answer ? 'yes' as const : 'no' as const);
return answers.includes('yes') ? answers : [...answers,'unknown'];
}
function bindEarlyRicheseBidTruth(g: Game,p: Player,claim: EarlyRicheseBidClaim,answer: boolean,asker: string): void {
@@ -18611,8 +18630,10 @@ function reconcileEarlyRicheseTruth(g: Game,voluntary?: {actor:string;action:Act
(g.richeseCache?.length ?? 0) > 0 &&
(g.phase < 3 || !round || round.turn !== turn || !round.cacheCanceled && round.stage !== 'complete');
const before: EarlyRicheseBidPromise[] = g.earlyRicheseBidPromises ?? [];
const phaseCaps = livePhaseBidPromises(g.phaseAnyBidPromises ?? [],p.id,turn).filter(row => !row.answer);
const maximum = Math.min(earlyRicheseBidMaximum(g,p),...phaseCaps.map(row => row.minimum - 1));
g.earlyRicheseBidPromises = earlyRicheseBidRule((): EarlyRicheseBidPromise[] => reconcileEarlyRicheseBids(before,p.id,turn,{
cachePending,canBid:p.hand.length < handLimit(p),maximum:earlyRicheseBidMaximum(g,p),
cachePending,canBid:p.hand.length < handLimit(p),maximum,
change:voluntary?.actor === p.id ? 'voluntary' : 'external',
}));
if (g.earlyRicheseBidPromises.some((row,index) => row.player === p.id && row.released && !before[index]?.released))
@@ -18654,7 +18675,7 @@ function richeseBidOtherPromises(g: Game, p: Player, options?: {allowPhaseAny?:
function richeseBidCompatibleLaterPromises(g: Game,p: Player): boolean {
const lot = g.richeseAuction;
if (!lot) return !liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).some(row => row.answer) ||
!richeseBidOtherPromises(g,p);
!richeseBidOtherPromises(g,p,{allowPhaseAny:true});
const context = {turn:g.turn,event:lot.event,player:p.id};
return !richeseBidRequired(g.richeseBidPromises ?? [],context) || !richeseBidOtherPromises(g,p);
}
@@ -18791,8 +18812,8 @@ function phaseBidHonorsTurnActions(g: Game, p: Player, lot: BidOpportunity, acti
/** Current witnesses must also satisfy the existing native funding and
* current-lot commitments. Future bidding with other financial/transport
* promises awaits their combined planner; do not invent those resources. */
function phaseBidFuturePlannerUnsupported(g: Game, p: Player): boolean {
return liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).some(row => row.answer) ||
function phaseBidFuturePlannerUnsupported(g: Game, p: Player, allowEarlyCache = false): boolean {
return !allowEarlyCache && liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).some(row => row.answer) ||
liveShipmentPromises(g.shipmentPromises ?? [],p.id,g.turn).some(row => matchesShipment(row,null) !== row.answer) ||
hasMovementPromises(g,p.id,!!g.advanced || g.expansions.length > 0) ||
liveRevivalPromises(g.revivalPromises ?? [],p.id,g.turn).some(row => row.answer) ||
@@ -18849,10 +18870,10 @@ function phaseBidRevivalShipmentWitness(g: Game, p: Player, promises: readonly P
}
return null;
}
function viablePhaseBidWitnesses(g: Game, p: Player, promises: readonly PhaseBidPromise[]) {
function viablePhaseBidWitnesses(g: Game, p: Player, promises: readonly PhaseBidPromise[], allowEarlyCache = false) {
const lot = bidOpportunity(g);
const live = livePhaseBidPromises(promises,p.id,g.turn);
const otherCommitments = phaseBidFuturePlannerUnsupported(g,p);
const otherCommitments = phaseBidFuturePlannerUnsupported(g,p,allowEarlyCache);
return phaseBidWitnesses(g,p).flatMap(witness => {
if (witness.kind === 'future') {
if (otherCommitments) {
@@ -18964,6 +18985,8 @@ function reconcilePhaseBids(g: Game, voluntary?: {actor:string;action:Action}) {
phaseBidIntegrity(g);
// An external raise can release an impossible local Yes while leaving a
// phase-wide Yes achievable in a later lot; resolve the narrower scope first.
if (g.phaseAnyBidPromises?.length && g.earlyRicheseBidPromises?.length)
reconcileEarlyRicheseTruth(g,voluntary);
if (g.phaseAnyBidPromises?.length && g.richeseBidPromises?.length) reconcileRicheseBids(g,voluntary);
reconcilePhaseAnyBids(g,voluntary);
if (!g.phaseBidPromises?.length || g.truthtrance || g.response || g.decision || g.phaseOpening ||
@@ -19040,13 +19063,10 @@ function phaseAnyBidConflict(g: Game, p: Player): boolean {
return livePhaseBidPromises(g.phaseBidPromises ?? [],p.id,g.turn).length > 0 ||
(g.bidPromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released &&
(!current || row.source !== current.source)) ||
(g.earlyRicheseBidPromises ?? []).some(row => row.player === p.id && row.turn === g.turn &&
!row.fulfilled && !row.released) ||
(g.pledgePromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.charityPromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
hasBribePromises(g,p.id,true) ||
liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).length > 0 ||
phaseBidFuturePlannerUnsupported(g,p);
phaseBidFuturePlannerUnsupported(g,p,true);
}
/** A completed Black Market offer is followed by Richese's real cache lot.
* Reserve this player's possibly winning card and its own committed funds;
@@ -19078,6 +19098,27 @@ function phaseAnyLastCache(g: Game,p: Player): PhaseBidOpportunity | null {
return Number.isSafeInteger(maximum) && maximum > 0
? {turn:g.turn,player:p.id,kind:'future',minimum:1,maximum} : null;
}
/** The waiting first cache is physical but its method and order are not yet
* known. Reserve only owned spice and never assume another player's bid. */
function pendingEarlyCacheMaximum(g: Game,p: Player): number {
const round = g.richeseBidding;
const pending = g.status === 'playing' && g.phase <= 3 && !!byFaction(g,'richese') &&
(g.richeseCache?.length ?? 0) > 0 && g.richeseAuction?.source !== 'cache' &&
(g.phase < 3 || !round || round.turn !== g.turn || !round.cacheCanceled && round.stage !== 'complete');
return pending ? earlyRicheseBidMaximum(g,p) : 0;
}
function earlyPhaseAnyPossible(g: Game,p: Player,early: readonly EarlyRicheseBidPromise[],
phase: readonly PhaseBidPromise[]): boolean {
const trial = {...g,earlyRicheseBidPromises:[...early]};
const cache = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase,
cacheMaximum:pendingEarlyCacheMaximum(g,p)});
if (cache.earlyRequired && !cache.cache) return false;
const lot = bidOpportunity(g);
if (!cache.phaseRequired && cache.earlyRequired && lot && bidRequired(g.bidPromises ?? [],p.id,lot))
return phaseAnyBidWitnesses(trial,p,phase).some(witness => witness.kind === 'future');
return !cache.phaseRequired || phaseAnyBidWitnesses(trial,p,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[],
@@ -19117,6 +19158,52 @@ function phaseAnyBidWitnesses(g: Game, p: Player, promises: readonly PhaseBidPro
return [...current,...jointRicheseFutureWitnesses(g,p,promises,native,opportunity)];
}
}
const early = liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn);
if (early.length) {
const cacheMaximum = pendingEarlyCacheMaximum(g,p);
const phase = livePhaseBidPromises(promises,p.id,g.turn);
const ordinaryLot = bidOpportunity(g);
let afterLocal = g;
if (ordinaryLot && bidRequired(g.bidPromises ?? [],p.id,ordinaryLot)) {
const caps: BidPromise[] = phase.filter(row => !row.answer).map((row,index) => ({
turn:g.turn,lot:ordinaryLot.lot,minimum:row.minimum,event:`early-cache-cap-${index}`,
source:ordinaryLot.source,player:p.id,asker:row.asker,answer:false}));
const action = bidPromiseCompletion(g,p,[...(g.bidPromises ?? []),...caps]);
if (!action || action.type !== 'bid') return [];
afterLocal = structuredClone(g);
afterLocal.auction!.bid = Number(action.amount); afterLocal.auction!.bidder = p.id;
afterLocal.auction!.allyPayment = Number(action.allyPayment ?? 0);
afterLocal.bidPromises = recordPromisedBid(afterLocal.bidPromises ?? [],p.id,ordinaryLot,Number(action.amount));
}
const quote = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase,
cacheMaximum:pendingEarlyCacheMaximum(afterLocal,getPlayer(afterLocal,p.id))});
if (quote.earlyRequired && !quote.cache) return [];
const result: PhaseBidOpportunity[] = quote.cache ?
[{turn:g.turn,player:p.id,kind:'future',...quote.cache}] : [];
// Quote each ordinary route with a minimal phase Yes so reconciliation can
// release individual impossible answers rather than discarding them all.
const positive = phase.find(row => row.answer);
if (!positive) return result;
const neutralPhase = [...phase.filter(row => !row.answer),{...positive,minimum:1}];
for (const opportunity of viablePhaseBidWitnesses(g,p,neutralPhase,true)) {
// Later ordinary witnesses follow any required local purchase; current
// witnesses are that purchase and must not reserve it twice.
const source = opportunity.kind === 'future' ? afterLocal : g;
const owner = getPlayer(source,p.id);
const pendingCards = source.auction?.bidder === p.id && !source.currentAuctionSale
? 1 + Number(p.faction === 'harkonnen') : 0;
const freeSlots = Math.max(0,handLimit(owner)-owner.hand.length-pendingCards);
const cash = Math.max(0,uncommittedSpice(source,owner));
const lockedAid = source.auction?.bidder === p.id && !source.currentAuctionSale
? (source.auction.allyPayment ?? 0) : 0;
const aid = Math.max(0,(aidFor(source,owner)?.amount ?? 0)-lockedAid);
const joint = quoteJointEarlyRicheseBids({player:p.id,turn:g.turn,early,phase:neutralPhase,cacheMaximum,
ordinary:{opportunity,cashAvailable:cash,aidAvailable:aid,freeSlots,
cacheWinSlots:1+Number(p.faction === 'harkonnen')}});
if (joint.separate) result.push({...opportunity,...joint.separate.ordinary});
}
return result;
}
const futureCache = phaseAnyFutureCache(g,p);
let lastCache = phaseAnyLastCache(g,p);
const ordinaryLot = bidOpportunity(g);
@@ -19134,8 +19221,13 @@ function phaseAnyBidWitnesses(g: Game, p: Player, promises: readonly PhaseBidPro
}
}
const ordinary = viablePhaseBidWitnesses(g,p,promises);
// Before Bidding the physically held Richese cache is itself an auction,
// even when its replacement leaves no ordinary cards to be sold.
const beforeBiddingCache = g.phase < 3 ? pendingEarlyCacheMaximum(g,p) : 0;
return [...(special ? [special] : []),...(futureCache ? [futureCache] : []),
...(lastCache ? [lastCache] : []),...ordinary];
...(lastCache ? [lastCache] : []),
...(beforeBiddingCache > 0 ? [{turn:g.turn,player:p.id,kind:'future' as const,
minimum:1,maximum:beforeBiddingCache}] : []),...ordinary];
}
function richesePhaseJointPossible(g: Game,p: Player,phase: readonly PhaseBidPromise[]): boolean {
const lot = g.richeseAuction;
@@ -19152,6 +19244,8 @@ function phaseAnyBidTruthAnswers(g: Game, p: Player, claim: PhaseBidClaim): Trut
return (['yes','no'] as const).filter(answer => {
const all: PhaseBidPromise[] = [...(g.phaseAnyBidPromises ?? []),
{...claim,event:'candidate',player:p.id,asker,answer:answer === 'yes'}];
if (liveEarlyRicheseBidPromises(g.earlyRicheseBidPromises ?? [],p.id,g.turn).length)
return earlyPhaseAnyPossible(g,p,g.earlyRicheseBidPromises ?? [],all);
if (g.richeseAuction && liveRicheseBidPromises(g.richeseBidPromises ?? [],
{turn:g.turn,event:g.richeseAuction.event,player:p.id}).length)
return richesePhaseJointPossible(g,p,all);
+99
View File
@@ -0,0 +1,99 @@
import {
EarlyRicheseBidError,
liveEarlyRicheseBidPromises,
type EarlyRicheseBidPromise,
} from './early-richese-bid';
import {
livePhaseBidPromises,
phaseBidCompletionRange,
type PhaseBidOpportunity,
type PhaseBidPromise,
type PhaseBidRange,
} from './turn-bid-promises';
/** Only facts established by the engine are supplied here: the physical cache
* must still be pending, and a separate ordinary lot must have its own native
* reachability and bid quote. No rival bid, refund or future income is assumed. */
export type JointEarlyRicheseBidInput = {
player: string;
turn: number;
early: readonly EarlyRicheseBidPromise[];
phase: readonly PhaseBidPromise[];
/** Current owned, uncommitted Spice available for a future cache bid.
* Zero also represents an unavailable cache or insufficient hand space. */
cacheMaximum: number;
/** Present only when the engine proves a separate ordinary opportunity.
* Its cash and aid are available before the hypothetical cache purchase;
* freeSlots excludes existing pending invoices and their physical cards. */
ordinary?: {
opportunity: PhaseBidOpportunity;
cashAvailable: number;
aidAvailable: number;
freeSlots: number;
/** Slots occupied by a potentially won cache card (including bonuses). */
cacheWinSlots: number;
};
};
export type JointEarlyRicheseBidQuote = {
earlyRequired: boolean;
phaseRequired: boolean;
/** A positive cache declaration satisfying early Yes and both sets of No. */
cache: PhaseBidRange | null;
/** One cache declaration satisfying all early and phase Yes answers. */
shared: PhaseBidRange | null;
/** A distinct ordinary phase bid after reserving any required cache bid.
* A null cacheBid means the cache may be declined. */
separate: { cacheBid: number | null; ordinary: PhaseBidRange } | null;
possible: boolean;
};
const whole = (value: unknown): value is number =>
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
/** Intersect cache constraints before admitting both questions or preserving
* their witnesses. Distinct bids are funded pessimistically as if the first
* purchase is won: reserve its cost and card capacity before quoting the
* second. The engine retains responsibility for current-lot rules, timing,
* escrow, releases, physical settlement and actual reachability. */
export function quoteJointEarlyRicheseBids(input: JointEarlyRicheseBidInput): JointEarlyRicheseBidQuote {
if (!input || typeof input.player !== 'string' || !input.player || input.player.trim() !== input.player ||
!whole(input.turn) || input.turn < 1 || !Array.isArray(input.early) || !Array.isArray(input.phase) ||
!whole(input.cacheMaximum))
throw new EarlyRicheseBidError('Retain the respondent, turn and funded cache opportunity.');
const early = liveEarlyRicheseBidPromises(input.early, input.player, input.turn);
const phase = livePhaseBidPromises(input.phase, input.player, input.turn);
const earlyRequired = early.some(row => row.answer);
const phaseRequired = phase.some(row => row.answer);
const minimum = Math.max(1, ...early.filter(row => row.answer).map(row => row.minimum));
const maximum = Math.min(input.cacheMaximum,
...early.filter(row => !row.answer).map(row => row.minimum - 1),
...phase.filter(row => !row.answer).map(row => row.minimum - 1));
const cache = minimum <= maximum ? {minimum, maximum} : null;
const sharedMinimum = Math.max(minimum, ...phase.filter(row => row.answer).map(row => row.minimum));
const shared = cache && sharedMinimum <= maximum ? {minimum:sharedMinimum, maximum} : null;
let separate: JointEarlyRicheseBidQuote['separate'] = null;
if (input.ordinary && phaseRequired) {
const {opportunity, cashAvailable, aidAvailable, freeSlots, cacheWinSlots} = input.ordinary;
if (!opportunity || opportunity.player !== input.player || opportunity.turn !== input.turn ||
!whole(cashAvailable) || !whole(aidAvailable) || !whole(freeSlots) || !whole(cacheWinSlots))
throw new EarlyRicheseBidError('Retain the funded separate ordinary bid and hand capacity.');
const reserved = earlyRequired ? cache?.minimum : 0;
if (reserved !== undefined && cashAvailable >= reserved &&
freeSlots > (earlyRequired ? cacheWinSlots : 0)) {
const maximumOrdinary = Math.min(opportunity.maximum, Number.MAX_SAFE_INTEGER,
cashAvailable - reserved + aidAvailable);
if (maximumOrdinary >= opportunity.minimum) {
const ordinary = phaseBidCompletionRange(phase, {...opportunity, maximum:maximumOrdinary});
if (ordinary) separate = {cacheBid:earlyRequired ? reserved : null, ordinary};
}
}
}
const possible = earlyRequired
? !!cache && (!phaseRequired || !!shared || !!separate)
: !phaseRequired || !!shared || !!separate;
return {earlyRequired, phaseRequired, cache, shared, separate, possible};
}
+1
View File
@@ -3792,6 +3792,7 @@ export const RULE_TOPICS: RuleTopic[] = [
'A current ordinary, Richese Once Around or Silent bid answer can coexist with the all-auction answer. One native declaration may satisfy both; each No caps that declaration, and a phase-wide Yes may instead wait for a separately funded later lot.',
'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 Basic Bidding, ask about a minimum bid in the first actual Richese 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; cancellation or an 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.',
'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.',
+96
View File
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { quoteJointEarlyRicheseBids, type JointEarlyRicheseBidInput } from '../game/joint-early-richese-bids';
import type { EarlyRicheseBidPromise } from '../game/early-richese-bid';
import type { PhaseBidPromise } from '../game/turn-bid-promises';
const early = (minimum:number,answer:boolean,extra:Partial<EarlyRicheseBidPromise> = {}):EarlyRicheseBidPromise =>
({id:`early-${minimum}-${answer}`,turn:3,player:'emperor',asker:'atreides',minimum,answer,...extra});
const phase = (minimum:number,answer:boolean,extra:Partial<PhaseBidPromise> = {}):PhaseBidPromise =>
({event:`phase-${minimum}-${answer}`,turn:3,player:'emperor',asker:'atreides',minimum,answer,...extra});
const input = (extra:Partial<JointEarlyRicheseBidInput> = {}):JointEarlyRicheseBidInput => ({
player:'emperor',turn:3,early:[],phase:[],cacheMaximum:10,...extra,
});
const ordinary = (extra:Partial<NonNullable<JointEarlyRicheseBidInput['ordinary']>> = {}) => ({
opportunity:{player:'emperor',turn:3,kind:'future' as const,minimum:1,maximum:10},
cashAvailable:9,aidAvailable:0,freeSlots:2,cacheWinSlots:1,...extra,
});
void test('one physical cache declaration intersects every live Yes and No',() => {
const result=quoteJointEarlyRicheseBids(input({
early:[early(3,true),early(8,false)],phase:[phase(5,true),phase(7,false)],
}));
assert.equal(result.earlyRequired,true); assert.equal(result.phaseRequired,true);
assert.deepEqual(result.cache,{minimum:3,maximum:6});
assert.deepEqual(result.shared,{minimum:5,maximum:6});
assert.equal(result.separate,null); assert.equal(result.possible,true);
const conflict=quoteJointEarlyRicheseBids(input({early:[early(3,true)],phase:[phase(3,false)]}));
assert.equal(conflict.cache,null); assert.equal(conflict.shared,null); assert.equal(conflict.possible,false);
const onlyNo=quoteJointEarlyRicheseBids(input({early:[early(1,false)],phase:[phase(1,false)]}));
assert.equal(onlyNo.cache,null); assert.equal(onlyNo.possible,true,'Both obligations can pass');
});
void test('a distinct ordinary bid reserves cash and a hand slot for a required cache purchase',() => {
const baseline=input({early:[early(3,true),early(4,false)],phase:[phase(6,true)],ordinary:ordinary()});
const quote=quoteJointEarlyRicheseBids(baseline);
assert.deepEqual(quote.cache,{minimum:3,maximum:3}); assert.equal(quote.shared,null);
assert.deepEqual(quote.separate,{cacheBid:3,ordinary:{minimum:6,maximum:6}});
assert.equal(quote.possible,true);
const insufficient=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({cashAvailable:8})});
assert.equal(insufficient.separate,null); assert.equal(insufficient.possible,false);
const aided=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({cashAvailable:8,aidAvailable:1})});
assert.deepEqual(aided.separate,{cacheBid:3,ordinary:{minimum:6,maximum:6}});
assert.equal(aided.possible,true);
const noSecondSlot=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({freeSlots:1})});
assert.equal(noSecondSlot.separate,null); assert.equal(noSecondSlot.possible,false);
// The first Harkonnen purchase can add its bonus card before the second
// declaration. Once that declaration is placed both obligations are met.
const harkonnenTwo=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({freeSlots:2,cacheWinSlots:2})});
assert.equal(harkonnenTwo.separate,null); assert.equal(harkonnenTwo.possible,false);
const harkonnenThree=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({freeSlots:3,cacheWinSlots:2})});
assert.deepEqual(harkonnenThree.separate,{cacheBid:3,ordinary:{minimum:6,maximum:6}});
assert.equal(harkonnenThree.possible,true);
const noCashForCache=quoteJointEarlyRicheseBids({...baseline,ordinary:ordinary({cashAvailable:2,aidAvailable:100})});
assert.equal(noCashForCache.separate,null,'Uncommitted ally aid cannot replace the cache cash witness');
});
void test('a phase Yes can use a separate ordinary bid while the early No permits a cache pass',() => {
const quote=quoteJointEarlyRicheseBids(input({early:[early(4,false)],phase:[phase(6,true)],
ordinary:ordinary({cashAvailable:6,freeSlots:1})}));
assert.equal(quote.earlyRequired,false); assert.equal(quote.shared,null);
assert.deepEqual(quote.separate,{cacheBid:null,ordinary:{minimum:6,maximum:6}});
assert.equal(quote.possible,true);
const blocked=quoteJointEarlyRicheseBids(input({early:[early(4,false)],phase:[phase(6,true),phase(6,false)],
ordinary:ordinary({cashAvailable:10})}));
assert.equal(blocked.shared,null); assert.equal(blocked.separate,null); assert.equal(blocked.possible,false);
});
void test('only the respondent’s live receipts for this turn bind the joint quote',() => {
const quote=quoteJointEarlyRicheseBids(input({
early:[early(3,true),early(1,false,{id:'other',player:'richese'}),
early(1,false,{id:'old',turn:2}),early(1,false,{id:'bound',boundEvent:'real-cache'}),
early(1,false,{id:'finished',fulfilled:true}),early(1,false,{id:'released',released:true})],
phase:[phase(4,true),phase(1,false,{event:'other',player:'richese'}),
phase(1,false,{event:'old',turn:2}),phase(1,false,{event:'finished',fulfilled:true}),
phase(1,false,{event:'released',released:true})],
}));
assert.deepEqual(quote.cache,{minimum:3,maximum:10});
assert.deepEqual(quote.shared,{minimum:4,maximum:10});
assert.equal(quote.possible,true);
});
void test('zero and maximum safe integer budgets do not invent funding',() => {
assert.equal(quoteJointEarlyRicheseBids(input({cacheMaximum:0,early:[early(1,true)]})).possible,false);
assert.equal(quoteJointEarlyRicheseBids(input({cacheMaximum:0,early:[early(1,false)]})).possible,true);
const max=Number.MAX_SAFE_INTEGER;
const single=quoteJointEarlyRicheseBids(input({cacheMaximum:max,early:[early(max,true)],phase:[phase(max,true)]}));
assert.deepEqual(single.shared,{minimum:max,maximum:max}); assert.equal(single.possible,true);
for (const cacheMaximum of [-1,0.5,Infinity,Number.NaN,Number.MAX_SAFE_INTEGER+1])
assert.throws(() => quoteJointEarlyRicheseBids(input({cacheMaximum})));
assert.throws(() => quoteJointEarlyRicheseBids(input({turn:0})));
assert.throws(() => quoteJointEarlyRicheseBids(input({player:' emperor '})));
assert.throws(() => quoteJointEarlyRicheseBids(input({phase:[phase(1,true)],
ordinary:ordinary({cashAvailable:1,aidAvailable:-1})})));
assert.throws(() => quoteJointEarlyRicheseBids(input({phase:[phase(1,true)],
ordinary:ordinary({opportunity:{player:'richese',turn:3,kind:'future',minimum:1,maximum:1}})})));
});
+138
View File
@@ -0,0 +1,138 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { handLimit, viewGame, type Game } from '../game/engine';
import {
actTruthtranceRichesePromises as act,
advanceTruthtranceRichesePromises as advance,
askTruthtranceRichesePromises as ask,
createTruthtranceRichesePromisesFixture as fixture,
passTruthRicheseFreshDiscard,
truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory,
truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
/** Public Basic setup; explicitly supplement only physical card custody.
* Atreides and Richese receive original unopened cards up to their hand limits;
* Emperor receives the original Distrans from the cache. No purse, auction,
* phase, promise or outcome is installed. Atreides discards its original
* Truthtrance, then Emperor uses the actual Distrans to fill that freed slot.
* The natural Bidding declaration therefore has only one eligible seat and
* the compulsory cache consumes that sole lot. */
function source() {
const f = fixture({advanced:false});
let game = structuredClone(f.earlySource);
const karamaIndex = game.deck.findIndex(card => card.effect === 'karama'); assert.ok(karamaIndex >= 0);
const [karama] = game.deck.splice(karamaIndex,1);
player(game,f.asker).hand.push(karama);
for (const id of [f.asker,f.richese]) {
const owner = player(game,id);
while (owner.hand.length < handLimit(owner)) {
const [card] = game.deck.splice(0,1); assert.ok(card);
owner.hand.push(card);
}
}
const index = game.richeseCache!.findIndex(card => card.effect === 'distrans'); assert.ok(index >= 0);
const [distrans] = game.richeseCache!.splice(index,1);
player(game,f.emperor).hand.push(distrans);
const given = player(game,f.emperor).hand.find(card => card.id !== distrans.id); assert.ok(given);
assert.deepEqual(inventory(game),f.originalCards);
game = ask(game,f,{kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:6});
assert.ok(viewGame(game,f.emperor).truthPhaseAnyBidAnswers?.includes('yes'));
game = passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer:'yes'}));
const receipt = game.phaseAnyBidPromises?.find(row => row.player === f.emperor); assert.ok(receipt);
game = act(game,f.emperor,{type:'card',card:distrans.id,target:f.asker,give:given.id});
game = passTruthRicheseFreshDiscard(game);
assert.equal(player(game,f.asker).hand.length,handLimit(player(game,f.asker)));
assert.equal(player(game,f.richese).hand.length,handLimit(player(game,f.richese)));
assert.ok(player(game,f.emperor).hand.length < handLimit(player(game,f.emperor)));
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === receipt.event && !row.released && !row.fulfilled));
assert.deepEqual(inventory(game),f.originalCards);
game = advance(game,state => state.decision?.kind === 'richeseDeclaration');
assert.equal(game.richeseBidding?.normalCountBeforeCache,1);
assert.equal(game.richeseBidding?.normalCount,0);
return {f,game,receipt,karama:karama.id};
}
void test('a phase Yes remains funded by the sole actual cache when no ordinary lots remain', () => {
const {f,receipt,...bound} = source();
let game = advance(bound.game,state => clean(state) && !!state.richeseAuction &&
state.richeseAuction.source === 'cache' && state.richeseAuction.method === 'silent' &&
!state.richeseAuction.outcome, [], {position:'first',method:'silent'});
assert.equal(game.richeseBidding?.normalCount,0);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === receipt.event && !row.released));
const lot = game.richeseAuction!, purse = player(game,f.emperor).spice;
const guide = viewGame(game,f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'richeseBid'); assert.equal(guide.amount,6);
game = act(game,f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === receipt.event && row.fulfilled));
game = advance(game,state => player(state,f.emperor).hand.some(card => card.id === lot.cardId));
assert.equal(player(game,f.emperor).spice,purse-6);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('external cache cancellation restores an ordinary lot and preserves the phase Yes', () => {
const {f,receipt,karama,...bound} = source();
let game:Game = act(bound.game,f.richese,
{type:'decision',event:bound.game.richeseBidding!.event,position:'first'});
assert.equal(game.response?.kind,'richeseAuction');
game = act(game,f.asker,{type:'card',card:karama,mode:'cancel'});
game = passTruthRicheseFreshDiscard(game);
assert.equal(game.richeseBidding?.cacheCanceled,true);
assert.equal(game.richeseBidding?.normalCount,1);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === receipt.event && !row.fulfilled && !row.released));
game = advance(game,state => clean(state) && !!state.auction && state.auction.active === f.emperor);
const card = game.auction!.cards[game.auction!.index].id, purse = player(game,f.emperor).spice;
const guide = viewGame(game,f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'bid'); assert.equal(guide.amount,6);
game = act(game,f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === receipt.event && row.fulfilled));
game = advance(game,state => player(state,f.emperor).hand.some(item => item.id === card));
assert.equal(player(game,f.emperor).spice,purse-6);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('external cache cancellation releases the early Yes but retains the phase Yes for the restored ordinary lot', () => {
const f = fixture({advanced:false});
let game = structuredClone(f.earlySource);
// Two original unopened cards change custody: Atreides receives a second
// Truthtrance and the printed Karama. No auction, funding or receipt is
// fabricated; both questions and the cancellation use native controls.
const secondIndex = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(secondIndex >= 0);
const [secondTruth] = game.deck.splice(secondIndex,1);
const karamaIndex = game.deck.findIndex(card => card.effect === 'karama'); assert.ok(karamaIndex >= 0);
const [karama] = game.deck.splice(karamaIndex,1);
player(game,f.asker).hand.push(secondTruth,karama);
assert.deepEqual(inventory(game),f.originalCards);
game = ask(game,f,{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:4});
assert.ok(viewGame(game,f.emperor).truthEarlyRicheseBidAnswers?.includes('yes'));
game = passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer:'yes'}));
const early = game.earlyRicheseBidPromises?.find(row => row.player === f.emperor); assert.ok(early);
game = act(game,f.asker,{type:'card',card:secondTruth.id});
game = advance(game,state => state.truthtrance?.stage === 'ask');
game = act(game,f.asker,{type:'truthAsk',question:{
kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:6,
}});
assert.ok(viewGame(game,f.emperor).truthPhaseAnyBidAnswers?.includes('yes'));
game = passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer:'yes'}));
const phase = game.phaseAnyBidPromises?.find(row => row.player === f.emperor); assert.ok(phase);
game = advance(game,state => state.decision?.kind === 'richeseDeclaration');
const ordinaryBefore = game.richeseBidding!.normalCount!;
game = act(game,f.richese,{type:'decision',event:game.richeseBidding!.event,position:'first'});
assert.equal(game.response?.kind,'richeseAuction');
game = passTruthRicheseFreshDiscard(act(game,f.asker,{type:'card',card:karama.id,mode:'cancel'}));
assert.equal(game.richeseBidding?.cacheCanceled,true);
assert.equal(game.richeseBidding?.normalCount,ordinaryBefore+1);
assert.ok(game.earlyRicheseBidPromises?.some(row => row.id === early.id && row.released && !row.boundEvent));
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === phase.event && !row.fulfilled && !row.released));
game = advance(game,state => clean(state) && !!state.auction && state.auction.active === f.emperor);
const card = game.auction!.cards[game.auction!.index].id, purse = player(game,f.emperor).spice;
const guide = viewGame(game,f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'bid'); assert.equal(guide.amount,6);
game = act(game,f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.event === phase.event && row.fulfilled));
game = advance(game,state => player(state,f.emperor).hand.some(item => item.id === card));
assert.equal(player(game,f.emperor).spice,purse-6);
assert.deepEqual(inventory(game),f.originalCards);
});
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Game } from '../game/engine';
import type { TruthQuestion } from '../game/truthtrance';
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 Fixture = ReturnType<typeof fixture>;
/** Public Basic source with explicitly staged legacy Semuta marker and card
* custody. A second original Truth moves from the unopened deck to Atreides;
* for a third question its first discarded original card is later recovered
* by a conserved zone move. No phase, auction, bid or receipt is fabricated.
* This covers a legacy saved profile, not a fresh Basic Richese start. */
function source() {
const f = fixture({advanced:false}), game = structuredClone(f.earlySource);
delete game.semutaPreview;
const index = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(index >= 0);
const [second] = game.deck.splice(index,1);
player(game,f.asker).hand.push(second);
assert.equal(player(game,f.emperor).spice,10);
assert.deepEqual(inventory(game),f.originalCards);
return {f,game,second:second.id};
}
function recoverOriginal(game:Game,f:Fixture,card:string) {
const at = game.discard.findIndex(row => row.id === card);
assert.ok(at >= 0,'The original discarded Truthtrance remains available for conserved staging');
player(game,f.asker).hand.push(game.discard.splice(at,1)[0]);
assert.deepEqual(inventory(game),f.originalCards);
}
function ask(game:Game,f:Fixture,card:string,question:TruthQuestion,answer:'yes'|'no') {
game=act(game,f.asker,{type:'card',card});
game=advance(game,state => state.truthtrance?.stage === 'ask');
game=act(game,f.asker,{type:'truthAsk',question});
const view=viewGame(game,f.emperor);
const choices=question.kind === 'earlyRicheseBid' ? view.truthEarlyRicheseBidAnswers :
question.kind === 'phaseAnyBid' ? view.truthPhaseAnyBidAnswers : view.truthBidAnswers;
assert.ok(choices?.includes(answer),`${question.kind} must offer ${answer}: ${JSON.stringify(choices)}`);
return passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer}));
}
void test('a phase Yes cannot reuse the funds already needed for a mandatory ordinary bid and later cache',() => {
const {f,second,...start}=source(); let game=start.game;
game=ask(game,f,f.truth,{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:1},'yes');
game=advance(game,state => clean(state) && !!state.auction && state.auction.active === f.emperor,
[],{position:'last',method:'silent'});
const lot=game.auction!.index+1;
game=ask(game,f,second,{kind:'bid',target:f.emperor,turn:game.turn,lot,minimum:9},'yes');
recoverOriginal(game,f,f.truth);
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:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:10}});
assert.ok(!viewGame(game,f.emperor).truthPhaseAnyBidAnswers?.includes('yes'),
'Ten spice cannot fund both the current nine-spice bid and a later ten-spice cache bid, or a ten-spice ordinary bid plus cache one');
const before=structuredClone(game);
assert.throws(() => act(game,f.emperor,{type:'truthAnswer',answer:'yes'}));
assert.deepEqual(game,before);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('an external shortfall releases only the higher phase Yes while the lower Yes can still use the cache',() => {
const {f,second,...start}=source(); let game=start.game;
game=ask(game,f,f.truth,{kind:'earlyRicheseBid',target:f.emperor,turn:game.turn,minimum:6},'no');
recoverOriginal(game,f,f.truth);
game=ask(game,f,second,{kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:4},'yes');
game=ask(game,f,f.truth,{kind:'phaseAnyBid',target:f.emperor,turn:game.turn,minimum:8},'yes');
const low=game.phaseAnyBidPromises?.find(row => row.player === f.emperor && row.minimum === 4);
const high=game.phaseAnyBidPromises?.find(row => row.player === f.emperor && row.minimum === 8);
assert.ok(low && high);
// Simulate an external loss rather than inventing a specific unimplemented
// interrupt: the other player's real ready action triggers reconciliation.
player(game,f.emperor).spice=6;
const other=game.players.find(row => row.id !== f.emperor && !game.ready.includes(row.id));
assert.ok(other,'A different original player can complete Charity');
game=act(game,other.id,{type:'ready'});
assert.equal(!!game.phaseAnyBidPromises?.find(row => row.event === low.event)?.released,false);
assert.equal(!!game.phaseAnyBidPromises?.find(row => row.event === high.event)?.released,true);
assert.equal(!!game.earlyRicheseBidPromises?.find(row => row.player === f.emperor)?.released,false);
assert.deepEqual(inventory(game),f.originalCards);
});
@@ -0,0 +1,214 @@
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 Answer = 'yes' | 'no';
type Kind = 'phaseAnyBid' | 'earlyRicheseBid';
/** The real public-start Richese/Atreides/Emperor fixture orders unopened
* setup and Spice cards. For two actual questions, move one additional original
* Truthtrance from the unopened deck into Atreides' hand; no wallets, auctions,
* or receipts are fabricated. */
function source() {
const f = fixture({ advanced: false });
const game = structuredClone(f.earlySource);
const at = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(at >= 0, 'A second original Truthtrance must remain in the unopened deck');
const [second] = game.deck.splice(at, 1);
player(game, f.asker).hand.push(second);
assert.deepEqual(inventory(game), f.originalCards);
return { f, game, second: second.id };
}
function openQuestion(game: Game, f: TruthtranceRichesePromisesFixture, card: string, kind: Kind, minimum: number) {
game = act(game, f.asker, { type: 'card', card });
game = advance(game, state => state.truthtrance?.stage === 'ask');
return act(game, f.asker, { type: 'truthAsk', question: { kind, target: f.emperor, turn: game.turn, minimum } });
}
function options(game: Game, f: TruthtranceRichesePromisesFixture, kind: Kind) {
const view = viewGame(game, f.emperor);
return kind === 'phaseAnyBid' ? view.truthPhaseAnyBidAnswers : view.truthEarlyRicheseBidAnswers;
}
function answer(game: Game, f: TruthtranceRichesePromisesFixture, kind: Kind, value: Answer) {
assert.ok(options(game, f, kind)?.includes(value), `${kind} ${value} must be offered when jointly feasible`);
return passTruthRicheseFreshDiscard(act(game, f.emperor, { type: 'truthAnswer', answer: value }));
}
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game, actor, action));
assert.deepEqual(game, before, 'A rejected declaration or stale guide preserves its source');
}
for (const method of ['onceAround', 'silent'] as const)
for (const position of ['first', 'last'] as const)
for (const first of ['phaseAnyBid', 'earlyRicheseBid'] as const)
for (const phaseAnswer of ['yes', 'no'] as const)
for (const earlyAnswer of ['yes', 'no'] as const) void test(
`Basic ${position} ${method}: ${first} first, phase ${phaseAnswer}, early ${earlyAnswer}`, () => {
const { f, second, ...initial } = source();
// Both Yes requirements can share a bid of 6. A No caps at 6,
// leaving the other Yes's bid of 4 possible in the same cache.
const phaseMinimum = phaseAnswer === 'yes' ? 4 : 6;
const earlyMinimum = earlyAnswer === 'yes' && phaseAnswer === 'yes' ? 6 :
earlyAnswer === 'yes' ? 4 : 6;
const secondKind: Kind = first === 'phaseAnyBid' ? 'earlyRicheseBid' : 'phaseAnyBid';
const minimum = (kind: Kind) => kind === 'phaseAnyBid' ? phaseMinimum : earlyMinimum;
const response = (kind: Kind) => kind === 'phaseAnyBid' ? phaseAnswer : earlyAnswer;
let game = openQuestion(initial.game, f, f.truth, first, minimum(first));
game = answer(game, f, first, response(first));
game = openQuestion(game, f, second, secondKind, minimum(secondKind));
game = answer(game, f, secondKind, response(secondKind));
const early = game.earlyRicheseBidPromises?.find(row => row.player === f.emperor);
const phase = game.phaseAnyBidPromises?.find(row => row.player === f.emperor);
assert.ok(early && phase);
assert.equal(early.answer, earlyAnswer === 'yes');
assert.equal(phase.answer, phaseAnswer === 'yes');
assert.equal(early.boundEvent, undefined, 'The future cache has no invented event');
game = advance(game, state => clean(state) && !!state.richeseAuction &&
state.richeseAuction.source === 'cache' && state.richeseAuction.method === method &&
!state.richeseAuction.outcome, [], { position, method });
const lot = game.richeseAuction!;
const event = lot.event, card = lot.cardId;
assert.equal(game.earlyRicheseBidPromises?.find(row => row.id === early.id)?.boundEvent, event);
if (method === 'onceAround')
game = advance(game, state => clean(state) && state.richeseAuction?.active === f.emperor);
const native = game.richeseBidPromises?.find(row => row.id === early.id); assert.ok(native);
assert.equal(native.event, event);
const view = viewGame(game, f.emperor);
const guide = view.phaseAnyBidGuide?.action ?? view.richeseBidPromiseGuide?.action;
assert.ok(guide, 'A jointly legal native guide is available');
assert.equal(guide.type, 'richeseBid');
assert.doesNotThrow(() => act(game, f.emperor, guide));
if (guide.phaseAnyBidPromiseEvent !== undefined)
reject(game, f.emperor, { ...guide, phaseAnyBidPromiseEvent: 'stale-phase' });
if (guide.richeseBidPromiseId !== undefined)
reject(game, f.emperor, { ...guide, richeseBidPromiseId: 'stale-cache' });
for (const difficulty of DIFFICULTIES) {
const bot = viewGame(game, f.emperor);
bot.players.find(row => row.id === f.emperor)!.bot = difficulty;
const chosen = botActions(bot)[0]; assert.ok(chosen, difficulty);
assert.doesNotThrow(() => act(game, f.emperor, chosen), difficulty);
}
if (phaseAnswer === 'no')
reject(game, f.emperor, { type: 'richeseBid', event, amount: phaseMinimum, allyPayment: 0 });
if (earlyAnswer === 'no')
reject(game, f.emperor, { type: 'richeseBid', event, amount: earlyMinimum, allyPayment: 0 });
if (earlyAnswer === 'yes')
reject(game, f.emperor, { type: 'richeseBid', event, amount: method === 'silent' ? 0 : null });
const amount = earlyAnswer === 'yes' ? earlyMinimum : phaseAnswer === 'yes' ? phaseMinimum : 2;
const before = player(game, f.emperor).spice;
game = act(game, f.emperor, { type: 'richeseBid', event, amount, allyPayment: 0 });
assert.equal(player(game, f.emperor).spice, before, 'A declaration does not prepay the invoice');
assert.equal(!!game.phaseAnyBidPromises?.find(row => row.event === phase.event)?.fulfilled, phaseAnswer === 'yes');
assert.ok(game.richeseBidPromises?.find(row => row.id === early.id)?.fulfilled);
game = advance(game, state => player(state, f.emperor).hand.some(item => item.id === card),
[], { position, method });
assert.equal(player(game, f.emperor).spice, before - amount);
assert.deepEqual(inventory(game), f.originalCards);
});
for (const first of ['phaseAnyBid', 'earlyRicheseBid'] as const) void test(
`A phase No 6 conflicts with an early cache Yes 6 when ${first} is asked first`, () => {
const { f, second, ...initial } = source();
const secondKind: Kind = first === 'phaseAnyBid' ? 'earlyRicheseBid' : 'phaseAnyBid';
const firstAnswer = first === 'phaseAnyBid' ? 'no' : 'yes';
let game = openQuestion(initial.game, f, f.truth, first, 6);
game = answer(game, f, first, firstAnswer);
game = openQuestion(game, f, second, secondKind, 6);
const impossible = secondKind === 'phaseAnyBid' ? 'no' : 'yes';
assert.ok(!options(game, f, secondKind)?.includes(impossible),
'A definite answer cannot demand a cache bid that its phase-wide No forbids');
reject(game, f.emperor, { type: 'truthAnswer', answer: impossible });
assert.deepEqual(inventory(game), f.originalCards);
});
void test('a voluntary bribe preserves the common funded Yes witness', () => {
const { f, second, ...initial } = source();
let game = openQuestion(initial.game, f, f.truth, 'phaseAnyBid', 6);
game = answer(game, f, 'phaseAnyBid', 'yes');
game = openQuestion(game, f, second, 'earlyRicheseBid', 4);
game = answer(game, f, 'earlyRicheseBid', 'yes');
reject(game, f.emperor, {type:'bribe',target:f.asker,amount:5});
game = act(game, f.emperor, {type:'bribe',target:f.asker,amount:4});
assert.equal(player(game, f.emperor).spice, 6);
game = advance(game, state => clean(state) && !!state.richeseAuction &&
state.richeseAuction.source === 'cache' && state.richeseAuction.method === 'silent', [],
{position:'first',method:'silent'});
const guide = viewGame(game, f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type, 'richeseBid'); assert.equal(guide.amount, 6);
game = act(game, f.emperor, guide);
assert.ok(game.phaseAnyBidPromises?.some(row => row.player === f.emperor && row.fulfilled));
assert.ok(game.richeseBidPromises?.some(row => row.player === f.emperor && row.fulfilled));
assert.deepEqual(inventory(game), f.originalCards);
});
for (const position of ['first', 'last'] as const)
for (const method of ['onceAround', 'silent'] as const)
for (const first of ['phaseAnyBid', 'earlyRicheseBid'] as const)
for (const earlyAnswer of ['yes', 'no'] as const) void test(
`Basic ${position} ${method}: ${first} first, phase Yes 6 and cache ${earlyAnswer} 4 may use separately funded bids`, () => {
const { f, second, ...initial } = source();
const secondKind: Kind = first === 'phaseAnyBid' ? 'earlyRicheseBid' : 'phaseAnyBid';
const min = (kind: Kind) => kind === 'phaseAnyBid' ? 6 : 4;
const response = (kind: Kind) => kind === 'phaseAnyBid' ? 'yes' : earlyAnswer;
let game = openQuestion(initial.game, f, f.truth, first, min(first));
game = answer(game, f, first, response(first));
game = openQuestion(game, f, second, secondKind, min(secondKind));
game = answer(game, f, secondKind, response(secondKind));
const originalSpice = player(game, f.emperor).spice;
assert.equal(originalSpice, 10, 'Use the real Emperor starting funds');
const round = {position,method};
const cacheBid = earlyAnswer === 'yes' ? 4 : 2;
const ordinary = (sourceGame: Game) => advance(sourceGame,
state => clean(state) && !!state.auction && state.auction.active === f.emperor, [], round);
const cache = (sourceGame: Game) => {
let current = advance(sourceGame, state => clean(state) && !!state.richeseAuction &&
state.richeseAuction.source === 'cache' && !state.richeseAuction.outcome, [], round);
if (method === 'onceAround')
current = advance(current, state => clean(state) && state.richeseAuction?.active === f.emperor, [], round);
return current;
};
const payOrdinary = (current: Game) => {
const guide = viewGame(current, f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type, 'bid'); assert.equal(guide.amount, 6);
if (earlyAnswer === 'yes' && position === 'last')
reject(current, f.emperor, {type:'bid',amount:7,allyPayment:0});
const card = current.auction!.cards[current.auction!.index].id;
const placed = act(current, f.emperor, guide);
assert.ok(placed.phaseAnyBidPromises?.some(row => row.player === f.emperor && row.fulfilled));
return advance(placed, state => player(state, f.emperor).hand.some(item => item.id === card), [], round);
};
const payCache = (current: Game) => {
const lot = current.richeseAuction!, card = lot.cardId;
if (earlyAnswer === 'no')
reject(current, f.emperor, {type:'richeseBid',event:lot.event,amount:4,allyPayment:0});
else
reject(current, f.emperor, {type:'richeseBid',event:lot.event,amount:method === 'silent' ? 0 : null});
const placed = act(current, f.emperor, {type:'richeseBid',event:lot.event,amount:cacheBid,allyPayment:0});
if (position === 'first')
assert.ok(placed.phaseAnyBidPromises?.some(row => row.player === f.emperor && !row.fulfilled && !row.released));
assert.ok(placed.richeseBidPromises?.some(row => row.player === f.emperor && row.fulfilled));
return advance(placed, state => player(state, f.emperor).hand.some(item => item.id === card), [], round);
};
game = position === 'first' ? payCache(cache(game)) : payOrdinary(ordinary(game));
game = position === 'first' ? payOrdinary(ordinary(game)) : payCache(cache(game));
assert.equal(player(game, f.emperor).spice, originalSpice - cacheBid - 6);
assert.deepEqual(inventory(game), f.originalCards);
});
@@ -0,0 +1,122 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { advanceAuctionClock, synchronizeAuctionClock, viewGame, type Game } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import type { TruthQuestion } from '../game/truthtrance';
import {
actTruthtranceRichesePromises as act, advanceTruthtranceRichesePromises as advance,
createTruthtranceRichesePromisesFixture as fixture, nextTruthtranceRichesePromisesStep as next,
passTruthRicheseFreshDiscard, truthtranceRichesePromisesClean as clean,
truthtranceRichesePromisesInventory as inventory, truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
type Fixture = ReturnType<typeof fixture>;
type Method = 'onceAround' | 'silent';
type Kind = 'earlyRicheseBid' | 'phaseAnyBid';
/** Native public Basic setup; only a second physical Truthtrance moves from
* the unopened deck to Atreides. The original cache, hands, funds and both
* later auction sales retain their real physical identities and controls. */
function source() {
const f = fixture({advanced:false});
const game = structuredClone(f.earlySource);
const index = game.deck.findIndex(card => card.effect === 'truthtrance' && card.id !== f.truth);
assert.ok(index >= 0);
const [second] = game.deck.splice(index,1);
player(game,f.asker).hand.push(second);
assert.equal(player(game,f.emperor).spice,10);
assert.deepEqual(inventory(game),f.originalCards);
return {f,game,second:second.id};
}
function question(game:Game,f:Fixture,card:string,kind:Kind,minimum:number,answer:'yes'|'no') {
game = act(game,f.asker,{type:'card',card});
game = advance(game,state => state.truthtrance?.stage === 'ask');
const claim:TruthQuestion = {kind,target:f.emperor,turn:game.turn,minimum};
game = act(game,f.asker,{type:'truthAsk',question:claim});
const view = viewGame(game,f.emperor);
const choices = kind === 'phaseAnyBid' ? view.truthPhaseAnyBidAnswers : view.truthEarlyRicheseBidAnswers;
assert.ok(choices?.includes(answer),`${kind} must offer ${answer}: ${JSON.stringify(choices)}`);
return passTruthRicheseFreshDiscard(act(game,f.emperor,{type:'truthAnswer',answer}));
}
function both(first:Kind) {
const {f,second,...initial} = source(); let game = initial.game;
const secondKind:Kind = first === 'phaseAnyBid' ? 'earlyRicheseBid' : 'phaseAnyBid';
const minimum = (kind:Kind) => kind === 'phaseAnyBid' ? 4 : 6;
game = question(game,f,f.truth,first,minimum(first),'yes');
game = question(game,f,second,secondKind,minimum(secondKind),'yes');
const early = game.earlyRicheseBidPromises?.find(row => row.player === f.emperor); assert.ok(early);
const phase = game.phaseAnyBidPromises?.find(row => row.player === f.emperor); assert.ok(phase);
return {game,f,early,phase};
}
function ordinaryTurn(game:Game,f:Fixture,method:Method) {
const opts = {position:'last' as const,method};
game = advance(game,state => clean(state) && !!state.auction,[],opts);
for (let count=0;game.auction?.active !== f.emperor && count<game.players.length;count++) {
const actor=game.auction?.active; assert.ok(actor);
game=act(game,actor,{type:'passBid'});
}
assert.equal(game.auction?.active,f.emperor);
assert.equal(game.richeseBidding?.position,'last');
return game;
}
function lastCache(game:Game,method:Method) {
const opts = {position:'last' as const,method};
for (let count=0;count<1000;count++) {
if (clean(game) && game.richeseAuction?.source === 'cache' && !game.richeseAuction.outcome) return game;
const step=next(game,opts); assert.ok(step,'Native controls must reach the actual last cache');
game=act(game,step.actor,step.action);
}
throw Error('The real last cache did not open');
}
for (const first of ['phaseAnyBid','earlyRicheseBid'] as const)
for (const method of ['onceAround','silent'] as const) void test(
`Basic last ${method}, ${first} first: ordinary phase Yes purchase retains independently funded cache Yes`,() => {
const bound=both(first), f=bound.f;
let game=ordinaryTurn(bound.game,f,method);
const ordinaryCard=game.auction!.cards[game.auction!.index].id;
const before=structuredClone(game);
assert.throws(() => act(game,f.emperor,{type:'bid',amount:5,allyPayment:0}),
'A five-spice purchase would leave less than the six-spice cache promise');
assert.deepEqual(game,before,'Rejected overcommitment cannot change either receipt or auction');
const guide=viewGame(game,f.emperor).phaseAnyBidGuide?.action;
assert.ok(guide); assert.equal(guide.type,'bid'); assert.equal(guide.amount,4);
for (const difficulty of DIFFICULTIES) {
const bot=viewGame(game,f.emperor); bot.players.find(row => row.id === f.emperor)!.bot=difficulty;
const action=botActions(bot)[0]; assert.ok(action,`${difficulty} supplies a legal ordinary action`);
assert.doesNotThrow(() => act(game,f.emperor,action));
}
game=act(game,f.emperor,guide);
assert.ok(game.phaseAnyBidPromises?.find(row => row.event === bound.phase.event)?.fulfilled);
const waiting=game.earlyRicheseBidPromises?.find(row => row.id === bound.early.id); assert.ok(waiting);
assert.equal(waiting.boundEvent,undefined); assert.equal(!!waiting.released,false);
assert.equal(player(game,f.emperor).spice,10,'The native winning declaration is not prepaid');
game=lastCache(game,method);
assert.ok(player(game,f.emperor).hand.some(card => card.id === ordinaryCard));
assert.equal(player(game,f.emperor).spice,6,'The actual ordinary invoice reserves the cache budget');
const lot=game.richeseAuction!;
assert.equal(game.earlyRicheseBidPromises?.find(row => row.id === bound.early.id)?.boundEvent,lot.event);
if (method === 'onceAround') game=advance(game,state => clean(state) &&
state.richeseAuction?.event === lot.event && state.richeseAuction.active === f.emperor,[],{position:'last',method});
const native=viewGame(game,f.emperor).richeseBidPromiseGuide?.action;
assert.ok(native); assert.equal(native.type,'richeseBid'); assert.equal(native.amount,6);
for (const difficulty of DIFFICULTIES) {
const bot=viewGame(game,f.emperor); bot.players.find(row => row.id === f.emperor)!.bot=difficulty;
const action=botActions(bot)[0]; assert.ok(action,`${difficulty} supplies a legal cache action`);
assert.doesNotThrow(() => act(game,f.emperor,action));
}
if (method === 'onceAround') {
const armed=synchronizeAuctionClock(game,1_000,'last-cache');
const expired=advanceAuctionClock(armed,11_000,'last-cache');
assert.ok(expired.richeseBidPromises?.find(row => row.id === bound.early.id)?.fulfilled,
'The native deadline honors the attached early Yes');
}
game=act(game,f.emperor,native);
assert.ok(game.richeseBidPromises?.find(row => row.id === bound.early.id)?.fulfilled);
assert.equal(player(game,f.emperor).spice,6);
game=advance(game,state => player(state,f.emperor).hand.some(card => card.id === lot.cardId),
[],{position:'last',method});
assert.equal(player(game,f.emperor).spice,0);
assert.deepEqual(inventory(game),f.originalCards);
});
@@ -0,0 +1,71 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Game } from '../game/engine';
import {
actTruthtranceRichesePromises as act,
createTruthtranceRichesePromisesFixture as fixture, passTruthRicheseFreshDiscard,
truthtranceRichesePromisesInventory as inventory, truthtranceRichesePromisesPlayer as player,
} from './fixture-truthtrance-richese-promises';
/** Genuine public Basic Richese setup; a second physical Truthtrance moves
* from unopened deck to Atreides and Semuta moves from Richese cache to its
* owner. No answer, bid, purse or reaction is manufactured. */
function source() {
const f=fixture({advanced:false});
const game=structuredClone(f.earlySource);
assert.equal(game.semutaPreview,true);
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 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 parent(game:Game) {
return structuredClone({turn:game.turn,phase:game.phase,active:game.active,ready:game.ready,order:game.order,
auction:game.auction,richeseAuction:game.richeseAuction,richeseBidding:game.richeseBidding,aid:game.aid});
}
for (const first of ['phase','early'] as const) for (const claim of [false,true]) void test(
`Basic early ${first} first: second Truth Semuta ${claim ? 'claim' : 'pass'} binds both waiting ledgers`,() => {
const f=source(), original=parent(f.game);
const phase={kind:'phaseAnyBid',target:f.f.emperor,turn:f.game.turn,minimum:4};
const early={kind:'earlyRicheseBid',target:f.f.emperor,turn:f.game.turn,minimum:6};
let game=act(f.game,f.f.asker,{type:'card',card:f.f.truth,cards:[f.second]});
while (game.truthtrance?.stage === 'priority') {
const actor=game.players.find(row => !game.truthtrance!.passed.includes(row.id)); assert.ok(actor);
game=act(game,actor.id,{type:'truthPass'});
}
assert.deepEqual(game.truthtrance?.queue.map(row => row.card),[f.f.truth,f.second]);
game=act(game,f.f.asker,{type:'truthAsk',question:first === 'phase' ? phase : early});
game=act(game,f.f.emperor,{type:'truthAnswer',answer:'yes'});
const single=game.pendingTreacheryDiscard; assert.ok(single?.reaction);
assert.equal(single.continuation.kind,'truthtranceDiscard');
assert.equal(single.continuation.jointEarlyPhaseBid,undefined,'The older single-answer receipt keeps its shape');
game=passTruthRicheseFreshDiscard(game);
assert.deepEqual(game.truthtrance?.queue.map(row => row.card),[f.second]);
game=act(game,f.f.asker,{type:'truthAsk',question:first === 'phase' ? early : phase});
game=act(game,f.f.emperor,{type:'truthAnswer',answer:'yes'});
const pending=game.pendingTreacheryDiscard; assert.ok(pending?.reaction);
assert.equal(pending.continuation.kind,'truthtranceDiscard');
assert.equal(pending.continuation.jointEarlyPhaseBid,true);
assert.equal(pending.batch.entries[0].card.id,f.second);
assert.equal(viewGame(game,f.f.richese).semutaReaction?.canCommit,true);
const phasePromises=structuredClone(game.phaseAnyBidPromises), earlyPromises=structuredClone(game.earlyRicheseBidPromises);
assert.deepEqual(parent(game),original);
for (const family of ['phaseAnyBidPromises','earlyRicheseBidPromises'] as const) {
const tampered=structuredClone(game);
tampered[family]![0].minimum++;
assert.throws(() => act(tampered,f.f.richese,{type:'semutaCommit',event:pending.batch.event}),
`The completed answer binds ${family}`);
}
game=claim ? act(game,f.f.richese,{type:'semutaCommit',event:pending.batch.event}) : passTruthRicheseFreshDiscard(game);
assert.equal(game.pendingTreacheryDiscard,null); assert.equal(game.truthtrance,null);
assert.equal(player(game,f.f.richese).hand.some(card => card.id === f.second),claim);
assert.equal(game.discard.some(card => card.id === f.semuta),claim);
assert.deepEqual(game.phaseAnyBidPromises,phasePromises); assert.deepEqual(game.earlyRicheseBidPromises,earlyPromises);
assert.deepEqual(parent(game),original);
assert.ok(game.earlyRicheseBidPromises?.some(row => row.player === f.f.emperor && !row.boundEvent && !row.released));
assert.deepEqual(inventory(game),f.f.originalCards);
});