hoi4-agent-tools 4.6.5 → 4.7.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 (80) hide show
  1. package/CHANGELOG.md +16 -5
  2. package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
  3. package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
  4. package/dist/hoi4_agent_tools/focus/compact.js +197 -18
  5. package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
  6. package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
  7. package/dist/hoi4_agent_tools/focus/layout.js +3 -2
  8. package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
  9. package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
  10. package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
  11. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
  12. package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
  13. package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
  14. package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
  15. package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
  16. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +202 -0
  17. package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
  18. package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -0
  19. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
  20. package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
  21. package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
  22. package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
  23. package/dist/hoi4_agent_tools/focus/tool-operations.js +206 -22
  24. package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
  25. package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
  26. package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
  27. package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
  28. package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
  29. package/dist/hoi4_agent_tools/reference/service.js +92 -21
  30. package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
  31. package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
  32. package/dist/hoi4_agent_tools/version.js +1 -1
  33. package/docs/configuration.md +17 -17
  34. package/docs/focus.md +100 -4
  35. package/docs/reference.md +1 -1
  36. package/docs/research/reference-benchmark.md +111 -1
  37. package/docs/setup.md +1 -1
  38. package/docs/tools.md +5 -5
  39. package/npm-shrinkwrap.json +2 -2
  40. package/package.json +2 -1
  41. package/schemas/configuration.schema.json +1 -1
  42. package/schemas/continuous-focus-palette.schema.json +1 -1
  43. package/schemas/custom-weighted-pool.schema.json +1 -1
  44. package/schemas/decision-inspect-input.schema.json +1 -1
  45. package/schemas/error-log-input.schema.json +1 -1
  46. package/schemas/event-feature-manifest.schema.json +1 -1
  47. package/schemas/focus-plan.schema.json +146 -120
  48. package/schemas/focus-planning-sidecar.schema.json +15 -7
  49. package/schemas/geography-model.schema.json +1 -1
  50. package/schemas/gui-animation-source.schema.json +1 -1
  51. package/schemas/gui-helper.schema.json +1 -1
  52. package/schemas/gui-scenario.schema.json +1 -1
  53. package/schemas/helper-expansion-request.schema.json +1 -1
  54. package/schemas/helper-expansion-summary.schema.json +1 -1
  55. package/schemas/impact-inspect-input.schema.json +1 -1
  56. package/schemas/map-operation.schema.json +1 -1
  57. package/schemas/mechanic-test-input.schema.json +1 -1
  58. package/schemas/mod-index-input.schema.json +1 -1
  59. package/schemas/operation-result.schema.json +1 -1
  60. package/schemas/package-check-input.schema.json +1 -1
  61. package/schemas/package-manifest.schema.json +1 -1
  62. package/schemas/probability-analysis-result.schema.json +1 -1
  63. package/schemas/probability-compare-input.schema.json +1 -1
  64. package/schemas/probability-evaluate-input.schema.json +1 -1
  65. package/schemas/probability-inspect-input.schema.json +1 -1
  66. package/schemas/probability-render-input.schema.json +1 -1
  67. package/schemas/probability-scenario-set.schema.json +1 -1
  68. package/schemas/probability-sequence-input.schema.json +1 -1
  69. package/schemas/probability-simulate-input.schema.json +1 -1
  70. package/schemas/probability-sweep-input.schema.json +1 -1
  71. package/schemas/reference-context-input.schema.json +1 -1
  72. package/schemas/reference-read-input.schema.json +1 -1
  73. package/schemas/reference-search-input.schema.json +1 -1
  74. package/schemas/reference-sheets.schema.json +1 -1
  75. package/schemas/scenario-suite.schema.json +1 -1
  76. package/schemas/scenario-test-input.schema.json +1 -1
  77. package/schemas/script-validate-input.schema.json +1 -1
  78. package/schemas/shared-scenario.schema.json +1 -1
  79. package/schemas/source-lookup-input.schema.json +1 -1
  80. package/server.json +2 -2
package/docs/focus.md CHANGED
@@ -118,6 +118,66 @@ When `treeId` is also supplied, it must equal `plan.id`.
118
118
 
119
119
  For a missing target, call `hoi4.focus_rewrite` with `createIfMissing: true`. Review the proposed and final artifacts returned by the rewrite, then inspect and render the result. `hoi4.focus_render` returns a deterministic PNG with decoded source icons. Do not call a tree complete with placeholder rewards, missing localisation, missing icons, or absent AI choices.
120
120
 
