hoi4-agent-tools 4.14.0 → 4.16.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 (60) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/hoi4_agent_tools/core/managed-outputs.js +102 -26
  3. package/dist/hoi4_agent_tools/map/operations.js +58 -1
  4. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +2 -2
  5. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +25 -3
  6. package/dist/hoi4_agent_tools/map/tool-operations.js +5 -0
  7. package/dist/hoi4_agent_tools/map/world-outputs.js +14 -1
  8. package/dist/hoi4_agent_tools/map/world.js +127 -11
  9. package/dist/hoi4_agent_tools/reference/source-lookup.js +226 -74
  10. package/dist/hoi4_agent_tools/schemas/map.js +10 -1
  11. package/dist/hoi4_agent_tools/schemas/mod-tools.js +33 -0
  12. package/dist/hoi4_agent_tools/version.js +1 -1
  13. package/docs/map.md +3 -1
  14. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  15. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  16. package/engine/bin/linux-x64/hoi4-engine +0 -0
  17. package/engine/bin/manifest.json +8 -8
  18. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  19. package/npm-shrinkwrap.json +2 -2
  20. package/package.json +1 -1
  21. package/schemas/configuration.schema.json +1 -1
  22. package/schemas/continuous-focus-palette.schema.json +1 -1
  23. package/schemas/custom-weighted-pool.schema.json +1 -1
  24. package/schemas/decision-inspect-input.schema.json +1 -1
  25. package/schemas/error-log-input.schema.json +1 -1
  26. package/schemas/event-feature-manifest.schema.json +1 -1
  27. package/schemas/focus-plan.schema.json +1 -1
  28. package/schemas/focus-planning-sidecar.schema.json +1 -1
  29. package/schemas/geography-model.schema.json +1 -1
  30. package/schemas/gui-animation-source.schema.json +1 -1
  31. package/schemas/gui-helper.schema.json +1 -1
  32. package/schemas/gui-scenario.schema.json +1 -1
  33. package/schemas/helper-expansion-request.schema.json +1 -1
  34. package/schemas/helper-expansion-summary.schema.json +1 -1
  35. package/schemas/impact-inspect-input.schema.json +1 -1
  36. package/schemas/map-operation.schema.json +28 -2
  37. package/schemas/mechanic-test-input.schema.json +1 -1
  38. package/schemas/mod-index-input.schema.json +1 -1
  39. package/schemas/operation-result.schema.json +1 -1
  40. package/schemas/package-check-input.schema.json +1 -1
  41. package/schemas/package-manifest.schema.json +1 -1
  42. package/schemas/probability-analysis-result.schema.json +1 -1
  43. package/schemas/probability-compare-input.schema.json +1 -1
  44. package/schemas/probability-evaluate-input.schema.json +1 -1
  45. package/schemas/probability-inspect-input.schema.json +1 -1
  46. package/schemas/probability-render-input.schema.json +1 -1
  47. package/schemas/probability-scenario-set.schema.json +1 -1
  48. package/schemas/probability-sequence-input.schema.json +1 -1
  49. package/schemas/probability-simulate-input.schema.json +1 -1
  50. package/schemas/probability-sweep-input.schema.json +1 -1
  51. package/schemas/reference-context-input.schema.json +1 -1
  52. package/schemas/reference-read-input.schema.json +1 -1
  53. package/schemas/reference-search-input.schema.json +1 -1
  54. package/schemas/reference-sheets.schema.json +1 -1
  55. package/schemas/scenario-suite.schema.json +1 -1
  56. package/schemas/scenario-test-input.schema.json +1 -1
  57. package/schemas/script-validate-input.schema.json +1 -1
  58. package/schemas/shared-scenario.schema.json +1 -1
  59. package/schemas/source-lookup-input.schema.json +1 -1
  60. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.16.0 - 2026-11-09
