Files
Dune/game/shipment-promises.ts
T
Quintine 9f4de647ce Connect compound Truthtrance shipment promises
Shipment-only AND/OR questions now evaluate one eventual reserve shipment or skip as a whole. Yes to AND requires every leaf, Yes to OR requires one, and No negates the complete expression. Separate answered questions remain jointly binding. The completion search considers all destination branches and owned preparation paths. Release and fulfillment apply once to the aggregate promise, and legacy flat records retain their shape.

The two-condition browser builder, grouped question/history and respondent guidance, all four AI answer policies and saved continuation are connected. Nested expressions have explicit software size limits. Existing active-unused-shipment, Basic/no-Guild Advanced and module gates remain; mixed present/future predicates and unresolved rule questions are unchanged. Independent source, privacy and persistence review found no blocker.

Types, lint, 4815 offline tests, build and 43 HTTP tests pass with stable source. The first typecheck caught an omitted flat-only guidance consumer and a legacy test requiring type narrowing; grouped guidance and an actual promised-state regression fix them. SQLite Basic/Advanced tests verify private reauthentication, second-OR-branch fulfillment, zero-write rejected actions, legal No skip and duplicate CAS with one result.

Two fixed genuine Basic/Advanced mixed-profile games complete in 1534 accepted actions, 41 periodic private JSON restores and 0 rejected candidates. Each uses one scenario-directed compound question from an actual held Truthtrance at a real legal opportunity; AI supplies all responses and other actions. Exact card, force, typed-elite and post-setup traitor custody are checked. Initial private harness runs needed correct immutable setup configuration and full-game auction/Fedaykin inventory accounting; original failed traces remain private, and the final same-seed runs pass. The full sample tree is reconstructed exactly by replacing only the three later UI/test edits; all 219 game source files match the samples. No game logic changed after those runs.

Browser QA used genuine base initialization before conserved turn-two staging. The human asked twenty to Carthag OR four to Arrakeen; the AI answered Yes and shipped four to the second destination. Public grouped history survived refresh. All 6 accepted actions replay exactly, with one discarded Truthtrance, one fulfilled aggregate promise, private JSON views and original seat custody intact. This remains bounded prototype evidence, not complete Truthtrance or mode certification.

All 1004 opening games and original seat/recovery records are preserved (1038 rooms after checks), including all 1005 rooms present immediately before checks. SQLite integrity and foreign-key checks pass. The healthy server was reused without restart, reset or recurring automation.

Verified source tree: 1b24372fbe34e24db56e8f095c25744eeefb27581f2bc6cced2fb752f5bdcb94
2026-09-14 05:43:00 +10:00

163 lines
5.8 KiB
TypeScript

