@chrischall/warapp-mcp 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +2 -2
  4. package/dist/analysis/card-support.js +12 -4
  5. package/dist/analysis/coalition.js +55 -0
  6. package/dist/analysis/local-deploy.js +14 -0
  7. package/dist/analysis/opponents.js +2 -1
  8. package/dist/analysis/picks.js +270 -37
  9. package/dist/analysis/plan/after-leftover.js +26 -4
  10. package/dist/analysis/plan/captures.js +76 -13
  11. package/dist/analysis/plan/completed.js +8 -1
  12. package/dist/analysis/plan/conceded-out.js +16 -11
  13. package/dist/analysis/plan/deploy-estimates.js +513 -0
  14. package/dist/analysis/plan/doomed-out.js +135 -0
  15. package/dist/analysis/plan/estimates.js +3 -1
  16. package/dist/analysis/plan/free-capture.js +34 -0
  17. package/dist/analysis/plan/holds.js +8 -309
  18. package/dist/analysis/plan/horizon.js +42 -0
  19. package/dist/analysis/plan/leftover.js +43 -5
  20. package/dist/analysis/plan/observe.js +896 -0
  21. package/dist/analysis/plan/orders.js +35 -1
  22. package/dist/analysis/plan/report.js +10 -4
  23. package/dist/analysis/plan/shared.js +4 -1376
  24. package/dist/analysis/plan/stand-still.js +5 -3
  25. package/dist/analysis/plan/state.js +12 -0
  26. package/dist/analysis/plan/strike-stack.js +467 -0
  27. package/dist/analysis/plan/strike.js +3 -463
  28. package/dist/analysis/plan/targets.js +213 -26
  29. package/dist/analysis/plan/threats.js +12 -4
  30. package/dist/analysis/plan/transfers.js +24 -1
  31. package/dist/analysis/plan/two-move.js +1 -1
  32. package/dist/analysis/plan/withdraw.js +316 -0
  33. package/dist/analysis/planner.js +54 -11
  34. package/dist/analysis/player.js +4 -0
  35. package/dist/analysis/relations.js +8 -2
  36. package/dist/analysis/stress.js +1 -1
  37. package/dist/bundle.js +8008 -7184
  38. package/dist/my-games.js +2 -0
  39. package/dist/open-games.js +94 -10
  40. package/dist/tools/card-advice.js +26 -11
  41. package/dist/tools/card-support-advice.js +17 -1
  42. package/dist/tools/check-plan.js +2 -1
  43. package/dist/tools/commander-check.js +2 -1
  44. package/dist/tools/decision-capture.js +4 -2
  45. package/dist/tools/join-game.js +44 -8
  46. package/dist/tools/live.js +33 -5
  47. package/dist/tools/open-games.js +2 -2
  48. package/dist/tools/picks.js +120 -47
  49. package/dist/tools/turn.js +43 -4
  50. package/dist/version.js +1 -1
  51. package/manifest.json +1 -1
  52. package/package.json +1 -1
  53. package/server.json +2 -2
package/dist/my-games.js CHANGED
@@ -175,6 +175,8 @@ export function activeGameIds(games, myInGameId) {
175
175
  .filter((g) => g.players.some((p) => p.id === myInGameId && p.stateCode === PLAYER_PLAYING))
176
176
  .map((g) => g.id);
177
177
  }
178
+ /** Games I am playing now: being played or picked with my seat playing (the policy's cap counts these, #423). */
179
+ export const attendedGames = (games, myInGameId) => activeGameIds(games, myInGameId).length;
178
180
  /**
179
181
  * Games whose chat is live (#256): lobbies, games being picked and games being played — every
180
182
  * game in the list but a finished one, whatever my seat's state — plus a finished game whose chat
@@ -47,7 +47,15 @@ const GI = {
47
47
  players: 16,
48
48
  realTime: 19,
49
49
  settings: 21,
50
+ tournament: 25,
50
51
  };
52
+ /**
53
+ * GameInfoTournament (#423): the coin structure, a number, and the tournament's id (verified live 2026-11-22: the id of
54
+ * both of my tournament games was in war.app's `/API/GameIDFeed?TournamentID=` list; 54 other games held no record).
55
+ */
56
+ const GAME_INFO_TOURNAMENT = 'warlight.shared.GameInfoTournament';
57
+ const GAME_INFO_TOURNAMENT_FIELDS = 3;
58
+ const GT = { tournamentId: 2 };
51
59
  /** GameInfoPlayer: the colour (an optional GameColor), the in-game id, the state (GamePlayerState) and the team. */
52
60
  // `ai` is the client's IsAI (GameInfoPlayer is built from GamePlayer's get_IsAI in that place; read from the bundle).
53
61
  const GP = { color: 0, ai: 4, id: 6, state: 7, team: 8 };
