hoi4-agent-tools 4.16.0 → 4.18.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 (109) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
  7. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  8. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  9. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  10. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  11. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  12. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  13. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  14. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  15. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  16. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  17. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  18. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  19. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  20. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  21. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  22. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  23. package/dist/hoi4_agent_tools/map/model.js +9 -8
  24. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  25. package/dist/hoi4_agent_tools/map/operations.js +266 -23
  26. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  27. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  28. package/dist/hoi4_agent_tools/map/service.js +25 -12
  29. package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
  30. package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
  31. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  32. package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  34. package/dist/hoi4_agent_tools/map/water.js +13 -10
  35. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  36. package/dist/hoi4_agent_tools/map/world.js +51 -1
  37. package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
  38. package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
  39. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  40. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  41. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  42. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  43. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  44. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  45. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  46. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  47. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  48. package/dist/hoi4_agent_tools/runtime.js +27 -11
  49. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  50. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  51. package/dist/hoi4_agent_tools/schemas/map.js +103 -2
  52. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  53. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  54. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  55. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  56. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  57. package/dist/hoi4_agent_tools/version.js +1 -1
  58. package/docs/configuration.md +1 -1
  59. package/docs/map.md +67 -23
  60. package/docs/research/reference-benchmark.md +64 -0
  61. package/docs/tools.md +20 -20
  62. package/docs/troubleshooting.md +4 -0
  63. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  64. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  65. package/engine/bin/linux-x64/hoi4-engine +0 -0
  66. package/engine/bin/manifest.json +8 -8
  67. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +5 -3
  70. package/schemas/configuration.schema.json +1 -1
  71. package/schemas/continuous-focus-palette.schema.json +1 -1
  72. package/schemas/custom-weighted-pool.schema.json +1 -1
  73. package/schemas/decision-inspect-input.schema.json +1 -1
  74. package/schemas/error-log-input.schema.json +1 -1
  75. package/schemas/event-feature-manifest.schema.json +1 -1
  76. package/schemas/focus-plan.schema.json +1 -1
  77. package/schemas/focus-planning-sidecar.schema.json +1 -1
  78. package/schemas/geography-model.schema.json +1 -1
  79. package/schemas/gui-animation-source.schema.json +1 -1
  80. package/schemas/gui-helper.schema.json +1 -1
  81. package/schemas/gui-scenario.schema.json +1 -1
  82. package/schemas/helper-expansion-request.schema.json +1 -1
  83. package/schemas/helper-expansion-summary.schema.json +1 -1
  84. package/schemas/impact-inspect-input.schema.json +1 -1
  85. package/schemas/map-operation.schema.json +1087 -815
  86. package/schemas/mechanic-test-input.schema.json +1 -1
  87. package/schemas/mod-index-input.schema.json +1 -1
  88. package/schemas/operation-result.schema.json +1 -1
  89. package/schemas/package-check-input.schema.json +1 -1
  90. package/schemas/package-manifest.schema.json +1 -1
  91. package/schemas/probability-analysis-result.schema.json +1 -1
  92. package/schemas/probability-compare-input.schema.json +1 -1
  93. package/schemas/probability-evaluate-input.schema.json +1 -1
  94. package/schemas/probability-inspect-input.schema.json +1 -1
  95. package/schemas/probability-render-input.schema.json +1 -1
  96. package/schemas/probability-scenario-set.schema.json +1 -1
  97. package/schemas/probability-sequence-input.schema.json +1 -1
  98. package/schemas/probability-simulate-input.schema.json +1 -1
  99. package/schemas/probability-sweep-input.schema.json +1 -1
  100. package/schemas/reference-context-input.schema.json +1 -1
  101. package/schemas/reference-read-input.schema.json +1 -1
  102. package/schemas/reference-search-input.schema.json +2 -2
  103. package/schemas/reference-sheets.schema.json +1 -1
  104. package/schemas/scenario-suite.schema.json +1 -1
  105. package/schemas/scenario-test-input.schema.json +1 -1
  106. package/schemas/script-validate-input.schema.json +7 -1
  107. package/schemas/shared-scenario.schema.json +1 -1
  108. package/schemas/source-lookup-input.schema.json +1 -1
  109. package/server.json +2 -2
@@ -11,7 +11,32 @@ import { allocateMapIdentifiersAsync, WORLD_OUTPUT_PATH_SAMPLE, } from './operat
11
11
  import { compactTerritoryReport } from './territory-operations.js';
12
12
  import { borderQualityDiagnostics } from './border-quality.js';
13
13
  import { measureIndexBorderNaturalness, summarizeBorderQuality, } from './border-quality-input.js';
