@chrischall/warapp-mcp 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +9 -6
  4. package/dist/analysis/airlift-plan.js +288 -0
  5. package/dist/analysis/blockade-plan.js +178 -0
  6. package/dist/analysis/bomb-plan.js +72 -0
  7. package/dist/analysis/card-threats.js +10 -9
  8. package/dist/analysis/cards-in-effect.js +20 -0
  9. package/dist/analysis/combat.js +5 -0
  10. package/dist/analysis/coordination.js +47 -0
  11. package/dist/analysis/income-calibration.js +280 -0
  12. package/dist/analysis/intel.js +1 -1
  13. package/dist/analysis/lookahead.js +4 -0
  14. package/dist/analysis/opponents.js +52 -3
  15. package/dist/analysis/plan/deploy-estimates.js +1 -1
  16. package/dist/analysis/plan/estimates.js +40 -6
  17. package/dist/analysis/plan/relations.js +57 -8
  18. package/dist/analysis/plan/threats.js +1 -1
  19. package/dist/analysis/player-record.js +1 -0
  20. package/dist/analysis/relations.js +40 -0
  21. package/dist/analysis/stress.js +42 -2
  22. package/dist/analysis/turn-sim.js +62 -0
  23. package/dist/bundle.js +24486 -21811
  24. package/dist/card-state.js +157 -0
  25. package/dist/decision-log.js +44 -5
  26. package/dist/local-time.js +142 -0
  27. package/dist/relations-store.js +30 -5
  28. package/dist/tools/airlift-readback.js +87 -0
  29. package/dist/tools/alternative-orders.js +21 -0
  30. package/dist/tools/begin-turn.js +19 -5
  31. package/dist/tools/calibration-harness.js +102 -0
  32. package/dist/tools/calibration.js +110 -0
  33. package/dist/tools/card-advice.js +5 -4
  34. package/dist/tools/card-plays.js +32 -20
  35. package/dist/tools/card-state-view.js +26 -0
  36. package/dist/tools/card-support-advice.js +25 -8
  37. package/dist/tools/chat-inbox.js +1 -1
  38. package/dist/tools/chat.js +1 -1
  39. package/dist/tools/check-plan.js +113 -9
  40. package/dist/tools/common.js +14 -0
  41. package/dist/tools/decision-capture.js +14 -1
  42. package/dist/tools/game.js +11 -2
  43. package/dist/tools/index.js +13 -1
  44. package/dist/tools/notifications.js +1 -1
  45. package/dist/tools/opponents.js +2 -0
  46. package/dist/tools/player-card-readback.js +45 -0
  47. package/dist/tools/relations.js +146 -14
  48. package/dist/tools/sanctions-played.js +51 -0
  49. package/dist/tools/stress-opponents.js +8 -4
  50. package/dist/tools/turn-history.js +214 -0
  51. package/dist/tools/turn.js +504 -20
  52. package/dist/turn-orders.js +64 -0
  53. package/dist/version.js +1 -1
  54. package/manifest.json +17 -2
  55. package/mint.yaml +7 -0
  56. package/package.json +1 -1
  57. package/server.json +8 -2
  58. package/skills/warapp-mcp/SKILL.md +9 -1