@@ -325,12 +333,25 @@ function readOpenGame(record) {
325
333
  game.openSeatTeams = openSeatTeams;
326
334
  if (settings?.cards)
327
335
  game.cards = settings.cards;
336
+ const tournamentId = tournamentOf(f[GI.tournament]);
337
+ if (tournamentId !== undefined)
338
+ game.tournamentId = tournamentId;
328
339
  const colorsTaken = [...new Set(all.map((p) => p.color).filter((c) => c !== null))];
329
340
  return {
330
341
  game: orderKeys(game),
331
342
  lobby: { seatedPlayerIds: seated.map((p) => p.id), colorsTaken, seated: seated.map((p) => ({ id: p.id, team: p.team, ai: p.ai })) },
332
343
  };
333
344
  }
345
+ /** The tournament id a GameInfoTournament carries (#423); undefined for none or a shape this server does not know. */
346
+ function tournamentOf(v) {
347
+ if (!isObj(v) || v.$type !== GAME_INFO_TOURNAMENT)
348
+ return undefined;
349
+ const f = fields(v);
350
+ if (f.length !== GAME_INFO_TOURNAMENT_FIELDS)
351
+ return undefined;
352
+ const id = f[GT.tournamentId];
353
+ return isInt(id) && id > 0 ? id : undefined;
354
+ }
334
355
  /** `games` with `joined: true` on each lobby where the in-game id `me` holds a seat. */