121
+ ## Layout quality
122
+
123
+ A tree can be structurally correct and still look wrong: a main line that steps one column left on every row, one branch floating off in a corner, half the canvas empty. Structure and layout are separate questions, so every `hoi4.focus_inspect` and `hoi4.focus_rewrite` result carries a **layout verdict** next to the structural answer. `validation.passed` stays the structural answer; the check `focus-layout-verdict` carries the layout one. "Structure ok" never means the layout is good.
124
+
125
+ | Verdict | Meaning | What to do |
126
+ | --------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
127
+ | `pass` | Every calibrated metric lies inside the range of the installed game's own trees. | Look at the render anyway: metrics cannot see composition. |
128
+ | `review` | A metric leaves the vanilla range, or a design flag is raised. Advisory. | Look at `hoi4.focus_render` and decide whether it is intended. |
129
+ | `revise` | A metric is far outside the vanilla range, or five or more are outside it. | The tree is not finished. Repair the failing branch, then inspect again. |
130
+ | `blocked` | A hard defect: two focuses on one coordinate, a prerequisite that is not above its dependant, or plaques that overlap in game. | Fix the defect first. Hand-typed coordinates are the usual cause. |
131
+
132
+ The result also carries a **scorecard** (at most 12 rows inline, the full list in the linked artifact), a fix for each failing row (`fix.action`, `fix.targetFocusIds`, `fix.suggested`, `fix.expectedMetricChange`, `fix.preservesGameplay`), `nextActions`, and `notEvaluated`, which always names what the tool cannot judge: gameplay and balance, visual review, and in-game connector geometry. A tree below 8 focuses gets only the hard-defect checks, and a tree below 40 focuses is never asked to `revise` because vanilla has too few small trees to set a limit.
133
+
134
+ ### Metrics
135
+
136
+ | Id | What it measures |
137
+ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
138
+ | H1 | Focuses on the same coordinate. Branches that are never visible together (`allow_branch`, hidden, or below a conditional focus) may share one. |
139
+ | H2 | A prerequisite that is not on an earlier row than its dependant. |
140
+ | H3 | Plaques closer than their own width (about 1.6 columns) on one row; the game's minimum spacing is 2. |
141
+ | H4 | Connector stems that run through an unrelated plaque, per 100 links. Advisory. |
142
+ | H5 | Stems that cross the bar of an unrelated connector, per 100 links. Advisory. |
143
+ | S1 | Largest empty rectangle as a fraction of the canvas. |
144
+ | S2, S3 | Side balance (focuses left against right of the centre column) and mass skew (mean column against the centre). |
145
+ | S4 | Fill ratio: focuses over the cells of the bounding box. Low is bad. |
146
+ | S5 | Row-centroid wander: how far the centre of each row drifts, as a fraction of the width. |
147
+ | S6 | Single-focus chains that jog sideways, per 100 links. |
148
+ | S7 | Sibling subtrees that share columns on the same rows, as a fraction of sibling pairs. |
149
+ | S8 | Largest distance between a fan-out's centre and its parent, in columns. Shown, never part of the verdict. |
150
+ | S9 | Unrelated connectors that share a bar or stem, per 100 links. Advisory. |
151
+ | S10 | Largest gap in rows between a focus and the row after its lowest prerequisite. |
152
+ | S11 | Sibling groups whose members sit on different rows. |
153
+ | D1, D2 | Longest run of single-successor focuses, and the fraction of leaves. |
154
+ | D3, D4 | Exclusive choices that rejoin six or more rows later, and a canvas taller than 2.5 rows per plaque column. |
155
+
156
+ The limits of S1 to S11, H4, H5, D1 and D2 are computed from the installed game's national focus trees (67 trees of 8 or more focuses, in two size buckets: 40 to 120 and over 120 focuses) and stored as derived numbers in `src/hoi4_agent_tools/focus/quality/focus-quality-calibration.json`. `review` starts at the edge of the vanilla range; `revise` starts a margin beyond it. H4, H5 and S9 can raise a tree to `review` at most until the connector model below is confirmed in the game. Design flags (D1 to D4) are proxies for the question "does the player choose anything?" and always go to a person: the tool never changes prerequisites, rewards or names for them.
157
+
158
+ `npm run focus:calibrate -- --write` recomputes the file from the installed game. The local test `tests/local/focus-quality-calibration.test.ts` recomputes it whenever the game is found and fails when the stored file differs. `npm run focus:calibrate -- --report` prints how often an unseen vanilla-quality tree is flagged: about 82 percent `pass`, 15 percent `review` and 3 percent `revise` with the limits fitted without that tree.
159
+
160
+ ### Connector model
161
+
162
+ The game draws right-angle connectors: a stem leaves the parent, a horizontal bar runs in the gap above the child's row, and a stem enters the child. Crossings, connector-through-plaque and shared-bar counts use that model, not the curved connector of the icon render, which over-reported crossings by a factor of nine on vanilla trees. All connectors between the parents and children of an **all-to-all bundle** (two or more parents that are each a prerequisite of the same two or more children) share one bar in the game and are never counted against each other, and neither are the members of an OR group. The model was read from one in-game screenshot for adjacent rows; multi-row bar placement is unverified, so confirm it with a screenshot of a multi-row connector before treating H4, H5 or S9 as defects.
163
+
164
+ `FOCUS_LAYOUT_CONNECTOR_CROSSING_UNSATISFIED`, `FOCUS_AVOIDABLE_CONNECTOR_CROSSING` and `FOCUS_LAYOUT_CONNECTOR_THROUGH_NODE` come from the curved model and are no longer shown in inspect and render results; the linked artifact keeps them.
165
+
166
+ ### Workflow for an agent
167
+
168
+ 1. Establish the design: purpose, route families, the choices the player makes.
169
+ 2. Write a lane plan: ordered branches (`branchGroups`, `laneGroups`) with their intended width and where they rejoin.
170
+ 3. Define prerequisites, exclusive choices and convergence.
171
+ 4. Place with `position.mode: "auto"` so the solver centres, spaces and balances the branches. Hand-written `x` and `y` are for exact anchors only; hand-typed coordinates are the usual cause of drift and lopsided branches.
172
+ 5. `hoi4.focus_render` and look at the inline overview and crops.
173
+ 6. Read the scorecard and answer: can every branch be named from the picture, and is every asymmetry intended?
174
+ 7. Revise one failing branch at a time with `layoutMode: "compact"`, `compactFocusIds` and `pinnedFocusIds`; pass the previous layout as `previous` to `hoi4.focus_inspect` to get the `layoutDelta`.
175
+ 8. Validate structure and gameplay.
176
+ 9. Show the before and after pictures and the scorecard to a person when the project asks for it.
177
+ 10. Check the tree in the game.
178
+
179
+ `layoutDelta` reports `verdictBefore` and `verdictAfter`, the scores, the metrics that improved and regressed, the moved focuses, a hash of the focuses that did not move (`unmovedHash`), and hashes of the prerequisites and exclusions with `prerequisitesUnchanged` and `mutualExclusionsUnchanged`, so a layout repair can prove that it changed coordinates only.
180
+
121
181
  ## Clean an existing tree