@@ -0,0 +1,102 @@
1
+ // The #318 calibration and opening-benchmark harness over the data directory: the body of
2
+ // `scripts/calibrate.mjs`, moved here (#569) so the script and warapp_calibration's `harness: true` share it.
3
+ // It reads the end-of-game records, settings records, stored maps and cached boards (src/calibration-source.ts)
4
+ // and returns aggregates only — no game id, player id or name. No request, nothing written. The pure parts are
5
+ // src/analysis/calibrate.ts; docs/PLAN-PROFILES.md "Calibration" says what it approximates.
6
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
7
+ import { trackGame } from '../analysis/opponents.js';
8
+ import { applyBonusOverrides } from '../analysis/overrides.js';
9
+ import { aggregateBenchmarks, aggregateEstimates, benchmarkByEra, estimateSamples, openingBenchmark, openingEra, openingFlags, ratioSummary, } from '../analysis/calibrate.js';
10
+ import { addCalibration } from '../analysis/game-lessons.js';
11
+ import { calibrationSources } from '../calibration-source.js';
12
+ import { holdsSeat } from '../player-states.js';
13
+ import { graphOf } from './common.js';
14
+ import { plannerSettings } from './turn.js';
15
+ /** What the opening benchmark approximates: printed by the script and reported by the tool. */
16
+ export const HARNESS_APPROXIMATIONS = [
17
+ 'Opening benchmark approximations: the planner sees the whole board (no fog); opponents never attack me —',
18
+ 'they hold the land and armies the history shows, except land I hold in the replay; card plays are left out;',
19
+ 'with luck or weighted rounding a battle is resolved at its expectation (counted as inexact).',
20
+ 'Eras (#503): pre-tool = never planned by this server, or no local cache names the game; pre-rule-4f = turn 1',
21
+ 'before 2026-11-13 08:24Z by its turn-1 time where known, else game id below 45690000 (ids are assigned at creation,',
22
+ 'so the id boundary approximates the time); current = the rest. A game with a turn with no orders of mine (read off',
23
+ 'the history boards: no capture, no failed attack, no orders cached; army growth alone is not orders) or a boot of my seat in turns',
24
+ '1-4 is reported apart, never averaged in.',
25
+ ];
26
+ /** Run the harness over `dir`. `turns`: the opening benchmark's length (default the module's). Never requests. */
27
+ export async function calibrationHarness(dir, opts = {}) {
28
+ const src = await calibrationSources(dir);
29
+ const counts = { histories: src.statuses, skipped: src.skipped, scored: 0, recordOnly: 0, benchmarked: 0, samples: 0 };
30
+ const byFormat = {};
31
+ const benchByFormat = {};
32
+ const eraEntries = [];
33
+ for (const input of src.inputs) {
34
+ const { history: h, settings, map, cached } = input;
35
+ if (input.source === 'record-only')
36
+ counts.recordOnly++;
37
+ const me = h.me;
38
+ const graph = graphOf(applyBonusOverrides(map, settings));
39
+ const seated = h.players.filter((p) => holdsSeat(p.state));
40
+ const format = profileFormatOf(seated);
41
+ const mine = seated.find((p) => p.id === me);
42
+ const myTeam = typeof mine?.team === 'number' && mine.team >= 0 ? mine.team : undefined;
43
+ const opponents = seated.filter((p) => p.id !== me && (myTeam === undefined || p.team !== myTeam)).map((p) => p.id);
44
+ const asPlaying = seated.map(({ state: _s, ...p }) => p);
45
+ const ps = plannerSettings(settings);
46
+ const samples = estimateSamples({
47
+ graph,
48
+ me,
49
+ cached,
50
+ history: h.boards,
51
+ plannerSettings: ps,
52
+ incomeSettings: settings,
53
+ settings,
54
+ game: trackGame(asPlaying, settings, map),
55
+ players: asPlaying,
56
+ opponents,
57
+ });
58
+ counts.samples += samples.length;
59
+ if (samples.length)
60
+ counts.scored++;
61
+ const agg = aggregateEstimates(samples);
62
+ const f = (byFormat[format] ??= {});
63
+ for (const [k, c] of Object.entries(agg))
64
+ f[k] = addCalibration(f[k] ?? {}, c);
65
+ const bench = openingBenchmark({
66
+ graph,
67
+ me,
68
+ history: h.boards,
69
+ plannerSettings: ps,
70
+ incomeSettings: settings,
71
+ players: asPlaying,
72
+ winners: seated.filter((p) => p.state === 'Won').map((p) => p.id),
73
+ ...(opts.turns ? { turns: opts.turns } : {}),
74
+ });
75
+ if (bench.turns.length) {
76
+ counts.benchmarked++;
77
+ (benchByFormat[format] ??= []).push(bench);
78
+ // #503: the era (turn-1 time where known — no record keeps one yet — else the game id) and the
79
+ // opening window's flags (turns with no orders of mine, a boot of my seat).
80
+ const o = input.opening;
81
+ const { era, basis } = openingEra({ planned: o.planned, ...(o.gameId !== undefined ? { gameId: o.gameId } : {}) });
82
+ const flags = openingFlags({
83
+ me,
84
+ history: h.boards,
85
+ sentTurns: o.sentTurns,
86
+ failedAttackTurns: o.failedAttackTurns,
87
+ booted: { turn: o.bootedTurn },
88
+ });
89
+ eraEntries.push({ era, basis, format, territories: graph.territoryById.size, flags, bench });
90
+ }
91
+ }
92
+ const calibration = {};
93
+ for (const [format, ests] of Object.entries(byFormat))
94
+ for (const [k, c] of Object.entries(ests))
95
+ for (const [band, stats] of Object.entries(c))
96
+ ((calibration[format] ??= {})[k] ??= {})[band] = ratioSummary(stats);
97
+ const benchmark = {};
98
+ for (const [format, list] of Object.entries(benchByFormat))
99
+ benchmark[format] = aggregateBenchmarks(list);
100
+ benchmark.all = aggregateBenchmarks(Object.values(benchByFormat).flat());
101
+ return { counts, calibration, benchmark, byEra: benchmarkByEra(eraEntries) };
102
+ }
@@ -0,0 +1,110 @@
1
+ // warapp_calibration (#569, for #568): the income estimates this server planned with, scored against the
2
+ // truth its finished games kept — read-only, from this server's state alone (no war.app request), so an agent
3
+ // can run the calibration on a hosted server whose data directory no local script can reach. The pure part is
4
+ // src/analysis/income-calibration.ts; `harness: true` adds the #318 harness (src/tools/calibration-harness.ts).
5
+ // Name-free: games are numbered by their place in the report, never by id; no player is named or numbered.
6
+ import { toolAnnotations } from '@chrischall/mcp-utils';
7
+ import { z } from 'zod';
8
+ import { incomeCalibration, incomeSamples } from '../analysis/income-calibration.js';
9
+ import { profileFormatOf } from '../analysis/opponent-profile.js';
10
+ import { listDecisionLogs, readDecisionLog } from '../decision-log.js';
11
+ import { holdsSeat } from '../player-states.js';
12
+ import { readGameRecord } from '../replay.js';
13
+ import { calibrationHarness, HARNESS_APPROXIMATIONS } from './calibration-harness.js';
14
+ import { respond } from './common.js';
15
+ import { mintMeta } from './hints.js';
16
+ import { refuse } from './write-kit.js';
17
+ /** Scored rows returned at most with `samples: true`. */
18
+ export const MAX_SAMPLES = 2000;
19
+ export const CALIBRATION_NOTE = 'Each sample is one income estimate a planned turn worked from, against that opponent\'s true income (base plus ' +
20
+ 'full bonuses, cards and the army cap aside) on the board the turn was played on, read from the finished game\'s ' +
21
+ 'history. ratio = estimate ÷ truth; meanError = estimate − truth in armies. Reported only: nothing plans on it. ' +
22
+ 'Only games whose decision log was given the end-of-game truth count (games played on builds with the decision log, ' +
23
+ 'finished, their history read); `method` (the tracker\'s, incl. rise-capped) is logged only since #569. The ' +
24
+ 'consequences block is a proxy: a lost territory has many causes.';
25
+ /** Every finished decision log in `dir` as the scoring reads it, in game-id order; lotteries counted apart. Never throws. */
26
+ export async function calibrationGames(dir) {
27
+ const listed = (await listDecisionLogs(dir)).filter((l) => l.status !== 'active');
28
+ const games = [];
29
+ let lotteries = 0;
30
+ let withoutTruth = 0;
31
+ for (const l of listed) {
32
+ const log = await readDecisionLog(dir, l.gameId, l.playerId);
33
+ if (!log)
34
+ continue;
35
+ if (log.join?.lottery !== undefined) {
36
+ lotteries++;
37
+ continue;
38
+ }
39
+ if (!Object.values(log.turns).some((e) => e.accuracy?.estimates.length)) {
40
+ withoutTruth++;
41
+ continue;
42
+ }
43
+ games.push({ ...(await formatOf(dir, log)), turns: log.turns });
44
+ }
45
+ return { games, logs: listed.length, lotteries, withoutTruth };
46
+ }
47
+ async function formatOf(dir, log) {
48
+ const game = await readGameRecord(dir, log.gameId);
49
+ if (game?.players.length) {
50
+ const seated = game.players.filter((p) => holdsSeat(p.state));
51
+ return { format: profileFormatOf(seated), seats: seated.length };
52
+ }
53
+ if (log.join)
54
+ return { format: log.join.flags.format, seats: log.join.flags.seats };
55
+ const seats = log.seats ? Object.keys(log.seats).length : null;
56
+ return { format: seats === 2 ? '1v1' : 'unknown', seats };
57
+ }
58
+ export function registerCalibrationTool(server, dataDir) {
59
+ server.registerTool('warapp_calibration', {
60
+ title: 'Score the income estimates against finished games',
61
+ _meta: mintMeta('lookup', ['how accurate are the income estimates', 'calibrate opponent income', 'estimate accuracy']),
62
+ description: 'Score the opponent income estimates this server planned with against the truth its finished games kept ' +
63
+ '(the decision log\'s end-of-game truth): each estimate ÷ the true income, and its signed error in armies, ' +
64
+ 'overall and by format, seats, phase (turns 1–4, 5–10, 11+), frontier coverage band, estimate source, thin ' +
65
+ 'evidence, the tracker\'s income method (rise-capped or not; logged since #569), leader vs trailer, and phase ' +
66
+ 'by coverage; the catch-up lag after a true income jump of 1.5× or more (turns until the estimate reaches two ' +
67
+ 'thirds of the truth); a consequences proxy (turns that lost a territory the plan did not concede, with an ' +
68
+ 'estimate under half the truth vs without); the largest misses; each pipeline stage\'s figure ÷ the truth ' +
69
+ '(visible, observed, tracked, prior, stated, blend, thin, known; logged since #568); and what correcting the ' +
70
+ 'tracked figure by its coverage band would have read at dampings 0 to 1 (leave one game out). `samples: true` adds the scored rows ' +
71
+ `(at most ${MAX_SAMPLES}), name-free, as a fixture set; \`harness: true\` also runs the #318 harness over the ` +
72
+ 'cached boards (tracker, fog prior and plan estimate by coverage band, and the opening benchmark), which can ' +
73
+ 'take a while on many games. Games are numbered by their place in the report, never by id, and no player is ' +
74
+ 'named. Makes no war.app request and writes nothing. Read-only.',
75
+ annotations: toolAnnotations({ title: 'Income estimate calibration', readOnly: true, destructive: false, idempotent: true, openWorld: false }),
76
+ inputSchema: z.object({
77
+ samples: z.boolean().optional().describe(`Also return the scored rows, name-free (default false; at most ${MAX_SAMPLES}).`),
78
+ harness: z.boolean().optional().describe('Also run the #318 harness over the cached boards and the opening benchmark (default false).'),
79
+ format: z.enum(['1v1', 'ffa', 'team']).optional().describe('Only games of this format.'),
80
+ }),
81
+ }, async ({ samples, harness, format }) => {
82
+ const dir = dataDir();
83
+ if (!dir)
84
+ refuse('This server has no data directory, so there is nothing to score.', 'Nothing to do here.');
85
+ const src = await calibrationGames(dir);
86
+ const games = format ? src.games.filter((g) => g.format === format) : src.games;
87
+ const report = incomeCalibration(games);
88
+ const rows = samples ? incomeSamples(games) : [];
89
+ const extra = harness ? await calibrationHarness(dir) : undefined;
90
+ return respond(undefined, ['compact'], () => ({
91
+ readAs: CALIBRATION_NOTE,
92
+ sources: {
93
+ finishedLogs: src.logs,
94
+ scoredGames: report.games,
95
+ lotteriesLeftOut: src.lotteries,
96
+ withoutTruth: src.withoutTruth,
97
+ ...(format ? { format, otherFormats: src.games.length - games.length } : {}),
98
+ },
99
+ ...(report.samples
100
+ ? { report }
101
+ : {
102
+ report: null,
103
+ empty: 'No finished game with the end-of-game truth in its decision log yet: the truth is written when a finished ' +
104
+ "game's history is read (warapp_backfill_history, warapp_my_games' sweep, warapp_get_game on it).",
105
+ }),
106
+ ...(samples ? { samples: rows.slice(0, MAX_SAMPLES), ...(rows.length > MAX_SAMPLES ? { samplesLeftOut: rows.length - MAX_SAMPLES } : {}) } : {}),
107
+ ...(extra ? { harness: { ...extra, approximations: HARNESS_APPROXIMATIONS } } : {}),
108
+ }));
109
+ });
110
+ }
@@ -8,6 +8,7 @@
8
8
  import { adviseOrderDelay, CARD_BLOCKADE, CARD_ORDER_DELAY, CARD_REINFORCEMENT, isMyCard, readActiveCards, readTurnReinforcementPlays } from '../cards.js';
