hoi4-agent-tools 4.17.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 (63) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  3. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  4. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  5. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  6. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  7. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  8. package/dist/hoi4_agent_tools/map/operations.js +246 -18
  9. package/dist/hoi4_agent_tools/map/territory-operations.js +66 -0
  10. package/dist/hoi4_agent_tools/map/territory-quality.js +33 -5
  11. package/dist/hoi4_agent_tools/map/tool-operations.js +52 -2
  12. package/dist/hoi4_agent_tools/mcp/tools/map.js +29 -0
  13. package/dist/hoi4_agent_tools/mcp/tools/reference.js +1 -1
  14. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  15. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  16. package/dist/hoi4_agent_tools/schemas/map.js +70 -2
  17. package/dist/hoi4_agent_tools/version.js +1 -1
  18. package/docs/map.md +58 -16
  19. package/docs/tools.md +1 -1
  20. package/engine/bin/manifest.json +1 -1
  21. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  22. package/npm-shrinkwrap.json +2 -2
  23. package/package.json +1 -1
  24. package/schemas/configuration.schema.json +1 -1
  25. package/schemas/continuous-focus-palette.schema.json +1 -1
  26. package/schemas/custom-weighted-pool.schema.json +1 -1
  27. package/schemas/decision-inspect-input.schema.json +1 -1
  28. package/schemas/error-log-input.schema.json +1 -1
  29. package/schemas/event-feature-manifest.schema.json +1 -1
  30. package/schemas/focus-plan.schema.json +1 -1
  31. package/schemas/focus-planning-sidecar.schema.json +1 -1
  32. package/schemas/geography-model.schema.json +1 -1
  33. package/schemas/gui-animation-source.schema.json +1 -1
  34. package/schemas/gui-helper.schema.json +1 -1
  35. package/schemas/gui-scenario.schema.json +1 -1
  36. package/schemas/helper-expansion-request.schema.json +1 -1
  37. package/schemas/helper-expansion-summary.schema.json +1 -1
  38. package/schemas/impact-inspect-input.schema.json +1 -1
  39. package/schemas/map-operation.schema.json +1004 -821
  40. package/schemas/mechanic-test-input.schema.json +1 -1
  41. package/schemas/mod-index-input.schema.json +1 -1
  42. package/schemas/operation-result.schema.json +1 -1
  43. package/schemas/package-check-input.schema.json +1 -1
  44. package/schemas/package-manifest.schema.json +1 -1
  45. package/schemas/probability-analysis-result.schema.json +1 -1
  46. package/schemas/probability-compare-input.schema.json +1 -1
  47. package/schemas/probability-evaluate-input.schema.json +1 -1
  48. package/schemas/probability-inspect-input.schema.json +1 -1
  49. package/schemas/probability-render-input.schema.json +1 -1
  50. package/schemas/probability-scenario-set.schema.json +1 -1
  51. package/schemas/probability-sequence-input.schema.json +1 -1
  52. package/schemas/probability-simulate-input.schema.json +1 -1
  53. package/schemas/probability-sweep-input.schema.json +1 -1
  54. package/schemas/reference-context-input.schema.json +1 -1
  55. package/schemas/reference-read-input.schema.json +1 -1
  56. package/schemas/reference-search-input.schema.json +1 -1
  57. package/schemas/reference-sheets.schema.json +1 -1
  58. package/schemas/scenario-suite.schema.json +1 -1
  59. package/schemas/scenario-test-input.schema.json +1 -1
  60. package/schemas/script-validate-input.schema.json +1 -1
  61. package/schemas/shared-scenario.schema.json +1 -1
  62. package/schemas/source-lookup-input.schema.json +1 -1
  63. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.18.0 - 2026-11-14