14
- import { buildMapCatalog, lookupMapCoordinate, searchMapCatalog } from './catalog.js';
14
+ import { naturalLandsFromIndex, summarizeNaturalLands, } from './natural-lands.js';
15
+ import { buildMapCatalog, lookupMapCoordinate, searchMapCatalog, } from './catalog.js';
16
+ /** Matches named inline, so a lookup answers without reading its artifact. */
17
+ const INLINE_MATCH_LIMIT = 20;
18
+ function inlineMatches(queryMatches, coordinateMatches) {
19
+ return {
20
+ ...(queryMatches.length === 0
21
+ ? {}
22
+ : {
23
+ matches: queryMatches
24
+ .slice(0, INLINE_MATCH_LIMIT)
25
+ .map(({ kind, id, key, displayName }) => ({ kind, id, key, name: displayName })),
26
+ }),
27
+ ...(coordinateMatches.length === 0
28
+ ? {}
29
+ : {
30
+ coordinateMatches: coordinateMatches
31
+ .slice(0, INLINE_MATCH_LIMIT)
32
+ .map(({ provinceId, stateIds, regionIds }) => ({
33
+ provinceId,
34
+ stateIds: stateIds.slice(0, 16),
35
+ regionIds: regionIds.slice(0, 16),
36
+ })),
37
+ }),
38
+ };
39
+ }
15
40
  import { GEOGRAPHY_FEATURE_KINDS } from './geography/model.js';
16
41
  import { operationHasGeography } from './geography/preparation.js';
17
42
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -745,6 +770,7 @@ export async function inspectMap(engine, nudger, input, context) {
745
770
  allocationCount: 0,
746
771
  queryMatchCount: queryMatches.length,
747
772
  coordinateMatchCount: coordinateMatches.length,
773
+ ...inlineMatches(queryMatches, coordinateMatches),
748
774
  overviewRendered: false,
749
775
  provinceGeometryCount: 0,
750
776
  provinceGeometryPixelCount: 0,
@@ -772,14 +798,14 @@ export async function inspectMap(engine, nudger, input, context) {
772
798
  // Check the ids on the cached scan before the full validation.
773
799
  if (input.stateIds.length + input.provinceIds.length + input.regionIds.length > 0)
774
800
  assertKnownMapEntities(await nudger.scan(context.workspaceId, context.principal, context.signal), input);
775
- const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality);
801
+ const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality || input.lands);
776
802
  const sharedRevision = snapshot.revision;
777
803
  let borderQuality;
778
804
  const qualityDiagnostics = [];
779
805
  if (input.quality) {
780
806
  await context.progress(1, 3, 'Measuring how natural the borders are');
781
807
  try {
782
- const measured = await measureIndexBorderNaturalness(snapshot.index, context.signal === undefined ? {} : { signal: context.signal });
808
+ const measured = await measureIndexBorderNaturalness(snapshot.index, context.signal === undefined ? {} : { signal: context.signal }, input.qualityScope);
783
809
  borderQuality = {
784
810
  report: measured.report,
785
811
  summary: summarizeBorderQuality(measured.report, measured.skipped),
@@ -798,6 +824,34 @@ export async function inspectMap(engine, nudger, input, context) {
798
824
  });
799
825
  }
800
826
  }
827
+ let naturalLands;
828
+ if (input.lands) {
829
+ await context.progress(1, 3, 'Cutting the land into natural lands');
830
+ try {
831
+ const computed = await naturalLandsFromIndex(snapshot.index, {
832
+ ...(input.landOptions ?? {}),
833
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
834
+ });
835
+ naturalLands = {
836
+ result: computed.result,
837
+ summary: summarizeNaturalLands(computed.result, computed.skipped),
838
+ };
839
+ }
840
+ catch (error) {
841
+ if (!(error instanceof ServiceError) ||
842
+ !(error.code === 'MAP_NATURAL_LANDS_RASTER_MISSING' ||
843
+ error.code === 'MAP_NATURAL_LANDS_INPUT_INVALID' ||
844
+ error.code === 'MAP_BORDER_QUALITY_RASTER_MISSING'))
845
+ throw error;
846
+ qualityDiagnostics.push({
847
+ code: 'MAP_NATURAL_LANDS_UNAVAILABLE',
848
+ severity: 'warning',
849
+ category: 'map',
850
+ message: `Natural lands could not be computed: ${error.message}`,
851
+ details: { reason: error.code, ...error.details },
852
+ });
853
+ }
854
+ }
801
855
  const catalog = buildMapCatalog(snapshot.index);
802
856
  const queryMatches = input.query === undefined ? [] : searchMapCatalog(catalog, input.query, input.queryLimit);
803
857
  const coordinateMatches = input.coordinates.map((coordinate) => lookupMapCoordinate(snapshot.index, coordinate));
@@ -885,6 +939,26 @@ export async function inspectMap(engine, nudger, input, context) {
885
939
  },
886
940
  description: 'Border naturalness: alignment with rivers, slopes, lake shores and terrain changes, enrichment over chance, straightness and the worst artificial runs for each border layer',