122
182
 
123
183
  For a layout-only cleanup of an existing national tree, call `hoi4.focus_rewrite` without a plan:
@@ -130,14 +190,14 @@ For a layout-only cleanup of an existing national tree, call `hoi4.focus_rewrite
130
190
  }
131
191
  ```
132
192
 
133
- A plan-free call is accepted only in national mode with `layoutMode: "compact"`.
193
+ A plan-free call is accepted only in national mode with `layoutMode: "compact"` or `layoutMode: "engine"` (see [Engine layout and placement](#engine-layout-and-placement)).
134
194
  It requires `treeId`, works on an existing focus source, and rejects `createIfMissing: true`.
135
195
  Every other national rewrite requires a `plan`.
136
196
  `compactFocusIds` (1 to 10,000 IDs), `pinnedFocusIds` (up to 10,000 IDs), and `symmetryGroups` (up to 64 groups) are accepted only with `layoutMode: "compact"`.
137
197
 
138
198
  Compact mode imports the tree, resets authored presentation coordinates and lane bounds, and performs a deterministic reflow in the same rewrite call. It keeps prerequisites, mutual exclusions, availability, bypasses, rewards, icons, localisation, AI behavior, and route/lane membership unchanged.
139
199
 
140
- The rewrite measures canvas bounds, same-row spacing, the same curved connector paths used by the renderer, connector lengths, connector-node intersections, branch balance, overall centering, and topology-aware fake-complexity patterns. Compact mode evaluates preservation, occupied-row repair, prerequisite-depth reflow, linear-chain repair, sibling balancing, and combined compression strategies, then chooses the cleanest valid result. Equivalent branches are aligned by dependency depth even when their authored rows differ, and connector shape is prioritized before raw canvas dimensions so a shorter canvas cannot win by introducing unnecessary horizontal detours. Sparse direct sibling fan-outs are packed around their parent at the minimum readable spacing, with each exclusive descendant branch moving as a unit and shared convergence focuses staying centered. Dense branches remain wider only when their contents need the room. It refuses invalid geometry such as overlapping or cramped focuses, bad parent order, rendered crossings, connectors through unrelated focuses, or an off-center canvas. Long connectors, fake detours, staircase or zigzag chains, and avoidable sibling imbalance are optimization priorities instead of independent rejection budgets.
200
+ The rewrite measures canvas bounds, same-row spacing, the same curved connector paths used by the renderer, connector lengths, connector-node intersections, branch balance, overall centering, and topology-aware fake-complexity patterns. Compact mode evaluates preservation, occupied-row repair, prerequisite-depth reflow, linear-chain repair, sibling balancing, and combined compression strategies, then chooses the cleanest valid result. Equivalent branches are aligned by dependency depth even when their authored rows differ, and connector shape is prioritized before raw canvas dimensions so a shorter canvas cannot win by introducing unnecessary horizontal detours. Sparse direct sibling fan-outs are packed around their parent at the minimum readable spacing, with each exclusive descendant branch moving as a unit and shared convergence focuses staying centered. Dense branches remain wider only when their contents need the room. A candidate must not be worse than the layout in place: no more hard layout errors, same-row spacing violations, crossings or connector-through-plaque counts in the in-game connector model (see [Layout quality](#layout-quality)), no worse layout verdict, and a centred canvas unless the tree already was not. A new tree starts from zero. When no candidate qualifies, or the layout already has the verdict `pass`, the call changes nothing and says why (`compactOutcome` with `reason` `verdict_pass`, `no_better_candidate` or `candidates_regress` and `blockedBy`, and the info diagnostic `FOCUS_COMPACT_NOTHING_TO_IMPROVE`); the first rewrite of a tree still writes its planning sidecar. A refusal of a new tree (`FOCUS_COMPACT_QUALITY_BLOCKED`) lists each blocking item in `details.blocking` with its before and after value and a remedy. Long connectors, fake detours, staircase or zigzag chains, and avoidable sibling imbalance are optimization priorities instead of independent rejection budgets.
141
201
 
142
202
  Use the default `layoutMode: "authored"` with a complete plan when deliberately designing coordinates or changing gameplay. Set `layoutMode: "compact"` with a complete plan when creating a large automatically arranged tree. Inspect and render calls remain useful before or after either rewrite mode, but a separate plan is not required for compact cleanup.
143
203
 
@@ -147,6 +207,42 @@ Pass `symmetryGroups` with a `centerFocusId` and one or more `{ "leftFocusId": "
147
207
 
148
208
  A cleanup should not change gameplay relationships to improve the picture. One `prerequisite` block containing several focus IDs is an OR group; several prerequisite blocks are AND requirements.
149
209
 
210
+ ## Engine layout and placement
211
+
212
+ `layoutMode: "engine"` lays out the tree's `auto` focuses with the shared Rust engine (`hoi4-engine focus-layout`, [ADR 0074](https://github.com/klimPaskov/hoi4-agent-tools/blob/main/docs/adr/0074-shared-rust-engine.md)) instead of the TypeScript solver. Fixed and relative focuses keep their coordinates. The engine places each lane as a band, centres parents over their children and children under their parents, keeps mutually exclusive focuses side by side, and never changes prerequisites or exclusions. The result is written through the ordinary source update: the topmost focus of each lane gets `x` and `y`, and every other placed focus of the lane gets `relative_position_id` to it, so moving a lane later means editing one focus. A plan is optional: `{"treeId":"my_tree","layoutMode":"engine"}` lays out the existing tree's automatic focuses.
213
+
214
+ `placement` fits new focuses into a tree whose other focuses keep their exact coordinates (the engine's `insert`). Add the new focuses with position mode `auto` to the plan that `hoi4.focus_inspect` returned, then:
215
+
216
+ ```json
217
+ {
218
+ "relativePath": "common/national_focus/my_tree.txt",
219
+ "plan": { "...": "the inspected plan with two new auto focuses" },
220
+ "placement": {
221
+ "focusIds": ["my_new_focus", "my_new_focus_2"],
222
+ "anchorId": "my_new_focus",
223
+ "preferSide": "right",
224
+ "allowShift": false
225
+ }
226
+ }
227
+ ```
228
+
229
+ - `focusIds` (1 to 10,000) are the focuses to place. With the default `layoutMode: "authored"` they must be new to the tree. With `layoutMode: "engine"` they may be existing focuses to move. Pinned focuses cannot be placed.
230
+ - `anchorId` (one of `focusIds`) is the branch root, written relative to its first prerequisite outside the branch. The other new focuses are written relative to it.
231
+ - `preferSide` is `left`, `right` or `either` (default).
232
+ - `allowShift` (default false) lets the engine move existing focuses aside when no place is free within 64 columns.
233
+ - Every focus outside `focusIds` keeps the coordinates the current source gives it. An automatic focus that has none yet is refused with `FOCUS_PLACEMENT_INVALID`: add it to `focusIds` or give it `x` and `y`.
234
+
235
+ The result has the usual `layoutQuality` verdict and `layoutDelta`, plus `data.engine`: the operation, the connector metrics the engine measured, `movedFocusIds`, any `shifted` focuses, and the engine's SHA-256 `hashes`. `hashes.untouched` covers `[{id,x,y}]` of every focus the call did not move (canonical JSON, sorted by id), so a caller can check that those focuses stayed where they were. `hashes.prerequisites` and `hashes.exclusions` show that the graph is unchanged. Engine warnings such as `FOCUS_ENGINE_LANE_BOUNDS_UNSATISFIED` and `FOCUS_ENGINE_EXISTING_CONFLICT` join the result's diagnostics. Calling again plan-free, or with the freshly inspected plan, leaves the source unchanged.
236
+
237
+ Nothing is written when the engine refuses:
238
+
239
+ - `FOCUS_ENGINE_BLOCKED`: the tree cannot be placed without breaking a layout rule. The message names the engine's reasons (`FOCUS_ENGINE_NO_CORRIDOR`, `FOCUS_ENGINE_SPACING_CONFLICT` or `FOCUS_ENGINE_PARENT_NOT_ABOVE`) and, for a placement with no free place, `needsRoom`: the shift that would make room (`fromX`, `columns`, `direction` and the focuses that would move). Retry with `allowShift: true` to apply it.
240
+ - `FOCUS_ENGINE_UNAVAILABLE`: no usable `hoi4-engine` binary. The tool uses `HOI4_ENGINE` (an absolute path) and otherwise the binary a release ships under `engine/bin/<platform>-<arch>/`. The message gives the reason (`binary_not_found`, `binary_path_invalid`, `spawn_failed`, `timeout` after 30 seconds, `output_too_large`, `exit_status` or `invalid_output`). Set `HOI4_ENGINE` to a built binary (`cargo build --release -p hoi4-engine-cli` in `engine/`) or install a release that ships the engine. There is no silent fallback to the TypeScript solver. `authored` and `compact` do not need the engine.
241
+ - `FOCUS_ENGINE_REQUEST_INVALID`: the engine refused the tree, for example for a prerequisite or relative-position cycle. The message has the engine's code.
242
+ - `FOCUS_ENGINE_LAYOUT_MISMATCH`: the coordinates prepared for the source differ from the engine's result.
243
+
244
+ The engine's algorithm and limits are in [engine/crates/focus/README.md](https://github.com/klimPaskov/hoi4-agent-tools/blob/main/engine/crates/focus/README.md).
245
+
150
246
  ## Continuous focus palettes
151
247
 
152
248
  Set `mode: "continuous"` on `hoi4.focus_inspect`, `hoi4.focus_render`, or `hoi4.focus_rewrite` to work with a `continuous_focus_palette` instead of a national tree; the default mode is `national`.
@@ -176,7 +272,7 @@ Source files are read as UTF-8 (with or without a byte order mark) and, when the
176
272
 
177
273
  ## What inspection checks
178
274
 
179
- Inspection and rendering can report missing references, invalid prerequisite structure, duplicate or overlapping positions, insufficient spacing, long or crossing connectors, branch asymmetry, route conflicts, missing localisation or sprites, weak terminal branches, repeated rewards, and missing AI metadata. National-tree inspection also returns the exact `continuous_focus_position` coordinates and linked palette IDs in its compact result, so an agent can identify and move the continuous-focus area without opening the full artifact. Renders are offline review artifacts, not game screenshots.
275
+ Inspection and rendering can report missing references, invalid prerequisite structure, duplicate or overlapping positions, insufficient spacing, long or crossing connectors, branch asymmetry (and, in the layout verdict, empty space, imbalance, drift and chains with no choice), route conflicts, missing localisation or sprites, weak terminal branches, repeated rewards, and missing AI metadata. National-tree inspection also returns the exact `continuous_focus_position` coordinates and linked palette IDs in its compact result, so an agent can identify and move the continuous-focus area without opening the full artifact. Renders are offline review artifacts, not game screenshots.
180
276
 
181
277
  For a named tree, pass `scenario: { "completedFocusIds": ["my_route_root"] }` to `hoi4.focus_inspect`. The linked inspection artifact records each focus's prerequisite groups, route locks, exclusive choices, and unresolved runtime fields against that completed set. The inline tree summary counts completed, blocked, unresolved, and structural candidate focuses, plus contradictory completed choices. A structural candidate still requires runtime trigger evaluation before an agent can call it playable.
182
278
 
@@ -184,6 +280,6 @@ Pass up to 16 `cropFocusIds` to `hoi4.focus_render` for source-linked problem cr
184
280
 
185
281
  The layout JSON reports horizontal, vertical, and Manhattan grid spans for every prerequisite connector in `layout.connectorMeasurements`.
186
282
 
187
- `hoi4.focus_render` writes complete HTML, SVG, JSON and source-map artifacts and a high-fidelity PNG with decoded icons. Pass `png: false` for the faster structural view without decoding icons. National trees with 200 or more focuses raster at half scale by default; pass `reviewScale` from `0.25` through `1` when a different PNG size is needed.
283
+ `hoi4.focus_render` returns an in-game-style schematic of the layout inline (no second call): an overview of at most 1,500 pixels and up to five close-ups of the places the scorecard blames, or of the branches named in `cropBranchIds` (up to 8; a derived branch is named by its first focus) and the focuses named in `cropFocusIds`. Failing focuses are outlined (red for hard defects, amber otherwise), exclusive choices are joined by red dashes, OR prerequisites are dotted, and a ruler shows the grid coordinates. Pass `inline: false` for linked artifacts only. The inline pictures are tool renders, not game screenshots, and carry no icons; the result lists each image in `data.inlineImages` with its region. It also writes complete HTML, SVG, JSON and source-map artifacts and a high-fidelity PNG with decoded icons. Pass `png: false` for the faster structural view without decoding icons. National trees with 200 or more focuses raster at half scale by default; pass `reviewScale` from `0.25` through `1` when a different PNG size is needed.
188
284
 
189
285
  The public workflow is regression-tested with 1,024-focus creation, compact rewrites, deterministic repeat runs, inspection, vector rendering, and raster rendering. A separate 1,024-icon test decodes a distinct texture for every focus. Large source diffs use the same deterministic review-artifact path instead of blocking at the quadratic matrix size.
package/docs/reference.md CHANGED
@@ -8,7 +8,7 @@ The server discovers these directories for a workspace:
8
8
  | Source | Default location | Optional workspace registration |
9
9
  | ------------------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------ |
10
10
  | Installed game documentation | `gameRoot/documentation/**/*.md` and `gameRoot/common/**/*documentation.md` | Configure `gameRoot`. |
11
- | Offline wiki | `modRoot/paradox_wiki/**/*.md` | Set absolute `wikiRoot`. |
11
+ | HOI4 wiki (kit) | `modRoot/hoi4_wiki/**/*.md`, else `modRoot/paradox_wiki/**/*.md` | Set absolute `wikiRoot`. |
12
12
  | Generated script documentation | `modRoot/script_docs/**/*.md` and `**/*.log` | Set absolute `scriptDocsRoot` to a user-supplied dump. |
13
13
 
14
14
  Markdown headings and recognizable standalone names in generated `.log` files form sections. A Markdown table row whose first cell is an identifier, such as a wiki effect, trigger, modifier, define, or on action, is also its own one-line section, so a citation can name the exact entry inside a long table. A dump that yields one section should be treated as insufficiently parsed; inspect its source format before relying on it. Source bytes are hashed on each request, while unchanged section indexes are reused. Missing roots are reported as unavailable. The public package contains none of these local source files.
@@ -57,15 +57,125 @@ Most use vocabulary the documentation does not: "national spirit" where script s
57
57
  Search the script name when it is known; the ranking does not add synonyms for individual questions.
58
58
  These are 61 task questions over one documentation snapshot, not a general precision guarantee.
59
59
 
60
- Run both sets with:
60
+ Run the sets with:
61
61
 
62
62
  ```bash
63
63
  npx tsx scripts/evaluate-reference-discovery.ts MOD_ROOT GAME_ROOT
64
64
  npx tsx scripts/evaluate-reference-discovery.ts MOD_ROOT GAME_ROOT --validation
65
+ npx tsx scripts/evaluate-reference-discovery.ts MOD_ROOT GAME_ROOT --held-out
65
66
  ```
66
67
 
67
68
  The script exits with a failure when a case has no expected answer in the supplied sources.
68
69
 
70
+ ## Refreshed wiki snapshot and a player vocabulary trial
71
+
72
+ Measured on 2026-11-01 against the Chaos Redux wiki snapshot refreshed on 2026-10-31 (54 wiki pages and 10 kit pages, 11,340 sections) and the installed 1.19.3.0 documentation (50 files, 3,281 sections).
73
+ The refresh renamed pages to snake case (`event_modding.md`), and the benchmark still expected `Event modding - Hearts of Iron 4 Wiki.md`, so it scored every wiki answer as a miss: 10 of 37 discovery answers first and seven cases reported as unanswerable.
74
+ The cases now accept both names.
75
+
76
+ A third set, `--held-out`, has 24 new questions written by a separate agent that was not told about the change below.
77
+ The validation set was no longer a clean check: two of its misses, "remove a national spirit" and "repeat effects", had been named in ADR 0040 as the motivating examples.
78
+
79
+ The trial expanded a plain-word query with the script word the documentation uses, at 0.6 of a query word's weight and never more informative than the player words it replaces.
80
+ `scripts/derive-reference-vocabulary.ts` mined the vocabulary from the game's English localisation, where `EFFECT_`, `TRIGGER_` and `MODIFIER_` keys name script and their text is what the player reads: 128 tooltip phrases of two or three words for documented commands ("at war" for `has_war`, "moves capital to" for `set_capital`) and 11 of 25 mined word pairs that name the same thing (conference for `pc`, technology for `tech`, freedom for `autonomy`).
81
+ The other 14 pairs only appear together ("male" and "female").
82
+ Five hand-checked entries covered what the localisation names only indirectly: national spirit to idea, temporary and expire to timed, repeat to loop, and skip to bypass ("at war" was listed by hand as well).
83
+ The entries and the weight were chosen on the discovery set alone: a hand entry from build to construction moved one discovery answer from first to second and was dropped, and weights of 0.4, 0.8 and 1.0 each placed 21 rather than 22 discovery answers first.
84
+ The held-out baseline was measured before the entries were final, but no entry was chosen from it; validation and held-out were each scored once with the final entries.
85
+
86
+ | Set and ranking | Answer first | Within three | Within five | Lands within three | Mean reciprocal rank |
87
+ | ---------------------------------- | -----------: | -----------: | ----------: | -----------------: | -------------------: |
88
+ | Discovery, current ranking | 19/37 | 27/37 | 28/37 | 25/37 | 0.595 |
89
+ | Discovery, with vocabulary (tuned) | 22/37 | 29/37 | 30/37 | 26/37 | 0.668 |
90
+ | Validation, current ranking | 11/24 | 15/24 | 18/24 | 15/24 | 0.559 |
91
+ | Validation, with vocabulary | 11/24 | 15/24 | 18/24 | 15/24 | 0.552 |
92
+ | Held-out, current ranking | 7/24 | 12/24 | 15/24 | 9/24 | 0.402 |
93
+ | Held-out, with vocabulary | 8/24 | 12/24 | 16/24 | 9/24 | 0.440 |
94
+
95
+ Both rankings placed all five exact identifiers first and returned nothing for the two negative queries.
96
+ The October discovery figures (19, 28 and 29 of 37) were measured on the previous snapshot and game documentation, so they are not a direct comparison.
97
+
98
+ The vocabulary lifted the set it was tuned on but not the questions it had never seen.
99
+ On validation, "is controlled by the AI" fell from second to third because "controlled by" also names `is_controlled_by`; on the held-out set "has researched" and "technology" found `has_tech`, "national spirit" moved `has_idea` no closer, and "does not own" pushed a claim question from third to fourth.
100
+ Across the 48 held-out and validation questions that is one more answer first and one more within five.
101
+ The trial was reverted and ADR 0040's rule against added synonyms stands; commit `ab56af1` reproduces it.
102
+
103
+ Two causes of the remaining misses are not vocabulary:
104
+
105
+ - The refreshed wiki documents some commands on more pages than the hand-checked answers name. `scopes.md` has a `for_loop_effect` row, `data_structures.md` a `check_variable` row, and `event_modding.md` a `news_event` row. The strict answers do not count them, before or after.
106
+ - When several sources have the same heading, later copies wait behind every distinct answer. For "remove a national spirit from a country" the console command `remove_ideas` ranks second, so the effect documentation and wiki copies of `remove_ideas` fall out of the first five.
107
+
108
+ ## Game text, question intent and a blind test set
109
+
110
+ Measured on 2026-11-01 on the same sources (ADR 0076).
111
+ Two changes were developed on the discovery, validation and held-out sets together (85 plain-word questions): each command entry also carries the words of its in-game tooltip or modifier name from the game's English localisation, and a question that starts with a check or an action verb prefers triggers or effects over other commands, on actions and dynamic variables.
112
+ A fourth set, `--test`, was then written by a second agent that saw none of the other sets' results: 36 plain-word questions, four exact names and two negative queries. It was scored once, before and after.
113
+
114
+ | Set | Answer first | Within three | Within five | Lands within three | Mean reciprocal rank |
115
+ | ------------------------- | -----------: | -----------: | ----------: | -----------------: | -------------------: |
116
+ | Development, before | 37/85 | 54/85 | 61/85 | 49/85 | 0.530 |
117
+ | Development, after | 40/85 | 58/85 | 63/85 | 53/85 | 0.570 |
118
+ | Discovery, after | 20/37 | 27/37 | 28/37 | 25/37 | 0.623 |
119
+ | Validation, after | 14/24 | 17/24 | 19/24 | 17/24 | 0.660 |
120
+ | Held-out, after | 6/24 | 14/24 | 16/24 | 11/24 | 0.401 |
121
+ | Blind test, before (once) | 16/40 | 25/40 | 31/40 | 22/40 | 0.547 |
122
+ | Blind test, after (once) | 20/40 | 28/40 | 31/40 | 25/40 | 0.606 |
123
+
124
+ All exact names stayed first in every set.
125
+ One blind negative query ("how to fix my graphics card driver crashing in a shooter") returned one result before and after; the other negatives returned none.
126
+ Within the development sets the held-out set lost one first place (7 to 6) while the other two gained four.
127
+ On the blind set, four questions moved to first ("some command power", "the ruling party and elections", "at war with anyone", "a decision is currently active") and "extra manpower" entered the first five, while "make all buildings construct faster" fell out of the first five because the action intent lowers modifier rows, and "use less supply" fell from second to third.
128
+
129
+ On the development sets, the question intent alone placed three more answers first (40 of 85, with 61 within five). The in-game words alone placed one fewer first and one more within five, and on top of the intent they placed two more within five and none more first; they are kept for the questions they lift into reach of a first read.
130
+ Weights of 0.4 and 0.8 for the intent penalty scored within one question of 0.6.
131
+ Pooling the full text of every copy of a command into each entry placed fewer answers first (34 of 85) and was dropped. So was a rule that kept console-command copies from demoting the script entry with the same name, which changed nothing.
132
+ Following links between wiki pages was not tried: cross-page links mostly point at whole pages, and their text repeats the target heading ("Flags" for `data_structures.md#Flags`), so they add no words a section does not already have.
133
+
134
+ Half of the blind questions still miss first place, and nine miss the first five.
135
+ The remaining misses mostly need meaning rather than shared words: "access to the sea" for `is_coastal`, "share a border" for `is_neighbor_of`, "research faster" for `research_speed_factor`, "free a puppet" for `end_puppet`.
136
+
137
+ The maintainer updated the game to 1.19.4.1 the same day; its documentation adds the `stockpile_fuel` AI strategy, changes a token list and removes one console command.
138
+ Every expected answer in all four sets is still present. Rescored on 1.19.4.1, before and after:
139
+
140
+ | Set (1.19.4.1) | Answer first | Within three | Within five | Lands within three | Mean reciprocal rank |
141
+ | ------------------ | -----------: | -----------: | ----------: | -----------------: | -------------------: |
142
+ | Discovery, before | 19/37 | 27/37 | 28/37 | 25/37 | 0.595 |
143
+ | Discovery, after | 20/37 | 27/37 | 28/37 | 25/37 | 0.623 |
144
+ | Validation, before | 11/24 | 15/24 | 18/24 | 15/24 | 0.559 |
145
+ | Validation, after | 14/24 | 17/24 | 19/24 | 17/24 | 0.660 |
146
+ | Held-out, before | 7/24 | 12/24 | 15/24 | 9/24 | 0.402 |
147
+ | Held-out, after | 6/24 | 14/24 | 16/24 | 11/24 | 0.401 |
148
+ | Blind test, before | 16/40 | 25/40 | 31/40 | 22/40 | 0.547 |
149
+ | Blind test, after | 21/40 | 27/40 | 31/40 | 24/40 | 0.613 |
150
+
151
+ The maintainer's target is the right answer first for at least 22 of 24 blind questions and within three for all of them. This ranking places about half first and two thirds within three, so the gap remains large.
152
+
153
+ ### Optional meaning layer trial
154
+
155
+ With the maintainer's approval, a local sentence-embedding layer was tried on top of the word ranking (commit `bb3c019`, reverted in `b5c1a46`).
156
+ It ran only when `HOI4_REFERENCE_EMBEDDINGS` named a cache folder and `@huggingface/transformers` 4.3.1 was installed, fetched the pinned `Xenova/all-MiniLM-L6-v2` revision `751bff37182d3f1213fa05d7196b954e230abad9` (the 22,972,370-byte quantized ONNX model and three tokenizer and config files, each checked against its pinned SHA-256), and embedded each section's page, heading and opening lines once into a 14 MB vector cache.
157
+ Meaning ranks were fused with word ranks by reciprocal rank (meaning weight 0.25, k = 10, cosine floor 0.35); exact names stayed with word ranking, and each result said which ranking ordered it.
158
+ Weights of 0.25 and 0.5 with k of 10 and 30, and embedding cleaned plain text instead of the Markdown excerpt, were compared on the development sets only.
159
+
160
+ | Set | Answer first | Within three | Within five | Lands within three | Mean reciprocal rank |
161
+ | ------------------------------------ | -----------: | -----------: | ----------: | -----------------: | -------------------: |
162
+ | Development, words | 40/85 | 58/85 | 63/85 | 53/85 | 0.570 |
163
+ | Development, words and meaning | 45/85 | 59/85 | 63/85 | 54/85 | 0.609 |
164
+ | Blind test, words (once) | 20/40 | 28/40 | 31/40 | 25/40 | 0.606 |
165
+ | Blind test, words and meaning (once) | 20/40 | 26/40 | 32/40 | 23/40 | 0.602 |
166
+
167
+ The gain on the development sets did not carry over to the blind set: the same number of first answers, two fewer within three, and the nonsense query "how to fix my graphics card driver crashing in a shooter" returned five troubleshooting sections rather than one. Exact names stayed first.
168
+ Installing the runtime adds about 470 MB (`onnxruntime-node` 288 MB, `onnxruntime-web` 141 MB, `sharp` and its images 29 MB, the library 14 MB), the model download is 23 MB, loading the model took 2.1 seconds, embedding all 14,621 sections took about 53 seconds once, and a query embedding took about 25 milliseconds.
169
+ The layer did not clearly win, so it was reverted, and the default install and ranking carry no model.
170
+ A stronger model or embedding the game's own text per command may do better, but would need a new blind set, because this one has now been used for both comparisons.
171
+
172
+ ### Speed
173
+
174
+ Before the change, every search reopened, reread and hashed all 114 documentation files. On a lightly loaded machine that inventory took a median of 70 ms of a 94 ms warm search, and with the file stamps reused it took 36 ms of 50 ms.
175
+ A warm read took 13 ms rather than 25–84 ms.
176
+ Later end-to-end runs shared the machine with other heavy work: three alternating rounds of the old and new code measured warm search medians of 145–183 ms and 84–583 ms, so no end-to-end speed gain is claimed from them.
177
+ The first `hoi4.source_lookup` still builds the whole game and mod symbol index: 53–66 seconds in three runs before this change on a lightly loaded machine, 108–192 seconds under the later load. This change does not touch it, and moving that index to the shared Rust engine is planned separately.
178
+
69
179
  ## Compact context budgets
70
180
 
71
181
  A 2026-09-27 check of the installed 3.5.0 server found that eight GUI results could contain only wiki sections even though the installed GUI documentation was available. The 3.5.1 source qualifies limits of one, two, and eight citations across the same six work surfaces. All eighteen cases retained installed documentation; limits of two or more also retained wiki citations. Required sources excluded by the limit appeared in `omittedSources`, separately from files absent under `missing`. The nine search queries still found all expected answer-bearing sections.
package/docs/setup.md CHANGED
@@ -83,7 +83,7 @@ Entries that are not plain relative folders, such as `../outside` or wildcard pa
83
83
 
84
84
  ## Add local reference material
85
85
 
86
- Place an offline wiki snapshot in `paradox_wiki/` inside the mod.
86
+ Place the kit's HOI4 wiki in `hoi4_wiki/` inside the mod. A mod the kit has not updated yet keeps working with the older `paradox_wiki/` name; when both exist, `hoi4_wiki/` wins.
87
87
  An optional generated documentation dump can go in `script_docs/`.
88
88
  For a configured workspace, `wikiRoot` and `scriptDocsRoot` can point to other absolute directories.
89
89
  The server reads these local files; it does not download the wiki.
package/docs/tools.md CHANGED
@@ -27,11 +27,11 @@ MCP clients may ask for approval to create review files.
27
27
 
28
28
  ## Focus trees
29
29
 
30
- | Tool | Purpose | Writes |
31
- | -------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------ |
32
- | `hoi4.focus_inspect` | Read focus trees, continuous-focus placement, and structural or reference problems. | review files |
33
- | `hoi4.focus_render` | Render a tree or palette as a PNG with decoded icons plus HTML, SVG, JSON and source maps; `png: false` for vector only. | review files |
34
- | `hoi4.focus_rewrite` | Create a focus tree or continuous-focus palette from a complete plan, or compact an existing tree's layout without a plan. | mod files |
30
+ | Tool | Purpose | Writes |
31
+ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------ |
32
+ | `hoi4.focus_inspect` | Read focus trees, structural or reference problems and a layout verdict with scorecard, fixes and, with `previous`, a delta. | review files |
33
+ | `hoi4.focus_render` | Return an in-game-style picture of a tree inline with close-ups, plus PNG with icons, HTML, SVG, JSON and source maps. | review files |
34
+ | `hoi4.focus_rewrite` | Create a focus tree or palette from a plan, or repair a layout; returns the layout verdict and delta, or says nothing to improve. | mod files |
35
35
 
36
36
  ## Scripted GUIs
37
37
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "hoi4-agent-tools",
3
- "version": "4.6.5",
3
+ "version": "4.7.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "hoi4-agent-tools",
9
- "version": "4.6.5",
9
+ "version": "4.7.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@fontsource-variable/roboto": "5.3.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hoi4-agent-tools",
3
3
  "mcpName": "io.github.klimPaskov/hoi4-agent-tools",
4
- "version": "4.6.5",
4
+ "version": "4.7.0",
5
5
  "description": "Build HOI4 mods: focus trees, events, decisions, worlds, GUI previews, docs and AI balance.",
6
6
  "type": "module",
7
7
  "license": "Apache-2.0",
@@ -102,6 +102,7 @@
102
102
  "fixtures:generate:technology": "tsx scripts/generate-technology-fixture.ts",
103
103
  "fixtures:generate:probability": "tsx scripts/generate-probability-fixture.ts",
104
104
  "fixtures:check": "npm run fixtures:generate && tsx scripts/check-generated.ts fixtures",
105
+ "focus:calibrate": "tsx scripts/focus-quality-calibration.ts",
105
106
  "schemas:generate": "tsx scripts/generate-schemas.ts",
106
107
  "schemas:check": "tsx scripts/generate-schemas.ts && tsx scripts/check-generated.ts schemas",
107
108
  "registry:validate": "tsx scripts/validate-registry.ts",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/configuration.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/configuration.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/continuous-focus-palette.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/continuous-focus-palette.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/custom-weighted-pool.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/custom-weighted-pool.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/decision-inspect-input.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/decision-inspect-input.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/error-log-input.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/error-log-input.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.6.5/schemas/event-feature-manifest.schema.json",
2
+ "$id": "https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.7.0/schemas/event-feature-manifest.schema.json",
3
3
  "$schema": "https://json-schema.org/draft/2020-12/schema",
4
4
  "type": "object",
5
5
  "properties": {