hoi4-agent-tools 4.8.0 → 4.9.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 (79) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/hoi4_agent_tools/core/index.js +28 -0
  3. package/dist/hoi4_agent_tools/decision/service.js +39 -2
  4. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  5. package/dist/hoi4_agent_tools/event/service.js +66 -11
  6. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  7. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  8. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -2
  9. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  10. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  11. package/dist/hoi4_agent_tools/map/world.js +158 -34
  12. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +57 -9
  13. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  14. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  15. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  16. package/dist/hoi4_agent_tools/mcp/tools/event.js +13 -0
  17. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  18. package/dist/hoi4_agent_tools/mcp/tools/reference.js +25 -0
  19. package/dist/hoi4_agent_tools/reference/error-log.js +35 -1
  20. package/dist/hoi4_agent_tools/reference/operations.js +141 -14
  21. package/dist/hoi4_agent_tools/reference/script-validation.js +113 -2
  22. package/dist/hoi4_agent_tools/schemas/ideas.js +4 -4
  23. package/dist/hoi4_agent_tools/schemas/map.js +32 -4
  24. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  25. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  26. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  27. package/dist/hoi4_agent_tools/version.js +1 -1
  28. package/docs/analysis.md +2 -2
  29. package/docs/events.md +1 -1
  30. package/docs/map.md +19 -8
  31. package/docs/tools.md +49 -43
  32. package/engine/README.md +9 -0
  33. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  34. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  35. package/engine/bin/linux-x64/hoi4-engine +0 -0
  36. package/engine/bin/manifest.json +8 -8
  37. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
  40. package/schemas/configuration.schema.json +1 -1
  41. package/schemas/continuous-focus-palette.schema.json +1 -1
  42. package/schemas/custom-weighted-pool.schema.json +1 -1
  43. package/schemas/decision-inspect-input.schema.json +1 -1
  44. package/schemas/error-log-input.schema.json +1 -1
  45. package/schemas/event-feature-manifest.schema.json +1 -1
  46. package/schemas/focus-plan.schema.json +1 -1
  47. package/schemas/focus-planning-sidecar.schema.json +1 -1
  48. package/schemas/geography-model.schema.json +1 -1
  49. package/schemas/gui-animation-source.schema.json +1 -1
  50. package/schemas/gui-helper.schema.json +1 -1
  51. package/schemas/gui-scenario.schema.json +1 -1
  52. package/schemas/helper-expansion-request.schema.json +1 -1
  53. package/schemas/helper-expansion-summary.schema.json +1 -1
  54. package/schemas/impact-inspect-input.schema.json +1 -1
  55. package/schemas/map-operation.schema.json +165 -101
  56. package/schemas/mechanic-test-input.schema.json +1 -1
  57. package/schemas/mod-index-input.schema.json +1 -1
  58. package/schemas/operation-result.schema.json +1 -1
  59. package/schemas/package-check-input.schema.json +1 -1
  60. package/schemas/package-manifest.schema.json +1 -1
  61. package/schemas/probability-analysis-result.schema.json +1 -1
  62. package/schemas/probability-compare-input.schema.json +1 -1
  63. package/schemas/probability-evaluate-input.schema.json +1 -1
  64. package/schemas/probability-inspect-input.schema.json +1 -1
  65. package/schemas/probability-render-input.schema.json +1 -1
  66. package/schemas/probability-scenario-set.schema.json +1 -1
  67. package/schemas/probability-sequence-input.schema.json +1 -1
  68. package/schemas/probability-simulate-input.schema.json +1 -1
  69. package/schemas/probability-sweep-input.schema.json +1 -1
  70. package/schemas/reference-context-input.schema.json +1 -1
  71. package/schemas/reference-read-input.schema.json +1 -1
  72. package/schemas/reference-search-input.schema.json +1 -1
  73. package/schemas/reference-sheets.schema.json +1 -1
  74. package/schemas/scenario-suite.schema.json +1 -1
  75. package/schemas/scenario-test-input.schema.json +1 -1
  76. package/schemas/script-validate-input.schema.json +1 -1
  77. package/schemas/shared-scenario.schema.json +1 -1
  78. package/schemas/source-lookup-input.schema.json +1 -1
  79. package/server.json +2 -2
@@ -1,13 +1,27 @@
1
1
  /**
2
2
  * World edge and seam policy (ADR 0061). The engine wraps the map horizontally and draws it as a
3
3
  * sphere for day and night, so land that touches column 0 or the last column is cut by a straight
4
- * line where the world repeats. This module keeps land away from the seam and the poles, or ends
5
- * it in an impassable rim, and writes the north and south frame borders the base map has.
4
+ * line where the world repeats. This module keeps land away from the seam and the poles, ends it in
5
+ * an impassable rim, or closes the seam with an impassable wall over the full height, and writes the
6
+ * north and south frame borders the base map has.
6
7
  */
7
8
  import { ServiceError } from '../core/result.js';
8
- import { valueNoise } from './world-noise.js';
9
+ import { fractal, valueNoise } from './world-noise.js';
9
10
  const SEA = 0;
10
11
  const LAND = 1;
12
+ /** Land classes a wall can take its look from. */
13
+ export const WALL_TERRAIN_KINDS = [
14
+ 'snow',
15
+ 'mountain',
16
+ 'hills',
17
+ 'desert',
18
+ 'forest',
19
+ 'plains',
20
+ 'marsh',
21
+ 'jungle',
22
+ ];
23
+ /** Default wall width: its narrowest rows (60%) still hold a default 400-pixel land province. */
24
+ export const WALL_DEFAULT_PX = 48;
11
25
  /** Lowest height of the rim range at its inner foot, and its height at the seam. */