6
+
7
+ - Keep the world output record (`.hoi4-agent-world.json`) current with the tool's own map edits. `update_states`, `move_state_provinces` and every other map operation rewrote recorded state, strategic-region and map files without recording their new hashes, so the next `create_world` refused them as hand edits (`MANAGED_OUTPUT_EDITED`). This happened in a later call and also later in the `create_world` call itself, because the record was planned at the end of `create_world`. ZIN had 191 such files on 9 November: 184 state files and 7 strategic regions. Every map rewrite now records the new hash of each recorded file it writes, and drops each one it deletes, in the same transaction (`MAP_WORLD_OUTPUTS_REFRESHED`). A recorded file edited by hand before the call keeps its old hash and is named in a warning, so it stays protected. The new `record_world_outputs` operation takes the current bytes of every recorded file as the world's own. It is for mods whose record is already stale: it writes only the record, drops files that are gone, and reports the counts (`MAP_WORLD_OUTPUTS_RECORDED`).
8
+
9
+ ## 4.15.0 - 2026-11-09
10
+
11
+ - Add `create_world.permanentSnow.paintedHeight`. Painted mountains, volcanoes and impassable land put permanent snow above a snow line of their own (232 at the equator to 140 at the poles), which `permanentSnow` did not reach: a ZIN write on 9 November with `iceCapLatitude` 0.97 and `peakHeight` 230 still had 15.37% of its land permanent (804,575 pixels, 20 times the base game's share), of which only about 69,000 were drawn snow. `paintedHeight` (a heightmap value) keeps that line at or above its height, and 256 removes it. `MAP_PERMANENT_SNOW_SHARE` and `MAP_PERMANENT_SNOW_ESTIMATE` gain `bySource`, the permanent pixels above range snow lines, above painted snow lines and on drawn snow, and their warning names the setting of the largest source. Requests without `paintedHeight` write the same files as before.
12
+ - `create_world.synthesisCheck` estimates the permanent-snow share of the write. `MAP_PERMANENT_SNOW_SHARE` came only from the terrain writer, so ZIN could try `permanentSnow` thresholds only through 28-minute writes. The check now applies the writer's rule (snow lines, then drawn snow on ice caps and at `peakHeight` and up) to the half-resolution relief it already builds, and reports `MAP_PERMANENT_SNOW_ESTIMATE` with the same details plus `estimate: true`, also under `synthesisCheck.permanentSnow` per operation. On a 1,024 by 512 test world the estimate was within 1% of the written share. The note is a warning above four times the base game's share, as at the write; a warning does not block the check.
13
+ - Answer `hoi4.source_lookup` from the shared Rust engine when it is asked for no references (`includeReferences: false`), as `hoi4.mod_index` already is (ADR 0082, maintainer decision M-8, first step of issue 107). The engine finds the definitions, their first and last line, the scan revision (the same value the TypeScript scan computes, so `expectedRevision` from any tool still matches) and the near names of a miss; the server reads only the chosen files, only from inside a configured root, and refuses one whose SHA-256 differs from the scan's with `SOURCE_REVISION_STALE`. A missing or failing engine answers `ENGINE_UNAVAILABLE` with no TypeScript fallback for these requests. A lookup that includes references (the default) and a lookup by file and line still answer from the TypeScript scan until the reference extraction moves too, and no input schema changed.
14
+
5
15
  ## 4.14.0 - 2026-11-09
6
16
 
7
17
  - `create_world` no longer turns drawn snow into permanent snow. Every reference pixel drawn as snow became the permanent-snow terrain (`terrain.bmp` index 19), and the game drew it as bright blue ice: ZIN's Cold Lands, seen on 9 November, had about a hundred times the base game's share. Drawn snow is now ordinary land (plains, as in play) with seasonal snow, as the base game's northern lands are. Permanent snow stays on ice caps (drawn snow in the tenth of rows nearest each pole, index 19, where the base game keeps it), drawn snow on high ground (height 150 and up, index 16) and above the snow lines of ranges and painted mountains (index 16). A strategic region drawn mostly as snow takes the weather of at least latitude 0.7 (on the map's 0 to 1 scale), so its winters bring snow wherever it lies. The new `create_world.permanentSnow` moves the thresholds (`{ iceCapLatitude, peakHeight }`, defaults 0.8 and 150) or, with `"snowlines"`, keeps permanent snow only above the snow lines: on ZIN's picture the defaults still leave 9.46% of the land permanent, because its inhabited Cold Lands fill the top rows. `MAP_PERMANENT_SNOW_SHARE` reports the permanent-snow share of the land against the base game's 0.76% (33,254 of 4,353,170 land pixels in 1.19.4.2), counting the `rim` and `wall` seam ranges apart, with the thresholds used, and is a warning above four times that share. Snow lines in a reference world now use the base game's snowy mountain entry (16) instead of 19; worlds without a reference picture are unchanged.
@@ -24,32 +24,13 @@ export function planManagedOutputs(input) {
24
24
  .filter((f) => f.rootKind === 'mod')
25
25
  .map((f) => [f.relativePath.replaceAll('\\', '/').toLowerCase(), f]));
26
26
  const manifest = sources.get(input.manifestPath.toLowerCase());
27
- const previous = manifest === undefined
28
- ? []
29
- : (() => {
30
- if (manifest.bytes.length > 2_000_000)
31
- throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory exceeds its byte limit');
32
- try {
33
- return manifestSchema.parse(JSON.parse(manifest.bytes.toString('utf8'))).files;
34
- }
35
- catch {
36
- throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory is invalid');
37
- }
38
- })();
27
+ const previous = manifest === undefined ? [] : parseManifest(manifest.bytes);
39
28
  const outputs = input.proposed.filter((f) => f.content !== null && input.permitsPath(f.relativePath));
40
29
  const next = new Set(outputs.map((f) => f.relativePath.toLowerCase()));
41
30
  const released = new Set();
42
31
  const ignored = new Set();