9
9
  import { blockadeOffer, bombAdvice, bombExposure, wallOffer, wallThreats } from '../analysis/card-threats.js';
10
10
  import { bonusTerritories } from '../analysis/bonuses.js';
11
+ import { sanctionsSettings } from '../analysis/cards-in-effect.js';
11
12
  import { diplomacyOpponents, supportAdvice } from './card-support-advice.js';
12
13
  export { giftInOrders, intelOrders } from './card-support-advice.js';
13
14
  import { inGameId, playersByInGameId } from '../live.js';
@@ -271,10 +272,10 @@ export function adviseCards(input) {
271
272
  : ''));
272
273
  }
273
274
  if (a.card === 'Sanctions' && a.target === me.id) {
274
- const pct = game.settings?.raw.SanctionsCard?.Percentage;
275
- const cut = typeof pct === 'number' ? ` by ${Math.round(pct * 100)}%` : '';
275
+ const pct = sanctionsSettings(game.settings)?.percentage ?? null;
276
+ const change = pct === null ? 'cut' : pct < 0 ? `raised by ${Math.round(-pct * 100)}%` : `cut by ${Math.round(pct * 100)}%`;
276
277
  if (!input.sanctionsApplied)
277
- warnings.push(`Sanctions are on you${until}: your income is cut${cut}, which the modelled income does not apply — deploy what the game shows ` +
278
+ warnings.push(`Sanctions are on you${until}: your income is ${change}, which the modelled income does not apply — deploy what the game shows ` +
278
279
  '(warapp_submit_turn takes a lower total when Sanctions are in the game).');
279
280
  }
280
281
  }