887
941
  });
942
+ if (naturalLands !== undefined)
943
+ artifactWrites.push({
944
+ name: `map-natural-lands.${snapshot.revision.slice(0, 16)}.json`,
945
+ mimeType: 'application/json',
946
+ content: `${canonicalJson({
947
+ revision: snapshot.revision,
948
+ ...naturalLands.result,
949
+ skippedInputs: naturalLands.summary.skippedInputs,
950
+ sourceHashes: sourceEvidence.complete,
951
+ })}
952
+ `,
953
+ provenance: {
954
+ kind: 'map-natural-lands',
955
+ toolVersion: PACKAGE_VERSION,
956
+ schemaVersion: 'map-natural-lands.v1',
957
+ sourceHashes: sourceEvidence.bounded.sourceHashes,
958
+ metadata: { sharedRevision, sourceHashInventory: sourceEvidence.bounded.inventory },
959
+ },
960
+ description: 'Natural lands: every land with its kind, provinces, terrain shares, coast, and the river, crest, terrain and divide lengths of its lines to each neighbouring land',
961
+ });
888
962
  if (overviewRendered) {
889
963
  const overviewLayer = 'state';
890
964
  const overviewOverlays = [
@@ -971,6 +1045,7 @@ export async function inspectMap(engine, nudger, input, context) {
971
1045
  allocationCount: allocationPreviews.length,
972
1046
  queryMatchCount: queryMatches.length,
973
1047
  coordinateMatchCount: coordinateMatches.length,
1048
+ ...inlineMatches(queryMatches, coordinateMatches),
974
1049
  overviewRendered,
975
1050
  provinceGeometryCount: provinceGeometry?.provinces.length ?? 0,
976
1051
  provinceGeometryPixelCount: provinceGeometry?.pixelCount ?? 0,
@@ -979,6 +1054,7 @@ export async function inspectMap(engine, nudger, input, context) {
979
1054
  missingGeometryProvinceIds: provinceGeometry?.missingGeometryProvinceIds ?? [],
980
1055
  ...(scriptReferences === undefined ? {} : { scriptReferences }),
981
1056
  ...(borderQuality === undefined ? {} : { quality: borderQuality.summary }),
1057
+ ...(naturalLands === undefined ? {} : { lands: naturalLands.summary }),
982
1058
  });
983
1059
  result.code = 'MAP_INSPECTED';
984
1060
  setInlineFilesScanned(result, snapshot.files.map(({ displayPath }) => displayPath));
@@ -240,6 +240,25 @@ function* provinceHoleCounts(raster, components, signal) {
240
240
  }
241
241
  return holes;
242
242
  }
243
+ /**
244
+ * The TypeScript geometry checks on a raster, run to the end: the reference the engine's
245
+ * topology (ADR 0084) is checked against in tests and `scripts/map-raster-parity.ts`.
246
+ */
247
+ export function typeScriptProvinceTopology(raster) {
248
+ const run = (steps) => {
249
+ for (;;) {
250
+ const next = steps.next();
251
+ if (next.done === true)
252
+ return next.value;
253
+ }
254
+ };
255
+ const components = run(provinceComponents(raster));
256
+ return {
257
+ components,
258
+ holes: run(provinceHoleCounts(raster, components)),
259
+ thin: run(provinceThinPixels(raster)),
260
+ };
261
+ }
243
262
  function* validateGeometry(index, diagnostics, options) {
244
263
  yield* cancellationCheckpoint(options.signal);
245
264
  const bitmap = index.provinceBitmap;
@@ -366,9 +385,10 @@ function* validateGeometry(index, diagnostics, options) {
366
385
  },
367
386
  });
368
387
  }
369
- const components = yield* provinceComponents(raster, options.signal);
370
- const holes = yield* provinceHoleCounts(raster, components, options.signal);
371
- const thin = yield* provinceThinPixels(raster, options.signal);
388
+ // The engine computes these with the raster (ADR 0084); a raster built in TypeScript does not.
389
+ const components = raster.topology?.components ?? (yield* provinceComponents(raster, options.signal));
390
+ const holes = raster.topology?.holes ?? (yield* provinceHoleCounts(raster, components, options.signal));
391
+ const thin = raster.topology?.thin ?? (yield* provinceThinPixels(raster, options.signal));
372
392
  for (const definition of index.definitions) {
373
393
  if (definition.id === 0)
374
394
  continue;
@@ -54,29 +54,32 @@ export function landDistanceField(kind, width, height, limit = 255) {
54
54
  distance[pixel] = 0;
55
55
  queue[tail++] = pixel;
56
56
  }
57
+ // No closure per pixel: on the game's 11.5 million pixels it was most of this function's time.
57
58
  while (head < tail) {
58
59
  const pixel = queue[head++];
59
60
  const next = distance[pixel] + 1;
60
61
  if (next >= limit)
61
62
  continue;
62
63
  const x = pixel % width;
63
- const visit = (other) => {
64
- if (distance[other] === limit && kind[other] !== LAND) {
65
- distance[other] = next;
66
- queue[tail++] = other;
67
- }
68
- };
69
64
  if (x > 0)
70
- visit(pixel - 1);
65
+ tail = reachWater(kind, distance, queue, tail, pixel - 1, next, limit);
71
66
  if (x < width - 1)
72
- visit(pixel + 1);
67
+ tail = reachWater(kind, distance, queue, tail, pixel + 1, next, limit);
73
68
  if (pixel >= width)
74
- visit(pixel - width);
69
+ tail = reachWater(kind, distance, queue, tail, pixel - width, next, limit);
75
70
  if (pixel < total - width)
76
- visit(pixel + width);
71
+ tail = reachWater(kind, distance, queue, tail, pixel + width, next, limit);
77
72
  }
78
73
  return distance;
79
74
  }
