@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,149 @@
1
+ // Is my commander takeable after my orders? (#274) Losing the commander ends the game, so this
2
+ // asks the stress test (stress.ts) one question only: of the single-deploy replies it tries, which
3
+ // take the territory my commander stands on once my orders have run, and how many armies would
4
+ // that territory need to survive every one of them. Pure and deterministic.
5
+ //
6
+ // territory where my commander stands after my orders run unanswered (my orders may take it along);
7
+ // armies the armies of mine there then (the commander not counted);
8
+ // distance moves from it to the nearest territory of an opponent or in the fog (null: none on the map);
9
+ // killers replies tried that kill it, each at the deploys given (the caller sizes them);
10
+ // needs the armies it needs there to survive every reply tried (luck-free under luck, as the
11
+ // stress test resolves battles): found by adding armies on the commander's starting
12
+ // territory (carried along when my orders move the commander from there) until no reply
13
+ // kills it. `armies` when none does; null past {@link SEARCH_CAP};
14
+ // killedBy the smallest deploy, made by every opponent at once (a per-opponent deploy, not a total),
15
+ // at which some reply tried kills it, with the opponent whose reply it is and, when that
16
+ // reply is two opponents striking together (#180, when I lead a free-for-all), its partner
17
+ // (null when none up to {@link SEARCH_CAP} does: no stack of theirs is in reach this turn;
18
+ // also null with `killedBy: false`, which skips that search: warapp_submit_turn never reads it).
19
+ //
20
+ // My Airlifts (`airlifts`, phase 43) run after every deploy and before every move: they are applied
21
+ // to the board with my deploys before anything else (armies off `from` and onto `to`, the commander
22
+ // with them when it goes along), so an Airlift out of, onto or of the commander is counted.
23
+ //
24
+ // Only the replies that strike the commander's territory are tried (`targets`), and never the
25
+ // look-ahead, so it is cheap enough to run inside warapp_submit_turn. What the stress test does not
26
+ // try (fog, a split deploy, cards, …) this does not either.
27
+ import { bfsDistances } from './graph.js';
28
+ import { stressPlan } from './stress.js';
29
+ import { simulateTurn } from './turn-sim.js';
30
+ /** Armies, or a deploy, past which the searches stop. */
31
+ export const SEARCH_CAP = 1_000_000;
32
+ /** The territory my commander stands on, if it is on the board. */
33
+ export function myCommanderTerritory(board, me) {
34
+ return board.territories.find((t) => t.owner.kind === 'player' && t.owner.playerId === me && t.specialUnits?.some((u) => u.kind === 'commander' && u.playerId === me))
35
+ ?.territoryId;
36
+ }
37
+ /** The board once my deploys and then my Airlifts have run (the commander moved with its Airlift). */
38
+ function airlifted(board, me, deploys, airlifts) {
39
+ const territories = board.territories.map((t) => ({ ...t, ...(t.specialUnits ? { specialUnits: [...t.specialUnits] } : {}) }));
40
+ const at = new Map(territories.map((t) => [t.territoryId, t]));
41
+ const add = (id, n) => {
42
+ const t = at.get(id);
43
+ if (t)
44
+ t.armies = Math.max(0, (t.armies ?? 0) + n);
45
+ };
46
+ for (const d of deploys)
47
+ add(d.territoryId, d.armies);
48
+ for (const a of airlifts) {
49
+ add(a.from, -a.armies);
50
+ add(a.to, a.armies);
51
+ if (!a.commander)
52
+ continue;
53
+ const src = at.get(a.from);
54
+ const dst = at.get(a.to);
55
+ const unit = src?.specialUnits?.find((u) => u.kind === 'commander' && u.playerId === me);
56
+ if (!src || !dst || !unit)
57
+ continue;
58
+ src.specialUnits = src.specialUnits.filter((u) => u !== unit);
59
+ if (!src.specialUnits.length)
60
+ delete src.specialUnits;
61
+ dst.specialUnits = [...(dst.specialUnits ?? []), unit];
62
+ }
63
+ return { ...board, territories };
64
+ }
65
+ /** The smallest n in [lo, SEARCH_CAP] with `ok(n)`, for `ok` false then true; null when `ok(SEARCH_CAP)` is false. */
66
+ function smallest(lo, ok) {
67
+ if (ok(lo))
68
+ return lo;
69
+ let bad = lo;
70
+ let hi = Math.max(1, lo * 2);
71
+ while (!ok(hi)) {
72
+ bad = hi;
73
+ if (hi >= SEARCH_CAP)
74
+ return null;
75
+ hi = Math.min(SEARCH_CAP, hi * 2);
76
+ }
77
+ while (hi - bad > 1) {
78
+ const mid = Math.floor((bad + hi) / 2);
79
+ if (ok(mid))
80
+ hi = mid;
81
+ else
82
+ bad = mid;
83
+ }
84
+ return hi;
85
+ }
86
+ export function commanderSafety(options) {
87
+ const { killedBy: searchKilledBy = true, airlifts, ...given } = options;
88
+ const start = myCommanderTerritory(given.board, given.me);
89
+ if (start === undefined)
90
+ return undefined;
91
+ // My deploys and Airlifts applied first: everything below runs on the board the moves start from.
92
+ const input = airlifts?.length ? { ...given, board: airlifted(given.board, given.me, given.deploys, airlifts), deploys: [] } : given;
93
+ const { graph, board, me } = input;
94
+ // Where it stands when the moves begin (its Airlift's destination, when one takes it).
95
+ const from = myCommanderTerritory(board, me) ?? start;
96
+ // Where my orders leave it (they may take it along), with nobody answering.
97
+ const after = simulateTurn({
98
+ graph,
99
+ board,
100
+ deploys: input.deploys.map((d) => ({ player: me, territoryId: d.territoryId, armies: d.armies })),
101
+ orders: [{ player: me, orders: input.moves.map((m) => ({ ...m })) }],
102
+ moveOrder: [me],
103
+ ...(input.settings ? { settings: input.settings } : {}),
104
+ ...(input.teams ? { teams: input.teams } : {}),
105
+ ...(input.orderPriority ? { orderPriority: [me] } : {}),
106
+ }).territories;
107
+ const ended = [...after].find(([, t]) => t.commander === me)?.[0];
108
+ const lostUnanswered = ended === undefined;
109
+ const territory = ended ?? from;
110
+ const armies = lostUnanswered ? 0 : (after.get(territory)?.armies ?? 0);
111
+ const at = [...new Set([from, territory])];
112
+ const run = (over) => stressPlan({ ...input, ...over, targets: at, lookAhead: false });
113
+ const kills = (r) => r.atRisk.commander;
114
+ const report = run({});
115
+ const killers = kills(report);
116
+ // The armies that hold: more on the starting territory, carried along by the move that takes the commander.
117
+ const carrier = territory === from ? -1 : input.moves.findIndex((m) => m.from === from && m.withCommander === true);
118
+ const withExtra = (extra) => ({
119
+ deploys: [...input.deploys, { territoryId: from, armies: extra }],
120
+ moves: input.moves.map((m, i) => (i === carrier ? { ...m, armies: m.armies + extra } : m)),
121
+ });
122
+ const extra = lostUnanswered ? null : killers === 0 ? 0 : smallest(1, (n) => kills(run(withExtra(n))) === 0);
123
+ // The smallest deploy, the same for every opponent, that kills it.
124
+ const killing = (d) => run({ opponents: input.opponents.map((o) => ({ ...o, deploy: d })) });
125
+ const killedAt = searchKilledBy && input.opponents.length && !lostUnanswered ? smallest(0, (d) => kills(killing(d)) > 0) : null;
126
+ const killer = killedAt === null ? undefined : killing(killedAt).replies.find((r) => r.commanderLost);
127
+ // Moves to the nearest territory of an opponent (a teammate's is not one) or in the fog.
128
+ const myTeam = input.teams?.get(me);
129
+ const hostile = board.territories.filter((t) => t.owner.kind === 'unknown' ||
130
+ t.armies === null ||
131
+ (t.owner.kind === 'player' && t.owner.playerId !== me && (myTeam === undefined || input.teams?.get(t.owner.playerId) !== myTeam)));
132
+ const dist = bfsDistances(graph, [territory]);
133
+ const reach = hostile.map((t) => dist.get(t.territoryId)).filter((d) => d !== undefined);
134
+ const worst = report.replies.find((r) => r.commanderLost);
135
+ return {
136
+ territory,
137
+ from: start,
138
+ armies,
139
+ distance: reach.length ? Math.min(...reach) : null,
140
+ killers,
141
+ ...(worst ? { worst } : {}),
142
+ needs: extra === null ? null : armies + extra,
143
+ killedBy: killedAt === null || !killer
144
+ ? null
145
+ : { deploy: killedAt, opponent: killer.opponent, ...(killer.kind === 'joint' && killer.partner !== undefined ? { partner: killer.partner } : {}) },
146
+ lostUnanswered,
147
+ exact: report.exact,
148
+ };
149
+ }
@@ -0,0 +1,338 @@
1
+ import { ownerShown } from './plan/shared.js';
2
+ import { bonusTerritories } from './bonuses.js';
3
+ import { agreementState, coveredTerritories, newAgreement, partyRefusal, scopeRefusal, TERMINAL_STATUSES, transitionAgreement, } from './relations.js';
4
+ /** Every commitment kind a message may declare. */
5
+ export const COMMITMENT_KINDS = ['no-attack', 'will-attack', 'notice', 'propose', 'accept'];
6
+ /** The most turns a `no-attack` promise may run. */
7
+ export const MAX_NO_ATTACK_TURNS = 10;
8
+ /** The most commitments one message may declare. */
9
+ export const MAX_MESSAGE_COMMITMENTS = 10;
10
+ /**
11
+ * Why a propose, accept or notice with `partner` cannot go to `audience`: the partner would never read
12
+ * it. `undefined` when it reads it (the private recipient, anyone on the public channel, a player on the
13
+ * team the message goes to).
14
+ */
15
+ export function audienceRefusal(audience, partner, players) {
16
+ if (audience.kind === 'public')
17
+ return undefined;
18
+ if (audience.kind === 'private')
19
+ return audience.to === partner
20
+ ? undefined
21
+ : `the message goes privately to player ${audience.to}, so player ${partner}, the truce's partner, would never read it (D3: a truce changes only with the partner told)`;
22
+ const p = players.find((x) => x.id === partner);
23
+ return p?.team === audience.team
24
+ ? undefined
25
+ : `the message goes to team ${audience.team} only, and player ${partner}, the truce's partner, is not on it: it would never read it (D3: a truce changes only with the partner told)`;
26
+ }
27
+ const ownerOf = (board, t) => {
28
+ const s = board.territories.find((x) => x.territoryId === t);
29
+ return s && ownerShown(s) && s.owner.kind === 'player' ? s.owner.playerId : null;
30
+ };
31
+ const heldBy = (board, p) => new Set(board.territories.filter((t) => ownerShown(t) && t.owner.kind === 'player' && t.owner.playerId === p).map((t) => t.territoryId));
32
+ /** The territories `scope` names (none for `all`) whose owner my board does not show: they may be anyone's. */
33
+ function unseenNamed(graph, board, scope) {
34
+ if (scope === 'all')
35
+ return new Set();
36
+ const ids = 'territories' in scope ? scope.territories : scope.bonuses.flatMap((b) => [...bonusTerritories(graph, b)]);
37
+ const shown = new Map(board.territories.map((t) => [t.territoryId, t]));
38
+ return new Set(ids.filter((t) => !ownerShown(shown.get(t))));
39
+ }
40
+ /** Every territory on the map whose owner my board does not show. */
41
+ function unseenAll(graph, board) {
42
+ const shown = new Map(board.territories.map((t) => [t.territoryId, t]));
43
+ return new Set([...graph.territoryById.keys()].filter((t) => !ownerShown(shown.get(t))));
44
+ }
45
+ const intoFog = (hit) => `${hit.map((h) => `move ${h.index + 1} (${h.from} → ${h.to})`).join(', ')} ${hit.length === 1 ? 'goes into a territory' : 'go into territories'} whose owner is not shown`;
46
+ /** The orders among `moves` that attack one of `targets` (by index), transfers-only aside. */
47
+ function attacksOn(moves, targets) {
48
+ return moves.flatMap((m, index) => (!m.transferOnly && targets.has(m.to) ? [{ index, from: m.from, to: m.to }] : []));
49
+ }
50
+ const normScope = (s) => JSON.stringify(s === 'all' ? 'all' : 'territories' in s ? { territories: [...s.territories].sort((x, y) => x - y) } : { bonuses: [...s.bonuses].sort((x, y) => x - y) });
51
+ /** Whether `given` (the terms an accept restates) agrees with `t` on every field it gives. */
52
+ function sameGivenTerms(given, t) {
53
+ return Object.keys(given).every((k) => given[k] === undefined ? true : k === 'scope' ? normScope(given.scope) === normScope(t.scope) : given[k] === t[k]);
54
+ }
55
+ /** New terms from what an accept gives: the scope `all` and 1 turn of notice unless stated. */
56
+ const fullTerms = (t) => ({ ...t, scope: t.scope ?? 'all', noticeTurns: t.noticeTurns ?? 1 });
57
+ /** A truce whose last turn has passed is over before it begins. */
58
+ const pastUntil = (t, turn) => t.untilTurn !== undefined && t.untilTurn < turn ? `the truce would bind only until turn ${t.untilTurn}, before this turn (${turn})` : undefined;
59
+ const openWith = (agreements, p) => agreements.find((a) => a.with === p && !TERMINAL_STATUSES.has(a.status));
60
+ /**
61
+ * The agreement change a `propose`, `accept` or `notice` makes to `agreements` on `turn`, or why it
62
+ * cannot. Shared by the check (`checkCommitments`) and the write once the message is sent, so both
63
+ * apply the same rule to the ledger as it then stands. `players` is checked for a new commitment
64
+ * (`partyRefusal`) only when given.
65
+ */
66
+ export function agreementChange(c, o) {
67
+ const { agreements, turn, me } = o;
68
+ const party = (p) => (o.players ? partyRefusal(o.players, me, p) : undefined);
69
+ const scopeBad = (t) => (o.graph ? scopeRefusal(o.graph, t.scope) : undefined);
70
+ const move = (a, status) => {
71
+ const r = transitionAgreement(a, status, turn);
72
+ return 'refused' in r ? r : { agreement: r.agreement, before: a, created: false };
73
+ };
74
+ if (c.kind === 'notice') {
75
+ const a = agreements.find((x) => x.id === c.agreement);
76
+ if (!a)
77
+ return { refused: `there is no agreement ${c.agreement} in the ledger` };
78
+ if (a.status === 'notice-by-me')
79
+ return { agreement: a, before: a, created: false };
80
+ if (a.status !== 'agreed')
81
+ return { refused: `agreement ${a.id} is ${a.status}: notice is given on an agreed truce` };
82
+ return move(a, 'notice-by-me');
83
+ }
84
+ if (c.kind === 'propose') {
85
+ const why = party(c.with) ?? scopeBad(c.terms) ?? pastUntil(c.terms, turn);
86
+ if (why)
87
+ return { refused: why };
88
+ const open = openWith(agreements, c.with);
89
+ if (!open)
90
+ return { agreement: newAgreement(o.nextAgreementId(agreements), c.with, 'proposed-by-me', turn, c.terms), before: undefined, created: true };
91
+ if (open.status !== 'proposed-by-me' && open.status !== 'proposed-by-them')
92
+ return { refused: `agreement ${open.id} with player ${c.with} is already ${open.status}: end it before proposing new terms` };
93
+ const withTerms = { ...open, terms: c.terms };
94
+ if (open.status === 'proposed-by-me')
95
+ return { agreement: withTerms, before: open, created: false };
96
+ const r = transitionAgreement(withTerms, 'proposed-by-me', turn);
97
+ return 'refused' in r ? r : { agreement: r.agreement, before: open, created: false };
98
+ }
99
+ // accept
100
+ let target;
101
+ if (c.agreement !== undefined) {
102
+ target = agreements.find((x) => x.id === c.agreement);
103
+ if (!target)
104
+ return { refused: `there is no agreement ${c.agreement} in the ledger` };
105
+ if (c.with !== undefined && c.with !== target.with)
106
+ return { refused: `agreement ${target.id} is with player ${target.with}, not player ${c.with}` };
107
+ }
108
+ else if (c.with !== undefined) {
109
+ const open = openWith(agreements, c.with);
110
+ if (open && (open.status === 'proposed-by-me' || open.status === 'proposed-by-them'))
111
+ target = open;
112
+ else if (open)
113
+ return { refused: `agreement ${open.id} with player ${c.with} is already ${open.status}` };
114
+ }
115
+ else {
116
+ return { refused: 'an acceptance names the agreement, or the player and the terms' };
117
+ }
118
+ if (target) {
119
+ if (target.status !== 'proposed-by-me' && target.status !== 'proposed-by-them')
120
+ return { refused: `agreement ${target.id} is ${target.status}: only a proposal is accepted` };
121
+ if (c.terms && !sameGivenTerms(c.terms, target.terms))
122
+ return { refused: `the terms differ from agreement ${target.id}'s: a counter-offer is a propose, not an accept` };
123
+ const why = party(target.with) ?? pastUntil(target.terms, turn);
124
+ if (why)
125
+ return { refused: why };
126
+ return move(target, 'agreed');
127
+ }
128
+ if (!c.terms)
129
+ return { refused: `no proposal from player ${c.with} is recorded: give the terms accepted` };
130
+ const terms = fullTerms(c.terms);
131
+ const why = party(c.with) ?? scopeBad(terms) ?? pastUntil(terms, turn);
132
+ if (why)
133
+ return { refused: why };
134
+ return { agreement: newAgreement(o.nextAgreementId(agreements), c.with, 'agreed', turn, terms), before: undefined, created: true };
135
+ }
136
+ /**
137
+ * B4: each commitment checked against this turn's orders (`moves`: the plan made in the call, or the
138
+ * orders already submitted — `source` says which) and the ledger, in the message's order: a change an
139
+ * earlier commitment makes to an agreement is seen by a later one. A commitment the orders or the
140
+ * ledger do not carry is `refused`, with the reason, and so is a propose, accept or notice whose
141
+ * partner is not among the message's readers (`audience`, {@link audienceRefusal}).
142
+ */
143
+ export function checkCommitments(input) {
144
+ const { graph, board, me, turn, players, moves, source, audience } = input;
145
+ let agreements = [...input.agreements];
146
+ const orders = source === 'plan' ? 'planned' : 'submitted';
147
+ const named = (a) => `the ${orders} move ${a.index + 1} (${a.from} → ${a.to})`;
148
+ const checks = [];
149
+ const player = (p) => players.find((x) => x.id === p);
150
+ // Under the scope `all`, orders into territories whose owner is not shown are said, never assumed safe.
151
+ const fogAll = attacksOn(moves, unseenAll(graph, board));
152
+ const unchecked = (scope) => (scope === 'all' && fogAll.length ? `; ${intoFog(fogAll)}, which ${fogAll.length === 1 ? 'was' : 'were'} not checked` : '');
153
+ input.commitments.forEach((c, index) => {
154
+ const out = (rest) => checks.push({ index, kind: c.kind, ...rest });
155
+ if (c.kind === 'no-attack') {
156
+ if (c.with === me)
157
+ return out({ refused: 'a promise not to attack yourself carries nothing' });
158
+ if (!player(c.with))
159
+ return out({ refused: `player ${c.with} is not in this game` });
160
+ const bad = scopeRefusal(graph, c.scope);
161
+ if (bad)
162
+ return out({ refused: bad });
163
+ const covered = new Set(coveredTerritories(graph, c.scope, heldBy(board, c.with)));
164
+ const hit = attacksOn(moves, covered);
165
+ if (hit.length)
166
+ return out({ refused: `${named(hit[0])} attacks player ${c.with}'s territory ${hit[0].to}, which the promise covers` });
167
+ const fog = attacksOn(moves, unseenNamed(graph, board, c.scope));
168
+ if (fog.length)
169
+ return out({ refused: `${named(fog[0])} attacks territory ${fog[0].to}, which the promise names and whose owner is not shown: it may be player ${c.with}'s` });
170
+ const toTurn = turn + c.turns - 1;
171
+ return out({
172
+ carried: `no ${orders} order this turn attacks player ${c.with}'s territories it covers (${covered.size} on the board now); it binds through turn ${toTurn}${unchecked(c.scope)}`,
173
+ record: { sentTurn: turn, kind: 'no-attack', with: c.with, scope: c.scope, fromTurn: turn, toTurn },
174
+ });
175
+ }
176
+ if (c.kind === 'will-attack') {
177
+ if (c.with === undefined && c.territory === undefined)
178
+ return out({ refused: 'a promise to attack names a player or a territory' });
179
+ const when = c.turn ?? turn;
180
+ if (when !== turn)
181
+ return out({ refused: `only this turn's orders (turn ${turn}) can carry a promise to attack: turn ${when} is not planned yet — send it on that turn` });
182
+ if (c.with !== undefined) {
183
+ if (c.with === me)
184
+ return out({ refused: 'you cannot attack yourself' });
185
+ if (!player(c.with))
186
+ return out({ refused: `player ${c.with} is not in this game` });
187
+ }
188
+ let targets;
189
+ if (c.territory !== undefined) {
190
+ if (!graph.territoryById.has(c.territory))
191
+ return out({ refused: `territory ${c.territory} is not on this map` });
192
+ const owner = ownerOf(board, c.territory);
193
+ if (owner === me)
194
+ return out({ refused: `territory ${c.territory} is yours: there is nothing to attack` });
195
+ if (c.with !== undefined && owner !== c.with)
196
+ return out({ refused: `territory ${c.territory} is not player ${c.with}'s on your board` });
197
+ targets = new Set([c.territory]);
198
+ }
199
+ else {
200
+ targets = heldBy(board, c.with);
201
+ }
202
+ const hit = attacksOn(moves, targets);
203
+ const what = c.territory !== undefined ? `territory ${c.territory}` : `player ${c.with}`;
204
+ if (!hit.length) {
205
+ const fog = attacksOn(moves, unseenAll(graph, board));
206
+ return out({ refused: `no ${orders} order this turn attacks ${what}${fog.length ? ` (${intoFog(fog)}, which does not count)` : ''}` });
207
+ }
208
+ return out({
209
+ carried: `${named(hit[0])} attacks ${what}`,
210
+ record: {
211
+ sentTurn: turn,
212
+ kind: 'will-attack',
213
+ ...(c.with !== undefined ? { with: c.with } : {}),
214
+ ...(c.territory !== undefined ? { territory: c.territory } : {}),
215
+ turn,
216
+ },
217
+ });
218
+ }
219
+ // notice, propose, accept: the ledger first, then the orders against what the agreement covers.
220
+ const change = agreementChange(c, { agreements, turn, me, players, graph, nextAgreementId: input.nextAgreementId });
221
+ if ('refused' in change)
222
+ return out({ refused: change.refused });
223
+ const a = change.agreement;
224
+ const unread = audienceRefusal(audience, a.with, players);
225
+ if (unread)
226
+ return out({ refused: unread });
227
+ const covered = new Set(coveredTerritories(graph, a.terms.scope, heldBy(board, a.with)));
228
+ const hit = attacksOn(moves, covered);
229
+ const fog = attacksOn(moves, unseenNamed(graph, board, a.terms.scope));
230
+ const fogText = (what) => `${named(fog[0])} attacks territory ${fog[0].to}, which ${what} names and whose owner is not shown: it may be player ${a.with}'s`;
231
+ if (c.kind === 'notice') {
232
+ const state = agreementState(a, turn, players);
233
+ // A truce with no notice (0 turns, an agreed term) ends with the message: notice served this turn
234
+ // has already run, so it binds no more from this turn and an attack this turn breaks nothing.
235
+ const endsNow = a.status === 'notice-by-me' && a.noticeTurn === turn && state.phase === 'over' && state.reason === 'notice-served';
236
+ const endsTurn = endsNow ? turn : state.endsTurn;
237
+ if (endsTurn === undefined || (!endsNow && state.phase !== 'notice'))
238
+ return out({ refused: `agreement ${a.id} is over (${state.reason ?? state.phase}): there is nothing to give notice on` });
239
+ if (c.endsTurn !== undefined && c.endsTurn !== endsTurn)
240
+ return out({
241
+ refused: `agreement ${a.id} carries ${a.terms.noticeTurns} turn${a.terms.noticeTurns === 1 ? '' : 's'} of notice: given on turn ${a.noticeTurn}, ` +
242
+ `it binds until turn ${endsTurn}, so the message cannot say it ends on turn ${c.endsTurn}` +
243
+ (c.endsTurn > endsTurn ? ` (the ledger frees its territories on turn ${endsTurn}: to keep the truce longer, propose new terms)` : ''),
244
+ });
245
+ const record = { sentTurn: turn, kind: 'notice', agreement: a.id, with: a.with, endsTurn };
246
+ if (endsNow) {
247
+ agreements = [...agreements.filter((x) => x.id !== a.id), a];
248
+ return out({
249
+ carried: `agreement ${a.id} with player ${a.with} carries no notice: it ends with this message, so it no longer binds from this turn (${turn}) and an attack on its territories this turn breaks nothing`,
250
+ record,
251
+ change,
252
+ });
253
+ }
254
+ if (hit.length)
255
+ return out({ refused: `${named(hit[0])} attacks territory ${hit[0].to}, which agreement ${a.id} covers while its notice runs` });
256
+ if (fog.length)
257
+ return out({ refused: fogText(`agreement ${a.id}`) });
258
+ agreements = [...agreements.filter((x) => x.id !== a.id), a];
259
+ return out({
260
+ carried: `agreement ${a.id} with player ${a.with}: notice from turn ${a.noticeTurn}, binding until turn ${endsTurn}, and no ${orders} order this turn attacks a territory it covers${unchecked(a.terms.scope)}`,
261
+ record,
262
+ change,
263
+ });
264
+ }
265
+ if (hit.length)
266
+ return out({ refused: `${named(hit[0])} attacks player ${a.with}'s territory ${hit[0].to}, which the ${c.kind === 'propose' ? 'proposed' : 'accepted'} truce covers` });
267
+ if (fog.length)
268
+ return out({ refused: fogText(`the ${c.kind === 'propose' ? 'proposed' : 'accepted'} truce`) });
269
+ agreements = [...agreements.filter((x) => x.id !== a.id), a];
270
+ return out({
271
+ carried: `agreement ${a.id} with player ${a.with} (${a.status}), and no ${orders} order this turn attacks a territory it covers${unchecked(a.terms.scope)}`,
272
+ record: { sentTurn: turn, kind: c.kind, agreement: a.id, with: a.with },
273
+ change,
274
+ });
275
+ });
276
+ return { checks, agreements };
277
+ }
278
+ /**
279
+ * B4 (warapp_submit_turn): the commitments I sent that `moves` would break on `turn` — an order that
280
+ * attacks a territory a `no-attack` still covers, or that a truce I proposed (still a proposal) covers;
281
+ * and a `will-attack` for this turn that no order carries. Notice and accepted truces are the ledger's
282
+ * own (`truceBreaksIn`). Under the scope `all`, orders that only go into territories whose owner is not
283
+ * shown are a soft warning (`unchecked`): they may land on the player. Warnings, never a refusal. Pure.
284
+ */
285
+ export function commitmentWarnings(input) {
286
+ const { graph, board, me, turn, moves } = input;
287
+ const out = [];
288
+ const said = (c) => `commitment ${c.id} (sent turn ${c.sentTurn})`;
289
+ const list = (hit) => hit.map((h) => `move ${h.index + 1} (${h.from} → ${h.to})`).join(', ');
290
+ // A territory the scope names whose owner is not shown may be the partner's: an attack there counts.
291
+ const hitsOn = (scope, p) => {
292
+ const covered = new Set(coveredTerritories(graph, scope, heldBy(board, p)));
293
+ const unseen = unseenNamed(graph, board, scope);
294
+ const hit = attacksOn(moves, new Set([...covered, ...unseen]));
295
+ const fogged = [...new Set(hit.filter((h) => unseen.has(h.to)).map((h) => h.to))];
296
+ const note = fogged.length ? ` (territory ${fogged.join(', ')}'s owner is not shown)` : '';
297
+ // Under the scope `all` any territory whose owner is not shown may be the player's: said, never assumed safe.
298
+ const fog = scope === 'all' && !hit.length ? attacksOn(moves, unseenAll(graph, board)) : [];
299
+ return { hit, note, fog, fogText: fog.length ? `${intoFog(fog)} — it may be player ${p}'s, which was not checked` : '' };
300
+ };
301
+ for (const c of [...input.commitments].sort((x, y) => x.id.localeCompare(y.id, 'en', { numeric: true }))) {
302
+ if (c.kind === 'no-attack') {
303
+ if (turn < c.fromTurn || turn > c.toTurn || c.with === me)
304
+ continue;
305
+ const { hit, note, fog, fogText } = hitsOn(c.scope, c.with);
306
+ if (hit.length)
307
+ out.push({ commitment: c.id, kind: c.kind, with: c.with, moves: hit, text: `${said(c)} promised player ${c.with} no attack there through turn ${c.toTurn}: ${list(hit)} attacks it${note}` });
308
+ else if (fog.length)
309
+ out.push({ commitment: c.id, kind: c.kind, with: c.with, moves: fog, unchecked: true, text: `${said(c)} promised player ${c.with} no attack on any of its territories through turn ${c.toTurn}: ${fogText}` });
310
+ }
311
+ else if (c.kind === 'will-attack') {
312
+ if (c.turn !== turn)
313
+ continue;
314
+ const targets = c.territory !== undefined ? new Set([c.territory]) : heldBy(board, c.with);
315
+ if (attacksOn(moves, targets).length)
316
+ continue;
317
+ const what = c.territory !== undefined ? `territory ${c.territory}` : `player ${c.with}`;
318
+ out.push({
319
+ commitment: c.id,
320
+ kind: c.kind,
321
+ ...(c.with !== undefined ? { with: c.with } : {}),
322
+ moves: [],
323
+ text: `${said(c)} said you would attack ${what} this turn: no order here does`,
324
+ });
325
+ }
326
+ else if (c.kind === 'propose') {
327
+ const a = input.agreements.find((x) => x.id === c.agreement);
328
+ if (!a || (a.status !== 'proposed-by-me' && a.status !== 'proposed-by-them'))
329
+ continue;
330
+ const { hit, note, fog, fogText } = hitsOn(a.terms.scope, a.with);
331
+ if (hit.length)
332
+ out.push({ commitment: c.id, kind: c.kind, with: a.with, moves: hit, text: `${said(c)} proposed truce ${a.id} to player ${a.with}, still open: ${list(hit)} attacks a territory it covers${note}` });
333
+ else if (fog.length)
334
+ out.push({ commitment: c.id, kind: c.kind, with: a.with, moves: fog, unchecked: true, text: `${said(c)} proposed truce ${a.id} to player ${a.with}, still open: ${fogText}` });
335
+ }
336
+ }
337
+ return out;
338
+ }
@@ -0,0 +1,155 @@
1
+ // Attacks on a player judged by their exchange, and a multi-turn view of a contested border
2
+ // (#167). Pure and deterministic; no I/O.
3
+ //
4
+ // Exchange. At the default rates (60/70, no luck) an attack below seven sixths of the defenders
5
+ // loses more armies than it kills; from there to five thirds it kills more without capturing;
6
+ // above that it captures. `classifyExchange` gives kills, losses and capture at three defender
7
+ // sizes — as they stand, after the owner's estimated deploy, after its whole income — and a label:
8
+ // - certain first strike: it captures even if the whole income lands there first;
9
+ // - favourable exchange: against the estimated deploy it kills more than it loses (or captures);
10
+ // - strike last: it does not pay, but the target's stack can hit my source — stand, let it
11
+ // attack first, and strike its survivors last;
12
+ // - stand: it loses more than it kills.
13
+ // Kills are luck-free and straight-rounded (`straightKills`), each side capped at the other's
14
+ // armies; a capture needs every defender dead and an attacker alive (`armiesToTake`).
15
+ //
16
+ // Border forecast. Two stacks facing each other, both owners deploying on them every turn, simulated
17
+ // forward with `simulateTurn` (one turn's resolution, chained through its `start` board, so the
18
+ // guard and the rounding are the game's): "press" — I attack with everything movable every turn
19
+ // while the opponent defends — and "pressed", the reverse. The outcome is `breaks` (press captures
20
+ // first), `ground-down` (pressed captures first; a tie goes to the opponent: the worse case), or
21
+ // `stand-off` (neither within the horizon). `pinned` is the least I must deploy there each turn for
22
+ // pressed not to break me within the horizon: the income the border pins (my whole income when
23
+ // even that is not enough).
24
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, straightKills } from './combat.js';
25
+ import { buildGraph, neighborsOf } from './graph.js';
26
+ import { simulateTurn } from './turn-sim.js';
27
+ export function classifyExchange(input) {
28
+ const off = input.rates?.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
29
+ const def = input.rates?.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
30
+ const a = Math.max(0, input.attackers);
31
+ const at = (kind, d) => {
32
+ const kills = Math.min(d, straightKills(a, off));
33
+ const losses = Math.min(a, straightKills(d, def));
34
+ const take = armiesToTake(d, input.rates);
35
+ return { case: kind, defenders: d, kills, losses, net: kills - losses, captures: take !== null && a >= take };
36
+ };
37
+ const d0 = Math.max(0, input.defenders);
38
+ const est = Math.max(0, input.deploy);
39
+ const whole = Math.max(est, input.income);
40
+ const cases = [at('now', d0), at('estimated', d0 + est), at('whole', d0 + whole)];
41
+ const [, e, w] = cases;
42
+ const label = w.captures
43
+ ? 'certain first strike'
44
+ : e.captures || e.net > 0
45
+ ? 'favourable exchange'
46
+ : input.threatensSource
47
+ ? 'strike last'
48
+ : 'stand';
49
+ return { label, cases };
50
+ }
51
+ /** The forecast horizon in turns (the planner's payback horizon). */
52
+ export const FORECAST_TURNS = 10;
53
+ const ME = 1;
54
+ const THEM = 2;
55
+ let pairGraph;
56
+ /** Two territories, 1 (mine) and 2 (theirs), next to each other. */
57
+ function pair() {
58
+ pairGraph ??= buildGraph({
59
+ id: 0,
60
+ name: 'border',
61
+ territories: [
62
+ { id: 1, name: 'mine', connectedTo: [2] },
63
+ { id: 2, name: 'theirs', connectedTo: [1] },
64
+ ],
65
+ bonuses: [],
66
+ distributionModes: [],
67
+ });
68
+ return pairGraph;
69
+ }
70
+ /**
71
+ * The turn (1-based) `attacker` first captures the other stack when it attacks with everything
72
+ * movable every turn and both deploy their per-turn armies on their stacks; `null` within `turns`.
73
+ */
74
+ function grind(attacker, mine, theirs, myDeploy, theirDeploy, turns, settings) {
75
+ const g = pair();
76
+ const guard = settings.oneArmyStandsGuard === false ? 0 : 1;
77
+ let start = new Map([
78
+ [1, { owner: ME, armies: Math.max(0, mine) }],
79
+ [2, { owner: THEM, armies: Math.max(0, theirs) }],
80
+ ]);
81
+ const from = attacker === ME ? 1 : 2;
82
+ const to = attacker === ME ? 2 : 1;
83
+ for (let turn = 1; turn <= turns; turn++) {
84
+ const before = start.get(from).armies + (attacker === ME ? myDeploy : theirDeploy);
85
+ const movable = before - guard;
86
+ const r = simulateTurn({
87
+ graph: g,
88
+ board: { source: 'gamefeed', verified: false, territories: [] },
89
+ start,
90
+ deploys: [
91
+ { player: ME, territoryId: 1, armies: Math.max(0, myDeploy) },
92
+ { player: THEM, territoryId: 2, armies: Math.max(0, theirDeploy) },
93
+ ],
94
+ orders: movable > 0 ? [{ player: attacker, orders: [{ from, to, armies: movable }] }] : [],
95
+ moveOrder: [attacker],
96
+ settings,
97
+ });
98
+ if (r.territories.get(to).owner === attacker)
99
+ return turn;
100
+ start = r.territories;
101
+ }
102
+ return null;
103
+ }
104
+ export function forecastBorder(input) {
105
+ const turns = Math.max(1, Math.floor(input.turns ?? FORECAST_TURNS));
106
+ const settings = { ...input.settings, luckModifier: 0, roundingMode: 'StraightRound' };
107
+ const myIncome = Math.max(0, Math.floor(input.myIncome));
108
+ const theirIncome = Math.max(0, Math.floor(input.theirIncome));
109
+ const myDeploy = Math.min(myIncome, Math.max(0, Math.floor(input.myDeploy ?? myIncome)));
110
+ const press = grind(ME, input.mine, input.theirs, myDeploy, theirIncome, turns, settings);
111
+ const pressed = grind(THEM, input.mine, input.theirs, myDeploy, theirIncome, turns, settings);
112
+ let outcome;
113
+ let turn;
114
+ if (pressed !== null && (press === null || pressed <= press)) {
115
+ outcome = 'ground-down';
116
+ turn = pressed;
117
+ }
118
+ else if (press !== null) {
119
+ outcome = 'breaks';
120
+ turn = press;
121
+ }
122
+ else {
123
+ outcome = 'stand-off';
124
+ turn = null;
125
+ }
126
+ let pinned = myIncome;
127
+ let pinnedHolds = false;
128
+ if (!input.outcomeOnly)
129
+ for (let d = 0; d <= myIncome; d++)
130
+ if (grind(THEM, input.mine, input.theirs, d, theirIncome, turns, settings) === null) {
131
+ pinned = d;
132
+ pinnedHolds = true;
133
+ break;
134
+ }
135
+ return { outcome, turn, turns, pinned, pinnedHolds };
136
+ }
137
+ /**
138
+ * #218: the main front, one definition for the planner's front outlook (#167) and the game
139
+ * outlook's front forecast (#201): the biggest enemy stack next to a territory of mine (ties to
140
+ * the lower id), against my biggest stack beside it (ties to the lower id). `enemies` are the
141
+ * visible stacks of every opponent (teammates left out by the caller); `myArmies` gives my stack
142
+ * on a territory of mine (special units included).
143
+ */
144
+ export function mainFront(g, isMine, enemies, myArmies) {
145
+ let front;
146
+ for (const e of [...enemies].sort((a, b) => a.id - b.id)) {
147
+ const next = neighborsOf(g, e.id).filter(isMine);
148
+ if (!next.length)
149
+ continue;
150
+ const from = [...next].sort((x, y) => myArmies(y) - myArmies(x) || x - y)[0];
151
+ if (!front || e.armies > front.theirs)
152
+ front = { from, at: e.id, mine: myArmies(from), theirs: e.armies, player: e.player };
153
+ }
154
+ return front;
155
+ }