@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,22 @@
|
|
|
1
|
+
// An in-process lock per file path, for the read-modify-write stores (the agreement ledger and the
|
|
2
|
+
// cross-game player record): two tool calls in this process that read, change and write the same
|
|
3
|
+
// file run one after the other, so neither write loses the other's change. It serialises this
|
|
4
|
+
// process only; another process sharing the data directory is not covered (writes stay atomic, so a
|
|
5
|
+
// file is never torn, but the later writer wins).
|
|
6
|
+
const tails = new Map();
|
|
7
|
+
/** Run `fn` once every earlier section on `path` in this process has finished (thrown or not). */
|
|
8
|
+
export async function withPathLock(path, fn) {
|
|
9
|
+
const previous = tails.get(path) ?? Promise.resolve();
|
|
10
|
+
let release;
|
|
11
|
+
const tail = previous.then(() => new Promise((resolve) => (release = resolve)));
|
|
12
|
+
tails.set(path, tail);
|
|
13
|
+
await previous;
|
|
14
|
+
try {
|
|
15
|
+
return await fn();
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
release();
|
|
19
|
+
if (tails.get(path) === tail)
|
|
20
|
+
tails.delete(path);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// My pick list of a game, kept so the award can be read from it (#166, src/analysis/award.ts).
|
|
2
|
+
//
|
|
3
|
+
// war.app serves a player's picks while territories are being distributed; whether it still does
|
|
4
|
+
// afterwards is not verified, and the award can only be read against the list it used. So the
|
|
5
|
+
// list is written here when this server reads it back from war.app (after warapp_submit_picks,
|
|
6
|
+
// or by warapp_get_my_picks during distribution), at `<dataDir>/picks/<gameId>.json`, with the
|
|
7
|
+
// award read from it on the first board after distribution. The same file keeps the territories
|
|
8
|
+
// the live board showed as pickable during distribution (written by warapp_plan_picks and by
|
|
9
|
+
// warapp_submit_picks' preview): once the game starts nothing says where a player could have
|
|
10
|
+
// started, and warapp_locate_opponents needs it. #201: beside them, the neutrals the picking board
|
|
11
|
+
// showed and their armies, so a neutral the fog hides later (a wasteland) keeps a known size for the
|
|
12
|
+
// turn planner. A record may hold any of these. Territory ids
|
|
13
|
+
// only: no names, no other player's data. Best effort and never throws; a game's file not
|
|
14
|
+
// written for 60 days is deleted on the first write of a process.
|
|
15
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { OWNER_NEUTRAL } from './live.js';
|
|
18
|
+
/** Where a game's pick list is kept. */
|
|
19
|
+
export const pickListPath = (dir, gameId) => join(dir, 'picks', `${gameId}.json`);
|
|
20
|
+
/** A game's pick list not written for this long is deleted (finished or abandoned games). */
|
|
21
|
+
export const PICK_LIST_MAX_AGE_MS = 60 * 86_400_000;
|
|
22
|
+
const PICK_FILE = /^\d+\.json$/;
|
|
23
|
+
/** Pick directories pruned by this process: once is enough. */
|
|
24
|
+
const pruned = new Set();
|
|
25
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
26
|
+
const isId = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v > 0;
|
|
27
|
+
const isIds = (v) => Array.isArray(v) && v.every(isId);
|
|
28
|
+
const isArmies = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
29
|
+
/** `[territory, armies]` pairs, the malformed dropped, each territory once (the first), ascending. */
|
|
30
|
+
function neutralsOf(v) {
|
|
31
|
+
if (!Array.isArray(v))
|
|
32
|
+
return undefined;
|
|
33
|
+
const seen = new Map();
|
|
34
|
+
for (const e of v)
|
|
35
|
+
if (Array.isArray(e) && e.length === 2 && isId(e[0]) && isArmies(e[1]) && !seen.has(e[0]))
|
|
36
|
+
seen.set(e[0], e[1]);
|
|
37
|
+
return seen.size ? [...seen].sort((a, b) => a[0] - b[0]) : undefined;
|
|
38
|
+
}
|
|
39
|
+
/** A stored award, loosely: anything that does not look like one is dropped. */
|
|
40
|
+
function awardOf(v) {
|
|
41
|
+
if (v === null)
|
|
42
|
+
return null;
|
|
43
|
+
if (!isRec(v) || !isIds(v.granted) || !isIds(v.unlisted) || !isIds(v.opponentStarts))
|
|
44
|
+
return undefined;
|
|
45
|
+
if (typeof v.allStartsKnown !== 'boolean')
|
|
46
|
+
return undefined;
|
|
47
|
+
if (v.role !== null && v.role !== 'first' && v.role !== 'second')
|
|
48
|
+
return undefined;
|
|
49
|
+
if (v.opponentFirstAward !== null && !isId(v.opponentFirstAward))
|
|
50
|
+
return undefined;
|
|
51
|
+
return {
|
|
52
|
+
granted: v.granted,
|
|
53
|
+
unlisted: v.unlisted,
|
|
54
|
+
opponentStarts: v.opponentStarts,
|
|
55
|
+
allStartsKnown: v.allStartsKnown,
|
|
56
|
+
role: v.role,
|
|
57
|
+
opponentFirstAward: v.opponentFirstAward,
|
|
58
|
+
// A team game's (C2): kept only when it reads as ids.
|
|
59
|
+
...(isIds(v.teammateStarts) ? { teammateStarts: v.teammateStarts } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The record kept for `gameId` when it is `playerId`'s: the pick list, the pickable territories, or
|
|
64
|
+
* both; `undefined` when absent or when it holds neither. An award is read only beside a list.
|
|
65
|
+
* Never throws.
|
|
66
|
+
*/
|
|
67
|
+
export async function readPickRecord(dir, gameId, playerId) {
|
|
68
|
+
try {
|
|
69
|
+
const c = JSON.parse(await readFile(pickListPath(dir, gameId), 'utf8'));
|
|
70
|
+
if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId)
|
|
71
|
+
return undefined;
|
|
72
|
+
const list = isIds(c.list) && c.list.length ? c.list : undefined;
|
|
73
|
+
const pickable = isIds(c.pickable) && c.pickable.length ? c.pickable : undefined;
|
|
74
|
+
const neutrals = neutralsOf(c.neutrals);
|
|
75
|
+
if (!list && !pickable)
|
|
76
|
+
return undefined;
|
|
77
|
+
const award = list ? awardOf(c.award) : undefined;
|
|
78
|
+
return {
|
|
79
|
+
gameId,
|
|
80
|
+
playerId,
|
|
81
|
+
...(list ? { list } : {}),
|
|
82
|
+
...(pickable ? { pickable } : {}),
|
|
83
|
+
...(neutrals ? { neutrals } : {}),
|
|
84
|
+
...(award !== undefined ? { award } : {}),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Delete the pick lists of games not written for {@link PICK_LIST_MAX_AGE_MS}. Best effort. */
|
|
92
|
+
async function prunePickLists(dir) {
|
|
93
|
+
const picks = join(dir, 'picks');
|
|
94
|
+
if (pruned.has(picks))
|
|
95
|
+
return;
|
|
96
|
+
pruned.add(picks);
|
|
97
|
+
const cutoff = Date.now() - PICK_LIST_MAX_AGE_MS;
|
|
98
|
+
try {
|
|
99
|
+
for (const name of await readdir(picks)) {
|
|
100
|
+
if (!PICK_FILE.test(name))
|
|
101
|
+
continue;
|
|
102
|
+
const file = join(picks, name);
|
|
103
|
+
try {
|
|
104
|
+
if ((await stat(file)).mtimeMs < cutoff)
|
|
105
|
+
await unlink(file);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// Gone already, or unreadable: leave it.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// No pick directory yet.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function writeRecord(dir, record) {
|
|
117
|
+
try {
|
|
118
|
+
const path = pickListPath(dir, record.gameId);
|
|
119
|
+
await mkdir(join(dir, 'picks'), { recursive: true, mode: 0o700 });
|
|
120
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
121
|
+
await writeFile(tmp, JSON.stringify(record), { mode: 0o600 });
|
|
122
|
+
await rename(tmp, path);
|
|
123
|
+
await prunePickLists(dir);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const sameIds = (a, b) => a !== undefined && a.length === b.length && a.every((t, i) => t === b[i]);
|
|
131
|
+
/**
|
|
132
|
+
* Keep `list` as `playerId`'s picks for `gameId`. The same list already kept stays as it is (its
|
|
133
|
+
* award too); a different one replaces it and drops the award read from the old one. The pickable
|
|
134
|
+
* territories kept beside it stay. Never throws.
|
|
135
|
+
*/
|
|
136
|
+
export async function writePickList(dir, gameId, playerId, list) {
|
|
137
|
+
if (!list.length || !isIds([...list]))
|
|
138
|
+
return false;
|
|
139
|
+
const kept = await readPickRecord(dir, gameId, playerId);
|
|
140
|
+
if (sameIds(kept?.list, list))
|
|
141
|
+
return true;
|
|
142
|
+
return writeRecord(dir, {
|
|
143
|
+
gameId,
|
|
144
|
+
playerId,
|
|
145
|
+
list: [...list],
|
|
146
|
+
...(kept?.pickable ? { pickable: kept.pickable } : {}),
|
|
147
|
+
...(kept?.neutrals ? { neutrals: kept.neutrals } : {}),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/** Keep the award read from the stored list (`null`: nothing could be read). False when no list is kept for this player. */
|
|
151
|
+
export async function writeAward(dir, gameId, playerId, award) {
|
|
152
|
+
const kept = await readPickRecord(dir, gameId, playerId);
|
|
153
|
+
if (!kept?.list)
|
|
154
|
+
return false;
|
|
155
|
+
return writeRecord(dir, {
|
|
156
|
+
gameId,
|
|
157
|
+
playerId,
|
|
158
|
+
list: kept.list,
|
|
159
|
+
...(kept.pickable ? { pickable: kept.pickable } : {}),
|
|
160
|
+
...(kept.neutrals ? { neutrals: kept.neutrals } : {}),
|
|
161
|
+
award,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Keep the territories the live board showed as pickable for `gameId` (ascending, each once),
|
|
166
|
+
* beside `playerId`'s list and its award when those are kept, and (#201) the picking board's
|
|
167
|
+
* neutrals with their armies when given (else those already kept stay). The same sets already
|
|
168
|
+
* kept stay as they are. Never throws.
|
|
169
|
+
*/
|
|
170
|
+
export async function writePickable(dir, gameId, playerId, pickable, neutralArmies) {
|
|
171
|
+
if (!pickable.length || !isIds([...pickable]))
|
|
172
|
+
return false;
|
|
173
|
+
const ids = [...new Set(pickable)].sort((a, b) => a - b);
|
|
174
|
+
const kept = await readPickRecord(dir, gameId, playerId);
|
|
175
|
+
const neutrals = neutralsOf(neutralArmies) ?? kept?.neutrals;
|
|
176
|
+
if (sameIds(kept?.pickable, ids) && JSON.stringify(kept?.neutrals) === JSON.stringify(neutrals))
|
|
177
|
+
return true;
|
|
178
|
+
return writeRecord(dir, {
|
|
179
|
+
gameId,
|
|
180
|
+
playerId,
|
|
181
|
+
...(kept?.list ? { list: kept.list } : {}),
|
|
182
|
+
pickable: ids,
|
|
183
|
+
...(neutrals ? { neutrals } : {}),
|
|
184
|
+
...(kept?.list && kept.award !== undefined ? { award: kept.award } : {}),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/** #201: the neutrals a live board shows with their armies (fogged ones left out), ascending by territory. */
|
|
188
|
+
export function pickingNeutrals(board) {
|
|
189
|
+
return board
|
|
190
|
+
.filter((t) => !t.fogged && t.owner === OWNER_NEUTRAL && t.armies !== null)
|
|
191
|
+
.map((t) => [t.territoryId, t.armies])
|
|
192
|
+
.sort((a, b) => a[0] - b[0]);
|
|
193
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// The cross-game player record on disk (docs/PLAN-TEAMS.md A2, owner decision D5 of 2026-11-14: ON,
|
|
2
|
+
// local and hosted — a hosted child keeps it in its per-user data dir, `state.dataDir` in mint.yaml).
|
|
3
|
+
// At `<dataDir>/relations/players.json` (version 3): per player, the name-free entries and the
|
|
4
|
+
// tallies of `src/analysis/player-record.ts`, and when they last changed. The player is keyed by an
|
|
5
|
+
// HMAC of its GameFeed id under a local secret salt (`<dataDir>/relations/players.salt`, 0600), and
|
|
6
|
+
// each entry by an HMAC of my account, the game and the agreement (the ledger is per account, so two
|
|
7
|
+
// accounts sharing a data dir never collide; entries written before the account was in the key are
|
|
8
|
+
// read as they are, `legacyEntryKey`): the file holds no player id, game id or name, and without the
|
|
9
|
+
// salt it cannot be joined to a game or a player.
|
|
10
|
+
//
|
|
11
|
+
// The salt is made only on the write path, never by a read; a salt file that exists but is
|
|
12
|
+
// malformed is never replaced (that would orphan every key on record): reads say `unreadable` and
|
|
13
|
+
// writes fail until the owner fixes or removes it. A record file that exists but cannot be read or
|
|
14
|
+
// parsed (bad JSON, not an object, no `players` object) is treated the same way — never moved aside,
|
|
15
|
+
// never overwritten, since writing over it would drop every other player's data: reads say
|
|
16
|
+
// `unreadable` and writes fail until the owner fixes or removes it. A missing file is empty.
|
|
17
|
+
//
|
|
18
|
+
// Bounded (`MAX_RECORD_ENTRIES` per player, `MAX_RECORD_PLAYERS` players). Isolated so it can be
|
|
19
|
+
// switched off: `WARAPP_PLAYER_RECORD=off` (or `0` / `false` / `no`) and nothing here reads or
|
|
20
|
+
// writes. Reads are loose (versions 1 and 2 are read too; an unusable player or entry is dropped);
|
|
21
|
+
// every write is atomic and runs under the in-process path lock (src/path-lock.ts). Never throws.
|
|
22
|
+
import { createHmac, randomBytes, randomUUID } from 'node:crypto';
|
|
23
|
+
import { link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
24
|
+
import { join } from 'node:path';
|
|
25
|
+
import { readEnvVar } from '@chrischall/mcp-utils';
|
|
26
|
+
import { addCounts, COUNT_KEYS, MAX_RECORD_PLAYERS, talliesOf, upsertEntry, ZERO_COUNTS, } from './analysis/player-record.js';
|
|
27
|
+
import { withPathLock } from './path-lock.js';
|
|
28
|
+
import { relationsDir } from './relations-store.js';
|
|
29
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
30
|
+
const SALT = /^[0-9a-f]{32}$/;
|
|
31
|
+
const HASH = /^[0-9a-f]{32}$/;
|
|
32
|
+
const OUTCOMES = new Set(['open', 'not-agreed', 'kept', 'ended-with-notice', 'broken-by-them', 'broken-by-me']);
|
|
33
|
+
export const playerRecordPath = (dir) => join(relationsDir(dir), 'players.json');
|
|
34
|
+
export const playerRecordSaltPath = (dir) => join(relationsDir(dir), 'players.salt');
|
|
35
|
+
/** Whether the cross-game record is on: yes (local and hosted) unless `WARAPP_PLAYER_RECORD` is `off`, `0`, `false` or `no`. */
|
|
36
|
+
export function playerRecordEnabled(env = process.env) {
|
|
37
|
+
const v = readEnvVar('WARAPP_PLAYER_RECORD', { env });
|
|
38
|
+
return v === undefined || !/^(off|0|false|no)$/i.test(v.trim());
|
|
39
|
+
}
|
|
40
|
+
async function readSalt(dir) {
|
|
41
|
+
let text;
|
|
42
|
+
try {
|
|
43
|
+
text = await readFile(playerRecordSaltPath(dir), 'utf8');
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return e.code === 'ENOENT' ? 'missing' : 'malformed';
|
|
47
|
+
}
|
|
48
|
+
const salt = text.trim();
|
|
49
|
+
return SALT.test(salt) ? { salt } : 'malformed';
|
|
50
|
+
}
|
|
51
|
+
/** The salt on record for `dir`; `undefined` when there is none yet or it is malformed. Never makes one. */
|
|
52
|
+
export async function playerRecordSalt(dir) {
|
|
53
|
+
const s = await readSalt(dir);
|
|
54
|
+
return typeof s === 'object' ? s.salt : undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The salt for a write: the one on record, else a new one (never over an existing file); `undefined`
|
|
58
|
+
* when malformed. The one "read or make" for every store keyed by `playerKey` (this record and the
|
|
59
|
+
* opponent profiles, src/profile-store.ts), so two salts can never exist. Throws when it cannot be
|
|
60
|
+
* written (callers run it inside their own never-throw guard).
|
|
61
|
+
*/
|
|
62
|
+
export async function playerSaltForWrite(dir) {
|
|
63
|
+
const s = await readSalt(dir);
|
|
64
|
+
if (typeof s === 'object')
|
|
65
|
+
return s.salt;
|
|
66
|
+
if (s === 'malformed')
|
|
67
|
+
return undefined;
|
|
68
|
+
const path = playerRecordSaltPath(dir);
|
|
69
|
+
await mkdir(relationsDir(dir), { recursive: true, mode: 0o700 });
|
|
70
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
71
|
+
await writeFile(tmp, randomBytes(16).toString('hex'), { mode: 0o600 });
|
|
72
|
+
try {
|
|
73
|
+
// `link` fails when the file exists: another writer's salt is never replaced.
|
|
74
|
+
await link(tmp, path);
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
if (e.code !== 'EEXIST')
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
await unlink(tmp).catch(() => undefined);
|
|
82
|
+
}
|
|
83
|
+
const again = await readSalt(dir);
|
|
84
|
+
return typeof again === 'object' ? again.salt : undefined;
|
|
85
|
+
}
|
|
86
|
+
const hmac = (salt, text) => createHmac('sha256', salt).update(text).digest('hex').slice(0, 32);
|
|
87
|
+
/** A player's key in the record: never the id itself. */
|
|
88
|
+
export const playerKey = (salt, playerId) => hmac(salt, `player:${playerId}`);
|
|
89
|
+
/** A game's key in the opponent profiles: my account and the game, never the ids themselves. */
|
|
90
|
+
export const profileGameKey = (salt, myId, gameId) => hmac(salt, `profile-game:${myId}:${gameId}`);
|
|
91
|
+
/** An agreement's key in the record: my account, the game and the agreement, never the ids themselves. */
|
|
92
|
+
export const entryKey = (salt, myId, gameId, agreementId) => hmac(salt, `agreement:${myId}:${gameId}:${agreementId}`);
|
|
93
|
+
/** The key entries were written under before my account was part of it: still read, and updated in place. */
|
|
94
|
+
export const legacyEntryKey = (salt, gameId, agreementId) => hmac(salt, `agreement:${gameId}:${agreementId}`);
|
|
95
|
+
const count = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
|
|
96
|
+
const intOrNull = (v) => v === null || (typeof v === 'number' && Number.isInteger(v));
|
|
97
|
+
function talliesFrom(v) {
|
|
98
|
+
if (!isRec(v) || !COUNT_KEYS.every((k) => count(v[k])))
|
|
99
|
+
return undefined;
|
|
100
|
+
const out = { ...ZERO_COUNTS };
|
|
101
|
+
for (const k of COUNT_KEYS)
|
|
102
|
+
out[k] = v[k];
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
function entryOf(v) {
|
|
106
|
+
// Entries are this module's own writes: checked for shape, not re-derived.
|
|
107
|
+
if (!isRec(v) || typeof v.key !== 'string' || !HASH.test(v.key) || !OUTCOMES.has(v.outcome) || typeof v.updated !== 'number')
|
|
108
|
+
return undefined;
|
|
109
|
+
if (!isRec(v.format) || !isRec(v.terms) || !intOrNull(v.agreedTurn) || !intOrNull(v.endedTurn))
|
|
110
|
+
return undefined;
|
|
111
|
+
return v;
|
|
112
|
+
}
|
|
113
|
+
/** One player as stored, in any version this module wrote; `undefined` when unusable. */
|
|
114
|
+
function playerOf(v) {
|
|
115
|
+
if (!isRec(v))
|
|
116
|
+
return undefined;
|
|
117
|
+
const entries = Array.isArray(v.entries) ? v.entries.map(entryOf).filter((e) => e !== undefined) : [];
|
|
118
|
+
// Version 3 keeps `tallies`, version 2 kept `counts` only, version 1 entries only.
|
|
119
|
+
const tallies = talliesFrom(v.tallies) ?? talliesFrom(v.counts) ?? (entries.length ? talliesOf(entries) : undefined);
|
|
120
|
+
if (!tallies)
|
|
121
|
+
return undefined;
|
|
122
|
+
const updated = typeof v.updated === 'number' ? v.updated : entries.reduce((m, e) => Math.max(m, e.updated), 0);
|
|
123
|
+
return { tallies, entries, updated };
|
|
124
|
+
}
|
|
125
|
+
/** The file on record: empty when there is none; `'unreadable'` when one exists but cannot be read or parsed. */
|
|
126
|
+
async function readFileRecord(dir) {
|
|
127
|
+
let text;
|
|
128
|
+
try {
|
|
129
|
+
text = await readFile(playerRecordPath(dir), 'utf8');
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
return e.code === 'ENOENT' ? { version: 3, players: {} } : 'unreadable';
|
|
133
|
+
}
|
|
134
|
+
let c;
|
|
135
|
+
try {
|
|
136
|
+
c = JSON.parse(text);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return 'unreadable';
|
|
140
|
+
}
|
|
141
|
+
if (!isRec(c) || !isRec(c.players))
|
|
142
|
+
return 'unreadable';
|
|
143
|
+
const players = {};
|
|
144
|
+
for (const [k, v] of Object.entries(c.players)) {
|
|
145
|
+
const p = HASH.test(k) ? playerOf(v) : undefined;
|
|
146
|
+
if (p)
|
|
147
|
+
players[k] = p;
|
|
148
|
+
}
|
|
149
|
+
return { version: 3, players };
|
|
150
|
+
}
|
|
151
|
+
async function writeFileRecord(dir, file) {
|
|
152
|
+
const keys = Object.keys(file.players)
|
|
153
|
+
.sort((a, b) => file.players[b].updated - file.players[a].updated || (a < b ? -1 : 1))
|
|
154
|
+
.slice(0, MAX_RECORD_PLAYERS)
|
|
155
|
+
.sort();
|
|
156
|
+
const bounded = { version: 3, players: Object.fromEntries(keys.map((k) => [k, file.players[k]])) };
|
|
157
|
+
const path = playerRecordPath(dir);
|
|
158
|
+
await mkdir(relationsDir(dir), { recursive: true, mode: 0o700 });
|
|
159
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
160
|
+
await writeFile(tmp, JSON.stringify(bounded), { mode: 0o600 });
|
|
161
|
+
await rename(tmp, path);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* What is on record for `playerId`: its tallies and entries; `null` when nothing is (no salt yet
|
|
165
|
+
* included); `'unreadable'` when the salt file is malformed or the record file cannot be parsed;
|
|
166
|
+
* `'off'` when the record is off. Never throws, never writes.
|
|
167
|
+
*/
|
|
168
|
+
export async function readPlayerRecord(dir, playerId, env) {
|
|
169
|
+
if (!playerRecordEnabled(env))
|
|
170
|
+
return 'off';
|
|
171
|
+
try {
|
|
172
|
+
const s = await readSalt(dir);
|
|
173
|
+
if (s === 'malformed')
|
|
174
|
+
return 'unreadable';
|
|
175
|
+
if (s === 'missing')
|
|
176
|
+
return null;
|
|
177
|
+
const file = await readFileRecord(dir);
|
|
178
|
+
if (file === 'unreadable')
|
|
179
|
+
return 'unreadable';
|
|
180
|
+
const p = file.players[playerKey(s.salt, playerId)];
|
|
181
|
+
return p ? { tallies: p.tallies, entries: p.entries } : null;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** The record's state for a tool result: `on`, `off`, or `unreadable` (a malformed salt file or a record file that cannot be parsed). */
|
|
188
|
+
export async function playerRecordState(dir, env) {
|
|
189
|
+
if (!playerRecordEnabled(env))
|
|
190
|
+
return 'off';
|
|
191
|
+
if (!dir)
|
|
192
|
+
return 'on';
|
|
193
|
+
if ((await readSalt(dir).catch(() => 'missing')) === 'malformed')
|
|
194
|
+
return 'unreadable';
|
|
195
|
+
return (await readFileRecord(dir).catch(() => 'unreadable')) === 'unreadable' ? 'unreadable' : 'on';
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Update `playerId`'s part of the record: `update` gets the salt (to key entries) and what is on
|
|
199
|
+
* record, and returns the tallies to add (`recordDelta`) and the entries to upsert. Read, change and
|
|
200
|
+
* write run under the in-process lock for the file. `updated` when written; `off` when the record is
|
|
201
|
+
* off; `failed` when it could not be (a malformed salt or an unparseable record file included: neither
|
|
202
|
+
* is ever overwritten). Never throws.
|
|
203
|
+
*/
|
|
204
|
+
export async function updatePlayerRecord(dir, playerId, update, env, now = Date.now()) {
|
|
205
|
+
if (!playerRecordEnabled(env))
|
|
206
|
+
return 'off';
|
|
207
|
+
try {
|
|
208
|
+
return await withPathLock(playerRecordPath(dir), async () => {
|
|
209
|
+
const file = await readFileRecord(dir);
|
|
210
|
+
if (file === 'unreadable')
|
|
211
|
+
return 'failed';
|
|
212
|
+
const salt = await playerSaltForWrite(dir);
|
|
213
|
+
if (!salt)
|
|
214
|
+
return 'failed';
|
|
215
|
+
const key = playerKey(salt, playerId);
|
|
216
|
+
const current = file.players[key] ?? { tallies: { ...ZERO_COUNTS }, entries: [], updated: 0 };
|
|
217
|
+
const { delta, entries } = update(salt, { tallies: current.tallies, entries: current.entries });
|
|
218
|
+
let next = current.entries;
|
|
219
|
+
for (const e of entries)
|
|
220
|
+
next = upsertEntry(next, e);
|
|
221
|
+
file.players[key] = { tallies: addCounts(current.tallies, delta), entries: next, updated: now };
|
|
222
|
+
await writeFileRecord(dir, file);
|
|
223
|
+
return 'updated';
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return 'failed';
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// A player's state in a game, and the one test of whether it holds a seat.
|
|
2
|
+
//
|
|
3
|
+
// GameFeed names the state (`"Playing"`, `"Declined"`, …); the web client's
|
|
4
|
+
// records carry the GamePlayerState code. Both are named here, so the open-games
|
|
5
|
+
// list, the join read-back and the game profile all ask the same question (#133).
|
|
6
|
+
/** GamePlayerState: the web client's codes, named as GameFeed names them. */
|
|
7
|
+
export const PLAYER_STATE_NAMES = {
|
|
8
|
+
1: 'Invited',
|
|
9
|
+
2: 'Playing',
|
|
10
|
+
3: 'Eliminated',
|
|
11
|
+
4: 'Won',
|
|
12
|
+
5: 'Declined',
|
|
13
|
+
6: 'RemovedByHost',
|
|
14
|
+
7: 'SurrenderAccepted',
|
|
15
|
+
8: 'Booted',
|
|
16
|
+
9: 'EndedByVote',
|
|
17
|
+
};
|
|
18
|
+
/** A GamePlayerState code's name; the code itself when it has none. */
|
|
19
|
+
export function playerStateName(code) {
|
|
20
|
+
return PLAYER_STATE_NAMES[code] ?? String(code);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* States of a player who does not hold a seat: an invitation not yet accepted, one declined, and a
|
|
24
|
+
* removal by the host. Such a player never started the game. Every other state held a seat — the
|
|
25
|
+
* finished ones (eliminated, surrendered, booted, …) included.
|
|
26
|
+
*/
|
|
27
|
+
const NOT_SEATED = new Set(['Invited', 'Declined', 'RemovedByHost']);
|
|
28
|
+
/** Whether a player in `state` (a GameFeed state name; absent reads as Playing) holds a seat. */
|
|
29
|
+
export function holdsSeat(state) {
|
|
30
|
+
return !NOT_SEATED.has(state ?? 'Playing');
|
|
31
|
+
}
|