import { TERRITORIES, territory } from './board';
/** Every leaf describes the same eventual ordinary reserve shipment, or its absence. */
export type ShipmentLeaf = { territory: string; minimum: number };
export type ShipmentExpression =
| ShipmentLeaf
| { op: 'and' | 'or'; terms: ShipmentExpression[] };
/** Old flat questions and saved promises remain valid without migration. */
export type ShipmentClaim =
| (ShipmentLeaf & { claim?: never })
| { claim: ShipmentExpression; territory?: never; minimum?: never };
export const SHIPMENT_EXPRESSION_MAX_DEPTH = 4;
export const SHIPMENT_EXPRESSION_MAX_LEAVES = 16;
export class ShipmentClaimError extends Error {}
function check(value: unknown, message: string): asserts value {
if (!value) throw new ShipmentClaimError(message);
}
function object(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
function parseLeaf(value: Record<string, unknown>): ShipmentLeaf {
check(
typeof value.territory === 'string' &&
TERRITORIES.some((t) => t.id === value.territory),
'Choose a printed destination territory.',
);
check(
typeof value.minimum === 'number' &&
Number.isSafeInteger(value.minimum) &&
value.minimum >= 1 &&
value.minimum <= 20,
'Choose a minimum of one to twenty physical forces.',
);
return { territory: value.territory, minimum: value.minimum };
}
/** Bounded software input, not an additional printed limit on asking questions. */
export function parseShipmentExpression(value: unknown): ShipmentExpression {
let leaves = 0;
const parse = (value: unknown, depth: number): ShipmentExpression => {
check(
object(value) && depth <= SHIPMENT_EXPRESSION_MAX_DEPTH,
'Use a bounded shipment-only expression with at most four nested groups.',
);
if (Object.hasOwn(value, 'op')) {
check(
Object.keys(value).sort().join(',') === 'op,terms' &&
(value.op === 'and' || value.op === 'or') &&
Array.isArray(value.terms) &&
value.terms.length >= 2 &&
value.terms.length <= SHIPMENT_EXPRESSION_MAX_LEAVES,
'Join two or more shipment statements with AND or OR.',
);
return {
op: value.op,
terms: value.terms.map((term) => parse(term, depth + 1)),
};
}
check(
Object.keys(value).sort().join(',') === 'minimum,territory' &&
++leaves <= SHIPMENT_EXPRESSION_MAX_LEAVES,
'Use at most sixteen reserve-shipment statements; other fact or action types cannot be mixed in.',
);
return parseLeaf(value);
};
return parse(value, 0);
}
/** Extract only claim fields; surrounding question and lifecycle metadata stays separate. */
export function parseShipmentClaim(value: unknown): ShipmentClaim {
check(object(value), 'Choose a valid shipment statement.');
if (Object.hasOwn(value, 'claim')) {
check(
!Object.hasOwn(value, 'territory') && !Object.hasOwn(value, 'minimum'),
'Choose either a legacy shipment statement or an expression, not both.',
);
return { claim: parseShipmentExpression(value.claim) };
}
check(
!Object.hasOwn(value, 'op') && !Object.hasOwn(value, 'terms'),
'Place the shipment expression in its claim field.',
);
return parseLeaf(value);
}
export function validShipmentClaim(value: unknown): value is ShipmentClaim {
try {
parseShipmentClaim(value);
return true;
} catch (error) {
if (error instanceof ShipmentClaimError) return false;
throw error;
}
}
export function shipmentExpressionOf(claim: ShipmentClaim): ShipmentExpression {
return (
claim.claim ?? { territory: claim.territory!, minimum: claim.minimum! }
);
}
export function shipmentClaimDestinations(claim: ShipmentClaim): string[] {
const collect = (expression: ShipmentExpression): string[] =>
'op' in expression
? expression.terms.flatMap(collect)
: [expression.territory];
return [...new Set(collect(shipmentExpressionOf(claim)))];
}
export function shipmentClaimText(claim: ShipmentClaim): string {
const text = (expression: ShipmentExpression): string =>
'op' in expression
? `(${expression.terms.map(text).join(expression.op === 'and' ? ' AND ' : ' OR ')})`
: `ship at least ${expression.minimum} physical forces from your reserves to ${territory(expression.territory).name}`;
return text(shipmentExpressionOf(claim));
}
/** Software readiness boundary; this is not a printed restriction on Truthtrance. */
export function shipmentPromiseModeSupported(game: {
advanced: boolean;
expansions: readonly unknown[];
players: readonly { faction: string }[];
techTokens?: unknown;
strongholdCards?: unknown;
nexusCards?: unknown;
homeworlds?: unknown;
}): boolean {
return (
!game.expansions.length &&
(!game.advanced ||
(!game.players.some((player) => player.faction === 'guild') &&
!game.techTokens &&
!game.strongholdCards &&
!game.nexusCards &&
!game.homeworlds))
);
}
export type ShipmentPromise = ShipmentClaim & {
turn: number;
player: string;
asker: string;
answer: boolean;
released?: boolean;
fulfilled?: boolean;
};
export function matchesShipment(
claim: ShipmentClaim,
shipment: { territory: string; amount: number } | null,
): boolean {
const matches = (expression: ShipmentExpression): boolean =>
'op' in expression
? expression.op === 'and'
? expression.terms.every(matches)
: expression.terms.some(matches)
: !!shipment &&
shipment.territory === expression.territory &&
shipment.amount >= expression.minimum;
return matches(shipmentExpressionOf(claim));
}
export function liveShipmentPromises(
promises: readonly ShipmentPromise[],
player: string,
turn: number,
): ShipmentPromise[] {
return promises.filter(
(p) =>
p.player === player && p.turn === turn && !p.released && !p.fulfilled,
);
}