Connect revealed Harass force allocation and exact casualties

Harass & Withdraw now admits legal Basic/Advanced mixed ordinary/elite commitments and multi-sector returns. A shared physical quote validates every returned counter against one exact legal dial/support complement. After both plans are revealed, the owner selects an ambiguous allocation; unique returns remain automatic. Selected counters become public before Traitor declarations, while physical transfer waits for atomic settlement and opposing-Traitor cancellation. This information is never added to a sealed Battle Plan or complete-plan inspection. Existing optional-module and Richese/Ecaz-allied gates remain.

The player panel, four AI profiles and saved event use the same quote. A versioned receipt binds the revealed plans, current typed location pools, battle and owner. Missing or altered receipts fail before reads, normalization and writes; concurrent choices select once. Previously valid legacy unique plans continue without reopening. Winner casualties now equal the selected dialed group, preventing a second smaller physical commitment after its undialed complement has returned.

Independent source and implementation review passed. Pure, engine, control and SQLite regressions cover typed/sector legality, exact complement, private pre-reveal views, public selected views, stale/malformed state, cross-owner actions, raced allocations, selected restoration, automatic exact casualties, opposing-Traitor cancellation and mandatory disposal. Types, lint and 4850 offline tests, production build and 43 HTTP/session tests pass. The first broad check caught the exhaustive decision registry and test union-narrowing omissions; those were fixed before the final stable checks. Browser testing corrected the incomplete-allocation selector label before verification.

Eight genuine card-variant Basic/Advanced games across all four homogeneous AI profiles completed with 9956 accepted actions, 266 periodic JSON restores and zero rejected candidates. Three Harass plans/returns and two Recruits plays occurred; no ambiguous allocation arose in these seeds. The new choice is exercised by targeted engine, authenticated recovery and browser cases, not inferred from those full-game samples. Full variant and combined-expansion acceptance remains incomplete.

A fresh isolated browser room used genuine Advanced card-variant setup followed by a conserved two-sector battle fixture. Actual controls rejected a partial return, selected two ordinary counters from sector nine, and preserved the selected state after refresh. Following actual owner and engine-driven opponent Traitor declines, two counters returned, the exact remaining ordinary/elite pair went to the Tanks, support cost one, and Harass discarded once. Final refresh restored 18 reserves, two Tanks, 29 spice and the same private Traitor. This is targeted browser evidence, not a complete human game.

All 1038 opening games and original seat/recovery/entry/handover records are unchanged; 1072 rooms remain including new QA. SQLite integrity and foreign keys pass. The healthy development server was reused without restart or reset. No mode/publication gate was opened.

Verified source tree: 61ee78f6e2bce47cb322b04f896db27fef28c56ba2097571a1d85bad5c121156
This commit is contained in:
Quintine committed 2026-09-14 06:37:23 +10:00
1 parent 640342527a
commit 62e87d2b96
18 files changed
+1654 -71

No files matched your search

