hoi4-agent-tools 4.9.0 → 4.11.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 (83) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/hoi4_agent_tools/core/operation-result.js +51 -11
  3. package/dist/hoi4_agent_tools/core/workspace.js +22 -7
  4. package/dist/hoi4_agent_tools/decision/service.js +13 -1
  5. package/dist/hoi4_agent_tools/event/graph.js +16 -2
  6. package/dist/hoi4_agent_tools/event/source-analysis.js +35 -16
  7. package/dist/hoi4_agent_tools/impact/service.js +4 -1
  8. package/dist/hoi4_agent_tools/map/gameplay/reachability.js +81 -0
  9. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -0
  10. package/dist/hoi4_agent_tools/map/operations.js +8 -0
  11. package/dist/hoi4_agent_tools/map/partition-tuning.js +2 -1
  12. package/dist/hoi4_agent_tools/map/reference-world.js +17 -3
  13. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +143 -0
  14. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +13 -0
  15. package/dist/hoi4_agent_tools/map/world.js +108 -23
  16. package/dist/hoi4_agent_tools/mcp/resources/register-modern.js +11 -4
  17. package/dist/hoi4_agent_tools/mcp/resources/register.js +7 -0
  18. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +1 -0
  19. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +12 -0
  20. package/dist/hoi4_agent_tools/mcp/tools/reference.js +12 -3
  21. package/dist/hoi4_agent_tools/package-check/service.js +14 -1
  22. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  23. package/dist/hoi4_agent_tools/probability/operations.js +6 -0
  24. package/dist/hoi4_agent_tools/probability/service.js +23 -0
  25. package/dist/hoi4_agent_tools/reference/operations.js +35 -6
  26. package/dist/hoi4_agent_tools/reference/service.js +118 -14
  27. package/dist/hoi4_agent_tools/reference/skill-resource.js +74 -0
  28. package/dist/hoi4_agent_tools/reference/skills.js +278 -0
  29. package/dist/hoi4_agent_tools/schemas/geography.js +5 -0
  30. package/dist/hoi4_agent_tools/schemas/map.js +29 -0
  31. package/dist/hoi4_agent_tools/schemas/reference.js +34 -2
  32. package/dist/hoi4_agent_tools/schemas/skill.js +72 -0
  33. package/dist/hoi4_agent_tools/version.js +1 -1
  34. package/docs/configuration.md +3 -3
  35. package/docs/map.md +12 -9
  36. package/docs/probability.md +1 -1
  37. package/docs/reference.md +27 -1
  38. package/docs/research/probability-adapter-evidence.md +15 -2
  39. package/docs/tools.md +101 -86
  40. package/engine/bin/manifest.json +1 -1
  41. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  42. package/npm-shrinkwrap.json +2 -2
  43. package/package.json +2 -1
  44. package/schemas/configuration.schema.json +1 -1
  45. package/schemas/continuous-focus-palette.schema.json +1 -1
  46. package/schemas/custom-weighted-pool.schema.json +1 -1
  47. package/schemas/decision-inspect-input.schema.json +1 -1
  48. package/schemas/error-log-input.schema.json +1 -1
  49. package/schemas/event-feature-manifest.schema.json +1 -1
  50. package/schemas/focus-plan.schema.json +1 -1
  51. package/schemas/focus-planning-sidecar.schema.json +1 -1
  52. package/schemas/geography-model.schema.json +4 -1
  53. package/schemas/gui-animation-source.schema.json +1 -1
  54. package/schemas/gui-helper.schema.json +1 -1
  55. package/schemas/gui-scenario.schema.json +1 -1
  56. package/schemas/helper-expansion-request.schema.json +1 -1
  57. package/schemas/helper-expansion-summary.schema.json +1 -1
  58. package/schemas/impact-inspect-input.schema.json +1 -1
  59. package/schemas/map-operation.schema.json +177 -118
  60. package/schemas/mechanic-test-input.schema.json +1 -1
  61. package/schemas/mod-index-input.schema.json +1 -1
  62. package/schemas/operation-result.schema.json +1 -1
  63. package/schemas/package-check-input.schema.json +1 -1
  64. package/schemas/package-manifest.schema.json +1 -1
  65. package/schemas/probability-analysis-result.schema.json +1 -1
  66. package/schemas/probability-compare-input.schema.json +1 -1
  67. package/schemas/probability-evaluate-input.schema.json +1 -1
  68. package/schemas/probability-inspect-input.schema.json +1 -1
  69. package/schemas/probability-render-input.schema.json +1 -1
  70. package/schemas/probability-scenario-set.schema.json +1 -1
  71. package/schemas/probability-sequence-input.schema.json +1 -1
  72. package/schemas/probability-simulate-input.schema.json +1 -1
  73. package/schemas/probability-sweep-input.schema.json +1 -1
  74. package/schemas/reference-context-input.schema.json +1 -1
  75. package/schemas/reference-read-input.schema.json +3 -3
  76. package/schemas/reference-search-input.schema.json +1 -1
  77. package/schemas/reference-sheets.schema.json +1 -1
  78. package/schemas/scenario-suite.schema.json +1 -1
  79. package/schemas/scenario-test-input.schema.json +1 -1
  80. package/schemas/script-validate-input.schema.json +1 -1
  81. package/schemas/shared-scenario.schema.json +1 -1
  82. package/schemas/source-lookup-input.schema.json +1 -1
  83. package/server.json +2 -2
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Relief from painted classes (ZR-27, ADR 0056 amended). A reference picture classified with a
3
+ * palette says, pixel by pixel, where the mountains, hills and volcanoes are, which the polygons
4
+ * of a geography model only approximate. This stage raises the macro relief toward those classes
5
+ * before the hydrology runs, so the model's rivers route around the painted mountains:
6
+ *
7
+ * - each class is measured as its share of every macro cell and blurred over `falloffPx`, so a
8
+ * single painted pixel lifts nothing and a class edge becomes a slope, never a cliff;
9
+ * - mountains rise toward `mountainPeak` under ridged noise, so ranges keep crests and saddles,
10
+ * hills toward `hillsPeak` under gentle noise, volcanoes toward `volcanoPeak`;
11
+ * - a cell keeps the model's height where that is higher, and every other cell keeps the model's
12
+ * broad elevation untouched;
13
+ * - impassable land (ZR-28) rises toward `impassablePeak`, the highest ground of the map;
14
+ * - painted mountains and volcanoes get permanent snow above a height that falls from the
15
+ * equator toward the poles, and weight the full-resolution detail as model ranges do.
16
+ */
17
+ import { LAND } from './grid.js';
18
+ import { fractal2, ridged2, smoothstep } from './math.js';
19
+ import { HEIGHT_CEILING, PEAK_BASE, PEAK_SPAN } from './macro-relief.js';
20
+ /** Reference terrain codes the stage reads (`REFERENCE_TERRAIN` of the reference interpretation). */
21
+ export const PAINTED_MOUNTAIN = 3;
22
+ export const PAINTED_VOLCANO = 5;
23
+ export const PAINTED_HILLS = 6;
24
+ /** Defaults measured against the base game 1.19.4.1: mountain p99 223, hills p90 140. */
25
+ export const DEFAULT_PAINTED_RELIEF = {
26
+ falloffPx: 24,
27
+ mountainPeak: 0.82,
28
+ hillsPeak: 0.27,
29
+ volcanoPeak: 0.9,
30
+ impassablePeak: 0.95,
31
+ };
32
+ /** Three passes of a separable box blur, about a Gaussian with the given radius in cells. */
33
+ function blur(field, width, height, radius) {
34
+ let source = field;
35
+ const passRadius = Math.max(1, Math.round(radius / Math.sqrt(3)));
36
+ const span = passRadius * 2 + 1;
37
+ for (let pass = 0; pass < 3; pass += 1) {
38
+ const across = new Float32Array(width * height);
39
+ for (let y = 0; y < height; y += 1) {
40
+ const row = y * width;
41
+ let sum = 0;
42
+ for (let x = -passRadius; x <= passRadius; x += 1)
43
+ sum += source[row + Math.min(width - 1, Math.max(0, x))];
44
+ for (let x = 0; x < width; x += 1) {
45
+ across[row + x] = sum / span;
46
+ sum +=
47
+ source[row + Math.min(width - 1, x + passRadius + 1)] -
48
+ source[row + Math.max(0, x - passRadius)];
49
+ }
50
+ }
51
+ const down = new Float32Array(width * height);
52
+ for (let x = 0; x < width; x += 1) {
53
+ let sum = 0;
54
+ for (let y = -passRadius; y <= passRadius; y += 1)
55
+ sum += across[Math.min(height - 1, Math.max(0, y)) * width + x];
56
+ for (let y = 0; y < height; y += 1) {
57
+ down[y * width + x] = sum / span;
58
+ sum +=
59
+ across[Math.min(height - 1, y + passRadius + 1) * width + x] -
60
+ across[Math.max(0, y - passRadius) * width + x];
61
+ }
62
+ }
63
+ source = down;
64
+ }
65
+ return source;
66
+ }
67
+ /** Permanent-snow height in map values at a row: 232 at the equator, 140 at the poles. */
68
+ export function paintedSnowHeight(y, height) {
69
+ const latitude = Math.abs((y + 0.5) / height - 0.5) * 2;
70
+ return Math.round(232 - 92 * latitude ** 1.5);
71
+ }
72
+ export function applyPaintedRelief(target, input) {
73
+ const { width: mw, height: mh, kind } = target;
74
+ const fullWidth = mw * 2;
75
+ const share = (code, source = input.classes) => {
76
+ const field = new Float32Array(mw * mh);
77
+ for (let y = 0; y < mh; y += 1)
78
+ for (let x = 0; x < mw; x += 1) {
79
+ const top = 2 * y * fullWidth + 2 * x;
80
+ let count = 0;
81
+ for (const offset of [0, 1, fullWidth, fullWidth + 1])
82
+ if (source[top + offset] === code)
83
+ count += 1;
84
+ field[y * mw + x] = count / 4;
85
+ }
86
+ return field;
87
+ };
88
+ const radius = Math.max(1, input.settings.falloffPx / 2);
89
+ const mountain = blur(share(PAINTED_MOUNTAIN), mw, mh, radius);
90
+ const hills = blur(share(PAINTED_HILLS), mw, mh, radius);
91
+ // Volcanoes are cones: a narrower falloff keeps them peaked.
92
+ const volcano = blur(share(PAINTED_VOLCANO), mw, mh, Math.max(1, radius / 2));
93
+ const blocked = input.impassable === undefined ? undefined : blur(share(1, input.impassable), mw, mh, radius);
94
+ const lift = (peak) => PEAK_SPAN * peak * target.scale;
95
+ const wavelength = Math.max(6, radius * 3);
96
+ let raisedCells = 0;
97
+ let highest = 0;
98
+ for (let y = 0; y < mh; y += 1)
99
+ for (let x = 0; x < mw; x += 1) {
100
+ const cell = y * mw + x;
101
+ if (kind[cell] !== LAND)
102
+ continue;
103
+ // Coverage saturates inside a painted area, so its interior reaches the peak.
104
+ const m = smoothstep(mountain[cell] * 1.6);
105
+ const h = smoothstep(hills[cell] * 1.6);
106
+ const v = smoothstep(volcano[cell] * 2);
107
+ const i = blocked === undefined ? 0 : smoothstep(blocked[cell] * 1.6);
108
+ if (m <= 0.001 && h <= 0.001 && v <= 0.001 && i <= 0.001)
109
+ continue;
110
+ const ridges = 0.55 + 0.45 * ridged2(input.seed + 4111, x, y, wavelength, 3);
111
+ const swell = 0.7 + 0.3 * fractal2(input.seed + 4127, x, y, wavelength, 3);
112
+ const goal = Math.min(HEIGHT_CEILING, Math.max(PEAK_BASE + lift(input.settings.mountainPeak) * m * ridges, PEAK_BASE + lift(input.settings.hillsPeak) * h * swell, PEAK_BASE + lift(input.settings.volcanoPeak) * v,
113
+ // Impassable land keeps its crests but never sinks below most of its peak.
114
+ PEAK_BASE + lift(input.settings.impassablePeak) * i * (0.8 + 0.2 * ridges)));
115
+ if (goal > target.heights[cell]) {
116
+ target.heights[cell] = goal;
117
+ raisedCells += 1;
118
+ if (goal > highest)
119
+ highest = goal;
120
+ }
121
+ const weight = Math.max(m, 0.6 * h, v, i);
122
+ if (weight > target.footprint[cell])
123
+ target.footprint[cell] = weight;
124
+ if (Math.max(m, v, i) > 0.25) {
125
+ const snow = paintedSnowHeight(y, mh);
126
+ if (snow < target.snowLine[cell])
127
+ target.snowLine[cell] = snow;
128
+ }
129
+ }
130
+ return { raisedCells, highest: Math.round(highest) };
131
+ }
132
+ /** Settings for `relief.painted`: `true` takes the defaults, an object overrides some of them. */
133
+ export function resolvePaintedRelief(input) {
134
+ if (input === true)
135
+ return DEFAULT_PAINTED_RELIEF;
136
+ return {
137
+ falloffPx: input.falloffPx ?? DEFAULT_PAINTED_RELIEF.falloffPx,
138
+ mountainPeak: input.mountainPeak ?? DEFAULT_PAINTED_RELIEF.mountainPeak,
139
+ hillsPeak: input.hillsPeak ?? DEFAULT_PAINTED_RELIEF.hillsPeak,
140
+ volcanoPeak: input.volcanoPeak ?? DEFAULT_PAINTED_RELIEF.volcanoPeak,
141
+ impassablePeak: input.impassablePeak ?? DEFAULT_PAINTED_RELIEF.impassablePeak,
142
+ };
143
+ }
@@ -5,6 +5,7 @@ import { checkRangesAndFeatures, reliefStatistics, straightRiverShare, } from '.
5
5
  import { buildFullResolutionHeights } from './full-resolution.js';
