hoi4-agent-tools 4.8.0 → 4.10.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 (93) hide show
  1. package/CHANGELOG.md +21 -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/graph.js +16 -2
  5. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  6. package/dist/hoi4_agent_tools/event/service.js +66 -11
  7. package/dist/hoi4_agent_tools/event/source-analysis.js +35 -16
  8. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  9. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  10. package/dist/hoi4_agent_tools/map/gameplay/reachability.js +81 -0
  11. package/dist/hoi4_agent_tools/map/geography/resolve.js +6 -2
  12. package/dist/hoi4_agent_tools/map/operations.js +8 -0
  13. package/dist/hoi4_agent_tools/map/partition-tuning.js +2 -1
  14. package/dist/hoi4_agent_tools/map/reference-world.js +17 -3
  15. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +143 -0
  16. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +13 -0
  17. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  18. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  19. package/dist/hoi4_agent_tools/map/world.js +243 -34
  20. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +57 -9
  21. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  22. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  23. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  24. package/dist/hoi4_agent_tools/mcp/tools/event.js +13 -0
  25. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  26. package/dist/hoi4_agent_tools/mcp/tools/reference.js +25 -0
  27. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  28. package/dist/hoi4_agent_tools/probability/operations.js +6 -0
  29. package/dist/hoi4_agent_tools/probability/service.js +23 -0
  30. package/dist/hoi4_agent_tools/reference/error-log.js +35 -1
  31. package/dist/hoi4_agent_tools/reference/operations.js +141 -14
  32. package/dist/hoi4_agent_tools/reference/script-validation.js +113 -2
  33. package/dist/hoi4_agent_tools/schemas/geography.js +5 -0
  34. package/dist/hoi4_agent_tools/schemas/ideas.js +4 -4
  35. package/dist/hoi4_agent_tools/schemas/map.js +61 -4
  36. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  37. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  38. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  39. package/dist/hoi4_agent_tools/version.js +1 -1
  40. package/docs/analysis.md +2 -2
  41. package/docs/events.md +1 -1
  42. package/docs/map.md +31 -17
  43. package/docs/probability.md +1 -1
  44. package/docs/research/probability-adapter-evidence.md +15 -2
  45. package/docs/tools.md +49 -43
  46. package/engine/README.md +9 -0
  47. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  48. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  49. package/engine/bin/linux-x64/hoi4-engine +0 -0
  50. package/engine/bin/manifest.json +8 -8
  51. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  52. package/npm-shrinkwrap.json +2 -2
  53. package/package.json +1 -1
  54. package/schemas/configuration.schema.json +1 -1
  55. package/schemas/continuous-focus-palette.schema.json +1 -1
  56. package/schemas/custom-weighted-pool.schema.json +1 -1
  57. package/schemas/decision-inspect-input.schema.json +1 -1
  58. package/schemas/error-log-input.schema.json +1 -1
  59. package/schemas/event-feature-manifest.schema.json +1 -1
  60. package/schemas/focus-plan.schema.json +1 -1
  61. package/schemas/focus-planning-sidecar.schema.json +1 -1
  62. package/schemas/geography-model.schema.json +4 -1
  63. package/schemas/gui-animation-source.schema.json +1 -1
  64. package/schemas/gui-helper.schema.json +1 -1
  65. package/schemas/gui-scenario.schema.json +1 -1
  66. package/schemas/helper-expansion-request.schema.json +1 -1
  67. package/schemas/helper-expansion-summary.schema.json +1 -1
  68. package/schemas/impact-inspect-input.schema.json +1 -1
  69. package/schemas/map-operation.schema.json +234 -111
  70. package/schemas/mechanic-test-input.schema.json +1 -1
  71. package/schemas/mod-index-input.schema.json +1 -1
  72. package/schemas/operation-result.schema.json +1 -1
  73. package/schemas/package-check-input.schema.json +1 -1
  74. package/schemas/package-manifest.schema.json +1 -1
  75. package/schemas/probability-analysis-result.schema.json +1 -1
  76. package/schemas/probability-compare-input.schema.json +1 -1
  77. package/schemas/probability-evaluate-input.schema.json +1 -1
  78. package/schemas/probability-inspect-input.schema.json +1 -1
  79. package/schemas/probability-render-input.schema.json +1 -1
  80. package/schemas/probability-scenario-set.schema.json +1 -1
  81. package/schemas/probability-sequence-input.schema.json +1 -1
  82. package/schemas/probability-simulate-input.schema.json +1 -1
  83. package/schemas/probability-sweep-input.schema.json +1 -1
  84. package/schemas/reference-context-input.schema.json +1 -1
  85. package/schemas/reference-read-input.schema.json +1 -1
  86. package/schemas/reference-search-input.schema.json +1 -1
  87. package/schemas/reference-sheets.schema.json +1 -1
  88. package/schemas/scenario-suite.schema.json +1 -1
  89. package/schemas/scenario-test-input.schema.json +1 -1
  90. package/schemas/script-validate-input.schema.json +1 -1
  91. package/schemas/shared-scenario.schema.json +1 -1
  92. package/schemas/source-lookup-input.schema.json +1 -1
  93. package/server.json +2 -2