6
+
7
+ - A focused `hoi4.event_inspect` trace or path that answers its question is now `EVENT_INSPECTED`, not `EVENT_INSPECTED_PARTIAL` (issue 66, ADR 0086). The partial code was set for every trace and path on every workspace, because the focused analysis defers the whole-workspace helper and lifecycle passes, so an agent could not tell a complete 7-node trace from a cut one. A trace cut by a limit, with a node on its boundary or with a skipped source, stays partial and says where (`summary.trace.truncated`, `boundaryNodes`). The rule is: a result is partial only when something the answer needs is missing.
8
+ - A focused `hoi4.event_inspect` trace or path no longer fails its `validation.passed` because of blocking diagnostics in unrelated files (issue 66, ADR 0086). It counts those in the files of the events it covers and names how many sit elsewhere in the workspace in the check message, so a clean `news.1` trace in vanilla is not reported as failing for two unrelated diagnostics. Every other event answer still counts the whole workspace.
9
+ - A partial `hoi4.event_inspect` result now says what is missing (issue 66, ADR 0086). `EVENT_INSPECTED_PARTIAL` carries an inline information diagnostic: `EVENT_TRACE_TRUNCATED` when a trace stopped at its limits (raise `maxDepth` or `maxNodes`), `EVENT_SOURCES_SKIPPED` with the count of skipped files, `EVENT_HELPER_EXPANSION_INCOMPLETE`, or `EVENT_FOCUSED_ANALYSIS_DEFERRED` when a large workspace defers the workspace-wide helper projections and state links, so that `roots` and `state_flow` answers may miss callers or links that exist only inside scripted effects. Before, a partial result gave no reason.
10
+ - Keep the `hoi4.mod_index` overview inline (issue 66). On vanilla, Kaiserreich, Old World Blues, ZIN and Chaos Redux the overview took 14 to 22 KB, mostly 200 namespaces listed alphabetically. It now lists the 50 busiest namespaces (the most events first, printed in alphabetical order) and the 25 busiest folders, in about 6 KB, and says how many namespaces it left out. Pass `namespace` or `prefix` with `mode: "overview"` to list the namespaces that start with it (up to 100).
11
+ - Add natural lands to `hoi4.map_inspect` (`lands: true`, thresholds in `landOptions`). Redrawing country borders along natural lines needs the land cut into the pieces its ground suggests, which a map lane did by hand in scratch scripts. The inspection now cuts the land provinces along major rivers (`rivers.bmp` width index 6 and up on at least 40% of a border), crests (the mean height along a border at least 3.5 above the higher province) and changes of terrain class (forest, hills and mountain, marsh, desert, open). It cuts open country into drainage basins (coasts and lakes are sinks, small basins merge over their lowest pass, and `maxBasinProvinces` splits big ones at branch points of the drainage tree), and merges lands below `minProvinces` (6) across their weakest line. Impassable borders are hard lines: an `impassable` adjacency, the edge of an `impassable = yes` state, or (for callers with a barrier plane) a 255 wall. Their two sides are never in the same land and no merge crosses them. `data.lands` gives the count per kind (`basin`, `range`, `forest`, `marsh`, `desert`, `plains`) and the first 50 lands; `map-natural-lands.<revision>.json` holds every land with its provinces, terrain shares, coast and the river, crest, terrain, impassable and divide lengths of its lines to each neighbour. `assign_territory` accepts the lands as `landIds` in `forced`, `blocked`, `cores`, `claims` and `unowned`, and `{ land }` as a seed, cut with the operation's `landOptions`. The ranges of a geography model, moving uplands to the side they drain to, and closed basins (rings) are not covered yet.
12
+ - Measure border quality in one region. `hoi4.map_inspect` takes `qualityScope` with `quality`, and `assign_territory` and `repartition_states` take `borderQualityScope`. Each has `owners`, `stateIds` and a pixel `box`: owners and states add provinces, and the box cuts. A border pixel pair, and the chance baseline, count when either side is inside, so a country is measured against its neighbours. Before, the measurement always covered the whole map, so a redrawn region could not be compared before and after; the ZIN map lane asked for this. The result gives `scopePixels`, and the territory note says `inside the scope`. A scope that selects nothing is `MAP_BORDER_QUALITY_UNAVAILABLE` with the reason `MAP_BORDER_QUALITY_SCOPE_EMPTY`, a blocker in `enforce`. Requests without a scope measure as before.
13
+ - A map write no longer leaves a state id without a state (issue 182). The game needs every id from 1 to the highest and crashes at setup on a missing one; `merge_states` left the merged-away ids empty and `assign_territory` the ids of the states it dissolved (21 holes in one mod). Now the highest states move into the holes the write made, in the same write, with their script references, building positions and `STATE_<id>` localisation (the removed state's key is taken over), and the result lists the moves in `MAP_STATE_IDS_COMPACTED`. A state id the request names is never moved, and a named id that would leave holes below it is refused with `MAP_STATE_ID_GAP`. Holes the mod already had are reported as a `MAP_STATE_ID_GAP` warning with the ids and the `renumber_map_entity` fix; the write still runs, so they can be closed. On Linux the game crashes on such holes during history setup (SIGSEGV), so this is a crash fix.
14
+ - Move building positions off a state a write removes (issue 182). `merge_states` and the states `assign_territory` dissolves left `map/buildings.txt` lines, such as floating harbours, naming the deleted state id. Each such line now names the state that holds its province (its last field, else the province under its map coordinates), reported in `MAP_BUILDING_POSITIONS_REASSIGNED`; a line no state holds is reported as `MAP_BUILDING_POSITION_STATE_MISSING`.
15
+ - A tool reply cut to the 32 KiB inline budget keeps the first changed and proposed files and reports the totals (`changedFilesTotal`, `changedFilesShown`, `proposedFilesTotal`, `proposedFilesShown`, `filesScannedTotal` in `MCP_RESPONSE_TRUNCATED`), instead of empty lists (issue 185). A map write that changed several hundred files answered `changedFiles: []`, which reads as a write that changed nothing.
16
+
5
17
  ## 4.17.0 - 2026-11-14
6
18
 
7
19
  - `hoi4.map_inspect` names its matches inline: `data.matches` lists the first 20 query matches (kind, id, key and name, best first) and `data.coordinateMatches` what each requested coordinate falls in (province, states, regions). It only counted them, so `{"query":"Brandenburg","lookupOnly":true}` answered `queryMatchCount: 2` without saying the state is 64; the full lists stay in the linked artifact.
@@ -194,7 +194,31 @@ function essentialDiagnostics(diagnostics) {
194
194
  }
195
195
  return kept;
196
196
  }