43
- const seen = new Set();
44
32
  for (const file of previous) {
45
33
  const key = file.relativePath.toLowerCase();
46
- // A path that could leave the workspace, or a duplicate, makes the whole inventory untrustworthy.
47
- if (file.relativePath.includes('\\') ||
48
- file.relativePath.split('/').some((s) => !s || s === '.' || s === '..') ||
49
- /^[a-z]:/iu.test(file.relativePath) ||
50
- seen.has(key))
51
- throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory contains an unsupported or duplicate path');
52
- seen.add(key);
53
34
  // A safe path this inventory does not manage is left alone: not compared, not deleted.
54
35
  if (!input.permitsPath(file.relativePath)) {
55
36
  ignored.add(file.relativePath);
@@ -80,12 +61,7 @@ export function planManagedOutputs(input) {
80
61
  ...deletions,
81
62
  {
82
63
  relativePath: input.manifestPath,
83
- content: Buffer.from(canonicalJson({
84
- version: 1,
85
- files: outputs
86
- .map((f) => ({ relativePath: f.relativePath, sha256: sha256Bytes(f.content) }))
87
- .sort((a, b) => compareCodeUnits(a.relativePath, b.relativePath)),
88
- }) + '\n'),
64
+ content: manifestBytes(outputs.map((f) => ({ relativePath: f.relativePath, sha256: sha256Bytes(f.content) }))),
89
65
  operationIds: [input.operationId],
90
66
  mediaType: 'application/json',
91
67
  },
@@ -98,3 +74,103 @@ export function planManagedOutputs(input) {
98
74
  ignored: sorted(ignored),
99
75
  };
100
76
  }
77
+ /**
78
+ * Parse a recorded inventory. An oversized or malformed one, a path that could leave the
79
+ * workspace, or a duplicate makes the whole inventory untrustworthy.
80
+ */
81
+ function parseManifest(bytes) {
82
+ if (bytes.length > 2_000_000)
83
+ throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory exceeds its byte limit');
84
+ let files;
85
+ try {
86
+ files = manifestSchema.parse(JSON.parse(Buffer.from(bytes).toString('utf8'))).files;
87
+ }
88
+ catch {
89
+ throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory is invalid');
90
+ }
91
+ const seen = new Set();
92
+ for (const file of files) {
93
+ const key = file.relativePath.toLowerCase();
94
+ if (file.relativePath.includes('\\') ||
95
+ file.relativePath.split('/').some((s) => !s || s === '.' || s === '..') ||
96
+ /^[a-z]:/iu.test(file.relativePath) ||
97
+ seen.has(key))
98
+ throw new ServiceError('MANAGED_OUTPUT_MANIFEST_INVALID', 'Generated-output inventory contains an unsupported or duplicate path');
99
+ seen.add(key);
100
+ }
101
+ return files;
102
+ }
103
+ function manifestBytes(files) {
104
+ return Buffer.from(canonicalJson({
105
+ version: 1,
106
+ files: [...files].sort((a, b) => compareCodeUnits(a.relativePath, b.relativePath)),
107
+ }) + '\n');
108
+ }
109
+ /**
110
+ * Bring the recorded hashes of an inventory up to date with the bytes a request leaves behind, so
111
+ * the tool's own later edits (update_states, move_state_provinces and the rest) never read as hand
112
+ * edits. Returns undefined when the workspace has no inventory or this request deletes it.
113
+ */
114
+ export function refreshManagedOutputs(input) {
115
+ const key = (relativePath) => relativePath.replaceAll('\\', '/').toLowerCase();
116
+ const proposed = new Map(input.proposed.map((change) => [key(change.relativePath), change]));
117
+ const sources = new Map(input.sources.filter((f) => f.rootKind === 'mod').map((f) => [key(f.relativePath), f]));
118
+ const manifestKey = key(input.manifestPath);
119
+ const written = proposed.get(manifestKey);
120
+ if (written?.content === null)
121
+ return undefined;
122
+ const bytes = written?.content ?? sources.get(manifestKey)?.bytes;
123
+ if (bytes === undefined)
124
+ return undefined;
125
+ const writtenHere = written !== undefined;
126
+ const refreshed = [];
127
+ const dropped = [];
128
+ const keptEdited = [];
129
+ const unchanged = [];
130
+ const operationIds = new Set();
131
+ const next = [];
132
+ for (const entry of parseManifest(bytes)) {
133
+ const change = proposed.get(key(entry.relativePath));
134
+ const source = sources.get(key(entry.relativePath));
135
+ let current;
136
+ if (change !== undefined) {
137
+ const trusted = writtenHere ||
138
+ input.adoptAll === true ||
139
+ source === undefined ||
140
+ sha256Bytes(source.bytes) === entry.sha256;
141
+ if (!trusted) {
142
+ keptEdited.push(entry.relativePath);
143
+ next.push(entry);
144
+ continue;
145
+ }
146
+ current = change.content;
147
+ for (const id of change.operationIds)
148
+ operationIds.add(id);
149
+ }
150
+ else if (input.adoptAll === true)
151
+ current = source === undefined ? null : source.bytes;
152
+ else {
153
+ next.push(entry);
154
+ continue;
155
+ }
156
+ if (current === null) {
157
+ dropped.push(entry.relativePath);
158
+ continue;
159
+ }
160
+ const sha256 = sha256Bytes(current);
161
+ if (sha256 === entry.sha256)
162
+ unchanged.push(entry.relativePath);
163
+ else
164
+ refreshed.push(entry.relativePath);
165
+ next.push({ relativePath: entry.relativePath, sha256 });
166
+ }
167
+ const changed = refreshed.length > 0 || dropped.length > 0;
168
+ return {
169
+ content: changed ? manifestBytes(next) : undefined,
170
+ refreshed: refreshed.sort(compareCodeUnits),
171
+ dropped: dropped.sort(compareCodeUnits),
172
+ keptEdited: keptEdited.sort(compareCodeUnits),
173
+ unchanged: unchanged.sort(compareCodeUnits),
174
+ operationIds: [...operationIds].sort(compareCodeUnits),
175
+ };
176
+ }
@@ -12,7 +12,7 @@ import { resolveEdge } from './world-edge.js';
12
12
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
13
13
  import { planMapPositions, planSupplyRebuild } from './derived.js';
14
14
  import { buildWorldContext, countryTagCatalog, WORLD_COUNTRY_TAG_FILE, } from './world-context.js';
15
- import { planWorldOutputs } from './world-outputs.js';
15
+ import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
16
16
  import { resolvePartitionMode } from './partition.js';
17
17
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
18
18
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -3750,6 +3750,49 @@ function applyRegenerateMapPositions(base, changes, operation) {
3750
3750
  for (const file of planMapPositions(index, operation))
3751
3751
  addChange(changes, file.relativePath, file.content, operation.id, 'text/plain');
3752
3752
  }
3753
+ function worldOutputsRefreshedDiagnostic(refresh) {
3754
+ return {
3755
+ code: 'MAP_WORLD_OUTPUTS_REFRESHED',
3756
+ severity: refresh.keptEdited.length > 0 ? 'warning' : 'info',
3757
+ category: 'map',
3758
+ message: `The world output inventory records the new bytes of ${refresh.refreshed.length} output(s) this request wrote` +
3759
+ (refresh.dropped.length > 0 ? ` and drops ${refresh.dropped.length} it deleted` : '') +
3760
+ (refresh.keptEdited.length > 0
3761
+ ? `; ${refresh.keptEdited.length} output(s) were edited before this request and keep their recorded hash, so the next create_world still refuses them (record_world_outputs adopts them)`
3762
+ : ''),
3763
+ details: {
3764
+ refreshed: refresh.refreshed.length,
3765
+ dropped: refresh.dropped.length,
3766
+ keptEdited: refresh.keptEdited.slice(0, 200),
3767
+ keptEditedCount: refresh.keptEdited.length,
3768
+ },
3769
+ };
3770
+ }
3771
+ /**
3772
+ * `record_world_outputs`: adopt the current bytes of every output the world inventory records, so
3773
+ * the next create_world takes them as the world's own. Recorded files that are gone are dropped.
3774
+ */
3775
+ function applyRecordWorldOutputs(base, changes, operation) {
3776
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), true);
3777
+ if (refresh === undefined)
3778
+ throw new ServiceError('MAP_WORLD_OUTPUTS_MISSING', `The workspace has no world output inventory (${WORLD_OUTPUT_MANIFEST}) to record; only a mod written by create_world has one`);
3779
+ if (refresh.content !== undefined)
3780
+ addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, operation.id, 'application/json');
3781
+ return {
3782
+ code: 'MAP_WORLD_OUTPUTS_RECORDED',
3783
+ severity: 'info',
3784
+ category: 'map',
3785
+ operationId: operation.id,
3786
+ message: `The world output inventory now records the current bytes of its outputs: ${refresh.refreshed.length} refreshed, ${refresh.unchanged.length} unchanged, ${refresh.dropped.length} dropped because the file is gone`,
3787
+ details: {
3788
+ refreshed: refresh.refreshed.length,
3789
+ unchanged: refresh.unchanged.length,
3790
+ dropped: refresh.dropped.length,
3791
+ refreshedPaths: refresh.refreshed.slice(0, 200),
3792
+ droppedPaths: refresh.dropped.slice(0, 200),
3793
+ },
3794
+ };
3795
+ }
3753
3796
  function applyRebuildSupply(base, changes, operation) {
3754
3797
  const index = currentIndex(base, changes);
3755
3798
  for (const file of planSupplyRebuild(index, operation))
@@ -3922,6 +3965,8 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
3922
3965
  applyRegenerateMapPositions(base, changes, operation);
3923
3966
  else if (operation.kind === 'rebuild_supply')
3924
3967
  applyRebuildSupply(base, changes, operation);
3968
+ else if (operation.kind === 'record_world_outputs')
3969
+ diagnostics.push(applyRecordWorldOutputs(base, changes, operation));
3925
3970
  else
3926
3971
  handleSimpleOperation(base, changes, operation);
3927
3972
  diagnostics.push(...(diagnosticsByPlan.get(changes) ?? []));
@@ -3959,6 +4004,18 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
3959
4004
  });
