@chrischall/warapp-mcp 0.0.0 → 0.2.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,305 @@
1
+ // Pick advisor tool (docs/PLAN-PICKS.md, K2): rank the pickable territories of a
2
+ // manual-distribution game from the map, the settings and the live board.
3
+ // Read-only — the owner submits the list with warapp_submit_picks.
4
+ import { McpToolError } from '@chrischall/mcp-utils';
5
+ import { z } from 'zod';
6
+ import { clientPickLimits, planPicks } from '../analysis/picks.js';
7
+ import { DEFAULT_TERRITORY_LIMIT } from '../analysis/opponents.js';
8
+ import { OWNER_PICKABLE } from '../live.js';
9
+ import { bonusNamer, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
10
+ import { lookupMeta } from './hints.js';
11
+ import { loadLiveGame } from './live-context.js';
12
+ import { BRIDGE_NOTE, resolveMe } from './live.js';
13
+ import { isTeamGame, teammatesOf } from '../teams.js';
14
+ import { teammateOrdersOf } from '../team-orders.js';
15
+ import { readTeammatePicks } from './team.js';
16
+ import { pickingNeutrals } from '../pick-list.js';
17
+ import { mapOf } from './map.js';
18
+ import { mapRecordFor, mapRecordView } from './past-games.js';
19
+ import { keepPickable } from './where.js';
20
+ import { resolveTeams } from './team-source.js';
21
+ const VIEWS = ['compact', 'full'];
22
+ /** The only GameFeed state in which territories are picked. */
23
+ export const PICK_PHASE_STATE = 'DistributingTerritories';
24
+ /** TerritoryLimit assumed when the settings do not say (war.app's usual default; shared with the outlook). */
25
+ export { DEFAULT_TERRITORY_LIMIT };
26
+ /** The pick scorer's view of the game settings. */
27
+ export function pickSettings(s) {
28
+ if (!s)
29
+ return {};
30
+ const keys = [
31
+ 'offensiveKillRate',
32
+ 'defensiveKillRate',
33
+ 'luckModifier',
34
+ 'roundingMode',
35
+ 'oneArmyStandsGuard',
36
+ 'minimumArmyBonus',
37
+ 'bonusArmyPer',
38
+ 'localDeployments',
39
+ 'initialPlayerArmiesPerTerritory',
40
+ 'initialNonDistributionArmies',
41
+ 'initialNeutralsInDistribution',
42
+ 'commanders',
43
+ 'noSplit',
44
+ ];
45
+ const out = {};
46
+ for (const k of keys)
47
+ if (s[k] !== undefined)
48
+ out[k] = s[k];
49
+ return out;
50
+ }
51
+ /** Throw unless territories are being picked. */
52
+ function requirePickPhase(game) {
53
+ if (game.state === PICK_PHASE_STATE)
54
+ return;
55
+ throw new McpToolError(`Game ${game.id} is not in the picking stage (game state: ${game.state}).`, {
56
+ hint: game.state === 'Playing'
57
+ ? 'Picks are over: plan the turn with warapp_plan_turn.'
58
+ : 'Picks are planned only while a manual-distribution game distributes territories.',
59
+ });
60
+ }
61
+ /**
62
+ * My playing teammates in a team game (C2); none, with a warning, when my seat cannot be told — then
63
+ * every other player is treated as an opponent (the worst case). Never throws.
64
+ */
65
+ async function teamOf(ctx, game, warnings) {
66
+ try {
67
+ const me = await resolveMe(ctx, game.players, undefined);
68
+ return teammatesOf(game.players, me).filter((p) => (p.state ?? 'Playing') === 'Playing');
69
+ }
70
+ catch {
71
+ warnings.push("Could not tell which seat is yours in this team game: every other player is treated as an opponent.");
72
+ return [];
73
+ }
74
+ }
75
+ /** What the coordination block says about where a teammate's list comes from (C2). */
76
+ const TEAM_LIST_NOTES = [
77
+ "A teammate's list is read from the live board's TeammateOrders (client bundle, UNVERIFIED live, V5), else from " +
78
+ "GetTerritoryPicks with the teammate's id (UNVERIFIED, V6); a list that cannot be read is unknown, and the plan is then " +
79
+ 'the one made without it.',
80
+ "The award order of a team game is UNVERIFIED: the mirrored list is laid out for a reversing order, and `splits` names " +
81
+ 'the bonuses a repeating order would split between you. Agree a list in team chat before relying on it.',
82
+ ];
83
+ export function registerPickTools(server, ctx, deps = {}) {
84
+ server.registerTool('warapp_plan_picks', {
85
+ title: 'Plan my territory picks in a war.app game',
86
+ description: untrustedDescription('Rank the pickable territories of a war.app (Warzone) game in manual distribution, from the map, the ' +
87
+ "game's settings (starting armies, neutral sizes, kill rates, base income) and the live board's " +
88
+ 'pickable territories: a list in priority order by name and id, split into a primary group ' +
89
+ '(the territory limit: what you are granted if nobody takes them first; one compact cluster, a 1v1 included, ' +
90
+ 'with maxHops between its two farthest picks) and a disjoint fallback group ' +
91
+ '(granted in order when another player picked first; in a two-player game with 2 to 4 picks each, every fallback pick ' +
92
+ 'answers the loss that grants it: its own opening, less half the opponent\'s from the picks then lost), each pick with its ' +
93
+ 'score and reasons (bonus, value, turns to complete, first-turn bonus, entry points and which are a double border, ' +
94
+ 'which other pickable territories can reach the bonus in time, contested), the bonuses each group completes with their ' +
95
+ '`threats` (the pickable territories outside the group that can reach each by the turn after it completes), ' +
96
+ '`twoOrderCaptures` (neutrals its opening takes with two attacks because one cannot be paid for), ' +
97
+ 'the award (how many sets the round-by-round award order can grant from the list, and the worst of them with the ' +
98
+ 'other players\' starts it implies), ' +
99
+ 'warnings (assumed settings) and the reasoning. The primary group carries its `coverage`: the share of reasonable bonuses ' +
100
+ '(positive, with a pickable territory, no wasteland, value per army at least the median) a pick can stand next to within 2 moves, ' +
101
+ 'and the ones it cannot, by name. In a two-player game without spread it may also return an `alternative`: a coverage-first list ' +
102
+ '(a pair, then the picks that most widen that reach) with its score, coverage and its own `submitPicks`, present only when it covers more. ' +
103
+ 'Prefer the compact primary by default; offer the alternative on a small board, when knowing where the opponent is and keeping a ' +
104
+ 'way into every region matter more than the fastest start — the user chooses per game. ' +
105
+ 'Its `submitPicks` is exactly what warapp_submit_picks ' +
106
+ 'takes — review it with the user first. Refuses outside the picking stage or when nothing is pickable. ' +
107
+ 'In a team game only the players off your team are threats, `team` names your teammates, and the list is judged by both award ' +
108
+ "orders that fit (`award.orders`; a team game's is unverified). When a teammate's pick list can be read (unverified), each " +
109
+ "teammate carries `picks`, and `team.coordination` reports the overlap with your list, the bonuses their top picks into " +
110
+ '(a bonus pays one holder, so yours there are not credited), and a `mirrored` alternative (the same top picks in both ' +
111
+ 'lists, with its own submitPicks) beside the split list that `submitPicks` gives — which leaves their top picks to them ' +
112
+ 'and is shortened only when disjoint from their full-length list. ' +
113
+ 'When you have finished games on this map, `mapRecord` reports them (reported only, never ranked on): games and results, ' +
114
+ 'your results by each bonus your start touched (`inPrimary` when this primary touches it too), the bonuses winners started in, ' +
115
+ 'and the pace — the median income after turns 4 and 8 of the winners and of you. ' +
116
+ `${BRIDGE_NOTE} Read-only on war.app; it never submits picks.`),
117
+ _meta: lookupMeta(['plan my picks', 'which territories to pick', 'suggest picks', 'warzone picks']),
118
+ annotations: readAnnotations('Plan war.app picks'),
119
+ inputSchema: z.object({
120
+ game_id: gameIdArg,
121
+ view: viewArg(VIEWS, 'compact (default) gives the ranked picks with reasons, the groups and submitPicks (and the first start bonuses of `mapRecord`); "full" adds the settings the plan assumed and every start bonus.'),
122
+ spread: z
123
+ .boolean()
124
+ .optional()
125
+ .describe('In a 1v1, spread the primary across bonuses against a counter-pick instead of one compact cluster ' +
126
+ '(default false); usually worse on large maps. Ignored with three or more players.'),
127
+ }),
128
+ }, async ({ game_id, view, spread }) => {
129
+ const feed = await ctx.client.getGame(game_id, { settings: true });
130
+ requirePickPhase(feed);
131
+ const { territories, info } = await loadLiveGame(ctx, feed);
132
+ const pickable = territories.filter((t) => !t.fogged && t.owner === OWNER_PICKABLE).map((t) => t.territoryId);
133
+ if (!pickable.length) {
134
+ throw new McpToolError(`The live board of game ${feed.id} has no pickable territories.`, {
135
+ hint: 'Check warapp_get_live_board: picks may already be closed, or this game distributes territories automatically.',
136
+ });
137
+ }
138
+ const neutralArmies = new Map(pickingNeutrals(territories));
139
+ // Kept for the turns to come: where a player could have started (warapp_locate_opponents), and
140
+ // (#201) the neutrals' sizes, which the fog may hide later (wastelands).
141
+ await keepPickable(ctx, feed, pickable, [...neutralArmies]);
142
+ // The teams, after the refusals: GameFeed's, else the game list's (asked once per game, kept).
143
+ const { game, source: teamSource } = await resolveTeams(ctx, feed);
144
+ const map = mapOf(game);
145
+ const warnings = [];
146
+ let territoryLimit = game.settings?.territoryLimit;
147
+ if (territoryLimit === undefined || territoryLimit <= 0) {
148
+ territoryLimit = DEFAULT_TERRITORY_LIMIT;
149
+ warnings.push(`Territory limit missing from settings; assumed ${DEFAULT_TERRITORY_LIMIT}.`);
150
+ }
151
+ // The list is as long as war.app's client allows (players × territories per player, #129),
152
+ // never shorter than the primary.
153
+ const maxPicks = Math.max(territoryLimit, clientPickLimits({ territoryLimit, players: game.players.length, pickable: pickable.length })?.max ?? 0);
154
+ const active = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length;
155
+ const players = Math.max(2, active || game.players.length);
156
+ const settings = pickSettings(game.settings);
157
+ // A team game (C2): only the players off my team are opponents. My seat is looked up only here.
158
+ const team = isTeamGame(game.players) ? await teamOf(ctx, game, warnings) : undefined;
159
+ // My teammates' lists (C2, coordination): the teammate orders first, then GetTerritoryPicks.
160
+ const mateLists = [];
161
+ if (team?.length) {
162
+ const entries = teammateOrdersOf(info, game.players);
163
+ for (const mate of team)
164
+ mateLists.push(await readTeammatePicks(ctx, game.id, mate, entries?.find((e) => e.playerId === mate.id)));
165
+ }
166
+ const lists = mateLists.map((l) => l?.territories ?? []);
167
+ const plan = planPicks({
168
+ graph: graphOf(map),
169
+ pickable,
170
+ settings,
171
+ players,
172
+ territoryLimit,
173
+ maxPicks,
174
+ neutralArmies,
175
+ spread: spread === true,
176
+ ...(team ? { team: { teammates: team.length, ...(lists.some((l) => l.length) ? { lists } : {}) } } : {}),
177
+ });
178
+ const name = namer(map);
179
+ const bonusName = bonusNamer(map);
180
+ const coord = plan.team;
181
+ const groupView = (g) => ({
182
+ territories: g.territoryIds.map(name),
183
+ score: g.score,
184
+ maxHops: g.maxHops,
185
+ bonuses: g.bonuses.map((b) => ({
186
+ id: b.bonusId,
187
+ name: b.name,
188
+ value: b.value,
189
+ turn: b.turn,
190
+ threats: b.threats.map(name),
191
+ })),
192
+ twoOrderCaptures: g.twoOrderCaptures.map((c) => ({
193
+ turn: c.turn,
194
+ territory: name(c.territoryId),
195
+ orders: c.orders.map((o) => ({ from: name(o.from), armies: o.armies })),
196
+ })),
197
+ });
198
+ const coverageView = (c) => ({
199
+ share: c.share,
200
+ covered: c.covered,
201
+ reasonable: c.reasonable,
202
+ uncovered: c.uncovered.map((b) => ({ id: b.bonusId, name: b.name })),
203
+ });
204
+ const alt = plan.alternative;
205
+ // #312 E3: what my finished games on this map say (reported only: the ranking above never reads it).
206
+ const record = await mapRecordFor(ctx.dataDir, deps.env, game.settings?.mapId);
207
+ return respond(view, VIEWS, (rung) => ({
208
+ game: { id: game.id, name: game.name ?? null, state: game.state },
209
+ players,
210
+ territoryLimit,
211
+ maxPicks,
212
+ ...(team
213
+ ? {
214
+ team: {
215
+ teammates: team.map((p, i) => {
216
+ const read = mateLists[i];
217
+ return {
218
+ id: p.id,
219
+ name: untrustedText(p.name),
220
+ picks: read ? { source: read.source, territories: read.territories.map(name) } : null,
221
+ };
222
+ }),
223
+ opponents: Math.max(0, players - 1 - team.length),
224
+ source: teamSource,
225
+ ...(coord
226
+ ? {
227
+ coordination: {
228
+ theirTop: coord.tops.map((t) => t.map(name)),
229
+ overlap: coord.overlap.map((o) => ({
230
+ territory: name(o.territoryId),
231
+ mine: o.mine,
232
+ theirs: o.theirs,
233
+ teammate: team[o.teammate]?.id ?? null,
234
+ })),
235
+ sharedBonuses: coord.sharedBonuses.map((b) => ({
236
+ bonus: bonusName(b.bonusId),
237
+ mine: b.mine.map(name),
238
+ theirs: b.theirs.map(name),
239
+ })),
240
+ ...(coord.shortened ? { shortened: coord.shortened } : {}),
241
+ mirrored: coord.mirrored
242
+ ? {
243
+ territories: coord.mirrored.top.map(name),
244
+ hands: coord.mirrored.hands.map((h) => h.map(name)),
245
+ splits: coord.mirrored.splits.map((x) => ({
246
+ order: x.order,
247
+ bonuses: x.bonuses.map((b) => ({ ...bonusName(b.bonusId), territories: b.picks.map(name) })),
248
+ })),
249
+ submitPicks: { game_id: game.id, territories: coord.mirrored.submitPicks },
250
+ }
251
+ : null,
252
+ notes: TEAM_LIST_NOTES,
253
+ },
254
+ }
255
+ : {}),
256
+ },
257
+ }
258
+ : {}),
259
+ picks: plan.picks.map((p, i) => ({
260
+ priority: i + 1,
261
+ territory: name(p.territoryId),
262
+ group: p.group,
263
+ score: p.score,
264
+ reasons: p.reasons,
265
+ })),
266
+ groups: {
267
+ primary: { ...groupView(plan.groups.primary), coverage: coverageView(plan.coverage) },
268
+ fallback: groupView(plan.groups.fallback),
269
+ },
270
+ award: plan.award
271
+ ? {
272
+ outcomes: plan.award.outcomes,
273
+ ...(plan.award.orders ? { orders: plan.award.orders } : {}),
274
+ worst: {
275
+ territories: plan.award.worst.territoryIds.map(name),
276
+ score: plan.award.worst.score,
277
+ opponentStarts: plan.award.worst.opponentStarts.map(name),
278
+ },
279
+ reordered: plan.award.reordered,
280
+ }
281
+ : null,
282
+ warnings: [...warnings, ...plan.warnings],
283
+ rationale: plan.rationale,
284
+ submitPicks: { game_id: game.id, territories: plan.picks.map((p) => p.territoryId) },
285
+ ...(alt
286
+ ? {
287
+ alternative: {
288
+ ...groupView(alt.group),
289
+ coverage: coverageView(alt.coverage),
290
+ fallback: alt.fallback.map(name),
291
+ submitPicks: { game_id: game.id, territories: alt.submitPicks },
292
+ },
293
+ }
294
+ : {}),
295
+ ...(record
296
+ ? {
297
+ mapRecord: record === 'unreadable'
298
+ ? record
299
+ : mapRecordView(record, { bonusName, full: rung === 'full', graph: graphOf(map), picks: plan.groups.primary.territoryIds }),
300
+ }
301
+ : {}),
302
+ ...(rung === 'full' ? { settings } : {}),
303
+ }));
304
+ });
305
+ }
@@ -0,0 +1,156 @@
1
+ // The opponent-profile hook (docs/PLAN-PROFILES.md A2): every tool that caches a board calls
2
+ // `recordProfile` right after `writeBoardCache` (warapp_plan_turn never on a what-if plan), so the
3
+ // turns its boards show are observed and kept (src/profile-store.ts). Best effort, never throws.
4
+ // Its own module so src/tools/turn.ts can call it without importing the tool that imports turn.ts.
5
+ import { stat, utimes } from 'node:fs/promises';
6
+ import { foldFinishedGame, profileEnabled, profileFileState, profileGameFolded, profileGamePath, profileSeatsOf, readProfileTurns, recordBehaviour, } from '../profile-store.js';
7
+ import { teammatesOf } from '../teams.js';
8
+ import { boardCachePath, readBoardHistory, readCachedOrders, readCachedPlayer } from '../trend.js';
9
+ import { graphOf } from './common.js';
10
+ import { mapOf } from './map.js';
11
+ import { keptTeams } from './team-source.js';
12
+ /** The combat settings an observation reads, from the game's settings. */
13
+ export function observeSettings(game) {
14
+ const s = game.settings;
15
+ return {
16
+ ...(s?.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
17
+ ...(s?.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
18
+ ...(s?.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
19
+ ...(s?.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
20
+ ...(s?.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
21
+ ...(s?.multiAttack !== undefined ? { multiAttack: s.multiAttack } : {}),
22
+ };
23
+ }
24
+ /** The cards in play, when the game's settings were read (else any card may be: unstated). */
25
+ export function cardsInPlay(game) {
26
+ return game.settings ? { cards: game.settings.cards } : {};
27
+ }
28
+ /** My opponents in `game`: every other player but my teammates (teammates are never profiled). */
29
+ export function profiledOpponents(game, me) {
30
+ const friends = new Set(teammatesOf(game.players, me).map((p) => p.id));
31
+ return game.players
32
+ .filter((p) => p.id !== me.id && !friends.has(p.id))
33
+ .map((p) => p.id)
34
+ .sort((a, b) => a - b);
35
+ }
36
+ /**
37
+ * The hook after each board-cache write (A2): observe `boards` (my history plus the board just read,
38
+ * my orders attached) and store each turn. Nothing without a data directory, with
39
+ * `WARAPP_PLAYER_PROFILE=off`, or while `teamsKnown` is false (`resolveTeams`' `known`: a game of
40
+ * more than two seats whose teams could not be read, where any player may be my teammate, and
41
+ * teammates are never profiled). Each write also drops what the file holds for my known teammates.
42
+ * Never throws.
43
+ */
44
+ export async function recordProfile(dataDir, env, game, me, boards, teamsKnown) {
45
+ if (!dataDir || !teamsKnown)
46
+ return;
47
+ try {
48
+ await recordBehaviour(dataDir, {
49
+ gameId: game.id,
50
+ me: me.id,
51
+ graph: graphOf(mapOf(game)),
52
+ settings: observeSettings(game),
53
+ ...cardsInPlay(game),
54
+ opponents: profiledOpponents(game, me),
55
+ teammates: teammatesOf(game.players, me).map((p) => p.id),
56
+ boards,
57
+ // Kept for a fold by the age rule, when no read shows the game finished (B2).
58
+ seats: profileSeatsOf(game),
59
+ }, env ?? process.env);
60
+ }
61
+ catch {
62
+ // Best effort: profiling never blocks a tool.
63
+ }
64
+ }
65
+ /** The note on a finished game with nothing to fold (#264). */
66
+ export const NOTHING_TO_FOLD = 'Nothing of this game could be counted: counts start with games played on this build.';
67
+ /** The note on a fold that failed (`failed`): the turns may well be kept, and the next read tries again. */
68
+ export const FOLD_FAILED = "This game's turns could not be counted now (a profile store could not be read or written); the next read of the finished game tries again.";
69
+ /** The note when there is no data directory (`no-data-dir`): nothing is kept, so nothing is counted. */
70
+ export const NO_DATA_DIR = 'Nothing is kept without a data directory, so no game is counted.';
71
+ const GAP_NOTES = { failed: FOLD_FAILED, 'no-data-dir': NO_DATA_DIR };
72
+ /** The opponents and turns the per-game file of `game` holds as `me` saw it. */
73
+ async function foldedOpponents(dataDir, env, game, me) {
74
+ const turns = await readProfileTurns(dataDir, game.id, me, env);
75
+ const seated = new Set(game.players.map((p) => p.id));
76
+ return [...turns].filter(([id]) => seated.has(id)).map(([id, list]) => ({ id, turns: list.length })).sort((a, b) => a.id - b.id);
77
+ }
78
+ /**
79
+ * Fold a finished game into the cross-game record (B2, #264), with no request: the per-game file kept
80
+ * while it was played (`live`), else — a game that finished before profiles were kept, or was never
81
+ * planned on this build — a one-time **backfill**: the boards (and my orders) the board cache holds
82
+ * for it are observed now, kept in a per-game file marked `backfill`, and folded as `live`. Only for
83
+ * the account whose boards were cached (a game the account played), never a teammate (teams from
84
+ * GameFeed, two seats, or the kept team record: no game list is read, so unknown teams fold nothing),
85
+ * never twice (a per-game file already there, or the stores already holding the game, is
86
+ * `already-folded`). The backfilled file takes the board cache's age, so it is deleted when the board
87
+ * cache would be (no id-bearing file outlives it). Nothing with profiling off. A fold that fails
88
+ * (`failed`: an unreadable store, an error) and a missing data directory (`no-data-dir`) carry their
89
+ * own notes; every other gap says counts start with games played on this build. Never throws.
90
+ */
91
+ export async function foldFinished(dataDir, env, game) {
92
+ if (!profileEnabled(env))
93
+ return { status: 'off' };
94
+ const nothing = (reason) => ({ status: 'nothing', reason, note: GAP_NOTES[reason] ?? NOTHING_TO_FOLD });
95
+ if (!dataDir)
96
+ return nothing('no-data-dir');
97
+ try {
98
+ if (game.state !== 'Finished')
99
+ return nothing('not-finished');
100
+ const me = await readCachedPlayer(dataDir, game.id);
101
+ // A per-game file kept while it was played (any account of mine): the live fold.
102
+ const live = await foldFinishedGame(dataDir, game, env);
103
+ if (me === undefined)
104
+ return live ? { status: 'folded', source: 'live', opponents: [] } : nothing('no-boards');
105
+ if (live)
106
+ return { status: 'folded', source: 'live', opponents: await foldedOpponents(dataDir, env, game, me) };
107
+ const mine = game.players.find((p) => p.id === me);
108
+ if (!mine)
109
+ return nothing('not-a-player');
110
+ const state = await profileFileState(dataDir, game.id, me);
111
+ if (state === 'folded')
112
+ return { status: 'already-folded' };
113
+ // A file kept but not folded by the live fold just now: it failed; never backfilled over.
114
+ if (state === 'kept')
115
+ return nothing('failed');
116
+ if (await profileGameFolded(dataDir, me, game.id))
117
+ return { status: 'already-folded' };
118
+ const teams = await keptTeams(dataDir, game);
119
+ if (!teams.known)
120
+ return nothing('teams-unknown');
121
+ if (!game.map)
122
+ return nothing('no-map');
123
+ const resolved = teams.game;
124
+ const seat = resolved.players.find((p) => p.id === me) ?? mine;
125
+ const orders = await readCachedOrders(dataDir, game.id, me);
126
+ const boards = (await readBoardHistory(dataDir, game.id, me)).map((b) => {
127
+ const o = orders.get(b.turn);
128
+ return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
129
+ });
130
+ const kept = await recordBehaviour(dataDir, {
131
+ gameId: game.id,
132
+ me,
133
+ graph: graphOf(mapOf(resolved)),
134
+ settings: observeSettings(resolved),
135
+ ...cardsInPlay(resolved),
136
+ opponents: profiledOpponents(resolved, seat),
137
+ teammates: teammatesOf(resolved.players, seat).map((p) => p.id),
138
+ boards,
139
+ seats: profileSeatsOf(resolved),
140
+ backfill: true,
141
+ }, env);
142
+ if (!kept)
143
+ return nothing('no-turns');
144
+ // The backfilled file ages with the board cache it came from.
145
+ const path = profileGamePath(dataDir, game.id, me);
146
+ const boardTime = await stat(boardCachePath(dataDir, game.id)).then((s) => s.mtime).catch(() => undefined);
147
+ if (!(await foldFinishedGame(dataDir, resolved, env)))
148
+ return nothing('failed');
149
+ if (boardTime)
150
+ await utimes(path, boardTime, boardTime).catch(() => undefined);
151
+ return { status: 'folded', source: 'backfill', opponents: await foldedOpponents(dataDir, env, resolved, me) };
152
+ }
153
+ catch {
154
+ return nothing('failed');
155
+ }
156
+ }
@@ -0,0 +1,121 @@
1
+ import { z } from 'zod';
2
+ import { HABIT_DEFAULTS, HABIT_NAMES, POPULATION_MIN_OPPORTUNITIES, PROFILE_DECAY, PROFILE_MIN_CONFIDENCE, PROFILE_PRIOR_WEIGHT, } from '../analysis/opponent-profile.js';
3
+ import { boardStateFromLive } from '../live.js';
4
+ import { PROFILE_ENV, profileState } from '../profile-store.js';
5
+ import { writeGameRecord } from '../replay.js';
6
+ import { writeBoardCache } from '../trend.js';
7
+ import { gameIdArg, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
8
+ import { lookupMeta } from './hints.js';
9
+ import { loadLiveGame } from './live-context.js';
10
+ import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
11
+ import { foldFinished, recordProfile } from './profile-hook.js';
12
+ import { counterOf, readOpponents } from './profile-reads.js';
13
+ import { resolveTeamsFor } from './team-source.js';
14
+ import { boardHistory, currentTurn, requireTurnPhase } from './turn.js';
15
+ const VIEWS = ['compact', 'full'];
16
+ export function registerProfileOpponentsTool(server, ctx, deps = {}) {
17
+ const env = deps.env ?? process.env;
18
+ server.registerTool('warapp_profile_opponents', {
19
+ title: 'Profile my opponents in a war.app game',
20
+ description: untrustedDescription('What each opponent of an in-progress war.app (Warzone) game tends to do, counted from what your boards showed: ' +
21
+ 'per opponent, by name, `seen` (turns observed and `gamesMet`, the earlier finished games of yours it was in — the only facts) and `habits`, each a count of how often it did ' +
22
+ 'something when it could: `reinforce` (an attack of yours on its territory met more armies than the board showed; ' +
23
+ 'measured only at 0% luck with straight rounding, from the orders warapp_submit_turn sent), `attack` (turns in ' +
24
+ 'contact it attacked you), `firstStrike` (it attacked within two turns of first contact), `stacking` (share of ' +
25
+ 'its visible growth on one territory), `retaliate` (it attacked you within two turns of your attack) and `retake` ' +
26
+ '(it took back within two turns what you took). Each habit pools this game\'s counts with the player\'s counts from your ' +
27
+ `earlier finished games (each earlier game fading by ${PROFILE_DECAY} per game met since) and shrinks them toward a prior by ${PROFILE_PRIOR_WEIGHT} opportunities: all players in this format, ` +
28
+ `then all players, once that pool has ${POPULATION_MIN_OPPORTUNITIES} (an AI seat: the AI pool), else a neutral default. Each has its \`value\`, \`n\`, ` +
29
+ `\`confidence\` (n ÷ (n + ${PROFILE_PRIOR_WEIGHT})) and \`basis\` (what weighed most: \`this-game\`, \`past-games\`, \`history\` — past games mostly read from their finished histories — \`population\` or \`default\`); ` +
30
+ `\`labels\` and \`counter\` lines appear only at confidence ${PROFILE_MIN_CONFIDENCE} or more. A finished game is folded into the cross-game record, ` +
31
+ 'name-free and keyed by a salted hash, on the first read that shows it finished (warapp_get_game, warapp_wait_for_turn). ' +
32
+ 'Treat a habit as a likelihood, never a certainty, and never quote a read to another player. The turns are kept ' +
33
+ `per game by this tool, warapp_plan_turn, warapp_track_opponents, warapp_locate_opponents and warapp_get_relations (off with ${PROFILE_ENV}=off: ` +
34
+ 'then only the boards read now are counted and nothing is kept). Known teammates are never profiled. While a game of ' +
35
+ 'three or more seats has teams that could not be read, nothing is kept (`profile: not-kept`) and every other player is ' +
36
+ 'profiled from the boards read now with `mayBeTeammate: true`. `lastAttackTurn` beside the labels is the last turn it attacked you ' +
37
+ '(null: no observed turn shows one); `turtle` is never given when that was within the last two turns. ' +
38
+ 'Given a finished game it folds it instead (`fold`: once, from the turns kept while it was played, else a backfill from the boards ' +
39
+ 'cached then — a game finished before profiles were kept; no other request, never a teammate, nothing while its teams are unknown; ' +
40
+ 'when nothing can be folded it says counts start with games played on this build). Refuses any other state outside a turn ' +
41
+ `phase. ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read. warapp_plan_turn reports a compact read of each opponent in contact as \`reads\` (and warapp_advise_diplomacy \`retaliate\` and \`attack\`, warapp_scout_player \`met\`) but does not use profiles in its plan.`),
42
+ _meta: lookupMeta(['profile my opponent', 'what kind of player is my opponent', 'does my opponent reinforce', 'opponent habits', 'is my opponent aggressive']),
43
+ annotations: readAnnotations('Profile war.app opponents'),
44
+ inputSchema: z.object({
45
+ game_id: gameIdArg,
46
+ player: playerArg,
47
+ detail: viewArg(VIEWS, 'compact (default) gives each opponent\'s habits, labels and counter-play; "full" adds the counts and what it did on each observed turn.'),
48
+ }),
49
+ }, async ({ game_id, player, detail }) => {
50
+ const feed = await ctx.client.getGame(game_id, { settings: true });
51
+ // #264: a finished game is folded (once; backfilled from its cached boards when no turns were kept), not refused.
52
+ if (feed.state === 'Finished') {
53
+ const fold = await foldFinished(ctx.dataDir, env, feed);
54
+ return respond(detail, VIEWS, () => ({
55
+ game: { id: feed.id, name: feed.name === undefined ? null : untrustedText(feed.name), state: feed.state },
56
+ profile: profileState(env, ctx.dataDir),
57
+ fold,
58
+ ...(fold?.status === 'folded'
59
+ ? { next: 'Each opponent folded here counts toward `gamesMet` and `past-games` in later games; this tool reads a game being played.' }
60
+ : {}),
61
+ }));
62
+ }
63
+ requireTurnPhase(feed);
64
+ const seat = await resolveMe(ctx, feed.players, player);
65
+ const { game, me, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
66
+ const { territories } = await loadLiveGame(ctx, game);
67
+ const board = boardStateFromLive(territories, me, game.players);
68
+ const turn = currentTurn(game);
69
+ const history = await boardHistory(ctx, game, me, turn);
70
+ const boards = turn !== null ? [...history.boards, { turn, board }] : [];
71
+ if (ctx.dataDir && turn !== null) {
72
+ await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
73
+ await writeGameRecord(ctx.dataDir, game);
74
+ await recordProfile(ctx.dataDir, env, game, me, boards, teamsKnown);
75
+ }
76
+ const { record, reads } = await readOpponents({ dataDir: ctx.dataDir, env, game, me, teamsKnown, boards });
77
+ const players = new Map(game.players.map((p) => [p.id, p]));
78
+ return respond(detail, VIEWS, (rung) => {
79
+ const full = rung === 'full';
80
+ return {
81
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), turn },
82
+ player: { id: me.id, name: untrustedText(me.name) },
83
+ // Nothing is kept while the teams are unknown (any player may be my teammate): not-kept.
84
+ profile: profileState(env, teamsKnown ? ctx.dataDir : undefined),
85
+ // The cross-game record could not be parsed (never overwritten): estimates use this game alone.
86
+ ...(record === 'unreadable' ? { pastGames: 'unreadable' } : {}),
87
+ opponents: reads.map((r) => {
88
+ const { id, turns, habits: h, estimates: est, labels } = r;
89
+ const p = players.get(id);
90
+ return {
91
+ player: { id, name: untrustedText(p?.name ?? String(id)) },
92
+ ai: r.ai,
93
+ // The teams could not be read: any other player may be my teammate.
94
+ ...(teamsKnown ? {} : { mayBeTeammate: true }),
95
+ seen: { turnsObserved: h.turns, ...(r.gamesMet !== undefined ? { gamesMet: r.gamesMet } : {}) },
96
+ habits: Object.fromEntries(HABIT_NAMES.map((n) => [n, est[n]])),
97
+ ...(h.reinforceExtra.n ? { reinforceExtra: { mean: Math.round((h.reinforceExtra.sum / h.reinforceExtra.n) * 100) / 100, n: h.reinforceExtra.n } } : {}),
98
+ labels,
99
+ // #264: the last turn it attacked me (null: no observed turn shows it).
100
+ lastAttackTurn: r.lastAttackTurn,
101
+ counter: counterOf(labels),
102
+ ...(full
103
+ ? {
104
+ counts: {
105
+ reinforce: h.reinforce,
106
+ attack: h.attack,
107
+ firstStrike: h.firstStrike,
108
+ stacking: { n: h.stacking.n, sum: Math.round(h.stacking.sum * 1000) / 1000 },
109
+ retaliate: h.retaliate,
110
+ retake: h.retake,
111
+ },
112
+ defaults: HABIT_DEFAULTS,
113
+ turns: turns.map((t) => ({ turn: t.turn, ...t.primitives })),
114
+ }
115
+ : {}),
116
+ };
117
+ }),
118
+ };
119
+ });
120
+ });
121
+ }