@@ -49,6 +49,7 @@ export function resolvePartitionTuning(tuning, base) {
49
49
  const sea = tuning?.seaArea;
50
50
  for (const [name, value] of Object.entries(sea ?? {}))
51
51
  checkPixels(`seaArea.${name}`, value, minProvincePixels);
52
+ checkPixels('lakeArea', tuning?.lakeArea, minProvincePixels);
52
53
  const coastal = clamp(sea?.coastal ?? base.seaProvincePixels * PARTITION_DEFAULTS.seaCoastal);
53
54
  const open = clamp(sea?.open ?? base.seaProvincePixels * PARTITION_DEFAULTS.seaOpen);
54
55
  if (coastal > open)
@@ -85,7 +86,7 @@ export function resolvePartitionTuning(tuning, base) {
85
86
  return {
86
87
  landArea: { fertile, plains: clamp(Math.sqrt(fertile * hills)), hills, mountain, waste },
87
88
  seaArea: { coastal, open },
88
- lakeArea: clamp(PARTITION_DEFAULTS.lake),
89
+ lakeArea: clamp(tuning?.lakeArea ?? PARTITION_DEFAULTS.lake),
89
90
  states: group(perState, base.provincesPerState, 0.5, 1.6),
90
91
  regions: group(regionSize, base.landProvincesPerRegion, 0.6, 1.5),
91
92
  seaRegions: group(undefined, base.seaProvincesPerRegion, 0.5, 1.6),
@@ -18,12 +18,15 @@ export const REFERENCE_TERRAIN = {
18
18
  };
19
19
  const TERRAIN_ELEVATION = [0.045, 0.055, 0.035, 0.44, 0.045, 0.35, 0.18, 0.025, 0.06];
20
20
  const TERRAIN_MOISTURE = [0.45, 0.8, 0.06, 0.35, 0.25, 0.05, 0.4, 0.96, 0.92];
21
+ /** Internal class code of `impassable_mountain`, after the terrain codes. */
22
+ const IMPASSABLE_CODE = 3 + Object.keys(REFERENCE_TERRAIN).length;
21
23
  const pointSchema = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) }).strict();
22
24
  const polygonSchema = z.array(pointSchema).min(3).max(2048);