3960
4005
  }
3961
4006
  }
4007
+ // The tool's own later edits of world outputs must never read as hand edits at the next
4008
+ // create_world, in this request or a later one.
4009
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes));
4010
+ if (refresh?.content !== undefined) {
4011
+ const [first, ...rest] = refresh.operationIds;
4012
+ addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, first, 'application/json');
4013
+ for (const id of rest)
4014
+ changes.get(normalizeRelative(WORLD_OUTPUT_MANIFEST)).operationIds.add(id);
4015
+ diagnostics.push(worldOutputsRefreshedDiagnostic(refresh));
4016
+ }
4017
+ else if (refresh !== undefined && refresh.keptEdited.length > 0)
4018
+ diagnostics.push(worldOutputsRefreshedDiagnostic(refresh));
3962
4019
  const finalized = proposedChanges(changes);
3963
4020
  yield* cancellationCheckpoint(signal);
3964
4021
  const finalIndex = indexWithProposedChanges(base, finalized, replacedRootsByPlan.get(changes) ?? []);
@@ -125,8 +125,8 @@ export function applyPaintedRelief(target, input) {
125
125
  if (weight > target.footprint[cell])
126
126
  target.footprint[cell] = weight;
127
127
  if (Math.max(m, v, i) > 0.25) {
128
- const snow = paintedSnowHeight(y, mh);
129
- if (snow < target.snowLine[cell])
128
+ const snow = Math.max(paintedSnowHeight(y, mh), input.snowFloor ?? 0);
129
+ if (snow < 255 && snow < target.snowLine[cell])
130
130
  target.snowLine[cell] = snow;
131
131
  }
132
132
  }