335
356
  export function markJoined(games, lobbies, me) {
336
357
  return games.map((g) => (lobbies.get(g.id)?.seatedPlayerIds.includes(me) ? orderKeys({ ...g, joined: true }) : g));
@@ -341,7 +362,7 @@ export function withLottery(game, verdict) {
341
362
  }
342
363
  const KEY_ORDER = [
343
364
  'id', 'name', 'url', 'pace', 'bootTime', 'bootTimeMinutes', 'players', 'openSeats', 'seats', 'maxPlayers',
344
- 'teamGame', 'joined', 'lottery', 'lotteryBasis', 'randomTeamsOf', 'openSeatTeams', 'mapId', 'entryFeeCoins', 'prizeCoins', 'cards', 'rules', 'plannerGaps',
365
+ 'teamGame', 'joined', 'tournamentId', 'lottery', 'lotteryBasis', 'randomTeamsOf', 'openSeatTeams', 'mapId', 'entryFeeCoins', 'prizeCoins', 'cards', 'rules', 'plannerGaps',
345
366
  ];
346
367
  function orderKeys(g) {
347
368
  const out = {};
@@ -473,19 +494,58 @@ const POLICY_MIN_BOOT_MINUTES = 12 * 60;
473
494
  * boot time — war.app's "never" — keeps it); no lotteries (#217: `game.lottery`; a likely one whose
474
495
  * map size went unread breaks it too). Lobbies are not counted against the game cap. Pure.
475
496
  */
476
- export function joiningPolicy(game, screen) {
477
- const breaks = policyBreaks(game, screen).map((b) => b.text);
497
+ export function joiningPolicy(game, screen, account) {
498
+ const breaks = policyBreaks(game, screen, account).map((b) => b.text);
499
+ const warnings = policyWarnings(game);
500
+ const warned = warnings.length ? { warnings } : {};
478
501
  if (breaks.length)
479
- return { passes: false, breaks };
502
+ return { passes: false, breaks, ...warned };
480
503
  const unchecked = [];
481
504
  if (!screen)
482
505
  unchecked.push("the cheapest neutral's cost");
483
- return unchecked.length ? { passes: null, breaks, unchecked } : { passes: true, breaks };
506
+ if (account && account.attendedGames === undefined)
507
+ unchecked.push('how many games I am playing');
508
+ if (account && account.negativeBonus === undefined)
509
+ unchecked.push("whether the map has a negative bonus");
510
+ return unchecked.length ? { passes: null, breaks, unchecked, ...warned } : { passes: true, breaks, ...warned };
511
+ }
512
+ /**
513
+ * What the joining policy warns about but never refuses (#423; owner 2026-11-22: a tournament game warns, it never
514
+ * refuses; a game from a template already running is allowed with no preference, so it is not here). Pure.
515
+ */
516
+ export function policyWarnings(game) {
517
+ const out = [];
518
+ if (game.tournamentId !== undefined) {
519
+ out.push(`A tournament game (tournament ${game.tournamentId}): it counts in the tournament, a surrender or boot is a loss there, ` +
520
+ 'and a vote to end is not allowed — join only meaning to play it out');
521
+ }
522
+ return out;
484
523
  }
524
+ /**
525
+ * The owner's cap on games played at once (2026-11-22: 15): a game being played or picked, my seat playing; lobbies
526
+ * are not counted. Joining at the cap breaks the policy.
527
+ */
528
+ export const ATTENDED_GAMES_LIMIT = 15;
485
529
  /** The joining policy's checks, by code, in policy order (#437: the decision log's join context). */
486
- export const POLICY_CHECKS = ['commerce', 'mods', 'custom-scenario', 'neutral-cost', 'seats', 'boot-time', 'lottery'];
530
+ export const POLICY_CHECKS = [
531
+ 'commerce',
532
+ 'mods',
533
+ 'custom-scenario',
534
+ 'neutral-cost',
535
+ 'seats',
536
+ 'boot-time',
537
+ 'lottery',
538
+ 'local-deployment',
539
+ 'commanders',
540
+ 'no-split',
541
+ 'army-cap',
542
+ 'multi-attack',
543
+ 'kill-rates',
544
+ 'attended-games',
545
+ 'negative-bonus',
546
+ ];
487
547
  /** Each rule `game` breaks, its code and the policy's words, in policy order. Pure. */
488
- function policyBreaks(game, screen) {
548
+ function policyBreaks(game, screen, account) {
489
549
  const breaks = [];
490
550
  if (game.rules.some((r) => r.startsWith('Commerce')))
491
551
  breaks.push({ code: 'commerce', text: 'Commerce — the policy joins no Commerce games' });
@@ -501,6 +561,19 @@ function policyBreaks(game, screen) {
501
561
  : `Costly neutrals — the cheapest takes ${screen.armiesToTake} armies, ${screen.turnsOfBaseIncome ?? '∞'} turns of base income; the policy is at most one turn`,
502
562
  });
503
563
  }
564
+ // #423: handicap rules (12 of 26 games played under them): each one is a break, so a join needs an explicit override.
565
+ if (game.rules.includes('Local deployments'))
566
+ breaks.push({ code: 'local-deployment', text: 'Local Deployment — the policy joins no Local Deployment games' });
567
+ if (game.rules.includes('Commanders'))
568
+ breaks.push({ code: 'commanders', text: 'Commanders — the policy joins no Commanders games' });
569
+ if (game.rules.includes('No-split mode'))
570
+ breaks.push({ code: 'no-split', text: 'No-Split — the policy joins no No-Split games' });
571
+ if (game.rules.some((r) => r.startsWith('Army cap')))
572
+ breaks.push({ code: 'army-cap', text: 'An army cap — the policy joins no capped games' });
573
+ if (game.rules.includes('Multi-attack'))
574
+ breaks.push({ code: 'multi-attack', text: 'Multi-Attack — the policy joins no Multi-Attack games' });
575
+ if (game.rules.some((r) => r.startsWith('Kill rates')))
576
+ breaks.push({ code: 'kill-rates', text: 'Kill rates other than 60/70 — the policy joins only the default rates' });
504
577
  const seats = game.maxPlayers ?? game.seats;
505
578
  if (seats > POLICY_MAX_SEATS)
506
579
  breaks.push({ code: 'seats', text: `${seats} seats — the policy is 1v1 or at most four players` });
@@ -513,16 +586,27 @@ function policyBreaks(game, screen) {
513
586
  // breaks must not let one through (#217 live check).
514
587
  if (game.lottery === null)
515
588
  breaks.push({ code: 'lottery', text: `Likely a lottery (${game.lotteryBasis ?? 'map size not read'}) — the policy joins no lotteries` });
589
+ if (account?.attendedGames !== undefined && account.attendedGames >= ATTENDED_GAMES_LIMIT) {
590
+ breaks.push({ code: 'attended-games', text: `${account.attendedGames} games already being played — the policy is at most ${ATTENDED_GAMES_LIMIT} at once` });
591
+ }
592
+ if (account?.negativeBonus === true)
593
+ breaks.push({ code: 'negative-bonus', text: 'The map has a negative bonus — the policy joins no negative-bonus maps' });
516
594
  return breaks;
517
595
  }
518
596
  /**
519
597
  * {@link joiningPolicy} by code (#437): the checks broken, passed and not checked (the neutral cost without
520
598
  * the lobby's screen), and the verdict. Pure.
521
599
  */
522
- export function policyChecks(game, screen) {
523
- const broke = [...new Set(policyBreaks(game, screen).map((b) => b.code))];
600
+ export function policyChecks(game, screen, account) {
601
+ const broke = [...new Set(policyBreaks(game, screen, account).map((b) => b.code))];
524
602
  const unchecked = screen ? [] : ['neutral-cost'];
525
- const passed = POLICY_CHECKS.filter((c) => !broke.includes(c) && !unchecked.includes(c));
603
+ // The two account checks run only when the caller gave an account (the list tool has none: not evaluated, not unchecked).
604
+ if (account && account.attendedGames === undefined)
605
+ unchecked.push('attended-games');
606
+ if (account && account.negativeBonus === undefined)
607
+ unchecked.push('negative-bonus');
608
+ const notEvaluated = account ? [] : ['attended-games', 'negative-bonus'];
609
+ const passed = POLICY_CHECKS.filter((c) => !broke.includes(c) && !unchecked.includes(c) && !notEvaluated.includes(c));
526
610
  return { passes: broke.length ? false : unchecked.length ? null : true, broke, passed, unchecked };
527
611
  }
528
612
  /**
@@ -8,7 +8,7 @@ import { adviseOrderDelay, CARD_BLOCKADE, CARD_ORDER_DELAY, CARD_REINFORCEMENT,
8
8
  import { blockadeOffer, bombAdvice, bombExposure, wallOffer, wallThreats } from '../analysis/card-threats.js';
9
9
  import { bonusTerritories } from '../analysis/bonuses.js';
10
10
  import { diplomacyOpponents, supportAdvice } from './card-support-advice.js';
11
- export { intelOrders } from './card-support-advice.js';
11
+ export { giftInOrders, intelOrders } from './card-support-advice.js';
12
12
  import { inGameId } from '../live.js';
13
13
  import { capturePieceValue, cardClock } from '../strategy/card-clock.js';
14
14
  import { isTeamGame, teammatesOf as teamOf } from '../teams.js';
@@ -299,15 +299,30 @@ export function cardPieceOption(settings, hand) {
299
299
  return v.armies !== null && v.armies > 0 ? { cardPieceValue: v.armies } : {};
300
300
  }
301
301
  /**
302
- * #164: an opponent's Reinforcement card for the threat model: the first turn one can be in a hand
303
- * (the card clock's fastest), the armies it adds (a fixed card's `FixedArmies`, else the
304
- * Reinforcement card in my hand as it is worth now) and the capturing turns each further card
305
- * takes. `undefined` when no Reinforcement card is in play or what it adds is unknown.
302
+ * #164: an opponent's Reinforcement card for the threat model: the first turn one can be in a hand,
303
+ * the armies it adds (a fixed card's `FixedArmies`, else the Reinforcement card in my hand as it is
304
+ * worth now) and the capturing turns each further card takes. `undefined` when no Reinforcement card
305
+ * is in play, none ever comes, or what it adds is unknown.
306
+ *
307
+ * #427 (proposed, owner approval pending): the clock runs at the EXPECTED weighted rate — the card's
308
+ * minimum per capturing turn plus its weighted share of the pieces drawn at random (`capturePieceValue`'s
309
+ * rate) — not the fastest (every random piece a Reinforcement piece), which counted a card every turn or
310
+ * two where one comes every few. Where no piece is drawn at random (most games) the two are the same.
306
311
  */
307
312
  export function opponentReinforcement(settings, hand) {
308
- const entry = cardClock(settings)?.cards.find((c) => c.card === 'Reinforcement');
309
- const first = entry?.firstPlayableTurn.fastest;
310
- if (!entry || first === null || first === undefined)
313
+ const clock = cardClock(settings);
314
+ const entry = clock?.cards.find((c) => c.card === 'Reinforcement');
315
+ if (!clock || !entry)
316
+ return undefined;
317
+ const drawWeight = clock.cards.reduce((n, c) => n + c.weight, 0);
318
+ const rate = entry.minimumPerTurn + (entry.weight > 0 && drawWeight > 0 ? (clock.randomPerTurn * entry.weight) / drawWeight : 0);
319
+ // Capturing turns until the k-th card is complete (pieces carried over); null when it never comes.
320
+ const turnsFor = (k) => {
321
+ const need = k * entry.pieces - entry.initialPieces;
322
+ return need <= 0 ? 0 : rate > 0 ? Math.ceil(need / rate - 1e-9) : null;
323
+ };
324
+ const firstTurns = turnsFor(1);
325
+ if (firstTurns === null)
311
326
  return undefined;
312
327
  const raw = settings.raw.ReinforcementCard;
313
328
  const fixed = typeof raw === 'object' && raw !== null ? Number(raw.FixedArmies) : NaN;
@@ -315,7 +330,7 @@ export function opponentReinforcement(settings, hand) {
315
330
  const armies = Number.isFinite(fixed) && fixed > 0 ? Math.floor(fixed) : inHand;
316
331
  if (armies === undefined || armies <= 0)
317
332
  return undefined;
318
- const after = entry.cardsAfter.fastest;
319
- const turnsPerCard = after && after.length >= 2 ? Math.max(1, after[1] - after[0]) : null;
320
- return { firstTurn: first, armies, turnsPerCard };
333
+ const second = turnsFor(2);
334
+ // Pieces arrive at the end of a turn, so the first card is playable the turn after its last piece.
335
+ return { firstTurn: firstTurns + 1, armies, turnsPerCard: second === null ? null : Math.max(1, second - firstTurns) };
321
336
  }
@@ -24,6 +24,18 @@ const CARD_SANCTIONS = 9;
24
24
  export function intelOrders(view) {
25
25
  return [view.spy, view.reconnaissance, view.surveillance].flatMap((a) => (a?.inOrders ? [a.order] : []));
26
26
  }
27
+ /**
28
+ * #435: the advised completing Gift when its play is verified live: the card orders warapp_plan_turn adds,
29
+ * and whether a planned move is one of the transfers the gift drops. Nothing (no cards, no move dropped)
30
+ * while Gift is unverified or none is advised.
31
+ */
32
+ export function giftInOrders(view) {
33
+ const g = view.gift?.inOrders ? view.gift : undefined;
34
+ return {
35
+ cards: g ? g.orders : [],
36
+ drops: (m) => !!g?.drop?.some((d) => d.from === m.from && d.to === m.to),
37
+ };
38
+ }
27
39
  const PLAY_IT = 'Advice only, not in the orders: pass its `order` to warapp_submit_turn to play it (the encoding is read from the client, not yet verified live).';
28
40
  const IN_ORDERS = 'In the orders: its encoding is verified live. Drop it from the orders to keep the card.';
29
41
  /** The Sanctions percentage (`SanctionsCard.Percentage`), when the settings carry one. */
@@ -157,13 +169,17 @@ export function supportAdvice(input) {
157
169
  if (gifts.length) {
158
170
  const g = giftAdvice(cb, input.plan.team?.sharedBonuses ?? [], gifts.length);
159
171
  if (g) {
172
+ // #435: a completing gift goes into the orders once its play is verified live (as #434's spy cards).
173
+ const live = !(input.unverifiedPlays ?? UNVERIFIED_CARD_PLAYS).has('Gift');
160
174
  view.gift = {
161
175
  player: g.player,
162
176
  bonus: g.bonus,
163
177
  territories: g.territories,
178
+ ...(g.drop.length ? { drop: g.drop } : {}),
179
+ ...(live ? { inOrders: true } : {}),
164
180
  orders: g.territories.map((t, i) => ({ kind: 'card', card: gifts[i].id, target: t, player: g.player })),
165
181
  };
166
- warnings.push(`${g.why} ${PLAY_IT}`);
182
+ warnings.push(`${g.why} ${live ? `${IN_ORDERS}${g.drop.length ? ' The transfers it drops are out of the orders.' : ''}` : PLAY_IT}`);
167
183
  }
168
184
  }
169
185
  return { view, warnings };
@@ -3,6 +3,7 @@
3
3
  // opponent could make with its estimated deploy, and the replies that cost something are
4
4
  // reported, worst first (src/analysis/stress.ts, on the turn resolver src/analysis/turn-sim.ts).
5
5
  // Read-only on war.app, and it writes nothing but its verdict to the decision log (#437): not the board cache.
6
+ import { gameBaseIncome } from '../analysis/player.js';
6
7
  import { McpToolError } from '@chrischall/mcp-utils';
7
8
  import { z } from 'zod';
8
9
  import { stressPlan } from '../analysis/stress.js';
@@ -354,7 +355,7 @@ export function registerCheckPlanTool(server, ctx) {
354
355
  ...(teams.size ? { teams } : {}),
355
356
  ...(first_mover !== undefined ? { firstMover: first_mover } : {}),
356
357
  orderPriority,
357
- ...(settings.localDeployments ? { localDeployments: true } : {}),
358
+ ...(settings.localDeployments ? { localDeployments: true, baseIncome: gameBaseIncome(settings) } : {}),
358
359
  ...(settings.localDeployments && (settings.bonusArmyPer ?? 0) > 0 ? { perTerritoryIncome: true } : {}),
359
360
  leader,
360
361
  ...(binding.length ? { truces: binding.map((r) => ({ player: r.player, covered: r.coveredMine })) } : {}),
@@ -4,6 +4,7 @@
4
4
  // larger of its estimate and my income (and enemy_deploy, a what-if floor; an untrusted opponent's at
5
5
  // least at the figure its #275 tripwire gave it, as the stress test sizes it), both move orders, the
6
6
  // free-for-all lead (#180), Order Priority and my Airlifts. No I/O: the callers load the boards.
7
+ import { gameBaseIncome } from '../analysis/player.js';
7
8
  import { commanderSafety } from '../analysis/commander-safety.js';
8
9
  /**
9
10
  * Card plays that turn my territory over, which the commander check does not simulate (an Airlift it
@@ -34,7 +35,7 @@ export function commanderCheckOn(a) {
34
35
  settings: a.settings,
35
36
  ...(so.teams.size ? { teams: so.teams } : {}),
36
37
  orderPriority: a.orderPriority,
37
- ...(a.settings.localDeployments ? { localDeployments: true } : {}),
38
+ ...(a.settings.localDeployments ? { localDeployments: true, baseIncome: gameBaseIncome(a.settings) } : {}),
38
39
  ...(a.settings.localDeployments && (a.settings.bonusArmyPer ?? 0) > 0 ? { perTerritoryIncome: true } : {}),
39
40
  leader: so.leader,
40
41
  killedBy: a.killedBy ?? false,
@@ -315,9 +315,9 @@ export function settingsKey(game) {
315
315
  * seats, pace and boot time; GameFeed's Local Deployment, Commanders, kill rates, luck, fog and cards when it
316
316
  * read the lobby) and the joining policy's checks by code. Name-free. Pure but for the clock.
317
317
  */
318
- export function joinContextLog(listed, feed, screen, now = Date.now()) {
318
+ export function joinContextLog(listed, feed, screen, now = Date.now(), account) {
319
319
  const s = feed?.settings;
320
- const policy = policyChecks(listed, screen);
320
+ const policy = policyChecks(listed, screen, account);
321
321
  const seats = listed.maxPlayers ?? listed.seats;
322
322
  return {
323
323
  at: new Date(now).toISOString(),
@@ -379,6 +379,8 @@ const PICK_WARNING_CODES = [
379
379
  [/^In a 1v1 the best /, 'spread-relaxed'],
380
380
  [/^Only \d+ pickable territor/, 'short-pickable'],
381
381
  [/^The fallback group scores more than the primary/, 'fallback-outscores'],
382
+ // #429: a primary pick replaced by one that pays when a pick above it goes to the opponent.
383
+ [/^Primary pick \d+ is /, 'primary-answered'],
382
384
  [/^Territory limit missing/, 'assumed-territory-limit'],
383
385
  [/^Full distribution \(DistributionMode 0/, 'full-distribution'],
384
386
  [/^Could not tell which seat is yours/, 'team-seat-unknown'],
@@ -17,6 +17,10 @@ import { captureJoin, joinContextLog } from './decision-capture.js';
17
17
  import { mintMeta } from './hints.js';
18
18
  import { requireApprovedAccount, writeAccount } from './live-context.js';
19
19
  import { fetchMyGames } from './my-games.js';
20
+ import { attendedGames } from '../my-games.js';
21
+ import { mapRecordSummary } from '../lessons-store.js';
22
+ import { mapRecordFor } from './past-games.js';
23
+ import { mapOf } from './map.js';
20
24
  import { markLotteries, openGamesPage } from './open-games.js';
21
25
  import { holdsSeat, playerStateName } from '../player-states.js';
22
26
  import { NO_TEAM } from '../teams.js';
@@ -136,11 +140,19 @@ function joinColor(requested, html, bundle, lobby, gameId) {
136
140
  */
137
141
  async function lobbyScreen(ctx, gameId) {
138
142
  try {
139
- const game = await ctx.client.getGame(gameId, { settings: true, map: false });
143
+ // #423: the map too, for the negative-bonus check (the join reads one lobby; the map store keeps it).
144
+ const game = await ctx.client.getGame(gameId, { settings: true, map: true });
140
145
  const { screen, gaps } = feedScreen(game.settings ?? { cards: [], raw: {} });
146
+ let negativeBonus;
147
+ try {
148
+ negativeBonus = mapOf(game).bonuses.some((b) => b.value < 0);
149
+ }
150
+ catch {
151
+ negativeBonus = undefined;
152
+ }
141
153
  return screen
142
- ? { screen, gaps, game }
143
- : { screen: null, gaps, game, note: "GameFeed's settings name no neutral size, so the neutral-cost screen was skipped." };
154
+ ? { screen, gaps, game, ...(negativeBonus !== undefined ? { negativeBonus } : {}) }
155
+ : { screen: null, gaps, game, ...(negativeBonus !== undefined ? { negativeBonus } : {}), note: "GameFeed's settings name no neutral size, so the neutral-cost screen was skipped." };
144
156
  }
145
157
  catch (e) {
146
158
  return {
@@ -184,7 +196,7 @@ export function registerJoinGameTool(server, ctx) {
184
196
  'pass); the preview shows which, plus a screen from the lobby\'s GameFeed settings (does the cheapest ' +
185
197
  'neutral cost at most one turn of base income; Light Fog) and `policy`: whether the lobby keeps the ' +
186
198
  'joining policy (no Commerce, mods or custom scenarios; that cheap neutral; at most four seats; a boot time ' +
187
- 'of at least 12 hours; no lottery — `lottery`, read from the data as warapp_list_open_games does) — advisory, the join is not refused for it. You become a player and are expected ' +
199
+ 'of at least 12 hours; no lottery — `lottery`, read from the data as warapp_list_open_games does) (also no Local Deployment, Commanders, No-Split, army cap, Multi-Attack or non-default kill rates) — a lobby that breaks it is refused unless `override_policy: true` (#423). You become a player and are expected ' +
188
200
  'to take turns — leaving later means declining or being booted.' +
189
201
  `${noBrowserNote(ctx.hosted)} ${CONFIRM_INJECTION_RULE}`,
190
202
  annotations: toolAnnotations({
@@ -205,6 +217,12 @@ export function registerJoinGameTool(server, ctx) {
205
217
  .describe('In a team game: the team to join (a team number with an open seat; the preview lists the teams offered and ' +
206
218
  'the seats on the chosen one). Implies allow_team. Refused outside a team game, with random teams, and for a ' +
207
219
  'team that is full or not in the game.'),
220
+ override_policy: z
221
+ .boolean()
222
+ .optional()
223
+ .describe("Join a game that breaks the owner's joining policy (#423: Commerce, mods, custom scenarios, costly neutrals, " +
224
+ 'more than four seats, a short boot time, lotteries, Local Deployment, Commanders, No-Split, an army cap, ' +
225
+ 'Multi-Attack, non-default kill rates). Default false: such a join is refused, naming each break.'),
208
226
  accept_entry_fee: z
209
227
  .boolean()
210
228
  .optional()
@@ -219,7 +237,7 @@ export function registerJoinGameTool(server, ctx) {
219
237
  'higher ones need an unlock). Default: your preferred colour, else your secondary, else the first ' +
220
238
  'standard colour no player in the game has.'),
221
239
  }),
222
- async plan({ game_id, allow_team, team: askedTeam, accept_entry_fee, color: requested }) {
240
+ async plan({ game_id, allow_team, team: askedTeam, accept_entry_fee, override_policy, color: requested }) {
223
241
  const gameId = parseGameId(game_id);
224
242
  // One fresh read gives the account the gate binds and its in-game id (sliced from the
225
243
  // token TEXT, #130), so the already-joined check is for that same account. A join always
@@ -238,6 +256,20 @@ export function registerJoinGameTool(server, ctx) {
238
256
  // #217: the lobby's screen, then whether it is a lottery (its map read only for that settings shape).
239
257
  const screened = await lobbyScreen(ctx, gameId);
240
258
  const [game] = (await markLotteries(ctx, [listed]));
259
+ // #423: the joining policy is a refusal, not advice: a break needs an explicit override.
260
+ let attended;
261
+ try {
262
+ attended = attendedGames((await fetchMyGames(ctx)).games, myId);
263
+ }
264
+ catch {
265
+ attended = undefined;
266
+ }
267
+ const account = { attendedGames: attended, negativeBonus: screened.negativeBonus };
268
+ const policy = joiningPolicy(game, screened.screen, account);
269
+ const record = await mapRecordFor(ctx.dataDir, undefined, game.mapId);
270
+ if (policy.passes === false && override_policy !== true) {
271
+ refuse(`Game ${gameId} breaks the joining policy, so it was not joined: ${policy.breaks.map(untrustedText).join('; ')}.`, 'Pass override_policy: true to join it anyway, or pick another game from warapp_list_open_games.');
272
+ }
241
273
  return {
242
274
  gate: {
243
275
  action: 'warapp.join_game',
@@ -266,8 +298,12 @@ export function registerJoinGameTool(server, ctx) {
266
298
  // #132: worth joining only when the cheapest neutral costs at most a turn of base income.
267
299
  screen: screened.screen,
268
300
  ...(screened.note ? { screenNote: screened.note } : {}),
269
- // #134: the owner's joining policy — advisory, the join is not refused for it.
270
- policy: joiningPolicy(game, screened.screen),
301
+ // #134/#423: the owner's joining policy; a break was refused above unless `override_policy` was given.
302
+ policy,
303
+ ...(attended !== undefined ? { attendedGames: attended } : {}),
304
+ // #423: my finished games on this map, reported only (the join never reads it).
305
+ ...(record && record !== 'unreadable' ? { mapRecord: (({ games, outcomes }) => ({ games, outcomes }))(mapRecordSummary(record)) } : {}),
306
+ ...(policy.passes === false ? { policyOverridden: true } : {}),
271
307
  color: { index: color, source },
272
308
  // C4: in a team game, the team joined and who already sits on it.
273
309
  ...(game.teamGame ? { team: teamView(game, lobby, team) } : {}),
@@ -283,7 +319,7 @@ export function registerJoinGameTool(server, ctx) {
283
319
  team,
284
320
  color,
285
321
  account: String(token),
286
- join: joinContextLog(game, screened.game, screened.screen),
322
+ join: joinContextLog(game, screened.game, screened.screen, undefined, account),
287
323
  },
288
324
  };
289
325
  },
@@ -4,14 +4,16 @@
4
4
  import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
5
5
  import { z } from 'zod';
6
6
  import { clientPickLimits } from '../analysis/picks.js';
7
- import { isTeamGame } from '../teams.js';
7
+ import { isTeamGame, teammatesOf } from '../teams.js';
8
+ import { teammateOrdersOf } from '../team-orders.js';
8
9
  import { parseGameId } from '../client.js';
9
10
  import { FOG_LEVEL_NAMES, inGameId, OWNER_NEUTRAL, OWNER_PICKABLE, playersByInGameId, } from '../live.js';
10
11
  import { pickingNeutrals, writePickable, writePickList } from '../pick-list.js';
11
12
  import { Method, writeSendTerritoryPicksParams } from '../protocol/methods.js';
12
13
  import { currentTurn, gameIdArg, namer, readAnnotations, respond, shownAccount, turnsCompleted, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, UNTRUSTED_LIST_MAX, untrustedList, untrustedText, viewArg, } from './common.js';
13
14
  import { lookupMeta, mintMeta } from './hints.js';
14
- import { loadLiveTerritories, loadPicks, requireApprovedAccount, writeAccount } from './live-context.js';
15
+ import { loadLiveGame, loadLiveTerritories, loadPicks, requireApprovedAccount, writeAccount } from './live-context.js';
16
+ import { readTeammatePicks } from './team.js';
15
17
  import { mapOf } from './map.js';
16
18
  import { resolvePlayer, resolveTerritory } from './resolve.js';
17
19
  import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
@@ -253,6 +255,12 @@ export function registerLiveTools(server, ctx) {
253
255
  .min(1)
254
256
  .max(MAX_PICK_ARGS)
255
257
  .describe('Your picks in priority order (first = most wanted): territory ids or names. Replaces any picks already submitted.'),
258
+ without_teammate_list: z
259
+ .boolean()
260
+ .optional()
261
+ .describe("Team games only (#435): submit even though a teammate's list could not be read (unknown, not empty). " +
262
+ 'Default false: the submit is refused until it can be read, since a pick you both list goes to one of you. ' +
263
+ 'Set it only when waiting is worse, e.g. the pick deadline is close.'),
256
264
  });
257
265
  defineGatedWrite(server, {
258
266
  title: 'Submit territory picks in a war.app game',
@@ -262,7 +270,8 @@ export function registerLiveTools(server, ctx) {
262
270
  description: 'Submit your territory picks for a war.app (Warzone) game in manual distribution, in priority order — ' +
263
271
  'they replace any picks you submitted before. Every territory must be pickable on the live board; a list ' +
264
272
  "longer than war.app's client allows (players × territories per player) or shorter than the territories " +
265
- 'each player is granted is warned about in the preview. After sending, the picks are read back and ' +
273
+ 'each player is granted is warned about in the preview. In a team game it is refused while a teammate\'s pick ' +
274
+ 'list cannot be read (unknown, not empty) unless `without_teammate_list: true` is passed (#435). After sending, the picks are read back and ' +
266
275
  `reported verified only if they match exactly. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
267
276
  annotations: toolAnnotations({
268
277
  title: 'Submit war.app picks',
@@ -272,7 +281,7 @@ export function registerLiveTools(server, ctx) {
272
281
  openWorld: true,
273
282
  }),
274
283
  inputSchema: submitSchema,
275
- async plan({ game_id, player, territories }) {
284
+ async plan({ game_id, player, territories, without_teammate_list }) {
276
285
  const feed = await ctx.client.getGame(parseGameId(game_id), { settings: true });
277
286
  const map = mapOf(feed);
278
287
  // A write through the bridge always acts as the signed-in account, whatever `player` says
@@ -288,7 +297,7 @@ export function registerLiveTools(server, ctx) {
288
297
  }
289
298
  seen.add(t.id);
290
299
  }
291
- const board = await loadLiveTerritories(ctx, game);
300
+ const { territories: board, info } = await loadLiveGame(ctx, game);
292
301
  const owner = new Map(board.map((t) => [t.territoryId, t]));
293
302
  const unpickable = picks.filter((t) => {
294
303
  const s = owner.get(t.id);
@@ -326,6 +335,25 @@ export function registerLiveTools(server, ctx) {
326
335
  "A shorter list is safe only when no teammate lists any of its picks (warapp_plan_picks shortens it only then).");
327
336
  if (bounds && picks.length < bounds.min)
328
337
  lengthWarnings.push(`war.app expects at least ${bounds.min} picks here (the territories each player is granted); got ${picks.length}, which it may reject.`);
338
+ // #435 (bug): a team game's picks went in while a teammate's list was unread (null), so an
339
+ // overlap could not be seen (45731288: my second pick went to my teammate). Each teammate still
340
+ // playing has its list read as warapp_plan_picks reads it (V5 teammate orders, else V6
341
+ // GetTerritoryPicks); an unread one refuses the submit unless the caller says to go without it.
342
+ // An empty list read is no refusal: the teammate has not picked yet, and picks around mine.
343
+ const unread = [];
344
+ if (isTeamGame(game.players)) {
345
+ const entries = teammateOrdersOf(info, game.players);
346
+ for (const mate of teammatesOf(game.players, me).filter((p) => (p.state ?? 'Playing') === 'Playing'))
347
+ if ((await readTeammatePicks(ctx, game.id, mate, entries?.find((e) => e.playerId === mate.id))) === null)
348
+ unread.push(mate.id);
349
+ }
350
+ if (unread.length && without_teammate_list !== true)
351
+ throw new McpToolError(`Your teammate's list (player ${unread.join(', ')}) could not be read, so an overlap with yours cannot be seen: a pick you both list goes to one of you.`, {
352
+ hint: "Nothing was sent. Wait until it can be read (warapp_get_team, warapp_plan_picks show it), agree a list in team chat, " +
353
+ 'or pass without_teammate_list: true to submit anyway when the pick deadline is close.',
354
+ });
355
+ if (unread.length)
356
+ lengthWarnings.push(`Your teammate's list (player ${unread.join(', ')}) was not read: submitted without it (without_teammate_list), so an overlap cannot be seen.`);
329
357
  const playerId = inGameId(me);
330
358
  const territoryIds = picks.map((t) => t.id);
331
359
  const named = picks.map((t) => ({ id: t.id, name: t.name }));
@@ -93,8 +93,8 @@ export function registerOpenGamesTool(server, ctx) {
93
93
  });
94
94
  // #134: advisory — the neutral-cost part needs each lobby's GameFeed settings, so only the join preview has it.
95
95
  const games = (await markLotteries(ctx, filtered)).map((g) => {
96
- const { breaks } = joiningPolicy(g, null);
97
- return breaks.length ? { ...g, policyBreaks: breaks } : g;
96
+ const { breaks, warnings } = joiningPolicy(g, null);
97
+ return { ...g, ...(breaks.length ? { policyBreaks: breaks } : {}), ...(warnings ? { policyWarnings: warnings } : {}) };
98
98
  });
99
99
  return respond(undefined, ['compact'], () => ({
100
100
  games,