197
- function boundedResult(result, actualBytes) {
197
+ /**
198
+ * The first paths of a list that fit in `budget` bytes. A truncated reply keeps them, with the
199
+ * total, so a write that changed files never reads as one that changed nothing.
200
+ */
201
+ function leadingPaths(paths, budget) {
202
+ const kept = [];
203
+ let bytes = 0;
204
+ for (const path of paths) {
205
+ bytes += Buffer.byteLength(JSON.stringify(path), 'utf8') + 1;
206
+ if (bytes > budget)
207
+ break;
208
+ kept.push(path);
209
+ }
210
+ return kept;
211
+ }
212
+ function boundedResult(result, actualBytes, totals) {
213
+ const changedFiles = leadingPaths(result.changedFiles, 4_096);
214
+ const proposedFiles = leadingPaths(result.proposedFiles, 2_048);
215
+ const fileCounts = {
216
+ changedFilesTotal: totals.changedFiles,
217
+ changedFilesShown: changedFiles.length,
218
+ proposedFilesTotal: totals.proposedFiles,
219
+ proposedFilesShown: proposedFiles.length,
220
+ filesScannedTotal: totals.filesScanned,
221
+ };
198
222
  const hasLinkedEvidence = result.artifacts.length > 0;
199
223
  const truncationDiagnostic = {
200
224
  code: 'MCP_RESPONSE_TRUNCATED',
@@ -203,7 +227,7 @@ function boundedResult(result, actualBytes) {
203
227
  message: hasLinkedEvidence
204
228
  ? 'Tool output exceeded the wire budget; inspect the linked evidence for complete details'
205
229
  : 'Tool output exceeded the wire budget; nonessential inline details were omitted',
206
- details: { actualBytes, maxBytes: MAX_TOOL_RESULT_BYTES },
230
+ details: { actualBytes, maxBytes: MAX_TOOL_RESULT_BYTES, ...fileCounts },
207
231
  };
208
232
  const compactData = result.data !== null && typeof result.data === 'object' && !Array.isArray(result.data)
209
233
  ? result.data
@@ -213,8 +237,8 @@ function boundedResult(result, actualBytes) {
213
237
  code: result.code.slice(0, 256),
214
238
  workspaceId: result.workspaceId.slice(0, 64),
215
239
  filesScanned: [],
216
- proposedFiles: [],
217
- changedFiles: [],
240
+ proposedFiles,
241
+ changedFiles,
218
242
  diagnostics: [truncationDiagnostic, ...essentialDiagnostics(result.diagnostics)],
219
243
  artifacts: result.artifacts
220
244
  .slice(0, 1)
@@ -523,14 +547,21 @@ export function toolResult(result, options = {}) {
523
547
  });
524
548
  const completeResult = preserveDeferredFilesDiagnostic(result);
525
549
  const compact = compactDescriptions(completeResult);
550
+ const totals = {
551
+ changedFiles: completeResult.changedFiles.length,
552
+ proposedFiles: completeResult.proposedFiles.length,
553
+ filesScanned: completeResult.filesScanned.length,
554
+ };
526
555
  const estimatedBytes = jsonBytesWithin(compact, MAX_TOOL_RESULT_BYTES)
527
556
  ? Buffer.byteLength(canonicalJson(compact), 'utf8')
528
557
  : MAX_TOOL_RESULT_BYTES + 1;
529
- const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES ? boundedResult(compact, estimatedBytes) : compact;
558
+ const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES
559
+ ? boundedResult(compact, estimatedBytes, totals)
560
+ : compact;
530
561
  let output = buildToolResult(selected, images.length, options.compact);
531
562
  const wireBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
532
563
  if (wireBytes > MAX_TOOL_RESULT_BYTES) {
533
- output = buildToolResult(boundedResult(compact, wireBytes), images.length, options.compact);
564
+ output = buildToolResult(boundedResult(compact, wireBytes, totals), images.length, options.compact);
534
565
  }
535
566
  const finalBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
536
567
  if (finalBytes > MAX_TOOL_RESULT_BYTES) {
@@ -49,33 +49,125 @@ export function eventGraphCounts(graph, artifacts) {
49
49
  artifacts,
50
50
  };
51
51
  }
52
- export function eventGraphValidation(graph) {
52
+ /**
53
+ * `answerPaths` names the source files the answer stands on, for a focused trace or path. Blocking
54
+ * diagnostics in other files of the workspace do not make that answer fail; they are counted apart
55
+ * and stay in the linked evidence. Without it, every blocking diagnostic of the workspace counts.
56
+ */
57
+ export function eventGraphValidation(graph, answerPaths) {
53
58
  const counts = eventGraphCounts(graph, 0);
59
+ const blockingHere = answerPaths === undefined
60
+ ? counts.blockingDiagnostics
61
+ : eventDiagnostics(graph).filter(({ severity, location }) => (severity === 'error' || severity === 'blocker') &&
62
+ location !== undefined &&
63
+ answerPaths.has(location.path)).length;
64
+ const blockingElsewhere = counts.blockingDiagnostics - blockingHere;
54
65
  const analysisBoundaryPassed = graph.complete || (graph.analysisMode === 'focused' && graph.skippedSourceCount === 0);
55
- const passed = analysisBoundaryPassed && counts.blockingDiagnostics === 0;
66
+ const passed = analysisBoundaryPassed && blockingHere === 0;
56
67
  return {
57
68
  passed,
58
69
  checks: [
59
70
  {
60
71
  id: 'event-analysis',
61
72
  passed,
62
- message: counts.blockingDiagnostics > 0
63
- ? `${counts.blockingDiagnostics} blocking event-chain diagnostics; full evidence is linked`
64
- : graph.complete
65
- ? 'The event-chain analysis is complete and has no blocking diagnostics'
66
- : graph.analysisMode === 'focused' && graph.skippedSourceCount === 0
67
- ? 'Whole-workspace helper projections and lifecycle passes were deferred; the requested event analysis retains direct source evidence'
68
- : graph.analysisMode === 'focused'
69
- ? `${graph.skippedSourceCount} event-analysis source(s) were skipped; linked evidence records the partial boundary`
70
- : graph.issues.some(({ code }) => code === 'EVENT_HELPER_DEPTH_LIMIT' ||
71
- code === 'EVENT_HELPER_PROJECTION_LIMIT' ||
72
- code === 'EVENT_HELPER_STATE_PROJECTION_LIMIT')
73
- ? 'Helper expansion reached a depth or materialization boundary; helper_expansion mode provides bounded source-linked continuation'
74
- : `${graph.skippedSourceCount} event-analysis source(s) were skipped; full evidence is linked`,
73
+ message: blockingHere > 0
74
+ ? `${blockingHere} blocking event-chain diagnostics${answerPaths === undefined ? '' : ' in the files of this answer'}; full evidence is linked`
75
+ : answerPaths !== undefined && blockingElsewhere > 0
76
+ ? `No blocking diagnostics in the files of this answer; ${blockingElsewhere} elsewhere in the workspace are in the linked evidence`
77
+ : graph.complete
78
+ ? 'The event-chain analysis is complete and has no blocking diagnostics'
79
+ : graph.analysisMode === 'focused' && graph.skippedSourceCount === 0
80
+ ? 'Whole-workspace helper projections and lifecycle passes were deferred; the requested event analysis retains direct source evidence'
81
+ : graph.analysisMode === 'focused'
82
+ ? `${graph.skippedSourceCount} event-analysis source(s) were skipped; linked evidence records the partial boundary`
83
+ : graph.issues.some(({ code }) => code === 'EVENT_HELPER_DEPTH_LIMIT' ||
84
+ code === 'EVENT_HELPER_PROJECTION_LIMIT' ||
85
+ code === 'EVENT_HELPER_STATE_PROJECTION_LIMIT')
86
+ ? 'Helper expansion reached a depth or materialization boundary; helper_expansion mode provides bounded source-linked continuation'
87
+ : `${graph.skippedSourceCount} event-analysis source(s) were skipped; full evidence is linked`,
75
88
  },
76
89
  ],
77
90
  };
78
91
  }
92
+ /**
93
+ * Whether the answer to the question that was asked is complete. A result is partial only when
94
+ * something the answer needs is missing, and the narrower scope of a focused analysis (the
95
+ * whole-workspace passes it defers, named by \`analysisMode\`) is not a gap in an answer that
96
+ * stands on its own. A focused trace is complete when no source was skipped, no limit cut it
97
+ * short and no node sits on its boundary. A focused path is complete when it was found without an
98
+ * assumption.
99
+ */
100
+ function eventAnswerComplete(inspected) {
101
+ if (inspected.helperExpansion !== undefined)
102
+ return inspected.helperExpansion.complete;
103
+ const { graph, summary } = inspected;
104
+ if (graph.complete)
105
+ return true;
106
+ if (graph.analysisMode !== 'focused' || graph.skippedSourceCount !== 0 || summary === undefined)
107
+ return false;
108
+ const trace = summary.trace;
109
+ if (typeof trace === 'object' && trace !== null && !Array.isArray(trace))
110
+ return trace.truncated === false && trace.boundaryNodes === 0;
111
+ return summary.found === true && summary.unresolvedAssumptions === 0;
112
+ }
113
+ /** The source files of a focused trace or path, or undefined for any other answer. */
114
+ function answerPaths(inspected) {
115
+ if (inspected.graph.analysisMode !== 'focused')
116
+ return undefined;
117
+ const report = inspected.report;
118
+ const nodes = report?.trace?.nodes ?? report?.explanation?.steps?.map(({ node }) => node);
119
+ if (nodes === undefined)
120
+ return undefined;
121
+ return new Set(nodes.flatMap((node) => {
122
+ const path = node.location?.path ?? node.sourcePath;
123
+ return path === undefined ? [] : [path];
124
+ }));
125
+ }
126
+ /**
127
+ * What a partial event answer is missing, as inline information, so an agent knows whether to
128
+ * raise a limit, trace from the boundary, or accept that callers reached only through scripted
129
+ * effects may be absent (ADR 0086: a partial result says what is missing).
130
+ */
131
+ export function eventPartialReasons(inspected) {
132
+ const { graph, summary } = inspected;
133
+ const reasons = [];
134
+ if (inspected.helperExpansion?.complete === false)
135
+ reasons.push({
136
+ code: 'EVENT_HELPER_EXPANSION_INCOMPLETE',
137
+ message: 'Helper expansion stopped at its depth or size limit; continue it with mode helper_expansion from a helper on its boundary',
138
+ });
139
+ if (graph.skippedSourceCount > 0)
140
+ reasons.push({
141
+ code: 'EVENT_SOURCES_SKIPPED',
142
+ message: `${graph.skippedSourceCount} event source file(s) were skipped as over a size limit, so events they define are missing from this answer`,
143
+ details: { skippedSources: graph.skippedSourceCount },
144
+ });
145
+ const trace = summary?.trace;
146
+ const cut = typeof trace === 'object' &&
147
+ trace !== null &&
148
+ !Array.isArray(trace) &&
149
+ (trace.truncated === true ||
150
+ (typeof trace.boundaryNodes === 'number' && trace.boundaryNodes > 0));
151
+ if (cut)
152
+ reasons.push({
153
+ code: 'EVENT_TRACE_TRUNCATED',
154
+ message: 'The trace stopped at its limits and continues beyond its boundary nodes; raise maxDepth or maxNodes, or trace again from a node on the boundary',
155
+ });
156
+ else if (graph.analysisMode === 'focused' &&
157
+ graph.skippedSourceCount === 0 &&
158
+ inspected.helperExpansion === undefined)
159
+ reasons.push({
160
+ code: 'EVENT_FOCUSED_ANALYSIS_DEFERRED',
161
+ message: 'This large workspace defers the workspace-wide helper projections and state links, so callers and state links that exist only inside scripted effects may be missing from this answer',
162
+ });
163
+ return reasons.map(({ code, message, details }) => ({
164
+ category: 'configuration',
165
+ code,
166
+ severity: 'info',
167
+ message,
168
+ ...(details === undefined ? {} : { details }),
169
+ }));
170
+ }
79
171
  /** Transport-independent event inspection and its complete bounded result contract. */
80
172
  export async function inspectEvents(viewer, input) {
81
173
  const inspected = await viewer.inspect(input);
@@ -99,10 +191,9 @@ export async function inspectEvents(viewer, input) {
99
191
  refresh: input.refresh ?? input.mode === 'scan',
100
192
  },
101
193
  });
102
- result.code =
103
- (inspected.helperExpansion?.complete ?? inspected.graph.complete)
104
- ? 'EVENT_INSPECTED'
105
- : 'EVENT_INSPECTED_PARTIAL';
194
+ result.code = eventAnswerComplete(inspected) ? 'EVENT_INSPECTED' : 'EVENT_INSPECTED_PARTIAL';
195
+ if (result.code === 'EVENT_INSPECTED_PARTIAL')
196
+ result.diagnostics.push(...eventPartialReasons(inspected));
106
197
  setInlineFilesScanned(result, inspected.graph.filesScanned);
107
198
  result.artifacts = inspected.artifacts.map(publicArtifactLink);
108
199
  if (inspected.graphSnapshotOmitted === true)
@@ -113,7 +204,7 @@ export async function inspectEvents(viewer, input) {
113
204
  message: 'The workspace graph is too large to retain as a snapshot artifact; the scan report is linked, and comparisons use revisions held by this server',
114
205
  details: { maximumBytes: EVENT_GRAPH_SNAPSHOT_MAX_BYTES },
115
206
  });
116
- result.validation = eventGraphValidation(inspected.graph);
207
+ result.validation = eventGraphValidation(inspected.graph, answerPaths(inspected));
117
208
  if (inspected.helperExpansion !== undefined)
118
209
  result.validation = helperExpansionValidation(inspected.helperExpansion);
119
210
  return result;
@@ -79,12 +79,59 @@ function labelsFor(index, kinds, label) {
79
79
  void index;
80
80
  return labels;
81
81
  }
82
- /**
83
- * Build the border quality input from a scanned map: the province raster, province kinds, the
84
- * province, state, strategic-region and country groupings the workspace defines, and the height,
85
- * river and terrain bitmaps when they are present and the size of the province map.
86
- */
87
- export function borderQualityInputFromIndex(index) {
82
+ export function borderQualityScopeIsEmpty(scope) {
83
+ return (scope === undefined ||
84
+ ((scope.owners ?? []).length === 0 &&
85
+ (scope.stateIds ?? []).length === 0 &&
86
+ scope.box === undefined));
87
+ }
88
+ /** The pixel mask of a scope over the province raster, refused when it selects no pixel. */
89
+ export function borderQualityScopeMask(index, scope) {
90
+ const raster = index.raster;
91
+ if (raster === undefined)
92
+ throw new ServiceError('MAP_BORDER_QUALITY_RASTER_MISSING', 'Border naturalness needs a valid province bitmap and definitions');
93
+ const { width, height, provinceIds } = raster;
94
+ const byProvince = (scope.owners ?? []).length > 0 || (scope.stateIds ?? []).length > 0
95
+ ? (() => {
96
+ let highest = 0;
97
+ for (const definition of index.definitions)
98
+ highest = Math.max(highest, definition.id);
99
+ const selected = new Uint8Array(highest + 1);
100
+ const owners = new Set(scope.owners ?? []);
101
+ const stateIds = new Set(scope.stateIds ?? []);
102
+ for (const state of index.states)
103
+ if (stateIds.has(state.id) || (state.owner !== undefined && owners.has(state.owner)))
104
+ for (const province of state.provinces)
105
+ if (province >= 0 && province < selected.length)
106
+ selected[province] = 1;
107
+ return selected;
108
+ })()
109
+ : undefined;
110
+ const box = scope.box;
111
+ const x0 = box === undefined ? 0 : Math.max(0, box.x);
112
+ const y0 = box === undefined ? 0 : Math.max(0, box.y);
113
+ const x1 = box === undefined ? width : Math.min(width, box.x + box.width);
114
+ const y1 = box === undefined ? height : Math.min(height, box.y + box.height);
115
+ const mask = new Uint8Array(width * height);
116
+ let pixels = 0;
117
+ for (let y = y0; y < y1; y += 1)
118
+ for (let x = x0; x < x1; x += 1) {
119
+ const pixel = y * width + x;
120
+ const id = provinceIds[pixel];
121
+ if (byProvince !== undefined && (id < 0 || byProvince[id] !== 1))
122
+ continue;
123
+ mask[pixel] = 1;
124
+ pixels += 1;
125
+ }
126
+ if (pixels === 0)
127
+ throw new ServiceError('MAP_BORDER_QUALITY_SCOPE_EMPTY', 'The border quality scope selects no pixel of the province map: check its owners, stateIds and box', {
128
+ ...(scope.owners === undefined ? {} : { owners: scope.owners.slice(0, 20) }),
129
+ ...(scope.stateIds === undefined ? {} : { stateIds: scope.stateIds.slice(0, 20) }),
130
+ ...(box === undefined ? {} : { box }),
131
+ });
132
+ return mask;
133
+ }
134
+ export function borderQualityInputFromIndex(index, scope) {
88
135
  const raster = index.raster;
89
136
  if (raster === undefined)
90
137
  throw new ServiceError('MAP_BORDER_QUALITY_RASTER_MISSING', 'Border naturalness needs a valid province bitmap and definitions');
@@ -165,13 +212,14 @@ export function borderQualityInputFromIndex(index) {
165
212
  provinceKinds: kinds,
166
213
  layers,
167
214
  features,
215
+ ...(borderQualityScopeIsEmpty(scope) ? {} : { scope: borderQualityScopeMask(index, scope) }),
168
216
  },
169
217
  skipped,
170
218
  };
171
219
  }
172
220
  /** Measure the borders of a scanned map workspace. */
173
- export async function measureIndexBorderNaturalness(index, options = {}) {
174
- const { input, skipped } = borderQualityInputFromIndex(index);
221
+ export async function measureIndexBorderNaturalness(index, options = {}, scope) {
222
+ const { input, skipped } = borderQualityInputFromIndex(index, scope);
175
223
  const result = await measureBorderNaturalness(input, options);
176
224
  return { ...result, skipped };
177
225
  }
@@ -180,6 +228,7 @@ export function summarizeBorderQuality(report, skipped) {
180
228
  return {
181
229
  inputs: report.inputs,
182
230
  skippedInputs: skipped,
231
+ ...(report.scopePixels === undefined ? {} : { scopePixels: report.scopePixels }),
183
232
  layers: report.layers.map((layer) => ({
184
233
  layer: layer.layer,
185
234
  status: layer.status,
@@ -346,6 +346,8 @@ function validateInput(input) {
346
346
  });
347
347
  if (input.provinceIds.length !== input.width * input.height)
348
348
  throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Border quality province raster does not match its dimensions', { width: input.width, height: input.height, length: input.provinceIds.length });
349
+ if (input.scope !== undefined && input.scope.length !== input.width * input.height)
350
+ throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Border quality scope does not match the raster dimensions', { width: input.width, height: input.height, length: input.scope.length });
349
351
  if (input.layers.length > MAX_LAYERS)
350
352
  throw new ServiceError('MAP_BORDER_QUALITY_INPUT_INVALID', 'Too many border layers', {
351
353
  layers: input.layers.length,
@@ -433,7 +435,10 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
433
435
  id < provinceKinds.length &&
434
436
  (provinceKinds[id] === BORDER_PROVINCE_KIND.sea ||
435
437
  provinceKinds[id] === BORDER_PROVINCE_KIND.lake);
436
- const visitPair = (a, b, key, bits) => {
438
+ const scope = input.scope;
439
+ const visitPair = (a, b, key, bits, pixel, neighbour) => {
440
+ if (scope !== undefined && scope[pixel] !== 1 && scope[neighbour] !== 1)
441
+ return;
437
442
  if (isLand(b)) {
438
443
  landPairs += 1;
439
444
  if ((bits & BARRIER_MASK) !== 0)
@@ -465,24 +470,26 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
465
470
  // A water pixel's land neighbours are counted from the land side below.
466
471
  continue;
467
472
  }
468
- landPixels += 1;
473
+ if (scope === undefined || scope[pixel] === 1)
474
+ landPixels += 1;
469
475
  const east = x === width - 1 ? 0 : x + 1;
470
- visitPair(id, provinceIds[rowStart + east], pixel * 2, current[x] | current[east]);
476
+ visitPair(id, provinceIds[rowStart + east], pixel * 2, current[x] | current[east], pixel, rowStart + east);
471
477
  if (y + 1 < height)
472
- visitPair(id, provinceIds[pixel + width], pixel * 2 + 1, current[x] | next[x]);
478
+ visitPair(id, provinceIds[pixel + width], pixel * 2 + 1, current[x] | next[x], pixel, pixel + width);
473
479
  }
474
480
  // Coast edges to the north and west of land come from water pixels looking at land.
475
481
  for (let x = 0; x < width; x += 1) {
476
482
  const id = provinceIds[rowStart + x];
477
483
  if (!isWater(id))
478
484
  continue;
485
+ const inside = (other) => scope === undefined || scope[rowStart + x] === 1 || scope[other] === 1;
479
486
  const east = x === width - 1 ? 0 : x + 1;
480
487
  const eastId = provinceIds[rowStart + east];
481
- if (isLand(eastId))
488
+ if (isLand(eastId) && inside(rowStart + east))
482
489
  coastEdgesByProvince[eastId] = coastEdgesByProvince[eastId] + 1;
483
490
  if (y + 1 < height) {
484
491
  const southId = provinceIds[rowStart + width + x];
485
- if (isLand(southId))
492
+ if (isLand(southId) && inside(rowStart + width + x))
486
493
  coastEdgesByProvince[southId] = coastEdgesByProvince[southId] + 1;
487
494
  }
488
495
  }
@@ -511,6 +518,7 @@ export function* buildBorderEdgeTableSteps(input, options = {}) {
511
518
  extra: input.features?.extra !== undefined,
512
519
  },
513
520
  options: resolved,
521
+ ...(scope === undefined ? {} : { scopePixels: scope.reduce((sum, value) => sum + value, 0) }),
514
522
  };
515
523
  }
516
524
  /** Drive `buildBorderEdgeTableSteps`, yielding to the event loop about every 12 milliseconds. */
@@ -1093,6 +1101,7 @@ export async function measureBorderNaturalness(input, options = {}) {
1093
1101
  width: table.width,
1094
1102
  height: table.height,
1095
1103
  landPixels: table.landPixels,
1104
+ ...(table.scopePixels === undefined ? {} : { scopePixels: table.scopePixels }),
1096
1105
  inputs: table.inputs,
1097
1106
  parameters: {
1098
1107
  riverRadius: table.options.riverRadius,
@@ -12,3 +12,16 @@ export const MAP_PROVINCE_GEOMETRY_SELECTOR_LIMIT = 32;
12
12
  /** Maximum polygon cell/edge comparisons before rasterization is refused. */
13
13
  export const MAP_POLYGON_WORK_LIMIT = 50_000_000;
14
14
  export const MAP_SELECTED_OFFSET_BYTES = Uint32Array.BYTES_PER_ELEMENT;
15
+ /** Kinds of natural land (`hoi4.map_inspect` with `lands`). */
16
+ export const NATURAL_LAND_KINDS = [
17
+ 'basin',
18
+ 'range',
19
+ 'forest',
20
+ 'marsh',
21
+ 'desert',
22
+ 'plains',
23
+ ];
24
+ /** Terrain classes whose changes are natural-land lines. */
25
+ export const NATURAL_TERRAIN_CLASSES = ['open', 'forest', 'upland', 'marsh', 'desert'];
26
+ /** Natural land ids: `L` and the smallest province id of the land. */
27
+ export const NATURAL_LAND_ID_PATTERN = /^L\d{1,6}$/u;