@@ -93,6 +93,10 @@ function barrierField(width, height, kind, heights, riverBitmap, macro, signal)
93
93
  * mouth throws as in `synthesizeTerrain`, with every failing river in its details.
94
94
  */
95
95
  export function checkTerrainRivers(input) {
96
+ return checkTerrainRiversWithRelief(input).notes;
97
+ }
98
+ /** `checkTerrainRivers`, also returning the half-resolution relief for estimates of the write. */
99
+ export function checkTerrainRiversWithRelief(input) {
96
100
  const { geography, width, height, seed, kind } = input;
97
101
  const relief = { ...DEFAULT_RELIEF, ...input.relief };
98
102
  let landPixels = 0;
@@ -108,6 +112,7 @@ export function checkTerrainRivers(input) {
108
112
  relief,
109
113
  signal: input.signal,
110
114
  });
115
+ const rangeSnowLine = macro.snowLine.slice();
111
116
  // The same painted relief as the full synthesis, so the rivers checked are the rivers written.
112
117
  if (input.painted !== undefined)
113
118
  applyPaintedRelief(macro, input.painted);
@@ -140,7 +145,16 @@ export function checkTerrainRivers(input) {
140
145
  for (const note of checkRangesAndFeatures(geography, macro.ranges, { width: macro.width, height: macro.height, kind: macro.kind, heights: quantised }, (peak) => peakHeight(peak, macro.scale), (peak) => peakHeight(peak, macro.scale)))
141
146
  if (note.code === 'MAP_PASS_NOT_LOWER')
142
147
  notes.push(note);
143
- return notes;
148
+ return {
149
+ notes,
150
+ relief: {
151
+ width: macro.width,
152
+ height: macro.height,
153
+ heights: hydrology.heights,
154
+ snowLine: macro.snowLine,
155
+ rangeSnowLine,
156
+ },
157
+ };
144
158
  }
145
159
  /** Build relief, hydrology, normals and fields for a geography model on a map of the given size. */
146
160
  export function synthesizeTerrain(input) {
@@ -163,6 +177,7 @@ export function synthesizeTerrain(input) {
163
177
  relief,
164
178
  signal: input.signal,
165
179
  });