6
6
  import { RIVER_PIXEL_CAP, synthesizeHydrology } from './hydrology.js';
7
7
  import { DEFAULT_RELIEF, LAND_FLOOR, HEIGHT_CEILING, peakHeight, synthesizeMacroRelief, } from './macro-relief.js';
8
+ import { applyPaintedRelief } from './painted-relief.js';
8
9
  import { rasterizeRivers } from './river-raster.js';
9
10
  /** Red channel response of the normal map per height step (base game: about 2.6). */
10
11
  export const NORMAL_RESPONSE = 2.6;
@@ -107,6 +108,9 @@ export function checkTerrainRivers(input) {
107
108
  relief,
108
109
  signal: input.signal,
109
110
  });
111
+ // The same painted relief as the full synthesis, so the rivers checked are the rivers written.
112
+ if (input.painted !== undefined)
113
+ applyPaintedRelief(macro, input.painted);
110
114
  const adjust = input.adjustHeight;
111
115
  if (adjust !== undefined)
112
116
  for (let y = 0; y < macro.height; y += 1)
@@ -158,6 +162,15 @@ export function synthesizeTerrain(input) {
158
162
  relief,
159
163
  signal: input.signal,
160
164
  });
165
+ if (input.painted !== undefined) {
166
+ const summary = applyPaintedRelief(macro, input.painted);
167
+ notes.push({
168
+ code: 'MAP_RELIEF_PAINTED',
169
+ severity: 'info',
170
+ message: `Raised ${summary.raisedCells} half-resolution cells toward the painted mountains, hills and volcanoes (highest ${summary.highest}) before routing the rivers`,
171
+ details: { ...summary, settings: input.painted.settings },
172
+ });
173
+ }
161
174
  const adjust = input.adjustHeight;
