hoi4-agent-tools 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
  7. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  8. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  9. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  10. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  11. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  12. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  13. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  14. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  15. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  16. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  17. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  18. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  19. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  20. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  21. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  22. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  23. package/dist/hoi4_agent_tools/map/model.js +9 -8
  24. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  25. package/dist/hoi4_agent_tools/map/operations.js +266 -23
  26. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  27. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  28. package/dist/hoi4_agent_tools/map/service.js +25 -12
  29. package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
  30. package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
  31. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  32. package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  34. package/dist/hoi4_agent_tools/map/water.js +13 -10
  35. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  36. package/dist/hoi4_agent_tools/map/world.js +51 -1
  37. package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
  38. package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
  39. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  40. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  41. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  42. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  43. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  44. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  45. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  46. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  47. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  48. package/dist/hoi4_agent_tools/runtime.js +27 -11
  49. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  50. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  51. package/dist/hoi4_agent_tools/schemas/map.js +103 -2
  52. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  53. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  54. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  55. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  56. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  57. package/dist/hoi4_agent_tools/version.js +1 -1
  58. package/docs/configuration.md +1 -1
  59. package/docs/map.md +67 -23
  60. package/docs/research/reference-benchmark.md +64 -0
  61. package/docs/tools.md +20 -20
  62. package/docs/troubleshooting.md +4 -0
  63. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  64. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  65. package/engine/bin/linux-x64/hoi4-engine +0 -0
  66. package/engine/bin/manifest.json +8 -8
  67. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +5 -3
  70. package/schemas/configuration.schema.json +1 -1
  71. package/schemas/continuous-focus-palette.schema.json +1 -1
  72. package/schemas/custom-weighted-pool.schema.json +1 -1
  73. package/schemas/decision-inspect-input.schema.json +1 -1
  74. package/schemas/error-log-input.schema.json +1 -1
  75. package/schemas/event-feature-manifest.schema.json +1 -1
  76. package/schemas/focus-plan.schema.json +1 -1
  77. package/schemas/focus-planning-sidecar.schema.json +1 -1
  78. package/schemas/geography-model.schema.json +1 -1
  79. package/schemas/gui-animation-source.schema.json +1 -1
  80. package/schemas/gui-helper.schema.json +1 -1
  81. package/schemas/gui-scenario.schema.json +1 -1
  82. package/schemas/helper-expansion-request.schema.json +1 -1
  83. package/schemas/helper-expansion-summary.schema.json +1 -1
  84. package/schemas/impact-inspect-input.schema.json +1 -1
  85. package/schemas/map-operation.schema.json +1087 -815
  86. package/schemas/mechanic-test-input.schema.json +1 -1
  87. package/schemas/mod-index-input.schema.json +1 -1
  88. package/schemas/operation-result.schema.json +1 -1
  89. package/schemas/package-check-input.schema.json +1 -1
  90. package/schemas/package-manifest.schema.json +1 -1
  91. package/schemas/probability-analysis-result.schema.json +1 -1
  92. package/schemas/probability-compare-input.schema.json +1 -1
  93. package/schemas/probability-evaluate-input.schema.json +1 -1
  94. package/schemas/probability-inspect-input.schema.json +1 -1
  95. package/schemas/probability-render-input.schema.json +1 -1
  96. package/schemas/probability-scenario-set.schema.json +1 -1
  97. package/schemas/probability-sequence-input.schema.json +1 -1
  98. package/schemas/probability-simulate-input.schema.json +1 -1
  99. package/schemas/probability-sweep-input.schema.json +1 -1
  100. package/schemas/reference-context-input.schema.json +1 -1
  101. package/schemas/reference-read-input.schema.json +1 -1
  102. package/schemas/reference-search-input.schema.json +2 -2
  103. package/schemas/reference-sheets.schema.json +1 -1
  104. package/schemas/scenario-suite.schema.json +1 -1
  105. package/schemas/scenario-test-input.schema.json +1 -1
  106. package/schemas/script-validate-input.schema.json +7 -1
  107. package/schemas/shared-scenario.schema.json +1 -1
  108. package/schemas/source-lookup-input.schema.json +1 -1
  109. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,47 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.18.0 - 2026-11-14