@@ -284,7 +285,7 @@ export function adviseCards(input) {
284
285
  const atPeace = new Set((view.active ?? []).flatMap((a) => (a.card === 'Diplomacy' && a.players?.includes(me.id) ? a.players.filter((p) => p !== me.id) : [])));
285
286
  // #424: the cards in force whose last turn this is (gone by the next): chained, not passed over.
286
287
  const lastTurn = new Set((view.active ?? []).flatMap((a) => a.card === 'Diplomacy' && a.players?.includes(me.id) && turn !== null && a.untilTurn === turn + 1 ? a.players.filter((p) => p !== me.id) : []));
287
- const support = supportAdvice({ game, me, plan, cards: own.filter((c) => !gone.has(c.id)), cb, atPeace, lastTurn, truces: input.truces ?? [], ...(input.unverifiedPlays ? { unverifiedPlays: input.unverifiedPlays } : {}) });
288
+ const support = supportAdvice({ game, me, plan, cards: own.filter((c) => !gone.has(c.id)), cb, atPeace, lastTurn, truces: input.truces ?? [], ...(input.unverifiedPlays ? { unverifiedPlays: input.unverifiedPlays } : {}), ...(input.nextIncome !== undefined ? { nextIncome: input.nextIncome } : {}) });
288
289
  Object.assign(view, support.view);
289
290
  warnings.push(...support.warnings);
290
291
  return { view, warnings };
@@ -8,6 +8,7 @@
8
8
  import { McpToolError } from '@chrischall/mcp-utils';
9
9
  import { inGameId } from '../live.js';
10
10
  import { untrustedText } from './common.js';
11
+ import { percentText, sanctionsSettings } from '../analysis/cards-in-effect.js';
11
12
  import { resolveBonus, resolvePlayer, resolveTerritory } from './resolve.js';
12
13
  /** The fields each card takes; every one is required except an Airlift's `commander`. */
13
14
  const TAKES = {
@@ -36,7 +37,7 @@ const FIELD_HELP = {
36
37
  Bomb: "`target`: a territory next to one of yours, not yours or a teammate's (its armies are halved)",
37
38
  Reconnaissance: '`target`: the territory to see',
38
39
  Spy: "`player`: the player whose territories to see (0 or \"neutral\": the neutral, when the game's Spy card allows it)",
39
- Sanctions: "`player`: the player whose income it cuts",
40
+ Sanctions: "`player`: the player whose income it changes — an opponent when the game's percentage is positive (a cut), yourself or a teammate when it is negative (a boost)",
40
41
  Gift: '`target`: your territory to give, and `player`: who receives it',
41
42
  Diplomacy: '`players`: the two players who may not attack each other (usually you and one opponent)',
42
43
  Surveillance: '`bonus`: the bonus to see',
@@ -156,14 +157,6 @@ function canSpyOnNeutral(settings) {
156
157
  const v = raw.CanSpyOnNeutral;
157
158
  return v === true || (typeof v === 'string' && v.toLowerCase() === 'true');
158
159
  }
159
- /** The Sanctions percentage (`SanctionsCard.Percentage`), when the settings carry one. */
160
- function sanctionsPercentage(settings) {
161
- const raw = settings?.raw.SanctionsCard;
162
- if (typeof raw !== 'object' || raw === null)
163
- return undefined;
164
- const pct = raw.Percentage;
165
- return typeof pct === 'number' ? pct : undefined;
166
- }
167
160
  /**
168
161
  * Resolve a targeted card play's fields against the map, the players and the live board, refusing
169
162
  * what war.app's validator (the client bundle's `GameValidateOrders`) or the card's rules exclude.
@@ -199,21 +192,36 @@ export function resolveCardTargets(kind, cardName, input, ctx) {
199
192
  return { fields: { player: p.inGameId }, player: p, warnings };
200
193
  }
201
194
  case 'Sanctions': {
202
- // GameValidateOrders refuses only a player not playing (219); the target is our rule: a sanction
203
- // cuts income, so never on me or a teammate — unless the game's percentage is negative (a boost).
195
+ // GameValidateOrders refuses only a player not playing (219), and the client offers every player still
196
+ // playing, me included. The side is our rule, read from the game's percentage (`sanctionsSettings`):
197
+ // a positive one cuts income, so never on me or a teammate; a negative one raises it (the client's own
198
+ // guide: play it on yourself), so never on an opponent; one that cannot be read keeps my side out.
204
199
  const p = player(ctx, input.player, cardName);
205
200
  requirePlaying(ctx, p, cardName, 'error 219');
206
- const pct = sanctionsPercentage(ctx.settings);
201
+ const san = sanctionsSettings(ctx.settings);
202
+ const pct = san?.percentage ?? null;
207
203
  const friendly = isMe(ctx, p) || isTeammate(ctx, p);
208
- if (pct !== undefined && pct < 0) {
204
+ const side = isMe(ctx, p) ? 'yourself' : `your teammate ${who(p)}`;
205
+ const turns = san?.duration ? ` for ${san.duration} turn${san.duration === 1 ? '' : 's'}` : '';
206
+ if (pct === null) {
207
+ if (friendly) {
208
+ throw new McpToolError(`This game's Sanctions percentage could not be read from its settings, so whether the card cuts or raises income is not known: it is not played on ${side}.`, { hint: 'warapp_get_game shows the card settings (`cards.settings`). Sanction an opponent, or keep the card.' });
209
+ }
210
+ }
211
+ else if (pct < 0) {
209
212
  if (!friendly) {
210
- throw new McpToolError(`This game's Sanctions percentage is negative (${Math.round(pct * 100)}%): a sanction raises the target's income, so it does not go on an opponent (${who(p)}).`, { hint: 'Play it on yourself or a teammate, or keep it.' });
213
+ throw new McpToolError(`This game's Sanctions percentage is negative (${percentText(pct)}): a sanction raises the target's income by ${percentText(-pct)}, so it does not go on an opponent (${who(p)}).`, { hint: 'Play it on yourself (or a teammate), or keep it.' });
211
214
  }
215
+ warnings.push(`Sanctions on ${isMe(ctx, p) ? 'yourself' : `your teammate ${who(p)}`}: this game's percentage is ${percentText(pct)}, so it raises ` +
216
+ `${isMe(ctx, p) ? 'your' : 'their'} income by ${percentText(-pct)}${turns}, from the turn after this one (war.app caps an income at 10,000).`);
212
217
  }
213
- else if (friendly) {
214
- throw new McpToolError(`Sanctions cut the target's income, so they do not go on ${isMe(ctx, p) ? 'yourself' : `your teammate ${who(p)}`}.`, {
215
- hint: 'Sanction an opponent — usually the leader.',
216
- });
218
+ else if (pct > 0) {
219
+ if (friendly) {
220
+ throw new McpToolError(`This game's Sanctions percentage is ${percentText(pct)}: it cuts the target's income by ${percentText(pct)}, so it does not go on ${side}.`, { hint: 'Sanction an opponent — usually the leader.' });
221
+ }
222
+ }
223
+ else {
224
+ warnings.push("This game's Sanctions percentage is 0%: the card changes nobody's income.");
217
225
  }
218
226
  return { fields: { player: p.inGameId }, player: p, warnings };
219
227
  }
@@ -399,8 +407,12 @@ function airlift(input, ctx, warnings) {
399
407
  }
400
408
  const there = (standingOf(ctx, f.id)?.armies ?? 0) + (ctx.deployedOn.get(f.id) ?? 0);
401
409
  const total = (ctx.seen.airliftedFrom.get(f.id) ?? 0) + armies;
402
- if (total > there) {
403
- throw new McpToolError(`These orders airlift ${total} armies from ${place(from)}, but at most ${there} stand there when the Airlift runs (its armies now plus this turn's deploys).`, { hint: 'Airlift no more armies than stand on the territory.' });
410
+ // Owner spec 2026-11-24: an Airlift leaves at least one army behind while One Army Must Stand Guard is on (the
411
+ // bundle's validator does not check the count; ours, as a move leaves its guard).
412
+ const guard = ctx.settings?.oneArmyStandsGuard === false ? 0 : 1;
413
+ if (total > there - guard) {
414
+ throw new McpToolError(`These orders airlift ${total} armies from ${place(from)}, but at most ${Math.max(0, there - guard)} can leave when the Airlift runs ` +
415
+ `(${there} stand there — its armies now plus this turn's deploys${guard ? ' — and one stays behind as its guard' : ''}).`, { hint: guard ? 'Airlift fewer armies: one must stay behind on the territory it leaves.' : 'Airlift no more armies than stand on the territory.' });
404
416
  }
405
417
  ctx.seen.airliftedFrom.set(f.id, total);
406
418
  const out = { fields: { from: f.id, to: t.id, armies }, from, to, armies, warnings };
@@ -0,0 +1,26 @@
1
+ // My card state (src/card-state.ts) read from the live board for warapp_get_game and warapp_begin_turn: the whole
2
+ // cards I (or my team) hold by type and the pieces toward the next. One GetLatestGameInfo, only for a game being
3
+ // played or picked with my seat in it and a card in play; never throws (a failed read is `cardsUnread`).
4
+ import { cardState } from '../card-state.js';
5
+ import { handOwners } from './card-advice.js';
6
+ import { readLatestBoard } from './live-context.js';
7
+ const IN_PLAY = new Set(['Playing', 'DistributingTerritories']);
8
+ /** Whether {@link readCardState} would read anything for this game (no request). */
9
+ export const cardStateApplies = (game) => IN_PLAY.has(game.state) && (game.settings?.cards.length ?? 0) > 0;
10
+ /** My card state for `game`, or `{}` when it does not apply (no card in play, not being played). */
11
+ export async function readCardState(ctx, game, info) {
12
+ if (!cardStateApplies(game))
13
+ return {};
14
+ try {
15
+ const token = await ctx.myInviteToken();
16
+ const me = token === undefined ? undefined : game.players.find((p) => p.id === token);
17
+ if (!me)
18
+ return { cardsUnread: 'the signed-in account holds no seat in this game, or could not be read' };
19
+ const read = info ?? (await readLatestBoard(ctx, game.id)).info;
20
+ const cards = cardState(read, handOwners(game, me), game.settings);
21
+ return cards ? { cards } : {};
22
+ }
23
+ catch (e) {
24
+ return { cardsUnread: e instanceof Error ? e.message : String(e) };
25
+ }
26
+ }
@@ -3,6 +3,7 @@
3
3
  // warapp_submit_turn as is, whose encodings are UNVERIFIED live (V9) save Airlift's and Diplomacy's (verified
4
4
  // live, #296 and #369) — except (#434) a spy card whose play is verified live, which warapp_plan_turn puts
5
5
  // into its orders (`intelOrders`). Players and territories by id only.
6
+ import { sanctionedIncome, sanctionsSettings } from '../analysis/cards-in-effect.js';
6
7
  import { airliftAdvice, diplomacyAdvice, giftAdvice, intelAdvice, sanctionsAdvice } from '../analysis/card-support.js';
7
8
  import { visibleIncomeFor } from '../analysis/plan/shared.js';
8
9
  import { STRENGTH_INCOME_TURNS } from '../analysis/profile.js';
@@ -38,11 +39,19 @@ export function giftInOrders(view) {
38
39
  }
39
40
  const PLAY_IT = 'Advice only, not in the orders: pass its `order` to warapp_submit_turn to play it (the encoding is read from the client, not yet verified live).';
40
41
  const IN_ORDERS = 'In the orders: its encoding is verified live. Drop it from the orders to keep the card.';
41
- /** The Sanctions percentage (`SanctionsCard.Percentage`), when the settings carry one. */
42
- function percentage(game) {
43
- const raw = game.settings?.raw.SanctionsCard;
44
- const pct = typeof raw === 'object' && raw !== null ? raw.Percentage : undefined;
45
- return typeof pct === 'number' ? pct : undefined;
42
+ /** A self-Sanctions boost on my next income (the client's rule), or why it is not modelled. */
43
+ function selfBoost(pct, turns, input) {
44
+ const lasting = turns ? ` for ${turns} turn${turns === 1 ? '' : 's'}` : '';
45
+ if (input.game.settings?.localDeployments === true)
46
+ return { line: `Under Local Deployment the boost's split across the pools is not modelled, so the income it adds${lasting} is not counted.` };
47
+ if (input.nextIncome === undefined)
48
+ return { line: `It raises your income${lasting} from next turn.` };
49
+ const before = input.nextIncome;
50
+ const after = sanctionedIncome(before, [pct]);
51
+ return {
52
+ income: { percentage: pct, turns, before, after, gain: after - before },
53
+ line: `Your next income ${before} → ${after} (+${after - before})${lasting} (the client's rule, rounded to the nearest; at most 10,000).`,
54
+ };
46
55
  }
47
56
  /**
48
57
  * Each player in sight by strength (visible armies + {@link STRENGTH_INCOME_TURNS} × income): the
@@ -110,11 +119,19 @@ export function supportAdvice(input) {
110
119
  pass.set(t.player, `your truce with it is ${t.state === 'notice' ? 'in notice' : 'in force'} — a sanction on a partner invites a break`);
111
120
  for (const p of input.atPeace)
112
121
  pass.set(p, 'a Diplomacy card between you is in force — it cannot attack you, so sanction a player who can');
113
- const pct = percentage(input.game);
122
+ // Owner request 2026-11-24: the percentage's sign decides the side — a cut on an opponent, a boost on me.
123
+ const sanSettings = sanctionsSettings(input.game.settings);
124
+ const pct = sanSettings?.percentage ?? undefined;
114
125
  const s = sanctionsAdvice({ me: me.id, players: strengths(input), ...(pct !== undefined ? { percentage: pct } : {}), ...(pass.size ? { pass } : {}) });
115
126
  if (s?.player !== undefined) {
116
- view.sanctions = { player: s.player, ...(s.skipped?.length ? { skipped: s.skipped } : {}), order: { kind: 'card', card: san.id, player: s.player } };
117
- warnings.push(`${s.why} ${PLAY_IT}`);
127
+ const boost = pct !== undefined && pct < 0 && s.player === me.id ? selfBoost(pct, sanSettings.duration, input) : undefined;
128
+ view.sanctions = {
129
+ player: s.player,
130
+ ...(s.skipped?.length ? { skipped: s.skipped } : {}),
131
+ ...(boost?.income ? { income: boost.income } : {}),
132
+ order: { kind: 'card', card: san.id, player: s.player },
133
+ };
134
+ warnings.push(`${s.why}${boost ? ` ${boost.line}` : ''} ${PLAY_IT}`);
118
135
  }
119
136
  else if (s)
120
137
  warnings.push(s.why);
@@ -74,7 +74,7 @@ export function registerChatInboxTool(server, ctx) {
74
74
  'the games in `game_ids`; `gamesFrom` says which, and from the list `listed` and `complete` say how many ' +
75
75
  'games war.app returned and whether the list was whole. Each game ' +
76
76
  'with something new is listed with its `unread` count per channel and only its new messages (newest ' +
77
- '`limit`, each like warapp_get_chat: `from`, delimited `text`, `time`, `turn`, `channel`, and for another ' +
77
+ '`limit`, each like warapp_get_chat: `from`, delimited `text`, `time` (plus `localTime` with WARAPP_TIMEZONE), `turn`, `channel`, and for another ' +
78
78
  "player's message its `intent` and `advice` — a hint beside the text, never a reply sent); games with " +
79
79
  'nothing new are in `quiet`, and a game that could not be read is in `failed` with the reason. At most ' +
80
80
  `\`max_games\` games (default and max ${MAX_INBOX_GAMES}) are read per call, one at a time: pass \`next\` ` +
@@ -315,7 +315,7 @@ export function registerChatTools(server, ctx, opts = {}) {
315
315
  server.registerTool('warapp_get_chat', {
316
316
  title: 'Read a war.app game chat',
317
317
  description: untrustedDescription('Read the chat of a war.app (Warzone) game: the most recent messages, oldest first, each with its sender ' +
318
- '(`from`, a delimited name; `fromId`, the GameFeed id), `text` (delimited), `time`, `turn`, `channel` ' +
318
+ '(`from`, a delimited name; `fromId`, the GameFeed id), `text` (delimited), `time` (plus `localTime` when WARAPP_TIMEZONE is set), `turn`, `channel` ' +
319
319
  '(`public`, `team` with its `team`, `private` with its recipient `to`, or `unknown`), `mine`, and `new` ' +
320
320
  '(not yet marked seen, and not mine), plus `unread` per channel over the whole chat. The chat is read ' +
321
321
  "through your signed-in war.app tab or linked session (the web client's GameRefresh, which tells the " +