180
+ const rangeSnowLine = macro.snowLine.slice();
166
181
  if (input.painted !== undefined) {
167
182
  const summary = applyPaintedRelief(macro, input.painted);
168
183
  notes.push({
@@ -224,6 +239,7 @@ export function synthesizeTerrain(input) {
224
239
  const heights = new Uint8Array(total);
225
240
  const elevation = new Float32Array(total);
226
241
  const snow = new Uint8Array(total);
242
+ const paintedSnow = new Uint8Array(total);
227
243
  for (let y = 0; y < height; y += 1) {
228
244
  if (y % 64 === 0)
229
245
  input.signal?.throwIfAborted();
@@ -236,9 +252,14 @@ export function synthesizeTerrain(input) {
236
252
  const quantised = Math.round(value);
237
253
  heights[index] = quantised;
238
254
  elevation[index] = Math.min(1, Math.max(0, (quantised - LAND_FLOOR) / 110));
239
- const line = macro.snowLine[(y >> 1) * macro.width + (x >> 1)];
240
- if (line < 255 && quantised >= line)
255
+ const cell = (y >> 1) * macro.width + (x >> 1);
256
+ const line = macro.snowLine[cell];
257
+ if (line < 255 && quantised >= line) {
241
258
  snow[index] = 1;
259
+ const range = rangeSnowLine[cell];
260
+ if (range === 255 || quantised < range)
261
+ paintedSnow[index] = 1;
262
+ }
242
263
  }
243
264
  else {
244
265
  const water = lakeHeight(landDistance[index]);
@@ -360,6 +381,7 @@ export function synthesizeTerrain(input) {
360
381
  riverOrder: raster.order,
361
382
  elevation,
362
383
  snow,
384
+ paintedSnow,
363
385
  fields,
364
386
  rivers: entries,
365
387
  riverPaths: paths,
@@ -574,6 +574,10 @@ async function previewSynthesisCheck(nudger, input, context) {
574
574
  : []);
575
575
  // Drawn rivers are authoritative: crossings of relief they cut through are warnings (ADR 0071).
576
576
  const carved = checked.diagnostics.flatMap(({ code, details }) => code === 'MAP_RIVER_CARVED_CROSSING' && details !== undefined ? [details] : []);
577
+ // The write's permanent-snow share, estimated on the check's relief, per operation.
578
+ const permanentSnow = checked.diagnostics.flatMap(({ code, operationId, details }) => code === 'MAP_PERMANENT_SNOW_ESTIMATE' && details !== undefined
579
+ ? [{ ...(operationId === undefined ? {} : { operationId }), ...details }]
580
+ : []);
577
581
  const compactSemantic = compactMapSemanticDiff(EMPTY_SEMANTIC_DIFF);
578
582
  const result = emptyServiceResult(context.workspaceId, {
579
583
  execution: 'preview',
@@ -590,6 +594,7 @@ async function previewSynthesisCheck(nudger, input, context) {
590
594
  geography: checked.geography.slice(0, 16).map(geographySummary),
591
595
  synthesisCheck: {
592
596
  passed: valid,
597
+ ...(permanentSnow.length === 0 ? {} : { permanentSnow: permanentSnow.slice(0, 16) }),
593
598
  unreachableRivers: rivers.length,
594
599
  rivers: rivers.slice(0, 200),
595
600
  carvedCrossings: carved.length,
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { planManagedOutputs } from '../core/managed-outputs.js';
2
+ import { planManagedOutputs, refreshManagedOutputs, } from '../core/managed-outputs.js';
3
3
  export const WORLD_OUTPUT_MANIFEST = '.hoi4-agent-world.json';
4
4
  /** Country outputs of a generated world: tags, country files, histories, units, flags, bookmark. */
5
5
  export function isWorldCountryOutput(relativePath) {
@@ -19,6 +19,19 @@ export function reconcileWorldOutputs(sources, proposed, operationId, mapRoot, s
19
19
  return planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots)
20
20
  .changes;
21
21
  }
22
+ /**
23
+ * The world inventory brought up to date with the bytes a request leaves behind: every recorded
24
+ * output the request writes gets its new hash, or with `adoptAll` every recorded output its
25
+ * current bytes (`record_world_outputs`). Undefined when the workspace has no world inventory.
26
+ */
27
+ export function refreshWorldOutputs(sources, proposed, adoptAll = false) {
28
+ return refreshManagedOutputs({
29
+ manifestPath: WORLD_OUTPUT_MANIFEST,
30
+ sources,
31
+ proposed,
32
+ ...(adoptAll ? { adoptAll: true } : {}),
33
+ });
34
+ }
22
35
  export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots, options = {}) {
23
36
  const mapFiles = new Set([
24
37
  'provinces.bmp',
@@ -27,7 +27,7 @@ import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from
27
27
  import { DEFAULT_PAINTED_RELIEF } from './relief/painted-relief.js';
28
28
  import { rowStrips, scanAreaStrip } from './geography/index.js';
29
29
  import { overlayGeographyLakes, rasterizeGeographyKind } from './relief/land.js';
30
- import { checkTerrainRivers, synthesizeTerrain, } from './relief/terrain-synthesis.js';
30
+ import { checkTerrainRiversWithRelief, synthesizeTerrain, } from './relief/terrain-synthesis.js';
31
31
  import { assignUnreachedRealmLand, checkRealmPoints, realmPointsError, resolveRealmRules, } from './world-realms.js';
32
32
  // ---------------------------------------------------------------------------------------------
33
33
  // Deterministic randomness and noise
@@ -271,6 +271,19 @@ function permanentSnowRule(input) {
271
271
  return {
272
272
  iceCapLatitude: input?.iceCapLatitude ?? ICE_CAP_LATITUDE,
273
273
  peakHeight: input?.peakHeight ?? PEAK_SNOW_HEIGHT,
274
+ ...(input?.paintedHeight === undefined ? {} : { paintedHeight: input.paintedHeight }),
275
+ };
276
+ }
277
+ function emptySnowCount() {
278
+ return {
279
+ permanent: 0,
280
+ rangeSnowLines: 0,
281
+ paintedSnowLines: 0,
282
+ drawnSnow: 0,
283
+ painted: 0,
284
+ seasonal: 0,
285
+ land: 0,
286
+ edge: 0,
274
287
  };
275
288
  }
276
289
  /** Strategic regions drawn mostly as snow take the weather of at least this latitude. */
@@ -287,39 +300,115 @@ const PERMANENT_SNOW_WARNING_FACTOR = 4;
287
300
  function pixelLatitude(y, height) {
288
301
  return Math.abs((y + 0.5) / height - 0.5) * 2;
289
302
  }
290
- function permanentSnowNote(count, input) {
303
+ function permanentSnowNote(count, input, estimate = false) {
291
304
  const rule = permanentSnowRule(input);
292
305
  const share = count.permanent / Math.max(1, count.land);
293
306
  const ratio = share / VANILLA_PERMANENT_SNOW.share;
294
307
  const high = ratio > PERMANENT_SNOW_WARNING_FACTOR;
295
308
  const percent = (value) => `${(value * 100).toFixed(2)}%`;
309
+ // The hint names what put most of the snow there, since each source has its own setting.
310
+ const largest = [
311
+ ['paintedSnowLines', count.paintedSnowLines],
312
+ ['rangeSnowLines', count.rangeSnowLines],
313
+ ['drawnSnow', count.drawnSnow],
314
+ ].reduce((best, next) => (next[1] > best[1] ? next : best));
315
+ const hint = largest[0] === 'paintedSnowLines'
316
+ ? `${largest[1]} of them lie above the snow line of painted mountains, volcanoes and impassable land: raise permanentSnow.paintedHeight (256 puts none)`
317
+ : largest[0] === 'rangeSnowLines'
318
+ ? `${largest[1]} of them lie above the snow lines of the model's ranges: raise or remove their snowline`
319
+ : 'raise permanentSnow.iceCapLatitude or peakHeight, or set permanentSnow to "snowlines"';
296
320
  return {
297
- code: 'MAP_PERMANENT_SNOW_SHARE',
321
+ code: estimate ? 'MAP_PERMANENT_SNOW_ESTIMATE' : 'MAP_PERMANENT_SNOW_SHARE',
298
322
  severity: high ? 'warning' : 'info',
299
- message: `Permanent snow covers ${percent(share)} of the land (${count.permanent} pixels), ` +
323
+ message: (estimate
324
+ ? `Estimated from the half-resolution relief of this check, permanent snow would cover ${percent(share)} of the land (${count.permanent} pixels), `
325
+ : `Permanent snow covers ${percent(share)} of the land (${count.permanent} pixels), `) +
300
326
  `${ratio.toFixed(1)} times the base game's ${percent(VANILLA_PERMANENT_SNOW.share)}` +
301
327
  (count.painted > 0
302
328
  ? `; ${count.seasonal} of ${count.painted} drawn snow pixels are ordinary land with seasonal snow`
303
329
  : '') +
304
- (high
305
- ? '. The game draws permanent snow as bright ice: raise permanentSnow.iceCapLatitude or peakHeight, or set permanentSnow to "snowlines"'
306
- : ''),
330
+ (high ? `. The game draws permanent snow as bright ice; ${hint}` : ''),
307
331
  details: {
308
332
  permanentPixels: count.permanent,
309
333
  landPixels: count.land,
310
334
  share: Number(share.toFixed(5)),
311
335
  vanilla: VANILLA_PERMANENT_SNOW,
312
336
  ratio: Number(ratio.toFixed(2)),
337
+ // What put each permanent pixel there, in this order of precedence.
338
+ bySource: {
339
+ rangeSnowLines: count.rangeSnowLines,
340
+ paintedSnowLines: count.paintedSnowLines,
341
+ drawnSnow: count.drawnSnow,
342
+ },
313
343
  drawnSnowPixels: count.painted,
314
344
  seasonalSnowPixels: count.seasonal,
315
345
  // The snow range or wall at a `rim` or `wall` seam, counted apart from the land.
316
346
  edgePixels: count.edge,
317
347
  permanentSnow: input === 'snowlines'
318
348
  ? 'snowlines'
319
- : { iceCapLatitude: rule.iceCapLatitude, peakHeight: rule.peakHeight },
349
+ : {
350
+ iceCapLatitude: rule.iceCapLatitude,
351
+ peakHeight: rule.peakHeight,
352
+ ...(rule.paintedHeight === undefined ? {} : { paintedHeight: rule.paintedHeight }),
353
+ },
354
+ // The write adds full-resolution detail to these heights, so its share differs a little.
355
+ ...(estimate ? { estimate: true, grid: 'half-resolution' } : {}),
320
356
  },
321
357
  };
322
358
  }
359
+ /**
360
+ * The permanent-snow count of the write, estimated on the half-resolution relief of the river
361
+ * check: the same rule as the terrain writer (snow lines, then drawn snow on ice caps and peaks),
362
+ * with each pixel taking the height and snow lines of its half-resolution cell.
363
+ */
364
+ function estimatePermanentSnow(input) {
365
+ const { width, height, kind, relief } = input;
366
+ const rule = permanentSnowRule(input.permanentSnow);
367
+ const count = emptySnowCount();
368
+ for (let y = 0; y < height; y += 1) {
369
+ if (y % 64 === 0)
370
+ input.signal?.throwIfAborted();
371
+ const iceCap = pixelLatitude(y, height) >= rule.iceCapLatitude;
372
+ const row = Math.min(relief.height - 1, y >> 1) * relief.width;
373
+ for (let x = 0; x < width; x += 1) {
374
+ const pixel = y * width + x;
375
+ if (kind[pixel] !== LAND)
376
+ continue;
377
+ if (input.edgePixel(pixel)) {
378
+ count.edge += 1;
379
+ continue;
380
+ }
381
+ count.land += 1;
382
+ const cell = row + Math.min(relief.width - 1, x >> 1);
383
+ const value = Math.round(relief.heights[cell]);
384
+ const line = relief.snowLine[cell];
385
+ const range = relief.rangeSnowLine[cell];
386
+ const drawn = input.drawnSnow(pixel);
387
+ const source = range < 255 && value >= range
388
+ ? 'range'
389
+ : line < 255 && value >= line
390
+ ? 'painted'
391
+ : drawn && (iceCap || value >= rule.peakHeight)
392
+ ? 'drawn'
393
+ : undefined;
394
+ if (source !== undefined) {
395
+ count.permanent += 1;
396
+ if (source === 'range')
397
+ count.rangeSnowLines += 1;
398
+ else if (source === 'painted')
399
+ count.paintedSnowLines += 1;
400
+ else
401
+ count.drawnSnow += 1;
402
+ }
403
+ if (drawn) {
404
+ count.painted += 1;
405
+ if (source === undefined)
406
+ count.seasonal += 1;
407
+ }
408
+ }
409
+ }
410
+ return count;
411
+ }
323
412
  /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
324
413
  export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
325
414
  function terrainSummaryNote(terrain, geography) {
@@ -660,6 +749,8 @@ export function generateWorld(spec, context, options = {}) {
660
749
  // impassable regions of the geography model (ZR-28).
661
750
  const impassableMask = impassableLand(reference?.impassable, geography, width, height);
662
751
  // Impassable land is the highest ground even without relief.painted: then only it is raised.
752
+ // permanentSnow.paintedHeight keeps the painted snow line at or above its height.
753
+ const snowFloor = permanentSnowRule(spec.permanentSnow).paintedHeight;
663
754
  const painted = geography === undefined
664
755
  ? undefined
665
756
  : spec.paintedRelief !== undefined && reference !== undefined
@@ -668,6 +759,7 @@ export function generateWorld(spec, context, options = {}) {
668
759
  impassable: impassableMask,
669
760
  settings: spec.paintedRelief,
670
761
  seed: spec.seed,
762
+ snowFloor,
671
763
  }
672
764
  : impassableMask !== undefined
673
765
  ? {
@@ -675,6 +767,7 @@ export function generateWorld(spec, context, options = {}) {
675
767
  impassable: impassableMask,
676
768
  settings: DEFAULT_PAINTED_RELIEF,
677
769
  seed: spec.seed,
770
+ snowFloor,
678
771
  }
679
772
  : undefined;
680
773
  if (edge.mode !== 'none') {
@@ -752,7 +845,7 @@ export function generateWorld(spec, context, options = {}) {
752
845
  .map(({ tag, capital }) => ({ tag, x: capital.x, y: capital.y })),
753
846
  }));
754
847
  try {
755
- const checked = checkTerrainRivers({
848
+ const { notes: checked, relief } = checkTerrainRiversWithRelief({
756
849
  geography,
757
850
  width,
758
851
  height,
@@ -773,6 +866,22 @@ export function generateWorld(spec, context, options = {}) {
773
866
  message: note.message,
774
867
  ...(note.details === undefined ? {} : { details: note.details }),
775
868
  });
869
+ // The share the write's MAP_PERMANENT_SNOW_SHARE will report, so the permanentSnow
870
+ // thresholds can be tuned without a write.
871
+ const snow = estimatePermanentSnow({
872
+ width,
873
+ height,
874
+ kind: surface.kind,
875
+ drawnSnow: (pixel) => reference?.terrain[pixel] === REFERENCE_SNOW,
876
+ edgePixel: (pixel) => wallMask !== undefined
877
+ ? wallMask[pixel] === 1
878
+ : rimStrength(edge, width, pixel % width) > 0.35,
879
+ relief,
880
+ permanentSnow: spec.permanentSnow,
881
+ signal: options.signal,
882
+ });
883
+ if (snow.permanent > 0 || snow.painted > 0)
884
+ notes.push(permanentSnowNote(snow, spec.permanentSnow, true));
776
885
  }
777
886
  catch (error) {
778
887
  if (!(error instanceof ServiceError))
@@ -1905,7 +2014,7 @@ export function generateWorld(spec, context, options = {}) {
1905
2014
  heights[pixel] >= snowRule.peakHeight
1906
2015
  ? 16
1907
2016
  : 19;
1908
- const snowCount = { permanent: 0, painted: 0, seasonal: 0, land: 0, edge: 0 };
2017
+ const snowCount = emptySnowCount();
1909
2018
  // A wall takes the look of the land it meets, row by row on each side.
1910
2019
  const wallLook = wallMask === undefined
1911
2020
  ? undefined
@@ -1958,8 +2067,15 @@ export function generateWorld(spec, context, options = {}) {
1958
2067
  snowCount.edge += 1;
1959
2068
  else {
1960
2069
  snowCount.land += 1;
1961
- if (snowy)
2070
+ if (snowy) {
1962
2071
  snowCount.permanent += 1;
2072
+ if (synthesized?.snow[pixel] !== 1)
2073
+ snowCount.drawnSnow += 1;
2074
+ else if (synthesized.paintedSnow[pixel] === 1)
2075
+ snowCount.paintedSnowLines += 1;
2076
+ else
2077
+ snowCount.rangeSnowLines += 1;
2078
+ }
1963
2079
  if (paintedSnow(pixel)) {
1964
2080
  snowCount.painted += 1;
1965
2081
  if (!snowy)