@chrischall/warapp-mcp 0.20.0 → 0.21.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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "MCP server for war.app (Warzone) — your games, players, settings, map bonuses and chokepoints, board analysis and route planning through war.app's per-player GameFeed API, plus the live board, territory picks, cards, turn planning and submission, turn notifications and game chat through your signed-in war.app tab (joining, leaving or surrendering a game, closing out a finished game, accepting another player's surrender, Begin on a speed first turn, picks, turn orders, withdrawing them, chat sends, marking notifications and chat read, deleting notifications, importing local history and linking a session are confirm-gated).",
10
- "version": "0.20.0"
10
+ "version": "0.21.0"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "war.app (Warzone)",
16
16
  "source": "./",
17
17
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
18
- "version": "0.20.0",
18
+ "version": "0.21.0",
19
19
  "author": {
20
20
  "name": "Chris Hall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "warapp-mcp",
3
3
  "displayName": "war.app (Warzone)",
4
- "version": "0.20.0",
4
+ "version": "0.21.0",
5
5
  "description": "war.app (Warzone) game advisor for Claude — games, maps, bonuses, routes, live board, picks, turns, cards and chat",
6
6
  "author": {
7
7
  "name": "Chris Hall",
package/README.md CHANGED
@@ -153,7 +153,7 @@ Locally `WARAPP_AUTH_TOKEN` is ignored.
153
153
  | `warapp_get_live_board` | The live board through your war.app tab: every territory with its owner (player, `neutral`, or `pickable` during picks), armies and fog, and in a Commanders game whose `commander` stands there. Works in the pick phase and mid-game. `view`: compact / full (every special unit — commanders, bosses — with its owner). Narrow it with `owner` (`me`, `neutral`, `pickable` or a player), `territories`, and `limit`/`offset` paging. Fog levels use war.app's own names: `You` (yours), `Visible`, `OwnerOnly` (owner shown, armies hidden: `armies` is null) and `Fogged` (owner and armies hidden). |
154
154
  | `warapp_get_my_picks` | Your submitted territory picks in priority order, and how many the game allows. |
155
155
  | `warapp_get_my_orders` | Your orders for the current turn read back from war.app (what the web client shows in "Modify orders"), read-only: `committed`, `orders` in exactly the shape `warapp_submit_turn` takes (card GUIDs and targets, players by GameFeed id, move options, Order Delay `before`) and `shown` (one line per order, with names). Resubmit them after `warapp_uncommit_turn` to change a committed turn without losing hand-made orders. `null` is unknown, never "none"; `unread` lists orders it could not read back. Committed orders verified live 2026-11-22; entered-but-uncommitted ones unverified. |
156
- | `warapp_plan_turn` | A plan for your turn from the live board (defaults to the signed-in account): income, your cards and whether you must play one, deploys and moves by name and id, expected captures, bonuses and next income, the `frontier` budget (borders left, those facing an enemy, what they need to hold next turn, next income), warnings and reasoning, and an `orders` array (card plays included); `chat.unread` counts the chat messages not yet marked seen (counts only, from GameFeed, so every count is under `unknown`; its `note` says so); `surrenderPending` lists other players' surrenders still pending (from the game details, unverified live; `null` when unreadable), and when one waits on your acceptance the first warning says so. `goal`: balanced (default: best income per army across holds, bonuses and breaking enemy bonuses, with at least 30% on expansion) / expand / complete-bonus / defend / siege (one opponent, `siege_target` by GameFeed id, default the strongest one bordering you: its bonus breaks are funded cheapest per income lost first, its other territories are left alone and the spare deploys build one strike stack facing it until the assault trigger fires — its income at 0.6× its baseline — the most the tracker saw it deploy over its window, or its income when the siege began — yours at 1.8× its, or a stack of yours able to take a member of its held bonus against its whole deploy — then the stack strikes; `siege` reports `target`, `opponentIncome`, `baseline`, `ratio`, `fallenTo`, `breaks`, `brokenThisTurn`, `ready`, `trigger` and `memory` — the siege's first turn, its turns, the target's income trend and the bonuses broken and broken again, kept per game while the siege runs, a gap of more than 3 turns starting a new one) — omit it and the game profile (`profile`: the One Army Must Stand Guard case and what it means for interior defence, format, phase, standing) picks it (never the siege, which plays only when you pass `goal: 'siege'`, #603): defend when behind on income outside a 1v1, else balanced tuned to the format (1v1 in contact: holds and breaks before expansion that completes nothing; behind on income in a 1v1: strike — break their bonuses, inferred ones too, sized to land; behind on armies: no trade below even; in a 1v1, spare deploys build one strike stack facing the opponent; FFA: no second front; ahead in a 1v1: more fog pressure); an explicit goal overrides it; `focus` bonuses; `reserve`; `enemy_deploy` (armies an enemy is assumed to deploy; default per opponent from its visible bonuses, or what it was observed to deploy when that is larger — its tracked income, carried across turns, once `warapp_track_opponents` has 2+ turns of it; growth beside the fog beyond twice what it was expected to deploy reads as a move out of the fog, not a deploy; in an even-start 1v1 or free-for-all an opponent bordering the fog is assumed to earn at least your income, a player out of a free-for-all having its share of the hidden board split among the rest; while its income was read from under half its frontier, an opponent is sized at the midpoint between its lower bound — its tracked figure, raised to its trend's next step when its tracked income rose two turns running — and its upper bound — that fog prior, else the most it could earn — moving toward what the evidence gives as more of its frontier is read; a rising track read from more of its frontier raises it to that lower bound); the `outlook` adds `leaning: behind` when it read even for 3 turns while a bonus of yours fell on each; `known_income` (per-player incomes you know, by GameFeed id — what a player said in chat, say: each replaces that opponent's estimate, a Reinforcement card the clock adds kept on top, said in its warning; `enemy_deploy` wins over it; the commander block keeps the submit's sizing); `min_win_chance` (0.5–1; default 1 = certain captures with no luck, 0.95 with luck on; below 1, each capture is sized for that exact win chance, and the captures a bonus still needs reach it together); `first_mover` (`me` or `opponent`, when you know who moves first this turn — Cycle move orders swap the first mover every turn; when you move first, Order Priority is not advised; the same argument as `warapp_check_plan`'s). Every attack carries `winChance` (its exact probability of capturing at the game's kill rates, luck and rounding); idle armies top an attack up to its next efficient size when the extra kill can matter. Reports the borders it gives up (`conceded`: not worth or not affordable to hold, never deployed to unless every territory you hold is conceded; it may still attack out with the armies already on it; an idle interior stack beside one that would make it hold transfers in, and it is then held), `cardAdvice` (`order-priority` when you hold one and it protects your first order: a commander strike while your commander is threatened, or a move out of a conceded border carrying enough armies to be worth a card — any size when the card must go anyway; never when `first_mover` is `me`; otherwise `order-delay` when you hold Order Delay and the schedule puts an attack last — the orders then carry the card with `before`, placed above the first non-urgent order, see `cards.advice.orderDelay`; an Order Delay that must leave the hand is played there rather than discarded), `cards.advice` for the cards `warapp_submit_turn` plays but the plan never does — `diplomacy` (the opponent tying down most of your border armies, only with two or more in contact, never a truce partner the truce already covers unless the card adds protection), `sanctions` (the leader, passing over a truce partner or a player a Diplomacy card keeps at peace with you, with the reason; yourself when the game's Sanctions percentage is negative — the card then raises the target's income — with `income`: your next income before and after the boost, by the client's rule (not under Local Deployment); never a negative card on an opponent nor a positive one on you), `airlift` (a border of yours or a teammate's that falls without it), `gift` (the members that complete a teammate's bonus), `spy` / `reconnaissance` / `surveillance` (only where the fog hides what the plan needs: an opponent out of view, a hidden territory on your border, a fogged member of a bonus you are completing; never with fog off) — each with an `order` to pass as is, never added to the orders save a completing `gift` (its play verified live 2026-11-23, #435: its card plays go into `orders` and the transfers out of or into the gifted members are dropped; never a territory with a special unit such as your commander, never one an attack leaves from) and a Reconnaissance (in a team game only cards read under you are played, discarded or advised; unverified live) and `trendSource` (where last turn's board came from — `history`, `cache` or null — for growing enemy stacks). Obeys the game's kill rates, Local Deployment and No-Split (`view: "full"` echoes the settings it assumed: `idleTransfers`, the planner's own switch for moving idle armies, beside the game's own `allowTransferOnly` and `allowAttackOnly`, `null` when GameFeed does not state them). Read-only; refuses outside a turn phase. In a Commanders game a commander counts as 7 armies, your commander's territory is never conceded (it gets the deploys it needs to hold against the worst case — the opponent's whole deploy, at least your own income, plus every enemy stack within two moves — or every army when that is not enough), and an adjacent enemy commander is attacked first, sized for its owner's full deploy. Within three moves of an enemy or the fog, with a safer territory of yours reachable, your commander walks one step a turn toward safety: a move in `orders` with `commander: true` (encoding not yet verified live), said in the first warning; the territory it leaves is held only for its own worth, plus what survives the attacks that may land before the walk (every enemy stack beside it, even when you move first: `warapp_submit_turn` checks both move orders; when that does not fit, each player's strongest attack, with the walk as your first order), no other order leaves it before the walk but a strike that ends a player, and Order Priority is advised for the walk only when even that falls short or the fog borders it; under No-Split a commander kill the walk displaces is named in a warning. Every turn of such a game `commander` reports your commander (#274): its territory, the armies there after the plan, `movesToEnemy` (to the nearest enemy or fog), `killedBy` (the smallest deploy, made by each opponent at once, at which a reply kills it: `player`, and `partner` when it is two opponents striking together; null when none reaches it this turn), and `safe` / `needs` at the larger of the estimate and your income; when it is not safe the first warning says so and whether `warapp_submit_turn` would refuse those orders (it does not without Commanders in the settings, nor when only an `enemy_deploy` what-if makes the commander unsafe). When the server kept your pick list, `award` says what the award of picks showed: the territories of your list that are another player's start for certain (in a two-player game planned as the opponent's while still fogged), whether you were awarded first or second and who moves first this turn under a `Cycle` move order, and with commanders the opponent's first award when the award pins it. `relations` reports each truce recorded with `warapp_record_agreement` as the plan treated it (honoured in a free-for-all; in a team or two-player game only its covered territories stay off-limits): while active or in notice no covered territory of the partner is attacked, a covered border facing only the partner is held against its stacks without a deploy (never your commander's, a border worth more than a quarter of your income, or any while trust is `watch`), and a border cap is kept: no move of yours fills that border past it, and the excess moves one step back (a warning when your own deploy for a hold is what exceeds it — deploy less, or give notice and ask before exceeding it — or when the cap leaves a border that also faces another opponent, or your commander's, short of its hold); `advice` says `give-notice` when the endgame or the partner outgrowing you made the trust `watch`; a truce the board shows broken is planned as an ordinary opponent, with the evidence (record it as `broken-by-them` before submitting: `warapp_submit_turn` reads only the ledger); each honoured truce reports `lossIfBroken` (what you would lose this turn if the partner landed its whole deploy beside your costliest covered territory, from any territory of its there, and attacked, carried out against the plan's orders: territories, armies, bonuses and income; logged per turn in the ledger beside the armies it freed); `tacit` lists quiet borders with no agreement (a report, never a truce). A Diplomacy card in effect between you and a player, read from the live board, is honoured in any format (that player is no threat and no target this turn), and Sanctions on you cut the plan's income (Sanctions on an opponent cut its estimate when that is read off the board, `sanctionsOnOthers`), when the decoder is sure of them (the card in play, its expiry within the game's duration); `cardsInEffect` lists them, marked `verified: false` (the active-card decoder is not yet checked live). Otherwise a warning says what was read and why it was not relied on. In a team game a bonus with a teammate's territory in it is never planned toward (a bonus pays one holder), and `team.sharedBonuses` lists each bonus you and a teammate both hold members of and who is `nearer` to holding it (advisory; team vision unverified). With your teammate's entered orders on the live board (unverified live): of two otherwise equal captures the one on the opponent they attack goes first (a "Team focus" rationale line); `team.support` lists a teammate's border that falls given their orders where your idle armies beside it would make it hold (each idle army offered to one border only, the border needing fewest first: the most borders held, not the most worth); `team.jointCaptures` a target neither of you takes alone but both together, resolved on the turn simulator in both orders (under a cyclic move order, `mustGoFirst`); and `cards.team` says who plays each card of the team hand — a card your teammate has entered is left to them and kept out of your plays. Support and joint captures are advice only (a move onto a teammate's territory is unverified live): never in `orders`. When one opponent touches two or more of your borders and no fixed split of the deploys there holds them all, `guess` offers a randomized split weighted by what each border is worth (each border's chance of being held, the best fixed split's worst case, the mix's expected loss, one draw seeded by the game, the turn and a local secret, so re-planning gives the same draw and the public code cannot reproduce it) and `guessOrders`, the plan's `orders` with that draw in place of its deploys on those borders — optional, a model of one opponent with one deploy, never taking armies off the territory your commander stands on or walks to, and dropped when its draw would be refused by the submit's commander check; the plan's `orders` are unchanged (`view: "full"` says why there is none). Holding an Airlift card, `airliftPlan` is an alternative beside the plan, its `orders` unchanged: the same planner on the board after the Airlifts (an interior stack flown onto a border the plan concedes, or a conceded border's armies flown to the border most pressed), the best compared by the plan's own measure — next income if its conceded borders fall, then next income, fewer concessions, more captures — with `airlifts`, `orders` (Airlift plays included), `expected`, `delta` (income, captures, borders saved, bonuses kept or completed), `cardsSpent` and `cardsLeft`; `keep_cards` holds cards in reserve; `null` with `airliftPlanNote` when none beats the plan. Airlifted armies cannot attack that turn, so a capture is staged for next turn instead (`staging`: an interior stack flown beside a target the plan does not take whose capture completes a bonus of yours or breaks an opponent's, with `nextTurnAttack` and the bonus value), scored on a two-turn objective — this turn's measure plus 0.8 × that bonus (`delta.twoTurn`) — and only when the staged stack holds against the plan's threat at that border; a plan the submit's commander check would refuse is not offered. Holding a Bomb card, `bombPlan` is the same kind of alternative: the planner on the board the Bomb leaves (its target keeps half its armies, rounded down, as the client bundle's Bomb result does) — an opponent's territory beside yours, a held bonus's member first, then the largest stacks, never a player at peace with you — with `bomb`, `orders` (the Bomb play included), `expected` and `delta`; `null` with `bombPlanNote` when none beats the plan. Holding an Emergency Blockade, `blockadePlan` walls off a border the plan concedes (neutral at its armies × the game's multiplier, before every move), worth the bonus its fall would hand an opponent when the wall holds this turn; holding a Blockade, the plain orders plus a Blockade on a territory of yours the stress-tested line keeps through the attacks (it walls it after them), worth the same denial less any bonus of yours it gives up — the better of the two is offered (owner-approved 2026-11-24). `reads` (opponent profiles, reported only — the plan never uses them): each opponent in contact with a habit at confidence 0.5 or a label, its `labels`, those habits with `n` and `basis`, and `gamesMet` (full adds the counter-play lines); absent with `WARAPP_PLAYER_PROFILE=off` or while a game's teams cannot be read. `headroom` (#275), weakest first: each border of yours with the smallest single deploy by a neighbouring opponent that takes it after the plan's orders, whether that is below your income, and what falls with it (bonuses, the territories behind it and their bonus income, and `breach`: the hollow territories within two moves behind it that only it shields, with their bonus income). The whole turn is carried out for it, so it may differ from the leftover spread's "~D" line (#268, reckoned on the deploys before any move); a player out of the game whose seat no AI plays gets no row. With the guard off the plan counts half of a border's breach income in its value. When one observation broke an opponent's estimate by 1.5× or more (a stack out of the fog, a capture, or an attack of yours it held), the first warning says so for 3 turns and the borders of your held bonuses facing it are sized for the larger of what it implied and your income (no `guess` is drawn against it then). Nothing is read once an opponent may hold an Airlift card or while the game's teams cannot be read (each `headroom` row then says `mayBeTeammate`); under Multi-Attack only a stack out of the fog is read. After turns 4 and 8 on a map you have finished games on, `pace` puts your income beside the median winner's there (reported only). `chat.messages` lists the newest unread messages other players sent (text delimited) with their `intent` and `advice` (compact: the stance and one reason; `messagesOmitted` counts the rest), from the plan's own standing: reported only, the orders never read chat. `chat.chatBlocks` lists the unread messages that would block the submit under `WARAPP_CHAT_BLOCKS_TURN` (report only). Once the outlook's surrender line (advice only) is crossed in a free-for-all with three or more still playing, `coalition` says whether a coalition against the leader is viable: the trailing players together out-earning it on the calibrated estimates, now or once a bonus of its that one of you borders breaks. While viable, for 2 turns from the crossing and as long as the leader's lead over you is not growing, "Try a coalition first" replaces the surrender warning; `coalition.partners` ranks every player who borders the leader, is not at war with you and has not broken a truce with you on the cross-game record (`leftOut` says why the others are not), and `coalition.drafts` holds a `propose` message for the top two naming the leader's bonus you could break together. Nothing is sent: send a draft yourself with `warapp_send_chat`, or with `WARAPP_CHAT_AUTOMATION=on` a draft carries `send`, still confirm-gated. |
156
+ | `warapp_plan_turn` | A plan for your turn from the live board (defaults to the signed-in account): income, your cards and whether you must play one, deploys and moves by name and id, expected captures, bonuses and next income, the `frontier` budget (borders left, those facing an enemy, what they need to hold next turn, next income), warnings and reasoning, and an `orders` array (card plays included); `chat.unread` counts the chat messages not yet marked seen (counts only, from GameFeed, so every count is under `unknown`; its `note` says so); `surrenderPending` lists other players' surrenders still pending (from the game details, unverified live; `null` when unreadable), and when one waits on your acceptance the first warning says so. `goal`: balanced (default: best income per army across holds, bonuses and breaking enemy bonuses, with at least 30% on expansion) / expand / complete-bonus / defend / siege (one opponent, `siege_target` by GameFeed id, default the strongest one bordering you: its bonus breaks are funded cheapest per income lost first, its other territories are left alone and the spare deploys build one strike stack facing it until the assault trigger fires — its income at 0.6× its baseline — the most the tracker saw it deploy over its window, or its income when the siege began — yours at 1.8× its, or a stack of yours able to take a member of its held bonus against its whole deploy — then the stack strikes; `siege` reports `target`, `opponentIncome`, `baseline`, `ratio`, `fallenTo`, `breaks`, `brokenThisTurn`, `ready`, `trigger` and `memory` — the siege's first turn, its turns, the target's income trend and the bonuses broken and broken again, kept per game while the siege runs, a gap of more than 3 turns starting a new one) — omit it and the game profile (`profile`: the One Army Must Stand Guard case and what it means for interior defence, format, phase, standing) picks it (never the siege, which plays only when you pass `goal: 'siege'`, #603): defend when behind on income outside a 1v1, else balanced tuned to the format (1v1 in contact: holds and breaks before expansion that completes nothing; behind on income in a 1v1: strike — break their bonuses, inferred ones too, sized to land; behind on armies: no trade below even; in a 1v1, spare deploys build one strike stack facing the opponent; FFA: no second front; ahead in a 1v1: more fog pressure); an explicit goal overrides it; `focus` bonuses; `reserve`; `enemy_deploy` (armies an enemy is assumed to deploy; default per opponent from its visible bonuses, or what it was observed to deploy when that is larger — its tracked income, carried across turns, once `warapp_track_opponents` has 2+ turns of it; growth beside the fog beyond twice what it was expected to deploy reads as a move out of the fog, not a deploy; in an even-start 1v1 or free-for-all an opponent bordering the fog is assumed to earn at least your income, a player out of a free-for-all having its share of the hidden board split among the rest; while its income was read from under half its frontier, an opponent is sized at the midpoint between its lower bound — its tracked figure, raised to its trend's next step when its tracked income rose two turns running — and its upper bound — that fog prior, else the most it could earn — moving toward what the evidence gives as more of its frontier is read; a rising track read from more of its frontier raises it to that lower bound); the `outlook` adds `leaning: behind` when it read even for 3 turns while a bonus of yours fell on each; `known_income` (per-player incomes you know, by GameFeed id — what a player said in chat, say: each replaces that opponent's estimate, a Reinforcement card the clock adds kept on top, said in its warning; `enemy_deploy` wins over it; the commander block keeps the submit's sizing); `min_win_chance` (0.5–1; default 1 = certain captures with no luck, 0.95 with luck on; below 1, each capture is sized for that exact win chance, and the captures a bonus still needs reach it together); `first_mover` (`me` or `opponent`, when you know who moves first this turn — Cycle move orders swap the first mover every turn; when you move first, Order Priority is not advised; the same argument as `warapp_check_plan`'s). Every attack carries `winChance` (its exact probability of capturing at the game's kill rates, luck and rounding); idle armies top an attack up to its next efficient size when the extra kill can matter. Reports the borders it gives up (`conceded`: not worth or not affordable to hold, never deployed to unless every territory you hold is conceded; it may still attack out with the armies already on it; an idle interior stack beside one that would make it hold transfers in, and it is then held), `cardAdvice` (`order-priority` when you hold one and it protects your first order: a commander strike while your commander is threatened, or a move out of a conceded border carrying enough armies to be worth a card — any size when the card must go anyway; never when `first_mover` is `me`; otherwise `order-delay` when you hold Order Delay and the schedule puts an attack last — the orders then carry the card with `before`, placed above the first non-urgent order, see `cards.advice.orderDelay`; an Order Delay that must leave the hand is played there rather than discarded), `cards.advice` for the cards `warapp_submit_turn` plays but the plan never does — `diplomacy` (the opponent tying down most of your border armies, only with two or more in contact, never a truce partner the truce already covers unless the card adds protection), `sanctions` (the leader, passing over a truce partner or a player a Diplomacy card keeps at peace with you, with the reason; yourself when the game's Sanctions percentage is negative — the card then raises the target's income — with `income`: your next income before and after the boost, by the client's rule (not under Local Deployment); never a negative card on an opponent nor a positive one on you), `airlift` (a border of yours or a teammate's that falls without it), `gift` (the members that complete a teammate's bonus), `spy` / `reconnaissance` / `surveillance` (only where the fog hides what the plan needs: an opponent out of view, a hidden territory on your border, a fogged member of a bonus you are completing; never with fog off) — each with an `order` to pass as is, never added to the orders save a completing `gift` (its play verified live 2026-11-23, #435: its card plays go into `orders` and the transfers out of or into the gifted members are dropped; never a territory with a special unit such as your commander, never one an attack leaves from) and a Reconnaissance (in a team game only cards read under you are played, discarded or advised; unverified live) and `trendSource` (where last turn's board came from — `history`, `cache` or null — for growing enemy stacks). Obeys the game's kill rates, Local Deployment and No-Split (`view: "full"` echoes the settings it assumed: `idleTransfers`, the planner's own switch for moving idle armies, beside the game's own `allowTransferOnly` and `allowAttackOnly`, `null` when GameFeed does not state them). Read-only; refuses outside a turn phase. In a Commanders game a commander counts as 7 armies, your commander's territory is never conceded (it gets the deploys it needs to hold against the worst case — the opponent's whole deploy, at least your own income, plus every enemy stack within two moves — or every army when that is not enough), and an adjacent enemy commander is attacked first, sized for its owner's full deploy. Within three moves of an enemy or the fog, with a safer territory of yours reachable, your commander walks one step a turn toward safety: a move in `orders` with `commander: true` (encoding not yet verified live), said in the first warning; the territory it leaves is held only for its own worth, plus what survives the attacks that may land before the walk (every enemy stack beside it, even when you move first: `warapp_submit_turn` checks both move orders; when that does not fit, each player's strongest attack, with the walk as your first order), no other order leaves it before the walk but a strike that ends a player, and Order Priority is advised for the walk only when even that falls short or the fog borders it; under No-Split a commander kill the walk displaces is named in a warning. Every turn of such a game `commander` reports your commander (#274): its territory, the armies there after the plan, `movesToEnemy` (to the nearest enemy or fog), `killedBy` (the smallest deploy, made by each opponent at once, at which a reply kills it: `player`, and `partner` when it is two opponents striking together; null when none reaches it this turn), and `safe` / `needs` at the larger of the estimate and your income; when it is not safe the first warning says so and whether `warapp_submit_turn` would refuse those orders (it does not without Commanders in the settings, nor when only an `enemy_deploy` what-if makes the commander unsafe). When the server kept your pick list, `award` says what the award of picks showed: the territories of your list that are another player's start for certain (in a two-player game planned as the opponent's while still fogged), whether you were awarded first or second and who moves first this turn under a `Cycle` move order, and with commanders the opponent's first award when the award pins it. `relations` reports each truce recorded with `warapp_record_agreement` as the plan treated it (honoured in a free-for-all; in a team or two-player game only its covered territories stay off-limits): while active or in notice no covered territory of the partner is attacked, a covered border facing only the partner is held against its stacks without a deploy (never your commander's, a border worth more than a quarter of your income, or any while trust is `watch`), and a border cap is kept: no move of yours fills that border past it, and the excess moves one step back (a warning when your own deploy for a hold is what exceeds it — deploy less, or give notice and ask before exceeding it — or when the cap leaves a border that also faces another opponent, or your commander's, short of its hold); `advice` says `give-notice` when the endgame or the partner outgrowing you made the trust `watch`; a truce the board shows broken is planned as an ordinary opponent, with the evidence (record it as `broken-by-them` before submitting: `warapp_submit_turn` reads only the ledger); each honoured truce reports `lossIfBroken` (what you would lose this turn if the partner landed its whole deploy beside your costliest covered territory, from any territory of its there, and attacked, carried out against the plan's orders: territories, armies, bonuses and income; logged per turn in the ledger beside the armies it freed); `tacit` lists quiet borders with no agreement (a report, never a truce). A Diplomacy card in effect between you and a player, read from the live board, is honoured in any format (that player is no threat and no target this turn), and Sanctions on you cut the plan's income (Sanctions on an opponent cut its estimate when that is read off the board, `sanctionsOnOthers`), when the decoder is sure of them (the card in play, its expiry within the game's duration); `cardsInEffect` lists them, marked `verified: false` (the active-card decoder is not yet checked live). Otherwise a warning says what was read and why it was not relied on. In a team game a bonus with a teammate's territory in it is never planned toward (a bonus pays one holder), and `team.sharedBonuses` lists each bonus you and a teammate both hold members of and who is `nearer` to holding it (advisory; team vision unverified). With your teammate's entered orders on the live board (unverified live): of two otherwise equal captures the one on the opponent they attack goes first (a "Team focus" rationale line); `team.support` lists a teammate's border that falls given their orders where your idle armies beside it would make it hold (each idle army offered to one border only, the border needing fewest first: the most borders held, not the most worth); `team.jointCaptures` a target neither of you takes alone but both together, resolved on the turn simulator in both orders (under a cyclic move order, `mustGoFirst`); and `cards.team` says who plays each card of the team hand — a card your teammate has entered is left to them and kept out of your plays. Support and joint captures are advice only (a move onto a teammate's territory is unverified live): never in `orders`. When one opponent touches two or more of your borders and no fixed split of the deploys there holds them all, `guess` offers a randomized split weighted by what each border is worth (each border's chance of being held, the best fixed split's worst case, the mix's expected loss, one draw seeded by the game, the turn and a local secret, so re-planning gives the same draw and the public code cannot reproduce it) and `guessOrders`, the plan's `orders` with that draw in place of its deploys on those borders — optional, a model of one opponent with one deploy, never taking armies off the territory your commander stands on or walks to, and dropped when its draw would be refused by the submit's commander check; the plan's `orders` are unchanged (`view: "full"` says why there is none). Holding an Airlift card, `airliftPlan` is an alternative beside the plan, its `orders` unchanged: the same planner on the board after the Airlifts (an interior stack flown onto a border the plan concedes, or a conceded border's armies flown to the border most pressed), the best compared by the plan's own measure — next income if its conceded borders fall, then next income, fewer concessions, more captures — with `airlifts`, `orders` (Airlift plays included), `expected`, `delta` (income, captures, borders saved, bonuses kept or completed), `cardsSpent` and `cardsLeft`; `keep_cards` holds cards in reserve; `null` with `airliftPlanNote` when none beats the plan. Airlifted armies cannot attack that turn, so a capture is staged for next turn instead (`staging`: an interior stack flown beside a target the plan does not take whose capture completes a bonus of yours or breaks an opponent's, with `nextTurnAttack` and the bonus value), scored on a two-turn objective — this turn's measure plus 0.8 × that bonus (`delta.twoTurn`) — and only when the staged stack holds against the plan's threat at that border; a plan the submit's commander check would refuse is not offered. Holding a Bomb card, `bombPlan` is the same kind of alternative: the planner on the board the Bomb leaves (its target keeps half its armies, rounded down, as the client bundle's Bomb result does) — an opponent's territory beside yours, a held bonus's member first, then the largest stacks, never a player at peace with you — with `bomb`, `orders` (the Bomb play included), `expected` and `delta`; `null` with `bombPlanNote` when none beats the plan. Holding an Emergency Blockade, `blockadePlan` walls off a border the plan concedes (neutral at its armies × the game's multiplier, before every move), worth the bonus its fall would hand an opponent when the wall holds this turn; holding a Blockade, the plain orders plus a Blockade on a territory of yours the stress-tested line keeps through the attacks (it walls it after them), worth the same denial less any bonus of yours it gives up — the better of the two is offered (owner-approved 2026-11-24). `reads` (opponent profiles, reported only — the plan never uses them): each opponent in contact with a habit at confidence 0.5 or a label, its `labels`, those habits with `n` and `basis`, and `gamesMet` (full adds the counter-play lines); absent with `WARAPP_PLAYER_PROFILE=off` or while a game's teams cannot be read. `headroom` (#275), weakest first: each border of yours with the smallest single deploy by a neighbouring opponent that takes it after the plan's orders, whether that is below your income, and what falls with it (bonuses, the territories behind it and their bonus income, and `breach`: the hollow territories within two moves behind it that only it shields, with their bonus income). The whole turn is carried out for it, so it may differ from the leftover spread's "~D" line (#268, reckoned on the deploys before any move); a player out of the game whose seat no AI plays gets no row. With the guard off the plan counts half of a border's breach income in its value. When one observation broke an opponent's estimate by 1.5× or more (a stack out of the fog, a capture, or an attack of yours it held), the first warning says so for 3 turns and the borders of your held bonuses facing it are sized for the larger of what it implied and your income (no `guess` is drawn against it then). Nothing is read once an opponent may hold an Airlift card or while the game's teams cannot be read (each `headroom` row then says `mayBeTeammate`); under Multi-Attack only a stack out of the fog is read. After turns 4 and 8 on a map you have finished games on, `pace` puts your income beside the median winner's there (reported only). `chat.messages` lists the newest unread messages other players sent (text delimited) with their `intent` and `advice` (compact: the stance and one reason; `messagesOmitted` counts the rest), from the plan's own standing: reported only, the orders never read chat. `chat.chatBlocks` lists the unread messages that would block the submit under `WARAPP_CHAT_BLOCKS_TURN` (report only). Once the outlook's surrender line (advice only) is crossed in a free-for-all with three or more still playing, `coalition` says whether a coalition against the leader is viable: the trailing players together out-earning it on the calibrated estimates, now or once a bonus of its that one of you borders breaks. While viable, for 2 turns from the crossing and as long as the leader's lead over you is not growing, "Try a coalition first" replaces the surrender warning; `coalition.partners` ranks every player who borders the leader, is not at war with you and has not broken a truce with you on the cross-game record (`leftOut` says why the others are not), and `coalition.drafts` holds a `propose` message for the top two naming the leader's bonus you could break together. Nothing is sent: send a draft yourself with `warapp_send_chat`, or with `WARAPP_CHAT_AUTOMATION=on` a draft carries `send`, still confirm-gated. `strategy: true` (#606) adds a menu for choosing a turn yourself: ranked capture and hold options with their costs and the default plan beside the planner under other goals, each stress-tested. `facts` adds the raw state behind them, only the parts you name: `me`, `territories`, `bonuses`, `opponents` (each income estimate and how it was read), `changes` since last turn and `past` turns. Every plan's `more` line says both can be asked for; the plan itself is unchanged. |
157
157
  | `warapp_check_plan` | A stress test of a list of orders before you submit it (`warapp_plan_turn`'s `orders`, or your own edit): the orders are carried out on the live board by the game's turn rules (deploys, then attacks and transfers in the zigzag move order, each an attack or a transfer by who holds its target when it runs) against the replies each opponent could make with one deploy — all of it on one stack and an attack on a territory you hold or are about to take, all of it on a territory you attack, or every stack attacking at once — with you moving first and with the opponent moving first unless `first_mover` says which. Returns `safe` (`null` when no reply could be tried), a one-line `summary`, the `worst` reply and the `otherReplies` that cost something (territories lost, captures that fail or are taken straight back, bonuses and income, your commander), everything `atRisk` to some single reply, `commander` (with your commander on the board: its territory, the armies there and `needs`, the armies that survive every reply tried — by `warapp_submit_turn`'s own check, each reply at the larger of the estimate and your income, `enemy_deploy` only raising it, both move orders, your Airlifts counted; when a reply kills it the `summary` starts with it), what the orders do unanswered, `blindBorders` (your territories next to the fog, where nothing could be tested) and `exposedNextTurn` (territories no stack touches today that one could take next turn by first taking the territory in between, each with the armies it would need to hold). Exact with no luck and straight rounding; otherwise `exact` is false. `known_income` (as `warapp_plan_turn`'s) tries a per-player income you know in place of that opponent's estimate (`enemyDeploy` source `known_income`; `enemy_deploy` wins over it; `commander` keeps the submit's sizing). Not tried: hidden stacks, a deploy above the estimate (`enemy_deploy` tests one), split deploys, opponents acting together, under Multi-Attack any chain but the one most damaging per stack, cards other than your own Order Priority, Airlifts, Bombs and Blockades: a Bomb is carried out after every deploy, its target keeping half its armies, rounded down; an Emergency Blockade (before the moves) and a Blockade (after them) turn their territory neutral at its armies × the game's multiplier, and the walled border is never counted lost (a wall with no multiplier in the settings is warned of as not simulated). An Airlift in the orders is carried out at its phase — after every deploy, before every move: its source loses the armies, its destination gains them, and they cannot move again that turn — so every reply is tried on the board it leaves. `award` (when the server kept your pick list) is the same reading `warapp_plan_turn` gives; its `firstMover` can be passed as `first_mover`. In a free-for-all with a recorded truce in force its partner is still tried (`safe` is safe against a break), a reply that attacks a territory the truce covers is marked `breaksTruce`, and `safeIfTruceHolds` is the verdict over the rest (`null` when every reply is a break); a Diplomacy card in effect that the decoder is sure of counts as such a truce in any format (`enforced`, `verified: false`). In a team game it warns, as `warapp_submit_turn` does, of a card play or discard your teammate has already entered. `headroom` (as `warapp_plan_turn`'s) gives each border the smallest single deploy that takes it after these orders; an opponent whose estimate an observation broke is tried at the larger of what it implied and your income (`enemyDeploy` source `untrusted`, said in the first warning). `belowPlan` (#275) compares the orders with the default plan made now on the same board, as `warapp_plan_turn` makes it with no options (or with its border guess when the deploys are the guess's: `belowPlanAgainst`): each border they leave below what that plan leaves standing there, with `planLeaves`, `left` and `short`, the largest shortfall first. `planLeaves` includes the plan's surplus, so a border named may still hold (see `headroom`). A Sanctions card in the orders is projected onto next turn in `sanctionsPlayed` (`nextIncome`: before, after and the change — yours from this turn's income when the game's percentage is negative and you play it on yourself, an opponent's estimate when positive); a card on the wrong side for its sign is a warning (`warapp_submit_turn` refuses it). Read-only. |
158
158
  | `warapp_turn_history` | A game turn by turn as you saw it, beside what this server planned, sent and expected (read from the game's decision log; ids only): per turn the board in view (summary, or whole with `board: true`), `changedHands` since the turn before, every player's visible `orders` that turn (deploys, moves, card plays, discards — kept from the next turn's live board since #570), the `plan`, the orders `sent` and `differsFromPlan`, the `outcome` next turn, cards, events, and once finished the turn's `truth` and `accuracy`. `from_turn`/`to_turn` (default the newest 5, at most 20 per call, `next` pages on); `view: "full"` adds the plan's rationale and warnings, checks, times and first mover; `read_last_turn: true` reads the live board once to keep the turn just resolved. Read-only; attack results are not decoded. |
159
159
  | `warapp_track_opponents` | Each opponent over your own board history (the boards `warapp_plan_turn` and this tool read, the last 10 turns, or the game history when war.app sends it), by name: its observed deploy each turn (territories visible both turns only — a stack that came out of the fog is not income), an income estimate (each observed deploy is a lower bound under fog, so the largest of its last three observed turns, or its visible army growth plus losses per turn (stacks out of the fog left out) when that is more; capped at what it could earn, at least its base plus the bonuses it visibly holds; `method` and `observedRange` say which term set it and how spread the observations were), `unexplainedArmies` (income earned since first seen minus its visible army change, its visible losses and its likely combat deaths: armies in the fog, spent there, or a misread) and `inferredBonuses` (the combinations of bonuses it could hold that best explain the gap, only those within 4 hops of its territories that it could have paid for, nearest first — candidates, never one asserted; none listed when more than 8 fit), with confidence notes. Every opponent still playing is listed, even with no territory in view (`visible` territories in view, `turnsUnseen` — a floor, `turnsUnseenAtLeast`, when your boards do not reach back to when it was last seen); one with nothing in view gets `earnedAtLeast` — its starting armies plus the base income for every turn so far, a lower bound on armies received (not held: its expansion cost some) — and a warning, also in `warapp_plan_turn`, when that beats your largest stack or your total visible armies. Once an opponent has 2+ observed turns, `warapp_plan_turn` uses this income in place of the single-turn observed figure. `view`: compact / full. Read-only on war.app (it caches the board it read); refuses outside a turn phase. `full` adds `pastGames`: the lessons of your finished games — how they were lost, when your income went flat, and this tracker's estimate ÷ the true income by format and coverage band (reported only). |
@@ -0,0 +1,157 @@
1
+ import { bonusTerritories } from './bonuses.js';
2
+ import { armiesToTake } from './combat.js';
3
+ import { neighborsOf } from './graph.js';
4
+ import { planTurn } from './planner.js';
5
+ /** Said with every `strategy` view: what the options are, and what they are not. */
6
+ export const STRATEGY_NOTE = 'Mechanics, not advice: capture costs at the game\'s kill rates with no luck beyond them, deploy estimates as warapp_plan_turn ' +
7
+ 'reads them, and each alternative stress-tested against single-deploy replies only (as warapp_check_plan). The default ' +
8
+ 'plan is the planner\'s pick; choosing another or your own is yours to judge — check it with warapp_check_plan.';
9
+ /** The most options of each kind listed. */
10
+ export const MAX_OPTIONS = 15;
11
+ const ownerOf = (t) => t?.owner.kind === 'neutral' ? 'neutral' : t?.owner.kind === 'player' ? t.owner.playerId : null;
12
+ /** The capture and hold options on this board, ranked. */
13
+ export function turnOptions(input, limit = MAX_OPTIONS) {
14
+ const { graph: g, board, me } = input;
15
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
16
+ const guard = input.guard === false ? 0 : 1;
17
+ const mine = new Set(board.territories.filter((t) => ownerOf(t) === me).map((t) => t.territoryId));
18
+ const foe = (o) => typeof o === 'number' && o !== me && !input.friends?.has(o);
19
+ const armies = (t) => state.get(t)?.armies ?? 0;
20
+ const take = (defenders) => armiesToTake(defenders, input.rates);
21
+ const bonusesOf = new Map();
22
+ for (const b of g.map.bonuses)
23
+ for (const t of bonusTerritories(g, b.id))
24
+ bonusesOf.set(t, [...(bonusesOf.get(t) ?? []), b.id]);
25
+ const missing = (bonusId, held) => bonusTerritories(g, bonusId).filter((t) => !held.has(t)).length;
26
+ const captures = [];
27
+ const seen = new Set();
28
+ for (const m of [...mine].sort((a, b) => a - b))
29
+ for (const t of neighborsOf(g, m)) {
30
+ if (mine.has(t) || seen.has(t))
31
+ continue;
32
+ seen.add(t);
33
+ const st = state.get(t);
34
+ const owner = ownerOf(st);
35
+ if (owner === null || st.armies === null)
36
+ continue;
37
+ if (typeof owner === 'number' && input.friends?.has(owner))
38
+ continue;
39
+ const defenders = st.armies;
40
+ const after = new Set([...mine, t]);
41
+ const completes = [];
42
+ const advances = [];
43
+ for (const id of bonusesOf.get(t) ?? []) {
44
+ const b = g.bonusById.get(id);
45
+ if (b.value <= 0)
46
+ continue;
47
+ const left = missing(id, after);
48
+ if (left === 0)
49
+ completes.push({ bonusId: id, value: b.value });
50
+ else
51
+ advances.push({ bonusId: id, value: b.value, missingAfter: left });
52
+ }
53
+ const opens = neighborsOf(g, t).filter((n) => !mine.has(n) && foe(ownerOf(state.get(n))) && !neighborsOf(g, n).some((x) => mine.has(x))).length;
54
+ captures.push({
55
+ target: t,
56
+ owner,
57
+ defenders,
58
+ needs: take(defenders),
59
+ ...(typeof owner === 'number' ? { needsIfReinforced: take(defenders + Math.max(0, input.deployOf(owner))) } : {}),
60
+ from: neighborsOf(g, t)
61
+ .filter((n) => mine.has(n))
62
+ .map((n) => ({ territoryId: n, spare: Math.max(0, armies(n) - guard) }))
63
+ .sort((a, b) => b.spare - a.spare || a.territoryId - b.territoryId),
64
+ completes,
65
+ advances: advances.sort((a, b) => a.missingAfter - b.missingAfter || b.value - a.value || a.bonusId - b.bonusId),
66
+ incomeGain: completes.reduce((n, c) => n + c.value, 0),
67
+ opensBorders: opens,
68
+ });
69
+ }
70
+ const nearest = (c) => (c.advances.length ? c.advances[0].missingAfter : Infinity);
71
+ const cost = (c) => c.needs ?? Infinity;
72
+ captures.sort((a, b) => b.incomeGain / Math.max(1, cost(b)) - a.incomeGain / Math.max(1, cost(a)) ||
73
+ nearest(a) - nearest(b) ||
74
+ cost(a) - cost(b) ||
75
+ a.target - b.target);
76
+ const holds = [];
77
+ for (const t of [...mine].sort((a, b) => a - b)) {
78
+ const byPlayer = new Map();
79
+ for (const n of neighborsOf(g, t)) {
80
+ const o = ownerOf(state.get(n));
81
+ if (!foe(o))
82
+ continue;
83
+ byPlayer.set(o, (byPlayer.get(o) ?? 0) + Math.max(0, armies(n) - guard));
84
+ }
85
+ if (!byPlayer.size)
86
+ continue;
87
+ const have = armies(t);
88
+ const facing = [...byPlayer].sort((a, b) => a[0] - b[0]).map(([player, stacks]) => ({ player, stacks, deploy: Math.max(0, input.deployOf(player)) }));
89
+ /** Armies to add to `have` so `attack` attackers do not take it. */
90
+ const add = (attack) => {
91
+ let n = 0;
92
+ while ((take(have + n) ?? Infinity) <= attack)
93
+ n++;
94
+ return n;
95
+ };
96
+ const stacks = Math.max(...facing.map((f) => f.stacks));
97
+ const deployed = Math.max(...facing.map((f) => f.stacks + f.deploy));
98
+ const protects = (bonusesOf.get(t) ?? [])
99
+ .map((id) => g.bonusById.get(id))
100
+ .filter((b) => b.value > 0 && bonusTerritories(g, b.id).every((x) => mine.has(x)))
101
+ .map((b) => ({ bonusId: b.id, value: b.value }));
102
+ holds.push({ territoryId: t, armies: have, facing, addAgainstStacks: add(stacks), addAgainstDeploy: add(deployed), protects });
103
+ }
104
+ const worth = (h) => h.protects.reduce((n, p) => n + p.value, 0);
105
+ holds.sort((a, b) => worth(b) - worth(a) || b.addAgainstDeploy - a.addAgainstDeploy || a.territoryId - b.territoryId);
106
+ return { captures: captures.slice(0, limit), holds: holds.slice(0, limit) };
107
+ }
108
+ /** The other goals an alternative plan is made under. */
109
+ export const ALTERNATIVE_GOALS = ['expand', 'defend'];
110
+ /**
111
+ * The default plan and the planner under {@link ALTERNATIVE_GOALS} (each a goal the default did not pick), each with
112
+ * its orders, what it expects and (`stress` given) its stress summary. A plan whose orders match one already listed
113
+ * is left out.
114
+ */
115
+ export function alternativePlans(input, base, stress) {
116
+ const view = (name, p) => {
117
+ const s = stress?.(p);
118
+ return {
119
+ name,
120
+ goal: p.goal,
121
+ deploys: p.deploys.map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
122
+ moves: p.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies, kind: m.kind })),
123
+ expected: {
124
+ nextIncome: p.expected.nextIncome,
125
+ captures: p.expected.captures,
126
+ bonusesCompleted: p.expected.bonusesCompleted,
127
+ ...(p.expected.nextIncomeIfConcededFall !== undefined ? { nextIncomeIfConcededFall: p.expected.nextIncomeIfConcededFall } : {}),
128
+ },
129
+ conceded: p.conceded,
130
+ ...(s ? { stress: s } : {}),
131
+ };
132
+ };
133
+ const key = (p) => JSON.stringify([p.deploys.map((d) => [d.territoryId, d.armies]), p.moves.map((m) => [m.from, m.to, m.armies])]);
134
+ const out = [view('default', base)];
135
+ const keys = new Set([key(base)]);
136
+ for (const goal of ALTERNATIVE_GOALS) {
137
+ if (goal === base.goal)
138
+ continue;
139
+ const p = planTurn({ ...input, options: { ...input.options, goal } });
140
+ if (keys.has(key(p)))
141
+ continue;
142
+ keys.add(key(p));
143
+ out.push(view(goal, p));
144
+ }
145
+ return out;
146
+ }
147
+ /** A stress report boiled down to what a choice between plans needs. */
148
+ export function stressSummary(r) {
149
+ return {
150
+ safe: r.considered === 0 ? null : r.harmful === 0,
151
+ harmful: r.harmful,
152
+ considered: r.considered,
153
+ ...(r.worst
154
+ ? { worst: { opponent: r.worst.opponent, lost: r.worst.lost, capturesFailed: r.worst.capturesFailed, incomeLost: r.worst.incomeLost } }
155
+ : {}),
156
+ };
157
+ }
@@ -0,0 +1,243 @@
1
+ import { bonusTerritories } from './bonuses.js';
2
+ import { armiesToTake } from './combat.js';
3
+ import { neighborsOf } from './graph.js';
4
+ /** The most territories listed (a huge map lists the ones nearest my land first). */
5
+ export const MAX_SITUATION_TERRITORIES = 400;
6
+ /** The most bonuses listed. */
7
+ export const MAX_SITUATION_BONUSES = 60;
8
+ /** The most earlier turns summarised (the newest). */
9
+ export const SITUATION_PAST_TURNS = 10;
10
+ const ownerOf = (t, me) => {
11
+ if (!t || t.owner.kind === 'unknown')
12
+ return 'fog';
13
+ if (t.owner.kind !== 'player')
14
+ return 'neutral';
15
+ return t.owner.playerId === me ? 'me' : t.owner.playerId;
16
+ };
17
+ /** The facts on this board (see the file header). */
18
+ export function situation(input) {
19
+ const { graph: g, board, me } = input;
20
+ const guard = input.guard === false ? 0 : 1;
21
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
22
+ const owner = (id) => ownerOf(state.get(id), me);
23
+ const armiesOf = (id) => state.get(id)?.armies ?? null;
24
+ const mine = [...state.keys()].filter((id) => owner(id) === 'me').sort((a, b) => a - b);
25
+ const mineSet = new Set(mine);
26
+ const take = (n) => armiesToTake(n, input.rates);
27
+ // Hops from my land, through any territory.
28
+ const dist = new Map(mine.map((m) => [m, 0]));
29
+ let frontier = mine;
30
+ while (frontier.length) {
31
+ const next = [];
32
+ for (const t of frontier)
33
+ for (const n of neighborsOf(g, t))
34
+ if (!dist.has(n)) {
35
+ dist.set(n, dist.get(t) + 1);
36
+ next.push(n);
37
+ }
38
+ frontier = next;
39
+ }
40
+ const bonusesOf = new Map();
41
+ for (const b of g.map.bonuses)
42
+ for (const t of bonusTerritories(g, b.id))
43
+ bonusesOf.set(t, [...(bonusesOf.get(t) ?? []), b.id]);
44
+ // Every territory in view, plus every hidden one beside my land; nearest first.
45
+ const listed = [...g.territoryById.keys()]
46
+ .filter((id) => owner(id) !== 'fog' || neighborsOf(g, id).some((n) => mineSet.has(n)))
47
+ .sort((a, b) => (dist.get(a) ?? Infinity) - (dist.get(b) ?? Infinity) || a - b);
48
+ const territories = listed.slice(0, MAX_SITUATION_TERRITORIES).map((id) => {
49
+ const t = state.get(id);
50
+ const units = t?.specialUnits?.map((u) => ({ kind: u.kind, owner: u.playerId === me ? 'me' : u.playerId }));
51
+ return {
52
+ id,
53
+ name: g.territoryById.get(id)?.name ?? String(id),
54
+ owner: owner(id),
55
+ armies: armiesOf(id),
56
+ ...(units?.length ? { units } : {}),
57
+ distance: dist.get(id) ?? -1,
58
+ bonuses: bonusesOf.get(id) ?? [],
59
+ neighbors: [...neighborsOf(g, id)],
60
+ };
61
+ });
62
+ // Every positive bonus I touch, that is beside my land, or that another player visibly holds in full.
63
+ const bonuses = [];
64
+ for (const b of g.map.bonuses) {
65
+ if (b.value <= 0)
66
+ continue;
67
+ const members = bonusTerritories(g, b.id);
68
+ let mineN = 0;
69
+ let neutral = 0;
70
+ let fogged = 0;
71
+ const players = new Map();
72
+ for (const t of members) {
73
+ const o = owner(t);
74
+ if (o === 'me')
75
+ mineN++;
76
+ else if (o === 'neutral')
77
+ neutral++;
78
+ else if (o === 'fog')
79
+ fogged++;
80
+ else
81
+ players.set(o, (players.get(o) ?? 0) + 1);
82
+ }
83
+ const heldBy = mineN === members.length ? 'me' : players.size === 1 && [...players.values()][0] === members.length ? [...players.keys()][0] : null;
84
+ const near = members.some((t) => (dist.get(t) ?? Infinity) <= 1);
85
+ if (!near && heldBy === null)
86
+ continue;
87
+ const missing = members.filter((t) => owner(t) !== 'me');
88
+ const hidden = missing.some((t) => armiesOf(t) === null);
89
+ bonuses.push({
90
+ bonusId: b.id,
91
+ name: b.name,
92
+ value: b.value,
93
+ size: members.length,
94
+ mine: mineN,
95
+ neutral,
96
+ fogged,
97
+ players: [...players].sort((x, y) => x[0] - y[0]).map(([player, count]) => ({ player, count })),
98
+ heldBy,
99
+ missing,
100
+ armiesToFinish: hidden ? null : missing.reduce((n, t) => n + (take(armiesOf(t)) ?? Infinity), 0),
101
+ reachable: missing.filter((t) => neighborsOf(g, t).some((n) => mineSet.has(n))),
102
+ });
103
+ }
104
+ // Mine first, then the nearest to done (fewest missing), then the most valuable.
105
+ bonuses.sort((a, b) => Number(b.heldBy === 'me') - Number(a.heldBy === 'me') ||
106
+ a.missing.length - b.missing.length ||
107
+ b.value - a.value ||
108
+ a.bonusId - b.bonusId);
109
+ const opponents = [...input.opponents]
110
+ .filter((o) => o.playerId !== me && !input.friends?.has(o.playerId))
111
+ .sort((a, b) => a.playerId - b.playerId)
112
+ .map((o) => {
113
+ const theirs = [...state.keys()].filter((id) => owner(id) === o.playerId);
114
+ const besideMe = theirs
115
+ .filter((id) => neighborsOf(g, id).some((n) => mineSet.has(n)))
116
+ .map((id) => ({ territoryId: id, armies: armiesOf(id) ?? 0, borders: neighborsOf(g, id).filter((n) => mineSet.has(n)) }));
117
+ return {
118
+ player: o.playerId,
119
+ income: {
120
+ estimate: o.estimate,
121
+ ...(o.source !== undefined ? { source: o.source } : {}),
122
+ ...(o.visibleIncome !== undefined ? { visible: o.visibleIncome } : {}),
123
+ ...(o.tracked !== undefined ? { tracked: o.tracked } : {}),
124
+ ...(o.range !== undefined ? { range: o.range } : {}),
125
+ ...(o.coverage !== undefined ? { coverage: o.coverage } : {}),
126
+ },
127
+ ...(o.history?.length ? { history: o.history.map((h) => ({ turn: h.turn, observed: h.observed })) } : {}),
128
+ territoriesInView: theirs.length,
129
+ armiesInView: theirs.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
130
+ bonusesHeld: bonuses.filter((b) => b.heldBy === o.playerId).map((b) => ({ bonusId: b.bonusId, value: b.value })),
131
+ besideMe,
132
+ movableBesideMe: besideMe.reduce((n, s) => n + Math.max(0, s.armies - guard), 0),
133
+ };
134
+ });
135
+ let changes = null;
136
+ if (input.previousBoard) {
137
+ const prev = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
138
+ const was = (id) => ownerOf(prev.get(id), me);
139
+ const lost = [];
140
+ const gained = [];
141
+ const moved = [];
142
+ for (const id of [...new Set([...prev.keys(), ...state.keys()])].sort((a, b) => a - b)) {
143
+ const before = was(id);
144
+ const now = owner(id);
145
+ if (before === 'me' && now !== 'me')
146
+ lost.push({ territoryId: id, to: now });
147
+ else if (now === 'me' && before !== 'me')
148
+ gained.push({ territoryId: id, from: before });
149
+ else if (typeof now === 'number' && before === now) {
150
+ const a = prev.get(id)?.armies;
151
+ const b = armiesOf(id);
152
+ if (a !== null && a !== undefined && b !== null && a !== b)
153
+ moved.push({ territoryId: id, owner: now, was: a, now: b });
154
+ }
155
+ }
156
+ moved.sort((x, y) => Math.abs(y.now - y.was) - Math.abs(x.now - x.was) || x.territoryId - y.territoryId);
157
+ changes = { lost, gained, moved: moved.slice(0, MAX_SITUATION_BONUSES) };
158
+ }
159
+ const past = [...(input.pastBoards ?? [])]
160
+ .sort((a, b) => a.turn - b.turn)
161
+ .slice(-SITUATION_PAST_TURNS)
162
+ .map((p) => {
163
+ const at = new Map(p.board.territories.map((t) => [t.territoryId, t]));
164
+ const sides = new Map();
165
+ for (const t of p.board.territories) {
166
+ const o = ownerOf(t, me);
167
+ if (o === 'fog' || o === 'neutral')
168
+ continue;
169
+ const side = sides.get(o) ?? { territories: 0, armies: 0 };
170
+ side.territories++;
171
+ side.armies += t.armies ?? 0;
172
+ sides.set(o, side);
173
+ }
174
+ const held = (o) => g.map.bonuses
175
+ .filter((b) => b.value > 0 && bonusTerritories(g, b.id).every((t) => ownerOf(at.get(t), me) === o))
176
+ .map((b) => b.id);
177
+ return {
178
+ turn: p.turn,
179
+ sides: [...sides]
180
+ .sort((a, b) => (a[0] === 'me' ? -1 : b[0] === 'me' ? 1 : a[0] - b[0]))
181
+ .map(([o, v]) => ({ owner: o, ...v, bonusesHeld: held(o) })),
182
+ ...(p.orders
183
+ ? {
184
+ myOrders: {
185
+ deploys: p.orders.deploys.map((d) => ({ territoryId: d.territoryId, armies: d.armies })),
186
+ moves: p.orders.moves.map((m) => ({ from: m.from, to: m.to, armies: m.armies })),
187
+ },
188
+ }
189
+ : {}),
190
+ };
191
+ });
192
+ return {
193
+ me: {
194
+ income: input.myIncome,
195
+ incomeHistory: [...(input.incomeHistory ?? [])],
196
+ territories: mine.length,
197
+ armies: mine.reduce((n, id) => n + (armiesOf(id) ?? 0), 0),
198
+ bonusesHeld: bonuses.filter((b) => b.heldBy === 'me').map((b) => ({ bonusId: b.bonusId, value: b.value })),
199
+ },
200
+ territories,
201
+ territoriesOmitted: Math.max(0, listed.length - MAX_SITUATION_TERRITORIES),
202
+ bonuses: bonuses.slice(0, MAX_SITUATION_BONUSES),
203
+ bonusesOmitted: Math.max(0, bonuses.length - MAX_SITUATION_BONUSES),
204
+ opponents,
205
+ changes,
206
+ past,
207
+ };
208
+ }
209
+ /** The parts of {@link Situation} a caller can ask for by name. */
210
+ export const FACT_PARTS = ['me', 'territories', 'bonuses', 'opponents', 'changes', 'past'];
211
+ /** What each part holds, for telling the caller what it can ask for. */
212
+ export const FACTS_AVAILABLE = {
213
+ me: 'my income and its history, land, armies and bonuses held',
214
+ territories: 'every territory in view and each hidden one beside my land, nearest first: owner, armies, special units, bonuses, neighbours',
215
+ bonuses: 'each bonus that matters: who holds how much of it, what finishing it costs, the members in reach',
216
+ opponents: "each opponent's income estimate with how it was read (source, visible, tracked, range, coverage, per-turn deploys), its bonuses and its stacks beside me",
217
+ changes: 'what changed since last turn: territories lost and gained, stacks that grew or shrank',
218
+ past: 'each of the last 10 turns kept: every side in view, its bonuses, my orders',
219
+ };
220
+ /** Only the parts asked for (the omitted counts go with their part). */
221
+ export function pickFacts(s, parts) {
222
+ const want = new Set(parts);
223
+ return {
224
+ ...(want.has('me') ? { me: s.me } : {}),
225
+ ...(want.has('territories') ? { territories: s.territories, territoriesOmitted: s.territoriesOmitted } : {}),
226
+ ...(want.has('bonuses') ? { bonuses: s.bonuses, bonusesOmitted: s.bonusesOmitted } : {}),
227
+ ...(want.has('opponents') ? { opponents: s.opponents } : {}),
228
+ ...(want.has('changes') ? { changes: s.changes } : {}),
229
+ ...(want.has('past') ? { past: s.past } : {}),
230
+ };
231
+ }
232
+ /** The one line every plan carries: what more the caller can ask warapp_plan_turn for. */
233
+ export const MORE_ON_REQUEST = 'Ask for more when you want to weigh the plan or build your own: strategy: true adds ranked captures and holds and the plan ' +
234
+ 'beside expand/defend alternatives, each stress-tested; facts: ["me","territories","bonuses","opponents","changes","past"] ' +
235
+ '(any of them) adds the raw game state behind them. Test any orders with warapp_check_plan.';
236
+ /** What to do with the facts: the tools that let the model test and act on its own plan. */
237
+ export const OWN_PLAN_STEPS = [
238
+ 'The plan, options and alternatives are inputs to your judgement, not the answer; ask warapp_plan_turn for the facts your decision needs (facts: me, territories, bonuses, opponents, changes, past).',
239
+ 'Write your own deploys and moves (any mix of the options, the alternatives or neither).',
240
+ 'Test them with warapp_check_plan (every opponent\'s replies, both move orders, one turn ahead); change and test again as needed.',
241
+ 'Look deeper when it matters: warapp_turn_history (what happened turn by turn), warapp_track_opponents and warapp_profile_opponents (how each opponent plays), warapp_plan_route (paths), warapp_get_map (the whole map), warapp_strategy (notes for this game), warapp_get_chat.',
242
+ 'Submit with warapp_submit_turn; when your orders differ from the plan, pass override_reason so the decision log keeps why.',
243
+ ];