75
+ /** Give an unreached water pixel its distance and queue it; returns the new queue end. */
76
+ function reachWater(kind, distance, queue, tail, other, next, limit) {
77
+ if (distance[other] !== limit || kind[other] === LAND)
78
+ return tail;
79
+ distance[other] = next;
80
+ queue[tail] = other;
81
+ return tail + 1;
82
+ }
80
83
  /**
81
84
  * Enforce the lake rules on a raster of 0 sea, 1 land and 2 lake (modified in place, with the
82
85
  * matching elevation values): lake water that touches the open sea is sea, and enclosed water
@@ -24,39 +24,51 @@ export function reconcileWorldOutputs(sources, proposed, operationId, mapRoot, s
24
24
  * output the request writes gets its new hash, or with `adoptAll` every recorded output its
25
25
  * current bytes (`record_world_outputs`). Undefined when the workspace has no world inventory.
26
26
  */
27
- export function refreshWorldOutputs(sources, proposed, adoptAll = false) {
27
+ export function refreshWorldOutputs(sources, proposed, roots, options = {}) {
28
+ const permits = worldOutputPermits(roots);
28
29
  return refreshManagedOutputs({
29
30
  manifestPath: WORLD_OUTPUT_MANIFEST,
30
31
  sources,
31
32
  proposed,
32
- ...(adoptAll ? { adoptAll: true } : {}),
33
+ // New files join the record where the world keeps its map outputs; country files stay out,
34
+ // since a workspace may own its countries (ADR 0069).
35
+ addable: (name) => permits(name) && !isWorldCountryOutput(name),
36
+ // States and strategic regions are in every map scan; bitmaps, colour maps and the world
37
+ // scripts only in some, so only the first can be known to be gone.
38
+ alwaysScanned: (name) => {
39
+ const dir = path.posix.dirname(name);
40
+ return roots.stateRoots.includes(dir) || dir === `${roots.mapRoot}/strategicregions`;
41
+ },
42
+ ...(options.adoptAll === true ? { adoptAll: true } : {}),
43
+ ...(options.adoptUnrecorded === true ? { adoptUnrecorded: true } : {}),
33
44
  });
34
45
  }
35
- export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots, options = {}) {
36
- const mapFiles = new Set([
37
- 'provinces.bmp',
38
- 'definition.csv',
39
- 'default.map',
40
- 'continent.txt',
41
- 'adjacencies.csv',
42
- 'adjacency_rules.txt',
43
- 'positions.txt',
44
- 'ambient_object.txt',
45
- 'heightmap.bmp',
46
- 'terrain.bmp',
47
- 'rivers.bmp',
48
- 'trees.bmp',
49
- 'cities.bmp',
50
- 'world_normal.bmp',
51
- 'buildings.txt',
52
- 'unitstacks.txt',
53
- 'weatherpositions.txt',
54
- 'supply_nodes.txt',
55
- 'railways.txt',
56
- ]);
57
- const permitsPath = (name) => {
46
+ const WORLD_MAP_FILES = new Set([
47
+ 'provinces.bmp',
48
+ 'definition.csv',
49
+ 'default.map',
50
+ 'continent.txt',
51
+ 'adjacencies.csv',
52
+ 'adjacency_rules.txt',
53
+ 'positions.txt',
54
+ 'ambient_object.txt',
55
+ 'heightmap.bmp',
56
+ 'terrain.bmp',
57
+ 'rivers.bmp',
58
+ 'trees.bmp',
59
+ 'cities.bmp',
60
+ 'world_normal.bmp',
61
+ 'buildings.txt',
62
+ 'unitstacks.txt',
63
+ 'weatherpositions.txt',
64
+ 'supply_nodes.txt',
65
+ 'railways.txt',
66
+ ]);
67
+ /** The paths a generated world records as its outputs. */
68
+ export function worldOutputPermits({ mapRoot, stateRoots, localisationRoots, }) {
69
+ return (name) => {
58
70
  const dir = path.posix.dirname(name), file = path.posix.basename(name);
59
- return ((dir === mapRoot && mapFiles.has(file)) ||
71
+ return ((dir === mapRoot && WORLD_MAP_FILES.has(file)) ||
60
72
  (dir === `${mapRoot}/terrain` && /^colormap_[a-z0-9_]+\.dds$/u.test(file)) ||
61
73
  (dir === `${mapRoot}/strategicregions` && /^\d+.*\.txt$/u.test(file)) ||
62
74
  (stateRoots.includes(dir) && /^\d+.*\.txt$/u.test(file)) ||
@@ -69,6 +81,9 @@ export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateR
69
81
  localisationRoots.some((root) => name === `${root}/english/world_l_english.yml` ||
70
82
  name === `${root}/replace/world_l_english.yml`));
71
83
  };
84
+ }
85
+ export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots, options = {}) {
86
+ const permitsPath = worldOutputPermits({ mapRoot, stateRoots, localisationRoots });
72
87
  return planManagedOutputs({
73
88
  manifestPath: WORLD_OUTPUT_MANIFEST,
74
89
  sources,
@@ -11,7 +11,7 @@ import { generateWorldDrainage } from './world-drainage.js';
11
11
  import { generateWorldProvinces } from './world-provinces.js';
12
12
  import { clusterRegions, clusterStates, partitionWorldFromRequest, } from './partition.js';
13
13
  import { repairSeamCorners, smoothDiagonalContacts } from './partition-fields.js';
14
- import { PARTITION_PROVINCE_ERROR, PARTITION_PROVINCE_WARNING } from './partition-tuning.js';
14
+ import { areaRowFactor, PARTITION_PROVINCE_ERROR, PARTITION_PROVINCE_WARNING, } from './partition-tuning.js';
15
15
  import { buildTerritoryAtoms, territoryGraphFromPartition } from './territory-graph.js';
16
16
  import { growTerritory } from './territory.js';
17
17
  import { geographyPartitionFields, provinceCountNote, surfacePartitionFields, } from './world-partition.js';
@@ -409,6 +409,53 @@ function estimatePermanentSnow(input) {
409
409
  }
410
410
  return count;
411
411
  }
412
+ /**
413
+ * The realised land province areas of `partitionTuning.areaByRow`: for each band between two of
414
+ * its rows (and the rows beyond its ends), the land provinces whose centre lies there, their mean
415
+ * area and its ratio to the mean of the band with the smallest factor.
416
+ */
417
+ function areaByRowNote(provinces, points, height) {
418
+ const edges = [...new Set([0, ...points.map(([row]) => row), 1])].sort((a, b) => a - b);
419
+ const bands = edges.slice(0, -1).map((from, index) => ({
420
+ from,
421
+ to: edges[index + 1],
422
+ factor: [
423
+ Number(areaRowFactor(points, from * height - 0.5, height).toFixed(3)),
424
+ Number(areaRowFactor(points, edges[index + 1] * height - 0.5, height).toFixed(3)),
425
+ ],
426
+ provinces: 0,
427
+ pixels: 0,
428
+ }));
429
+ for (let id = 0; id < provinces.kind.length; id += 1) {
430
+ if (provinces.kind[id] !== LAND || (provinces.size[id] ?? 0) === 0)
431
+ continue;
432
+ const row = provinces.sumY[id] / provinces.size[id] / height;
433
+ const band = bands.find(({ from, to }, index) => row >= from && (row < to || index === bands.length - 1)) ?? bands[bands.length - 1];
434
+ band.provinces += 1;
435
+ band.pixels += provinces.size[id];
436
+ }
437
+ const filled = bands.filter(({ provinces: count }) => count > 0);
438
+ const smallest = filled.reduce((best, band) => best === undefined || Math.max(...band.factor) < Math.max(...best.factor) ? band : best, undefined);
439
+ const reference = smallest === undefined ? 0 : smallest.pixels / smallest.provinces;
440
+ const report = bands.map(({ from, to, factor, provinces: count, pixels }) => {
441
+ const mean = count === 0 ? 0 : pixels / count;
442
+ return {
443
+ rows: [from, to],
444
+ factor,
445
+ landProvinces: count,
446
+ meanAreaPx: Math.round(mean),
447
+ ...(reference > 0 && count > 0 ? { ratio: Number((mean / reference).toFixed(2)) } : {}),
448
+ };
449
+ });
450
+ return {
451
+ code: 'MAP_PARTITION_AREA_BY_ROW',
452
+ severity: 'info',
453
+ message: `Land province area by row: ${report
454
+ .map(({ rows, landProvinces, meanAreaPx }) => `rows ${rows[0]}-${rows[1]}: ${landProvinces} provinces of ${meanAreaPx} px on average`)
455
+ .join('; ')}`,
456
+ details: { areaByRow: points, bands: report },
457
+ };
458
+ }
412
459
  /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
413
460
  export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
414
461
  function terrainSummaryNote(terrain, geography) {
@@ -1039,6 +1086,9 @@ export function generateWorld(spec, context, options = {}) {
1039
1086
  provinces = featurePartition.provinces;
1040
1087
  for (const note of featurePartition.notes)
1041
1088
  notes.push(note);
1089
+ const areaByRow = featurePartition.tuning.areaByRow;
1090
+ if (areaByRow !== undefined)
1091
+ notes.push(areaByRowNote(provinces, areaByRow, height));
1042
1092
  }
1043
1093
  else
1044
1094
  provinces = generateWorldProvinces({
@@ -1,6 +1,7 @@
1
1
  import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
2
2
  import { z } from 'zod/v4';
3
3
  import { mapInspectRequestSchema, mapRewriteRequestSchema } from '../../schemas/map-requests.js';
4
+ import { NATURAL_LAND_KINDS, NATURAL_LANDS_INLINE_LIMIT } from '../../map/natural-lands.js';
4
5
  import { allocationEvidenceSchema, bitmapRenderHashesSchema, nonNegativeIntegerSchema, operationBlockerDataSchema, sha256Schema, } from '../server/output-schemas.js';
5
6
  import { strictOperationResultSchema } from '../server/result.js';
6
7
  const changedBoundsSchema = z
@@ -96,9 +97,36 @@ const borderQualitySummarySchema = z
96
97
  skippedInputs: z
97
98
  .array(z.object({ input: z.string().max(32), reason: z.string().max(256) }).strict())
98
99
  .max(8),
100
+ scopePixels: nonNegativeIntegerSchema
101
+ .optional()
102
+ .describe('Pixels inside qualityScope; absent when the whole map was measured.'),
99
103
  layers: z.array(borderLayerSummarySchema).max(8),
100
104
  })
101
105
  .strict();
106
+ const naturalLandKindSchema = z.enum(NATURAL_LAND_KINDS);
107
+ const naturalLandsSummarySchema = z
108
+ .object({
109
+ count: nonNegativeIntegerSchema,
110
+ landProvinces: nonNegativeIntegerSchema,
111
+ counts: z.record(naturalLandKindSchema, nonNegativeIntegerSchema),
112
+ inputs: z.object({ heights: z.boolean(), rivers: z.boolean() }).strict(),
113
+ skippedInputs: z
114
+ .array(z.object({ input: z.string().max(32), reason: z.string().max(256) }).strict())
115
+ .max(8),
116
+ undersized: nonNegativeIntegerSchema,
117
+ lands: z
118
+ .array(z
119
+ .object({
120
+ id: z.string().max(16),
121
+ kind: naturalLandKindSchema,
122
+ provinces: nonNegativeIntegerSchema,
123
+ coast: z.boolean(),
124
+ })
125
+ .strict())
126
+ .max(NATURAL_LANDS_INLINE_LIMIT),
127
+ truncated: z.boolean(),
128
+ })
129
+ .strict();
102
130
  const mapWorkspaceInspectDataSchema = z
103
131
  .object({
104
132
  revision: sha256Schema,
@@ -120,6 +148,29 @@ const mapWorkspaceInspectDataSchema = z
120
148
  provinceGeometryPixelCount: nonNegativeIntegerSchema,
121
149
  provinceGeometryRowRunCount: nonNegativeIntegerSchema,
122
150
  lookupOnly: z.boolean().optional(),
151
+ /** The first 20 query matches, best first; the full list is in the linked artifact. */
152
+ matches: z
153
+ .array(z
154
+ .object({
155
+ kind: z.enum(['province', 'state', 'strategic-region']),
156
+ id: nonNegativeIntegerSchema,
157
+ key: z.string(),
158
+ name: z.string(),
159
+ })
160
+ .strict())
161
+ .max(20)
162
+ .optional(),
163
+ /** What each requested coordinate falls in (the first 20). */
164
+ coordinateMatches: z
165
+ .array(z
166
+ .object({
167
+ provinceId: nonNegativeIntegerSchema.nullable(),
168
+ stateIds: z.array(nonNegativeIntegerSchema).max(16),
169
+ regionIds: z.array(nonNegativeIntegerSchema).max(16),
170
+ })
171
+ .strict())
172
+ .max(20)
173
+ .optional(),
123
174
  unknownProvinceIds: z.array(nonNegativeIntegerSchema).max(512),
124
175
  missingGeometryProvinceIds: z.array(nonNegativeIntegerSchema).max(512),
125
176
  scriptReferences: z
@@ -127,6 +178,7 @@ const mapWorkspaceInspectDataSchema = z
127
178
  .strict()
128
179
  .optional(),
129
180
  quality: borderQualitySummarySchema.optional(),
181
+ lands: naturalLandsSummarySchema.optional(),
130
182
  })
131
183
  .strict();
132
184
  const mapRenderDataSchema = z
@@ -19,7 +19,7 @@ export const referenceTools = [
19
19
  {
20
20
  name: 'hoi4.reference_search',
21
21
  title: 'Find a modding rule',
22
- 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.',
22
+ description: 'Find a modding rule in the offline wiki and installed game docs by plain words or script name. Returns up to 10 short candidates (limit up to 12) with file, lines, revision and, for a command, a one-line meaning and its scopes. Pick the one that fits, since several commands sound alike, then read it with hoi4.reference_read using its id and revision. Example: {"query":"add_timed_idea"} or {"query":"make a country hold elections now"}.',
23
23
  inputSchema: referenceSearchRequestSchema,
24
24
  outputSchema: strictOperationResultSchema(referenceSearchToolDataSchema),
25
25
  annotations: readOnly,
@@ -51,7 +51,7 @@ export const referenceTools = [
51
51
  {
52
52
  name: 'hoi4.script_validate',
53
53
  title: 'Check HOI4 script commands and scopes',
54
- description: 'Find broken syntax, commands and scopes in an effect, trigger or mod file using the installed docs. Unknown helpers and native argument blocks stay unresolved. Example: {"source":"add_political_power = 10","kind":"effect","scope":"country"} or {"path":"events/a.txt"}. Returns up to 12 findings.',
54
+ description: 'Find broken syntax, commands and scopes in an effect, trigger or mod file using the installed docs. Unknown helpers and native argument blocks stay unresolved. Example: {"source":"add_political_power = 10","kind":"effect","scope":"country"} or {"path":"events/a.txt"}. {"closure":true} instead counts whether the references of the whole mod resolve, per kind. Returns up to 12 findings.',
55
55
  inputSchema: scriptValidateRequestSchema,
56
56
  outputSchema: strictOperationResultSchema(scriptValidateDataSchema),
57
57
  annotations: readOnly,
@@ -91,7 +91,7 @@ export const referenceTools = [
91
91
  {
92
92
  name: 'hoi4.mod_index',
93
93
  title: 'Explore mod content and find free IDs',
94
- description: 'Summarize the content in a mod or find a free event ID across the mod, game and dependencies. Use overview for descriptors, folders and definitions, or next_id with a namespace or prefix. Example: {"mode":"next_id","kind":"event","namespace":"my_mod"}. Returns a compact summary; the first call indexes the mod, which takes seconds on a large one.',
94
+ description: 'Summarize the content in a mod or find a free event ID across the mod, game and dependencies. Use overview for descriptors, folders and definitions (the 50 busiest namespaces; pass a namespace or prefix to list those starting with it), or next_id with a namespace or prefix. Example: {"mode":"next_id","kind":"event","namespace":"my_mod"}. Returns a compact summary; the first call indexes the mod, which takes seconds on a large one.',
95
95
  inputSchema: modIndexRequestSchema,
96
96
  outputSchema: strictOperationResultSchema(modIndexDataSchema),
97
97
  annotations: readOnly,
@@ -45,6 +45,30 @@ const analysisDataSchema = z
45
45
  graphHash: sha256Schema,
46
46
  counts: countsSchema,
47
47
  helperExpansion: helperExpansionSummarySchema.optional(),
48
+ /** Mode explain: the technology, its direct neighbours and unlocks (20 names each at most). */
49
+ technology: z
50
+ .object({
51
+ id: z.string(),
52
+ path: z.string(),
53
+ line: z.number().int().min(0),
54
+ name: z.string().optional(),
55
+ startYear: z.string().optional(),
56
+ researchCost: z.string().optional(),
57
+ folders: z.array(z.string()),
58
+ categories: z.array(z.string()),
59
+ prerequisites: z.array(z.string()).max(20),
60
+ leadsTo: z.array(z.string()).max(20),
61
+ exclusiveWith: z.array(z.string()).max(20),
62
+ unlocks: z.array(z.object({ kind: z.string(), targetId: z.string() }).strict()).max(20),
63
+ allPrerequisites: nonNegativeIntegerSchema,
64
+ allDescendants: nonNegativeIntegerSchema,
65
+ unlockCount: nonNegativeIntegerSchema,
66
+ grantedBy: nonNegativeIntegerSchema,
67
+ issues: nonNegativeIntegerSchema,
68
+ truncated: z.boolean(),
69
+ })
70
+ .strict()
71
+ .optional(),
48
72
  })
49
73
  .strict();
50
74
  const renderOutputSchema = strictOperationResultSchema(z
@@ -93,7 +117,7 @@ export const technologyTaskTools = [
93
117
  {
94
118
  name: 'hoi4.tech_inspect',
95
119
  title: 'Inspect technology trees',
96
- description: 'Explain technology and doctrine paths, unlocks, bonuses and dependencies. Find layout or reference problems and compare revisions with mode compare. Example: {"mode":"explain","technologyId":"my_tech"}. Returns counts and the main findings inline; the full report is a linked resource.',
120
+ description: 'Explain technology and doctrine paths, unlocks, bonuses and dependencies. Find layout or reference problems and compare revisions with mode compare. Example: {"mode":"explain","technologyId":"my_tech"}. Returns counts inline, and for explain the prerequisites, what it leads to and its unlocks; the full report is a linked resource.',
97
121
  inputSchema: inspectInputSchema,
98
122
  outputSchema: analysisOutputSchema,
99
123
  annotations: readOnlyTechnologyTool,
@@ -0,0 +1,65 @@
1
+ import { defaultPatterns } from '../core/engine.js';
2
+ import { runEngineCommand } from '../core/engine-client.js';
3
+ import { ServiceError } from '../core/result.js';
4
+ import { closureEngineResponseSchema } from '../schemas/mod-tools.js';
5
+ import { modIndexEngineRequest, SOURCE_ROOT_KINDS } from './mod-index.js';
6
+ const CLOSURE_REQUEST_SCHEMA = 'hoi4-closure-request/1';
7
+ /** A cold index of the game, its DLC and a large mod, plus the semantic scan of the mod's sources. */
8
+ const CLOSURE_TIMEOUT_MS = 180_000;
9
+ /** One plain sentence on the closure, for the validation message. */
10
+ export function closureMessage(closure) {
11
+ const { resolved, unresolved, unknown } = closure.totals;
12
+ return `Closure ${closure.verdict}: ${resolved} resolved, ${unresolved} unresolved, ${unknown} unknown references in ${closure.sources} sources`;
13
+ }
14
+ /**
15
+ * The closure option of `hoi4.script_validate` (ADR 0083): whether the definitions the mod's own
16
+ * sources point at exist. The shared Rust engine indexes the game, its DLC and the mod, counts the
17
+ * mod's references per target kind and decides the verdict; a missing engine is
18
+ * `ENGINE_UNAVAILABLE`, never a TypeScript scan.
19
+ */
20
+ export async function checkClosure(engine, workspaceId, principal, signal) {
21
+ signal?.throwIfAborted();
22
+ await engine.resolver.refreshDescriptors(workspaceId, principal);
23
+ const workspace = engine.resolver.get(workspaceId, principal);
24
+ const answered = await runEngineCommand('closure', {
25
+ ...modIndexEngineRequest(workspace, engine.resolver.config(), SOURCE_ROOT_KINDS),
26
+ schema: CLOSURE_REQUEST_SCHEMA,
27
+ patterns: defaultPatterns(workspace),
28
+ }, closureEngineResponseSchema, { timeoutMs: CLOSURE_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) });
29
+ if (!answered.available)
30
+ throw new ServiceError('ENGINE_UNAVAILABLE', answered.message, { reason: answered.reason });
31
+ if (answered.outcome === 'invalid_request')
32
+ throw new ServiceError(answered.error.code, answered.error.message);
33
+ const response = answered.response;
34
+ const reasons = [];
35
+ if (response.totals.unknown > 0)
36
+ reasons.push(`${response.totals.unknown} references cannot be decided: their target is dynamic, a skipped source may define it, or a variable, flag or event target is read with no visible writer`);
37
+ if (!response.complete)
38
+ reasons.push(`The index skipped ${response.skippedSourceCount} sources that exceed a parsing limit, so a definition may be missing`);
39
+ if (!response.semanticComplete)
40
+ reasons.push('The reference scan skipped a source or reached its ceiling');
41
+ const closure = {
42
+ verdict: response.verdict,
43
+ revision: response.revision,
44
+ complete: response.complete,
45
+ semanticComplete: response.semanticComplete,
46
+ skippedSourceCount: response.skippedSourceCount,
47
+ sources: response.sources,
48
+ totals: response.totals,
49
+ kinds: response.kinds,
50
+ };
51
+ return {
52
+ valid: response.verdict === 'closed' ? true : response.verdict === 'unresolved' ? false : null,
53
+ checksPerformed: ['closure'],
54
+ parametersChecked: false,
55
+ findings: [],
56
+ totalFindings: 0,
57
+ omittedFindings: 0,
58
+ checkedCommands: 0,
59
+ unresolvedCount: 0,
60
+ truncated: false,
61
+ argumentBlocksUnchecked: 0,
62
+ ...(reasons.length === 0 ? {} : { partialReasons: reasons.slice(0, 5) }),
63
+ closure,
64
+ };
65
+ }