12
26
  export const RIM_FOOT_HEIGHT = 150;
13
27
  export const RIM_SEAM_HEIGHT = 230;
@@ -25,7 +39,10 @@ export function resolveEdge(input, width, height) {
25
39
  const polarLimit = Math.floor(height / 4);
26
40
  const bandPx = input.bandPx ?? Math.min(Math.max(192, Math.round(0.04 * width)), quarter);
27
41
  const polarPx = input.polarPx ?? Math.min(64, Math.floor(height / 8));
28
- const rimPx = input.rimPx ?? Math.min(160, quarter);
42
+ // A wall closes the seam at any width; the default is the narrowest that still forms its own
43
+ // provinces at the usual province sizes, so it costs as little of the picture as possible.
44
+ const rimPx = input.rimPx ?? Math.min(mode === 'wall' ? WALL_DEFAULT_PX : 160, quarter);
45
+ const ranged = mode === 'rim' || mode === 'wall';
29
46
  if (bandPx > quarter || rimPx > quarter || polarPx > polarLimit)
30
47
  throw new ServiceError('MAP_EDGE_BAND_TOO_WIDE', 'The edge band and rim may not exceed a quarter of the world width, nor the polar band a quarter of its height', { width, height, bandPx, rimPx, polarPx, maximumWidth: quarter, maximumHeight: polarLimit });
31
48
  if (mode === 'none')
@@ -34,9 +51,16 @@ export function resolveEdge(input, width, height) {
34
51
  mode,
35
52
  bandPx: mode === 'sea-band' ? bandPx : 0,
36
53
  polarPx,
37
- rimPx: mode === 'rim' ? rimPx : 0,
54
+ rimPx: ranged ? rimPx : 0,
55
+ ...(mode === 'wall' && input.wallTerrain !== undefined
56
+ ? { wallTerrain: input.wallTerrain }
57
+ : {}),
38
58
  };
39
59
  }
60
+ /** `rim` and `wall` both end land at the seam in a raised snow range. */
61
+ export function hasRimRange(edge) {
62
+ return edge.mode === 'rim' || edge.mode === 'wall';
63
+ }
40
64
  /** Cities and named land features may not stand where the policy clears land. */
41
65
  export function assertFeaturesOutsideBand(edge, width, height, features) {
42
66
  if (edge.mode === 'none')
@@ -45,7 +69,8 @@ export function assertFeaturesOutsideBand(edge, width, height, features) {
45
69
  if (feature.kind === 'sea')
46
70
  return false;
47
71
  const northSouth = feature.y < edge.polarPx || feature.y >= height - edge.polarPx;
48
- const eastWest = edge.mode === 'sea-band' && (feature.x < edge.bandPx || feature.x >= width - edge.bandPx);
72
+ const side = edge.mode === 'sea-band' ? edge.bandPx : edge.mode === 'wall' ? edge.rimPx : 0;
73
+ const eastWest = side > 0 && (feature.x < side || feature.x >= width - side);
49
74
  return northSouth || eastWest;
50
75
  });
51
76
  if (offenders.length === 0)
@@ -57,6 +82,7 @@ export function assertFeaturesOutsideBand(edge, width, height, features) {
57
82
  mode: edge.mode,
58
83
  bandPx: edge.bandPx,
59
84
  polarPx: edge.polarPx,
85
+ ...(edge.mode === 'wall' ? { rimPx: edge.rimPx } : {}),
60
86
  features: offenders.slice(0, 20),
61
87
  });
62
88
  }
