@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,266 @@
1
+ // warapp_team_brief (C4, docs/PLAN-TEAMS.md): the content of a team-chat message as data, by stage — never sent.
2
+ // While picking: my list and its overlap with each teammate's. On turn 1: the picks my list lost and what they
3
+ // show. Each turn: each opponent's estimated income and its basis, my planned deploys and attacks, what I ask of
4
+ // my teammates, what I could give them, the card I intend to play, and the conflicts between my plan and the
5
+ // orders they have entered. The agent words it and sends it with warapp_send_chat (channel: "team").
6
+ //
7
+ // Read-only: it plans as warapp_plan_turn would (livePlanSetup, award not read and not written) and writes
8
+ // nothing — no board cache, no award, no outlook. UNVERIFIED live: the teams (V1, via resolveTeams), the
9
+ // teammates' entered orders (V5) and picks (V5/V6), what a move onto a teammate does (V7) and how the team hand
10
+ // is keyed (V8). The pure parts are src/analysis/team-brief.ts.
11
+ import { McpToolError } from '@chrischall/mcp-utils';
12
+ import { z } from 'zod';
13
+ import { readAward } from '../analysis/award.js';
14
+ import { planEnemyEstimates, planTurn } from '../analysis/planner.js';
15
+ import { briefAsks, briefConflicts, opponentIncomes, pickOverlap, picksLost } from '../analysis/team-brief.js';
16
+ import { advisedOrderPriority } from '../cards.js';
17
+ import { parseGameId } from '../client.js';
18
+ import { boardStateFromLive } from '../live.js';
19
+ import { readPickRecord } from '../pick-list.js';
20
+ import { withTeammateOrders } from '../team-orders.js';
21
+ import { carriesTeam, teammatesOf } from '../teams.js';
22
+ import { gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText } from './common.js';
23
+ import { lookupMeta } from './hints.js';
24
+ import { loadLiveGame, loadPicks } from './live-context.js';
25
+ import { BRIDGE_NOTE } from './live.js';
26
+ import { mapOf } from './map.js';
27
+ import { readTeammatePicks } from './team.js';
28
+ import { resolveTeamsFor } from './team-source.js';
29
+ import { boardHistory, currentTurn, livePlanSetup, requirePlayingSeat } from './turn.js';
30
+ import { accountUnknown } from './write-kit.js';
31
+ const DISTRIBUTING = 'DistributingTerritories';
32
+ const PLAYING = 'Playing';
33
+ /** What every brief says about itself. */
34
+ export const BRIEF_NOTES = [
35
+ 'Data for a team-chat message, never sent: word it and send it with warapp_send_chat (channel: "team"). ' +
36
+ 'In a team everything true and concrete is shared; promise only what the plan does.',
37
+ "Teams come from GameFeed, else your game list (unverified, V1). Your teammates' entered orders and picks are read " +
38
+ 'from the live board (UNVERIFIED live, V5; picks fall back to GetTerritoryPicks, V6): none read means unknown, so ' +
39
+ 'no conflict can be named — not "no conflict".',
40
+ 'What a plain move onto a teammate\'s territory does is unverified (V7): every ask to move armies onto one is advice ' +
41
+ "to your teammate, never an order of yours, and warapp_plan_turn never puts one in `orders`.",
42
+ ];
43
+ const CONFLICT_NOTE = "`same-target`: you both attack it — whichever lands second moves onto your teammate's territory (V7), so one of " +
44
+ 'you should switch, unless it is a joint capture (`joint`); `bonus`: their attack takes a member of a bonus your plan ' +
45
+ 'completes (`completes`) or captures into (a bonus pays one holder: agree who takes it); `attacks-me`: an order of theirs attacks your territory; `onto-mine`: a plain ' +
46
+ 'order of theirs moves onto your territory (what it does is V7).';
47
+ const PICKS_LOST_NOTE = 'Each pick ranked above one you were granted went to another player first: `teammate` when the first board showed it ' +
48
+ "as your teammate's, `opponent` otherwise (a fogged one could still be your teammate's: team vision is unverified). " +
49
+ 'An opponent start says where they are.';
50
+ export function registerTeamBriefTool(server, ctx) {
51
+ server.registerTool('warapp_team_brief', {
52
+ title: 'Brief my teammates in a war.app team game',
53
+ description: untrustedDescription('The facts for a team-chat message in a war.app (Warzone) team game, by stage, as data — it sends nothing. ' +
54
+ "While picking: your pick list and its overlap with each teammate's (the same picks with both positions, and " +
55
+ 'the bonuses you both pick into). On turn 1: the picks your list lost and to whom (teammate or opponent, from ' +
56
+ 'your kept pick list and the first board). Each turn: each opponent\'s estimated income and its basis, your ' +
57
+ "planned deploys and attacks (warapp_plan_turn's plan, profile goal), what you ask of your teammates (keep a " +
58
+ 'joint attack, cover a border you concede), what you could give them (a border of theirs your idle armies would ' +
59
+ 'hold), the card you intend to play and the cards left to them, and the conflicts with the orders they have ' +
60
+ 'entered (a target you both attack, a bonus you complete or capture into, an order onto your territory). Word it and send it with ' +
61
+ 'warapp_send_chat (channel: "team"). Teammate orders and picks are read from the client\'s own structures and are ' +
62
+ `UNVERIFIED live. Refuses outside a team game. ${BRIDGE_NOTE} Read-only: writes nothing.`),
63
+ _meta: lookupMeta(['team brief', 'brief my teammate', 'what to tell my teammate', 'team chat message', 'coordinate with my team']),
64
+ annotations: readAnnotations('Brief my war.app team'),
65
+ inputSchema: z.object({ game_id: gameIdArg }),
66
+ }, async ({ game_id }) => {
67
+ const gameId = parseGameId(game_id);
68
+ const identity = await ctx.myIdentity().catch(() => undefined);
69
+ if (!identity)
70
+ throw accountUnknown(ctx.hosted, 'your team brief cannot be read');
71
+ const feed = await ctx.client.getGame(gameId, { settings: true });
72
+ if (feed.state !== PLAYING && feed.state !== DISTRIBUTING) {
73
+ throw new McpToolError(`Game ${feed.id} is not being picked or played (game state: ${feed.state}), so there is nothing to brief.`, {
74
+ hint: 'A brief is for a game in progress: picking territories or playing turns.',
75
+ });
76
+ }
77
+ const seat = feed.players.find((p) => p.id === identity.token);
78
+ if (!seat) {
79
+ throw new McpToolError(`The signed-in war.app account is not a player in game ${feed.id}.`, {
80
+ hint: 'Check the game id with warapp_my_games.',
81
+ });
82
+ }
83
+ requirePlayingSeat(feed, seat);
84
+ // The teams, after the seat refusals: GameFeed's, else the game list's (asked once per game, kept).
85
+ const { game, me, source, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
86
+ if (source === 'none' || !carriesTeam(me.team)) {
87
+ throw new McpToolError(`Game ${game.id} is not a team game, or your team there is unknown.`, {
88
+ hint: "GameFeed's team field is unverified and your game list did not name a team either. warapp_get_team reads the team.",
89
+ });
90
+ }
91
+ const mates = teammatesOf(game.players, me);
92
+ const allies = new Set(mates.map((p) => p.id));
93
+ const map = mapOf(game);
94
+ const graph = graphOf(map);
95
+ const name = namer(map);
96
+ const bonusRef = (id) => {
97
+ const b = map.bonuses.find((x) => x.id === id);
98
+ return { id, name: b?.name ?? String(id), value: b?.value ?? null };
99
+ };
100
+ const playerRef = (id) => {
101
+ const p = game.players.find((x) => x.id === id);
102
+ return { id, name: p ? untrustedText(p.name) : null };
103
+ };
104
+ const who = (id) => (id === me.id ? 'me' : playerRef(id));
105
+ const head = {
106
+ game: { id: game.id, state: game.state, turn: currentTurn(game) },
107
+ team: { id: me.team, source },
108
+ me: { id: me.id, name: untrustedText(me.name) },
109
+ teammates: mates.map((p) => ({
110
+ ...playerRef(p.id),
111
+ kind: p.isAI || p.humanTurnedIntoAI ? 'ai' : 'human',
112
+ committed: p.hasCommittedOrders,
113
+ })),
114
+ };
115
+ if (game.state === DISTRIBUTING) {
116
+ const { territories, info } = await loadLiveGame(ctx, game);
117
+ const board = withTeammateOrders(boardStateFromLive(territories, me, game.players), info, me, game.players);
118
+ const mine = await loadPicks(ctx, game.id, identity.inGameId).catch(() => null);
119
+ const lists = [];
120
+ for (const p of mates) {
121
+ const entry = board.teammateOrders?.find((e) => e.playerId === p.id);
122
+ const read = await readTeammatePicks(ctx, game.id, p, entry);
123
+ lists.push({ player: p.id, list: read?.territories ?? null, source: read?.source ?? null });
124
+ }
125
+ const o = pickOverlap(graph, mine ?? [], lists);
126
+ return respond(undefined, ['compact'], () => ({
127
+ ...head,
128
+ stage: 'picks',
129
+ picks: {
130
+ mine: mine === null ? null : mine.map(name),
131
+ teammates: lists.map((l) => ({ player: playerRef(l.player), list: l.list === null ? null : l.list.map(name), source: l.source })),
132
+ overlap: o.overlap.map((x) => ({ territory: name(x.territory), mine: x.mine, teammate: playerRef(x.teammate), theirs: x.theirs })),
133
+ sharedBonuses: o.sharedBonuses.map((b) => ({ bonus: bonusRef(b.bonus), mine: b.mine.map(name), teammate: playerRef(b.teammate), theirs: b.theirs.map(name) })),
134
+ ...(mine === null ? { note: 'Your own list could not be read: warapp_get_my_picks.' } : !mine.length ? { note: 'You have no picks entered yet: warapp_plan_picks, then warapp_submit_picks.' } : {}),
135
+ },
136
+ notes: BRIEF_NOTES,
137
+ }));
138
+ }
139
+ const turn = currentTurn(game);
140
+ const [{ territories, info }, history] = await Promise.all([loadLiveGame(ctx, game), boardHistory(ctx, game, me, turn)]);
141
+ // award: false — reading the award on turn 1 writes it, and a team plan does not use it (two players only).
142
+ const setup = await livePlanSetup(ctx, { game, map, me, turn, territories, info, history, award: false, teamsKnown });
143
+ const plan = planTurn(setup.input);
144
+ const { estimates } = planEnemyEstimates({
145
+ graph,
146
+ board: setup.board,
147
+ me: me.id,
148
+ income: setup.income - setup.cards.extraArmies,
149
+ settings: setup.settings,
150
+ ...(setup.trend ? { previousBoard: setup.trend.board } : {}),
151
+ ...(setup.trend && setup.previousOrders ? { previousOrders: setup.previousOrders } : {}),
152
+ ...(setup.tracks ? { tracks: setup.tracks } : {}),
153
+ game: setup.gameContext,
154
+ turn,
155
+ });
156
+ const foes = game.players.filter((p) => p.id !== me.id && !allies.has(p.id) && (p.state ?? PLAYING) === PLAYING).map((p) => p.id);
157
+ const joint = plan.team?.jointCaptures ?? [];
158
+ const conflicts = briefConflicts({
159
+ g: graph,
160
+ board: setup.seen,
161
+ me: me.id,
162
+ allies,
163
+ moves: plan.moves,
164
+ bonusesCompleted: plan.expected.bonusesCompleted,
165
+ joint: new Set(joint.map((j) => j.target)),
166
+ });
167
+ const asks = briefAsks({
168
+ g: graph,
169
+ board: setup.seen,
170
+ allies,
171
+ conceded: plan.conceded,
172
+ jointCaptures: joint.map((j) => ({
173
+ target: j.target,
174
+ teammates: [...new Set(j.teammate.map((x) => x.player))],
175
+ ...(j.mustGoFirst !== undefined ? { mustGoFirst: j.mustGoFirst } : {}),
176
+ })),
177
+ });
178
+ const advised = plan.cardAdvice === 'order-priority' ? advisedOrderPriority(setup.myCards, setup.cards) : undefined;
179
+ const plays = advised ? [...setup.cards.plays, advised] : setup.cards.plays;
180
+ const cardRef = (c) => ({ id: c.id, type: c.name, ...(c.armies !== undefined ? { armies: c.armies } : {}) });
181
+ const read = (setup.seen.teammateOrders ?? []).filter((e) => allies.has(e.playerId) && e.orders).map((e) => e.playerId);
182
+ const lost = turn === 1 ? await firstTurnPicks(ctx, game, me, setup.seen) : undefined;
183
+ return respond(undefined, ['compact'], () => ({
184
+ ...head,
185
+ stage: 'turn',
186
+ // Turn 1 only: what the award of my picks showed.
187
+ ...(lost !== undefined
188
+ ? {
189
+ picks: lost === null
190
+ ? { lost: null, note: 'No pick list of yours is kept for this game (warapp_submit_picks keeps it), or it does not explain your start.' }
191
+ : {
192
+ granted: lost.granted.map(name),
193
+ lost: lost.lost.map((x) => ({ territory: name(x.territory), rank: x.rank, by: x.by })),
194
+ ...(lost.unlisted.length ? { unlisted: lost.unlisted.map(name) } : {}),
195
+ note: PICKS_LOST_NOTE,
196
+ },
197
+ }
198
+ : {}),
199
+ opponents: opponentIncomes(estimates, foes).map((o) => ({ ...o, player: playerRef(o.player) })),
200
+ income: setup.income,
201
+ goal: plan.goal,
202
+ deploys: plan.deploys.map((d) => ({ territory: name(d.territoryId), armies: d.armies })),
203
+ attacks: plan.moves
204
+ .filter((m) => m.kind === 'attack')
205
+ .map((m) => ({
206
+ from: name(m.from),
207
+ to: name(m.to),
208
+ armies: m.armies,
209
+ ...(m.winChance !== undefined ? { winChance: Math.round(m.winChance * 1000) / 1000 } : {}),
210
+ })),
211
+ conceded: plan.conceded.map(name),
212
+ bonusesCompleted: plan.expected.bonusesCompleted.map(bonusRef),
213
+ asks: asks.map((a) => a.kind === 'joint-capture'
214
+ ? {
215
+ kind: a.kind,
216
+ target: name(a.target),
217
+ teammates: a.teammates.map(playerRef),
218
+ ...(a.mustGoFirst !== undefined ? { mustGoFirst: a.mustGoFirst === null ? 'either' : who(a.mustGoFirst) } : {}),
219
+ }
220
+ : { kind: a.kind, territory: name(a.territory), beside: a.beside.map((b) => ({ teammate: playerRef(b.teammate), territory: name(b.territory), armies: b.armies })) }),
221
+ offers: (plan.team?.support ?? []).map((s) => ({
222
+ territory: name(s.territory),
223
+ teammate: playerRef(s.teammate),
224
+ threat: s.threat,
225
+ from: playerRef(s.player),
226
+ need: s.need,
227
+ mine: s.from.map((f) => ({ territory: name(f.territory), armies: f.armies })),
228
+ })),
229
+ cards: {
230
+ play: plays.map(cardRef),
231
+ discard: setup.cards.discards.map(cardRef),
232
+ leftToTeammates: setup.teamClaimed.map((c) => ({ ...cardRef(c.card), teammate: playerRef(c.player), kind: c.kind })),
233
+ },
234
+ conflicts: {
235
+ // `null`: no teammate's orders were read, so conflicts are unknown.
236
+ read: read.length ? read.map(playerRef) : null,
237
+ list: conflicts.map((c) => c.kind === 'same-target'
238
+ ? { kind: c.kind, territory: name(c.territory), teammate: playerRef(c.teammate), mine: c.mine, theirs: c.theirs, joint: c.joint }
239
+ : c.kind === 'bonus'
240
+ ? { kind: c.kind, bonus: bonusRef(c.bonus), territory: name(c.territory), teammate: playerRef(c.teammate), completes: c.completes }
241
+ : { kind: c.kind, from: name(c.from), to: name(c.to), teammate: playerRef(c.teammate), armies: c.armies }),
242
+ note: CONFLICT_NOTE,
243
+ },
244
+ notes: BRIEF_NOTES,
245
+ }));
246
+ });
247
+ }
248
+ /**
249
+ * Turn 1: the picks my kept list lost, read from the first board (`readAward`, pure — this tool writes no award;
250
+ * warapp_plan_turn keeps it). `null` when no list is kept or it does not explain the start; `undefined` without a
251
+ * data directory. Never throws.
252
+ */
253
+ async function firstTurnPicks(ctx, game, me, board) {
254
+ if (!ctx.dataDir)
255
+ return undefined;
256
+ const record = await readPickRecord(ctx.dataDir, game.id, me.id).catch(() => undefined);
257
+ if (!record?.list)
258
+ return null;
259
+ let reading = record.award;
260
+ if (reading === undefined) {
261
+ const mates = new Set(teammatesOf(game.players, me).map((p) => p.id));
262
+ const held = (pred) => board.territories.filter((t) => t.owner.kind === 'player' && pred(t.owner.playerId)).map((t) => t.territoryId);
263
+ reading = readAward({ list: record.list, mine: held((o) => o === me.id), players: game.players.length, teammateHeld: held((o) => mates.has(o)) });
264
+ }
265
+ return reading ? picksLost(record.list, reading) : null;
266
+ }
@@ -0,0 +1,222 @@
1
+ // Where a game's teams come from (docs/PLAN-TEAMS.md, "Team source"). GameFeed's player `team` is
2
+ // UNVERIFIED live (V1); when no player in GameFeed's game carries one and the game has more than two
3
+ // seats, the team comes from GetMyGames' GameInfoPlayer (read from the client bundle, itself unverified
4
+ // live), matched by in-game id. Every tool that decides teams loads its game through `resolveTeams`, so
5
+ // they all agree.
6
+ //
7
+ // Trust: the list's answer is checked against GameFeed's seats before it is used (`judgeList`). Trusted
8
+ // are only an answer that gives every seat a team with at least two distinct teams among them, and one
9
+ // that lists every seat with no team at all (a free-for-all). Every seat on one team, or one team only
10
+ // among them, is not trusted (a misread team field would read that way): the teams stay unknown and
11
+ // nothing is kept, so the next call asks again. An answer that leaves a seat out, or gives some seats a
12
+ // team and others none, is incomplete: the teams stay unknown too.
13
+ //
14
+ // Cost: GetMyGames is asked at most once per game. A trusted answer — the game's in-game ids and team
15
+ // numbers, or that the game carries none — is kept at `<dataDir>/teams/<gameId>.json` (NAME-FREE: ids and
16
+ // team numbers only; 0600 in a 0700 folder, atomic, best effort, the newest MAX_TEAM_RECORDS kept), since
17
+ // a game's teams do not change once it has started. An incomplete answer keeps only a marker
18
+ // (`incompleteTurn`, GameFeed's numberOfTurns when it was read) and no teams, so a list that permanently
19
+ // leaves a seat out is asked at most once per turn, not on every call. A lobby's answer is used but never
20
+ // kept (a player who joins later would have no entry), and a kept record that lacks a seated player's
21
+ // in-game id is not trusted: the list is asked again. A failed GetMyGames read, or a list that does not
22
+ // hold the game, leaves the teams unknown (as GameFeed sent them) and is not kept: the next call asks again.
23
+ //
24
+ // Bump TEAM_RECORD_VERSION whenever the GameInfoPlayer team decode (`src/my-games.ts`) or the trust
25
+ // check changes: a record kept by another version is ignored, so a misread kept earlier is never reused.
26
+ import { readdir, readFile, stat, unlink } from 'node:fs/promises';
27
+ import { join } from 'node:path';
28
+ import { playersByInGameId } from '../live.js';
29
+ import { writeJsonAtomic } from '../map-store.js';
30
+ import { myGamesTeams } from '../my-games.js';
31
+ import { carriesTeam, isTeamGame } from '../teams.js';
32
+ import { fetchMyGames } from './my-games.js';
33
+ /** Team records kept; the least recently written goes first. */
34
+ export const MAX_TEAM_RECORDS = 200;
35
+ /** The kept record's version: bump it whenever the GameInfoPlayer team decode or the trust check changes. */
36
+ export const TEAM_RECORD_VERSION = 2;
37
+ const TEAM_FILE = /^\d+\.json$/;
38
+ export const teamsDir = (dir) => join(dir, 'teams');
39
+ export const teamRecordPath = (dir, gameId) => join(teamsDir(dir), `${gameId}.json`);
40
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
41
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
42
+ /** The kept record of `gameId`; `undefined` when none is kept, it is malformed or from another version. Never throws. */
43
+ export async function readTeamFile(dir, gameId) {
44
+ try {
45
+ const r = JSON.parse(await readFile(teamRecordPath(dir, gameId), 'utf8'));
46
+ if (!isRec(r) || r.version !== TEAM_RECORD_VERSION || r.gameId !== gameId)
47
+ return undefined;
48
+ if (!('teams' in r))
49
+ return isInt(r.incompleteTurn) ? { incompleteTurn: r.incompleteTurn } : undefined;
50
+ if (!Array.isArray(r.teams))
51
+ return undefined;
52
+ const out = new Map();
53
+ for (const e of r.teams) {
54
+ if (!Array.isArray(e) || e.length !== 2 || !isInt(e[0]) || !isInt(e[1]) || !carriesTeam(e[1]))
55
+ return undefined;
56
+ out.set(e[0], e[1]);
57
+ }
58
+ return { teams: out };
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
64
+ /** The kept teams of `gameId` (in-game id → team; empty: the game carries none); `undefined` when none is kept. Never throws. */
65
+ export async function readTeamRecord(dir, gameId) {
66
+ const r = await readTeamFile(dir, gameId);
67
+ return r && 'teams' in r ? r.teams : undefined;
68
+ }
69
+ async function pruneTeams(dir, keep) {
70
+ const folder = teamsDir(dir);
71
+ const files = [];
72
+ for (const name of await readdir(folder)) {
73
+ if (!TEAM_FILE.test(name) || name === `${keep}.json`)
74
+ continue;
75
+ try {
76
+ files.push({ name, at: (await stat(join(folder, name))).mtimeMs });
77
+ }
78
+ catch {
79
+ // Gone already.
80
+ }
81
+ }
82
+ const excess = files.length + 1 - MAX_TEAM_RECORDS;
83
+ if (excess <= 0)
84
+ return;
85
+ files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
86
+ for (const f of files.slice(0, excess))
87
+ await unlink(join(folder, f.name)).catch(() => { });
88
+ }
89
+ async function writeRecord(dir, gameId, body) {
90
+ try {
91
+ await writeJsonAtomic(teamRecordPath(dir, gameId), teamsDir(dir), { version: TEAM_RECORD_VERSION, gameId, ...body });
92
+ await pruneTeams(dir, gameId).catch(() => { });
93
+ }
94
+ catch {
95
+ // Not kept: the next call asks again.
96
+ }
97
+ }
98
+ /** Keep `gameId`'s teams (in-game id → team; empty: none). Best effort, never throws. */
99
+ export function writeTeamRecord(dir, gameId, teams) {
100
+ return writeRecord(dir, gameId, { teams: [...teams].sort((a, b) => a[0] - b[0]) });
101
+ }
102
+ /** Keep only that the list left a seat of `gameId` out on `turn` (no teams). Best effort, never throws. */
103
+ export function writeIncompleteMarker(dir, gameId, turn) {
104
+ return writeRecord(dir, gameId, { incompleteTurn: turn });
105
+ }
106
+ /** The game list; `undefined` when the read fails or the list does not hold the game. */
107
+ async function myGamesWith(ctx, gameId) {
108
+ try {
109
+ // The account first: an unknown one asks nothing (fetchMyGames reuses the cached answer).
110
+ if ((await ctx.myInGameId()) === undefined)
111
+ return undefined;
112
+ const { games } = await fetchMyGames(ctx);
113
+ return games.some((g) => g.id === gameId) ? games : undefined;
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ /**
120
+ * Judge the list's answer for `gameId` against the seats GameFeed shows (in-game ids): every seat listed
121
+ * without a team is a free-for-all; every seat with a team and two or more teams among them is trusted; a
122
+ * seat left out, or teams on some seats only, is incomplete; one team for every seat is not trusted.
123
+ */
124
+ export function judgeList(games, gameId, seats) {
125
+ const listed = new Set((games.find((g) => g.id === gameId)?.players ?? []).map((p) => p.id));
126
+ if (!seats.every((id) => listed.has(id)))
127
+ return { kind: 'incomplete' };
128
+ const teams = myGamesTeams(games, gameId);
129
+ const withTeam = seats.filter((id) => teams.has(id));
130
+ if (!withTeam.length)
131
+ return { kind: 'trusted', teams: new Map() };
132
+ if (withTeam.length < seats.length)
133
+ return { kind: 'incomplete' };
134
+ if (new Set(withTeam.map((id) => teams.get(id))).size < 2)
135
+ return { kind: 'untrusted' };
136
+ return { kind: 'trusted', teams };
137
+ }
138
+ /** GameFeed's state for a game still filling its seats. */
139
+ const LOBBY_STATE = 'WaitingForPlayers';
140
+ /** Whether a kept record names every seated player of `game` (an empty one — no teams — always does). */
141
+ function coversSeats(game, teams) {
142
+ if (!teams.size)
143
+ return true;
144
+ return [...playersByInGameId(game.players).keys()].every((id) => teams.has(id));
145
+ }
146
+ /** `game` with each player's team from `teams` (in-game id → team), for the players it can match. */
147
+ function withTeams(game, teams) {
148
+ if (!teams.size)
149
+ return undefined;
150
+ const byInGame = playersByInGameId(game.players);
151
+ const teamOf = new Map();
152
+ for (const [inGame, team] of teams) {
153
+ const p = byInGame.get(inGame);
154
+ if (p)
155
+ teamOf.set(p.id, team);
156
+ }
157
+ const players = game.players.map((p) => (teamOf.has(p.id) ? { ...p, team: teamOf.get(p.id) } : p));
158
+ return isTeamGame(players) ? { ...game, players } : undefined;
159
+ }
160
+ /**
161
+ * The game with each player's team, and where the teams came from. GameFeed's when any player carries
162
+ * one (`gamefeed`); else, in a game of more than two seats, GetMyGames' — from the per-game record when
163
+ * kept, else asked once, judged against the seats and kept when trusted (`my-games`); else the game as
164
+ * GameFeed sent it (`none`). Never throws.
165
+ */
166
+ export async function resolveTeams(ctx, game) {
167
+ // A team on some seats but not all (GameFeed's team field is unverified): a seat without one may be
168
+ // my teammate, so the teams are not known.
169
+ if (isTeamGame(game.players))
170
+ return { game, source: 'gamefeed', known: game.players.every((p) => carriesTeam(p.team)) };
171
+ if (game.players.length <= 2)
172
+ return { game, source: 'none', known: true };
173
+ const none = { game, source: 'none', known: false };
174
+ const kept = ctx.dataDir ? await readTeamFile(ctx.dataDir, game.id) : undefined;
175
+ const turn = game.numberOfTurns;
176
+ // The list left a seat out on this turn already: not asked again until the next.
177
+ if (kept && 'incompleteTurn' in kept && turn !== undefined && kept.incompleteTurn === turn)
178
+ return none;
179
+ let teams = kept && 'teams' in kept && coversSeats(game, kept.teams) ? kept.teams : undefined;
180
+ if (!teams) {
181
+ const games = await myGamesWith(ctx, game.id);
182
+ if (!games)
183
+ return none;
184
+ const verdict = judgeList(games, game.id, [...playersByInGameId(game.players).keys()]);
185
+ // Kept only once the seats are settled: a lobby can still fill.
186
+ const keep = ctx.dataDir && game.state !== LOBBY_STATE ? ctx.dataDir : undefined;
187
+ if (verdict.kind === 'incomplete' && keep && turn !== undefined)
188
+ await writeIncompleteMarker(keep, game.id, turn);
189
+ if (verdict.kind !== 'trusted')
190
+ return none;
191
+ teams = verdict.teams;
192
+ if (keep)
193
+ await writeTeamRecord(keep, game.id, teams);
194
+ }
195
+ const resolved = withTeams(game, teams);
196
+ // A trusted list with no team on any seat: a free-for-all, known.
197
+ return resolved ? { game: resolved, source: 'my-games', known: true } : { ...none, known: !teams.size };
198
+ }
199
+ /**
200
+ * The teams of `game` as far as they are known without asking anything (#264's backfill of a finished
201
+ * game reads no game list): GameFeed's, two seats or fewer, or the record kept at `<dataDir>/teams`
202
+ * when it covers every seat; else `known: false`. Never throws.
203
+ */
204
+ export async function keptTeams(dataDir, game) {
205
+ if (isTeamGame(game.players))
206
+ return { game, source: 'gamefeed', known: game.players.every((p) => carriesTeam(p.team)) };
207
+ if (game.players.length <= 2)
208
+ return { game, source: 'none', known: true };
209
+ const teams = dataDir ? await readTeamRecord(dataDir, game.id) : undefined;
210
+ if (!teams || !coversSeats(game, teams))
211
+ return { game, source: 'none', known: false };
212
+ const resolved = withTeams(game, teams);
213
+ return resolved ? { game: resolved, source: 'my-games', known: true } : { game, source: 'none', known: !teams.size };
214
+ }
215
+ /**
216
+ * {@link resolveTeams} for a tool that has already found my seat (and refused a seat it refuses, so
217
+ * that refusal asks no game list): the game, the source, and my seat in the resolved game.
218
+ */
219
+ export async function resolveTeamsFor(ctx, game, me) {
220
+ const r = await resolveTeams(ctx, game);
221
+ return { ...r, me: r.game.players.find((p) => p.id === me.id) ?? me };
222
+ }