@chrischall/warapp-mcp 0.4.0 → 0.6.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 (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +41 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +48009 -39350
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +46 -4
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/my-games.js +1 -1
  47. package/dist/normalize.js +17 -0
  48. package/dist/profile-store.js +12 -2
  49. package/dist/protocol/bundle.js +28 -10
  50. package/dist/protocol/codec.js +1 -1
  51. package/dist/protocol/dialect.js +371 -0
  52. package/dist/protocol/interp.js +143 -66
  53. package/dist/protocol/methods.js +95 -34
  54. package/dist/protocol/rpc.js +35 -3
  55. package/dist/push/socketio.js +2 -2
  56. package/dist/relations-store.js +38 -4
  57. package/dist/siege-store.js +49 -0
  58. package/dist/state-bundle.js +525 -0
  59. package/dist/state-cli.js +69 -0
  60. package/dist/surrender-pending.js +4 -4
  61. package/dist/team-cards.js +25 -0
  62. package/dist/tools/award.js +15 -1
  63. package/dist/tools/card-advice.js +16 -5
  64. package/dist/tools/card-plays.js +2 -2
  65. package/dist/tools/card-support-advice.js +2 -1
  66. package/dist/tools/chat-inbox.js +36 -3
  67. package/dist/tools/chat-read-mark.js +3 -1
  68. package/dist/tools/chat.js +65 -6
  69. package/dist/tools/check-plan.js +54 -10
  70. package/dist/tools/commerce-deploy.js +33 -0
  71. package/dist/tools/common.js +31 -0
  72. package/dist/tools/end-of-game.js +5 -3
  73. package/dist/tools/index.js +7 -0
  74. package/dist/tools/my-games.js +10 -3
  75. package/dist/tools/notifications.js +2 -2
  76. package/dist/tools/picks.js +12 -0
  77. package/dist/tools/profile-opponents.js +2 -0
  78. package/dist/tools/push.js +2 -1
  79. package/dist/tools/relations.js +137 -0
  80. package/dist/tools/state.js +227 -0
  81. package/dist/tools/stress-opponents.js +5 -2
  82. package/dist/tools/surrender-pending.js +11 -6
  83. package/dist/tools/survival.js +11 -3
  84. package/dist/tools/team-brief.js +2 -2
  85. package/dist/tools/team.js +12 -3
  86. package/dist/tools/turn.js +332 -60
  87. package/dist/version.js +1 -1
  88. package/manifest.json +10 -2
  89. package/mint.yaml +14 -4
  90. package/package.json +4 -4
  91. package/server.json +2 -2
  92. package/skills/warapp-mcp/SKILL.md +31 -9
@@ -1,37 +1,41 @@
1
1
  // war.app web-client method ids (the int32 in every frame header) and the
2
- // parameter writers this server uses. The name is also the `m=` query value of
2
+ // parameter writers this server uses. The ids are protocol 243's: 243 inserted six methods
3
+ // (ChangeCommitConfirmation 26, TeamSurrender 70, TournamentGroup 94, UploadSharedImage 129,
4
+ // ChatRoomReactionsChanged 247, SetReaction 285) and renumbered everything after each. The name is also the `m=` query value of
3
5
  // https://war.app/Services?m=<name>&js=1.
4
6
  export const Method = {
5
7
  /** Exists in the client's method table, but the web client never calls it (open games come from a page). */
6
8
  GetOpenGames: 10,
7
- GetGameDetails: 38,
8
- GameRefresh: 39,
9
- GetLatestGameInfo: 40,
10
- SendChat: 42,
11
- RegisterChatView: 43,
12
- GetGameSettings: 48,
13
- GetMyGames: 50,
14
- AcceptGame: 60,
15
- AcceptOpenSeat: 61,
16
- AcceptOpenAutoGame: 62,
17
- GetOpenAutoGame: 63,
18
- DeclineGame: 64,
19
- Surrender: 67,
20
- AcceptSurrender: 68,
21
- GetMapDetails: 73,
22
- SendOrders: 74,
23
- SendInProgressOrders: 75,
24
- SendTerritoryPicks: 76,
25
- SendInProgressPicks: 77,
26
- BeginFirstTurn: 78,
27
- GetTerritoryPicks: 79,
28
- UnCommit: 80,
29
- GetTurns: 81,
30
- Subscribe: 238,
31
- GameUpdated: 241,
32
- GetInAppNotifications: 317,
33
- DeleteInAppNotification: 318,
34
- AcknowledgeInAppNotifications: 319,
9
+ GetGameDetails: 39,
10
+ GameRefresh: 40,
11
+ GetLatestGameInfo: 41,
12
+ SendChat: 43,
13
+ RegisterChatView: 44,
14
+ RetrieveChat: 45,
15
+ RetrievePrivateMessageHistory: 46,
16
+ GetGameSettings: 49,
17
+ GetMyGames: 51,
18
+ AcceptGame: 61,
19
+ AcceptOpenSeat: 62,
20
+ AcceptOpenAutoGame: 63,
21
+ GetOpenAutoGame: 64,
22
+ DeclineGame: 65,
23
+ Surrender: 68,
24
+ AcceptSurrender: 69,
25
+ GetMapDetails: 75,
26
+ SendOrders: 76,
27
+ SendInProgressOrders: 77,
28
+ SendTerritoryPicks: 78,
29
+ SendInProgressPicks: 79,
30
+ BeginFirstTurn: 80,
31
+ GetTerritoryPicks: 81,
32
+ UnCommit: 82,
33
+ GetTurns: 83,
34
+ Subscribe: 242,
35
+ GameUpdated: 245,
36
+ GetInAppNotifications: 323,
37
+ DeleteInAppNotification: 324,
38
+ AcknowledgeInAppNotifications: 325,
35
39
  };
36
40
  const NAMES = new Map(Object.entries(Method).map(([name, id]) => [id, name]));
37
41
  /** The method's name for a known id, or undefined. */
@@ -271,6 +275,8 @@ export function writeGameRefreshParams(w, p) {
271
275
  .string(NO_CHAT_MARKER)
272
276
  .bool(p.lobby)
273
277
  .bool(false)
278
+ .bool(false)
279
+ // Protocol 243 added a last, optional value (a nullable number the client sends as text): absent.
274
280
  .bool(false);
275
281
  }
276
282
  /** A chat read mark: a message id as decimal text, or `-1` (the client's "no mark"). */
@@ -300,11 +306,42 @@ export function writeRegisterChatViewParams(w, p) {
300
306
  writeMarkDict(w, p.privateMarks);
301
307
  writeMarkDict(w, p.groupMarks);
302
308
  }
309
+ /**
310
+ * The "older than" marker of a chat history read when nothing has been received on that channel yet: the
311
+ * client's 9999E14 (its initial lowest-id-received), written as text.
312
+ */
313
+ export const OLDEST_CHAT_MARKER = '999900000000000000';
314
+ const MESSAGE_ID_TEXT = /^\d{1,20}$/;
315
+ function beforeMarker(m) {
316
+ if (m === undefined)
317
+ return OLDEST_CHAT_MARKER;
318
+ if (!MESSAGE_ID_TEXT.test(m))
319
+ throw new RangeError(`not a message id: ${JSON.stringify(m)}`);
320
+ return m;
321
+ }
322
+ /**
323
+ * RetrieveChat(auth, …) — the web client's "show older messages" for the public and team channels (#363). READ
324
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, then per channel the lowest message id the client has
325
+ * received (string; 9999E14 when none). Reply: a result flag, then a list of optional `GameMessage` (as the
326
+ * SendChat reply). GameRefresh with `-1` markers leaves out messages war.app counts as seen (an own team
327
+ * message, seen live 2026-11-19); this read returns them.
328
+ */
329
+ export function writeRetrieveChatParams(w, p) {
330
+ w.int32(p.gameId).string(beforeMarker(p.publicBefore)).string(beforeMarker(p.teamBefore));
331
+ }
332
+ /**
333
+ * RetrievePrivateMessageHistory(auth, …) — the client's history button of one private conversation (#387). READ
334
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, the lowest message id received in it (string; 9999E14 when
335
+ * none), the counterpart's in-game id (int32). Reply as RetrieveChat's.
336
+ */
337
+ export function writeRetrievePrivateMessageHistoryParams(w, p) {
338
+ w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
339
+ }
303
340
  /**
304
341
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
305
342
  * serializer; the owner verifies it live): game id, text, channel, optional
306
343
  * private recipient, optional game-group id (absent), two marker strings
307
- * (absent), two optional "last seen" dicts (absent). An optional int32 is a
344
+ * (`-1`: seen nothing), two optional "last seen" dicts (absent). An optional int32 is a
308
345
  * present flag then the value.
309
346
  */
310
347
  export function writeSendChatParams(w, p) {
@@ -313,10 +350,14 @@ export function writeSendChatParams(w, p) {
313
350
  w.bool(false);
314
351
  else
315
352
  w.bool(true).int32(p.recipient);
353
+ // The two chat markers are the last message seen on each channel: war.app parses them as numbers
354
+ // (ParseLongSafe), so a null one is refused (server error 1); a client that has seen nothing sends `-1`.
316
355
  w.bool(false) // game-group id
317
- .string(null)
318
- .string(null)
356
+ .string(NO_CHAT_MARKER)
357
+ .string(NO_CHAT_MARKER)
319
358
  .bool(false)
359
+ .bool(false)
360
+ // Protocol 243 added a last, optional list of strings (the shared images a message carries): absent.
320
361
  .bool(false);
321
362
  }
322
363
  // ---------------------------------------------------------------------------
@@ -341,6 +382,17 @@ export function writeDeployOrder(w, o) {
341
382
  .int32(o.armies);
342
383
  writeOrderBase(w, o.playerId);
343
384
  }
385
+ const ORDER_TAG_PURCHASE = 24;
386
+ /**
387
+ * Encode a Purchase order (`GameOrderPurchase`, client 6.08.0.2's writer; UNVERIFIED live): tag 24, a present bool,
388
+ * an int32 count of territory → cities entries, each two int32s, then the order base.
389
+ */
390
+ export function writePurchaseOrder(w, o) {
391
+ w.u8(ORDER_TAG_PURCHASE).bool(true).int32(o.cities.length);
392
+ for (const c of o.cities)
393
+ w.int32(c.territoryId).int32(c.count);
394
+ writeOrderBase(w, o.playerId);
395
+ }
344
396
  /** The special-unit tag of a Commander (`warlight.shared.Commander`, from the bundle; docs/WEB-PROTOCOL.md). */
345
397
  const SPECIAL_UNIT_COMMANDER = 1;
346
398
  /**
@@ -402,9 +454,11 @@ export const TARGETED_CARD_PLAYS = new Set([
402
454
  ]);
403
455
  /**
404
456
  * The card plays whose encoding is read from the bundle but not yet sent live (V9): the preview warns
405
- * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296).
457
+ * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296), Diplomacy
458
+ * once verified live 2026-11-18 (#369: played through warapp_submit_turn, read in force on later boards).
406
459
  */
407
- export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => kind !== 'Airlift'));
460
+ const VERIFIED_CARD_PLAYS = new Set(['Airlift', 'Diplomacy']);
461
+ export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => !VERIFIED_CARD_PLAYS.has(kind)));
408
462
  function need(v, card, what) {
409
463
  if (v === undefined)
410
464
  throw new Error(`A ${card} card play needs ${what}.`);
@@ -484,6 +538,8 @@ export function writeDiscardOrder(w, o) {
484
538
  * from the bundle's `GameOrderDiscard.Vd`).
485
539
  */
486
540
  export const TurnPhase = {
541
+ /** #332, bundle (`GameOrderPurchase`), UNVERIFIED live: a commerce game's purchase, before every other order. */
542
+ Purchases: 0,
487
543
  Discards: 10,
488
544
  OrderPriorityCards: 12,
489
545
  /** Spy, Reconnaissance and Surveillance (bundle, UNVERIFIED live). */
@@ -528,6 +584,8 @@ export function turnPhaseOf(o) {
528
584
  return TurnPhase.Attacks;
529
585
  if (o.kind === 'discard')
530
586
  return TurnPhase.Discards;
587
+ if (o.kind === 'purchase')
588
+ return TurnPhase.Purchases;
531
589
  return CARD_PHASE[o.card];
532
590
  }
533
591
  /**
@@ -603,6 +661,9 @@ export function writeSendOrdersParams(w, gameId, playerId, orders, turnNumber) {
603
661
  else if (o.kind === 'discard') {
604
662
  writeDiscardOrder(w, { playerId, cardId: o.cardId });
605
663
  }
664
+ else if (o.kind === 'purchase') {
665
+ writePurchaseOrder(w, { playerId, cities: o.cities });
666
+ }
606
667
  else if (o.kind === 'deploy') {
607
668
  writeDeployOrder(w, { playerId, territoryId: o.territoryId, armies: o.armies });
608
669
  }
@@ -8,7 +8,7 @@ import { scrubSecrets } from '../redact.js';
8
8
  import { decodeReplyEnvelope, encodeRequest, PROTOCOL_VERSION, fromHex, ProtocolError, toHex, } from './codec.js';
9
9
  import { Method } from './methods.js';
10
10
  /** The client version string the current web client sends. */
11
- export const CLIENT_VERSION = 'v6.07.0.1';
11
+ export const CLIENT_VERSION = 'v6.08.0.2';
12
12
  /** EnumSerialization_Platform: the website. */
13
13
  export const PLATFORM_WEBSITE = 15;
14
14
  /**
@@ -45,6 +45,14 @@ export const SERVER_ERROR_MESSAGES = {
45
45
  254: 'Sorry, your slot was assigned to someone else by the game creator. Please ask the game creator to open up your slot.',
46
46
  473: "You don't have enough coins to join this game. Please deposit some coins and try again.",
47
47
  750: 'Sorry, the slot you joined is no longer available. Please try again with a different slot.',
48
+ // #332, commerce games: the client names these but shows no wording; these are ours.
49
+ 593: 'war.app worked out a different gold cost for these orders than the client did (ExpectedCostInaccurate).',
50
+ 596: 'In a commerce game every deploy must be paid for in gold (DeploymentsCannotBeFree).',
51
+ 597: 'You do not have enough gold for these orders (InsufficientGold): deploy fewer armies or buy fewer cities.',
52
+ 599: 'Only one purchase order may be sent in a turn (CannotSendDuplicatePurchaseOrders).',
53
+ 600: 'A city can only be built on a territory you hold (CannotBuildCityOnAnotherPlayersTerritory).',
54
+ 601: 'The number of cities to build cannot be negative (CannotBuildNegativeCitites).',
55
+ 602: 'This game does not allow cities (CannotBuildCities).',
48
56
  };
49
57
  /** The longest slice of an unmapped server message shown to the caller. */
50
58
  const MAX_SERVER_MESSAGE = 200;
@@ -67,8 +75,8 @@ export class ProtocolVersionError extends McpToolError {
67
75
  export class WarappServerError extends McpToolError {
68
76
  code;
69
77
  name = 'WarappServerError';
70
- constructor(code, message) {
71
- super(message, { kind: 'unknown' });
78
+ constructor(code, message, hint) {
79
+ super(message, { kind: 'unknown', ...(hint ? { hint } : {}) });
72
80
  this.code = code;
73
81
  }
74
82
  }
@@ -202,7 +210,31 @@ export class WarappRpc {
202
210
  this.state.kFa = down.unreadMail.kFa;
203
211
  }
204
212
  }
213
+ /** war.app's `ClientOutOfDate`: the protocol this server speaks is older than war.app still accepts. */
214
+ export const CLIENT_OUT_OF_DATE = 48;
215
+ /** war.app's `ClientVersionTooHigh`: the client version this server sends is newer than war.app knows. */
216
+ export const CLIENT_VERSION_TOO_HIGH = 49;
217
+ /**
218
+ * war.app refused this server's client as out of date (48) or too new (49). Probed live 2026-11-17: war.app
219
+ * keeps answering about 21 older protocols, and a request below that window gets 48 — the sign that war.app
220
+ * has retired the protocol this server speaks, which no retry or relink fixes: only the update in
221
+ * docs/CLIENT-RELEASES.md ("Updating to a new client") does.
222
+ */
223
+ export class ClientOutOfDateError extends WarappServerError {
224
+ name = 'ClientOutOfDateError';
225
+ constructor(methodName, code) {
226
+ super(code, code === CLIENT_OUT_OF_DATE
227
+ ? `war.app refused ${methodName} as ClientOutOfDate (war.app error 48): it no longer accepts protocol ` +
228
+ `${PROTOCOL_VERSION}, the one this server speaks, so every war.app call through the web protocol will fail ` +
229
+ 'until this server is updated to war.app’s current client.'
230
+ : `war.app refused ${methodName} as ClientVersionTooHigh (war.app error 49): it does not know client ` +
231
+ `${CLIENT_VERSION}, the version this server sends.`, 'This server needs an update to war.app’s current client: see docs/CLIENT-RELEASES.md, "Updating to a new ' +
232
+ 'client". Retrying or signing in again will not help.');
233
+ }
234
+ }
205
235
  function serverError(methodName, code, message, email) {
236
+ if (code === CLIENT_OUT_OF_DATE || code === CLIENT_VERSION_TOO_HIGH)
237
+ return new ClientOutOfDateError(methodName, code);
206
238
  const known = SERVER_ERROR_MESSAGES[code];
207
239
  if (known)
208
240
  return new WarappServerError(code, `${known} (war.app error ${code})`);
@@ -4,7 +4,7 @@ import { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets
4
4
  import { realSetTimer, runWebSocketSession, WebSocketUnavailableError } from './websocket.js';
5
5
  export { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets.js';
6
6
  export const POST_CONTENT_TYPE = 'text/plain;charset=UTF-8';
7
- /** A Subscribe frame (method 238, no auth block) as the uppercase hex a message packet carries. */
7
+ /** A Subscribe frame (method 242 in protocol 243, no auth block) as the uppercase hex a message packet carries. */
8
8
  export function subscribeFrameHex(topics, msgNum, extras) {
9
9
  return toHex(encodeRequest({
10
10
  method: Method.Subscribe,
@@ -16,7 +16,7 @@ export function subscribeFrameHex(topics, msgNum, extras) {
16
16
  }
17
17
  /**
18
18
  * Decode a frame from a message packet. A server push is a request-shaped
19
- * frame (MessageExtrasUp, no auth): GameUpdated (241) starts with the game id,
19
+ * frame (MessageExtrasUp, no auth): GameUpdated (245 in protocol 243) starts with the game id,
20
20
  * then two bools the client logs as `chat` and `nonChat` (read from the bundle's
21
21
  * handler; UNVERIFIED live), then an optional dict this server does not read.
22
22
  * The flags are read only when present: a push without them is a plain update.
@@ -9,6 +9,9 @@
9
9
  // `commitments` (part B4): what my chat messages promised (warapp_send_chat's declared commitments,
10
10
  // never the text), recorded once a message is sent; warapp_submit_turn warns when orders break one.
11
11
  //
12
+ // `intel` (#386): avoid targets and stated incomes from diplomacy (warapp_record_intel), applied by
13
+ // warapp_plan_turn and warapp_check_plan by default.
14
+ //
12
15
  // `usage` (part B2): per planned turn, what each honoured truce freed and what a break would have
13
16
  // cost (rule T6: the armies and the income); warapp_plan_turn calls `recordTruceUsage`.
14
17
  import { randomUUID } from 'node:crypto';
@@ -17,6 +20,7 @@ import { join } from 'node:path';
17
20
  import { withPathLock } from './path-lock.js';
18
21
  import { AGREEMENT_STATUSES, MAX_NOTICE_TURNS, } from './analysis/relations.js';
19
22
  import { COMMITMENT_KINDS } from './analysis/commitments.js';
23
+ import { AVOID_REASONS, intelIsEmpty } from './analysis/intel.js';
20
24
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
21
25
  const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
22
26
  const ints = (v) => (Array.isArray(v) && v.every(isInt) ? [...v] : undefined);
@@ -26,6 +30,9 @@ export const MAX_AGREEMENTS = 50;
26
30
  export const MAX_USAGE_TURNS = 200;
27
31
  /** Commitments kept per game (the newest). */
28
32
  export const MAX_COMMITMENTS = 200;
33
+ /** #386: intel entries kept per game and kind (the newest). */
34
+ export const MAX_INTEL_TERRITORIES = 200;
35
+ export const MAX_INTEL_PLAYERS = 50;
29
36
  export const relationsDir = (dir) => join(dir, 'relations');
30
37
  export const relationsPath = (dir, gameId, playerId) => join(relationsDir(dir), `${gameId}-${playerId}.json`);
31
38
  const AGREEMENT_ID = /^a(\d{1,9})$/;
@@ -122,6 +129,24 @@ export function nextCommitmentId(ledger) {
122
129
  const n = (ledger.commitments ?? []).reduce((m, c) => Math.max(m, Number(COMMITMENT_ID.exec(c.id)?.[1] ?? 0)), 0);
123
130
  return `c${n + 1}`;
124
131
  }
132
+ /** #386: the intel of a ledger file, the unusable entries dropped; absent when none. */
133
+ export function intelOf(v) {
134
+ if (!isRec(v))
135
+ return {};
136
+ const list = (x) => (Array.isArray(x) ? x.filter(isRec) : []);
137
+ const intel = {
138
+ avoidTerritories: list(v.avoidTerritories)
139
+ .filter((a) => isInt(a.territory) && isInt(a.turn))
140
+ .map((a) => ({ territory: a.territory, turn: a.turn, ...(isInt(a.promisedTo) ? { promisedTo: a.promisedTo } : {}) })),
141
+ avoidPlayers: list(v.avoidPlayers)
142
+ .filter((a) => isInt(a.player) && isInt(a.turn) && typeof a.reason === 'string' && AVOID_REASONS.includes(a.reason))
143
+ .map((a) => ({ player: a.player, turn: a.turn, reason: a.reason })),
144
+ incomes: list(v.incomes)
145
+ .filter((a) => isInt(a.player) && isInt(a.income) && a.income >= 0 && isInt(a.turn))
146
+ .map((a) => ({ player: a.player, income: a.income, turn: a.turn })),
147
+ };
148
+ return intelIsEmpty(intel) ? {} : { intel };
149
+ }
125
150
  function usageOf(v) {
126
151
  if (!isRec(v))
127
152
  return {};
@@ -153,7 +178,7 @@ export async function readLedger(dir, gameId, playerId) {
153
178
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
154
179
  return undefined;
155
180
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
156
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
181
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
157
182
  }
158
183
  catch {
159
184
  return undefined;
@@ -177,7 +202,7 @@ export async function readLedgerForWrite(dir, gameId, playerId) {
177
202
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
178
203
  return 'unreadable';
179
204
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
180
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
205
+ return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel) };
181
206
  }
182
207
  catch {
183
208
  return 'unreadable';
@@ -200,8 +225,17 @@ export function boundLedger(ledger) {
200
225
  .slice(0, MAX_USAGE_TURNS)
201
226
  .sort((a, b) => a - b);
202
227
  const commitments = ledger.commitments?.length ? { commitments: ledger.commitments.slice(-MAX_COMMITMENTS) } : {};
203
- const { commitments: _all, ...rest } = ledger;
204
- return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments };
228
+ const { commitments: _all, intel: _intel, ...rest } = ledger;
229
+ const intel = intelIsEmpty(ledger.intel)
230
+ ? {}
231
+ : {
232
+ intel: {
233
+ avoidTerritories: ledger.intel.avoidTerritories.slice(-MAX_INTEL_TERRITORIES),
234
+ avoidPlayers: ledger.intel.avoidPlayers.slice(-MAX_INTEL_PLAYERS),
235
+ incomes: ledger.intel.incomes.slice(-MAX_INTEL_PLAYERS),
236
+ },
237
+ };
238
+ return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel };
205
239
  }
206
240
  /** Write the ledger (bounded), atomically, 0600. `true` when written; never throws. */
207
241
  export async function writeLedger(dir, ledger) {
@@ -0,0 +1,49 @@
1
+ // The siege's memory on disk (#382): per game and account, at `<dataDir>/siege/<gameId>-<playerId>.json`,
2
+ // the target and each planned siege turn (the target's income, mine, the bonuses that turn's plan broke).
3
+ // Ids and numbers only, never a name; 0600 in a 0700 directory, written atomically under the in-process
4
+ // path lock. Written by warapp_plan_turn under `goal: 'siege'` (not with `enemy_deploy`, a what-if) and
5
+ // read back as `PlanInput.siegeMemory`. Reads are loose: an unusable file is no memory, an unusable turn
6
+ // is dropped; nothing here throws.
7
+ import { randomUUID } from 'node:crypto';
8
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
9
+ import { join } from 'node:path';
10
+ import { withPathLock } from './path-lock.js';
11
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
12
+ const isInt = (v) => typeof v === 'number' && Number.isSafeInteger(v);
13
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
14
+ export const siegeDir = (dir) => join(dir, 'siege');
15
+ export const siegePath = (dir, gameId, playerId) => join(siegeDir(dir), `${gameId}-${playerId}.json`);
16
+ function turnOf(v) {
17
+ if (!isRec(v) || !isInt(v.turn) || !isNum(v.opponentIncome) || !isNum(v.myIncome))
18
+ return undefined;
19
+ const breaks = Array.isArray(v.breaks) && v.breaks.every(isInt) ? [...v.breaks] : [];
20
+ return { turn: v.turn, opponentIncome: v.opponentIncome, myIncome: v.myIncome, breaks };
21
+ }
22
+ /** The siege memory kept for `gameId` as `playerId`; `undefined` when none or unusable. Never throws. */
23
+ export async function readSiegeMemory(dir, gameId, playerId) {
24
+ try {
25
+ const c = JSON.parse(await readFile(siegePath(dir, gameId, playerId), 'utf8'));
26
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isInt(c.target) || !Array.isArray(c.turns))
27
+ return undefined;
28
+ return { target: c.target, turns: c.turns.map(turnOf).filter((t) => t !== undefined) };
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ /** Write the siege memory, atomically, 0600. `true` when written; never throws. */
35
+ export async function writeSiegeMemory(dir, gameId, playerId, memory) {
36
+ const path = siegePath(dir, gameId, playerId);
37
+ return withPathLock(path, async () => {
38
+ try {
39
+ await mkdir(siegeDir(dir), { recursive: true, mode: 0o700 });
40
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
41
+ await writeFile(tmp, JSON.stringify({ gameId, playerId, target: memory.target, turns: memory.turns }), { mode: 0o600 });
42
+ await rename(tmp, path);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ });
49
+ }