162
175
  if (adjust !== undefined)
163
176
  for (let y = 0; y < macro.height; y += 1)
@@ -16,6 +16,7 @@ import { buildTerritoryAtoms, territoryGraphFromPartition } from './territory-gr
16
16
  import { growTerritory } from './territory.js';
17
17
  import { geographyPartitionFields, provinceCountNote, surfacePartitionFields, } from './world-partition.js';
18
18
  import { adjacencyRowText, adjacencyRulesText } from './gameplay/crossings.js';
19
+ import { realmReachNotes } from './gameplay/reachability.js';
19
20
  import { convertInlandSeas } from './gameplay/inland-sea.js';
20
21
  import { planEconomy } from './gameplay/economy.js';
21
22
  import { prepareGameplay } from './gameplay/prepare.js';
@@ -23,6 +24,8 @@ import { fractal, lattice } from './world-noise.js';
23
24
  import { calibratedColourMap, COLOUR_CLASSES, } from './colormap.js';
24
25
  import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, hasRimRange, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, WALL_TERRAIN_KINDS, wallRowKinds, } from './world-edge.js';
25
26
  import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from './water.js';
27
+ import { DEFAULT_PAINTED_RELIEF } from './relief/painted-relief.js';
28
+ import { rowStrips, scanAreaStrip } from './geography/index.js';
26
29
  import { overlayGeographyLakes, rasterizeGeographyKind } from './relief/land.js';
