hoi4-agent-tools 4.7.0 → 4.8.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 (101) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +32 -13
  3. package/dist/hoi4_agent_tools/core/engine-client.js +74 -5
  4. package/dist/hoi4_agent_tools/core/operation-result.js +9 -0
  5. package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
  6. package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
  7. package/dist/hoi4_agent_tools/decision/service.js +7 -0
  8. package/dist/hoi4_agent_tools/event/service.js +18 -6
  9. package/dist/hoi4_agent_tools/event/summary.js +9 -0
  10. package/dist/hoi4_agent_tools/focus/engine-layout.js +1 -1
  11. package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
  12. package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
  13. package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
  14. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +241 -241
  15. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +30 -19
  16. package/dist/hoi4_agent_tools/focus/quality/schematic.js +5 -3
  17. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +1 -1
  18. package/dist/hoi4_agent_tools/focus/render.js +21 -9
  19. package/dist/hoi4_agent_tools/focus/tool-operations.js +158 -3
  20. package/dist/hoi4_agent_tools/gui/assets.js +18 -0
  21. package/dist/hoi4_agent_tools/gui/dds.js +38 -5
  22. package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
  23. package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
  24. package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
  25. package/dist/hoi4_agent_tools/gui/validators.js +31 -2
  26. package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
  27. package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
  28. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  29. package/dist/hoi4_agent_tools/mcp/tools/event.js +2 -0
  30. package/dist/hoi4_agent_tools/mcp/tools/focus.js +1 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/reference.js +18 -0
  32. package/dist/hoi4_agent_tools/probability/operations.js +27 -1
  33. package/dist/hoi4_agent_tools/probability/service.js +91 -11
  34. package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
  35. package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
  36. package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
  37. package/dist/hoi4_agent_tools/reference/error-log.js +24 -0
  38. package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
  39. package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
  40. package/dist/hoi4_agent_tools/reference/operations.js +68 -2
  41. package/dist/hoi4_agent_tools/reference/ranking.js +32 -0
  42. package/dist/hoi4_agent_tools/reference/script-validation.js +46 -6
  43. package/dist/hoi4_agent_tools/reference/service.js +33 -0
  44. package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
  45. package/dist/hoi4_agent_tools/schemas/focus-requests.js +4 -0
  46. package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
  47. package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
  48. package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/focus.md +9 -5
  51. package/docs/research/reference-benchmark.md +41 -0
  52. package/docs/tools.md +43 -39
  53. package/docs/troubleshooting.md +13 -12
  54. package/engine/README.md +284 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +26 -0
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +4 -1
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +1 -1
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +1 -1
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +1 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 4.8.0 - 2026-11-05
6
+
7
+ - 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.
8
+ - Add `hoi4.idea_inspect` on the shared Rust engine (`hoi4-engine ideas`; coverage tools part 2, issue #71). An idea comes back with its category, every definition in load order, its picture sprite and texture, its modifiers checked against the game's documentation, the mod's `common/modifier_definitions` and the modifiers the game builds from buildings, sub-units, unit categories, idea slots and operations, its conditions and effects as written, its name and description in every language, the character whose advisor `idea_token` it is, and the files that mention it. A character comes back with its name, every role (country leader, advisor, general, field marshal, admiral, operative) with its traits checked, and its portraits checked. `audit: true` checks every idea or character of the mod. Hidden ideas and ideas with `visible = { always = no }` need no picture or name. Sprites and textures of the game itself are not judged, because a DLC that is not installed may supply them. A missing name is information. An unknown id is `IDEA_NOT_FOUND` or `CHARACTER_NOT_FOUND` with close ids. On vanilla, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every reported problem was checked by hand: vanilla has none.
9
+ - Add `hoi4.localisation_inspect` on the shared Rust engine (`hoi4-engine localisation`; issue #71, plan `docs/plans/coverage-tools.md`). It reads every localisation file of the game, DLC, dependencies and mod in every language. `key` returns one key's text per language with file, line and layer, the supported languages that lack it and the script files that mention it; an unknown key is `LOCALISATION_KEY_NOT_FOUND` with close keys. `audit` counts the mod's problems and keeps a few examples of each: keys the mod's script uses that no language defines, keys of the main language missing from a supported language, keys defined twice in one language, and file problems. Text that scripted localisation shows as written, and a translation that writes a name out instead of keeping `$key$`, are information, not problems. `coverage` counts keys per language. A language is supported when it holds at least a quarter of the main language's keys. Without the engine the tool answers `ENGINE_UNAVAILABLE`. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 every reported problem was checked by hand. A key lookup takes about 2.5 s and an audit 3 to 15 s.
10
+ - Find more documentation answers first from plain-word questions (ADR 0078). Each documented effect, trigger and modifier now also matches four plain-word phrasings of what it does (`command-phrases.json`, written once from its documentation and in-game text), and a question that grants something prefers `add_` and `create_` commands over their `remove_` and `end_` counterparts, and the other way round. On 40 blind test questions on HOI4 1.19.4.1, 25 rather than 21 answers rank first and 31 rather than 27 within three. On a second blind set written for this change, 17 rather than 9 of 38 rank first. Add that set as `--fresh` to the discovery benchmark.
11
+ - Make the focus preview fast (#74). `hoi4.focus_render` no longer rasterizes the schematic SVG for its PNG, which took 118 to 129 seconds of every call on vanilla Germany: the resident engine draws the game view instead. New input `view: "game"` returns the game view alone (PNG, a JSON report that records the render request, an SVG hover map and a self-contained HTML viewer with zoom, drag and hover titles, and one inline overview of at most about 700 KB), without the schematic or the presentation pass, for a preview that renders after every edit. The engine caches each workspace's parsed `.gfx` files, folder listings, textures and fonts for the server's life, checks each folder once per render and remembers sprites within a render. On the largest trees of the game and six mods, a warm `view: "game"` call takes 3 to 12 s and the engine's own warm render 0.1 to 0.5 s, against 15 to 136 s per call before; numbers per mod are in the pull request. `scripts/bench/preview-timing.ts` and `preview-engine-timing.ts` measure them, and `bench/corpus.json` gains Atlantis.
12
+ - Draw the national focus view as the game does (#75). `hoi4.focus_render`'s PNG is now the game view whenever the engine binary is available; without it, the PNG stays the schematic with decoded icons. Assets the view cannot draw are listed as `FOCUS_GAME_VIEW_ASSET_MISSING` and a failed engine render as `FOCUS_GAME_VIEW_UNAVAILABLE`. The new engine crate `hoi4-preview` renders a focus tree from the game's own assets in load order: the tree window background, the "can start" and "unavailable" plaques, icons, titles in the game's bitmap font (`hoi_16mbs`, with `§` colour codes), the solid and dotted connector tiles with their junction tiles, and the exclusive mark. Its geometry is read from `interface/nationalfocusview.gui`, so a mod that changes the view is drawn its way. On the in-game screenshots of game 1.19.4.1 at the default UI scale (run27), plaques, icons, titles and connectors land on the same pixels: the mean difference per region is 0.0 for titles and at most 2.8 of 255 for plaques, icons and connectors. Missing sprites, textures, fonts and glyphs are reported per focus, never drawn as something else. `hoi4-engine focus-render` draws one tree, and `hoi4-engine serve` answers `focus.render` with a cache per workspace. Not modelled: focus states other than "can start" and "unavailable", `available` and `bypass` triggers, joint-focus plaques, scripted localisation, animations, and exclusive marks between focuses on different rows or more than two columns apart.
13
+ - Decode every DDS format the game draws (#76). The GUI, sprite and icon renders now read DX10-header textures in any 8-bit RGBA or BGRA layout (DXGI 27 to 30 and 87 to 93) and BC1 to BC3 themselves, and hand BC4, BC5, BC7, packed 16-bit and 10-bit formats, luminance and alpha-only DDS to the Rust engine's new `hoi4-texture` crate (`engine/crates/texture`). Its decodes match a reference decode on 35 synthetic fixtures, bit for bit for BC7 (every mode and partition) and the 8-bit formats. It decodes all 34,923 DDS and TGA files of game 1.19.4.1 and all 219 DX10 files of Chaos Redux, and reads a file by its content, so the 456 PNG files Kaiserreich and Old World Blues ship with a `.dds` name decode too. A format nothing decodes, such as BC6H, still reports `GUI_TEXTURE_UNSUPPORTED`, now naming the format, and without the engine binary the reason says how to get it. A sprite whose texture is BC7 gets the warning `GUI_TEXTURE_FORMAT_RISKY`: in an in-game check on 1.19.4.1 a BC7 texture failed to load and the game crashed.
14
+ - Keep one engine process for the server's life (ADR 0077). `hoi4-engine serve` answers framed requests (a JSON line, then raw bytes) in parallel over stdin and stdout, with no idle eviction, a restart after a crash and a timeout per request. `hoi4-engine texture` decodes or checks texture files and folders.
15
+ - Correct the in-game focus connector model: the bar runs just under the parent's row and the long vertical drops in the child's column into the child's icon, as an in-game run on 1.19.4.1 showed at the default UI scale and zoom. The TypeScript scorecard, the schematic render and the Rust engine (`insert` crossing costs included) share it, with a parity test of seven hand-counted trees. The vanilla calibration is recomputed for game 1.19.4.1 and the corrected model, so the H4, H5 and S9 limits change.
16
+ - Add the benchmark harness (`bench/`, `npm run bench`; decisions Q-1, M-6, M-12). Each case is one tool call over the real stdio server with a hand-checked expected answer and its evidence. Sweeps count false positives over known-good files. Runs report correctness, inline answers, latency and result size per surface, against a stored baseline. The synthetic suite runs in CI on every platform (`tests/integration/bench-synthetic.test.ts`) and fails on any regression. The real suite runs on the installed game, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 on the maintainer's machine (`scripts/bench/nightly.sh`). It pins each corpus by game build, Git commit, Workshop manifest and content hash, and keeps its results there. `scripts/bench/hoi4-mcp/` holds the one-time isolated head-to-head with cpntodd/HOI4-MCP. CI gains a macOS arm64 job. The npm package is unchanged. The test setup runs in the temporary folder's real path, so the suite also passes on macOS.
17
+ - Remove 104 of the 110 false errors `script_validate` raised on known-good vanilla 1.19.4.1, Chaos Redux, Kaiserreich and Old World Blues files (benchmark sweeps of 1,027 files); the other 6 are real errors the game confirms. An in-game check (2026-11-02) settled each rule. A unit leader event runs with the general as ROOT and THIS, and accepts country commands as well, as vanilla options use them. `controller` is accepted in country scope and `capital_scope` in state scope. Event namespaces match in any letter case. An event id with a text suffix (vanilla `BBA_italy_missiolinis.02_north`) is no longer reported, only a number of 100000 or more, which the game confirms collides with the next namespace. `owner = ROOT` and other links used as triggers are still errors, which the game drops at load, now reported as `SCRIPT_SCOPE_LINK_AS_TRIGGER` naming `is_owned_by` or `is_controlled_by` (#67).
18
+ - `error_log` reads the active mods of the logged launch from `logs/system.log` (`data.launch`) and fails its check when that launch did not load the mod, instead of reporting no errors (#65). Every tool's text answer now lists the messages of failed checks (`failedChecks`), for clients that show only the text.
19
+ - `source_lookup` and `decision_inspect` answer an id that nothing defines with `SYMBOL_NOT_FOUND` or `DECISION_NOT_FOUND` and the close names, instead of an empty `ok` (#59).
20
+ - Evaluate the probability request that was asked. A sweep of a decision with `days_remove = -1` no longer runs as a mission, a sweep path with only a current value now spreads the requested `steps` over zero to twice that value (reported as `PROBABILITY_SWEEP_RANGE_DEFAULTED`), an adapter that matches nothing is refused with the adapters that do match instead of being replaced silently, a requested metric that cannot be computed gets a `PROBABILITY_METRIC_NOT_COMPUTED` reason (for example `cumulative_chance` without `horizonDays`), and `probability_inspect` with an event id and no adapter now evaluates the event's options. (#63)
21
+ - Stop `gui_inspect` reporting working GUI as defective. Sprite names returned by `defined_text` (`localization_key = GFX_...`) now resolve against the sprite inventory instead of raising `GUI_REFERENCE_UNRESOLVED`. A plain background, frame or fill image under an element it wholly contains is no longer a `GUI_VISIBLE_OVERLAP`. A meter fill image parked beyond the leading edge of its clip window is no longer `GUI_ACCIDENTAL_CLIPPING`. Inline diagnostics put errors before warnings when the list is truncated, so a flood of warnings cannot hide an error (#62)
22
+ - `gui_inspect` answers an unknown `windowName` with `GUI_WINDOW_NOT_FOUND`, naming the window, and writes no artifact. It used to return `ok` with a 116 MB inspection artifact on Chaos Redux (#59).
23
+ - Fix `event_inspect` focused routes (trace, explain_path, and selector-scoped scan, roots and lint) scanning only `events/` and `common/on_actions/`: scripted effects defined in `common/scripted_effects/` were reported as `EVENT_HELPER_UNRESOLVED`, and callers in scripted effects, decisions, focuses, ideas and the other event-bearing folders were never found, so upstream traces returned no callers and events looked callerless. Focused routes now scan every event-bearing folder and skip only localisation, and a trace summary names the entry points and scripted effects it passes through (#57, #58).
24
+ - `event_inspect` traces of an event that no scanned file defines or fires now fail with `EVENT_NOT_FOUND` and the close event ids, instead of an empty `ok` trace (#59).
25
+ - Check duplicate ids of every definition kind in the shared Rust engine (`hoi4-engine check`). `LINT_DUPLICATE_DEFINITION` now covers focuses (shared and joint ones included), ideas, decisions, characters and technologies as errors, the same localisation key twice in one language as a warning, and the same sprite twice as information. Advisor `idea_token`s repeated across a character's instances and keys under `localisation/replace/` are not duplicates. The new `LINT_DUPLICATE_ACROSS_LAYERS` reports an id that a dependency or the game also defines in a file the mod does not replace: an error for events, whose ids collide, and a warning otherwise. On Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 it raises no new error.
26
+
3
27
  ## 4.7.0 - 2026-11-02
4
28
 
5
29
  - Lay out focus trees with the shared Rust engine. `hoi4.focus_rewrite` takes `layoutMode: "engine"`, which places the tree's automatic focuses with `hoi4-engine focus-layout` and writes lane roots with x and y and every other placed focus with `relative_position_id`, and `placement` (`focusIds`, `anchorId`, `preferSide`, `allowShift`), which fits new focuses in while every other focus keeps its coordinates. The result adds the engine's metrics and hashes (`hashes.untouched` proves the other focuses did not move) to the layout verdict and delta. A blocked layout is refused with `needsRoom` and a missing engine with `FOCUS_ENGINE_UNAVAILABLE`, and nothing is written; there is no fallback to the TypeScript solver. The engine is found through `HOI4_ENGINE` or a binary shipped under `engine/bin`. `authored` and `compact` are unchanged.
package/README.md CHANGED
@@ -1,17 +1,36 @@
1
- # HOI4 Agent Tools
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/klimPaskov/hoi4-agent-tools/main/docs/images/logo.png" width="96" height="96" alt="HOI4 Agent Tools">
3
+ </p>
4
+
5
+ <h1 align="center">HOI4 Agent Tools</h1>
6
+
7
+ <p align="center">
8
+ An <a href="https://modelcontextprotocol.io/">MCP</a> server that helps coding agents build and edit <em>Hearts of Iron IV</em> mods.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/hoi4-agent-tools"><img alt="npm" src="https://img.shields.io/npm/v/hoi4-agent-tools"></a>
13
+ <a href="https://nodejs.org/"><img alt="Node.js" src="https://img.shields.io/node/v/hoi4-agent-tools"></a>
14
+ <a href="LICENSE"><img alt="License" src="https://img.shields.io/npm/l/hoi4-agent-tools"></a>
15
+ <a href="https://github.com/klimPaskov/hoi4-agent-tools/releases/latest"><img alt="Release" src="https://img.shields.io/github/v/release/klimPaskov/hoi4-agent-tools?label=Release&logo=github&color=2ea44f"></a>
16
+ <a href="https://discord.gg/rAXesGcT2t"><img alt="Discord" src="https://img.shields.io/badge/Discord-Join%20Community-7289da?logo=discord&logoColor=white"></a>
17
+ <a href="https://www.youtube.com/@ChaosRedux"><img alt="YouTube" src="https://img.shields.io/badge/YouTube-Chaos%20Redux-ff0000?logo=youtube&logoColor=white"></a>
18
+ <a href="https://ko-fi.com/klimpaskov"><img alt="Ko-fi" src="https://img.shields.io/badge/Ko--fi-Support%20the%20Project-ff5e5b?logo=kofi&logoColor=white"></a>
19
+ <a href="https://github.com/klimPaskov/hoi4-agent-tools/issues"><img alt="Issues" src="https://img.shields.io/badge/Bugs%20%26%20Ideas-Issues-24292f?logo=github&logoColor=white"></a>
20
+ </p>
21
+
22
+ <p align="center">
23
+ <a href="#quick-start">Quick start</a> ·
24
+ <a href="https://www.npmjs.com/package/hoi4-agent-tools">npm</a> ·
25
+ <a href="CHANGELOG.md">Changelog</a> ·
26
+ <a href="CONTRIBUTING.md">Contributing</a> ·
27
+ <a href="SECURITY.md">Security</a>
28
+ </p>
29
+
30
+ <p align="center">
31
+ <a href="https://www.youtube.com/watch?v=Dd36E_NK4rQ"><img src="https://raw.githubusercontent.com/klimPaskov/hoi4-agent-tools/main/docs/images/agent-tools-demo-thumbnail.png" alt="Watch the HOI4 Agent Tools demo"></a>
32
+ </p>
2
33
 
3
- [![Watch the HOI4 Agent Tools demo](https://raw.githubusercontent.com/klimPaskov/hoi4-agent-tools/main/docs/images/agent-tools-demo-thumbnail.png)](https://www.youtube.com/watch?v=Dd36E_NK4rQ)
4
-
5
- [![npm](https://img.shields.io/npm/v/hoi4-agent-tools)](https://www.npmjs.com/package/hoi4-agent-tools)
6
- [![Node.js](https://img.shields.io/node/v/hoi4-agent-tools)](https://nodejs.org/)
7
- [![License](https://img.shields.io/npm/l/hoi4-agent-tools)](LICENSE)
8
- [![Discord](https://img.shields.io/badge/Discord-Join%20Community-7289da?logo=discord&logoColor=white)](https://discord.gg/rAXesGcT2t)
9
- [![YouTube](https://img.shields.io/badge/YouTube-Chaos%20Redux-ff0000?logo=youtube&logoColor=white)](https://www.youtube.com/@ChaosRedux)
10
- [![Ko-fi](https://img.shields.io/badge/Ko--fi-Support%20the%20Project-ff5e5b?logo=kofi&logoColor=white)](https://ko-fi.com/klimpaskov)
11
- [![Download](https://img.shields.io/github/v/release/klimPaskov/hoi4-agent-tools?label=Release&logo=github&color=2ea44f)](https://github.com/klimPaskov/hoi4-agent-tools/releases/latest)
12
- [![Issues](https://img.shields.io/badge/Bugs%20%26%20Ideas-Issues-24292f?logo=github&logoColor=white)](https://github.com/klimPaskov/hoi4-agent-tools/issues)
13
-
14
- An [MCP](https://modelcontextprotocol.io/) server that helps coding agents build and edit Hearts of Iron IV mods.
15
34
  Make focus trees, events and decisions. Edit maps and generate a new world. Preview windows, trees and maps, find the right rule in the docs, fix broken script and balance AI choices.
16
35
 
17
36
  ## What it does
@@ -1,5 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { statSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, statSync } from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
5
6
  import { z } from 'zod/v4';
@@ -26,13 +27,78 @@ function isFile(candidate) {
26
27
  return false;
27
28
  }
28
29
  }
30
+ export const ENGINE_BUNDLE_MANIFEST_SCHEMA = 'hoi4-engine-bundle/1';
31
+ /** `engine/bin/manifest.json`: the SHA-256 and size of every bundled binary, keyed by `<platform>-<arch>`. */
32
+ export const engineBundleManifestSchema = z.strictObject({
33
+ schema: z.literal(ENGINE_BUNDLE_MANIFEST_SCHEMA),
34
+ engineVersion: z.string().min(1),
35
+ binaries: z.record(z.string().regex(/^[a-z0-9]+-[a-z0-9]+$/u), z.strictObject({
36
+ file: z.string().regex(/^[a-z0-9]+-[a-z0-9]+\/hoi4-engine(?:\.exe)?$/u),
37
+ sha256: z.string().regex(/^[0-9a-f]{64}$/u),
38
+ size: z.number().int().positive(),
39
+ })),
40
+ });
41
+ export function engineBundleManifestPath(packageRoot = defaultPackageRoot()) {
42
+ return path.join(packageRoot, 'engine', 'bin', 'manifest.json');
43
+ }
44
+ /** Hashes already checked in this process, keyed by path; a changed size or time is hashed again. */
45
+ const verifiedBinaries = new Map();
46
+ function sha256OfFile(file) {
47
+ const stat = statSync(file);
48
+ const known = verifiedBinaries.get(file);
49
+ if (known?.size === stat.size && known.mtimeMs === stat.mtimeMs)
50
+ return known.sha256;
51
+ const sha256 = createHash('sha256').update(readFileSync(file)).digest('hex');
52
+ verifiedBinaries.set(file, { size: stat.size, mtimeMs: stat.mtimeMs, sha256 });
53
+ return sha256;
54
+ }
55
+ /**
56
+ * A bundled binary runs only when the package's manifest lists it with the same SHA-256, so a
57
+ * damaged or replaced file is reported instead of run.
58
+ */
59
+ function verifyPackagedBinary(packageRoot, binary) {
60
+ const key = `${process.platform}-${process.arch}`;
61
+ let manifest;
62
+ try {
63
+ manifest = engineBundleManifestSchema.parse(JSON.parse(readFileSync(engineBundleManifestPath(packageRoot), 'utf8')));
64
+ }
65
+ catch {
66
+ return {
67
+ reason: 'binary_checksum_mismatch',
68
+ message: `The bundled hoi4-engine for ${key} has no valid engine/bin/manifest.json to check it against`,
69
+ };
70
+ }
71
+ const entry = manifest.binaries[key];
72
+ if (entry === undefined)
73
+ return {
74
+ reason: 'binary_checksum_mismatch',
75
+ message: `engine/bin/manifest.json lists no hoi4-engine for ${key}`,
76
+ };
77
+ let sha256;
78
+ try {
79
+ sha256 = sha256OfFile(binary);
80
+ }
81
+ catch {
82
+ return {
83
+ reason: 'binary_not_found',
84
+ message: `The bundled hoi4-engine for ${key} cannot be read`,
85
+ };
86
+ }
87
+ if (sha256 !== entry.sha256)
88
+ return {
89
+ reason: 'binary_checksum_mismatch',
90
+ message: `The bundled hoi4-engine for ${key} does not match the SHA-256 in engine/bin/manifest.json; reinstall hoi4-agent-tools`,
91
+ };
92
+ return undefined;
93
+ }
29
94
  /** The bundled binary's path for this platform, whether or not it exists. */
30
95
  export function packagedEngineBinaryPath(packageRoot = defaultPackageRoot(), platform = process.platform, arch = process.arch) {
31
96
  return path.join(packageRoot, 'engine', 'bin', `${platform}-${arch}`, platform === 'win32' ? 'hoi4-engine.exe' : 'hoi4-engine');
32
97
  }
33
98
  /**
34
99
  * `HOI4_ENGINE` (an absolute path) wins; a set but unusable `HOI4_ENGINE` is reported instead of
35
- * silently using the bundled binary. Otherwise the package's own `engine/bin` binary, if present.
100
+ * silently using the bundled binary. Otherwise the package's own `engine/bin` binary, if present
101
+ * and matching the SHA-256 in `engine/bin/manifest.json`.
36
102
  */
37
103
  export function locateEngineBinary(options = {}) {
38
104
  const configured = (options.env ?? process.env)[ENGINE_BINARY_ENV];
@@ -49,9 +115,12 @@ export function locateEngineBinary(options = {}) {
49
115
  };
50
116
  return { path: configured, source: 'environment' };
51
117
  }
52
- const packaged = packagedEngineBinaryPath(options.packageRoot ?? defaultPackageRoot());
53
- if (isFile(packaged))
54
- return { path: packaged, source: 'package' };
118
+ const packageRoot = options.packageRoot ?? defaultPackageRoot();
119
+ const packaged = packagedEngineBinaryPath(packageRoot);
120
+ if (isFile(packaged)) {
121
+ const rejected = verifyPackagedBinary(packageRoot, packaged);
122
+ return rejected ?? { path: packaged, source: 'package' };
123
+ }
55
124
  return {
56
125
  reason: 'binary_not_found',
57
126
  message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
@@ -448,6 +448,15 @@ function buildToolResult(selected, imageCount = 0) {
448
448
  ...(selected.artifacts.length > shown.length
449
449
  ? { artifactsListedInStructuredContent: selected.artifacts.length }
450
450
  : {}),
451
+ // Clients that show only the text still see why a check failed.
452
+ ...(selected.validation.checks.some(({ passed }) => !passed)
453
+ ? {
454
+ failedChecks: selected.validation.checks
455
+ .filter(({ passed }) => !passed)
456
+ .slice(0, 3)
457
+ .map(({ message }) => message.slice(0, 300)),
458
+ }
459
+ : {}),
451
460
  ...(selected.status === 'ok' || selected.blockers.length === 0
452
461
  ? {}
453
462
  : {
@@ -0,0 +1,273 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { locateEngineBinary, } from './engine-client.js';
3
+ /**
4
+ * The resident engine (`hoi4-engine serve`, ADR 0074): one long-lived engine process per server
5
+ * that keeps its caches between calls. Requests and responses are frames: a JSON line, then the
6
+ * raw bytes its `payload` field counts. Requests run in parallel inside the engine and are matched
7
+ * to responses by id.
8
+ *
9
+ * The process is started on first use and kept until the server exits, with no idle eviction. A
10
+ * crash fails the requests in flight and the next request starts a fresh process; after
11
+ * `RESIDENT_ENGINE_MAX_RESTARTS` crashes in a row the engine is reported unavailable.
12
+ */
13
+ export const RESIDENT_ENGINE_PROTOCOL = 1;
14
+ export const RESIDENT_ENGINE_TIMEOUT_MS = 120_000;
15
+ export const RESIDENT_ENGINE_MAX_RESTARTS = 3;
16
+ /** The largest response header line; payloads are bounded by `maxPayloadBytes`. */
17
+ const RESIDENT_ENGINE_MAX_HEADER_BYTES = 1024 * 1024;
18
+ const RESIDENT_ENGINE_MAX_PAYLOAD_BYTES = 512 * 1024 * 1024;
19
+ const STDERR_TAIL_BYTES = 4096;
20
+ export class ResidentEngine {
21
+ options;
22
+ child;
23
+ binary;
24
+ pending = new Map();
25
+ nextId = 1;
26
+ buffered = [];
27
+ bufferedBytes = 0;
28
+ header;
29
+ stderrTail = '';
30
+ crashes = 0;
31
+ closed = false;
32
+ constructor(options = {}) {
33
+ this.options = options;
34
+ }
35
+ /** The binary in use, once a request has started the process. */
36
+ get location() {
37
+ return this.binary;
38
+ }
39
+ /** Whether a binary can be found, without starting it. */
40
+ available() {
41
+ return 'path' in locateEngineBinary(this.options);
42
+ }
43
+ async request(op, body = {}, payload, options = {}) {
44
+ options.signal?.throwIfAborted();
45
+ if (this.closed)
46
+ return { ok: false, kind: 'unavailable', reason: 'spawn_failed', message: 'closed' };
47
+ const started = this.ensureStarted();
48
+ if (started !== undefined)
49
+ return started;
50
+ const child = this.child;
51
+ const id = this.nextId++;
52
+ const timeoutMs = options.timeoutMs ?? RESIDENT_ENGINE_TIMEOUT_MS;
53
+ return new Promise((resolve, reject) => {
54
+ const entry = {
55
+ resolve,
56
+ timer: setTimeout(() => {
57
+ this.settle(id, {
58
+ ok: false,
59
+ kind: 'unavailable',
60
+ reason: 'timeout',
61
+ message: `hoi4-engine ${op} did not answer within ${timeoutMs} ms`,
62
+ });
63
+ }, timeoutMs),
64
+ };
65
+ if (options.signal !== undefined) {
66
+ const signal = options.signal;
67
+ entry.signal = signal;
68
+ entry.onAbort = () => {
69
+ const current = this.pending.get(id);
70
+ if (current === undefined)
71
+ return;
72
+ clearTimeout(current.timer);
73
+ this.pending.delete(id);
74
+ this.updateRef();
75
+ const reason = signal.reason;
76
+ reject(reason instanceof Error ? reason : new Error('The engine request was cancelled'));
77
+ };
78
+ signal.addEventListener('abort', entry.onAbort, { once: true });
79
+ }
80
+ this.pending.set(id, entry);
81
+ this.updateRef();
82
+ const line = `${JSON.stringify({ ...body, id, op, payload: payload?.length ?? 0 })}\n`;
83
+ child.stdin.write(line);
84
+ if (payload !== undefined && payload.length > 0)
85
+ child.stdin.write(payload);
86
+ });
87
+ }
88
+ /** Stops the process; requests in flight fail as unavailable. */
89
+ close() {
90
+ this.closed = true;
91
+ this.stop('the resident engine was closed');
92
+ }
93
+ ensureStarted() {
94
+ if (this.child !== undefined)
95
+ return undefined;
96
+ if (this.crashes >= RESIDENT_ENGINE_MAX_RESTARTS)
97
+ return {
98
+ ok: false,
99
+ kind: 'unavailable',
100
+ reason: 'exit_status',
101
+ message: `hoi4-engine serve stopped ${this.crashes} times in a row: ${this.stderrTail.trim().slice(-300)}`,
102
+ };
103
+ const located = locateEngineBinary(this.options);
104
+ if (!('path' in located))
105
+ return { ok: false, kind: 'unavailable', reason: located.reason, message: located.message };
106
+ this.binary = located;
107
+ // A JavaScript engine (a development wrapper or a test double) runs under this Node.
108
+ const script = /\.(?:c|m)?js$/iu.test(located.path);
109
+ let child;
110
+ try {
111
+ child = spawn(script ? process.execPath : located.path, script ? [located.path, 'serve'] : ['serve'], {
112
+ shell: false,
113
+ windowsHide: true,
114
+ env: this.options.env ?? process.env,
115
+ stdio: ['pipe', 'pipe', 'pipe'],
116
+ });
117
+ }
118
+ catch (error) {
119
+ return {
120
+ ok: false,
121
+ kind: 'unavailable',
122
+ reason: 'spawn_failed',
123
+ message: error instanceof Error ? error.message : String(error),
124
+ };
125
+ }
126
+ this.child = child;
127
+ this.buffered = [];
128
+ this.bufferedBytes = 0;
129
+ this.header = undefined;
130
+ child.stdout.on('data', (chunk) => this.onData(child, chunk));
131
+ child.stderr.on('data', (chunk) => {
132
+ this.stderrTail = `${this.stderrTail}${chunk.toString('utf8')}`.slice(-STDERR_TAIL_BYTES);
133
+ });
134
+ child.stdin.on('error', () => undefined);
135
+ child.on('error', (error) => this.onExit(child, `hoi4-engine serve failed: ${error.message}`));
136
+ child.on('close', (code, signal) => this.onExit(child, `hoi4-engine serve exited with ${code === null ? `signal ${signal ?? 'unknown'}` : `code ${code}`}`));
137
+ this.updateRef();
138
+ return undefined;
139
+ }
140
+ /** Keeps Node alive only while a request waits, so an idle engine never holds the server open. */
141
+ updateRef() {
142
+ const child = this.child;
143
+ if (child === undefined)
144
+ return;
145
+ const waiting = this.pending.size > 0;
146
+ if (waiting)
147
+ child.ref();
148
+ else
149
+ child.unref();
150
+ // The pipes are sockets at run time, which Node's stream types do not say.
151
+ for (const stream of [child.stdout, child.stderr, child.stdin]) {
152
+ const socket = stream;
153
+ if (waiting)
154
+ socket.ref?.();
155
+ else
156
+ socket.unref?.();
157
+ }
158
+ }
159
+ take(bytes) {
160
+ const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
161
+ const head = all.subarray(0, bytes);
162
+ const rest = all.subarray(bytes);
163
+ this.buffered = rest.length === 0 ? [] : [rest];
164
+ this.bufferedBytes = rest.length;
165
+ return head;
166
+ }
167
+ onData(child, chunk) {
168
+ if (child !== this.child)
169
+ return;
170
+ this.buffered.push(chunk);
171
+ this.bufferedBytes += chunk.length;
172
+ for (;;) {
173
+ if (this.header === undefined) {
174
+ const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
175
+ this.buffered = all.length === 0 ? [] : [all];
176
+ const newline = all.indexOf(0x0a);
177
+ if (newline < 0) {
178
+ if (all.length > RESIDENT_ENGINE_MAX_HEADER_BYTES)
179
+ this.stop('hoi4-engine serve printed an oversized response header');
180
+ return;
181
+ }
182
+ const line = this.take(newline + 1).toString('utf8');
183
+ let body;
184
+ try {
185
+ body = JSON.parse(line);
186
+ }
187
+ catch {
188
+ this.stop('hoi4-engine serve printed a response that is not JSON');
189
+ return;
190
+ }
191
+ const id = typeof body.id === 'number' ? body.id : -1;
192
+ const payload = body.ok === true && typeof body.payload === 'number' ? body.payload : 0;
193
+ if (!Number.isSafeInteger(payload) ||
194
+ payload < 0 ||
195
+ payload > RESIDENT_ENGINE_MAX_PAYLOAD_BYTES) {
196
+ this.stop('hoi4-engine serve announced an invalid payload size');
197
+ return;
198
+ }
199
+ this.header = { id, body, payload };
200
+ }
201
+ const header = this.header;
202
+ if (this.bufferedBytes < header.payload)
203
+ return;
204
+ const payload = header.payload === 0 ? Buffer.alloc(0) : Buffer.from(this.take(header.payload));
205
+ this.header = undefined;
206
+ this.crashes = 0;
207
+ const body = header.body;
208
+ if (body.ok === true) {
209
+ const result = typeof body.result === 'object' && body.result !== null
210
+ ? body.result
211
+ : {};
212
+ this.settle(header.id, { ok: true, response: { result, payload } });
213
+ }
214
+ else {
215
+ const error = typeof body.error === 'object' && body.error !== null
216
+ ? body.error
217
+ : {};
218
+ const { code, message, ...details } = error;
219
+ this.settle(header.id, {
220
+ ok: false,
221
+ kind: 'error',
222
+ code: typeof code === 'string' ? code : 'error',
223
+ message: typeof message === 'string' ? message : 'the engine reported an error',
224
+ details,
225
+ });
226
+ }
227
+ }
228
+ }
229
+ settle(id, outcome) {
230
+ const entry = this.pending.get(id);
231
+ if (entry === undefined)
232
+ return;
233
+ clearTimeout(entry.timer);
234
+ if (entry.onAbort !== undefined)
235
+ entry.signal?.removeEventListener('abort', entry.onAbort);
236
+ this.pending.delete(id);
237
+ this.updateRef();
238
+ entry.resolve(outcome);
239
+ }
240
+ onExit(child, message) {
241
+ if (child !== this.child)
242
+ return;
243
+ this.child = undefined;
244
+ if (!this.closed)
245
+ this.crashes += 1;
246
+ this.failAll(`${message}${this.stderrTail.trim() === '' ? '' : `: ${this.stderrTail.trim().slice(-300)}`}`);
247
+ }
248
+ stop(message) {
249
+ const child = this.child;
250
+ this.child = undefined;
251
+ if (child !== undefined) {
252
+ if (!this.closed)
253
+ this.crashes += 1;
254
+ child.kill();
255
+ }
256
+ this.failAll(message);
257
+ }
258
+ failAll(message) {
259
+ for (const id of [...this.pending.keys()])
260
+ this.settle(id, { ok: false, kind: 'unavailable', reason: 'exit_status', message });
261
+ }
262
+ }
263
+ let shared;
264
+ /** The server-wide resident engine (one process per server). */
265
+ export function sharedResidentEngine() {
266
+ shared ??= new ResidentEngine();
267
+ return shared;
268
+ }
269
+ /** Test hook: replaces the shared engine and closes the old one. */
270
+ export function replaceSharedResidentEngine(engine) {
271
+ shared?.close();
272
+ shared = engine;
273
+ }
@@ -167,7 +167,7 @@ export async function sweepTemporaryDirectories(parent, options = {}) {
167
167
  continue;
168
168
  await lock.close();
169
169
  lock = undefined;
170
- await rm(entry.directory, { recursive: true, force: true });
170
+ await rm(entry.directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
171
171
  retainedBytes -= entry.bytes;
172
172
  removed += 1;
173
173
  }
@@ -265,7 +265,8 @@ export class TemporaryDirectoryLifetime {
265
265
  }
266
266
  if ((await lstat(directory)).isSymbolicLink() || (await realpath(directory)) !== directory)
267
267
  throw new Error('Temporary directory changed before cleanup');
268
- await rm(directory, { recursive: true, force: true });
268
+ // Windows can hold a file a closed process wrote for a moment (ENOTEMPTY, EBUSY).
269
+ await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
269
270
  this.#owned.delete(directory);
270
271
  this.#forgetFiles(directory);
271
272
  }
@@ -4,6 +4,7 @@ import { canonicalJson, hashCanonical } from '../core/canonical.js';
4
4
  import { setInlineFilesScanned } from '../core/operation-result.js';
5
5
  import { emptyServiceResult, ServiceError } from '../core/result.js';
6
6
  import { buildProposedSourceOverlay } from '../core/source-overlay.js';
7
+ import { nearestNames } from '../reference/suggestions.js';
7
8
  import { PACKAGE_VERSION } from '../version.js';
8
9
  import { inspectDecisionAi } from './ai.js';
9
10
  import { compareDecisionScenarios, inspectDecisionScenario } from './comparison.js';
@@ -33,6 +34,12 @@ export class DecisionAnalyzer {
33
34
  if (input.mode !== 'compare' && input.proposedSources !== undefined)
34
35
  throw new ServiceError('DECISION_PROPOSAL_MODE', 'Proposed sources require compare mode');
35
36
  const inventory = decisionSourceInventory(before);
37
+ if (input.mode === 'inspect' &&
38
+ input.id !== undefined &&
39
+ !inventory.decisions.some((source) => source.id === input.id)) {
40
+ const suggestions = nearestNames(input.id, new Set(inventory.decisions.map((source) => source.id)));
41
+ throw new ServiceError('DECISION_NOT_FOUND', `No decision ${input.id.slice(0, 256)} is defined${before.complete ? '' : ' in the scanned files (the scan is incomplete)'}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: input.id.slice(0, 256), suggestions, scanComplete: before.complete });
42
+ }
36
43
  const overlay = input.proposedSources === undefined
37
44
  ? undefined
38
45
  : buildProposedSourceOverlay(before, workspace, input.proposedSources);
@@ -6,6 +6,7 @@ import { canonicalJson, canonicalJsonByteLength, compareCodeUnits, hashCanonical
6
6
  import { installedEffectCommands } from '../core/game-documentation.js';
7
7
  import { boundedSourceHashEvidence, publicArtifactLink, } from '../core/artifacts.js';
8
8
  import { ServiceError } from '../core/result.js';
9
+ import { nearestNames } from '../reference/suggestions.js';
9
10
  import { RenderBudget } from '../core/render-budget.js';
10
11
  import { SOURCE_MAX_BYTES } from '../core/source/index.js';
11
12
  import { isPortablePathSegment } from '../core/workspace.js';
@@ -13,7 +14,7 @@ import { PACKAGE_VERSION } from '../version.js';
13
14
  import { buildEventGraph, buildEventGraphAsync } from './graph.js';
14
15
  import { summarizeEventImpact, summarizeEventIssues, summarizeEventPath, summarizeEventRoots, summarizeEventTrace, } from './summary.js';
15
16
  import { EVENT_FRAGMENT_CACHE_MAX_ENTRIES, EVENT_FRAGMENT_CACHE_MAX_SOURCE_BYTES, EVENT_GRAPH_SNAPSHOT_MAX_BYTES, EVENT_PROPOSED_SOURCE_MAX_BYTES, EVENT_PROPOSED_SOURCE_MAX_FILES, } from './limits.js';
16
- import { analyzeEventImpact, discoverEventRoots, explainEventPath, inspectEventStateFlow, lintEventGraph, traceSelectedEvents, } from './queries.js';
17
+ import { analyzeEventImpact, discoverEventRoots, explainEventPath, inspectEventStateFlow, lintEventGraph, selectEventNodes, traceSelectedEvents, } from './queries.js';
17
18
  import { compareEventGraphs, eventGraphHash } from './compare.js';
18
19
  import { selectEventComparison } from './comparison-selection.js';
19
20
  import { eventFlowEdges } from './algorithms.js';
@@ -161,9 +162,15 @@ function engineGeneration(engine, workspaceId) {
161
162
  function eventScanPatterns(workspace, focused = false) {
162
163
  const roots = workspace.registration.roots;
163
164
  const under = (values, glob) => values.map((root) => `${root.replaceAll('\\', '/').replace(/\/$/u, '')}/${glob}`);
164
- if (focused) {
165
- return ['events/**/*.txt', 'common/on_actions/**/*.txt'].sort(compareCodeUnits);
166
- }
165
+ // A focused route still resolves scripted-effect helpers and follows callers back through
166
+ // them, so it scans every folder that can define or call one. Only localisation, which
167
+ // feeds the skipped lint passes, is left out.
168
+ const localisation = focused
169
+ ? []
170
+ : [
171
+ ...under(roots.localisation, 'english/**/*.{yml,yaml}'),
172
+ ...under(roots.localisation, '*.{yml,yaml}'),
173
+ ];
167
174
  return [
168
175
  'events/**/*.txt',
169
176
  'history/countries/**/*.txt',
@@ -182,8 +189,7 @@ function eventScanPatterns(workspace, focused = false) {
182
189
  'common/scripted_effects/**/*.txt',
183
190
  ...under(roots.focus, '**/*.txt'),
184
191
  ...under(roots.scriptedGui, '**/*.txt'),
185
- ...under(roots.localisation, 'english/**/*.{yml,yaml}'),
186
- ...under(roots.localisation, '*.{yml,yaml}'),
192
+ ...localisation,
187
193
  ].sort(compareCodeUnits);
188
194
  }
189
195
  async function scanEventSources(engine, workspaceId, workspace, focused = false, signal) {
@@ -854,6 +860,12 @@ export class EventChainViewer {
854
860
  case 'trace':
855
861
  if (input.selector === undefined)
856
862
  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
+ }
857
869
  {
858
870
  const trace = traceSelectedEvents(graph, input.selector, {
859
871
  maxDepth,
@@ -3,6 +3,7 @@ import { compareCodeUnits } from '../core/canonical.js';
3
3
  export const EVENT_INLINE_FINDINGS = 10;
4
4
  const EVENT_INLINE_CODES = 10;
5
5
  const EVENT_INLINE_EVENT_IDS = 20;
6
+ const EVENT_INLINE_TRACE_NAMES = 20;
6
7
  const EVENT_INLINE_MESSAGE_LENGTH = 300;
7
8
  const CLASSIFICATION_ORDER = {
8
9
  confirmed_error: 0,
@@ -72,11 +73,19 @@ export function summarizeEventTrace(trace) {
72
73
  const events = trace.nodes
73
74
  .flatMap(({ kind, eventId }) => (kind === 'event' && eventId !== undefined ? [eventId] : []))
74
75
  .sort(compareCodeUnits);
76
+ // Callers that reach an event through scripted effects, decisions or focuses are not events,
77
+ // so name them here as well. Otherwise an upstream trace looks callerless without its report.
78
+ const entries = [
79
+ ...new Set(trace.nodes.flatMap(({ kind, label }) => (kind === 'entry' ? [label] : []))),
80
+ ].sort(compareCodeUnits);
81
+ const helpers = [...new Set(trace.edges.flatMap(({ helperStack }) => helperStack))].sort(compareCodeUnits);
75
82
  return {
76
83
  nodes: trace.nodes.length,
77
84
  edges: trace.edges.length,
78
85
  events: events.length,
79
86
  eventIds: events.slice(0, EVENT_INLINE_EVENT_IDS),
87
+ entryPoints: entries.slice(0, EVENT_INLINE_TRACE_NAMES),
88
+ helpers: helpers.slice(0, EVENT_INLINE_TRACE_NAMES),
80
89
  boundaryNodes: trace.boundaryNodeIds.length,
81
90
  truncated: trace.truncated,
82
91
  };
@@ -1,7 +1,7 @@
1
1
  import { FOCUS_LAYOUT_REQUEST_SCHEMA, runFocusLayoutEngine, } from '../core/engine-client.js';
2
2
  import { ServiceError } from '../core/result.js';
3
3
  import { focusLaneId } from './layout.js';
4
- export const FOCUS_ENGINE_REMEDY = 'Set HOI4_ENGINE to the absolute path of a hoi4-engine binary (cargo build --release -p hoi4-engine-cli in engine/), or install a hoi4-agent-tools release that ships the engine for this platform. layoutMode authored and compact do not need it.';
4
+ export const FOCUS_ENGINE_REMEDY = 'The package bundles hoi4-engine for Windows x64, macOS arm64 and Linux x64 and arm64; reinstall it if the bundled binary fails its checksum. Elsewhere, set HOI4_ENGINE to the absolute path of a hoi4-engine binary (cargo build --release -p hoi4-engine-cli in engine/). layoutMode authored and compact do not need it.';
5
5
  const MOVED_FOCUS_ID_LIMIT = 100;
6
6
  function enginePosition(position) {
7
7
  if (position.mode === 'fixed')