@chrischall/warapp-mcp 0.5.0 → 0.7.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.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +133 -8
- package/dist/analysis/accept-surrender.js +20 -2
- package/dist/analysis/calibrate.js +1 -0
- package/dist/analysis/card-support.js +177 -17
- package/dist/analysis/card-threats.js +126 -14
- package/dist/analysis/chat-advice.js +182 -0
- package/dist/analysis/chat-blocks.js +106 -0
- package/dist/analysis/chat-intent.js +559 -0
- package/dist/analysis/chat-read.js +159 -0
- package/dist/analysis/decision-replay.js +279 -0
- package/dist/analysis/decision-truth.js +146 -0
- package/dist/analysis/finished-game.js +62 -3
- package/dist/analysis/game-lessons.js +15 -10
- package/dist/analysis/hold-diff.js +3 -1
- package/dist/analysis/income-trend.js +38 -0
- package/dist/analysis/intel.js +75 -0
- package/dist/analysis/opens.js +64 -0
- package/dist/analysis/opponent-profile.js +121 -10
- package/dist/analysis/opponents.js +246 -20
- package/dist/analysis/outlook.js +360 -15
- package/dist/analysis/picks.js +91 -12
- package/dist/analysis/plan/after-leftover.js +4 -1
- package/dist/analysis/plan/bonus-attempts.js +105 -0
- package/dist/analysis/plan/capture-instead.js +116 -0
- package/dist/analysis/plan/captures.js +49 -7
- package/dist/analysis/plan/conceded-out.js +13 -2
- package/dist/analysis/plan/estimates.js +203 -30
- package/dist/analysis/plan/guard-off.js +2 -1
- package/dist/analysis/plan/holds.js +110 -9
- package/dist/analysis/plan/jabs.js +113 -0
- package/dist/analysis/plan/leftover.js +393 -8
- package/dist/analysis/plan/orders.js +76 -4
- package/dist/analysis/plan/relations.js +135 -2
- package/dist/analysis/plan/report.js +69 -3
- package/dist/analysis/plan/second-sizing.js +133 -0
- package/dist/analysis/plan/shared.js +279 -27
- package/dist/analysis/plan/siege.js +303 -0
- package/dist/analysis/plan/stand-still.js +9 -5
- package/dist/analysis/plan/state.js +8 -0
- package/dist/analysis/plan/stockpile.js +104 -0
- package/dist/analysis/plan/strike.js +39 -7
- package/dist/analysis/plan/targets.js +256 -110
- package/dist/analysis/plan/threats.js +148 -10
- package/dist/analysis/plan/transfers.js +57 -6
- package/dist/analysis/plan/two-move.js +70 -0
- package/dist/analysis/plan/vacated.js +124 -2
- package/dist/analysis/planner.js +527 -49
- package/dist/analysis/profile.js +13 -2
- package/dist/analysis/since-last.js +18 -5
- package/dist/analysis/stress.js +8 -2
- package/dist/board.js +36 -2
- package/dist/bonus-attempt-store.js +55 -0
- package/dist/build-id.js +106 -0
- package/dist/bundle.js +54138 -41059
- package/dist/cards.js +7 -5
- package/dist/chat-automation.js +22 -0
- package/dist/chat.js +35 -1
- package/dist/client.js +14 -0
- package/dist/commerce.js +111 -0
- package/dist/decision-log.js +1093 -0
- package/dist/finished-store.js +5 -1
- package/dist/index.js +9 -1
- package/dist/lessons-store.js +322 -21
- package/dist/live.js +43 -0
- package/dist/move-order.js +64 -3
- package/dist/normalize.js +17 -0
- package/dist/open-games.js +36 -16
- package/dist/outlook-log.js +42 -1
- package/dist/profile-store.js +12 -2
- package/dist/protocol/methods.js +62 -5
- package/dist/protocol/rpc.js +8 -0
- package/dist/relations-store.js +38 -4
- package/dist/review-export.js +198 -0
- package/dist/siege-store.js +49 -0
- package/dist/state-bundle.js +584 -0
- package/dist/state-cli.js +71 -0
- package/dist/strategy/notes.js +56 -0
- package/dist/team-cards.js +25 -0
- package/dist/tools/accept-surrender.js +23 -9
- package/dist/tools/award.js +20 -2
- package/dist/tools/card-advice.js +93 -28
- package/dist/tools/card-plays.js +2 -2
- package/dist/tools/card-support-advice.js +37 -7
- package/dist/tools/chat-advice.js +330 -0
- package/dist/tools/chat-inbox.js +19 -4
- package/dist/tools/chat.js +106 -17
- package/dist/tools/check-plan.js +68 -12
- package/dist/tools/commerce-deploy.js +33 -0
- package/dist/tools/common.js +31 -0
- package/dist/tools/decision-capture.js +459 -0
- package/dist/tools/end-of-game.js +151 -21
- package/dist/tools/game-kind.js +92 -0
- package/dist/tools/how-lost.js +7 -2
- package/dist/tools/index.js +10 -0
- package/dist/tools/join-game.js +10 -4
- package/dist/tools/live-context.js +6 -0
- package/dist/tools/live.js +10 -1
- package/dist/tools/map-curves.js +73 -0
- package/dist/tools/notifications.js +4 -3
- package/dist/tools/opponents.js +2 -0
- package/dist/tools/past-games.js +74 -8
- package/dist/tools/picks.js +61 -10
- package/dist/tools/profile-hook.js +62 -3
- package/dist/tools/profile-opponents.js +4 -0
- package/dist/tools/push.js +2 -2
- package/dist/tools/relations.js +139 -0
- package/dist/tools/scout.js +16 -2
- package/dist/tools/state.js +232 -0
- package/dist/tools/strategy.js +3 -3
- package/dist/tools/stress-opponents.js +7 -2
- package/dist/tools/surrender-pending.js +10 -1
- package/dist/tools/surrender.js +18 -3
- package/dist/tools/survival.js +11 -3
- package/dist/tools/team-brief.js +2 -2
- package/dist/tools/team.js +12 -3
- package/dist/tools/turn.js +643 -76
- package/dist/tools/where.js +3 -1
- package/dist/version.js +1 -1
- package/manifest.json +32 -3
- package/mint.yaml +37 -4
- package/package.json +4 -4
- package/server.json +20 -2
- package/skills/warapp-mcp/SKILL.md +73 -17
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
// The decision log's capture points (#412 task 2), one helper each, so every tool logs the same way:
|
|
2
|
+
// `capturePlan` (warapp_plan_turn's decision, and the previous turn's outcome), `captureObservation`
|
|
3
|
+
// (a board read without a plan: the board cache's writers and boardHistory's history fill) and
|
|
4
|
+
// `captureSent` (warapp_submit_turn's orders, with any override). Best effort, never throws; nothing
|
|
5
|
+
// without a data dir or with `WARAPP_DECISION_LOG=off` (`LiveContext.decisionLog`). Name-free: every
|
|
6
|
+
// player name the game carries is scrubbed by the store.
|
|
7
|
+
//
|
|
8
|
+
// #437: the per-turn additions — `capturePlan` takes the first mover, my hand, the card advice and the
|
|
9
|
+
// turn's boot deadlines; `captureSent` the submit's checks; `captureCheck` warapp_check_plan's summary —
|
|
10
|
+
// and the pure helpers that turn each tool's own values into the log's name-free shapes.
|
|
11
|
+
//
|
|
12
|
+
// #437 task 2, per game: `captureSeats` (every GameFeed game read, through `WarappClient.observeGames`: the
|
|
13
|
+
// seat events and opponents first seen, as the log's own account — else the signed-in one only when a read
|
|
14
|
+
// already gave it, never a request), `captureGameEvent` (a pending surrender seen, my acceptance, my own
|
|
15
|
+
// surrender), `captureJoin` (warapp_join_game confirmed) and `captureOpponentRead` (warapp_scout_player with
|
|
16
|
+
// a game), and the pure shapers `joinContextLog` and `mySurrenderDetail`.
|
|
17
|
+
//
|
|
18
|
+
// #437 task 3, the picks phase: `capturePicksAdvice` (warapp_plan_picks: `picksAdviceLog`, warnings by
|
|
19
|
+
// `pickWarningCode`), `capturePicksSent` (warapp_submit_picks after a send) and `capturePicksAward` (the award
|
|
20
|
+
// `loadAward` reads on turn 1, once).
|
|
21
|
+
import { createHash } from 'node:crypto';
|
|
22
|
+
import { parseFeedTime } from '../normalize.js';
|
|
23
|
+
import { bonusTerritories } from '../analysis/bonuses.js';
|
|
24
|
+
import { policyChecks } from '../open-games.js';
|
|
25
|
+
import { nameFreeSettings } from '../replay.js';
|
|
26
|
+
import { recordPicksAdvice, recordPicksAward, recordPicksSent, decisionLogMode, decisionLogOwner, decisionLogPath, decisionOutcome, recordGameEvent, recordJoin, recordOpponentRead, recordSeats, fillOutcome, recordChat, recordCheck, recordDecision, recordObservations, recordSubmission, } from '../decision-log.js';
|
|
27
|
+
const modeOf = (ctx) => (ctx.decisionLog ? { mode: ctx.decisionLog } : {});
|
|
28
|
+
/** Every bonus of the map with its member territories (superbonuses flattened). */
|
|
29
|
+
const bonusesOf = (graph) => new Map([...graph.bonusById.keys()].map((id) => [id, bonusTerritories(graph, id)]));
|
|
30
|
+
/**
|
|
31
|
+
* Log the turn warapp_plan_turn planned (not a what-if plan), then fill the previous turn's outcome
|
|
32
|
+
* from this turn's board and income when that turn has an entry without one. Never throws.
|
|
33
|
+
*/
|
|
34
|
+
export async function capturePlan(ctx, a) {
|
|
35
|
+
if (!ctx.dataDir)
|
|
36
|
+
return;
|
|
37
|
+
const opts = modeOf(ctx);
|
|
38
|
+
await recordDecision(ctx.dataDir, a.gameId, a.me, {
|
|
39
|
+
turn: a.turn,
|
|
40
|
+
board: a.board,
|
|
41
|
+
...(a.plannedBoard ? { plannedBoard: a.plannedBoard } : {}),
|
|
42
|
+
input: a.input,
|
|
43
|
+
plan: a.plan,
|
|
44
|
+
outlookState: a.outlookState,
|
|
45
|
+
...(a.outlookLean ? { outlookLean: a.outlookLean } : {}),
|
|
46
|
+
...(a.estimates ? { estimates: a.estimates } : {}),
|
|
47
|
+
players: a.players,
|
|
48
|
+
...(a.firstMover !== undefined ? { firstMover: a.firstMover } : {}),
|
|
49
|
+
...(a.cards ? { cards: a.cards } : {}),
|
|
50
|
+
...(a.times ? { times: a.times } : {}),
|
|
51
|
+
}, opts);
|
|
52
|
+
if (a.turn < 2)
|
|
53
|
+
return;
|
|
54
|
+
try {
|
|
55
|
+
await fillOutcome(ctx.dataDir, a.gameId, a.me, a.turn - 1, (entry, before) => decisionOutcome({ before, after: a.board, me: a.me, income: a.income, captures: entry.decision?.expected.captures ?? [], bonuses: bonusesOf(a.graph) }), opts);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// Best effort.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Log boards seen without a plan as observations (never over a planned entry). Never throws. */
|
|
62
|
+
export async function captureObservation(ctx, gameId, me, seen) {
|
|
63
|
+
if (!ctx.dataDir || !seen.length)
|
|
64
|
+
return;
|
|
65
|
+
await recordObservations(ctx.dataDir, gameId, me, seen, modeOf(ctx));
|
|
66
|
+
}
|
|
67
|
+
/** Log the orders warapp_submit_turn sent, with any override (see `recordSubmission`). Never throws. */
|
|
68
|
+
export async function captureSent(ctx, gameId, me, turn, sub) {
|
|
69
|
+
if (!ctx.dataDir)
|
|
70
|
+
return;
|
|
71
|
+
await recordSubmission(ctx.dataDir, gameId, me, turn, sub, modeOf(ctx));
|
|
72
|
+
}
|
|
73
|
+
/** Log the chat read on a planned turn (#415: ids and labels only) beside its entry. Never throws. */
|
|
74
|
+
export async function captureChat(ctx, gameId, me, turn, chat, opts = {}) {
|
|
75
|
+
if (!ctx.dataDir || !chat.length)
|
|
76
|
+
return;
|
|
77
|
+
await recordChat(ctx.dataDir, gameId, me, turn, chat, { ...modeOf(ctx), ...opts });
|
|
78
|
+
}
|
|
79
|
+
/** Log warapp_check_plan's summary of the turn (the latest run wins). Never throws. */
|
|
80
|
+
export async function captureCheck(ctx, gameId, me, turn, summary) {
|
|
81
|
+
if (!ctx.dataDir)
|
|
82
|
+
return;
|
|
83
|
+
await recordCheck(ctx.dataDir, gameId, me, turn, summary, modeOf(ctx));
|
|
84
|
+
}
|
|
85
|
+
// ---------------------------------------------------------------------------------------------
|
|
86
|
+
// #437: the tools' values in the log's shapes (pure)
|
|
87
|
+
const byNum = (a, b) => a - b;
|
|
88
|
+
/** My hand by card type, counted, sorted by name (then type). */
|
|
89
|
+
export function handLog(cards) {
|
|
90
|
+
const m = new Map();
|
|
91
|
+
for (const c of cards) {
|
|
92
|
+
const e = m.get(c.type);
|
|
93
|
+
if (e)
|
|
94
|
+
e.count += 1;
|
|
95
|
+
else
|
|
96
|
+
m.set(c.type, { card: c.name, type: c.type, count: 1 });
|
|
97
|
+
}
|
|
98
|
+
return [...m.values()].sort((a, b) => a.card.localeCompare(b.card) || a.type - b.type);
|
|
99
|
+
}
|
|
100
|
+
const rec = (v) => (typeof v === 'object' && v !== null && !Array.isArray(v) ? v : undefined);
|
|
101
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
|
|
102
|
+
const nums = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'number') : []);
|
|
103
|
+
/**
|
|
104
|
+
* The card advice warapp_plan_turn offered (`cards.advice`), one entry per card advised: its kind, the
|
|
105
|
+
* target ids, the player when one is named and a reason code — never the advice's prose. `active` (the
|
|
106
|
+
* cards in effect) is not advice and is left out.
|
|
107
|
+
*/
|
|
108
|
+
export function cardAdviceLog(view) {
|
|
109
|
+
const v = view;
|
|
110
|
+
const out = [];
|
|
111
|
+
const add = (kind, targets, reason, player, extra = {}) => out.push({ kind, targets, ...(player !== undefined ? { player } : {}), reason, ...extra });
|
|
112
|
+
const d = rec(v.orderDelay);
|
|
113
|
+
if (d)
|
|
114
|
+
add('orderDelay', [], d.insteadOfDiscard ? 'instead-of-discard' : 'delay-attacks', undefined, num(d.before) !== undefined ? { before: num(d.before) } : {});
|
|
115
|
+
const b = rec(v.bomb);
|
|
116
|
+
if (b)
|
|
117
|
+
add('bomb', num(b.target) !== undefined ? [num(b.target)] : [], typeof b.kind === 'string' ? b.kind : 'none');
|
|
118
|
+
const e = rec(v.emergencyBlockade);
|
|
119
|
+
if (e)
|
|
120
|
+
add('emergencyBlockade', nums([e.territory]), 'conceded-wall', num(e.player));
|
|
121
|
+
const bk = rec(v.blockade);
|
|
122
|
+
if (bk)
|
|
123
|
+
add('blockade', nums([bk.territory]), 'gate', num(bk.player));
|
|
124
|
+
const dip = rec(v.diplomacy);
|
|
125
|
+
if (dip)
|
|
126
|
+
add('diplomacy', nums(dip.borders), dip.overTruce !== undefined ? 'over-truce' : 'border-pressure', num(dip.player));
|
|
127
|
+
const s = rec(v.sanctions);
|
|
128
|
+
if (s)
|
|
129
|
+
add('sanctions', [], 'strongest', num(s.player));
|
|
130
|
+
const a = rec(v.airlift);
|
|
131
|
+
const re = rec(a?.redeploy);
|
|
132
|
+
if (a)
|
|
133
|
+
add('airlift', nums([a.from, a.to]), re ? `${String(re.source)}-to-${String(re.target)}` : a.teammate !== undefined ? 'teammate-border' : 'border');
|
|
134
|
+
const g = rec(v.gift);
|
|
135
|
+
if (g)
|
|
136
|
+
add('gift', nums(g.territories), 'teammate-bonus', num(g.player));
|
|
137
|
+
const spy = rec(v.spy);
|
|
138
|
+
if (spy)
|
|
139
|
+
add('spy', [], 'fog', num(spy.player));
|
|
140
|
+
const r = rec(v.reconnaissance);
|
|
141
|
+
if (r)
|
|
142
|
+
add('reconnaissance', nums([r.target]), 'fog');
|
|
143
|
+
const sv = rec(v.surveillance);
|
|
144
|
+
if (sv)
|
|
145
|
+
add('surveillance', nums([sv.bonus]), 'fog');
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
/** Headroom rows logged at most. */
|
|
149
|
+
export const LOGGED_HEADROOM_ROWS = 5;
|
|
150
|
+
/** The weakest {@link LOGGED_HEADROOM_ROWS} headroom rows (the smallest deploy that takes it first; none taking it last). */
|
|
151
|
+
export function headroomLog(rows) {
|
|
152
|
+
const key = (r) => r.deploy ?? Number.POSITIVE_INFINITY;
|
|
153
|
+
return [...rows]
|
|
154
|
+
.sort((x, y) => key(x) - key(y) || x.territory - y.territory)
|
|
155
|
+
.slice(0, LOGGED_HEADROOM_ROWS)
|
|
156
|
+
.map((r) => ({
|
|
157
|
+
territory: r.territory,
|
|
158
|
+
takeAt: r.deploy,
|
|
159
|
+
opponent: r.opponent,
|
|
160
|
+
from: r.from,
|
|
161
|
+
protects: { bonuses: r.bonuses.map((b) => b.id).sort(byNum), behindIncome: r.behindIncome, breachIncome: r.breach.income },
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
/** warapp_check_plan's report in the log's shape: the verdict, the worst reply in numbers and the at-risk counts. */
|
|
165
|
+
export function checkPlanLog(report, o) {
|
|
166
|
+
const w = report.worst;
|
|
167
|
+
return {
|
|
168
|
+
safe: report.safe,
|
|
169
|
+
worst: w
|
|
170
|
+
? {
|
|
171
|
+
opponent: w.opponent,
|
|
172
|
+
kind: w.kind,
|
|
173
|
+
deploy: w.deploy,
|
|
174
|
+
lost: w.lost.length,
|
|
175
|
+
capturesFailed: w.capturesFailed.length,
|
|
176
|
+
bonusesLost: w.bonusesLost.length,
|
|
177
|
+
incomeLost: w.incomeLost,
|
|
178
|
+
commanderLost: w.commanderLost,
|
|
179
|
+
}
|
|
180
|
+
: null,
|
|
181
|
+
harmful: report.harmful,
|
|
182
|
+
considered: report.considered,
|
|
183
|
+
atRisk: {
|
|
184
|
+
commander: report.atRisk.commander,
|
|
185
|
+
territories: report.atRisk.territories.length,
|
|
186
|
+
captures: report.atRisk.captures.length,
|
|
187
|
+
bonuses: report.atRisk.bonuses.length,
|
|
188
|
+
},
|
|
189
|
+
...(o.whatIf ? { whatIf: true } : {}),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/** What warapp_submit_turn checked on the orders, in the log's shape (ids and numbers only). */
|
|
193
|
+
export function submitChecksLog(a) {
|
|
194
|
+
const c = a.commander;
|
|
195
|
+
return {
|
|
196
|
+
commander: c
|
|
197
|
+
? {
|
|
198
|
+
territory: c.safety.territory,
|
|
199
|
+
armies: c.safety.armies,
|
|
200
|
+
needs: c.safety.needs,
|
|
201
|
+
replies: c.safety.killers,
|
|
202
|
+
replyDeploy: c.replyDeploy,
|
|
203
|
+
...(c.accepted ? { accepted: true } : {}),
|
|
204
|
+
}
|
|
205
|
+
: null,
|
|
206
|
+
headroom: headroomLog(a.headroom),
|
|
207
|
+
belowPlan: (a.belowPlan?.rows ?? []).map((r) => ({ territory: r.territory, planLeaves: r.planLeaves, left: r.left, short: r.short })),
|
|
208
|
+
...(a.belowPlan ? { belowPlanAgainst: a.belowPlan.against } : {}),
|
|
209
|
+
chat: a.chat.map((w) => ({
|
|
210
|
+
kind: w.kind,
|
|
211
|
+
...(w.with !== undefined ? { with: w.with } : {}),
|
|
212
|
+
moves: w.moves.map((m) => m.index),
|
|
213
|
+
...(w.unchecked ? { unchecked: true } : {}),
|
|
214
|
+
})),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* The turn's start (GameFeed's `lastTurnTime`, read as it — UNVERIFIED, as the boot warnings say) and the
|
|
219
|
+
* boot deadlines its AutoBoot and DirectBoot minutes give, ISO; empty when the game read gives none.
|
|
220
|
+
*/
|
|
221
|
+
export function bootTimes(game) {
|
|
222
|
+
const start = parseFeedTime(game.lastTurnTime);
|
|
223
|
+
if (start === undefined)
|
|
224
|
+
return {};
|
|
225
|
+
const at = (m) => (m !== undefined && m > 0 ? new Date(start + m * 60_000).toISOString() : undefined);
|
|
226
|
+
const auto = at(game.endRules?.autoBootMinutes);
|
|
227
|
+
const direct = at(game.endRules?.directBootMinutes);
|
|
228
|
+
return {
|
|
229
|
+
turnStartedAt: new Date(start).toISOString(),
|
|
230
|
+
...(auto || direct ? { bootAt: { ...(auto ? { auto } : {}), ...(direct ? { direct } : {}) } } : {}),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
// ---------------------------------------------------------------------------------------------
|
|
234
|
+
// #437 task 2: per-game events and context
|
|
235
|
+
/** The turn being played as a game read gives it: GameFeed's completed turns + 1, 0 before the first turn. */
|
|
236
|
+
export const turnOfGame = (game) => game.numberOfTurns !== undefined && game.numberOfTurns >= 0 ? game.numberOfTurns + 1 : 0;
|
|
237
|
+
const offMode = (ctx) => (ctx.decisionLog ?? decisionLogMode()) === 'off';
|
|
238
|
+
/** Each game's seats as last captured this process (data dir + game → signature), so an unchanged read costs nothing. */
|
|
239
|
+
const seatsSeen = new Map();
|
|
240
|
+
const SEATS_SEEN_MAX = 2000;
|
|
241
|
+
/**
|
|
242
|
+
* Diff a game read's seats into its decision log (`recordSeats`): as the account the log belongs to when it
|
|
243
|
+
* is seated, else the signed-in account when a read already gave it (`cachedInviteToken`) and the game is not
|
|
244
|
+
* over — that starts a log; never a request. A read whose seats did not change since the last capture in this
|
|
245
|
+
* process is skipped. Never throws.
|
|
246
|
+
*/
|
|
247
|
+
export async function captureSeats(ctx, game) {
|
|
248
|
+
try {
|
|
249
|
+
if (!ctx.dataDir || offMode(ctx) || !game.players.length)
|
|
250
|
+
return;
|
|
251
|
+
const sig = JSON.stringify(game.players.map((p) => [p.id, p.state ?? null, !!p.humanTurnedIntoAI, !!p.isAI]));
|
|
252
|
+
const key = `${ctx.dataDir}\0${game.id}`;
|
|
253
|
+
if (seatsSeen.get(key) === sig)
|
|
254
|
+
return;
|
|
255
|
+
const ids = new Set(game.players.map((p) => p.id));
|
|
256
|
+
const owner = await decisionLogOwner(decisionLogPath(ctx.dataDir, game.id), game.id);
|
|
257
|
+
let me;
|
|
258
|
+
let create = false;
|
|
259
|
+
if (owner !== undefined) {
|
|
260
|
+
if (ids.has(owner))
|
|
261
|
+
me = owner;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
const token = ctx.cachedInviteToken?.();
|
|
265
|
+
if (token !== undefined && ids.has(token) && game.state !== 'Finished') {
|
|
266
|
+
me = token;
|
|
267
|
+
create = true;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// Not mine (yet): not remembered, so a later read that knows the account captures it.
|
|
271
|
+
if (me === undefined)
|
|
272
|
+
return;
|
|
273
|
+
await recordSeats(ctx.dataDir, game.id, me, { turn: turnOfGame(game), players: game.players, create }, modeOf(ctx));
|
|
274
|
+
if (seatsSeen.size >= SEATS_SEEN_MAX)
|
|
275
|
+
seatsSeen.delete(seatsSeen.keys().next().value);
|
|
276
|
+
seatsSeen.set(key, sig);
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// Best effort.
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/** Log one per-game event (see `recordGameEvent`), starting a log with `create`. Never throws. */
|
|
283
|
+
export async function captureGameEvent(ctx, gameId, me, ev, o = {}) {
|
|
284
|
+
if (!ctx.dataDir)
|
|
285
|
+
return;
|
|
286
|
+
await recordGameEvent(ctx.dataDir, gameId, me, ev, o, modeOf(ctx));
|
|
287
|
+
}
|
|
288
|
+
/** Keep the lobby warapp_join_game joined. Never throws. */
|
|
289
|
+
export async function captureJoin(ctx, gameId, me, join) {
|
|
290
|
+
if (!ctx.dataDir)
|
|
291
|
+
return;
|
|
292
|
+
await recordJoin(ctx.dataDir, gameId, me, join, modeOf(ctx));
|
|
293
|
+
}
|
|
294
|
+
/** Keep what warapp_scout_player read of an opponent in that game's log, when the game has one. Never throws. */
|
|
295
|
+
export async function captureOpponentRead(ctx, gameId, me, player, read) {
|
|
296
|
+
if (!ctx.dataDir)
|
|
297
|
+
return;
|
|
298
|
+
await recordOpponentRead(ctx.dataDir, gameId, me, player, read, modeOf(ctx));
|
|
299
|
+
}
|
|
300
|
+
/** Keys in sorted order, so one settings shape always hashes alike. */
|
|
301
|
+
function stable(v) {
|
|
302
|
+
if (Array.isArray(v))
|
|
303
|
+
return v.map(stable);
|
|
304
|
+
if (rec(v))
|
|
305
|
+
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, stable(v[k])]));
|
|
306
|
+
return v;
|
|
307
|
+
}
|
|
308
|
+
/** `sha256:<16 hex>` of a game's name-free settings shape (`nameFreeSettings`); `null` without settings. */
|
|
309
|
+
export function settingsKey(game) {
|
|
310
|
+
const s = nameFreeSettings(game);
|
|
311
|
+
return s ? `sha256:${createHash('sha256').update(JSON.stringify(stable(s))).digest('hex').slice(0, 16)}` : null;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* The join context (#437): the lobby's settings key and readable flags (the open-games record's format,
|
|
315
|
+
* seats, pace and boot time; GameFeed's Local Deployment, Commanders, kill rates, luck, fog and cards when it
|
|
316
|
+
* read the lobby) and the joining policy's checks by code. Name-free. Pure but for the clock.
|
|
317
|
+
*/
|
|
318
|
+
export function joinContextLog(listed, feed, screen, now = Date.now()) {
|
|
319
|
+
const s = feed?.settings;
|
|
320
|
+
const policy = policyChecks(listed, screen);
|
|
321
|
+
const seats = listed.maxPlayers ?? listed.seats;
|
|
322
|
+
return {
|
|
323
|
+
at: new Date(now).toISOString(),
|
|
324
|
+
settingsKey: feed ? settingsKey(feed) : null,
|
|
325
|
+
flags: {
|
|
326
|
+
format: listed.teamGame ? 'team' : seats <= 2 ? '1v1' : 'ffa',
|
|
327
|
+
seats,
|
|
328
|
+
...(listed.pace ? { pace: String(listed.pace) } : {}),
|
|
329
|
+
...(listed.bootTimeMinutes !== undefined ? { bootMinutes: listed.bootTimeMinutes } : {}),
|
|
330
|
+
...(s
|
|
331
|
+
? {
|
|
332
|
+
...(s.localDeployments !== undefined ? { localDeployments: s.localDeployments } : {}),
|
|
333
|
+
...(s.commanders !== undefined ? { commanders: s.commanders } : {}),
|
|
334
|
+
killRates: { offence: s.offensiveKillRate ?? null, defence: s.defensiveKillRate ?? null },
|
|
335
|
+
...(s.luckModifier !== undefined ? { luck: s.luckModifier } : {}),
|
|
336
|
+
...(s.fog !== undefined ? { fog: s.fog } : {}),
|
|
337
|
+
cards: [...s.cards].sort(),
|
|
338
|
+
}
|
|
339
|
+
: {}),
|
|
340
|
+
},
|
|
341
|
+
policy: { passes: policy.passes, broke: policy.broke, passed: policy.passed, unchecked: policy.unchecked },
|
|
342
|
+
...(listed.lottery !== undefined ? { lottery: listed.lottery } : {}),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* My surrender's detail (#437) from the outlook log's latest turn: my income and the strongest opponent's
|
|
347
|
+
* in its evidence, its state and turn (all `null` when nothing was logged).
|
|
348
|
+
*/
|
|
349
|
+
export function mySurrenderDetail(status, log) {
|
|
350
|
+
const l = log?.latest;
|
|
351
|
+
const ev = l?.evidence;
|
|
352
|
+
const top = [...(ev?.opponents ?? [])].sort((a, b) => b.income - a.income || a.playerId - b.playerId)[0];
|
|
353
|
+
return {
|
|
354
|
+
status,
|
|
355
|
+
income: ev?.incomes?.mine ?? null,
|
|
356
|
+
strongest: top ? { player: top.playerId, income: top.income, source: top.source, thin: top.thin } : null,
|
|
357
|
+
outlook: l?.state ?? null,
|
|
358
|
+
// #454: the income lean beside an even state (additive).
|
|
359
|
+
...(l?.lean ? { outlookLean: l.lean } : {}),
|
|
360
|
+
outlookTurn: l?.turn ?? null,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
// ---------------------------------------------------------------------------------------------
|
|
364
|
+
// #437 task 3: the picks phase
|
|
365
|
+
/** Picks whose score the advice log keeps, from the top of the list. */
|
|
366
|
+
export const LOGGED_PICK_SCORES = 10;
|
|
367
|
+
/** The pick advisor's warnings (and its tool's) by the start of their wording; anything else is `other`. */
|
|
368
|
+
const PICK_WARNING_CODES = [
|
|
369
|
+
[/^Ignored pickable ids not on the map/, 'unknown-pickable'],
|
|
370
|
+
[/^Starting armies per picked territory missing/, 'assumed-pick-armies'],
|
|
371
|
+
[/^Base income missing/, 'assumed-base-income'],
|
|
372
|
+
[/^Kill rates missing/, 'assumed-kill-rates'],
|
|
373
|
+
[/^Neutral size of unpicked pickable territories missing/, 'assumed-neutrals-in'],
|
|
374
|
+
[/^Neutral size of territories outside the distribution missing/, 'assumed-neutrals-out'],
|
|
375
|
+
[/^Luck is /, 'luck'],
|
|
376
|
+
[/^Capture costs assume straight rounding/, 'rounding'],
|
|
377
|
+
[/^Local deployments are on/, 'local-deployments'],
|
|
378
|
+
[/^No compact /, 'not-compact'],
|
|
379
|
+
[/^In a 1v1 the best /, 'spread-relaxed'],
|
|
380
|
+
[/^Only \d+ pickable territor/, 'short-pickable'],
|
|
381
|
+
[/^The fallback group scores more than the primary/, 'fallback-outscores'],
|
|
382
|
+
[/^Territory limit missing/, 'assumed-territory-limit'],
|
|
383
|
+
[/^Full distribution \(DistributionMode 0/, 'full-distribution'],
|
|
384
|
+
[/^Could not tell which seat is yours/, 'team-seat-unknown'],
|
|
385
|
+
];
|
|
386
|
+
/** A pick warning's code (never its prose, which may carry ids and figures). */
|
|
387
|
+
export function pickWarningCode(w) {
|
|
388
|
+
return PICK_WARNING_CODES.find(([re]) => re.test(w))?.[1] ?? 'other';
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* The pick advisor's plan as the decision log keeps it (#437 task 3): ids, the top scores, the warnings by
|
|
392
|
+
* code (the tool's own first, each once), the award orders judged with the worst outcome, coverage and any
|
|
393
|
+
* alternative. No reason, rationale or name. Pure but for the clock.
|
|
394
|
+
*/
|
|
395
|
+
export function picksAdviceLog(plan, a) {
|
|
396
|
+
const cov = (c) => ({ share: c.share, covered: c.covered, reasonable: c.reasonable });
|
|
397
|
+
const alt = plan.alternative;
|
|
398
|
+
return {
|
|
399
|
+
at: new Date(a.now ?? Date.now()).toISOString(),
|
|
400
|
+
players: a.players,
|
|
401
|
+
territoryLimit: a.territoryLimit,
|
|
402
|
+
maxPicks: a.maxPicks,
|
|
403
|
+
spread: a.spread,
|
|
404
|
+
list: plan.picks.map((p) => p.territoryId),
|
|
405
|
+
primary: [...plan.groups.primary.territoryIds],
|
|
406
|
+
fallback: [...plan.groups.fallback.territoryIds],
|
|
407
|
+
scores: plan.picks.slice(0, LOGGED_PICK_SCORES).map((p) => ({ territory: p.territoryId, score: p.score })),
|
|
408
|
+
groupScores: { primary: plan.groups.primary.score, fallback: plan.groups.fallback.score },
|
|
409
|
+
warnings: [...new Set([...a.warnings, ...plan.warnings].map(pickWarningCode))],
|
|
410
|
+
award: plan.award
|
|
411
|
+
? {
|
|
412
|
+
outcomes: plan.award.outcomes,
|
|
413
|
+
// A free-for-all or 1v1 is judged by the reversing order alone (planPicks names the orders only in a team game).
|
|
414
|
+
orders: plan.award.orders ? [...plan.award.orders] : ['reversing'],
|
|
415
|
+
worst: { territories: [...plan.award.worst.territoryIds], score: plan.award.worst.score, opponentStarts: [...plan.award.worst.opponentStarts] },
|
|
416
|
+
reordered: plan.award.reordered,
|
|
417
|
+
}
|
|
418
|
+
: null,
|
|
419
|
+
coverage: cov(plan.coverage),
|
|
420
|
+
...(alt ? { alternative: { territories: [...alt.group.territoryIds], fallback: [...alt.fallback], score: alt.group.score, coverage: cov(alt.coverage) } } : {}),
|
|
421
|
+
...(a.team ? { team: a.team } : {}),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Keep warapp_plan_picks' summary (a re-plan replaces it), starting a log, as the account the game's log
|
|
426
|
+
* belongs to when it is seated, else the signed-in account when seated (`myInviteToken`: cached for a while,
|
|
427
|
+
* so usually no request; the advisor is read-only and plans for that seat). Nothing when neither is seated,
|
|
428
|
+
* the log is off or there is no data dir. Never throws.
|
|
429
|
+
*/
|
|
430
|
+
export async function capturePicksAdvice(ctx, game, advice) {
|
|
431
|
+
try {
|
|
432
|
+
if (!ctx.dataDir || offMode(ctx))
|
|
433
|
+
return;
|
|
434
|
+
const seated = (id) => (id !== undefined && game.players.some((p) => p.id === id) ? id : undefined);
|
|
435
|
+
const owner = await decisionLogOwner(decisionLogPath(ctx.dataDir, game.id), game.id);
|
|
436
|
+
const me = owner !== undefined ? seated(owner) : seated(await ctx.myInviteToken?.());
|
|
437
|
+
if (me === undefined)
|
|
438
|
+
return;
|
|
439
|
+
await recordPicksAdvice(ctx.dataDir, game.id, me, advice, modeOf(ctx));
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
// Best effort.
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** Keep the list warapp_submit_picks sent and read back (the latest send wins), starting a log. Never throws. */
|
|
446
|
+
export async function capturePicksSent(ctx, gameId, me, sent) {
|
|
447
|
+
if (!ctx.dataDir)
|
|
448
|
+
return;
|
|
449
|
+
await recordPicksSent(ctx.dataDir, gameId, me, sent, modeOf(ctx));
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Keep the award `loadAward` read on turn 1 (`null`: nothing could be read), once, starting a log. Takes the
|
|
453
|
+
* data dir and mode rather than a context (loadAward has no context). Never throws.
|
|
454
|
+
*/
|
|
455
|
+
export async function capturePicksAward(dataDir, mode, gameId, me, turn, reading) {
|
|
456
|
+
if (!dataDir)
|
|
457
|
+
return;
|
|
458
|
+
await recordPicksAward(dataDir, gameId, me, { turn, reading: reading ? { ...reading } : null }, mode ? { mode } : {});
|
|
459
|
+
}
|