27
30
  import { checkTerrainRivers, synthesizeTerrain, } from './relief/terrain-synthesis.js';
28
31
  import { assignUnreachedRealmLand, checkRealmPoints, realmPointsError, resolveRealmRules, } from './world-realms.js';
@@ -255,6 +258,8 @@ function geographySurface(spec, geography, reference) {
255
258
  }
256
259
  return { kind, elevation: new Float32Array(total), moisture };
257
260
  }
261
+ /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
262
+ export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
258
263
  function terrainSummaryNote(terrain, geography) {
259
264
  const { relief, riverStatistics } = terrain;
260
265
  return {
@@ -264,6 +269,8 @@ function terrainSummaryNote(terrain, geography) {
264
269
  details: {
265
270
  modelHash: geography.hash,
266
271
  relief,
272
+ // The base game 1.19.4.1 over its land provinces, for comparison.
273
+ vanilla: VANILLA_RELIEF,
267
274
  rivers: riverStatistics,
268
275
  // The first of the named rivers only: the response budget is shared with everything else the
269
276
  // world reports, and a river that did not complete is always listed.
@@ -465,14 +472,27 @@ function realmPins(realms, width, height, kind) {
465
472
  }
466
473
  return pins.map(({ pixel }) => pixel);
467
474
  }
475
+ /** The union of painted impassable land and the model's impassable regions, or undefined. */
476
+ function impassableLand(painted, geography, width, height) {
477
+ const regions = (geography?.regions ?? []).filter((region) => region.impassable === true && region.area !== undefined);
478
+ if (regions.length === 0)
479
+ return painted;
480
+ const mask = painted === undefined ? new Uint8Array(width * height) : new Uint8Array(painted);
481
+ const grid = { width, height };
482
+ for (const strip of rowStrips(grid))
483
+ for (const region of regions)
484
+ scanAreaStrip(region.area, grid, strip, (y, x0, x1) => mask.fill(1, y * width + x0, y * width + x1));
485
+ return mask;
486
+ }
468
487
  /**
469
- * Make the states of a `wall` edge what the base game's impassable states are: `impassable = yes`,
488
+ * Make the states of a `wall` edge and of impassable land (ZR-28) what the base game's impassable
489
+ * states are: `impassable = yes`,
470
490
  * linked by `force_link_ownership_to` to the nearest passable state and owned as it is, `enclave`
471
491
  * where the category exists, and without infrastructure, buildings, resources, victory points,
472
492
  * ports or forts. Nearest counts province steps over land and water, since a wall often stands
473
493
  * in what was sea; ties go to the passable state met through most borders, then the lowest id.
474
494
  */
475
- function finishWallStates(states, neighbors, context) {
495
+ function finishImpassableStates(states, neighbors, context) {
476
496
  const stateOfProvince = new Map();
477
497
  for (const state of states)
478
498
  for (const id of state.provinces)
@@ -554,6 +574,8 @@ export function generateWorld(spec, context, options = {}) {
554
574
  if (reference !== undefined && (reference.width !== width || reference.height !== height))
555
575
  throw new ServiceError('MAP_WORLD_REFERENCE_DIMENSIONS', 'Reference raster dimensions do not match the world');
556
576
  const geography = spec.geography;
577
+ if (spec.paintedRelief !== undefined && (reference === undefined || geography === undefined))
578
+ throw new ServiceError('MAP_RELIEF_PAINTED_INPUTS', 'relief.painted raises the relief from the classes of a reference picture onto a geography model; give both reference and geography', { reference: reference !== undefined, geography: geography !== undefined });
557
579
  if (geography !== undefined &&
558
580
  (geography.frame.width !== width || geography.frame.height !== height))
559
581
  throw new ServiceError('MAP_GEOGRAPHY_FRAME_MISMATCH', 'The geography model was resolved for a different map size than the world being created', {
@@ -572,6 +594,27 @@ export function generateWorld(spec, context, options = {}) {
572
594
  const notes = [];
573
595
  const edge = spec.edge ?? { mode: 'none', bandPx: 0, polarPx: 0, rimPx: 0 };
574
596
  let wallMask;
597
+ // Land no army may enter: painted `impassable_mountain` of the reference picture and the
598
+ // impassable regions of the geography model (ZR-28).
599
+ const impassableMask = impassableLand(reference?.impassable, geography, width, height);
600
+ // Impassable land is the highest ground even without relief.painted: then only it is raised.
601
+ const painted = geography === undefined
602
+ ? undefined
603
+ : spec.paintedRelief !== undefined && reference !== undefined
604
+ ? {
605
+ classes: reference.terrain,
606
+ impassable: impassableMask,
607
+ settings: spec.paintedRelief,
608
+ seed: spec.seed,
609
+ }
610
+ : impassableMask !== undefined
611
+ ? {
612
+ classes: new Uint8Array(width * height),
613
+ impassable: impassableMask,
614
+ settings: DEFAULT_PAINTED_RELIEF,
615
+ seed: spec.seed,
616
+ }
617
+ : undefined;
575
618
  if (edge.mode !== 'none') {
576
619
  assertFeaturesOutsideBand(edge, width, height, (spec.referenceCities ?? []).map(({ name, x, y }) => ({ name, x, y, kind: 'city' })));
577
620
  const applied = applyEdgePolicy(surface.kind, surface.elevation, width, height, edge, spec.seed, Math.max(40, Math.round(spec.landProvincePixels / 4)));
@@ -624,6 +667,7 @@ export function generateWorld(spec, context, options = {}) {
624
667
  adjustHeight: hasRimRange(edge)
625
668
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
626
669
  : undefined,
670
+ painted,
627
671
  signal: options.signal,
628
672
  });
629
673
  for (const note of checked) {
@@ -685,6 +729,7 @@ export function generateWorld(spec, context, options = {}) {
685
729
  adjustHeight: hasRimRange(edge)
686
730
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
687
731
  : undefined,
732
+ painted,
688
733
  signal: options.signal,
689
734
  });
690
735
  if (synthesized !== undefined) {
@@ -839,17 +884,32 @@ export function generateWorld(spec, context, options = {}) {
839
884
  const landIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === LAND);
840
885
  const seaIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === SEA);
841
886
  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;
887
+ // A land province with most of its pixels in the wall, or in land painted impassable (ZR-28),
888
+ // belongs to impassable states.
889
+ const majorityIn = (mask) => {
890
+ const found = new Set();
891
+ if (mask === undefined)
892
+ return found;
893
+ const inside = new Uint32Array(count);
894
+ for (let pixel = 0; pixel < mask.length; pixel += 1)
895
+ if (mask[pixel] === 1)
896
+ inside[provinces.pixel[pixel]] += 1;
849
897
  for (const id of landIds)
850
- if (inWall[id] * 2 > provinces.size[id])
851
- wallProvinces.add(id);
852
- }
898
+ if (inside[id] * 2 > provinces.size[id])
899
+ found.add(id);
900
+ return found;
901
+ };
902
+ const wallProvinces = majorityIn(wallMask);
903
+ const impassableProvinces = new Set([...wallProvinces, ...majorityIn(impassableMask)]);
904
+ const offendingCities = (spec.referenceCities ?? []).filter(({ x, y }) => {
905
+ const pixel = Math.floor(y) * width + Math.floor(x);
906
+ return impassableMask?.[pixel] === 1;
907
+ });
908
+ if (offendingCities.length > 0)
909
+ throw new ServiceError('MAP_FEATURE_IN_IMPASSABLE', `${offendingCities.length} city or cities stand on impassable land: ${offendingCities
910
+ .slice(0, 5)
911
+ .map(({ name, x, y }) => `${name} (${Math.round(x)}, ${Math.round(y)})`)
912
+ .join('; ')}. Move them or repaint the land.`, { cities: offendingCities.slice(0, 20) });
853
913
  if (landIds.length < spec.countries.length)
854
914
  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 });
855
915
  const coastal = (id) => [...provinces.neighbors[id]].some((other) => provinces.kind[id] === SEA
@@ -1075,7 +1135,7 @@ export function generateWorld(spec, context, options = {}) {
1075
1135
  });
1076
1136
  const capitals = [];
1077
1137
  const largest = landIds
1078
- .filter((id) => !wallProvinces.has(id))
1138
+ .filter((id) => !impassableProvinces.has(id))
1079
1139
  .sort((left, right) => provinces.size[right] - provinces.size[left] || left - right);
1080
1140
  const realmRules = spec.realms === undefined
1081
1141
  ? undefined
@@ -1087,12 +1147,16 @@ export function generateWorld(spec, context, options = {}) {
1087
1147
  isLand: (id) => provinces.kind[id] === LAND,
1088
1148
  });
1089
1149
  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
1150
+ const walled = realmRules.capitals.flatMap((id, index) => impassableProvinces.has(id)
1151
+ ? [{ tag: spec.countries[index]?.tag, wall: wallProvinces.has(id), ...center(id) }]
1152
+ : []);
1153
+ if (walled.length > 0) {
1154
+ const atSeam = walled.some(({ wall }) => wall);
1155
+ throw new ServiceError(atSeam ? 'MAP_EDGE_FEATURE_IN_BAND' : 'MAP_FEATURE_IN_IMPASSABLE', `${walled.length} capital(s) stand on impassable land${atSeam ? ' (the wall at the seam)' : ''}: ${walled
1093
1156
  .slice(0, 5)
1094
1157
  .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) });
1158
+ .join('; ')}. Move them${atSeam ? ' inland or narrow edge.rimPx' : ' onto passable land'}.`, { mode: edge.mode, rimPx: edge.rimPx, capitals: walled.slice(0, 20) });
1159
+ }
1096
1160
  capitals.push(...realmRules.capitals);
1097
1161
  }
1098
1162
  while (capitals.length < countryCount) {
@@ -1117,7 +1181,7 @@ export function generateWorld(spec, context, options = {}) {
1117
1181
  let best = -1;
1118
1182
  let bestDistance = -1;
1119
1183
  for (const id of landIds) {
1120
- if (capitals.includes(id) || wallProvinces.has(id))
1184
+ if (capitals.includes(id) || impassableProvinces.has(id))
1121
1185
  continue;
1122
1186
  const c = center(id);
1123
1187
  const distance = Math.min(...capitals.map((other) => Math.hypot(center(other).x - c.x, center(other).y - c.y)));
@@ -1230,7 +1294,7 @@ export function generateWorld(spec, context, options = {}) {
1230
1294
  // States: within each region and country, clusters of about provincesPerState.
1231
1295
  const groups = new Map();
1232
1296
  for (const id of landIds) {
1233
- const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}${wallProvinces.has(id) ? ':wall' : ''}`;
1297
+ const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}${impassableProvinces.has(id) ? ':impassable' : ''}`;
1234
1298
  const list = groups.get(key) ?? [];
1235
1299
  list.push(id);
1236
1300
  groups.set(key, list);
@@ -1268,7 +1332,7 @@ export function generateWorld(spec, context, options = {}) {
1268
1332
  victoryPoints: new Map(),
1269
1333
  navalBases: new Map(),
1270
1334
  forts: new Map(),
1271
- ...(key.endsWith(':wall') ? { impassable: true } : {}),
1335
+ ...(key.endsWith(':impassable') ? { impassable: true } : {}),
1272
1336
  };
1273
1337
  states.push(draft);
1274
1338
  for (const id of sorted)
@@ -1457,7 +1521,7 @@ export function generateWorld(spec, context, options = {}) {
1457
1521
  if (stateOf.get(id).navalBases.has(id))
1458
1522
  hasPort = true;
1459
1523
  if (coastal(id) &&
1460
- !wallProvinces.has(id) &&
1524
+ !impassableProvinces.has(id) &&
1461
1525
  (bestCoast === undefined || provinces.size[id] > provinces.size[bestCoast]))
1462
1526
  bestCoast = id;
1463
1527
  for (const next of provinces.neighbors[id])
@@ -1472,8 +1536,8 @@ export function generateWorld(spec, context, options = {}) {
1472
1536
  stateOf.get(bestCoast).navalBases.set(bestCoast, 1);
1473
1537
  }
1474
1538
  }
1475
- if (wallProvinces.size > 0)
1476
- finishWallStates(states, provinces.neighbors, context);
1539
+ if (impassableProvinces.size > 0)
1540
+ finishImpassableStates(states, provinces.neighbors, context);
1477
1541
  // Province IDs: 1-based in reading order of the province's first pixel; 0 is the null row.
1478
1542
  const provinceId = (index) => index + 1;
1479
1543
  // Unique colours, never black.
@@ -1541,6 +1605,27 @@ export function generateWorld(spec, context, options = {}) {
1541
1605
  details: { rows: rimRows.length },
1542
1606
  });
1543
1607
  const crossingRows = (gameplay?.crossings.rows ?? []).map(adjacencyRowText);
1608
+ // Impassable land and rows must not cut a realm apart or box it in by accident (ZR-28).
1609
+ if (impassableProvinces.size > 0 || (gameplay?.crossings.blocked.length ?? 0) > 0)
1610
+ for (const note of realmReachNotes({
1611
+ kind: provinces.kind,
1612
+ neighbors: provinces.neighbors,
1613
+ impassable: impassableProvinces,
1614
+ blocked: [
1615
+ ...(gameplay?.crossings.blocked ?? []),
1616
+ ...rimRows.map((row) => {
1617
+ const [from, to] = row.split(';').map(Number);
1618
+ return [from - 1, to - 1];
1619
+ }),
1620
+ ],
1621
+ crossings: (gameplay?.crossings.rows ?? [])
1622
+ .filter(({ type }) => type === 'sea')
1623
+ .map(({ from, to }) => [from - 1, to - 1]),
1624
+ owner,
1625
+ capitals,
1626
+ tags: spec.countries.map(({ tag }) => tag),
1627
+ }))
1628
+ notes.push(note);
1544
1629
  add(`${map}/adjacencies.csv`, text(`From;To;Type;Through;start_x;start_y;stop_x;stop_y;adjacency_rule_name;Comment\r\n${[...crossingRows, ...rimRows].map((row) => `${row}\r\n`).join('')}-1;-1;;-1;-1;-1;-1;-1;-1\r\n`));
1545
1630
  add(`${map}/adjacency_rules.txt`, text(gameplay === undefined
1546
1631
  ? '# No straits or canals in this world yet.\n'
@@ -3,15 +3,19 @@ import { ProtocolError, ProtocolErrorCode, ResourceNotFoundError, } from '@model
3
3
  import { artifactResourceDefinition, readArtifactResource } from '../../core/artifact-resource.js';
4
4
  import { readServerStatus, serverStatusResource } from '../../core/server-status-resource.js';
5
5
  import { ServiceError } from '../../core/result.js';
6
+ import { listSkillResources, readSkillResource, skillResourceDefinition, } from '../../reference/skill-resource.js';
6
7
  /** Modern wire projection of the same non-enumerating, authorization-bound resource reader. */
7
8
  export function registerModernResources(server, engine, context) {
8
9
  // Process details are offered to the local client only, never to authenticated remote ones.
9
10
  const local = context.principal === undefined;
10
- server.setRequestHandler('resources/list', () => ({
11
- resources: local ? [serverStatusResource] : [],
11
+ server.setRequestHandler('resources/list', async (_request, extra) => ({
12
+ resources: [
13
+ ...(local ? [serverStatusResource] : []),
14
+ ...(await listSkillResources(engine, context, extra.mcpReq.signal)),
15
+ ],
12
16
  }));
13
17
  server.setRequestHandler('resources/templates/list', () => ({
14
- resourceTemplates: [artifactResourceDefinition],
18
+ resourceTemplates: [artifactResourceDefinition, skillResourceDefinition],
15
19
  }));
16
20
  server.setRequestHandler('resources/read', async (request, extra) => {
17
21
  if (local && request.params.uri === serverStatusResource.uri)
@@ -23,7 +27,9 @@ export function registerModernResources(server, engine, context) {
23
27
  });
24
28
  try {
25
29
  return ReadResourceResultSchema.parse({
26
- ...(await readArtifactResource(engine, request.params.uri, context, extra.mcpReq.signal)),
30
+ ...(/^hoi4-agent:\/\/workspace\/[^/]+\/skill\//u.test(request.params.uri)
31
+ ? await readSkillResource(engine, request.params.uri, context, extra.mcpReq.signal)
32
+ : await readArtifactResource(engine, request.params.uri, context, extra.mcpReq.signal)),
27
33
  resultType: 'complete',
28
34
  ttlMs: 0,
29
35
  cacheScope: 'private',
@@ -34,6 +40,7 @@ export function registerModernResources(server, engine, context) {
34
40
  throw error;
35
41
  if (error instanceof ServiceError) {
36
42
  if (error.code.startsWith('RESOURCE_') ||
43
+ error.code === 'SKILL_TEXT_DRIFTED' ||
37
44
  ['ARTIFACT_URI_INVALID', 'ARTIFACT_RANGE_INVALID', 'ARTIFACT_METADATA_INVALID'].includes(error.code))
38
45
  throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message, {
39
46
  code: error.code,
@@ -1,10 +1,17 @@
1
1
  import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { artifactResourceDefinition, readArtifactResource } from '../../core/artifact-resource.js';
3
3
  import { readServerStatus, serverStatusResource } from '../../core/server-status-resource.js';
4
+ import { listSkillResources, readSkillResource, skillResourceDefinition, } from '../../reference/skill-resource.js';
4
5
  /** SDK-v1 registration only; ownership and byte-range behavior live in the shared core. */
5
6
  export function registerMcpResources(server, engine, context) {
6
7
  const { name, uriTemplate, ...metadata } = artifactResourceDefinition;
7
8
  server.registerResource(name, new ResourceTemplate(uriTemplate, { list: undefined }), metadata, (uri, _variables, extra) => readArtifactResource(engine, uri.href, context, extra.signal));
9
+ const { name: skillName, uriTemplate: skillTemplate, ...skillMetadata } = skillResourceDefinition;
10
+ server.registerResource(skillName, new ResourceTemplate(skillTemplate, {
11
+ list: async (extra) => ({
12
+ resources: await listSkillResources(engine, context, extra.signal),
13
+ }),
14
+ }), skillMetadata, (uri, _variables, extra) => readSkillResource(engine, uri.href, context, extra.signal));
8
15
  // Process details are offered to the local client only, never to authenticated remote ones.
9
16
  if (context.principal !== undefined)
10
17
  return;
@@ -18,6 +18,7 @@ export const ARGUMENT_EXAMPLES = {
18
18
  'hoi4.system_inspect': '{"kind":"mio","id":"my_organization"} or {"kind":"on_actions","audit":true}',
19
19
  'hoi4.unit_inspect': '{"kind":"oob","id":"GER_1936"} or {"kind":"variant","audit":true}',
20
20
  'hoi4.asset_inspect': '{"kind":"sprite","id":"GFX_my_icon"} or {"kind":"flag","audit":true}',
21
+ 'hoi4.skill': '{} or {"name":"hoi4-events"}',
21
22
  'hoi4.event_inspect': '{"mode":"lint","selector":"chaosx.nr14"} or {"mode":"trace","selector":"chaosx.nr14.1","direction":"downstream"}',
22
23
  'hoi4.event_render': '{"view":"overview","selector":"chaosx.nr14"}',
23
24
  'hoi4.focus_inspect': '{"treeId":"my_focus_tree"}',
@@ -83,6 +83,18 @@ const packageOutputSchema = strictOperationResultSchema(z
83
83
  absent: nonNegativeIntegerSchema,
84
84
  shadowed: nonNegativeIntegerSchema,
85
85
  unresolved: nonNegativeIntegerSchema,
86
+ notPresent: z
87
+ .array(z
88
+ .object({
89
+ category: z.string().max(64),
90
+ id: z.string().max(1024),
91
+ status: z.enum(['absent', 'shadowed', 'unresolved']),
92
+ reason: z.string().max(256).optional(),
93
+ path: z.string().max(1024).optional(),
94
+ })
95
+ .strict())
96
+ .max(32),
97
+ notPresentTruncated: z.boolean(),
86
98
  })
87
99
  .strict());
88
100
  const scenarioOutputSchema = strictOperationResultSchema(z
@@ -1,11 +1,12 @@
1
1
  import { errorResult, strictOperationResultSchema } from '../../core/operation-result.js';
2
2
  import { ReferenceToolService } from '../../reference/operations.js';
3
- import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, referenceContextDataSchema, referenceReadDataSchema, referenceSearchDataSchema, sourceLookupDataSchema, } from '../../schemas/reference.js';
3
+ import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, referenceContextToolDataSchema, referenceReadDataSchema, referenceSearchToolDataSchema, sourceLookupDataSchema, } from '../../schemas/reference.js';
4
4
  import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../../schemas/localisation.js';
5
5
  import { systemInspectDataSchema, systemInspectRequestSchema, unitInspectDataSchema, unitInspectRequestSchema, assetInspectDataSchema, assetInspectRequestSchema, } from '../../schemas/system.js';
6
6
  import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../../schemas/ideas.js';
7
7
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../../schemas/mod-tools.js';
8
8
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../../schemas/script-validation.js';
9
+ import { skillDataSchema, skillRequestSchema } from '../../schemas/skill.js';
9
10
  const readOnly = {
10
11
  readOnlyHint: true,
11
12
  destructiveHint: false,
@@ -18,7 +19,7 @@ export const referenceTools = [
18
19
  title: 'Find a modding rule',
19
20
  description: 'Find the right modding rule in the offline wiki and installed game docs using ordinary words or script names. Each hit includes its file, lines, revision and answering line. Example: {"query":"add_timed_idea"}. Returns 6 hits by default (up to 12); read one with hoi4.reference_read using its id and revision.',
20
21
  inputSchema: referenceSearchRequestSchema,
21
- outputSchema: strictOperationResultSchema(referenceSearchDataSchema),
22
+ outputSchema: strictOperationResultSchema(referenceSearchToolDataSchema),
22
23
  annotations: readOnly,
23
24
  },
24
25
  {
@@ -34,7 +35,7 @@ export const referenceTools = [
34
35
  title: 'Find docs for a modding task',
35
36
  description: 'Find documentation for the content you are building: events, decisions, ideas, focuses, technology, GUI, maps, localisation or AI. Example: {"surface":"event","question":"fire an event after a delay"}. Returns up to 16 short sections; read more with hoi4.reference_read.',
36
37
  inputSchema: referenceContextRequestSchema,
37
- outputSchema: strictOperationResultSchema(referenceContextDataSchema),
38
+ outputSchema: strictOperationResultSchema(referenceContextToolDataSchema),
38
39
  annotations: readOnly,
39
40
  },
40
41
  {
@@ -109,6 +110,14 @@ export const referenceTools = [
109
110
  outputSchema: strictOperationResultSchema(assetInspectDataSchema),
110
111
  annotations: readOnly,
111
112
  },
113
+ {
114
+ name: 'hoi4.skill',
115
+ title: "Read the mod's modding skills",
116
+ description: 'List the modding skills installed in the mod, or load one by name, at the kit version HOI4 Mod Setup pinned, with its hash. A file edited since Setup installed it is refused unless acceptLocalEdits. Example: {"name":"hoi4-events"}. Returns up to 20,000 bytes of text; continue from nextOffset.',
117
+ inputSchema: skillRequestSchema,
118
+ outputSchema: strictOperationResultSchema(skillDataSchema),
119
+ annotations: readOnly,
120
+ },
112
121
  ];
113
122
  export function registerReferenceTools(server, engine, context) {
114
123
  const service = new ReferenceToolService(engine);
@@ -201,6 +201,7 @@ export class PackageAnalyzer {
201
201
  sourceHashes: evidence.sourceHashes,
202
202
  metadata: { beforeRevision: snapshot.revision, sourceInventory: evidence.inventory },
203
203
  }, 'Revision-pinned package connection inventory', input.signal);
204
+ const missing = results.filter(({ status }) => status !== 'present');
204
205
  const result = emptyServiceResult(input.workspaceId, {
205
206
  sourceRevision: snapshot.revision,
206
207
  reportHash,
@@ -210,10 +211,22 @@ export class PackageAnalyzer {
210
211
  absent: results.filter(({ status }) => status === 'absent').length,
211
212
  shadowed: results.filter(({ status }) => status === 'shadowed').length,
212
213
  unresolved: results.filter(({ status }) => status === 'unresolved').length,
214
+ // The answer is which items are missing; name them inline, not only in the report (#66).
215
+ notPresent: missing.slice(0, 32).map(({ category, id, status, reason, path }) => ({
216
+ category,
217
+ id: id.slice(0, 1024),
218
+ status: status,
219
+ ...(reason === undefined ? {} : { reason: reason.slice(0, 256) }),
220
+ ...(path === undefined ? {} : { path: path.slice(0, 1024) }),
221
+ })),
222
+ notPresentTruncated: missing.length > 32,
213
223
  });
214
224
  result.code = report.complete ? 'PACKAGE_CHECK_PASSED' : 'PACKAGE_CHECK_INCOMPLETE';
215
225
  result.artifacts = [publicArtifactLink(artifact)];
216
- setInlineFilesScanned(result, snapshot.files.map(({ displayPath }) => displayPath));
226
+ // The files that hold the checked items, not the first files of the workspace (#66).
227
+ setInlineFilesScanned(result, [
228
+ ...new Set(results.flatMap(({ path }) => (path === undefined ? [] : [path]))),
229
+ ]);
217
230
  result.validation = {
218
231
  passed: report.complete,
219
232
  checks: [
@@ -1,5 +1,5 @@
1
1
  export const PROBABILITY_SCHEMA_VERSION = 1;
2
- export const PROBABILITY_ADAPTER_VERSION = 'hoi4-1.19.2.v1';
3
- export const VERIFIED_GAME_VERSION = 'Operation Postern 1.19.2.0 (d245)';
4
- export const VERIFIED_GAME_RAW_VERSION = '1.19.2.0';
5
- export const VERIFIED_GAME_CHECKSUM = 'd245';
2
+ export const PROBABILITY_ADAPTER_VERSION = 'hoi4-1.19.4.1.v1';
3
+ export const VERIFIED_GAME_VERSION = 'Operation Postern 1.19.4.1 (f584)';
4
+ export const VERIFIED_GAME_RAW_VERSION = '1.19.4.1';
5
+ export const VERIFIED_GAME_CHECKSUM = 'f584';
@@ -1,6 +1,7 @@
1
1
  import { emptyServiceResult } from '../core/result.js';
2
2
  import { setInlineFilesScanned } from '../core/operation-result.js';
3
3
  import { probabilityCompareRequestSchema, probabilityEvaluateRequestSchema, probabilityInspectRequestSchema, probabilityRenderRequestSchema, probabilitySequenceRequestSchema, probabilitySimulateRequestSchema, probabilitySweepRequestSchema, probabilityAnalyzeRequestSchema, splitProbabilityAnalyzeRequest, } from '../schemas/probability-requests.js';
4
+ import { gameVersionDiagnostics } from './service.js';
4
5
  function runtime(context, refresh) {
5
6
  return {
6
7
  workspaceId: context.workspaceId,
@@ -305,6 +306,11 @@ export async function inspectProbabilities(analyzer, input, context) {
305
306
  : inspected.discovery !== undefined
306
307
  ? 'PROBABILITY_SOURCE_DISCOVERED'
307
308
  : 'PROBABILITY_ADAPTERS_LISTED';
309
+ if (surface !== undefined)
310
+ result.diagnostics = [
311
+ ...gameVersionDiagnostics(surface.gameVersionVerification),
312
+ ...result.diagnostics,
313
+ ];
308
314
  result.artifacts = inspected.artifacts;
309
315
  setInlineFilesScanned(result, inspected.filesScanned);
310
316
  return result;