@@ -64,13 +90,16 @@ export function assertFeaturesOutsideBand(edge, width, height, features) {
64
90
  function limits(edge, width, height, seed) {
65
91
  const rows = new Int32Array(height);
66
92
  const columns = new Int32Array(width);
67
- const scaleY = Math.max(8, edge.bandPx / 3);
93
+ const scaleY = Math.max(8, (edge.mode === 'wall' ? edge.rimPx : edge.bandPx) / 3);
68
94
  const scaleX = Math.max(8, edge.polarPx / 1.5);
69
95
  for (let y = 0; y < height; y += 1)
70
96
  rows[y] =
71
97
  edge.mode === 'sea-band'
72
98
  ? edge.bandPx + Math.round(valueNoise(seed + 9187, y / scaleY, 0.5) * edge.bandPx * 0.5)
73
- : 0;
99
+ : edge.mode === 'wall'
100
+ ? // The wall's inner edge is ragged like a coast, but never wider than the band itself.
101
+ Math.round(edge.rimPx * (0.6 + 0.4 * fractal(seed + 9187, 0.5, y, scaleY, 5)))
102
+ : 0;
74
103
  for (let x = 0; x < width; x += 1)
75
104
  columns[x] =
76
105
  edge.polarPx > 0
@@ -116,7 +145,9 @@ function landComponents(kind, width) {
116
145
  /**
117
146
  * Clear land and lakes from the east, west, north and south bands (modifying `kind` and
118
147
  * `elevation` in place). The outline is ragged so the cleared coast does not read as a ruled
119
- * line; land fragments the clearing detached sink when smaller than `minimumIsland`.
148
+ * line; land fragments the clearing detached sink when smaller than `minimumIsland`. A `wall`
149
+ * instead fills its east and west band with land over the full height, so no water reaches the
150
+ * seam, and returns the band as `wall`.
120
151
  */
121
152
  export function applyEdgePolicy(kind, elevation, width, height, edge, seed, minimumIsland) {
122
153
  if (edge.mode === 'none')
@@ -124,11 +155,24 @@ export function applyEdgePolicy(kind, elevation, width, height, edge, seed, mini
124
155
  const before = landComponents(kind, width);
125
156
  const { rows, columns } = limits(edge, width, height, seed);
126
157
  const cleared = new Uint8Array(kind.length);
158
+ const wall = edge.mode === 'wall' ? new Uint8Array(kind.length) : undefined;
127
159
  let clearedLand = 0;
160
+ let filledWater = 0;
128
161
  for (let y = 0; y < height; y += 1)
129
162
  for (let x = 0; x < width; x += 1) {
130
163
  const limitX = rows[y];
131
- const clear = x < limitX || x >= width - limitX || y < columns[x] || y >= height - columns[x];
164
+ const side = x < limitX || x >= width - limitX;
165
+ if (wall !== undefined && side) {
166
+ const pixel = y * width + x;
167
+ wall[pixel] = 1;
168
+ if (kind[pixel] !== LAND) {
169
+ filledWater += 1;
170
+ kind[pixel] = LAND;
171
+ elevation[pixel] = Math.max(elevation[pixel], 0.05);
172
+ }
173
+ continue;
174
+ }
175
+ const clear = (wall === undefined && side) || y < columns[x] || y >= height - columns[x];
132
176
  if (!clear)
133
177
  continue;
134
178
  const pixel = y * width + x;
@@ -152,14 +196,25 @@ export function applyEdgePolicy(kind, elevation, width, height, edge, seed, mini
152
196
  }
153
197
  reshapeClearedCoast(kind, elevation, cleared, width, height);
154
198
  const notes = [];
199
+ if (filledWater > 0)
200
+ notes.push({
201
+ code: 'MAP_EDGE_WALL_FILLED',
202
+ severity: 'info',
203
+ message: `The wall edge policy filled ${filledWater} water pixels of its east and west band with land, so no water reaches the seam`,
204
+ details: { mode: edge.mode, rimPx: edge.rimPx, filledWaterPixels: filledWater },
205
+ });
155
206
  if (clearedLand + sunk > 0)
156
207
  notes.push({
157
208
  code: 'MAP_EDGE_LAND_CLEARED',
158
209
  severity: 'warning',
159
- message: `The ${edge.mode} edge policy cleared ${clearedLand} land pixels to open sea${sunk > 0 ? ` and sank ${sunk} pixels of fragments it detached` : ''}; land that must reach the edge needs edge.mode "rim"`,
210
+ message: `The ${edge.mode} edge policy cleared ${clearedLand} land pixels to open sea${sunk > 0 ? ` and sank ${sunk} pixels of fragments it detached` : ''}; land that must reach the edge needs edge.mode "rim" or "wall"${edge.mode === 'wall' ? ', and land that must reach the poles needs polarPx 0' : ''}`,
160
211
  details: { mode: edge.mode, clearedLandPixels: clearedLand, sunkFragmentPixels: sunk },
161
212
  });
162
- return { notes, clearedLandPixels: clearedLand + sunk };
213
+ return {
214
+ notes,
215
+ clearedLandPixels: clearedLand + sunk,
216
+ ...(wall === undefined ? {} : { wall }),
217
+ };
163
218
  }
164
219
  /**
165
220
  * Give the new coast a shelf and a coastal land ramp, as the reference interpretation does for
@@ -229,10 +284,56 @@ function smooth(t) {
229
284
  return clamped * clamped * (3 - 2 * clamped);
230
285
  }
231
286
  /**
232
- * Rim strength 0 to 1 at a column: 0 at the inner foot, 1 at the seam. Zero outside `rim` mode.
287
+ * The look of the wall row by row on each side. Each row takes the kind of the nearest land
288
+ * beyond the wall within four wall widths, short of the other side's wall; a row that meets only water is snow in the outer
289
+ * fifths of the map and mountain elsewhere. Kinds are smoothed by a majority over about half a
290
+ * wall width of rows, so the look changes in stretches, and caller segments win over all of it.
291
+ */
292
+ export function wallRowKinds(input) {
293
+ const { edge, width, height, wall } = input;
294
+ const reach = Math.max(16, edge.rimPx * 4);
295
+ const fallback = (y) => y < height * 0.2 || y >= height * 0.8 ? 'snow' : 'mountain';
296
+ const side = (step) => {
297
+ const raw = [];
298
+ for (let y = 0; y < height; y += 1) {
299
+ let x = step === 1 ? 0 : width - 1;
300
+ while (x >= 0 && x < width && wall[y * width + x] === 1)
301
+ x += step;
302
+ let found;
303
+ for (let distance = 0; distance < reach && x >= 0 && x < width; distance += 1, x += step) {
304
+ // The other side's wall ends the search: a narrow map meets only water.
305
+ if (wall[y * width + x] === 1)
306
+ break;
307
+ found = input.landKind(y * width + x);
308
+ if (found !== undefined)
309
+ break;
310
+ }
311
+ raw.push(found ?? fallback(y));
312
+ }
313
+ const window = Math.max(8, Math.round(edge.rimPx / 2));
314
+ const smoothed = [];
315
+ for (let y = 0; y < height; y += 1) {
316
+ const counts = new Map();
317
+ for (let other = Math.max(0, y - window); other <= Math.min(height - 1, y + window); other++)
318
+ counts.set(raw[other], (counts.get(raw[other]) ?? 0) + 1);
319
+ // Ties keep the row's own kind, then the order of WALL_TERRAIN_KINDS.
320
+ smoothed.push([...counts].sort(([a, left], [b, right]) => right - left ||
321
+ Number(b === raw[y]) - Number(a === raw[y]) ||
322
+ WALL_TERRAIN_KINDS.indexOf(a) - WALL_TERRAIN_KINDS.indexOf(b))[0][0]);
323
+ }
324
+ if (Array.isArray(edge.wallTerrain))
325
+ for (const segment of edge.wallTerrain)
326
+ for (let y = Math.max(0, segment.y0); y <= Math.min(height - 1, segment.y1); y += 1)
327
+ smoothed[y] = segment.kind;
328
+ return smoothed;
329
+ };
330
+ return { west: side(1), east: side(-1) };
331
+ }
332
+ /**
333
+ * Rim strength 0 to 1 at a column: 0 at the inner foot, 1 at the seam. Zero outside `rim` and `wall`.
233
334
  */
234
335
  export function rimStrength(edge, width, x) {
235
- if (edge.mode !== 'rim')
336
+ if (!hasRimRange(edge))
236
337
  return 0;
237
338
  const distance = Math.min(x, width - 1 - x);
238
339
  return distance >= edge.rimPx ? 0 : smooth(1 - distance / edge.rimPx);
@@ -258,7 +359,8 @@ export function edgeWaterDarkness(edge, width, height, x, y) {
258
359
  return Math.max(side, pole);
259
360
  }
260
361
  /**
261
- * Impassable rows for every pair of distinct land provinces that meet across the seam, in
362
+ * Impassable rows for every pair of distinct land provinces that meet across the seam (`rim` and
363
+ * `wall`), in
262
364
  * `adjacencies.csv` order (rows are sorted by the lower then the higher province ID).
263
365
  */
264
366
  export function rimAdjacencyRows(input) {
@@ -21,7 +21,7 @@ import { planEconomy } from './gameplay/economy.js';
21
21
  import { prepareGameplay } from './gameplay/prepare.js';
22
22
  import { fractal, lattice } from './world-noise.js';
23
23
  import { calibratedColourMap, COLOUR_CLASSES, } from './colormap.js';
24
- import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, } from './world-edge.js';
24
+ import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, hasRimRange, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, WALL_TERRAIN_KINDS, wallRowKinds, } from './world-edge.js';
25
25
  import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from './water.js';
26
26
  import { overlayGeographyLakes, rasterizeGeographyKind } from './relief/land.js';
27
27
  import { checkTerrainRivers, synthesizeTerrain, } from './relief/terrain-synthesis.js';
@@ -465,6 +465,70 @@ function realmPins(realms, width, height, kind) {
465
465
  }
466
466
  return pins.map(({ pixel }) => pixel);
467
467
  }
468
+ /**
469
+ * Make the states of a `wall` edge what the base game's impassable states are: `impassable = yes`,
470
+ * linked by `force_link_ownership_to` to the nearest passable state and owned as it is, `enclave`
471
+ * where the category exists, and without infrastructure, buildings, resources, victory points,
472
+ * ports or forts. Nearest counts province steps over land and water, since a wall often stands
473
+ * in what was sea; ties go to the passable state met through most borders, then the lowest id.
474
+ */
475
+ function finishWallStates(states, neighbors, context) {
476
+ const stateOfProvince = new Map();
477
+ for (const state of states)
478
+ for (const id of state.provinces)
479
+ stateOfProvince.set(id, state);
480
+ const enclave = context.stateCategories === undefined || context.stateCategories.has('enclave');
481
+ const nearestPassable = (start) => {
482
+ const seen = new Set(start);
483
+ let frontier = [...start].sort((a, b) => a - b);
484
+ while (frontier.length > 0) {
485
+ const found = new Map();
486
+ const next = [];
487
+ for (const id of frontier)
488
+ for (const other of [...neighbors[id]].sort((a, b) => a - b)) {
489
+ const state = stateOfProvince.get(other);
490
+ if (state !== undefined && state.impassable !== true)
491
+ found.set(state.id, (found.get(state.id) ?? 0) + 1);
492
+ if (seen.has(other))
493
+ continue;
494
+ seen.add(other);
495
+ next.push(other);
496
+ }
497
+ if (found.size > 0)
498
+ return [...found].sort(([a, left], [b, right]) => right - left || a - b)[0][0];
499
+ frontier = next;
500
+ }
501
+ return undefined;
502
+ };
503
+ for (const state of states) {
504
+ if (state.impassable !== true)
505
+ continue;
506
+ const link = nearestPassable(state.provinces);
507
+ if (link === undefined) {
508
+ delete state.link;
509
+ delete state.owner;
510
+ }
511
+ else {
512
+ state.link = link;
513
+ const owner = states[link - 1].owner;
514
+ if (owner === undefined)
515
+ delete state.owner;
516
+ else
517
+ state.owner = owner;
518
+ }
519
+ if (enclave)
520
+ state.category = 'enclave';
521
+ state.infrastructure = 0;
522
+ state.civilian = 0;
523
+ state.military = 0;
524
+ state.dockyard = 0;
525
+ state.airBase = 0;
526
+ state.resources = new Map();
527
+ state.victoryPoints = new Map();
528
+ state.navalBases = new Map();
529
+ state.forts = new Map();
530
+ }
531
+ }
468
532
  export function generateWorld(spec, context, options = {}) {
469
533
  const { width, height } = spec;
470
534
  if (width % 256 !== 0 || height % 256 !== 0)
@@ -507,10 +571,12 @@ export function generateWorld(spec, context, options = {}) {
507
571
  };
508
572
  const notes = [];
509
573
  const edge = spec.edge ?? { mode: 'none', bandPx: 0, polarPx: 0, rimPx: 0 };
574
+ let wallMask;
510
575
  if (edge.mode !== 'none') {
511
576
  assertFeaturesOutsideBand(edge, width, height, (spec.referenceCities ?? []).map(({ name, x, y }) => ({ name, x, y, kind: 'city' })));
512
577
  const applied = applyEdgePolicy(surface.kind, surface.elevation, width, height, edge, spec.seed, Math.max(40, Math.round(spec.landProvincePixels / 4)));
513
578
  notes.push(...applied.notes.map((note) => note));
579
+ wallMask = applied.wall;
514
580
  }
515
581
  // Lakes need a minimum size and may not touch the open sea (ADR 0053).
516
582
  for (const note of normalizeLakes(surface.kind, surface.elevation, width, height))
@@ -555,7 +621,7 @@ export function generateWorld(spec, context, options = {}) {
555
621
  kind: surface.kind,
556
622
  relief: spec.relief,
557
623
  rivers: { density: spec.riverDensity, count: spec.riverCount },
558
- adjustHeight: edge.mode === 'rim'
624
+ adjustHeight: hasRimRange(edge)
559
625
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
560
626
  : undefined,
561
627
  signal: options.signal,
@@ -616,7 +682,7 @@ export function generateWorld(spec, context, options = {}) {
616
682
  kind: surface.kind,
617
683
  relief: spec.relief,
618
684
  rivers: { density: spec.riverDensity, count: spec.riverCount },
619
- adjustHeight: edge.mode === 'rim'
685
+ adjustHeight: hasRimRange(edge)
620
686
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
621
687
  : undefined,
622
688
  signal: options.signal,
@@ -773,6 +839,17 @@ export function generateWorld(spec, context, options = {}) {
773
839
  const landIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === LAND);
774
840
  const seaIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === SEA);
775
841
  const lakeIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === LAKE);
842
+ // A land province with most of its pixels in the wall belongs to the wall's impassable states.
843
+ const wallProvinces = new Set();
844
+ if (wallMask !== undefined) {
845
+ const inWall = new Uint32Array(count);
846
+ for (let pixel = 0; pixel < wallMask.length; pixel += 1)
847
+ if (wallMask[pixel] === 1)
848
+ inWall[provinces.pixel[pixel]] += 1;
849
+ for (const id of landIds)
850
+ if (inWall[id] * 2 > provinces.size[id])
851
+ wallProvinces.add(id);
852
+ }
776
853
  if (landIds.length < spec.countries.length)
777
854
  throw new ServiceError('MAP_WORLD_LAND_TOO_SMALL', 'The generated land has fewer provinces than countries; raise landCoverage or lower landProvincePixels', { landProvinces: landIds.length, countries: spec.countries.length });
778
855
  const coastal = (id) => [...provinces.neighbors[id]].some((other) => provinces.kind[id] === SEA
@@ -997,7 +1074,9 @@ export function generateWorld(spec, context, options = {}) {
997
1074
  };
998
1075
  });
999
1076
  const capitals = [];
1000
- const largest = [...landIds].sort((left, right) => provinces.size[right] - provinces.size[left] || left - right);
1077
+ const largest = landIds
1078
+ .filter((id) => !wallProvinces.has(id))
1079
+ .sort((left, right) => provinces.size[right] - provinces.size[left] || left - right);
1001
1080
  const realmRules = spec.realms === undefined
1002
1081
  ? undefined
1003
1082
  : resolveRealmRules(spec.realms, {
@@ -1007,8 +1086,15 @@ export function generateWorld(spec, context, options = {}) {
1007
1086
  provinceSize: provinces.size,
1008
1087
  isLand: (id) => provinces.kind[id] === LAND,
1009
1088
  });
1010
- if (realmRules !== undefined)
1089
+ if (realmRules !== undefined) {
1090
+ const walled = realmRules.capitals.flatMap((id, index) => wallProvinces.has(id) ? [{ tag: spec.countries[index]?.tag, ...center(id) }] : []);
1091
+ if (walled.length > 0)
1092
+ throw new ServiceError('MAP_EDGE_FEATURE_IN_BAND', `${walled.length} capital(s) stand in the impassable wall at the seam: ${walled
1093
+ .slice(0, 5)
1094
+ .map(({ tag, x, y }) => `${tag ?? '?'} (${Math.round(x)}, ${Math.round(y)})`)
1095
+ .join('; ')}. Move them inland or narrow edge.rimPx.`, { mode: edge.mode, rimPx: edge.rimPx, capitals: walled.slice(0, 20) });
1011
1096
  capitals.push(...realmRules.capitals);
1097
+ }
1012
1098
  while (capitals.length < countryCount) {
1013
1099
  const countryIndex = capitals.length;
1014
1100
  const regionCandidates = largest.filter((id) => referenceOwners.get(id) === countryIndex && !capitals.includes(id));
@@ -1031,7 +1117,7 @@ export function generateWorld(spec, context, options = {}) {
1031
1117
  let best = -1;
1032
1118
  let bestDistance = -1;
1033
1119
  for (const id of landIds) {
1034
- if (capitals.includes(id))
1120
+ if (capitals.includes(id) || wallProvinces.has(id))
1035
1121
  continue;
1036
1122
  const c = center(id);
1037
1123
  const distance = Math.min(...capitals.map((other) => Math.hypot(center(other).x - c.x, center(other).y - c.y)));
@@ -1144,7 +1230,7 @@ export function generateWorld(spec, context, options = {}) {
1144
1230
  // States: within each region and country, clusters of about provincesPerState.
1145
1231
  const groups = new Map();
1146
1232
  for (const id of landIds) {
1147
- const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}`;
1233
+ const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}${wallProvinces.has(id) ? ':wall' : ''}`;
1148
1234
  const list = groups.get(key) ?? [];
1149
1235
  list.push(id);
1150
1236
  groups.set(key, list);
@@ -1182,6 +1268,7 @@ export function generateWorld(spec, context, options = {}) {
1182
1268
  victoryPoints: new Map(),
1183
1269
  navalBases: new Map(),
1184
1270
  forts: new Map(),
1271
+ ...(key.endsWith(':wall') ? { impassable: true } : {}),
1185
1272
  };
1186
1273
  states.push(draft);
1187
1274
  for (const id of sorted)
@@ -1370,6 +1457,7 @@ export function generateWorld(spec, context, options = {}) {
1370
1457
  if (stateOf.get(id).navalBases.has(id))
1371
1458
  hasPort = true;
1372
1459
  if (coastal(id) &&
1460
+ !wallProvinces.has(id) &&
1373
1461
  (bestCoast === undefined || provinces.size[id] > provinces.size[bestCoast]))
1374
1462
  bestCoast = id;
1375
1463
  for (const next of provinces.neighbors[id])
@@ -1384,6 +1472,8 @@ export function generateWorld(spec, context, options = {}) {
1384
1472
  stateOf.get(bestCoast).navalBases.set(bestCoast, 1);
1385
1473
  }
1386
1474
  }
1475
+ if (wallProvinces.size > 0)
1476
+ finishWallStates(states, provinces.neighbors, context);
1387
1477
  // Province IDs: 1-based in reading order of the province's first pixel; 0 is the null row.
1388
1478
  const provinceId = (index) => index + 1;
1389
1479
  // Unique colours, never black.
@@ -1435,7 +1525,7 @@ export function generateWorld(spec, context, options = {}) {
1435
1525
  '',
1436
1526
  ].join('\n')));
1437
1527
  add(`${map}/continent.txt`, text(`continents = {\n${[...new Set([...continentNames.map((_, index) => `world_continent_${index + 1}`), ...(context.continentKeys ?? [])])].map((key) => `\t${key}`).join('\n')}\n}\n`));
1438
- const rimRows = edge.mode === 'rim'
1528
+ const rimRows = hasRimRange(edge)
1439
1529
  ? rimAdjacencyRows({
1440
1530
  provincePixels: provinces.pixel,
1441
1531
  provinceKinds: provinces.kind,
@@ -1447,7 +1537,7 @@ export function generateWorld(spec, context, options = {}) {
1447
1537
  notes.push({
1448
1538
  code: 'MAP_EDGE_RIM_ADJACENCIES',
1449
1539
  severity: 'info',
1450
- message: `The rim edge policy wrote ${rimRows.length} impassable adjacency row(s) for provinces that meet across the seam`,
1540
+ message: `The ${edge.mode} edge policy wrote ${rimRows.length} impassable adjacency row(s) for provinces that meet across the seam`,
1451
1541
  details: { rows: rimRows.length },
1452
1542
  });
1453
1543
  const crossingRows = (gameplay?.crossings.rows ?? []).map(adjacencyRowText);
@@ -1531,34 +1621,62 @@ export function generateWorld(spec, context, options = {}) {
1531
1621
  Math.abs(heights[Math.min(height - 1, y + 1) * width + x] -
1532
1622
  heights[Math.max(0, y - 1) * width + x]) <=
1533
1623
  2;
1624
+ const snowAt = (pixel, type) => synthesized !== undefined
1625
+ ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1626
+ surface.kind[pixel] === LAND
1627
+ : reference === undefined
1628
+ ? type === 'mountain' && latitude(provinces.pixel[pixel]) > 0.7
1629
+ : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1630
+ // A wall takes the look of the land it meets, row by row on each side.
1631
+ const wallLook = wallMask === undefined
1632
+ ? undefined
1633
+ : wallRowKinds({
1634
+ edge,
1635
+ width,
1636
+ height,
1637
+ wall: wallMask,
1638
+ landKind: (pixel) => {
1639
+ if (surface.kind[pixel] !== LAND)
1640
+ return undefined;
1641
+ const type = visualTerrain(pixel);
1642
+ if (snowAt(pixel, type))
1643
+ return 'snow';
1644
+ return WALL_TERRAIN_KINDS.includes(type)
1645
+ ? type
1646
+ : 'plains';
1647
+ },
1648
+ });
1534
1649
  for (let pixel = 0; pixel < width * height; pixel += 1) {
1535
- const id = provinces.pixel[pixel];
1536
1650
  const type = visualTerrain(pixel);
1537
- const snowy = synthesized !== undefined
1538
- ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1539
- surface.kind[pixel] === LAND
1540
- : reference === undefined
1541
- ? type === 'mountain' && latitude(id) > 0.7
1542
- : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1651
+ const snowy = snowAt(pixel, type);
1543
1652
  const x = pixel % width;
1544
- const rimmed = rimStrength(edge, width, x) > 0.35 && surface.kind[pixel] === LAND;
1545
- let index = snowy
1546
- ? reference === undefined
1547
- ? 16
1548
- : 19
1549
- : rimmed
1653
+ const walled = wallLook === undefined || wallMask[pixel] !== 1 || surface.kind[pixel] !== LAND
1654
+ ? undefined
1655
+ : (x < width / 2 ? wallLook.west : wallLook.east)[(pixel - x) / width];
1656
+ const rimmed = walled === undefined &&
1657
+ wallLook === undefined &&
1658
+ rimStrength(edge, width, x) > 0.35 &&
1659
+ surface.kind[pixel] === LAND;
1660
+ let index = walled !== undefined
1661
+ ? walled === 'snow'
1550
1662
  ? 16
1551
- : type === 'lakes'
1552
- ? lakeIndex
1553
- : (terrainIndex.get(type) ?? DEFAULT_TERRAIN_INDEX.get(type) ?? 0);
1554
- let colour = type === 'lakes' || type === 'ocean' || type === 'urban'
1555
- ? type === 'urban'
1556
- ? 'urban'
1557
- : type
1558
- : snowy || rimmed
1559
- ? 'snow'
1560
- : type;
1561
- if (calibrated && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1663
+ : (terrainIndex.get(walled) ?? DEFAULT_TERRAIN_INDEX.get(walled) ?? 0)
1664
+ : snowy
1665
+ ? reference === undefined
1666
+ ? 16
1667
+ : 19
1668
+ : rimmed
1669
+ ? 16
1670
+ : type === 'lakes'
1671
+ ? lakeIndex
1672
+ : (terrainIndex.get(type) ?? DEFAULT_TERRAIN_INDEX.get(type) ?? 0);
1673
+ let colour = walled ??
1674
+ (type === 'lakes' || type === 'ocean' || type === 'urban'
1675
+ ? type
1676
+ : snowy || rimmed
1677
+ ? 'snow'
1678
+ : type);
1679
+ if (calibrated && walled === undefined && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1562
1680
  // Variant graphical terrains by rule, so one class is not one flat texture.
1563
1681
  const y = (pixel - x) / width;
1564
1682
  if (type === 'plains' &&
@@ -1732,7 +1850,7 @@ export function generateWorld(spec, context, options = {}) {
1732
1850
  colormap[offset + 3] = cityPixels[source] === 15 ? 200 : 0;
1733
1851
  }
1734
1852
  }
1735
- if (edge.mode === 'rim')
1853
+ if (hasRimRange(edge))
1736
1854
  for (let y = 0; y < halfHeight; y += 1)
1737
1855
  for (let x = 0; x < halfWidth; x += 1) {
1738
1856
  const strength = rimStrength(edge, width, x * 2);
@@ -1809,6 +1927,12 @@ export function generateWorld(spec, context, options = {}) {
1809
1927
  `\tid = ${state.id}`,
1810
1928
  `\tname = "STATE_${state.id}"`,
1811
1929
  `\tmanpower = ${state.manpower}`,
1930
+ ...(state.impassable === true
1931
+ ? [
1932
+ '\timpassable = yes',
1933
+ ...(state.link === undefined ? [] : [`\tforce_link_ownership_to = ${state.link}`]),
1934
+ ]
1935
+ : []),
1812
1936
  `\tstate_category = ${state.category}`,
1813
1937
  ...(resources.length === 0
1814
1938
  ? []
@@ -15,6 +15,9 @@ export const ARGUMENT_EXAMPLES = {
15
15
  'hoi4.mod_index': '{"mode":"overview"} or {"mode":"next_id","kind":"event","namespace":"my_mod"}',
16
16
  'hoi4.localisation_inspect': '{"mode":"key","key":"my_event.1.t"} or {"mode":"audit"}',
17
17
  'hoi4.idea_inspect': '{"kind":"idea","id":"my_idea"} or {"kind":"character","audit":true}',
18
+ 'hoi4.system_inspect': '{"kind":"mio","id":"my_organization"} or {"kind":"on_actions","audit":true}',
19
+ 'hoi4.unit_inspect': '{"kind":"oob","id":"GER_1936"} or {"kind":"variant","audit":true}',
20
+ 'hoi4.asset_inspect': '{"kind":"sprite","id":"GFX_my_icon"} or {"kind":"flag","audit":true}',
18
21
  'hoi4.event_inspect': '{"mode":"lint","selector":"chaosx.nr14"} or {"mode":"trace","selector":"chaosx.nr14.1","direction":"downstream"}',
19
22
  'hoi4.event_render': '{"view":"overview","selector":"chaosx.nr14"}',
20
23
  'hoi4.focus_inspect': '{"treeId":"my_focus_tree"}',
@@ -22,7 +25,7 @@ export const ARGUMENT_EXAMPLES = {
22
25
  'hoi4.focus_rewrite': '{"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}',
23
26
  'hoi4.gui_inspect': '{"windowName":"my_window"}',
24
27
  'hoi4.gui_render': '{"windowName":"my_window","scenario":{"id":"normal"}}',
25
- 'hoi4.gui_rewrite': '{"mode":"patches","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"expectedSourceHash":"<sha256 of the file>","patches":[{"start":120,"end":130,"expectedText":"x = 10 y","text":"x = 40 y"}]}',
28
+ 'hoi4.gui_rewrite': '{"mode":"patches","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"expectedSourceHash":"<sha256 of the file>","patches":[{"description":"Move the button right","start":120,"end":130,"expectedText":"x = 10 y","text":"x = 40 y"}]}',
26
29
  'hoi4.map_inspect': '{"query":"Brandenburg","lookupOnly":true} or {"layer":"state","tile":{"x":2600,"y":500,"width":256,"height":256}}',
27
30
  'hoi4.map_rewrite': '{"operations":[{"id":"new-state","kind":"create_state","provinceIds":[120,121],"displayName":"New State"}]}',
28
31
  'hoi4.tech_inspect': '{"mode":"scan"} or {"mode":"explain","technologyId":"my_tech"} or {"mode":"lint"}',
@@ -37,11 +40,56 @@ export const ARGUMENT_EXAMPLES = {
37
40
  'hoi4.job_inspect': '{"jobId":"job_<64 hex characters from a native task id>"}',
38
41
  'hoi4.job_cancel': '{"jobId":"job_<64 hex characters from a native task id>"}',
39
42
  };
40
- function describeIssue(issue) {
43
+ function defOf(schema) {
44
+ return schema?._zod?.def;
45
+ }
46
+ /**
47
+ * The fields the object at a path accepts, so an unknown field names the expected shape (#65).
48
+ * Wrappers are unwrapped and the fields of every union alternative are listed.
49
+ */
50
+ export function acceptedFields(schema, path, depth = 0) {
51
+ const def = defOf(schema);
52
+ if (def === undefined || depth > 32)
53
+ return [];
54
+ switch (def.type) {
55
+ case 'optional':
56
+ case 'nullable':
57
+ case 'default':
58
+ case 'prefault':
59
+ case 'readonly':
60
+ case 'catch':
61
+ case 'nonoptional':
62
+ return acceptedFields(def.innerType, path, depth + 1);
63
+ case 'pipe': {
64
+ // A preprocess step pipes from an unknown or a transform; then out checks the fields.
65
+ const fromInput = acceptedFields(def.in, path, depth + 1);
66
+ return fromInput.length > 0 ? fromInput : acceptedFields(def.out, path, depth + 1);
67
+ }
68
+ case 'union':
69
+ return [
70
+ ...new Set((def.options ?? []).flatMap((option) => acceptedFields(option, path, depth + 1))),
71
+ ];
72
+ case 'array':
73
+ return typeof path[0] === 'number'
74
+ ? acceptedFields(def.element, path.slice(1), depth + 1)
75
+ : [];
76
+ case 'record':
77
+ return path.length === 0 ? [] : acceptedFields(def.valueType, path.slice(1), depth + 1);
78
+ case 'object':
79
+ if (path.length === 0)
80
+ return Object.keys(def.shape ?? {});
81
+ return acceptedFields(def.shape?.[String(path[0])], path.slice(1), depth + 1);
82
+ default:
83
+ return [];
84
+ }
85
+ }
86
+ function describeIssue(issue, schema) {
41
87
  const field = issue.path.length === 0 ? '(arguments)' : issue.path.map(String).join('.');
42
88
  let problem = issue.message;
43
- if (issue.code === 'unrecognized_keys')
44
- problem = `unknown field${issue.keys.length === 1 ? '' : 's'} ${issue.keys.join(', ')}`;
89
+ if (issue.code === 'unrecognized_keys') {
90
+ const accepted = acceptedFields(schema, issue.path);
91
+ problem = `unknown field${issue.keys.length === 1 ? '' : 's'} ${issue.keys.join(', ')}${accepted.length === 0 ? '' : `; accepted fields: ${accepted.join(', ')}`}`;
92
+ }
45
93
  else if (issue.code === 'invalid_value')
46
94
  problem = `expected one of ${issue.values.map((value) => JSON.stringify(value)).join(', ')}`;
47
95
  else if (issue.code === 'invalid_union') {
@@ -49,14 +97,14 @@ function describeIssue(issue) {
49
97
  const closest = [...issue.errors].sort((left, right) => left.length - right.length)[0];
50
98
  const first = closest?.[0];
51
99
  if (first !== undefined) {
52
- const nested = describeIssue(first);
100
+ const nested = describeIssue(first, schema);
53
101
  problem = `${issue.message}; closest form: ${nested.field === '(arguments)' ? '' : `${nested.field}: `}${nested.problem}`;
54
102
  }
55
103
  }
56
104
  return { field, problem: problem.slice(0, 300) };
57
105
  }
58
- export function invalidArgumentsError(toolName, error) {
59
- const issues = error.issues.slice(0, 6).map(describeIssue);
106
+ export function invalidArgumentsError(toolName, error, schema) {
107
+ const issues = error.issues.slice(0, 6).map((issue) => describeIssue(issue, schema));
60
108
  const example = ARGUMENT_EXAMPLES[toolName];
61
109
  const message = [
62
110
  `Invalid arguments for ${toolName}: ${issues.map(({ field, problem }) => `${field}: ${problem}`).join('; ')}.`,
@@ -69,6 +117,6 @@ export function invalidArgumentsError(toolName, error) {
69
117
  ...(example === undefined ? {} : { example }),
70
118
  });
71
119
  }
72
- export function invalidArgumentsResult(toolName, error, workspaceId) {
73
- return errorResult(invalidArgumentsError(toolName, error), typeof workspaceId === 'string' ? workspaceId : 'current');
120
+ export function invalidArgumentsResult(toolName, error, workspaceId, schema) {
121
+ return errorResult(invalidArgumentsError(toolName, error, schema), typeof workspaceId === 'string' ? workspaceId : 'current');
74
122
  }