23
25
  const semanticSchema = z.enum([
24
26
  'sea',
25
27
  'land',
26
28
  'lake',
29
+ 'impassable_mountain',
27
30
  'plains',
28
31
  'forest',
29
32
  'desert',
@@ -135,7 +138,9 @@ function semanticCode(kind) {
135
138
  ? 2
136
139
  : kind === 'land'
137
140
  ? 3
138
- : REFERENCE_TERRAIN[kind] + 3;
141
+ : kind === 'impassable_mountain'
142
+ ? IMPASSABLE_CODE
143
+ : REFERENCE_TERRAIN[kind] + 3;
139
144
  }
140
145
  function pixelColor(data, pixel) {
141
146
  return { r: data[pixel * 3], g: data[pixel * 3 + 1], b: data[pixel * 3 + 2] };
@@ -473,9 +478,17 @@ export async function extractReferenceWorld(imageBytes, input) {
473
478
  }
474
479
  const kind = new Uint8Array(codes.length);
475
480
  const terrain = new Uint8Array(codes.length);
481
+ let impassable;
476
482
  for (let pixel = 0; pixel < codes.length; pixel += 1) {
477
- kind[pixel] = codes[pixel] < 3 ? codes[pixel] : 1;
478
- terrain[pixel] = codes[pixel] < 3 ? 0 : codes[pixel] - 3;
483
+ const code = codes[pixel];
484
+ kind[pixel] = code < 3 ? code : 1;
485
+ if (code === IMPASSABLE_CODE) {
486
+ terrain[pixel] = REFERENCE_TERRAIN.mountain;
487
+ impassable ??= new Uint8Array(codes.length);
488
+ impassable[pixel] = 1;
489
+ }
490
+ else
491
+ terrain[pixel] = code < 3 ? 0 : code - 3;
479
492
  }
480
493
  const riverPoints = (options.riverAnnotations ?? []).reduce((total, path) => total + path.length, 0);
481
494
  if (riverPoints > 131072)
@@ -514,6 +527,7 @@ export async function extractReferenceWorld(imageBytes, input) {
514
527
  rivers,
515
528
  country: new Uint16Array(kind.length),
516
529
  inferredCountries: [],
530
+ ...(impassable === undefined ? {} : { impassable }),
517
531
  diagnostics,
518
532
  };
519
533
  if (!exact)
@@ -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)
@@ -140,6 +140,43 @@ function mapArtifactSourceEvidence(files) {
140
140
  const complete = Object.fromEntries(files.map(({ displayPath, sha256 }) => [displayPath, sha256]));
141
141
  return { complete, bounded: boundedSourceHashEvidence(complete) };
142
142
  }
143
+ /**
144
+ * A selection whose ids the map defines none of is not-found before any work, never an ok result
145
+ * with empty records and a whole-map artifact (#59). A selection with some known ids goes on and
146
+ * reports the unknown ones (unknownProvinceIds, and a null state or region record).
147
+ */
148
+ function assertKnownMapEntities(snapshot, input) {
149
+ const index = snapshot.index;
150
+ const unknown = {
151
+ stateIds: [...new Set(input.stateIds)].filter((id) => !index.statesById.has(id)),
152
+ provinceIds: [...new Set(input.provinceIds)].filter((id) => !index.definitionsById.has(id)),
153
+ regionIds: [...new Set(input.regionIds)].filter((id) => !index.regionsById.has(id)),
154
+ };
155
+ const requested = new Set(input.stateIds).size + new Set(input.provinceIds).size + new Set(input.regionIds).size;
156
+ const unknownCount = unknown.stateIds.length + unknown.provinceIds.length + unknown.regionIds.length;
157
+ if (requested === 0 || unknownCount < requested)
158
+ return;
159
+ const highest = (ids) => {
160
+ let value = 0;
161
+ for (const id of ids)
162
+ if (id > value)
163
+ value = id;
164
+ return value;
165
+ };
166
+ const parts = [
167
+ ['state', unknown.stateIds, highest(index.statesById.keys())],
168
+ ['province', unknown.provinceIds, highest(index.definitionsById.keys())],
169
+ ['strategic region', unknown.regionIds, highest(index.regionsById.keys())],
170
+ ];
171
+ const missing = parts.filter(([, ids]) => ids.length > 0);
172
+ throw new ServiceError('MAP_ENTITY_ID_NOT_FOUND', `The map defines no ${missing
173
+ .map(([kind, ids, highest]) => `${kind} ${ids.slice(0, 16).join(', ')}${ids.length > 16 ? ' and more' : ''} (the highest ${kind} id is ${highest})`)
174
+ .join('; no ')}`, {
175
+ stateIds: unknown.stateIds.slice(0, 64),
176
+ provinceIds: unknown.provinceIds.slice(0, 64),
177
+ regionIds: unknown.regionIds.slice(0, 64),
178
+ });
179
+ }
143
180
  function selectedMapEntities(snapshot, provinceIds, stateIds, regionIds) {
144
181
  const provinces = [...new Set(provinceIds)]
145
182
  .sort((a, b) => a - b)
@@ -661,6 +698,7 @@ export async function inspectMap(engine, nudger, input, context) {
661
698
  if (input.allocationRequests.length > 0)
662
699
  throw new ServiceError('MAP_LOOKUP_ALLOCATION_UNSUPPORTED', 'Use full map inspection for identifier allocation previews');
663
700
  const snapshot = await nudger.scan(context.workspaceId, context.principal, context.signal);
701
+ assertKnownMapEntities(snapshot, input);
664
702
  const catalog = input.query === undefined ? undefined : buildMapCatalog(snapshot.index);
665
703
  const queryMatches = catalog === undefined ? [] : searchMapCatalog(catalog, input.query, input.queryLimit);
666
704
  const coordinateMatches = input.coordinates.map((coordinate) => lookupMapCoordinate(snapshot.index, coordinate));
@@ -720,6 +758,9 @@ export async function inspectMap(engine, nudger, input, context) {
720
758
  await context.progress(3, 3, 'Map lookup complete');
721
759
  return result;
722
760
  }
761
+ // Check the ids on the cached scan before the full validation.
762
+ if (input.stateIds.length + input.provinceIds.length + input.regionIds.length > 0)
763
+ assertKnownMapEntities(await nudger.scan(context.workspaceId, context.principal, context.signal), input);
723
764
  const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality);
724
765
  const sharedRevision = snapshot.revision;
725
766
  let borderQuality;
@@ -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) {