6
+
7
+ - A focused `hoi4.event_inspect` trace or path that answers its question is now `EVENT_INSPECTED`, not `EVENT_INSPECTED_PARTIAL` (issue 66, ADR 0086). The partial code was set for every trace and path on every workspace, because the focused analysis defers the whole-workspace helper and lifecycle passes, so an agent could not tell a complete 7-node trace from a cut one. A trace cut by a limit, with a node on its boundary or with a skipped source, stays partial and says where (`summary.trace.truncated`, `boundaryNodes`). The rule is: a result is partial only when something the answer needs is missing.
8
+ - A focused `hoi4.event_inspect` trace or path no longer fails its `validation.passed` because of blocking diagnostics in unrelated files (issue 66, ADR 0086). It counts those in the files of the events it covers and names how many sit elsewhere in the workspace in the check message, so a clean `news.1` trace in vanilla is not reported as failing for two unrelated diagnostics. Every other event answer still counts the whole workspace.
9
+ - A partial `hoi4.event_inspect` result now says what is missing (issue 66, ADR 0086). `EVENT_INSPECTED_PARTIAL` carries an inline information diagnostic: `EVENT_TRACE_TRUNCATED` when a trace stopped at its limits (raise `maxDepth` or `maxNodes`), `EVENT_SOURCES_SKIPPED` with the count of skipped files, `EVENT_HELPER_EXPANSION_INCOMPLETE`, or `EVENT_FOCUSED_ANALYSIS_DEFERRED` when a large workspace defers the workspace-wide helper projections and state links, so that `roots` and `state_flow` answers may miss callers or links that exist only inside scripted effects. Before, a partial result gave no reason.
10
+ - Keep the `hoi4.mod_index` overview inline (issue 66). On vanilla, Kaiserreich, Old World Blues, ZIN and Chaos Redux the overview took 14 to 22 KB, mostly 200 namespaces listed alphabetically. It now lists the 50 busiest namespaces (the most events first, printed in alphabetical order) and the 25 busiest folders, in about 6 KB, and says how many namespaces it left out. Pass `namespace` or `prefix` with `mode: "overview"` to list the namespaces that start with it (up to 100).
11
+ - Add natural lands to `hoi4.map_inspect` (`lands: true`, thresholds in `landOptions`). Redrawing country borders along natural lines needs the land cut into the pieces its ground suggests, which a map lane did by hand in scratch scripts. The inspection now cuts the land provinces along major rivers (`rivers.bmp` width index 6 and up on at least 40% of a border), crests (the mean height along a border at least 3.5 above the higher province) and changes of terrain class (forest, hills and mountain, marsh, desert, open). It cuts open country into drainage basins (coasts and lakes are sinks, small basins merge over their lowest pass, and `maxBasinProvinces` splits big ones at branch points of the drainage tree), and merges lands below `minProvinces` (6) across their weakest line. Impassable borders are hard lines: an `impassable` adjacency, the edge of an `impassable = yes` state, or (for callers with a barrier plane) a 255 wall. Their two sides are never in the same land and no merge crosses them. `data.lands` gives the count per kind (`basin`, `range`, `forest`, `marsh`, `desert`, `plains`) and the first 50 lands; `map-natural-lands.<revision>.json` holds every land with its provinces, terrain shares, coast and the river, crest, terrain, impassable and divide lengths of its lines to each neighbour. `assign_territory` accepts the lands as `landIds` in `forced`, `blocked`, `cores`, `claims` and `unowned`, and `{ land }` as a seed, cut with the operation's `landOptions`. The ranges of a geography model, moving uplands to the side they drain to, and closed basins (rings) are not covered yet.
12
+ - Measure border quality in one region. `hoi4.map_inspect` takes `qualityScope` with `quality`, and `assign_territory` and `repartition_states` take `borderQualityScope`. Each has `owners`, `stateIds` and a pixel `box`: owners and states add provinces, and the box cuts. A border pixel pair, and the chance baseline, count when either side is inside, so a country is measured against its neighbours. Before, the measurement always covered the whole map, so a redrawn region could not be compared before and after; the ZIN map lane asked for this. The result gives `scopePixels`, and the territory note says `inside the scope`. A scope that selects nothing is `MAP_BORDER_QUALITY_UNAVAILABLE` with the reason `MAP_BORDER_QUALITY_SCOPE_EMPTY`, a blocker in `enforce`. Requests without a scope measure as before.
13
+ - A map write no longer leaves a state id without a state (issue 182). The game needs every id from 1 to the highest and crashes at setup on a missing one; `merge_states` left the merged-away ids empty and `assign_territory` the ids of the states it dissolved (21 holes in one mod). Now the highest states move into the holes the write made, in the same write, with their script references, building positions and `STATE_<id>` localisation (the removed state's key is taken over), and the result lists the moves in `MAP_STATE_IDS_COMPACTED`. A state id the request names is never moved, and a named id that would leave holes below it is refused with `MAP_STATE_ID_GAP`. Holes the mod already had are reported as a `MAP_STATE_ID_GAP` warning with the ids and the `renumber_map_entity` fix; the write still runs, so they can be closed. On Linux the game crashes on such holes during history setup (SIGSEGV), so this is a crash fix.
14
+ - Move building positions off a state a write removes (issue 182). `merge_states` and the states `assign_territory` dissolves left `map/buildings.txt` lines, such as floating harbours, naming the deleted state id. Each such line now names the state that holds its province (its last field, else the province under its map coordinates), reported in `MAP_BUILDING_POSITIONS_REASSIGNED`; a line no state holds is reported as `MAP_BUILDING_POSITION_STATE_MISSING`.
15
+ - A tool reply cut to the 32 KiB inline budget keeps the first changed and proposed files and reports the totals (`changedFilesTotal`, `changedFilesShown`, `proposedFilesTotal`, `proposedFilesShown`, `filesScannedTotal` in `MCP_RESPONSE_TRUNCATED`), instead of empty lists (issue 185). A map write that changed several hundred files answered `changedFiles: []`, which reads as a write that changed nothing.
16
+
17
+ ## 4.17.0 - 2026-11-14
18
+
19
+ - `hoi4.map_inspect` names its matches inline: `data.matches` lists the first 20 query matches (kind, id, key and name, best first) and `data.coordinateMatches` what each requested coordinate falls in (province, states, regions). It only counted them, so `{"query":"Brandenburg","lookupOnly":true}` answered `queryMatchCount: 2` without saying the state is 64; the full lists stay in the linked artifact.
20
+ - `hoi4.tech_inspect` with `mode: "explain"` names the technology inline: its file and line, start year, research cost, folders and categories, its direct prerequisites, what it leads to, its exclusive choices and its unlocks (20 names each at most, `truncated` when there are more), and the totals of all prerequisites, descendants, unlocks, grants and issues. The answer gave only the whole tree's counts, so an agent had to read the linked report (280 KB for the game) to learn what `infantry_weapons` leads to.
21
+ - Accept localisation values with quotes inside them. A line such as `k:0 "He said "hi" now"` was reported as `LOCALISATION_MALFORMED_LINE`, and a file with more than 100 of them was skipped whole, which made `hoi4.mod_index` answer `MOD_INDEXED_PARTIAL` for Old World Blues (five files, over 100 such lines each) and left their keys out of every lookup. The game reads from the first quote to the last one on the line, and its own localisation has 444 such lines, so they are valid. The TypeScript parser and the engine's symbol index now take them; a line that never closes its value is still malformed.
22
+ - Answer every `hoi4.source_lookup` call that names a symbol from the shared Rust engine, references included (ADR 0083, maintainer decision M-8, issue 107). The engine ports the definition walk's technology, focus, GUI and state references and the semantic scan's typed script edges, keeps those to the requested symbol, and counts the rest, so `referenceCount`, `referencesComplete` and `unresolvedReferenceCount` stay the whole scan's. The answer is the TypeScript route's, checked by `scripts/source-lookup-parity.ts` on the installed game and the benchmark mods. Only a request for a source position (`path` and `line`) still scans in TypeScript. A missing engine is `ENGINE_UNAVAILABLE` for every lookup that names a symbol, `includeReferences` included.
23
+ - Add `closure: true` to `hoi4.script_validate`, on the shared engine (ADR 0083, issue 107). It counts the references of the mod's own sources that resolve, do not resolve, or cannot be decided, per target kind, and returns a verdict: `incomplete` whenever anything is unknown or the scan is partial, `unresolved` when only unresolved references remain, `closed` otherwise. Dynamic targets, kinds a skipped source could define, and variables, flags and event targets that are read but never written in the scanned sources count as unknown. The option excludes `source` and `path`; the result has `checksPerformed: ["closure"]`, a `closure` object, and no `documentation`, which is now optional in the output schema.
24
+ - Add `create_world.partitionTuning.areaByRow` (feature-aware partition). The owner asked on 9 November (ZIN decision K116) for larger provinces and states toward the north, and the partition sized provinces by ground alone. `areaByRow` takes `[row, factor]` points (row 0 at the top edge, 1 at the bottom; factors 0.25 to 8), linear between points and held beyond the ends, and multiplies the planned land province area after it is scaled to `landProvincePixels`, so rows with factor 1 keep their sizes. States keep their province counts, so they grow by the same factor. `MAP_PARTITION_AREA_BY_ROW` reports the land provinces and mean area per band. On a 512 by 256 test world `[[0, 3], [0.3, 1.6], [0.45, 1], [1, 1]]` gave 246 pixels on average in rows 0 to 0.3, 153 in rows 0.3 to 0.45 and 116 in the south (117 without the option), and 138 states instead of 171. Requests without `areaByRow` write the same files as before.
25
+ - Accept a server state root under the macOS temporary folder. macOS ships `/var`, `/tmp` and `/etc` as links into `/private`, so a state root such as `$TMPDIR/state` (`/var/folders/...`) always passed through a link and startup stopped with `SERVER_STATE_UNSAFE`. A link that only the superuser can change (owned by root, in a root-owned directory that group and others cannot write) is now resolved to its real path first. Any other link in the path is still refused, and Windows is unchanged. The test helper resolves `TMPDIR` before the suite runs, which is why macOS CI never saw this.
26
+ - Make `hoi4.focus_inspect` and `hoi4.focus_rewrite` far cheaper per call (issue 137). On a four-focus mod with the game installed a warm inspect took 20 to 30 s; it now takes about 2 s on a loaded machine. The importer rebuilt a set of every game identifier for each assignment of every focus, the reference catalog was rebuilt for each imported file, a call that named a tree but no file imported every focus file of the game, and every rewrite and the next inspect indexed the whole game again. Each is fixed (the catalog sets and the catalog are cached, a tree id reads only the files that define it, and the workspace's last index supplies the records of unchanged files after an edit). A call with a tree id and no file now lists only that tree's source files in its source hashes.
27
+ - Start the server outside a mod when no configuration file exists (issue 150). It stopped with `AUTO_MOD_ROOT_NOT_FOUND`, so a modder who installed it globally and fetched the docs pack could not search the documentation from their home folder without running `--init`. It now starts with no workspace: documentation search answers, and mod tools answer `WORKSPACE_CONTEXT_NOT_FOUND`.
28
+ - Answer more plain-word documentation questions first (issue 64). A little word of a command name that the question also says ("at war with" for `has_war_with`) now counts, an exact name keeps a trigger or effect ahead of a console command, define or variable of the same name, and about twenty player words map to script words (sea, temporary, vassal, spirit, owner). On a new set of 22 blind questions the right answer moved from first on 12 to 13, and on the earlier sets from 9 to 11 of 24 (held-out) and 17 to 19 of 38 (fresh) with no answer lost. The target of issue 64 is not met yet.
29
+ - Report a localisation key that nothing defines as a warning, not an error, and text written directly in a scripted localisation (`localization_key = "Planes"`) as information. The game shows such a key as written, the localisation audit already said so, and `hoi4.mod_health` on Chaos Redux listed 2,663 "errors" of this kind ahead of the real problems. The engine check's code for the text case is `LOC_SCRIPTED_TEXT_LITERAL`, the audit's.
30
+ - Stop reading the installed game from disk on every call (issue 137). A scan read all 1,438 game files a focus call needs, about 1 s each time, and a focus rewrite scans three times. An installed game or DLC file whose device, file number, size, modification time and change time are unchanged now keeps its bytes and hash, checked against its stored hash before each reuse. Mod files are still read every time.
31
+ - Answer plain-word documentation questions better, and show ten candidates (issue 64). Every one of the 1,127 documented effects and triggers now has ten plain-word phrasings in `command-phrases.json` instead of four, written once at build time and shipped as data. `hoi4.reference_search` returns up to ten hits by default, and a command hit carries a one-line meaning with the scopes it works in, so an agent can pick the right one. On a new blind set of 43 questions the right answer is first on 31 (was 23) and among the first ten on 39 (91 percent, was 36). Counting a hit by command instead of by documentation file corrects the earlier figures of this issue upward.
32
+ - Skip the walk of the installed game while it is unchanged (issue 137). A scan opened, resolved and checked the 1,438 game files a focus call needs, about a second each time. The scanner now keeps the inventory of the game folder and reuses it while the game's version files (`hoi4_rev.txt` and its neighbours) and top-level folders look the same, and walks again as soon as they change. On a four-focus mod a warm `focus_inspect` takes about 0.5 s (was 1.0 to 1.3 s, and 20 to 30 s before the earlier fixes to this issue), a rewrite with nothing to change 0.8 s. A game file edited in place without an update is not seen until the server restarts; `HOI4_AGENT_FULL_GAME_SCAN` turns the shortcut off (see troubleshooting).
33
+ - Say "Did you mean ...?" in the message of a script command the game does not document (`SCRIPT_COMMAND_UNRESOLVED`). The close documented names were already in `suggestions`, but an agent that reads only the diagnostics saw "Not documented as a native command" and no hint, so `add_poltical_power` gave no pointer to `add_political_power`.
34
+ - `hoi4.script_validate` says what an unknown id does in game: `add_timed_idea names idea X, which no loaded file defines; the game loads the file, but this command does nothing`. It stays a warning, as the game loads such files and vanilla ships dangling ids, but now reads as the bug it is in the modder's own file. Benchmark: `vanilla.validation.timed-idea-wrong-id` expects that warning, and the undefined-description case moved from the ZIN corpus (which fixed its own file) to the synthetic regression mod, whose localisation now uses the double quotes the game reads.
35
+ - Say what is missing and how to get it when no `hoi4-engine` binary is found. The package ships the engine for Windows x64, Linux x64 and arm64, and macOS on Apple silicon; on another platform, such as an Intel Mac (`darwin-x64`), a tool that needs it answers `ENGINE_UNAVAILABLE` naming the shipped platforms and how to build the engine and point `HOI4_ENGINE` at it, and on a shipped platform whose binary is missing it says to reinstall. The README names the supported platforms.
36
+ - Map tools pass the province raster request and answer to `hoi4-engine map-provinces` through temporary files (`--input`, `--output`) instead of the engine's stdin and stdout. On macOS runners the synchronous call, which wrote hundreds of kilobytes to the pipe and read as much back, sometimes hung until its 120-second timeout and failed the map tests with `ENGINE_UNAVAILABLE` (`spawnSync ... ETIMEDOUT`). The engine still reads stdin and writes stdout when the options are absent.
37
+ - Event Chain Viewer analysis spends far less time hashing (maintainer decision M-8, issue 69). A CPU profile of `hoi4.event_inspect` `state_flow` on Chaos Redux (141 s) showed about 60 s of canonical JSON hashing and 22 s of garbage collection. Two causes are fixed. A dependency-walk checkpoint ran `z.json()` over the walk's whole frontier before every save (25 s) and canonicalised it twice. It now checks only the key and revision, and canonical JSON still refuses what JSON cannot hold. Loading a checkpoint still validates all of it. The semantic graph hash serialised each edge and state access with its option's conditions inline, about 3 GB on Chaos Redux (264,828 edges of 9.5 KB on average). Each shared condition is now hashed once and named by its digest (`event-semantic-graph-hash.v3`). `graphHash` values therefore differ from earlier versions, but within one version they still change exactly when the graph's meaning does. On the benchmark machine the Chaos Redux `state_flow` case took 79 and 70 s instead of 107 and 111 s.
38
+ - Build the province raster and run the province geometry checks on the shared Rust engine (ADR 0084, maintainer decision M-8, step 4). The province of every pixel, each province's extent, neighbours, seam-only pairs, undefined colours, coastal provinces, and the 4-connected parts, holes and thin runs that map validation reports now come from `hoi4-engine map-provinces`, in the same order the TypeScript code produced them. `scripts/map-raster-parity.ts` checks this on the installed game and the benchmark mods. Map tools that read `provinces.bmp` now answer `ENGINE_UNAVAILABLE` without an engine, as `hoi4.mod_index` does.
39
+ - `hoi4.map_inspect` and the other map tools no longer build the shared symbol index (maintainer decision M-8, step 4). The map model parses its own sources and never read it, yet every map call indexed every scanned file, its localisation included. Map scans now use `CoreEngine.scanFiles`, which shares the scan cache and admission limit and skips the index. On the benchmark machine (median of three cold runs), `{"query":"Brandenburg","lookupOnly":true}` on the game took 6.4 s instead of 11.4 s, an unknown-state lookup on Chaos Redux 3.0 s instead of 4.5 s, and a full inspection of the game map 22.5 s instead of 27.1 s. Answers are unchanged. The heightmap check of a full inspection also stops its land-distance search one step past the three-pixel lake-bank allowance instead of flooding every sea pixel, with the same answers; on the game a full inspection took 13.7 s instead of 26.8 s. The new benchmark case `vanilla.map.full-inspect` measures it.
40
+ - `hoi4.probability_inspect` and `hoi4.probability_analyze` accept a top-level `path` for the source file, as their description promises ("by path, ID or candidate IDs"). `{"path":"common/national_focus/germany.txt","candidatePool":[...]}` was refused with `INVALID_ARGUMENTS`; it now means `source: {"path": ...}`. A call that gives both `path` and `source` is still refused.
41
+ - Add the files map operations create to the world output record (`.hoi4-agent-world.json`). `assign_territory`, `split_state`, `create_state` and the other operations created state and strategic-region files that never entered the record, so a sync that copies the recorded files left them out. ZIN's first Linux run of a redrawn map lost 124 state files this way, and the game stopped at setup. Every map rewrite now also adds each file it creates where the world keeps its outputs (state files, strategic regions, map files and world localisation, not country files), in the same transaction. `MAP_WORLD_OUTPUTS_REFRESHED` gives `added` and `addedPaths`. For mods already in this state, `record_world_outputs` now also adds the mod's files at those paths that the record lacks; `adoptUnrecorded: false` keeps the old behaviour of re-hashing listed entries only.
42
+ - `record_world_outputs` no longer drops recorded files that are on disk. Its scan did not read the bitmaps, colour maps and world scripts that only `create_world` scanned, so it dropped them as gone: on ZIN, 12 entries, among them `map/rivers.bmp`, `map/terrain.bmp` and `common/on_actions/world.txt`. A Linux copy of the recorded files then ran with the base game's rivers. It now reads every world output, and drops only recorded state and strategic-region files that are gone. Any other recorded file it did not read keeps its entry and is listed in `unscannedPaths`.
43
+ - Territory controls for redrawing borders, from the ZIN map lane's rev3 findings. `assign_territory` takes culture or people `groups` (`{ provinceId: group }`): a growth step across a group line costs `1 + groupPenalty` times more (default 2), and with `groupHard: true` growth never crosses one. In rev3, peoples' pockets were shared across those lines. A country with `fixed: true` owns exactly its seeds and forced land and never grows. In rev3, Kingson still grew from 122 to 142 provinces into its neighbours' free bands. A preview and a write add `map-territory-assignment.json`, the provinces of each owner and of each new or changed state; before, the only source was the 22 MB proposed map. A seed in water is refused with the nearest land province named (`details.nearestLandProvince`).
44
+ - `assign_territory` warns when a country or overlord tag gets land although no active `common/country_tags` file declares it (`MAP_TERRITORY_TAG_UNDEFINED`). It took such tags silently, and the game then did not know the states' owner. The ZIN map lane assigns new realms before their country files exist. The assignment is still written, unless the new `strictTags: true` asks for a refusal. Nothing is reported when the workspace declares no tags at all.
45
+
5
46
  ## 4.16.0 - 2026-11-09
6
47
 
7
48
  - Keep the world output record (`.hoi4-agent-world.json`) current with the tool's own map edits. `update_states`, `move_state_provinces` and every other map operation rewrote recorded state, strategic-region and map files without recording their new hashes, so the next `create_world` refused them as hand edits (`MANAGED_OUTPUT_EDITED`). This happened in a later call and also later in the `create_world` call itself, because the record was planned at the end of `create_world`. ZIN had 191 such files on 9 November: 184 state files and 7 strategic regions. Every map rewrite now records the new hash of each recorded file it writes, and drops each one it deletes, in the same transaction (`MAP_WORLD_OUTPUTS_REFRESHED`). A recorded file edited by hand before the call keeps its old hash and is named in a warning, so it stays protected. The new `record_world_outputs` operation takes the current bytes of every recorded file as the world's own. It is for mods whose record is already stale: it writes only the record, drops files that are gone, and reports the counts (`MAP_WORLD_OUTPUTS_RECORDED`).
package/README.md CHANGED
@@ -42,6 +42,7 @@ You describe what you want; the agent picks the right tools.
42
42
  ## Quick start
43
43
 
44
44
  1. Install [Node.js](https://nodejs.org/) 22 (22.19 or later) or 24, and keep Hearts of Iron IV installed for vanilla files, artwork and fonts.
45
+ The package ships its analysis engine for Windows x64, Linux x64 and arm64, and macOS on Apple silicon. On another platform, such as an Intel Mac, the tools that need the engine say so and how to build it; set `HOI4_ENGINE` to that build.
45
46
  2. Install the server:
46
47
 
47
48
  ```bash
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { z } from 'zod/v4';
3
- import { canonicalJson, hashCanonical } from './canonical.js';
3
+ import { canonicalJson, hashCanonical, sha256Bytes } from './canonical.js';
4
4
  import { ServiceError } from './result.js';
5
5
  import { PACKAGE_VERSION } from '../version.js';
6
6
  const digest = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -12,6 +12,7 @@ const envelopeSchema = z
12
12
  state: z.json(),
13
13
  })
14
14
  .strict();
15
+ const saveIdentitySchema = z.object({ key: digest, sourceRevision: digest }).strict();
15
16
  const active = new AsyncLocalStorage();
16
17
  /** Internal typed execution context; no transport or caller-supplied executable hooks. */
17
18
  export function withAnalysisCheckpoints(checkpoints, run) {
@@ -44,12 +45,18 @@ export function jobAnalysisCheckpoints(context) {
44
45
  },
45
46
  async save(key, sourceRevision, state, completed, total) {
46
47
  context.signal.throwIfAborted();
47
- const envelope = envelopeSchema.parse({ version: 1, key, sourceRevision, state });
48
+ // The state is the analysis's own in-memory value. Canonical JSON already refuses what
49
+ // JSON cannot hold, so only the identity fields are checked here: a deep z.json() pass
50
+ // over a large frontier cost more than the analysis itself (25 s of a 141 s event query on a
51
+ // large mod). `load` still validates the whole envelope it reads back from disk.
52
+ saveIdentitySchema.parse({ key, sourceRevision });
53
+ const content = canonicalJson({ version: 1, key, sourceRevision, state });
54
+ const stateHash = sha256Bytes(content);
48
55
  await context.engine.artifacts.withAtomicChunkedWrites(workspace, [
49
56
  {
50
57
  name: 'analysis-checkpoint.json',
51
58
  mimeType: 'application/json',
52
- content: canonicalJson(envelope),
59
+ content,
53
60
  provenance: {
54
61
  kind: 'analysis-checkpoint',
55
62
  toolVersion: PACKAGE_VERSION,
@@ -64,7 +71,7 @@ export function jobAnalysisCheckpoints(context) {
64
71
  sourceRevision,
65
72
  resourceUri: resource.uri,
66
73
  cursor: `analysis:${key}`,
67
- stateHash: hashCanonical(envelope),
74
+ stateHash,
68
75
  resources: physical.map(({ uri }) => uri),
69
76
  };
70
77
  // Publish the authenticated pin before releasing artifact admission. A competing
@@ -27,6 +27,35 @@ function isFile(candidate) {
27
27
  return false;
28
28
  }
29
29
  }
30
+ /**
31
+ * Every platform a release ships `hoi4-engine` for (ADR 0074), as `<process.platform>-<process.arch>`.
32
+ * Other platforms, such as macOS on Intel (`darwin-x64`), get no bundled binary.
33
+ */
34
+ export const ENGINE_BUNDLE_PLATFORMS = [
35
+ 'darwin-arm64',
36
+ 'linux-arm64',
37
+ 'linux-x64',
38
+ 'win32-x64',
39
+ ];
40
+ const PLATFORM_NAMES = {
41
+ 'darwin-arm64': 'macOS on Apple silicon',
42
+ 'linux-arm64': 'Linux arm64',
43
+ 'linux-x64': 'Linux x64',
44
+ 'win32-x64': 'Windows x64',
45
+ };
46
+ /**
47
+ * What a tool answers when no engine binary is found: what is missing and how to get one. A
48
+ * platform the release does not ship for needs a local build; a shipped platform whose binary is
49
+ * missing needs a reinstall.
50
+ */
51
+ export function missingEngineMessage(platform, arch) {
52
+ const target = `${platform}-${arch}`;
53
+ const supported = ENGINE_BUNDLE_PLATFORMS.map((name) => PLATFORM_NAMES[name]).join(', ');
54
+ const build = `build it from the repository's engine/ folder (cargo build --release -p hoi4-engine-cli) and set ${ENGINE_BINARY_ENV} to the binary's absolute path`;
55
+ return ENGINE_BUNDLE_PLATFORMS.includes(target)
56
+ ? `The hoi4-engine binary for ${target} is missing from this installation. Reinstall hoi4-agent-tools (npm install --global hoi4-agent-tools), or ${build}.`
57
+ : `hoi4-agent-tools ships the hoi4-engine binary for ${supported}, not for ${target}. To use the tools that need it here, ${build}.`;
58
+ }
30
59
  export const ENGINE_BUNDLE_MANIFEST_SCHEMA = 'hoi4-engine-bundle/1';
31
60
  /** `engine/bin/manifest.json`: the SHA-256 and size of every bundled binary, keyed by `<platform>-<arch>`. */
32
61
  export const engineBundleManifestSchema = z.strictObject({
@@ -123,7 +152,7 @@ export function locateEngineBinary(options = {}) {
123
152
  }
124
153
  return {
125
154
  reason: 'binary_not_found',
126
- message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
155
+ message: missingEngineMessage(process.platform, process.arch),
127
156
  };
128
157
  }
129
158
  function clip(text) {
@@ -100,6 +100,14 @@ export class CoreEngine {
100
100
  #scanCache = new Map();
101
101
  #scanFlights = new Map();
102
102
  #scanGenerations = new Map();
103
+ /**
104
+ * The newest completed index of each workspace. After an edit or with another file pattern no
105
+ * scan of the same request is left to start from, and the segment cache holds too few records
106
+ * to index the installed game again cheaply, so this index supplies every unchanged file's
107
+ * records. They are addressed by the file's content hash, so an older index can never supply
108
+ * a wrong one.
109
+ */
110
+ #latestIndexes = new Map();
103
111
  #scanAdmissionQueue = [];
104
112
  #activeScanAdmissions = new Set();
105
113
  #recovery;
@@ -191,6 +199,17 @@ export class CoreEngine {
191
199
  return this.resolver.list(principal).map(({ id }) => this.status(id, principal));
192
200
  }
193
201
  async scan(workspaceId, options = {}, principal, signal) {
202
+ return (await this.#scan(workspaceId, options, principal, signal, true));
203
+ }
204
+ /**
205
+ * The same scan without the symbol index, for callers that read only the files (the map
206
+ * model parses its own sources). It shares the admission limit and the cache with `scan`,
207
+ * under its own cache entries, and skips the index build and the persistent analysis cache.
208
+ */
209
+ async scanFiles(workspaceId, options = {}, principal, signal) {
210
+ return this.#scan(workspaceId, options, principal, signal, false);
211
+ }
212
+ async #scan(workspaceId, options, principal, signal, withIndex) {
194
213
  signal?.throwIfAborted();
195
214
  await this.resolver.refreshDescriptors(workspaceId, principal);
196
215
  const workspace = this.resolver.get(workspaceId, principal);
@@ -203,6 +222,7 @@ export class CoreEngine {
203
222
  rootKinds: [...(options.rootKinds ?? [])].sort(),
204
223
  maxFiles: options.maxFiles ?? this.resolver.config().scanMaxFiles,
205
224
  maxBytes: options.maxBytes ?? this.resolver.config().scanMaxBytes,
225
+ ...(withIndex ? {} : { index: false }),
206
226
  })}`;
207
227
  let flight = this.#scanFlights.get(requestKey);
208
228
  if (flight === undefined) {
@@ -234,6 +254,11 @@ export class CoreEngine {
234
254
  this.#scanCache.set(cacheKey, cached);
235
255
  return cached;
236
256
  }
257
+ if (!withIndex) {
258
+ const snapshot = { workspaceId, revision, files };
259
+ this.#retainScan(workspaceId, generation, requestKey, cacheKey, snapshot);
260
+ return snapshot;
261
+ }
237
262
  const persistentAnalysisCache = await this.persistentAnalysisCache;
238
263
  const analysisScope = {
239
264
  workspaceIdentity: workspace.workspaceIdentity,
@@ -245,9 +270,10 @@ export class CoreEngine {
245
270
  // records, so only edited files are parsed and indexed again.
246
271
  const previous = [...this.#scanCache]
247
272
  .filter(([key]) => key.startsWith(`${requestKey}:`))
248
- .at(-1)?.[1].index;
273
+ .at(-1)?.[1]?.index ?? this.#latestIndexes.get(workspaceId);
249
274
  const index = await SymbolIndex.buildAsync(files, controller.signal, this.indexSegments, previous);
250
275
  await persistentAnalysisCache?.persist(analysisScope, files, sourceDocuments, this.indexSegments, controller.signal);
276
+ this.#latestIndexes.set(workspaceId, index);
251
277
  const documentedEffects = await installedEffectCommands(workspace.gameRoot);
252
278
  const snapshot = {
253
279
  workspaceId,
@@ -260,32 +286,7 @@ export class CoreEngine {
260
286
  diagnostics: index.diagnostics,
261
287
  ...(documentedEffects === undefined ? {} : { documentedEffects }),
262
288
  };
263
- if ((this.#scanGenerations.get(workspaceId) ?? 0) === generation) {
264
- // Replace this request's earlier revision and drop earlier generations; keep the
265
- // most recent other requests of this workspace.
266
- for (const key of this.#scanCache.keys()) {
267
- if (key.startsWith(`${requestKey}:`) ||
268
- (key.startsWith(`${workspaceId}:`) &&
269
- !key.startsWith(`${workspaceId}:${generation}:`)))
270
- this.#scanCache.delete(key);
271
- }
272
- this.#scanCache.set(cacheKey, snapshot);
273
- const retained = [...this.#scanCache.keys()].filter((key) => key.startsWith(`${workspaceId}:`));
274
- for (const key of retained.slice(0, -SCAN_CACHE_ENTRIES_PER_WORKSPACE))
275
- this.#scanCache.delete(key);
276
- // Snapshots hold every file's bytes; keep all of them within twice one scan's limit.
277
- const limit = this.resolver.config().scanMaxBytes * 2;
278
- const bytes = (cached) => cached.files.reduce((sum, { size }) => sum + size, 0);
279
- let retainedBytes = [...this.#scanCache.values()].reduce((sum, cached) => sum + bytes(cached), 0);
280
- for (const [key, cached] of this.#scanCache) {
281
- if (retainedBytes <= limit)
282
- break;
283
- if (key === cacheKey)
284
- continue;
285
- this.#scanCache.delete(key);
286
- retainedBytes -= bytes(cached);
287
- }
288
- }
289
+ this.#retainScan(workspaceId, generation, requestKey, cacheKey, snapshot);
289
290
  return snapshot;
290
291
  });
291
292
  })();
@@ -306,6 +307,33 @@ export class CoreEngine {
306
307
  }
307
308
  return this.awaitScanFlight(requestKey, flight, signal);
308
309
  }
310
+ #retainScan(workspaceId, generation, requestKey, cacheKey, snapshot) {
311
+ if ((this.#scanGenerations.get(workspaceId) ?? 0) !== generation)
312
+ return;
313
+ // Replace this request's earlier revision and drop earlier generations; keep the most
314
+ // recent other requests of this workspace.
315
+ for (const key of this.#scanCache.keys()) {
316
+ if (key.startsWith(`${requestKey}:`) ||
317
+ (key.startsWith(`${workspaceId}:`) && !key.startsWith(`${workspaceId}:${generation}:`)))
318
+ this.#scanCache.delete(key);
319
+ }
320
+ this.#scanCache.set(cacheKey, snapshot);
321
+ const retained = [...this.#scanCache.keys()].filter((key) => key.startsWith(`${workspaceId}:`));
322
+ for (const key of retained.slice(0, -SCAN_CACHE_ENTRIES_PER_WORKSPACE))
323
+ this.#scanCache.delete(key);
324
+ // Snapshots hold every file's bytes; keep all of them within twice one scan's limit.
325
+ const limit = this.resolver.config().scanMaxBytes * 2;
326
+ const bytes = (cached) => cached.files.reduce((sum, { size }) => sum + size, 0);
327
+ let retainedBytes = [...this.#scanCache.values()].reduce((sum, cached) => sum + bytes(cached), 0);
328
+ for (const [key, cached] of this.#scanCache) {
329
+ if (retainedBytes <= limit)
330
+ break;
331
+ if (key === cacheKey)
332
+ continue;
333
+ this.#scanCache.delete(key);
334
+ retainedBytes -= bytes(cached);
335
+ }
336
+ }
309
337
  invalidate(workspaceId) {
310
338
  this.#scanGenerations.set(workspaceId, (this.#scanGenerations.get(workspaceId) ?? 0) + 1);
311
339
  for (const key of this.#scanCache.keys()) {
@@ -322,6 +350,7 @@ export class CoreEngine {
322
350
  /** Drop completed scan buffers without invalidating revisions or interrupting active scans. */
323
351
  releaseScanCaches() {
324
352
  this.#scanCache.clear();
353
+ this.#latestIndexes.clear();
325
354
  this.indexSegments.clear();
326
355
  sourceDocuments.clear();
327
356
  this.scanner.clearCaches();
@@ -127,6 +127,7 @@ export function refreshManagedOutputs(input) {
127
127
  const dropped = [];
128
128
  const keptEdited = [];
129
129
  const unchanged = [];
130
+ const unscanned = [];
130
131
  const operationIds = new Set();
131
132
  const next = [];
132
133
  for (const entry of parseManifest(bytes)) {
@@ -147,8 +148,19 @@ export function refreshManagedOutputs(input) {
147
148
  for (const id of change.operationIds)
148
149
  operationIds.add(id);
149
150
  }
150
- else if (input.adoptAll === true)
151
- current = source === undefined ? null : source.bytes;
151
+ else if (input.adoptAll === true) {
152
+ // A file the scan did not read is not a file that is gone: keep its entry.
153
+ if (source === undefined && input.alwaysScanned?.(entry.relativePath) === true) {
154
+ dropped.push(entry.relativePath);
155
+ continue;
156
+ }
157
+ if (source === undefined) {
158
+ unscanned.push(entry.relativePath);
159
+ next.push(entry);
160
+ continue;
161
+ }
162
+ current = source.bytes;
163
+ }
152
164
  else {
153
165
  next.push(entry);
154
166
  continue;
@@ -164,13 +176,52 @@ export function refreshManagedOutputs(input) {
164
176
  refreshed.push(entry.relativePath);
165
177
  next.push({ relativePath: entry.relativePath, sha256 });
166
178
  }
167
- const changed = refreshed.length > 0 || dropped.length > 0;
179
+ // Files the request creates at managed paths, and on request the ones already on disk.
180
+ const added = [];
181
+ const recorded = new Set(next.map(({ relativePath }) => key(relativePath)));
182
+ for (const entry of dropped)
183
+ recorded.add(key(entry));
184
+ const addable = input.addable;
185
+ if (addable !== undefined) {
186
+ const candidates = new Map();
187
+ if (input.adoptUnrecorded === true)
188
+ for (const [name, file] of sources)
189
+ candidates.set(name, {
190
+ relativePath: file.relativePath.replaceAll('\\', '/'),
191
+ bytes: file.bytes,
192
+ ids: [],
193
+ });
194
+ for (const [name, change] of proposed) {
195
+ if (change.content === null) {
196
+ candidates.delete(name);
197
+ continue;
198
+ }
199
+ // A change to an existing unrecorded file is not a creation unless adoption was asked for.
200
+ if (!sources.has(name) || input.adoptUnrecorded === true)
201
+ candidates.set(name, {
202
+ relativePath: change.relativePath.replaceAll('\\', '/'),
203
+ bytes: change.content,
204
+ ids: [...change.operationIds],
205
+ });
206
+ }
207
+ for (const [name, candidate] of [...candidates].sort(([a], [b]) => compareCodeUnits(a, b))) {
208
+ if (name === manifestKey || recorded.has(name) || !addable(candidate.relativePath))
209
+ continue;
210
+ next.push({ relativePath: candidate.relativePath, sha256: sha256Bytes(candidate.bytes) });
211
+ added.push(candidate.relativePath);
212
+ for (const id of candidate.ids)
213
+ operationIds.add(id);
214
+ }
215
+ }
216
+ const changed = refreshed.length > 0 || dropped.length > 0 || added.length > 0;
168
217
  return {
169
218
  content: changed ? manifestBytes(next) : undefined,
219
+ added: added.sort(compareCodeUnits),
170
220
  refreshed: refreshed.sort(compareCodeUnits),
171
221
  dropped: dropped.sort(compareCodeUnits),
172
222
  keptEdited: keptEdited.sort(compareCodeUnits),
173
223
  unchanged: unchanged.sort(compareCodeUnits),
224
+ unscanned: unscanned.sort(compareCodeUnits),
174
225
  operationIds: [...operationIds].sort(compareCodeUnits),
175
226
  };
176
227
  }
@@ -194,7 +194,31 @@ function essentialDiagnostics(diagnostics) {
194
194
  }
195
195
  return kept;
196
196
  }
197
- function boundedResult(result, actualBytes) {
197
+ /**
198
+ * The first paths of a list that fit in `budget` bytes. A truncated reply keeps them, with the
199
+ * total, so a write that changed files never reads as one that changed nothing.
200
+ */
201
+ function leadingPaths(paths, budget) {
202
+ const kept = [];
203
+ let bytes = 0;
204
+ for (const path of paths) {
205
+ bytes += Buffer.byteLength(JSON.stringify(path), 'utf8') + 1;
206
+ if (bytes > budget)
207
+ break;
208
+ kept.push(path);
209
+ }
210
+ return kept;
211
+ }
212
+ function boundedResult(result, actualBytes, totals) {
213
+ const changedFiles = leadingPaths(result.changedFiles, 4_096);
214
+ const proposedFiles = leadingPaths(result.proposedFiles, 2_048);
215
+ const fileCounts = {
216
+ changedFilesTotal: totals.changedFiles,
217
+ changedFilesShown: changedFiles.length,
218
+ proposedFilesTotal: totals.proposedFiles,
219
+ proposedFilesShown: proposedFiles.length,
220
+ filesScannedTotal: totals.filesScanned,
221
+ };
198
222
  const hasLinkedEvidence = result.artifacts.length > 0;
199
223
  const truncationDiagnostic = {
200
224
  code: 'MCP_RESPONSE_TRUNCATED',
@@ -203,7 +227,7 @@ function boundedResult(result, actualBytes) {
203
227
  message: hasLinkedEvidence
204
228
  ? 'Tool output exceeded the wire budget; inspect the linked evidence for complete details'
205
229
  : 'Tool output exceeded the wire budget; nonessential inline details were omitted',
206
- details: { actualBytes, maxBytes: MAX_TOOL_RESULT_BYTES },
230
+ details: { actualBytes, maxBytes: MAX_TOOL_RESULT_BYTES, ...fileCounts },
207
231
  };
208
232
  const compactData = result.data !== null && typeof result.data === 'object' && !Array.isArray(result.data)
209
233
  ? result.data
@@ -213,8 +237,8 @@ function boundedResult(result, actualBytes) {
213
237
  code: result.code.slice(0, 256),
214
238
  workspaceId: result.workspaceId.slice(0, 64),
215
239
  filesScanned: [],
216
- proposedFiles: [],
217
- changedFiles: [],
240
+ proposedFiles,
241
+ changedFiles,
218
242
  diagnostics: [truncationDiagnostic, ...essentialDiagnostics(result.diagnostics)],
219
243
  artifacts: result.artifacts
220
244
  .slice(0, 1)
@@ -523,14 +547,21 @@ export function toolResult(result, options = {}) {
523
547
  });
524
548
  const completeResult = preserveDeferredFilesDiagnostic(result);
525
549
  const compact = compactDescriptions(completeResult);
550
+ const totals = {
551
+ changedFiles: completeResult.changedFiles.length,
552
+ proposedFiles: completeResult.proposedFiles.length,
553
+ filesScanned: completeResult.filesScanned.length,
554
+ };
526
555
  const estimatedBytes = jsonBytesWithin(compact, MAX_TOOL_RESULT_BYTES)
527
556
  ? Buffer.byteLength(canonicalJson(compact), 'utf8')
528
557
  : MAX_TOOL_RESULT_BYTES + 1;
529
- const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES ? boundedResult(compact, estimatedBytes) : compact;
558
+ const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES
559
+ ? boundedResult(compact, estimatedBytes, totals)
560
+ : compact;
530
561
  let output = buildToolResult(selected, images.length, options.compact);
531
562
  const wireBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
532
563
  if (wireBytes > MAX_TOOL_RESULT_BYTES) {
533
- output = buildToolResult(boundedResult(compact, wireBytes), images.length, options.compact);
564
+ output = buildToolResult(boundedResult(compact, wireBytes, totals), images.length, options.compact);
534
565
  }
535
566
  const finalBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
536
567
  if (finalBytes > MAX_TOOL_RESULT_BYTES) {