@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.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +199 -8
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +159 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +551 -0
- package/dist/analysis/opponents.js +1245 -0
- package/dist/analysis/outlook.js +633 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1218 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +927 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2922 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +577 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1109 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +117959 -36172
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +192 -0
- package/dist/client.js +361 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/live.js +278 -0
- package/dist/map-stats.js +152 -0
- package/dist/map-store.js +204 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +180 -0
- package/dist/normalize.js +411 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +138 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +229 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +677 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +531 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +215 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +269 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2168 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +146 -0
- package/dist/tools/chat.js +483 -0
- package/dist/tools/check-plan.js +688 -0
- package/dist/tools/commander-check.js +102 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/game.js +126 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +142 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-stats.js +117 -0
- package/dist/tools/map.js +133 -0
- package/dist/tools/my-games.js +123 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +151 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/picks.js +292 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +385 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +200 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender.js +240 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +182 -0
- package/dist/tools/turn.js +2761 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +275 -0
- package/dist/tools/write-kit.js +158 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +452 -0
- package/dist/version.js +4 -0
- package/manifest.json +174 -4
- package/mint.yaml +101 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +969 -21
|
@@ -0,0 +1,677 @@
|
|
|
1
|
+
// The in-game opponent profile on disk (docs/PLAN-PROFILES.md A2; owner decision P4 of 2026-11-15:
|
|
2
|
+
// on, local and hosted — a hosted child keeps it in its per-user data dir).
|
|
3
|
+
//
|
|
4
|
+
// `<dataDir>/profiles/games/<gameId>-<myId>.json` (version 1): per turn T, per opponent, what that
|
|
5
|
+
// opponent did between my boards of T and T+1 (`TurnPrimitives`, src/analysis/opponent-profile.ts).
|
|
6
|
+
// It holds real ids, like the board cache beside it (src/trend.ts), and only gameplay counts: no
|
|
7
|
+
// name, no chat, no time of play. Every turn ever observed is kept (the board cache keeps ten);
|
|
8
|
+
// observing a turn again overwrites that turn's entry, so planning a turn twice never adds.
|
|
9
|
+
//
|
|
10
|
+
// Same guarantees as the board cache: 0600 files in a 0700 folder, atomic writes (under the
|
|
11
|
+
// in-process path lock), best effort, never throws; an unusable file reads as empty; only the newest
|
|
12
|
+
// `MAX_PROFILE_GAME_FILES` game files are kept, and none unwritten for the board cache's age limit
|
|
13
|
+
// (`BOARD_CACHE_MAX_AGE_MS`). `WARAPP_PLAYER_PROFILE=off` (or `0` / `false` / `no`): nothing here
|
|
14
|
+
// reads or writes.
|
|
15
|
+
//
|
|
16
|
+
// Across games (B2) two name-free stores sit beside it:
|
|
17
|
+
// - `<dataDir>/profiles/players.json` (version 1): per player, keyed by the deal record's
|
|
18
|
+
// `playerKey` under the one shared salt (`playerSaltForWrite`, src/player-record-store.ts), so the
|
|
19
|
+
// two join in memory and neither holds an id: up to `MAX_PROFILE_ENTRIES` per-game entries (each
|
|
20
|
+
// keyed by an HMAC of my account and the game) and the faded totals by format; at most
|
|
21
|
+
// `MAX_PROFILE_PLAYERS` players, the least recently updated dropped first (by a counter, never a
|
|
22
|
+
// clock: no time of play is kept).
|
|
23
|
+
// - `<dataDir>/profiles/population.json` (version 1): the totals per format over every human
|
|
24
|
+
// opponent, a pooled `ai` profile, a games count, and one entry per folded game (bounded) so a game
|
|
25
|
+
// folded again replaces its own contribution. It never fades.
|
|
26
|
+
// `foldGame` adds a game by the difference between its new entry and the one stored under the same
|
|
27
|
+
// key, so folding twice, or a `history` entry replacing a `live` one, never counts twice; a game new
|
|
28
|
+
// to a player first fades that player's totals (and every entry's weight) by `PROFILE_DECAY`. AI
|
|
29
|
+
// seats go to the pool only; a human who became an AI is left out of the game altogether (no turn of
|
|
30
|
+
// the change is known, V4). A finished game is folded by `foldFinishedGame` on the first read that
|
|
31
|
+
// shows it finished (warapp_get_game, warapp_wait_for_turn's re-read); its per-game file is then
|
|
32
|
+
// marked `folded: 'live'` and kept until the age rule deletes it (part C, which would read the
|
|
33
|
+
// game's history first, is not built), and a file reaching that age unfolded is folded with every
|
|
34
|
+
// ending `unknown`, then deleted. A store or salt that exists but is not JSON, not an object or not
|
|
35
|
+
// version 1 is never overwritten: reads say `unreadable`, folds fail. Inside a version-1 store the
|
|
36
|
+
// read is loose, like the board cache's: a malformed player record, entry or total is dropped (an
|
|
37
|
+
// `entries` that is not an array reads as none), and the next fold writes the store back without it.
|
|
38
|
+
//
|
|
39
|
+
// Folding is idempotent only while the game's entry is still stored: `foldGame` finds "this game
|
|
40
|
+
// again" among a player's last `MAX_PROFILE_ENTRIES` entries and the population's last
|
|
41
|
+
// `MAX_POPULATION_ENTRIES`. A game folded again after its entry was dropped (part C's history
|
|
42
|
+
// replacement arriving that late) is faded and counted a second time. Likewise the
|
|
43
|
+
// `MAX_PROFILE_GAME_FILES` bound can fold a game still in progress (endings `unknown`) and delete
|
|
44
|
+
// its file; if play goes on, `recordBehaviour` starts a new file with the later turns only, and the
|
|
45
|
+
// fold at the finish replaces the earlier entry with that shorter one, so the turns before the
|
|
46
|
+
// eviction leave the totals. Both are rare today (30 games with one opponent, 200 games in play);
|
|
47
|
+
// part C must guard them (a kept tombstone of folded keys, or merging into the stored entry) before
|
|
48
|
+
// it relies on refolding.
|
|
49
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
50
|
+
import { join } from 'node:path';
|
|
51
|
+
import { randomUUID } from 'node:crypto';
|
|
52
|
+
import { readEnvVar } from '@chrischall/mcp-utils';
|
|
53
|
+
import { addHabits, emptyHabits, habitsOf, observeTurn, PROFILE_DECAY, PROFILE_FORMATS, profileFormatOf, scaleHabits, } from './analysis/opponent-profile.js';
|
|
54
|
+
import { withPathLock } from './path-lock.js';
|
|
55
|
+
import { playerKey, playerRecordSalt, playerRecordSaltPath, playerSaltForWrite, profileGameKey } from './player-record-store.js';
|
|
56
|
+
import { holdsSeat } from './player-states.js';
|
|
57
|
+
import { isTeamGame, teammatesOf } from './teams.js';
|
|
58
|
+
import { BOARD_CACHE_MAX_AGE_MS } from './trend.js';
|
|
59
|
+
export const PROFILE_ENV = 'WARAPP_PLAYER_PROFILE';
|
|
60
|
+
/** Game files kept: the newest by last write. */
|
|
61
|
+
export const MAX_PROFILE_GAME_FILES = 200;
|
|
62
|
+
/** Whether opponent profiling is on: yes (local and hosted) unless `WARAPP_PLAYER_PROFILE` is `off`, `0`, `false` or `no`. */
|
|
63
|
+
export function profileEnabled(env = process.env) {
|
|
64
|
+
const v = readEnvVar(PROFILE_ENV, { env });
|
|
65
|
+
return v === undefined || !/^(off|0|false|no)$/i.test(v.trim());
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* What the profile tool says of its store: `kept` (stored per game), `not-kept` (on, but no data dir to
|
|
69
|
+
* keep it in; the tool passes none while a game's teams are unknown) or `off`.
|
|
70
|
+
*/
|
|
71
|
+
export function profileState(env, dataDir) {
|
|
72
|
+
if (!profileEnabled(env))
|
|
73
|
+
return 'off';
|
|
74
|
+
return dataDir ? 'kept' : 'not-kept';
|
|
75
|
+
}
|
|
76
|
+
export const profileGamesDir = (dir) => join(dir, 'profiles', 'games');
|
|
77
|
+
export const profileGamePath = (dir, gameId, playerId) => join(profileGamesDir(dir), `${gameId}-${playerId}.json`);
|
|
78
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
79
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
80
|
+
const ids = (v) => (Array.isArray(v) && v.every(isInt) ? [...v] : undefined);
|
|
81
|
+
/** One stored record, loosely: `undefined` when unusable. */
|
|
82
|
+
function primitivesOf(v) {
|
|
83
|
+
if (!isRec(v) || typeof v.contact !== 'boolean' || typeof v.iAttacked !== 'boolean')
|
|
84
|
+
return undefined;
|
|
85
|
+
if (v.attackedMe !== null && typeof v.attackedMe !== 'boolean')
|
|
86
|
+
return undefined;
|
|
87
|
+
const r = v.reinforce;
|
|
88
|
+
if (!isRec(r) || !isInt(r.n) || !isInt(r.e) || !isInt(r.extra))
|
|
89
|
+
return undefined;
|
|
90
|
+
const s = v.stack;
|
|
91
|
+
if (s !== null && !(isRec(s) && isInt(s.top) && isInt(s.total)))
|
|
92
|
+
return undefined;
|
|
93
|
+
const took = v.tookFromMe === null ? null : ids(v.tookFromMe);
|
|
94
|
+
const lost = ids(v.lostToMe);
|
|
95
|
+
if (took === undefined || !lost)
|
|
96
|
+
return undefined;
|
|
97
|
+
return {
|
|
98
|
+
contact: v.contact,
|
|
99
|
+
attackedMe: v.attackedMe,
|
|
100
|
+
iAttacked: v.iAttacked,
|
|
101
|
+
reinforce: { n: r.n, e: r.e, extra: r.extra },
|
|
102
|
+
stack: s === null ? null : { top: s.top, total: s.total },
|
|
103
|
+
tookFromMe: took,
|
|
104
|
+
lostToMe: lost,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const seatsOf = (v) => isRec(v) && PROFILE_FORMATS.includes(v.format) && isInt(v.players) && ids(v.ai) && ids(v.turnedAI)
|
|
108
|
+
? { format: v.format, players: v.players, ai: ids(v.ai), turnedAI: ids(v.turnedAI) }
|
|
109
|
+
: undefined;
|
|
110
|
+
/** A game file as `playerId` saw it; `turns` empty when absent or unusable. */
|
|
111
|
+
async function readGameFile(dir, gameId, playerId) {
|
|
112
|
+
try {
|
|
113
|
+
const f = JSON.parse(await readFile(profileGamePath(dir, gameId, playerId), 'utf8'));
|
|
114
|
+
if (!isRec(f) || f.version !== 1 || f.gameId !== gameId || f.playerId !== playerId || !isRec(f.turns))
|
|
115
|
+
return { turns: {} };
|
|
116
|
+
const out = {};
|
|
117
|
+
for (const [t, byOpponent] of Object.entries(f.turns)) {
|
|
118
|
+
if (!/^\d+$/.test(t) || !isRec(byOpponent))
|
|
119
|
+
continue;
|
|
120
|
+
const kept = {};
|
|
121
|
+
for (const [o, p] of Object.entries(byOpponent)) {
|
|
122
|
+
const v = /^\d+$/.test(o) ? primitivesOf(p) : undefined;
|
|
123
|
+
if (v)
|
|
124
|
+
kept[o] = v;
|
|
125
|
+
}
|
|
126
|
+
out[t] = kept;
|
|
127
|
+
}
|
|
128
|
+
const seats = seatsOf(f.seats);
|
|
129
|
+
return {
|
|
130
|
+
turns: out,
|
|
131
|
+
...(seats ? { seats } : {}),
|
|
132
|
+
...(f.folded === 'live' || f.folded === 'history' ? { folded: f.folded } : {}),
|
|
133
|
+
...(f.backfill === true ? { backfill: true } : {}),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return { turns: {} };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** The stored turns of a game as `playerId` saw it; `{}` when absent or unusable. */
|
|
141
|
+
async function readTurns(dir, gameId, playerId) {
|
|
142
|
+
return (await readGameFile(dir, gameId, playerId)).turns;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Every turn stored for `gameId` as `playerId` saw it, by opponent, oldest turn first; an empty map
|
|
146
|
+
* when none, or when profiling is off. Never throws.
|
|
147
|
+
*/
|
|
148
|
+
export async function readProfileTurns(dir, gameId, playerId, env = process.env) {
|
|
149
|
+
const out = new Map();
|
|
150
|
+
if (!profileEnabled(env))
|
|
151
|
+
return out;
|
|
152
|
+
const turns = await readTurns(dir, gameId, playerId);
|
|
153
|
+
for (const t of Object.keys(turns).map(Number).sort((a, b) => a - b))
|
|
154
|
+
for (const [o, primitives] of Object.entries(turns[String(t)])) {
|
|
155
|
+
const list = out.get(Number(o)) ?? [];
|
|
156
|
+
list.push({ turn: t, primitives });
|
|
157
|
+
out.set(Number(o), list);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The turns `input.boards` lets me observe: one entry per pair of boards of consecutive turns T and
|
|
163
|
+
* T+1, the turn T, by opponent. A pair with a board read from GameFeed's `GetHistory` (`source:
|
|
164
|
+
* 'history'`, unverified for a game in progress) is not observed: stored primitives come from the
|
|
165
|
+
* live boards this server cached only (principle 6). Pure.
|
|
166
|
+
*/
|
|
167
|
+
export function observeBoards(input) {
|
|
168
|
+
const sorted = [...input.boards].sort((a, b) => a.turn - b.turn);
|
|
169
|
+
const out = new Map();
|
|
170
|
+
for (let i = 0; i + 1 < sorted.length; i++) {
|
|
171
|
+
const was = sorted[i];
|
|
172
|
+
const now = sorted[i + 1];
|
|
173
|
+
if (now.turn !== was.turn + 1 || was.source === 'history' || now.source === 'history')
|
|
174
|
+
continue;
|
|
175
|
+
out.set(was.turn, observeTurn({
|
|
176
|
+
graph: input.graph,
|
|
177
|
+
me: input.me,
|
|
178
|
+
previous: was.board,
|
|
179
|
+
current: now.board,
|
|
180
|
+
orders: was.orders,
|
|
181
|
+
settings: input.settings,
|
|
182
|
+
opponents: input.opponents,
|
|
183
|
+
...(input.cards !== undefined ? { cards: input.cards } : {}),
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Keep only the newest {@link MAX_PROFILE_GAME_FILES} game files, and none not written for
|
|
190
|
+
* {@link BOARD_CACHE_MAX_AGE_MS} (the board cache's own age rule: no id-bearing file outlives it,
|
|
191
|
+
* B2). Best effort.
|
|
192
|
+
*/
|
|
193
|
+
async function prune(dir, env) {
|
|
194
|
+
try {
|
|
195
|
+
const folder = profileGamesDir(dir);
|
|
196
|
+
const files = [];
|
|
197
|
+
for (const name of await readdir(folder)) {
|
|
198
|
+
const m = /^(\d+)-(\d+)\.json$/.exec(name);
|
|
199
|
+
if (!m)
|
|
200
|
+
continue;
|
|
201
|
+
const path = join(folder, name);
|
|
202
|
+
try {
|
|
203
|
+
files.push({ path, mtime: (await stat(path)).mtimeMs, gameId: Number(m[1]), playerId: Number(m[2]) });
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// Gone already.
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
files.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path));
|
|
210
|
+
const cutoff = Date.now() - BOARD_CACHE_MAX_AGE_MS;
|
|
211
|
+
for (const [i, f] of files.entries()) {
|
|
212
|
+
if (i < MAX_PROFILE_GAME_FILES && f.mtime >= cutoff)
|
|
213
|
+
continue;
|
|
214
|
+
// An unfolded game going out: folded first, every ending unknown (B2), when its seats were kept.
|
|
215
|
+
await withPathLock(f.path, async () => {
|
|
216
|
+
const file = await readGameFile(dir, f.gameId, f.playerId);
|
|
217
|
+
if (!file.folded && file.seats)
|
|
218
|
+
await foldFile(dir, f.gameId, f.playerId, file, file.seats, () => 'unknown', env);
|
|
219
|
+
await unlink(f.path).catch(() => undefined);
|
|
220
|
+
}).catch(() => undefined);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
// No folder yet.
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Observe every consecutive pair of `input.boards` and store each turn's record, overwriting that
|
|
229
|
+
* turn's entry (planning a turn twice rewrites, never adds); turns not observed this time stay.
|
|
230
|
+
* Every entry for one of `input.teammates` is dropped. Writes nothing when profiling is off, or when
|
|
231
|
+
* nothing could be observed and no teammate's entry was there. Never throws; `false` when nothing
|
|
232
|
+
* was written.
|
|
233
|
+
*/
|
|
234
|
+
export async function recordBehaviour(dir, input, env = process.env) {
|
|
235
|
+
if (!profileEnabled(env))
|
|
236
|
+
return false;
|
|
237
|
+
try {
|
|
238
|
+
const observed = observeBoards(input);
|
|
239
|
+
const friends = new Set((input.teammates ?? []).map(String));
|
|
240
|
+
if (!observed.size && !friends.size)
|
|
241
|
+
return false;
|
|
242
|
+
const path = profileGamePath(dir, input.gameId, input.me);
|
|
243
|
+
const written = await withPathLock(path, async () => {
|
|
244
|
+
const stored = await readGameFile(dir, input.gameId, input.me);
|
|
245
|
+
const turns = stored.turns;
|
|
246
|
+
// Never keep a teammate: an entry written while the teams were unknown goes now.
|
|
247
|
+
let dropped = false;
|
|
248
|
+
for (const entry of Object.values(turns))
|
|
249
|
+
for (const o of Object.keys(entry))
|
|
250
|
+
if (friends.has(o)) {
|
|
251
|
+
delete entry[o];
|
|
252
|
+
dropped = true;
|
|
253
|
+
}
|
|
254
|
+
if (!observed.size && !dropped)
|
|
255
|
+
return false;
|
|
256
|
+
for (const [t, byOpponent] of observed) {
|
|
257
|
+
const entry = {};
|
|
258
|
+
for (const [o, p] of [...byOpponent].sort(([a], [b]) => a - b))
|
|
259
|
+
if (!friends.has(String(o)))
|
|
260
|
+
entry[String(o)] = p;
|
|
261
|
+
turns[String(t)] = entry;
|
|
262
|
+
}
|
|
263
|
+
const seats = input.seats ?? stored.seats;
|
|
264
|
+
const body = {
|
|
265
|
+
version: 1,
|
|
266
|
+
gameId: input.gameId,
|
|
267
|
+
playerId: input.me,
|
|
268
|
+
turns,
|
|
269
|
+
...(seats ? { seats } : {}),
|
|
270
|
+
...(stored.folded ? { folded: stored.folded } : {}),
|
|
271
|
+
...(input.backfill || stored.backfill ? { backfill: true } : {}),
|
|
272
|
+
};
|
|
273
|
+
await writeGameFile(path, body);
|
|
274
|
+
return true;
|
|
275
|
+
});
|
|
276
|
+
if (written)
|
|
277
|
+
await prune(dir, env);
|
|
278
|
+
return written;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async function writeGameFile(path, body) {
|
|
285
|
+
await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });
|
|
286
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
287
|
+
await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
|
|
288
|
+
await rename(tmp, path);
|
|
289
|
+
}
|
|
290
|
+
// ---- across games (B2) ----
|
|
291
|
+
export { PROFILE_DECAY };
|
|
292
|
+
/** Per-game entries kept per player (the oldest dropped first; their counts stay in the totals). */
|
|
293
|
+
export const MAX_PROFILE_ENTRIES = 30;
|
|
294
|
+
/** Players kept (the least recently updated dropped first). */
|
|
295
|
+
export const MAX_PROFILE_PLAYERS = 1000;
|
|
296
|
+
/** Per-game entries the population keeps, so a game folded again replaces its own contribution. */
|
|
297
|
+
export const MAX_POPULATION_ENTRIES = 500;
|
|
298
|
+
export const profilePlayersPath = (dir) => join(dir, 'profiles', 'players.json');
|
|
299
|
+
export const profilePopulationPath = (dir) => join(dir, 'profiles', 'population.json');
|
|
300
|
+
/** One lock for both stores: a fold changes them together. */
|
|
301
|
+
const storeLock = (dir) => join(dir, 'profiles', '.store');
|
|
302
|
+
const ENDINGS = ['Won', 'SurrenderAccepted', 'Booted', 'Eliminated', 'EndedByVote'];
|
|
303
|
+
/** A player's final state as a profile ending (`PLAYER_STATE_NAMES`, src/player-states.ts): anything else is `unknown`. */
|
|
304
|
+
export function endingOf(state) {
|
|
305
|
+
return ENDINGS.includes(state ?? '') ? state : 'unknown';
|
|
306
|
+
}
|
|
307
|
+
const HASH = /^[0-9a-f]{32}$/;
|
|
308
|
+
const num = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
309
|
+
const rateOf = (v) => (isRec(v) && num(v.e) && num(v.n) ? { e: v.e, n: v.n } : undefined);
|
|
310
|
+
/** Stored counts, loosely: `undefined` when any is missing. */
|
|
311
|
+
function habitsFrom(v) {
|
|
312
|
+
if (!isRec(v))
|
|
313
|
+
return undefined;
|
|
314
|
+
const r = rateOf(v.reinforce);
|
|
315
|
+
const a = rateOf(v.attack);
|
|
316
|
+
const f = rateOf(v.firstStrike);
|
|
317
|
+
const rt = rateOf(v.retaliate);
|
|
318
|
+
const rk = rateOf(v.retake);
|
|
319
|
+
const x = v.reinforceExtra;
|
|
320
|
+
const s = v.stacking;
|
|
321
|
+
if (!r || !a || !f || !rt || !rk || !num(v.turns))
|
|
322
|
+
return undefined;
|
|
323
|
+
if (!isRec(x) || !num(x.n) || !num(x.sum) || !isRec(s) || !num(s.n) || !num(s.sum) || !num(s.sq))
|
|
324
|
+
return undefined;
|
|
325
|
+
return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, turns: v.turns };
|
|
326
|
+
}
|
|
327
|
+
function totalsFrom(v) {
|
|
328
|
+
const out = {};
|
|
329
|
+
if (!isRec(v))
|
|
330
|
+
return out;
|
|
331
|
+
for (const f of PROFILE_FORMATS) {
|
|
332
|
+
const h = habitsFrom(v[f]);
|
|
333
|
+
if (h)
|
|
334
|
+
out[f] = h;
|
|
335
|
+
}
|
|
336
|
+
return out;
|
|
337
|
+
}
|
|
338
|
+
const isFormat = (v) => PROFILE_FORMATS.includes(v);
|
|
339
|
+
function entryFrom(v) {
|
|
340
|
+
if (!isRec(v) || typeof v.key !== 'string' || !HASH.test(v.key) || !isFormat(v.format) || !isInt(v.players) || !isInt(v.turnsSeen))
|
|
341
|
+
return undefined;
|
|
342
|
+
if ((v.source !== 'live' && v.source !== 'history') || !num(v.weight))
|
|
343
|
+
return undefined;
|
|
344
|
+
const habits = habitsFrom(v.habits);
|
|
345
|
+
if (!habits)
|
|
346
|
+
return undefined;
|
|
347
|
+
const ending = v.ending === 'unknown' || ENDINGS.includes(v.ending) ? v.ending : undefined;
|
|
348
|
+
return { key: v.key, format: v.format, players: v.players, turnsSeen: v.turnsSeen, source: v.source, habits, ...(ending ? { ending } : {}), weight: v.weight };
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Read a store: `missing` (empty), the parsed object, or `unreadable` (exists, not JSON or not an
|
|
352
|
+
* object). Callers refuse a wrong version as `unreadable` and read the rest loosely: a malformed part
|
|
353
|
+
* is dropped, never a reason to refuse the store.
|
|
354
|
+
*/
|
|
355
|
+
async function readStore(path) {
|
|
356
|
+
let text;
|
|
357
|
+
try {
|
|
358
|
+
text = await readFile(path, 'utf8');
|
|
359
|
+
}
|
|
360
|
+
catch (e) {
|
|
361
|
+
return e.code === 'ENOENT' ? 'missing' : 'unreadable';
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
const v = JSON.parse(text);
|
|
365
|
+
return isRec(v) ? v : 'unreadable';
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
return 'unreadable';
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async function readPlayers(dir) {
|
|
372
|
+
const v = await readStore(profilePlayersPath(dir));
|
|
373
|
+
if (v === 'unreadable')
|
|
374
|
+
return v;
|
|
375
|
+
if (v === 'missing')
|
|
376
|
+
return { version: 1, seq: 0, players: {} };
|
|
377
|
+
if (v.version !== 1 || !isRec(v.players))
|
|
378
|
+
return 'unreadable';
|
|
379
|
+
const players = {};
|
|
380
|
+
for (const [k, p] of Object.entries(v.players)) {
|
|
381
|
+
if (!HASH.test(k) || !isRec(p) || !isInt(p.seq) || !isInt(p.games) || !Array.isArray(p.entries))
|
|
382
|
+
continue;
|
|
383
|
+
players[k] = { seq: p.seq, games: p.games, totals: totalsFrom(p.totals), entries: p.entries.map(entryFrom).filter((e) => e !== undefined) };
|
|
384
|
+
}
|
|
385
|
+
return { version: 1, seq: isInt(v.seq) ? v.seq : 0, players };
|
|
386
|
+
}
|
|
387
|
+
async function readPopulation(dir) {
|
|
388
|
+
const v = await readStore(profilePopulationPath(dir));
|
|
389
|
+
if (v === 'unreadable')
|
|
390
|
+
return v;
|
|
391
|
+
if (v === 'missing')
|
|
392
|
+
return { version: 1, games: 0, totals: {}, ai: emptyHabits(), entries: [] };
|
|
393
|
+
if (v.version !== 1)
|
|
394
|
+
return 'unreadable';
|
|
395
|
+
const entries = [];
|
|
396
|
+
for (const e of Array.isArray(v.entries) ? v.entries : []) {
|
|
397
|
+
if (!isRec(e) || typeof e.key !== 'string' || !HASH.test(e.key) || !isFormat(e.format))
|
|
398
|
+
continue;
|
|
399
|
+
if (e.source !== 'live' && e.source !== 'history')
|
|
400
|
+
continue;
|
|
401
|
+
const humans = habitsFrom(e.humans);
|
|
402
|
+
const ai = habitsFrom(e.ai);
|
|
403
|
+
if (humans && ai)
|
|
404
|
+
entries.push({ key: e.key, format: e.format, source: e.source, humans, ai });
|
|
405
|
+
}
|
|
406
|
+
return { version: 1, games: isInt(v.games) ? v.games : 0, totals: totalsFrom(v.totals), ai: habitsFrom(v.ai) ?? emptyHabits(), entries };
|
|
407
|
+
}
|
|
408
|
+
async function writeStore(path, body) {
|
|
409
|
+
await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });
|
|
410
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
411
|
+
await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
|
|
412
|
+
await rename(tmp, path);
|
|
413
|
+
}
|
|
414
|
+
const sumOf = (list) => list.reduce((a, h) => addHabits(a, h), emptyHabits());
|
|
415
|
+
const sumTotals = (t) => sumOf(PROFILE_FORMATS.flatMap((f) => (t[f] ? [t[f]] : [])));
|
|
416
|
+
const bump = (t, f, h, scale) => {
|
|
417
|
+
t[f] = addHabits(t[f] ?? emptyHabits(), h, scale);
|
|
418
|
+
};
|
|
419
|
+
/**
|
|
420
|
+
* Fold one game into the cross-game stores (B2): each human seat's entry under its player key,
|
|
421
|
+
* the totals moved by the difference from the entry already stored for this game (zero the first
|
|
422
|
+
* time), a player's totals faded once when the game is new to it; AI seats into the AI pool only. A
|
|
423
|
+
* `live` entry never replaces a `history` one. `folded` when written; `off` when profiling is off;
|
|
424
|
+
* `failed` when it could not be (a store or salt that is not JSON, not an object or not version 1 is
|
|
425
|
+
* never overwritten; malformed parts inside a version-1 store are dropped on read, so they are not
|
|
426
|
+
* written back). Idempotent only while this game's entry is still stored (see the file header). Never
|
|
427
|
+
* throws.
|
|
428
|
+
*/
|
|
429
|
+
export async function foldGame(dir, input, env = process.env) {
|
|
430
|
+
if (!profileEnabled(env))
|
|
431
|
+
return 'off';
|
|
432
|
+
try {
|
|
433
|
+
return await withPathLock(storeLock(dir), async () => {
|
|
434
|
+
const players = await readPlayers(dir);
|
|
435
|
+
const population = await readPopulation(dir);
|
|
436
|
+
if (players === 'unreadable' || population === 'unreadable')
|
|
437
|
+
return 'failed';
|
|
438
|
+
const salt = await playerSaltForWrite(dir);
|
|
439
|
+
if (!salt)
|
|
440
|
+
return 'failed';
|
|
441
|
+
const key = profileGameKey(salt, input.me, input.gameId);
|
|
442
|
+
const seats = [...input.seats].sort((a, b) => a.id - b.id);
|
|
443
|
+
// Each human seat, under its player key.
|
|
444
|
+
for (const seat of seats) {
|
|
445
|
+
if (seat.ai)
|
|
446
|
+
continue;
|
|
447
|
+
const pk = playerKey(salt, seat.id);
|
|
448
|
+
const p = players.players[pk] ?? { seq: 0, games: 0, totals: {}, entries: [] };
|
|
449
|
+
const old = p.entries.find((e) => e.key === key);
|
|
450
|
+
if (old?.source === 'history' && input.source === 'live')
|
|
451
|
+
continue;
|
|
452
|
+
if (!old) {
|
|
453
|
+
// A game new to this player: everything before it fades once.
|
|
454
|
+
for (const f of PROFILE_FORMATS)
|
|
455
|
+
if (p.totals[f])
|
|
456
|
+
p.totals[f] = scaleHabits(p.totals[f], PROFILE_DECAY);
|
|
457
|
+
for (const e of p.entries)
|
|
458
|
+
e.weight = Math.round(e.weight * PROFILE_DECAY * 1e9) / 1e9;
|
|
459
|
+
p.games++;
|
|
460
|
+
}
|
|
461
|
+
const weight = old?.weight ?? 1;
|
|
462
|
+
if (old)
|
|
463
|
+
bump(p.totals, old.format, old.habits, -old.weight);
|
|
464
|
+
bump(p.totals, input.format, seat.habits, weight);
|
|
465
|
+
const entry = {
|
|
466
|
+
key,
|
|
467
|
+
format: input.format,
|
|
468
|
+
players: input.players,
|
|
469
|
+
turnsSeen: seat.habits.turns,
|
|
470
|
+
source: input.source,
|
|
471
|
+
habits: seat.habits,
|
|
472
|
+
ending: seat.ending,
|
|
473
|
+
weight,
|
|
474
|
+
};
|
|
475
|
+
p.entries = [...p.entries.filter((e) => e.key !== key), entry].slice(-MAX_PROFILE_ENTRIES);
|
|
476
|
+
p.seq = ++players.seq;
|
|
477
|
+
players.players[pk] = p;
|
|
478
|
+
}
|
|
479
|
+
// The population: humans by format, AIs pooled; replaced as a whole for a game folded again.
|
|
480
|
+
const humans = sumOf(seats.filter((s) => !s.ai).map((s) => s.habits));
|
|
481
|
+
const ai = sumOf(seats.filter((s) => s.ai).map((s) => s.habits));
|
|
482
|
+
const old = population.entries.find((e) => e.key === key);
|
|
483
|
+
if (!(old?.source === 'history' && input.source === 'live')) {
|
|
484
|
+
if (old) {
|
|
485
|
+
bump(population.totals, old.format, old.humans, -1);
|
|
486
|
+
population.ai = addHabits(population.ai, old.ai, -1);
|
|
487
|
+
}
|
|
488
|
+
else
|
|
489
|
+
population.games++;
|
|
490
|
+
bump(population.totals, input.format, humans, 1);
|
|
491
|
+
population.ai = addHabits(population.ai, ai, 1);
|
|
492
|
+
population.entries = [...population.entries.filter((e) => e.key !== key), { key, format: input.format, source: input.source, humans, ai }].slice(-MAX_POPULATION_ENTRIES);
|
|
493
|
+
}
|
|
494
|
+
for (const f of PROFILE_FORMATS)
|
|
495
|
+
if (population.totals[f] && isEmpty(population.totals[f]))
|
|
496
|
+
delete population.totals[f];
|
|
497
|
+
// Bound the players: the least recently updated go first.
|
|
498
|
+
const keys = Object.keys(players.players)
|
|
499
|
+
.sort((a, b) => players.players[b].seq - players.players[a].seq || (a < b ? -1 : 1))
|
|
500
|
+
.slice(0, MAX_PROFILE_PLAYERS)
|
|
501
|
+
.sort();
|
|
502
|
+
await writeStore(profilePlayersPath(dir), { version: 1, seq: players.seq, players: Object.fromEntries(keys.map((k) => [k, players.players[k]])) });
|
|
503
|
+
await writeStore(profilePopulationPath(dir), population);
|
|
504
|
+
return 'folded';
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
return 'failed';
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
const isEmpty = (h) => JSON.stringify(h) === JSON.stringify(emptyHabits());
|
|
512
|
+
/**
|
|
513
|
+
* The cross-game record for `ids`, with `game` (when given: my account and the game being read) left
|
|
514
|
+
* out of each player's past and its games count. Empty when nothing is on record (a read never makes
|
|
515
|
+
* the salt); `unreadable` when a store or the salt cannot be parsed; `off` when profiling is off.
|
|
516
|
+
* Never throws, never writes.
|
|
517
|
+
*/
|
|
518
|
+
export async function readProfileHistory(dir, ids, game, env = process.env) {
|
|
519
|
+
if (!profileEnabled(env))
|
|
520
|
+
return 'off';
|
|
521
|
+
try {
|
|
522
|
+
const players = await readPlayers(dir);
|
|
523
|
+
const population = await readPopulation(dir);
|
|
524
|
+
if (players === 'unreadable' || population === 'unreadable')
|
|
525
|
+
return 'unreadable';
|
|
526
|
+
const pools = { byFormat: population.totals, all: sumTotals(population.totals), ai: population.ai, games: population.games };
|
|
527
|
+
const out = { players: new Map(), pools };
|
|
528
|
+
const saltText = await readFile(playerRecordSaltPath(dir), 'utf8').catch((e) => (e.code === 'ENOENT' ? null : ''));
|
|
529
|
+
if (saltText === null)
|
|
530
|
+
return out;
|
|
531
|
+
const salt = await playerRecordSalt(dir);
|
|
532
|
+
if (!salt)
|
|
533
|
+
return 'unreadable';
|
|
534
|
+
const thisGame = game.me !== undefined && game.gameId !== undefined ? profileGameKey(salt, game.me, game.gameId) : undefined;
|
|
535
|
+
for (const id of ids) {
|
|
536
|
+
const p = players.players[playerKey(salt, id)];
|
|
537
|
+
if (!p)
|
|
538
|
+
continue;
|
|
539
|
+
const own = thisGame ? p.entries.find((e) => e.key === thisGame) : undefined;
|
|
540
|
+
let past = sumTotals(p.totals);
|
|
541
|
+
if (own)
|
|
542
|
+
past = addHabits(past, own.habits, -own.weight);
|
|
543
|
+
const games = p.games - (own ? 1 : 0);
|
|
544
|
+
if (games > 0 || !isEmpty(past))
|
|
545
|
+
out.players.set(id, { games, past });
|
|
546
|
+
}
|
|
547
|
+
return out;
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return 'unreadable';
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/** Fold one stored game file. Marks nothing. */
|
|
554
|
+
async function foldFile(dir, gameId, me, file, seats, ending, env) {
|
|
555
|
+
const byOpponent = new Map();
|
|
556
|
+
for (const t of Object.keys(file.turns).map(Number).sort((a, b) => a - b))
|
|
557
|
+
for (const [o, primitives] of Object.entries(file.turns[String(t)])) {
|
|
558
|
+
const list = byOpponent.get(Number(o)) ?? [];
|
|
559
|
+
list.push({ turn: t, primitives });
|
|
560
|
+
byOpponent.set(Number(o), list);
|
|
561
|
+
}
|
|
562
|
+
const turned = new Set(seats.turnedAI);
|
|
563
|
+
const ai = new Set(seats.ai);
|
|
564
|
+
const out = [];
|
|
565
|
+
for (const [id, turns] of [...byOpponent].sort(([a], [b]) => a - b)) {
|
|
566
|
+
if (id === me || turned.has(id))
|
|
567
|
+
continue;
|
|
568
|
+
out.push({ id, ai: ai.has(id), habits: habitsOf(turns), ending: ending(id) });
|
|
569
|
+
}
|
|
570
|
+
if (!out.length)
|
|
571
|
+
return 'folded';
|
|
572
|
+
return foldGame(dir, { me, gameId, format: seats.format, players: seats.players, source: 'live', seats: out }, env);
|
|
573
|
+
}
|
|
574
|
+
/** The seats of `game` as a fold reads them. */
|
|
575
|
+
export function profileSeatsOf(game) {
|
|
576
|
+
return {
|
|
577
|
+
format: profileFormatOf(game.players),
|
|
578
|
+
players: game.players.filter((p) => holdsSeat(p.state)).length,
|
|
579
|
+
ai: game.players.filter((p) => p.isAI).map((p) => p.id).sort((a, b) => a - b),
|
|
580
|
+
turnedAI: game.players.filter((p) => p.humanTurnedIntoAI).map((p) => p.id).sort((a, b) => a - b),
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* The seats a finished read folds under. GameFeed's team field is unverified (the profile tool
|
|
585
|
+
* resolves teams from GetMyGames when it is missing), so a read with no team carries no evidence
|
|
586
|
+
* about the format: the format and seat count recorded from the team-resolved game stand, and only
|
|
587
|
+
* the AI seats come from the final read.
|
|
588
|
+
*/
|
|
589
|
+
function seatsForFold(raw, recorded, rawHasTeams) {
|
|
590
|
+
if (rawHasTeams || !recorded)
|
|
591
|
+
return raw;
|
|
592
|
+
return { ...raw, format: recorded.format, players: recorded.players };
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* On a read that shows `game` finished: fold every per-game file of it not folded yet (one per
|
|
596
|
+
* account of mine that recorded it), with each player's final state as its ending, and mark it
|
|
597
|
+
* `folded: 'live'`. Only opponents in GameFeed's player list, never a teammate, never a human who
|
|
598
|
+
* became an AI. The number of files folded; 0 when the game is not finished, profiling is off, or
|
|
599
|
+
* nothing was there. Never throws.
|
|
600
|
+
*/
|
|
601
|
+
export async function foldFinishedGame(dir, game, env = process.env) {
|
|
602
|
+
if (!profileEnabled(env) || game.state !== 'Finished')
|
|
603
|
+
return 0;
|
|
604
|
+
let folded = 0;
|
|
605
|
+
try {
|
|
606
|
+
const prefix = `${game.id}-`;
|
|
607
|
+
const names = (await readdir(profileGamesDir(dir)).catch(() => [])).filter((n) => n.startsWith(prefix) && /^\d+-\d+\.json$/.test(n)).sort();
|
|
608
|
+
const raw = profileSeatsOf(game);
|
|
609
|
+
const byId = new Map(game.players.map((p) => [p.id, p]));
|
|
610
|
+
for (const name of names) {
|
|
611
|
+
const me = Number(name.slice(prefix.length, -'.json'.length));
|
|
612
|
+
const mePlayer = byId.get(me);
|
|
613
|
+
if (!mePlayer)
|
|
614
|
+
continue;
|
|
615
|
+
const friends = new Set(teammatesOf(game.players, mePlayer).map((p) => p.id));
|
|
616
|
+
const path = profileGamePath(dir, game.id, me);
|
|
617
|
+
const done = await withPathLock(path, async () => {
|
|
618
|
+
const file = await readGameFile(dir, game.id, me);
|
|
619
|
+
if (file.folded)
|
|
620
|
+
return false;
|
|
621
|
+
const seats = seatsForFold(raw, file.seats, isTeamGame(game.players));
|
|
622
|
+
// Only players of this game, never a teammate.
|
|
623
|
+
const turns = {};
|
|
624
|
+
for (const [t, byOpponent] of Object.entries(file.turns))
|
|
625
|
+
turns[t] = Object.fromEntries(Object.entries(byOpponent).filter(([o]) => byId.has(Number(o)) && !friends.has(Number(o))));
|
|
626
|
+
const r = await foldFile(dir, game.id, me, { turns }, seats, (id) => endingOf(byId.get(id)?.state), env);
|
|
627
|
+
if (r !== 'folded')
|
|
628
|
+
return false;
|
|
629
|
+
await writeGameFile(path, { version: 1, gameId: game.id, playerId: me, turns: file.turns, seats, folded: 'live', ...(file.backfill ? { backfill: true } : {}) });
|
|
630
|
+
return true;
|
|
631
|
+
});
|
|
632
|
+
if (done)
|
|
633
|
+
folded++;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
// Best effort.
|
|
638
|
+
}
|
|
639
|
+
return folded;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* The per-game file of `gameId` as `playerId` saw it (#264): `none` when there is none, `folded` when
|
|
643
|
+
* it was folded, else `kept`. Never throws (an unreadable file reads as `kept`: never backfilled over).
|
|
644
|
+
*/
|
|
645
|
+
export async function profileFileState(dir, gameId, playerId) {
|
|
646
|
+
try {
|
|
647
|
+
await stat(profileGamePath(dir, gameId, playerId));
|
|
648
|
+
}
|
|
649
|
+
catch (e) {
|
|
650
|
+
return e.code === 'ENOENT' ? 'none' : 'kept';
|
|
651
|
+
}
|
|
652
|
+
return (await readGameFile(dir, gameId, playerId)).folded ? 'folded' : 'kept';
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Whether the cross-game stores already hold `gameId` as folded by `me` (#264: a per-game file the
|
|
656
|
+
* age rule or the file bound removed after its fold). Reads the population's entries under the game's
|
|
657
|
+
* key; `false` when no salt was ever made. A store or salt that cannot be read counts as folded, so a
|
|
658
|
+
* backfill never runs over it. Never throws, never writes.
|
|
659
|
+
*/
|
|
660
|
+
export async function profileGameFolded(dir, me, gameId) {
|
|
661
|
+
try {
|
|
662
|
+
const population = await readPopulation(dir);
|
|
663
|
+
if (population === 'unreadable')
|
|
664
|
+
return true;
|
|
665
|
+
const saltText = await readFile(playerRecordSaltPath(dir), 'utf8').catch((e) => (e.code === 'ENOENT' ? null : ''));
|
|
666
|
+
if (saltText === null)
|
|
667
|
+
return false;
|
|
668
|
+
const salt = await playerRecordSalt(dir);
|
|
669
|
+
if (!salt)
|
|
670
|
+
return true;
|
|
671
|
+
const key = profileGameKey(salt, me, gameId);
|
|
672
|
+
return population.entries.some((e) => e.key === key);
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return true;
|
|
676
|
+
}
|
|
677
|
+
}
|