+282
View File
@@ -0,0 +1,282 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
applyAction,
normalizeAutomaticGame,
viewGame,
type Action,
type Game,
} from '../game/engine';
import { botActions } from '../game/bots';
import { defaultHarassWithdrawAllocation } from '../game/harass-withdraw';
import { harassWithdrawGame, harassCustody } from './fixture-harass-withdraw';
function sealed(advanced = true, sector = false) {
let g = harassWithdrawGame(
advanced
? { advanced, normal: 3, elite: 1 }
: { territory: 'imperial_basin', sector: 9 },
);
if (sector)
g.players[0].forces = { 'imperial_basin:9': 2, 'imperial_basin:10': 3 };
g = applyAction(g, 'a', {
type: 'battlePlan',
dial: 2,
support: advanced ? 1 : 0,
leader: 'emperor-0',
defense: 'ecaz-harass-withdraw',
});
return g;
}
function reveal(g: Game) {
return applyAction(g, 'd', {
type: 'battlePlan',
dial: 0,
support: 0,
leader: 'atreides-0',
});
}
function selection(g: Game, returns: unknown): Action {
return { type: 'decision', event: g.battle!.harassAllocation!.event, returns };
}
function reject(g: Game, id: string, action: Action, re: RegExp) {
const before = JSON.stringify(g);
assert.throws(() => applyAction(g, id, action), re);
assert.equal(JSON.stringify(g), before);
}
function finish(g: Game) {
g = applyAction(g, 'a', { type: 'traitorCall', call: false });
return applyAction(g, 'd', { type: 'traitorCall', call: false });
}
void test('ambiguous Harass stays out of sealed plans and opens only after public reveal', () => {
const s = sealed();
assert.equal(s.battle!.harassAllocation, undefined);
assert.equal(s.decision, null);
assert.equal(viewGame(s, 'd').battle!.plans.a, undefined);
assert.equal(viewGame(s, 'a').battle!.harassAllocation, null);
const g = reveal(s);
assert.equal(g.decision!.kind, 'harassWithdraw');
assert.equal(g.battle!.revealed, true);
assert.equal(viewGame(g, 'd').battle!.harassAllocation, null);
assert.ok(viewGame(g, 'a').battle!.harassAllocation);
assert.deepEqual(g.battle!.plans.a, s.battle!.plans.a);
for (const p of g.players)
assert.deepEqual(
viewGame(JSON.parse(JSON.stringify(g)), p.id),
viewGame(g, p.id),
);
reject(
g,
'd',
{ type: 'traitorCall', call: false },
/decision|waiting|choose|resolve|not available/i,
);
});
void test('every legal Advanced typed choice preserves the selected elite custody through resolution', () => {
for (const returns of [
{ 'arrakeen:10': { normal: 0, elite: 1 } },
{ 'arrakeen:10': { normal: 2, elite: 0 } },
{ 'arrakeen:10': { normal: 3, elite: 0 } },
]) {
const g = reveal(sealed());
const chosen = applyAction(g, 'a', selection(g, returns));
assert.equal(chosen.decision, null);
assert.deepEqual(chosen.players[0].forces, g.players[0].forces);
assert.deepEqual(
viewGame(chosen, 'd').battle!.harassAllocation!.selection,
returns,
);
const done = finish(chosen);
const total = returns['arrakeen:10'].normal + returns['arrakeen:10'].elite;
assert.equal(done.players[0].reserves, 16 + total);
assert.equal(
done.players[0].elites!.reserves,
4 + returns['arrakeen:10'].elite,
);
harassCustody(done);
assert.equal(done.players[0].tanks, 4 - total);
assert.deepEqual(done.players[0].forces, {});
assert.equal(
done.discard.filter((c) => c.id === 'ecaz-harass-withdraw').length,
1,
);
}
});
void test('Basic multi-sector selection withdraws the chosen exact locations without forced early allocation', () => {
const g = reveal(sealed(false, true));
const returns = {
'imperial_basin:9': { normal: 1, elite: 0 },
'imperial_basin:10': { normal: 2, elite: 0 },
};
const chosen = applyAction(g, 'a', selection(g, returns));
assert.deepEqual(chosen.battle!.harassAllocation!.selection, returns);
const done = finish(chosen);
assert.equal(done.players[0].reserves, 18);
assert.equal(done.players[0].tanks, 2);
harassCustody(done);
});
void test('stale, other-owner, partial, overdrawn and forged choices reject without mutation', () => {
const g = reveal(sealed());
const valid = { 'arrakeen:10': { normal: 2, elite: 0 } };
reject(
g,
'd',
selection(g, valid),
/decision|waiting|choose|resolve|not available/i,
);
reject(g, 'a', { ...selection(g, valid), event: 'stale' }, /exact revealed/);
for (const returns of [
null,
{},
{ 'arrakeen:10': { normal: 1, elite: 0 } },
{ 'arrakeen:10': { normal: 5, elite: 0 } },
{ 'carthag:11': { normal: 2, elite: 0 } },
])
reject(
g,
'a',
selection(g, returns),
/selection|return|location|undialed|physical|force/i,
);
const done = applyAction(g, 'a', selection(g, valid));
reject(
done,
'a',
selection(g, valid),
/decision|waiting|choose|resolve|not available/i,
);
});
void test('corrupt saved pending/selected allocations reject reads, normalization and actions', () => {
const pending = reveal(sealed());
const chosen = applyAction(
pending,
'a',
selection(pending, { 'arrakeen:10': { normal: 2, elite: 0 } }),
);
for (const [base, edit] of [
[
pending,
(g: Game) => {
delete g.battle!.harassAllocation;
},
],
[
pending,
(g: Game) => {
g.decision = null;
},
],
[
pending,
(g: Game) => {
g.battle!.plans.a.support = 0;
},
],
[
pending,
(g: Game) => {
g.battle!.harassAllocation!.player = 'd';
},
],
[
chosen,
(g: Game) => {
g.battle!.harassAllocation!.selection = {};
},
],
[
chosen,
(g: Game) => {
delete g.battle!.harassAllocationEvent;
},
],
] as const) {
const g = structuredClone(base);
edit(g);
const before = JSON.stringify(g);
for (const p of g.players)
assert.throws(
() => viewGame(g, p.id),
/withdraw|Harass|returned counters/i,
);
assert.throws(
() => normalizeAutomaticGame(g),
/withdraw|Harass|returned counters/i,
);
assert.throws(
() => applyAction(g, 'a', { type: 'setAutopilot', difficulty: 'Easy' }),
/withdraw|Harass|returned counters/i,
);
assert.equal(JSON.stringify(g), before);
}
});
void test('four AI profiles select real after-reveal allocations using only the owner projection', () => {
const g = reveal(sealed());
for (const difficulty of ['Easy', 'Medium', 'Hard', 'Brutal'] as const) {
const v = viewGame(g, 'a');
v.players[0].bot = difficulty;
const before = JSON.stringify(v),
action = botActions(v)[0];
assert.equal(action?.type, 'decision');
const done = applyAction(g, 'a', action);
assert.equal(done.decision, null);
assert.equal(JSON.stringify(v), before);
const offer = v.battle!.harassAllocation!;
assert.deepEqual(
action.returns,
defaultHarassWithdrawAllocation(offer.context, offer.dial, offer.support),
);
}
});
void test('opposing traitor cancellation ignores the selected return and loses every original board counter', () => {
let g = sealed();
const traitor = g.battle!.plans.a.leader!,
old = g.players[1].traitors[0];
let replaced = false;
for (const p of g.players) {
const at = p.traitors.indexOf(traitor);
if (at >= 0) {
p.traitors[at] = old;
replaced = true;
}
const dancer = p.faceDancers?.find((c) => c.leader === traitor);
if (dancer) {
dancer.leader = old;
replaced = true;
}
}
const at = g.traitorReserve!.indexOf(traitor);
if (at >= 0) {
g.traitorReserve![at] = old;
replaced = true;
}
assert.ok(replaced);
g.players[1].traitors[0] = traitor;
harassCustody(g);
g = reveal(g);
g = applyAction(
g,
'a',
selection(g, { 'arrakeen:10': { normal: 2, elite: 0 } }),
);
g = applyAction(g, 'a', { type: 'traitorCall', call: false });
g = applyAction(g, 'd', { type: 'traitorCall', call: true });
assert.equal(g.players[0].reserves, 16);
assert.equal(g.players[0].tanks, 4);
assert.equal(g.players[0].elites!.reserves, 4);
assert.equal(g.players[0].elites!.tanks, 1);
harassCustody(g);
assert.equal(
g.discard.filter((card) => card.id === 'ecaz-harass-withdraw').length,
1,
);
assert.notEqual(g.decision?.kind, 'battleLosses');
assert.equal(g.players[1].tanks, 0);
assert.equal(
g.log.filter((e) => e.text.includes('used Harass & Withdraw to return'))
.length,
0,
);
});
+194
View File
@@ -0,0 +1,194 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { DatabaseSync } from 'node:sqlite';
import { applyAction, viewGame, type Game } from '../game/engine';
import { unitStore } from './fixture-nexus-room-store';
import { harassWithdrawGame, harassCustody } from './fixture-harass-withdraw';
const clock = { now: () => 84000, sleep: async () => {} };
const rows = (sqlite: DatabaseSync) =>
sqlite.prepare('SELECT * FROM rooms').all();
async function fixture(t: test.TestContext) {
const f = unitStore();
t.after(() => f.sqlite.close());
const made = await f.rooms.createRoom('Harass allocation', 'emperor', true, [
'ix',
]);
const code = made.view.code;
const tokens = [
made.token,
(await f.rooms.joinRoom(code, 'Atreides', 'atreides')).token!,
(await f.rooms.joinRoom(code, 'Tleilaxu', 'tleilaxu')).token!,
];
const auths = await Promise.all(
tokens.map((token) => f.rooms.authenticate(code, token)),
);
const ids = auths.map((a) => a.playerId) as [string, string, string];
let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1, ids });
g.code = code;
g.version = (await f.rooms.readRoom(code)).version;
g = applyAction(g, ids[0], {
type: 'battlePlan',
dial: 2,
support: 1,
leader: 'emperor-0',
defense: 'ecaz-harass-withdraw',
});
g = applyAction(g, ids[1], {
type: 'battlePlan',
dial: 0,
leader: 'atreides-0',
});
harassCustody(g);
f.sqlite
.prepare('UPDATE rooms SET state=?, version=? WHERE code=?')
.run(JSON.stringify(g), g.version, code);
return { ...f, code, tokens, ids, auths, game: g };
}
void test('revealed allocation survives seat restoration; concurrent legal choices select once, with exact winner losses', async (t) => {
const f = await fixture(t),
beforeRows = rows(f.sqlite);
for (const [index, token] of f.tokens.entries()) {
const r = f.restart(),
auth = await r.authenticate(f.code, token);
assert.deepEqual(
await r.readSeatView(f.code, auth),
viewGame(f.game, f.ids[index]),
);
}
assert.deepEqual(rows(f.sqlite), beforeRows);
const rooms = f.restart(),
auth = await rooms.authenticate(f.code, f.tokens[0]);
let entered = 0,
release!: () => void;
const both = new Promise<void>((resolve) => {
release = resolve;
});
f.hooks.beforeWrite = async () => {
if (++entered === 2) release();
await both;
};
const choices = [
{ 'arrakeen:10': { normal: 0, elite: 1 } },
{ 'arrakeen:10': { normal: 2, elite: 0 } },
];
const outcomes = await Promise.allSettled(
choices.map((returns) =>
rooms.act(
f.code,
auth,
f.game.version,
{ type: 'decision', event: f.game.battle!.harassAllocation!.event, returns },
clock,
),
),
);
f.hooks.beforeWrite = undefined;
assert.equal(outcomes.filter((r) => r.status === 'fulfilled').length, 1);
let g = await f.restart().readRoom(f.code);
assert.equal(g.version, f.game.version + 1);
const selected = g.battle!.harassAllocation!.selection!['arrakeen:10'];
assert.equal(g.players[0].reserves, 16);
assert.equal(g.decision, null);
for (const [index, token] of f.tokens.entries()) {
const r = f.restart(),
a = await r.authenticate(f.code, token);
assert.deepEqual(
(await r.readSeatView(f.code, a)).battle!.harassAllocation!.selection,
g.battle!.harassAllocation!.selection,
);
assert.deepEqual(
await r.readSeatView(f.code, a),
viewGame(g, f.ids[index]),
);
}
const staleRows = rows(f.sqlite);
await assert.rejects(() =>
f
.restart()
.act(
f.code,
auth,
f.game.version,
{
type: 'decision',
event: f.game.battle!.harassAllocation!.event,
returns: choices[0],
},
clock,
),
);
assert.deepEqual(rows(f.sqlite), staleRows);
for (const index of [0, 1]) {
const r = f.restart(),
a = await r.authenticate(f.code, f.tokens[index]);
await r.act(
f.code,
a,
g.version,
{ type: 'traitorCall', call: false },
clock,
);
g = await r.readRoom(f.code);
}
assert.equal(g.battle, null);
assert.equal(g.players[0].reserves, 16 + selected.normal + selected.elite);
assert.equal(g.players[0].tanks, 4 - selected.normal - selected.elite);
assert.deepEqual(g.players[0].forces, {});
assert.equal(g.players[0].elites!.reserves, 4 + selected.elite);
harassCustody(g);
assert.equal(
g.log.filter(
(e) =>
e.text.includes('selected') &&
e.text.includes('undialed forces for Harass'),
).length,
1,
);
assert.equal(
g.log.filter((e) => e.text.includes('used Harass & Withdraw to return'))
.length,
1,
);
});
void test('lost or edited saved physical choice cannot normalize or write through authenticated room recovery', async (t) => {
const f = await fixture(t);
for (const edit of [
(g: Game) => {
g.decision = null;
},
(g: Game) => {
delete g.battle!.harassAllocationEvent;
},
(g: Game) => {
g.battle!.harassAllocation!.frame += 'changed';
},
]) {
const bad = structuredClone(f.game);
edit(bad);
f.sqlite
.prepare('UPDATE rooms SET state=? WHERE code=?')
.run(JSON.stringify(bad), f.code);
const before = rows(f.sqlite);
const r = f.restart();
await assert.rejects(
() => r.readSeatView(f.code, f.auths[0]),
/withdraw|Harass/i,
);
await assert.rejects(
() =>
r.act(
f.code,
f.auths[0],
bad.version,
{
type: 'decision',
event: f.game.battle!.harassAllocation!.event,
returns: { 'arrakeen:10': { normal: 2, elite: 0 } },
},
clock,
),
/withdraw|Harass/i,
);
assert.deepEqual(rows(f.sqlite), before);
}
});
+330
View File
@@ -0,0 +1,330 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { casualtyOptions } from '../game/combat';
import {
defaultHarassWithdrawAllocation,
harassWithdrawCommitments,
harassWithdrawNeedsAllocation,
quoteHarassWithdraw,
HarassWithdrawError,
type HarassWithdrawContext,
type HarassWithdrawSelection,
} from '../game/harass-withdraw';
const mixed = (): HarassWithdrawContext => ({
blocked: null,
forces: { normal: 3, elite: 2, eliteStrength: 1, freeSupport: true },
locations: {
'imperial_basin:9': { normal: 2, elite: 1 },
'imperial_basin:10': { normal: 1, elite: 1 },
},
});
const ordinary = (): HarassWithdrawContext => ({
blocked: null,
forces: { normal: 5, elite: 0, eliteStrength: 1, freeSupport: false },
locations: {
'imperial_basin:9': { normal: 2, elite: 0 },
'imperial_basin:10': { normal: 3, elite: 0 },
},
});
function reject(
context: HarassWithdrawContext,
dial: number,
support: number,
selection: unknown,
) {
const before = structuredClone({ context, selection });
assert.throws(
() =>
quoteHarassWithdraw(
context,
dial,
support,
selection as HarassWithdrawSelection,
),
HarassWithdrawError,
);
assert.deepEqual({ context, selection }, before);
}
void test('mixed regular/elite commitments are physical choices; explicit returns select one without mutating custody', () => {
const context = mixed();
const before = structuredClone(context);
assert.deepEqual(harassWithdrawCommitments(context, 2, 0), [
{ normal: 2, elite: 0 },
{ normal: 1, elite: 1 },
{ normal: 0, elite: 2 },
]);
assert.equal(harassWithdrawNeedsAllocation(context, 2, 0), true);
assert.throws(
() => quoteHarassWithdraw(context, 2, 0),
/ambiguous regular\/elite/,
);
const selection = {
'imperial_basin:9': { normal: 1, elite: 1 },
'imperial_basin:10': { normal: 1, elite: 0 },
};
const quote = quoteHarassWithdraw(context, 2, 0, selection);
assert.deepEqual(quote.returned, { normal: 2, elite: 1 });
assert.deepEqual(quote.remaining, { ...context.forces, normal: 1, elite: 1 });
assert.deepEqual(quote.locations, selection);
assert.notEqual(quote.locations, selection);
assert.notEqual(
quote.locations['imperial_basin:9'],
selection['imperial_basin:9'],
);
assert.deepEqual(context, before);
});
void test('multiple sectors may explicitly divide a uniquely typed return while legacy callers retain the sector guard', () => {
const context = ordinary();
assert.deepEqual(harassWithdrawCommitments(context, 2, 2), [
{ normal: 2, elite: 0 },
]);
assert.equal(harassWithdrawNeedsAllocation(context, 2, 2), true);
assert.throws(
() => quoteHarassWithdraw(context, 2, 2),
/ambiguous allocation among sectors/,
);
for (const [a, b] of [
[0, 3],
[1, 2],
[2, 1],
]) {
const quote = quoteHarassWithdraw(context, 2, 2, {
'imperial_basin:9': { normal: a, elite: 0 },
'imperial_basin:10': { normal: b, elite: 0 },
});
assert.deepEqual(quote.returned, { normal: 3, elite: 0 });
assert.deepEqual(quote.remaining, { ...context.forces, normal: 2 });
assert.ok(
Object.values(quote.locations).every(
(group) => group.normal + group.elite > 0,
),
);
}
});
void test('Advanced paid/unpaid and Ixian half-strength commitments retain exact regular/elite complements', () => {
for (const forces of [
{ normal: 3, elite: 2, eliteStrength: 2 as const, freeSupport: false },
{
normal: 3,
elite: 2,
eliteStrength: 2 as const,
freeSupport: false,
normalFixedHalf: true,
},
{
normal: 3,
elite: 2,
eliteStrength: 1 as const,
freeSupport: false,
eliteFreeSupport: true,
},
]) {
const context: HarassWithdrawContext = { ...mixed(), forces };
for (const [dial, support] of [
[0.5, 0],
[2, 0],
[2, 1],
[3, 2],
]) {
const choices = casualtyOptions(forces, dial, support);
if (!choices.length) continue;
const physical = harassWithdrawCommitments(context, dial, support);
assert.equal(
new Set(physical.map((choice) => JSON.stringify(choice))).size,
physical.length,
);
assert.ok(
physical.every(
(choice) => Object.keys(choice).sort().join(',') === 'elite,normal',
),
);
for (const choice of physical) {
let normal = forces.normal - choice.normal,
elite = forces.elite - choice.elite;
const selection = Object.fromEntries(
Object.entries(context.locations).map(([key, group]) => {
const selected = {
normal: Math.min(normal, group.normal),
elite: Math.min(elite, group.elite),
};
normal -= selected.normal;
elite -= selected.elite;
return [key, selected];
}),
);
const quote = quoteHarassWithdraw(context, dial, support, selection);
assert.deepEqual(
{ normal: quote.remaining.normal, elite: quote.remaining.elite },
choice,
);
}
}
}
});
void test('default physical returns are deterministic across location insertion order and are always legal', () => {
const context = mixed(),
before = structuredClone(context);
const reversed = {
...context,
locations: Object.fromEntries(Object.entries(context.locations).reverse()),
};
for (const dial of [0, 1, 2, 5]) {
const allocation = defaultHarassWithdrawAllocation(context, dial, 0);
assert.deepEqual(
allocation,
defaultHarassWithdrawAllocation(reversed, dial, 0),
);
const quote = quoteHarassWithdraw(context, dial, 0, allocation);
assert.deepEqual(quote.locations, allocation);
assert.deepEqual(
{ normal: quote.remaining.normal, elite: quote.remaining.elite },
harassWithdrawCommitments(context, dial, 0)[0],
);
}
assert.deepEqual(context, before);
});
void test('a chosen physical commitment gets a shared legal default, while invented or malformed commitments reject', () => {
const context = mixed(),
before = structuredClone(context);
for (const commitment of harassWithdrawCommitments(context, 2, 0)) {
const selection = defaultHarassWithdrawAllocation(
context,
2,
0,
commitment,
);
const quote = quoteHarassWithdraw(context, 2, 0, selection);
assert.deepEqual(
{ normal: quote.remaining.normal, elite: quote.remaining.elite },
commitment,
);
}
for (const commitment of [
{ normal: 3, elite: 0 },
{ normal: 1, elite: 0 },
{ normal: 1, elite: 1, paidNormal: 0 },
{ normal: -1, elite: 3 },
null,
])
assert.throws(
() => defaultHarassWithdrawAllocation(context, 2, 0, commitment as never),
HarassWithdrawError,
);
assert.deepEqual(context, before);
});
void test('explicit empty returns require a full physical commitment, while zero dial returns every physical counter', () => {
const context = ordinary();
assert.deepEqual(quoteHarassWithdraw(context, 5, 5, {}).returned, {
normal: 0,
elite: 0,
});
assert.equal(harassWithdrawNeedsAllocation(context, 5, 5), false);
assert.deepEqual(
quoteHarassWithdraw(context, 5, 5),
quoteHarassWithdraw(context, 5, 5, {}),
);
reject(context, 2, 2, {});
assert.equal(harassWithdrawNeedsAllocation(context, 0, 0), false);
assert.deepEqual(
quoteHarassWithdraw(context, 0, 0).locations,
context.locations,
);
assert.deepEqual(
quoteHarassWithdraw(context, 0, 0, context.locations).remaining,
{ ...context.forces, normal: 0, elite: 0 },
);
});
void test('return selection rejects malformed groups, unknown locations, overdraw and a wrong typed complement immutably', () => {
const context = mixed();
for (const selection of [
null,
[],
2,
'all',
{ 'unknown:0': { normal: 3, elite: 0 } },
{ 'imperial_basin:9': { normal: 3, elite: 0 } },
{ 'imperial_basin:9': { normal: 0, elite: 2 } },
{ 'imperial_basin:9': { normal: 1 } },
{ 'imperial_basin:9': { normal: 1, elite: 1, paidNormal: 1 } },
{ 'imperial_basin:9': { normal: -1, elite: 0 } },
{ 'imperial_basin:9': { normal: 0.5, elite: 0 } },
{ 'imperial_basin:9': { normal: NaN, elite: 0 } },
{ 'imperial_basin:9': { normal: Number.MAX_SAFE_INTEGER + 1, elite: 0 } },
{ 'imperial_basin:9': { normal: '2', elite: 1 } },
{ 'imperial_basin:9': { normal: 1, elite: 0 } },
])
reject(context, 2, 0, selection);
const advanced = {
...context,
forces: { ...context.forces, eliteStrength: 2 as const },
};
// Leaves two regular counters: strength two, not the revealed strength four.
reject(advanced, 4, 0, {
'imperial_basin:9': { normal: 1, elite: 1 },
'imperial_basin:10': { normal: 0, elite: 1 },
});
});
void test('all allocation helpers validate context and dial before reporting an ambiguous or default choice', () => {
for (const context of [
{ ...mixed(), blocked: 'A combined rule remains guarded.' },
{ ...mixed(), locations: null },
{ ...mixed(), locations: [] },
{ ...mixed(), locations: { 'imperial_basin:9': { normal: 3, elite: 1 } } },
{
...mixed(),
locations: { 'imperial_basin:9': { normal: 3, elite: 2, other: 0 } },
},
{ ...mixed(), forces: { ...mixed().forces, elite: 0, temporaryElite: 1 } },
] as unknown as HarassWithdrawContext[]) {
const before = structuredClone(context);
for (const helper of [
harassWithdrawCommitments,
harassWithdrawNeedsAllocation,
defaultHarassWithdrawAllocation,
])
assert.throws(() => helper(context, 2, 0), HarassWithdrawError);
assert.deepEqual(context, before);
}
for (const [dial, support] of [
[NaN, 0],
[1.25, 0],
[-1, 0],
[2, 0.5],
[2, 6],
])
for (const helper of [
harassWithdrawCommitments,
harassWithdrawNeedsAllocation,
defaultHarassWithdrawAllocation,
])
assert.throws(
() => helper(ordinary(), dial, support),
HarassWithdrawError,
);
});
void test('legacy omitted returns retain insertion order and unique allocation JSON shape', () => {
const context: HarassWithdrawContext = {
blocked: null,
forces: { normal: 3, elite: 2, eliteStrength: 2, freeSupport: true },
locations: {
'imperial_basin:9': { normal: 0, elite: 2 },
'imperial_basin:11': { normal: 3, elite: 0 },
},
};
const quote = quoteHarassWithdraw(context, 0, 0);
assert.equal(
JSON.stringify(quote.locations),
'{"imperial_basin:11":{"normal":3,"elite":0},"imperial_basin:9":{"normal":0,"elite":2}}',
);
assert.equal(harassWithdrawNeedsAllocation(context, 0, 0), false);
});
@@ -0,0 +1,182 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import {
HarassWithdrawChoice,
harassWithdrawChoiceState,
} from '../components/harass-withdraw-choice';
import {
HarassWithdrawGuide,
harassWithdrawControlState,
} from '../components/harass-withdraw';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import { applyAction, viewGame, type Game } from '../game/engine';
import {
defaultHarassWithdrawAllocation,
harassWithdrawCommitments,
} from '../game/harass-withdraw';
import { harassWithdrawGame } from './fixture-harass-withdraw';
function submitPlans(game: Game) {
const owner = game.players[0];
const opponent = game.players[1];
let next = applyAction(game, owner.id, {
type: 'battlePlan',
dial: game.advanced ? 2 : 2,
support: game.advanced ? 1 : 0,
leader: owner.leaders.find((leader) => !leader.dead)!.id,
weapon: 'ecaz-harass-withdraw',
});
next = applyAction(next, opponent.id, {
type: 'battlePlan',
dial: 0,
support: 0,
leader: opponent.leaders.find((leader) => !leader.dead)!.id,
});
assert.equal(next.decision?.kind, 'harassWithdraw');
return next;
}
function multiSectorGame() {
const game = harassWithdrawGame({
territory: 'imperial_basin',
sector: 9,
});
game.players[0].forces = {
'imperial_basin:9': 2,
'imperial_basin:10': 3,
};
return game;
}
void test('pre-seal guidance permits a supported ambiguous plan and defers its private allocation', () => {
const game = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 });
const preview = viewGame(game, 'a').battle!.harassWithdraw!;
const state = harassWithdrawControlState(preview, true, 2, 1);
assert.deepEqual(state, { blocked: null, returned: null });
const html = renderToStaticMarkup(
createElement(HarassWithdrawGuide, { preview, state }),
);
assert.match(html, /After plans are revealed/);
assert.match(html, /choose exactly which undialed ordinary and elite forces/);
assert.doesNotMatch(html, /ambiguous regular\/elite/);
for (const difficulty of DIFFICULTIES) {
const botView = viewGame(game, 'a');
botView.players.find((player) => player.id === 'a')!.bot = difficulty;
const candidates = botActions(botView).filter(
(action) =>
action.type === 'battlePlan' &&
(action.weapon === 'ecaz-harass-withdraw' ||
action.defense === 'ecaz-harass-withdraw'),
);
assert.ok(candidates.length, `${difficulty} omitted legal Harass plans`);
assert.ok(
candidates.every((action) => !Object.hasOwn(action, 'returns')),
`${difficulty} exposed an early return selection`,
);
}
});
void test('the revealed owner gets exact commitment and per-sector controls while rivals get no allocation', () => {
const revealed = submitPlans(multiSectorGame());
const ownerView = viewGame(revealed, 'a');
const observerView = viewGame(revealed, 't');
assert.equal(observerView.battle!.harassAllocation, null);
const offer = ownerView.battle!.harassAllocation!;
assert.equal(offer.selection, null);
const commitments = harassWithdrawCommitments(
offer.context,
offer.dial,
offer.support,
);
assert.deepEqual(commitments, [{ normal: 2, elite: 0 }]);
const first = defaultHarassWithdrawAllocation(
offer.context,
offer.dial,
offer.support,
commitments[0],
);
assert.deepEqual(first, {
'imperial_basin:10': { normal: 3, elite: 0 },
});
assert.equal(
harassWithdrawChoiceState(offer.context, offer.dial, offer.support, first)
.blocked,
null,
);
assert.match(
harassWithdrawChoiceState(offer.context, offer.dial, offer.support, {
'imperial_basin:9': { normal: 2, elite: 0 },
}).blocked!,
/exact undialed complement/,
);
const html = renderToStaticMarkup(
createElement(HarassWithdrawChoice, {
game: ownerView,
act() {},
busy: false,
}),
);
assert.match(html, /aria-label="Harass and Withdraw force allocation"/);
assert.match(html, /Dialed physical commitment/);
assert.match(html, /2 ordinary · 0 elite/);
assert.match(html, /Imperial Basin · sector 9/);
assert.match(html, /Imperial Basin · sector 10/);
assert.match(html, /Confirm returned forces/);
assert.equal(
renderToStaticMarkup(
createElement(HarassWithdrawChoice, {
game: observerView,
act() {},
busy: false,
}),
),
'',
);
assert.match(
renderToStaticMarkup(
createElement(HarassWithdrawChoice, {
game: ownerView,
act() {},
busy: true,
}),
),
/disabled=""/,
);
});
void test('every bot profile submits the shared deterministic allocation only at its revealed decision', () => {
for (const difficulty of DIFFICULTIES) {
const revealed = submitPlans(
harassWithdrawGame({ advanced: true, normal: 3, elite: 1 }),
);
const view = viewGame(revealed, 'a');
view.players.find((player) => player.id === 'a')!.bot = difficulty;
const offer = view.battle!.harassAllocation!;
const expected = defaultHarassWithdrawAllocation(
offer.context,
offer.dial,
offer.support,
);
const action = botActions(view)[0];
assert.deepEqual(action, {
type: 'decision',
event:
revealed.decision?.kind === 'harassWithdraw'
? revealed.decision.event
: '',
returns: expected,
});
const selected = applyAction(revealed, 'a', action);
assert.deepEqual(selected.battle!.harassAllocation!.selection, expected);
assert.notEqual(selected.decision?.kind, 'harassWithdraw');
assert.deepEqual(
viewGame(selected, 't').battle!.harassAllocation!.selection,
expected,
);
}
});
+4 -1
View File
@@ -445,8 +445,9 @@ void test('co-present reciprocal Ecaz allies are publicly guarded before sealing
}
});
void test('ambiguous unit mixes and sector allocations reject before sealing without hidden opponent dependence', () => {
void test('legacy ambiguous unit mixes and sector allocations reject before sealing without hidden opponent dependence', () => {
let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 });
delete g.battle!.harassAllocationVersion;
reject(
g,
'a',
@@ -454,6 +455,7 @@ void test('ambiguous unit mixes and sector allocations reject before sealing wit
/ambiguous regular\/elite/,
);
g = harassWithdrawGame({ territory: 'imperial_basin', sector: 9 });
delete g.battle!.harassAllocationVersion;
g.players[0].forces = { 'imperial_basin:9': 2, 'imperial_basin:10': 3 };
const preview = viewGame(g, 'a').battle!.harassWithdraw!;
assert.throws(
@@ -686,6 +688,7 @@ void test('Reinforcements and public Richese/optional-module contexts remain gua
void test('malformed sealed withdrawal allocations reject private reads and both ordinary/autopilot actions', () => {
let g = harassWithdrawGame({ advanced: true, normal: 3, elite: 1 });
delete g.battle!.harassAllocationVersion;
g = applyAction(g, 'a', ownPlan(g, { dial: 0, support: 0 }));
g.battle!.plans.a.dial = 2;
g.battle!.plans.a.support = 1;