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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.10.0 - 2026-11-06
6
+
7
+ - Size lake provinces: `create_world.partitionTuning.lakeArea` (default 6,000 pixels, capped at the largest province the map allows) sets the area of a lake province, so a drawn lake no larger than it stays one province.
8
+ - Raise the relief toward a reference picture's painted mountains, hills and volcanoes (`create_world.relief.painted`, ADR 0079). The classes are blurred over `falloffPx` (default 24) before the rivers are routed, so slopes stay natural and the model's rivers flow around the drawn ranges. Painted mountains get permanent snow by latitude. `MAP_RELIEF_SYNTHESIZED` now reports the base game's relief beside the world's.
9
+ - Make land impassable (ADR 0079): paint it with the palette kind `impassable_mountain` or mark a model region `impassable: true`.
10
+ - Its provinces become impassable `enclave` states linked to the nearest passable state, and it rises to the highest ground.
11
+ - Cities and capitals on it are refused (`MAP_FEATURE_IN_IMPASSABLE`).
12
+ - `MAP_REALM_CUT_OFF` and `MAP_REALM_ENCLOSED` warn when impassable land or borders cut a realm apart or box it in.
13
+ - `EVENT_TARGET_READ_BEFORE_SAVE` no longer reports correct script (#60). A `has_event_target` or `has_global_event_target` check tests whether a target exists. Without a visible producer it is now the design warning `EVENT_GATE_WITHOUT_WRITER`, not a probable defect. A read that such a check guards in the same event, focus or decision is not reported. Names built in a `meta_effect` or with `$parameter$`s are no longer cut at their first bracket. Names far into a long block are read in full instead of being cut at the display limit. The event graph now reads shared and joint focuses and the `completion_reward_joint_originator` and `completion_reward_joint_member` rewards, where vanilla saves `SSB_leader`. On Chaos Redux with vanilla 1.19.4.1 the findings drop from 33 to 2. Both remaining ones are real: vanilla reads `demanded_prov_target` in `events/Generic.txt` and saves it nowhere.
14
+ - Check the hand-kept game data against the installed build (#70). The probability adapters were re-checked on 1.19.4.1: five of the six documentation files they rest on are byte-identical to 1.19.2.0, and the two AI strategy sections they use say the same, so the target moves to `Operation Postern 1.19.4.1 (f584)` and the adapter version to `hoi4-1.19.4.1.v1`. A result on another build now carries the warning `PROBABILITY_GAME_BUILD_UNVERIFIED` instead of only recording `workspace_observed` in its metadata. The nightly game-update watcher lists the adapters or the native-effects list under "Checked against another build" on every run while their pin differs from the installed build, not only on the night the build changes.
15
+
16
+ ## 4.9.0 - 2026-11-05
17
+
18
+ - Results no longer suggest the wrong conclusion (#65, the parts #82 left open). `error_log` fails a new `error-log-age` check when the mod's script, localisation or interface files changed after the log was written, and names how many, the newest time and an example file, because such a log cannot vouch for the current source. `script_validate` names what made a result partial (`partialReasons`), for example the blocks of a scripted helper file whose scope depends on the caller, by line, so `SCRIPT_CHECK_PARTIAL` with `unresolvedCount: 0` no longer comes without a reason. Every example in a tool description or an argument error is now checked against the tool's own schema in a test. That found and fixed the `gui_rewrite` patch example, which lacked the required `description`, and the `gui_rewrite` and `mechanic_test` examples, which held `...` placeholders. An unknown field in the arguments now lists the fields that object accepts. The tools list budget in the discovery test moves from 80 to 84 KiB for the longer, runnable examples.
19
+ - Apply every selector, and answer unknown ids with an explicit not-found instead of `ok` with nothing (#59). `event_inspect` checks its selector in every mode: an event, namespace, node or source that nothing matches is `EVENT_NOT_FOUND`, `EVENT_NAMESPACE_NOT_FOUND`, `EVENT_NODE_NOT_FOUND` or `EVENT_SOURCE_NOT_FOUND` with close names. `roots` keeps only the selected events, the entry points that start them and the cycles through them. It now counts an event a scripted effect fires as called, so such events are no longer listed as callerless. `state_flow` narrows its issues and summary to the `stateSubject`, puts the subject's producers and readers inline, and answers `EVENT_STATE_NOT_FOUND` for a flag, variable or target nothing uses. A `decision_inspect` inventory with an `id` lists only that category's decisions, or that one decision, with their ids inline, and any other id is `DECISION_NOT_FOUND`. `impact_inspect` answers `IMPACT_SYMBOL_NOT_FOUND` for a symbol nothing defines or uses, instead of dropping it. `map_inspect` answers `MAP_ENTITY_ID_NOT_FOUND` when none of the requested state, province or region ids exists, before any validation or render. A selection with some known ids still reports the unknown ones.
20
+ - `script_validate` checks identifier arguments against the definitions of the mod, its dependencies and the game (#68): ideas (`add_ideas`, `remove_ideas`, `has_idea`, `add_timed_idea`, `modify_timed_idea`), decisions (`activate_decision`, `activate_targeted_decision`), focuses (`has_completed_focus`, `complete_national_focus`, `uncomplete_national_focus`), technologies (`has_tech`) and events (`country_event`, `news_event`, `state_event`, `unit_leader_event`, `operative_leader_event`). An id that nothing defines is `SCRIPT_ARGUMENT_UNKNOWN_ID` with up to three close names, and `parametersChecked` is true. It is a warning, because the game loads the file and the command does nothing, as five dangling ids in vanilla 1.19.4.1 show. Ids match without case, as the game finds them (vanilla fires `NSB_news.2` for `nsb_news.2`). Computed values are not read, and a partial index reports `unresolved` instead. The index now holds shared and joint focuses and the ideas that advisors' `idea_token`s make. The known-good sweeps of vanilla, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues raise no new error.
21
+ - Add `hoi4.asset_inspect` on the shared Rust engine (`hoi4-engine assets`; coverage tools part 5, issue #71). One tool reads sprites, sounds and flags. A sprite comes back with every definition in load order, its texture with layer, container, pixel format, size and mipmaps, and its frames. A sound, sound effect, category or music track comes back with its audio file (relative to its `.asset` file's folder) and the sounds or sound effects it plays. A flag comes back with its three files (82x52, `medium/` 41x26 and `small/` 10x7). Each answer lists the files that mention the asset. `audit: true` checks every sprite, sound or flag the mod defines, and the flag audit also reports country tags of the mod with no flag at all (dynamic tags excepted). Missing and unreadable textures, BC7 textures (`ASSET_TEXTURE_FORMAT_RISKY`, after an in-game crash on 1.19.4.1), missing audio files, unknown sounds and wrong flag sizes are warnings. Uneven frames, sprites without a texture that the game fills itself, empty texture files that hide a picture and flags one pixel off are information. Texture headers are now read by content, so PNG files named `.dds` read as PNG, as the game reads them. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every warning was checked by hand. Vanilla's are real: six sound files saved under other names, three flags of the wrong size and a placeholder flag with one size.
22
+ - Add `hoi4.unit_inspect` on the shared Rust engine (`hoi4-engine units`; coverage tools part 4, issue #71). One tool reads orders of battle (`history/units` files), sub-units, equipment and equipment modules, and equipment variants. One id comes back with every definition in load order, its parts (templates, fleets, module slots), each name it uses with whether something defines it, its name and description in every language, and the files that mention it. `audit: true` checks every one the mod makes. An order of battle's templates must fit the division designer's grid, read from the `MAX_DIVISION_` defines so a mod that changes the grid is judged by its own, and no two sub-units may share a slot. Its divisions, fleets and air wings must name templates (from any order of battle or the `division_template` effect), sub-units, equipment, variants, provinces, states or carriers that load. Equipment must name known archetypes, parents, upgrades, resources, module categories and default modules, and a variant known equipment, modules and upgrades. Equipment that a `duplicate_archetypes` copy derives counts as defined. The audit of orders of battle also reports `oob`, `set_oob` and `load_oob` names that no `history/units` file has. A missing name is information. An unknown id is `UNIT_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every finding was checked by hand. Vanilla still has real ones: two regiments in one slot in `CZE_1936`, `oob` names of countries without a file, and division name groups lost to unbalanced quotes in `FIN_names_divisions.txt`. An audit takes 5 to 40 s with a cold file cache.
23
+ - Add `hoi4.system_inspect` on the shared Rust engine (`hoi4-engine system`; coverage tools part 3, issue #71). One tool reads the newer systems: on_actions hooks, military-industrial organizations and their policies, balances of power, special projects with their prototype rewards, specializations and project tags, operations with their phases and tokens, and raids with their categories. One id comes back with every definition in load order, its fields as written, its parts (traits, ranges, sides, options, phases), each reference it makes with whether something defines the target, its name and description in every language, and the files that mention it. `audit: true` checks every definition of that system the mod makes. The checks follow the documentation in each game folder, corrected where the shipped files differ: an organization's include, removed and overridden traits and trait parents, duplicate trait tokens, pictures, and modifiers; a balance of power's sides and ranges; a project's specialization, tags, parents, rewards and the equipment, modules and sub-units it enables; an operation's phases, tokens and equipment; a raid's category, sub-units and target buildings; the events an on_actions hook fires; and the hooks a mod drops by replacing an on_actions file. A hook that neither the documentation, the game's own files nor its executable uses, and a missing name, are information. A balance of power's `decision_category` creates its category, so it is not checked. An unknown id is `SYSTEM_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues no warning remains and every finding was checked by hand. An audit takes 2 to 12 s with a warm file cache.
24
+ - Close the world seam for fleets as well as armies: `create_world.edge.mode: "wall"` (ADR 0061, amended). A `rim` blocks land provinces across the seam but leaves the sea there sailable, so ships crossed from the far west to the far east. A wall fills `rimPx` (default 48) at the east and west edges with land over the full height (`MAP_EDGE_WALL_FILLED`), with a ragged inner edge, the rim's heights and seam rows, and the look of the land it meets row by row (or caller `wallTerrain` segments), and puts its provinces in impassable `enclave` states linked by `force_link_ownership_to` to the nearest passable state, as the base game's impassable states are. Cities and workspace capitals in the wall are refused, and validation reports water on the seam columns of a wall world as `MAP_EDGE_WALL_OPEN`. `polarPx: 0` lets land run off the top and bottom edges.
25
+
5
26
  ## 4.8.0 - 2026-11-05
6
27
 
7
28
  - Ship `hoi4-engine` inside the npm package and the container image (ADR 0074, amended): the release builds it for Windows x64, macOS arm64 and Linux x64 and arm64 (glibc 2.35 or later) and bundles every platform under `engine/bin/` with a SHA-256 manifest, so `layoutMode: "engine"`, `placement` and the engine checks work after a plain install. The bundled binary runs only when its SHA-256 matches `engine/bin/manifest.json`; otherwise the call reports `binary_checksum_mismatch` and nothing runs. `HOI4_ENGINE` still wins, and other platforms report the engine unavailable as before. Each image holds the binary for its own architecture. The package grows by about 4 MB.
@@ -594,6 +594,20 @@ export class SymbolIndex {
594
594
  for (const assignment of assignments(block)) {
595
595
  const key = assignment.key.value;
596
596
  if (assignment.value.type !== 'block') {
597
+ // An advisor's `idea_token` is the idea that `add_ideas` and `has_idea` name.
598
+ if (key === 'idea_token' &&
599
+ sourcePath.startsWith('common/characters/') &&
600
+ ancestors.at(-1) === 'advisor') {
601
+ this.addSymbol({
602
+ kind: 'idea',
603
+ id: assignment.value.value,
604
+ path: file.displayPath,
605
+ rootKind: file.rootKind,
606
+ loadOrder: file.loadOrder,
607
+ location: nodeLocation(document, assignment, assignment.value.value),
608
+ metadata: { advisor: true },
609
+ });
610
+ }
597
611
  if (sourcePath.startsWith('common/script_constants/') &&
598
612
  key !== 'schema' &&
599
613
  !ancestors.includes('schema')) {
@@ -918,6 +932,20 @@ export class SymbolIndex {
918
932
  location: nodeLocation(document, icon, id),
919
933
  });
920
934
  }
935
+ else if ((key === 'shared_focus' || key === 'joint_focus') &&
936
+ id !== undefined &&
937
+ ancestors.length === 0) {
938
+ // Shared and joint focuses sit outside any tree; trees add them with `shared_focus = <id>`.
939
+ this.addSymbol({
940
+ kind: 'focus',
941
+ id,
942
+ path: file.displayPath,
943
+ rootKind: file.rootKind,
944
+ loadOrder: file.loadOrder,
945
+ location: nodeLocation(document, assignment, id),
946
+ metadata: { shared: key },
947
+ });
948
+ }
921
949
  else if (key === 'focus' && id !== undefined && ancestors.at(-1) === 'focus_tree') {
922
950
  this.addSymbol({
923
951
  kind: 'focus',
@@ -8,7 +8,34 @@ import { nearestNames } from '../reference/suggestions.js';
8
8
  import { PACKAGE_VERSION } from '../version.js';
9
9
  import { inspectDecisionAi } from './ai.js';
10
10
  import { compareDecisionScenarios, inspectDecisionScenario } from './comparison.js';
11
- import { decisionSourceInventory, decisionTargetCatalog } from './source-inventory.js';
11
+ import { decisionSourceInventory, decisionTargetCatalog, } from './source-inventory.js';
12
+ /**
13
+ * An inventory narrowed to one category (its decisions) or one decision (#59). Any other id is
14
+ * not-found with close names, never a whole-workspace inventory.
15
+ */
16
+ function scopedInventory(inventory, id, complete) {
17
+ const ids = new Set([id]);
18
+ const isCategory = inventory.categories.some((category) => category.id === id);
19
+ const decisions = inventory.decisions.filter((source) => isCategory ? source.category === id : source.id === id);
20
+ if (!isCategory && decisions.length === 0) {
21
+ const suggestions = nearestNames(id, new Set([
22
+ ...inventory.categories.map((category) => category.id),
23
+ ...inventory.decisions.map((source) => source.id),
24
+ ]));
25
+ throw new ServiceError('DECISION_NOT_FOUND', `No decision or decision category ${id.slice(0, 256)} is defined${complete ? '' : ' in the scanned files (the scan is incomplete)'}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: id.slice(0, 256), suggestions, scanComplete: complete });
26
+ }
27
+ for (const source of decisions) {
28
+ ids.add(source.category);
29
+ ids.add(source.id);
30
+ }
31
+ return {
32
+ ...inventory,
33
+ decisions,
34
+ categories: inventory.categories.filter((category) => ids.has(category.id)),
35
+ overrides: inventory.overrides.filter((override) => ids.has(override.id)),
36
+ unresolvedDefinitions: inventory.unresolvedDefinitions.filter((entry) => ids.has(entry.id)),
37
+ };
38
+ }
12
39
  /** Authorized, read-only decision operation over the shared source scanner. */
13
40
  export class DecisionAnalyzer {
14
41
  engine;
@@ -33,7 +60,10 @@ export class DecisionAnalyzer {
33
60
  throw new ServiceError('DECISION_PROPOSAL_REQUIRED', 'Decision comparison requires proposed sources');
34
61
  if (input.mode !== 'compare' && input.proposedSources !== undefined)
35
62
  throw new ServiceError('DECISION_PROPOSAL_MODE', 'Proposed sources require compare mode');
36
- const inventory = decisionSourceInventory(before);
63
+ const fullInventory = decisionSourceInventory(before);
64
+ const inventory = input.mode === 'inventory' && input.id !== undefined
65
+ ? scopedInventory(fullInventory, input.id, before.complete)
66
+ : fullInventory;
37
67
  if (input.mode === 'inspect' &&
38
68
  input.id !== undefined &&
39
69
  !inventory.decisions.some((source) => source.id === input.id)) {
@@ -156,6 +186,13 @@ export class DecisionAnalyzer {
156
186
  categories: inventory.categories.length,
157
187
  overrides: inventory.overrides.length,
158
188
  scenarios: input.mode === 'inventory' ? 0 : input.scenarios.length,
189
+ // A scoped inventory answers inline: the decisions of that category or the one decision.
190
+ ...(input.mode === 'inventory' && input.id !== undefined
191
+ ? {
192
+ decisionIds: inventory.decisions.slice(0, 64).map(({ id }) => id),
193
+ decisionIdsTruncated: inventory.decisions.length > 64,
194
+ }
195
+ : {}),
159
196
  unresolvedDefinitions: inventory.unresolvedDefinitions.length,
160
197
  ...(inventory.unresolvedDefinitions.length === 0
161
198
  ? {}
@@ -1206,15 +1206,29 @@ function stateLifecycleIssues(graph, stateLinks, budget) {
1206
1206
  clearers.set(key, values);
1207
1207
  }
1208
1208
  }
1209
+ // has_event_target checks per owner: a read in the same owner that ends after the check starts
1210
+ // is guarded. That includes the read recorded for an enclosing `if` or `limit` block.
1211
+ const presenceChecks = new Map();
1212
+ for (const access of graph.stateAccesses) {
1213
+ if (access.metadata.presence !== true)
1214
+ continue;
1215
+ const key = `${access.ownerId}\u0000${stateKey(access)}`;
1216
+ presenceChecks.set(key, [...(presenceChecks.get(key) ?? []), access]);
1217
+ }
1218
+ const guarded = (access) => (presenceChecks.get(`${access.ownerId}\u0000${stateKey(access)}`) ?? []).some((check) => check.location.path === access.location.path &&
1219
+ check.location.start.offset < access.location.end.offset);
1209
1220
  for (const access of graph.stateAccesses) {
1210
1221
  if (access.access !== 'read' && access.access !== 'read_write')
1211
1222
  continue;
1212
1223
  if (compatibleProducerKeys(access).some((producerKey) => (producers.get(producerKey) ?? []).length > 0))
1213
1224
  continue;
1214
1225
  const owner = semanticOwnerId(access.ownerId, nodes, parent);
1215
- if (access.kind === 'event_target' ||
1226
+ if ((access.kind === 'event_target' ||
1216
1227
  access.kind === 'global_event_target' ||
1217
- access.kind === 'saved_scope') {
1228
+ access.kind === 'saved_scope') &&
1229
+ access.metadata.presence !== true) {
1230
+ if (guarded(access))
1231
+ continue;
1218
1232
  addIssue(graph.issues, {
1219
1233
  code: 'EVENT_TARGET_READ_BEFORE_SAVE',
1220
1234
  classification: 'probable_defect',
@@ -103,11 +103,34 @@ export function selectEventNodes(graph, selector, signal) {
103
103
  signal?.throwIfAborted();
104
104
  return matched.sort((left, right) => compareCodeUnits(left.id, right.id));
105
105
  }
106
- export function discoverEventRoots(graph, signal) {
106
+ export function discoverEventRoots(graph, signal, selector) {
107
+ const roots = allEventRoots(graph, signal);
108
+ if (selector === undefined)
109
+ return roots;
110
+ // A selector keeps the roots among its nodes, the entry points that start them and the
111
+ // cycles through them (#59).
112
+ const selected = new Set(selectEventNodes(graph, selector, signal).map(({ id }) => id));
113
+ const startsSelected = new Set(eventFlowEdges(graph, false)
114
+ .filter(({ to }) => selected.has(to))
115
+ .map(({ from }) => from));
116
+ const ids = new Set(graph.nodes
117
+ .filter(({ id, kind }) => kind === 'event' && selected.has(id))
118
+ .flatMap(({ eventId }) => (eventId === undefined ? [] : [eventId])));
119
+ return {
120
+ entryPoints: roots.entryPoints.filter(({ id }) => selected.has(id) || startsSelected.has(id)),
121
+ automaticEvents: roots.automaticEvents.filter(({ id }) => selected.has(id)),
122
+ knownRootEventIds: roots.knownRootEventIds.filter((id) => ids.has(id)),
123
+ callerlessTriggeredEvents: roots.callerlessTriggeredEvents.filter(({ id }) => selected.has(id)),
124
+ stronglyConnectedComponents: roots.stronglyConnectedComponents.filter(({ nodeIds }) => nodeIds.some((id) => selected.has(id))),
125
+ };
126
+ }
127
+ function allEventRoots(graph, signal) {
107
128
  signal?.throwIfAborted();
108
129
  const edges = eventFlowEdges(graph, false);
109
130
  const incoming = new Map();
110
- for (const [index, edge] of edges.entries()) {
131
+ // An event a scripted effect fires has a caller. Roots do not project helpers, so count the
132
+ // direct edges too, helper edges included.
133
+ for (const [index, edge] of [...edges, ...eventFlowEdges(graph, true)].entries()) {
111
134
  if ((index & 255) === 0)
112
135
  signal?.throwIfAborted();
113
136
  incoming.set(edge.to, (incoming.get(edge.to) ?? 0) + 1);
@@ -271,6 +271,25 @@ function boundedEvidence(values, limit = EVENT_FOCUSED_EVIDENCE_LIMIT) {
271
271
  inventory: { count: values.length, retainedCount: limit, truncated: true },
272
272
  };
273
273
  }
274
+ /** The not-found for a selector no scanned node matches, with close names where there are any. */
275
+ function selectorNotFound(graph, selector) {
276
+ const close = (value, names) => nearestNames(value, new Set([...names].filter((name) => name !== undefined)));
277
+ const hint = (suggestions) => suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`;
278
+ switch (selector.kind) {
279
+ case 'event': {
280
+ const suggestions = close(selector.eventId, graph.nodes.map(({ eventId }) => eventId));
281
+ return new ServiceError('EVENT_NOT_FOUND', `No scanned file defines or fires event ${selector.eventId.slice(0, 256)}${hint(suggestions)}`, { eventId: selector.eventId.slice(0, 256), suggestions });
282
+ }
283
+ case 'namespace': {
284
+ const suggestions = close(selector.namespace, graph.nodes.map(({ namespace }) => namespace));
285
+ return new ServiceError('EVENT_NAMESPACE_NOT_FOUND', `No scanned event belongs to the namespace ${selector.namespace.slice(0, 256)}${hint(suggestions)}`, { namespace: selector.namespace.slice(0, 256), suggestions });
286
+ }
287
+ case 'node':
288
+ return new ServiceError('EVENT_NODE_NOT_FOUND', `No node ${selector.nodeId.slice(0, 256)} is in the event graph`, { nodeId: selector.nodeId.slice(0, 256) });
289
+ default:
290
+ return new ServiceError('EVENT_SOURCE_NOT_FOUND', 'No event, option or entry point of the event graph is in the selected source', { selector: selector.kind });
291
+ }
292
+ }
274
293
  function boundedUnresolved(graph, selectedNodeIds) {
275
294
  const relevant = selectedNodeIds === undefined
276
295
  ? graph.unresolved
@@ -834,17 +853,32 @@ export class EventChainViewer {
834
853
  ...(input.impactSubject === undefined ? {} : { impactSubject: input.impactSubject }),
835
854
  refresh: input.refresh ?? input.mode === 'scan',
836
855
  };
856
+ // A selector or state subject that matches nothing is not-found, never an empty answer (#59).
857
+ if (input.selector !== undefined &&
858
+ input.mode !== 'impact' &&
859
+ selectEventNodes(graph, input.selector).length === 0)
860
+ throw selectorNotFound(graph, input.selector);
861
+ if (input.mode === 'state_flow' &&
862
+ input.stateSubject !== undefined &&
863
+ !graph.stateAccesses.some(({ kind, name }) => kind === input.stateSubject.kind && name === input.stateSubject.name)) {
864
+ const { kind, name } = input.stateSubject;
865
+ const suggestions = nearestNames(name, new Set(graph.stateAccesses.filter((access) => access.kind === kind).map((a) => a.name)));
866
+ throw new ServiceError('EVENT_STATE_NOT_FOUND', `No scanned file sets, checks or clears the ${kind.replaceAll('_', ' ')} ${name.slice(0, 256)}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { kind, name: name.slice(0, 256), suggestions });
867
+ }
837
868
  let report;
838
869
  let summary;
839
870
  switch (input.mode) {
840
871
  case 'scan':
841
872
  report = eventScanReport(graph);
842
- summary = summarizeEventIssues(graph.issues);
873
+ // A selector narrows the findings to its events, as lint does (#59).
874
+ summary = summarizeEventIssues(input.selector === undefined
875
+ ? graph.issues
876
+ : lintEventGraph(graph, input.selector, input.signal));
843
877
  break;
844
878
  case 'roots':
845
879
  {
846
880
  const unresolved = boundedUnresolved(graph);
847
- const roots = discoverEventRoots(graph, input.signal);
881
+ const roots = discoverEventRoots(graph, input.signal, input.selector);
848
882
  summary = summarizeEventRoots(roots);
849
883
  report = {
850
884
  graphRevision: graph.revision,
@@ -860,12 +894,6 @@ export class EventChainViewer {
860
894
  case 'trace':
861
895
  if (input.selector === undefined)
862
896
  throw new ServiceError('EVENT_SELECTOR_REQUIRED', 'Trace requires a selector');
863
- if (input.selector.kind === 'event' &&
864
- selectEventNodes(graph, input.selector).length === 0) {
865
- // An event no file defines or fires is not-found, never an empty trace.
866
- const suggestions = nearestNames(input.selector.eventId, new Set(graph.nodes.flatMap(({ eventId }) => (eventId === undefined ? [] : [eventId]))));
867
- throw new ServiceError('EVENT_NOT_FOUND', `No scanned file defines or fires event ${input.selector.eventId.slice(0, 256)}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { eventId: input.selector.eventId.slice(0, 256), suggestions });
868
- }
869
897
  {
870
898
  const trace = traceSelectedEvents(graph, input.selector, {
871
899
  maxDepth,
@@ -906,13 +934,40 @@ export class EventChainViewer {
906
934
  case 'state_flow':
907
935
  {
908
936
  const unresolved = boundedUnresolved(graph);
909
- const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code));
910
- summary = summarizeEventIssues(stateIssues);
937
+ const subject = input.stateSubject;
938
+ const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code, details }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code) &&
939
+ // A subject narrows the issues as well as the flow. Analysis limits stay, because
940
+ // they make the flow partial.
941
+ (subject === undefined ||
942
+ (typeof details.name === 'string'
943
+ ? details.name === subject.name &&
944
+ (details.stateKind === undefined || details.stateKind === subject.kind)
945
+ : code.endsWith('_LIMIT'))));
946
+ const flow = inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal);
947
+ const where = (accesses) => accesses.slice(0, 8).map(({ location }) => `${location.path}:${location.start.line}`);
948
+ summary = {
949
+ ...summarizeEventIssues(stateIssues),
950
+ // The subject's own flow answers inline; the report holds every access.
951
+ ...(subject === undefined
952
+ ? {}
953
+ : {
954
+ flow: {
955
+ subject: `${subject.kind}:${subject.name}`,
956
+ producers: flow.producers.length,
957
+ consumers: flow.consumers.length,
958
+ clears: flow.clears.length,
959
+ links: flow.links.length,
960
+ unproducedReads: flow.unproducedReads.length,
961
+ producedAt: where(flow.producers),
962
+ readAt: where(flow.consumers),
963
+ },
964
+ }),
965
+ };
911
966
  const issues = boundedEvidence(stateIssues);
912
967
  report = {
913
968
  graphRevision: graph.revision,
914
969
  sourceHashes: graph.sourceHashes,
915
- flow: inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal),
970
+ flow,
916
971
  issues: issues.values,
917
972
  unresolved: unresolved.values,
918
973
  ...(issues.inventory === undefined ? {} : { issueInventory: issues.inventory }),
@@ -152,6 +152,12 @@ function isScopeChain(value) {
152
152
  function isLiteralCountryTag(value) {
153
153
  return /^[A-Z][A-Z0-9]{2}$/u.test(value);
154
154
  }
155
+ const FOCUS_BLOCKS = new Set(['focus', 'shared_focus', 'joint_focus']);
156
+ const FOCUS_REWARD_BLOCKS = [
157
+ 'completion_reward',
158
+ 'completion_reward_joint_originator',
159
+ 'completion_reward_joint_member',
160
+ ];
155
161
  const EFFECT_WRAPPER_BLOCKS = new Set([
156
162
  ...CONTROL_BLOCKS,
157
163
  'effect',
@@ -785,7 +791,9 @@ class FragmentAnalyzer {
785
791
  }
786
792
  analyzeFocuses() {
787
793
  this.visitAssignments(this.document.root, (assignment, ancestors) => {
788
- if (assignment.key.value !== 'focus' || assignment.value.type !== 'block')
794
+ // Shared and joint focuses run their rewards like tree focuses (vanilla's Saadabad branch
795
+ // saves SSB_leader in a joint_focus).
796
+ if (!FOCUS_BLOCKS.has(assignment.key.value) || assignment.value.type !== 'block')
789
797
  return;
790
798
  const id = firstScalar(assignment.value, 'id')?.value;
791
799
  if (id === undefined)
@@ -805,19 +813,22 @@ class FragmentAnalyzer {
805
813
  });
806
814
  });
807
815
  }
808
- const rewardOccurrences = new Map();
809
- childBlocks(assignment.value, 'completion_reward').forEach((block) => this.walk(block, {
810
- ownerId,
811
- sourceScope: 'country',
812
- phase: 'entry',
813
- conditions: [],
814
- helperStack: [],
815
- semanticPath: [
816
- ...ancestors,
817
- id,
818
- semanticOccurrenceSegment('completion_reward', semanticSourceEntry(block), rewardOccurrences),
819
- ],
820
- }));
816
+ // A joint focus rewards its originator and its members in blocks of their own.
817
+ for (const key of FOCUS_REWARD_BLOCKS) {
818
+ const rewardOccurrences = new Map();
819
+ childBlocks(assignment.value, key).forEach((block) => this.walk(block, {
820
+ ownerId,
821
+ sourceScope: 'country',
822
+ phase: 'entry',
823
+ conditions: [],
824
+ helperStack: [],
825
+ semanticPath: [
826
+ ...ancestors,
827
+ id,
828
+ semanticOccurrenceSegment(key, semanticSourceEntry(block), rewardOccurrences),
829
+ ],
830
+ }));
831
+ }
821
832
  });
822
833
  }
823
834
  analyzeDecisions() {
@@ -1397,8 +1408,11 @@ class FragmentAnalyzer {
1397
1408
  }
1398
1409
  const rule = STATE_RULES[assignment.key.value];
1399
1410
  if (rule === undefined) {
1400
- const raw = valueText(this.document, assignment.value);
1401
- for (const match of raw.matchAll(/\b(event_target|global_event_target):([A-Za-z0-9_-]+)/gu)) {
1411
+ // The whole value: valueText is cut for display and would cut a name at its end.
1412
+ const raw = this.document.text.slice(assignment.value.start, assignment.value.end);
1413
+ // A name that runs on into `[...]` or `$...$` is built at run time (meta_effect, scripted
1414
+ // parameters); its literal prefix is not the target's name.
1415
+ for (const match of raw.matchAll(/\b(event_target|global_event_target):([A-Za-z0-9_-]+)(?![A-Za-z0-9_[$-])/gu)) {
1402
1416
  this.addState(context, match[1] === 'global_event_target' ? 'global_event_target' : 'event_target', match[2], 'read', assignment, semanticPath, false);
1403
1417
  }
1404
1418
  return;
@@ -1430,6 +1444,11 @@ class FragmentAnalyzer {
1430
1444
  this.addState(context, kind, name, access, assignment, semanticPath, isDynamic(name), {
1431
1445
  ...(rule.storage === undefined ? {} : { storage: rule.storage }),
1432
1446
  ...(rule.temporary === true ? { temporary: true } : {}),
1447
+ // has_event_target tests whether the target exists; it never reads an unset one.
1448
+ ...(assignment.key.value === 'has_event_target' ||
1449
+ assignment.key.value === 'has_global_event_target'
1450
+ ? { presence: true }
1451
+ : {}),
1433
1452
  });
1434
1453
  }
1435
1454
  addState(context, kind, name, access, node, _semanticPath, dynamic, metadata = {}) {
@@ -6,6 +6,7 @@ import { inspectImpactGraph } from '../core/impact-graph.js';
6
6
  import { setInlineFilesScanned } from '../core/operation-result.js';
7
7
  import { emptyServiceResult, ServiceError } from '../core/result.js';
8
8
  import { buildProposedSourceOverlay } from '../core/source-overlay.js';
9
+ import { nearestNames } from '../reference/suggestions.js';
9
10
  import { PACKAGE_VERSION } from '../version.js';
10
11
  import { inspectImpactScenarioSuites } from './scenario-suites.js';
11
12
  /** Authorized, read-only impact operation shared by ordinary calls and persistent jobs. */
@@ -35,6 +36,20 @@ export class ImpactAnalyzer {
35
36
  for (const file of input.changedFiles)
36
37
  if (!availablePaths.has(file))
37
38
  throw new ServiceError('IMPACT_SOURCE_UNKNOWN', 'Changed file is not in the authorized source inventory or proposed overlay', { file });
39
+ // A symbol that nothing defines or names would answer an empty graph; say so instead (#59).
40
+ const indexes = [before.index, ...(overlay === undefined ? [] : [overlay.snapshot.index])];
41
+ const unknown = input.symbols.filter(({ kind, id }) => !indexes.some((index) => index.find(kind, id) !== undefined ||
42
+ index.references.some((reference) => reference.toKind === kind && reference.to === id)));
43
+ if (unknown.length > 0) {
44
+ const symbols = unknown.map(({ kind, id }) => ({
45
+ kind,
46
+ id: id.slice(0, 256),
47
+ suggestions: nearestNames(id, new Set(before.index.findAll(kind).map((symbol) => symbol.id))),
48
+ }));
49
+ throw new ServiceError('IMPACT_SYMBOL_NOT_FOUND', `Nothing defines or uses ${symbols
50
+ .map(({ kind, id, suggestions }) => `${kind} ${id}${suggestions.length === 0 ? '' : ` (did you mean ${suggestions.join(', ')}?)`}`)
51
+ .join('; ')}${before.complete ? '' : ' in the scanned files (the scan is incomplete)'}`, { symbols, scanComplete: before.complete });
52
+ }
38
53
  const query = {
39
54
  symbols: input.symbols,
40
55
  changedFiles: input.changedFiles.length > 0
@@ -1046,11 +1046,23 @@ function* validateLakesAndEdge(index, raster, report, options) {
1046
1046
  pairs.add(`${Math.min(a, b)}:${Math.max(a, b)}`);
1047
1047
  }
1048
1048
  }
1049
- if (rows > 0)
1049
+ // A wall closes the seam with land on purpose; there, water at the seam is the defect.
1050
+ if (options.edgeMode === 'wall') {
1051
+ const open = height * 2 - left - right;
1052
+ if (open > 0)
1053
+ report({
1054
+ code: 'MAP_EDGE_WALL_OPEN',
1055
+ severity: 'error',
1056
+ message: `Water reaches the first or last column at ${open} pixels (${height - left} on the west edge, ${height - right} on the east); ships can cross the seam there`,
1057
+ location,
1058
+ details: { west: height - left, east: height - right },
1059
+ });
1060
+ }
1061
+ else if (rows > 0)
1050
1062
  report({
1051
1063
  code: 'MAP_EDGE_LAND_CUT',
1052
1064
  severity: options.edgeMode === 'sea-band' ? 'error' : 'warning',
1053
- message: `Land touches the first or last column on ${rows} rows (${left} on the west edge, ${right} on the east); where the world wraps, the coast is cut by a straight vertical line. Use edge.mode "sea-band" or "rim"`,
1065
+ message: `Land touches the first or last column on ${rows} rows (${left} on the west edge, ${right} on the east); where the world wraps, the coast is cut by a straight vertical line. Use edge.mode "sea-band", "rim" or "wall"`,
1054
1066
  location,
1055
1067
  details: { rows, west: left, east: right, firstRows: rowSamples },
1056
1068
  });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Overland reach of each realm through impassable land (ZR-28). Impassable states and impassable
3
+ * adjacency rows make a strategic board, but they can also cut a realm in two or box it in by
4
+ * accident. This compares two graphs of land provinces joined by shared borders and `sea`
5
+ * crossings: one with every province and border, and one without the impassable provinces and
6
+ * the blocked borders. Whatever the first joins and the second separates was cut by impassable
7
+ * land; islands, which neither graph joins, are never reported.
8
+ */
9
+ function components(count, include, edges) {
10
+ const label = new Int32Array(count).fill(-1);
11
+ let next = 0;
12
+ for (let start = 0; start < count; start += 1) {
13
+ if (label[start] !== -1 || !include(start))
14
+ continue;
15
+ const queue = [start];
16
+ label[start] = next;
17
+ // The array iterator also visits provinces queued during the loop.
18
+ for (const id of queue)
19
+ for (const other of edges(id))
20
+ if (label[other] === -1 && include(other)) {
21
+ label[other] = next;
22
+ queue.push(other);
23
+ }
24
+ next += 1;
25
+ }
26
+ return label;
27
+ }
28
+ export function realmReachNotes(input) {
29
+ const count = input.kind.length;
30
+ const key = (a, b) => (a < b ? `${a}:${b}` : `${b}:${a}`);
31
+ const blocked = new Set(input.blocked.map(([a, b]) => key(a, b)));
32
+ const linked = [];
33
+ for (const [a, b] of input.crossings) {
34
+ (linked[a] ??= []).push(b);
35
+ (linked[b] ??= []).push(a);
36
+ }
37
+ const land = (id) => input.kind[id] === 1;
38
+ const everything = components(count, land, (id) => [
39
+ ...input.neighbors[id],
40
+ ...(linked[id] ?? []),
41
+ ]);
42
+ const passable = components(count, (id) => land(id) && !input.impassable.has(id), (id) => [...input.neighbors[id], ...(linked[id] ?? [])].filter((other) => !blocked.has(key(id, other))));
43
+ const notes = [];
44
+ for (const [realm, capital] of input.capitals.entries()) {
45
+ const tag = input.tags[realm] ?? String(realm);
46
+ const home = passable[capital];
47
+ const cut = [];
48
+ for (const [id, owner] of input.owner)
49
+ if (owner === realm &&
50
+ !input.impassable.has(id) &&
51
+ passable[id] !== home &&
52
+ everything[id] === everything[capital])
53
+ cut.push(id);
54
+ if (cut.length > 0)
55
+ notes.push({
56
+ code: 'MAP_REALM_CUT_OFF',
57
+ severity: 'warning',
58
+ message: `${cut.length} land province(s) of ${tag} are cut off from its capital by impassable land or borders; open a pass or give them to a realm on their side`,
59
+ details: { tag, provinces: cut.length, sample: cut.slice(0, 10).map((id) => id + 1) },
60
+ });
61
+ // Boxed in: the land around the capital reaches another realm only through impassable land.
62
+ let foreignBefore = false;
63
+ let foreignAfter = false;
64
+ for (const [id, owner] of input.owner) {
65
+ if (owner === realm)
66
+ continue;
67
+ if (everything[id] === everything[capital])
68
+ foreignBefore = true;
69
+ if (passable[id] === home)
70
+ foreignAfter = true;
71
+ }
72
+ if (foreignBefore && !foreignAfter)
73
+ notes.push({
74
+ code: 'MAP_REALM_ENCLOSED',
75
+ severity: 'warning',
76
+ message: `${tag} reaches no other realm over land: impassable land or borders close every way out of the land around its capital`,
77
+ details: { tag, capitalProvince: capital + 1 },
78
+ });
79
+ }
80
+ return notes;
81
+ }
@@ -540,6 +540,8 @@ export function resolveGeography(model, options) {
540
540
  const shareSum = Object.values(terrain).reduce((sum, share) => sum + share, 0);
541
541
  if (shareSum > 1.05)
542
542
  sink('MAP_GEOGRAPHY_REGION_TERRAIN_SUM', 'warning', `The terrain shares of region ${input.id} add up to ${shareSum.toFixed(2)}, above 1`, { featureId: input.id, sum: shareSum });
543
+ if (input.impassable === true && area === undefined)
544
+ sink('MAP_GEOGRAPHY_IMPASSABLE_WITHOUT_AREA', 'error', `Region ${input.id} is impassable but has no polygons to say where`, { featureId: input.id });
543
545
  const perState = input.density?.provincesPerState;
544
546
  if (perState !== undefined && !(perState[0] <= perState[1] && perState[1] <= perState[2]))
545
547
  sink('MAP_GEOGRAPHY_REGION_DENSITY_ORDER', 'error', `Region ${input.id} lists provincesPerState as [smallest, usual, largest] but they are not in order`, { featureId: input.id });
@@ -551,6 +553,7 @@ export function resolveGeography(model, options) {
551
553
  ...(Object.keys(terrain).length === 0 ? {} : { terrain }),
552
554
  ...(perState === undefined ? {} : { provincesPerState: perState }),
553
555
  ...opt('provinceAreaPx', input.density?.provinceAreaPx),
556
+ ...(input.impassable === true && area !== undefined ? { impassable: true } : {}),
554
557
  });
555
558
  }
556
559
  const lands = [];
@@ -1421,8 +1424,9 @@ function coarseChecks(input) {
1421
1424
  }
1422
1425
  function edgeChecks(input) {
1423
1426
  const { frame, edgeBand, sink, grid } = input;
1424
- // A rim wall ends land inside the band by design, and `none` opts out of the check.
1425
- if (input.policy?.mode === 'none' || input.policy?.mode === 'rim')
1427
+ // A rim or wall ends land inside the band by design, and `none` opts out of the check.
1428
+ const mode = input.policy?.mode;
1429
+ if (mode === 'none' || mode === 'rim' || mode === 'wall')
1426
1430
  return;
1427
1431
  const severity = input.policy?.mode === 'sea-band' ? 'error' : 'warning';
1428
1432
  const fx = edgeBand.westEastPx / frame.width;
@@ -16,6 +16,7 @@ import { planWorldOutputs } 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';
19
+ import { resolvePaintedRelief } from './relief/painted-relief.js';
19
20
  export function* cancellationCheckpoint(signal, iteration = 0, stride = 1) {
20
21
  if (iteration % stride !== 0)
21
22
  return;
@@ -3336,6 +3337,8 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3336
3337
  throw new ServiceError('MAP_LOOK_CUSTOM_PALETTE_REQUIRED', 'look "custom" needs colormap.palette with at least one class colour');
3337
3338
  if (colormapProfile === 'legacy' && look !== undefined)
3338
3339
  throw new ServiceError('MAP_LOOK_REQUIRES_CALIBRATED_COLORMAP', 'look selects a calibrated palette; remove colormap.profile "legacy" or look');
3340
+ if ((operation.relief?.painted ?? false) !== false && (!hasGeography || reference === undefined))
3341
+ throw new ServiceError('MAP_RELIEF_PAINTED_INPUTS', 'relief.painted raises the relief from the classes of a reference picture onto a geography model; give both reference and geography (or geographyPath)', { reference: reference !== undefined, geography: hasGeography });
3339
3342
  if (!hasGeography && operation.development?.model === 'geography')
3340
3343
  throw new ServiceError('MAP_DEVELOPMENT_REQUIRES_GEOGRAPHY', 'development.model "geography" plans the economy from a geography model; give geography or geographyPath, or use "legacy"');
3341
3344
  if (!hasGeography && operation.autoStraits !== undefined && operation.autoStraits !== false)
@@ -3436,6 +3439,11 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3436
3439
  : { detail: operation.relief.detail }),
3437
3440
  },
3438
3441
  }),
3442
+ ...(operation.relief?.painted === undefined || operation.relief.painted === false
3443
+ ? {}
3444
+ : {
3445
+ paintedRelief: resolvePaintedRelief(operation.relief.painted),
3446
+ }),
3439
3447
  ...(typeof operation.rivers === 'object'
3440
3448
  ? { riverDensity: operation.rivers.density }
3441
3449
  : typeof operation.rivers === 'number'