hoi4-agent-tools 4.7.0 → 4.9.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 (120) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +32 -13
  3. package/dist/hoi4_agent_tools/core/engine-client.js +74 -5
  4. package/dist/hoi4_agent_tools/core/index.js +28 -0
  5. package/dist/hoi4_agent_tools/core/operation-result.js +9 -0
  6. package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
  7. package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
  8. package/dist/hoi4_agent_tools/decision/service.js +46 -2
  9. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  10. package/dist/hoi4_agent_tools/event/service.js +78 -11
  11. package/dist/hoi4_agent_tools/event/summary.js +9 -0
  12. package/dist/hoi4_agent_tools/focus/engine-layout.js +1 -1
  13. package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
  14. package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
  15. package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
  16. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +241 -241
  17. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +30 -19
  18. package/dist/hoi4_agent_tools/focus/quality/schematic.js +5 -3
  19. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +1 -1
  20. package/dist/hoi4_agent_tools/focus/render.js +21 -9
  21. package/dist/hoi4_agent_tools/focus/tool-operations.js +158 -3
  22. package/dist/hoi4_agent_tools/gui/assets.js +18 -0
  23. package/dist/hoi4_agent_tools/gui/dds.js +38 -5
  24. package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
  25. package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
  26. package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
  27. package/dist/hoi4_agent_tools/gui/validators.js +31 -2
  28. package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
  29. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  30. package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
  31. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  32. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -2
  33. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  34. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  35. package/dist/hoi4_agent_tools/map/world.js +158 -34
  36. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +59 -9
  37. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  38. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  39. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  40. package/dist/hoi4_agent_tools/mcp/tools/event.js +15 -0
  41. package/dist/hoi4_agent_tools/mcp/tools/focus.js +1 -1
  42. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  43. package/dist/hoi4_agent_tools/mcp/tools/reference.js +43 -0
  44. package/dist/hoi4_agent_tools/probability/operations.js +27 -1
  45. package/dist/hoi4_agent_tools/probability/service.js +91 -11
  46. package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
  47. package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
  48. package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
  49. package/dist/hoi4_agent_tools/reference/error-log.js +59 -1
  50. package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
  51. package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
  52. package/dist/hoi4_agent_tools/reference/operations.js +205 -12
  53. package/dist/hoi4_agent_tools/reference/ranking.js +32 -0
  54. package/dist/hoi4_agent_tools/reference/script-validation.js +159 -8
  55. package/dist/hoi4_agent_tools/reference/service.js +33 -0
  56. package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
  57. package/dist/hoi4_agent_tools/schemas/focus-requests.js +4 -0
  58. package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
  59. package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
  60. package/dist/hoi4_agent_tools/schemas/map.js +32 -4
  61. package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
  62. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  63. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  64. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  65. package/dist/hoi4_agent_tools/version.js +1 -1
  66. package/docs/analysis.md +2 -2
  67. package/docs/events.md +1 -1
  68. package/docs/focus.md +9 -5
  69. package/docs/map.md +19 -8
  70. package/docs/research/reference-benchmark.md +41 -0
  71. package/docs/tools.md +49 -39
  72. package/docs/troubleshooting.md +13 -12
  73. package/engine/README.md +293 -0
  74. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  75. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  76. package/engine/bin/linux-x64/hoi4-engine +0 -0
  77. package/engine/bin/manifest.json +26 -0
  78. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  79. package/npm-shrinkwrap.json +2 -2
  80. package/package.json +4 -1
  81. package/schemas/configuration.schema.json +1 -1
  82. package/schemas/continuous-focus-palette.schema.json +1 -1
  83. package/schemas/custom-weighted-pool.schema.json +1 -1
  84. package/schemas/decision-inspect-input.schema.json +1 -1
  85. package/schemas/error-log-input.schema.json +1 -1
  86. package/schemas/event-feature-manifest.schema.json +1 -1
  87. package/schemas/focus-plan.schema.json +1 -1
  88. package/schemas/focus-planning-sidecar.schema.json +1 -1
  89. package/schemas/geography-model.schema.json +1 -1
  90. package/schemas/gui-animation-source.schema.json +1 -1
  91. package/schemas/gui-helper.schema.json +1 -1
  92. package/schemas/gui-scenario.schema.json +1 -1
  93. package/schemas/helper-expansion-request.schema.json +1 -1
  94. package/schemas/helper-expansion-summary.schema.json +1 -1
  95. package/schemas/impact-inspect-input.schema.json +1 -1
  96. package/schemas/map-operation.schema.json +165 -101
  97. package/schemas/mechanic-test-input.schema.json +1 -1
  98. package/schemas/mod-index-input.schema.json +1 -1
  99. package/schemas/operation-result.schema.json +1 -1
  100. package/schemas/package-check-input.schema.json +1 -1
  101. package/schemas/package-manifest.schema.json +1 -1
  102. package/schemas/probability-analysis-result.schema.json +1 -1
  103. package/schemas/probability-compare-input.schema.json +1 -1
  104. package/schemas/probability-evaluate-input.schema.json +1 -1
  105. package/schemas/probability-inspect-input.schema.json +1 -1
  106. package/schemas/probability-render-input.schema.json +1 -1
  107. package/schemas/probability-scenario-set.schema.json +1 -1
  108. package/schemas/probability-sequence-input.schema.json +1 -1
  109. package/schemas/probability-simulate-input.schema.json +1 -1
  110. package/schemas/probability-sweep-input.schema.json +1 -1
  111. package/schemas/reference-context-input.schema.json +1 -1
  112. package/schemas/reference-read-input.schema.json +1 -1
  113. package/schemas/reference-search-input.schema.json +1 -1
  114. package/schemas/reference-sheets.schema.json +1 -1
  115. package/schemas/scenario-suite.schema.json +1 -1
  116. package/schemas/scenario-test-input.schema.json +1 -1
  117. package/schemas/script-validate-input.schema.json +1 -1
  118. package/schemas/shared-scenario.schema.json +1 -1
  119. package/schemas/source-lookup-input.schema.json +1 -1
  120. package/server.json +2 -2
@@ -4,10 +4,38 @@ import { canonicalJson, hashCanonical } from '../core/canonical.js';
4
4
  import { setInlineFilesScanned } from '../core/operation-result.js';
5
5
  import { emptyServiceResult, ServiceError } from '../core/result.js';
6
6
  import { buildProposedSourceOverlay } from '../core/source-overlay.js';
7
+ import { nearestNames } from '../reference/suggestions.js';
7
8
  import { PACKAGE_VERSION } from '../version.js';
8
9
  import { inspectDecisionAi } from './ai.js';
9
10
  import { compareDecisionScenarios, inspectDecisionScenario } from './comparison.js';
10
- import { decisionSourceInventory, decisionTargetCatalog } from './source-inventory.js';
11
+ import { decisionSourceInventory, decisionTargetCatalog, } from './source-inventory.js';
12
+ /**
13
+ * An inventory narrowed to one category (its decisions) or one decision (#59). Any other id is
14
+ * not-found with close names, never a whole-workspace inventory.
15
+ */
16
+ function scopedInventory(inventory, id, complete) {
17
+ const ids = new Set([id]);
18
+ const isCategory = inventory.categories.some((category) => category.id === id);
19
+ const decisions = inventory.decisions.filter((source) => isCategory ? source.category === id : source.id === id);
20
+ if (!isCategory && decisions.length === 0) {
21
+ const suggestions = nearestNames(id, new Set([
22
+ ...inventory.categories.map((category) => category.id),
23
+ ...inventory.decisions.map((source) => source.id),
24
+ ]));
25
+ throw new ServiceError('DECISION_NOT_FOUND', `No decision or decision category ${id.slice(0, 256)} is defined${complete ? '' : ' in the scanned files (the scan is incomplete)'}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: id.slice(0, 256), suggestions, scanComplete: complete });
26
+ }
27
+ for (const source of decisions) {
28
+ ids.add(source.category);
29
+ ids.add(source.id);
30
+ }
31
+ return {
32
+ ...inventory,
33
+ decisions,
34
+ categories: inventory.categories.filter((category) => ids.has(category.id)),
35
+ overrides: inventory.overrides.filter((override) => ids.has(override.id)),
36
+ unresolvedDefinitions: inventory.unresolvedDefinitions.filter((entry) => ids.has(entry.id)),
37
+ };
38
+ }
11
39
  /** Authorized, read-only decision operation over the shared source scanner. */
12
40
  export class DecisionAnalyzer {
13
41
  engine;
@@ -32,7 +60,16 @@ export class DecisionAnalyzer {
32
60
  throw new ServiceError('DECISION_PROPOSAL_REQUIRED', 'Decision comparison requires proposed sources');
33
61
  if (input.mode !== 'compare' && input.proposedSources !== undefined)
34
62
  throw new ServiceError('DECISION_PROPOSAL_MODE', 'Proposed sources require compare mode');
35
- const inventory = decisionSourceInventory(before);
63
+ const fullInventory = decisionSourceInventory(before);
64
+ const inventory = input.mode === 'inventory' && input.id !== undefined
65
+ ? scopedInventory(fullInventory, input.id, before.complete)
66
+ : fullInventory;
67
+ if (input.mode === 'inspect' &&
68
+ input.id !== undefined &&
69
+ !inventory.decisions.some((source) => source.id === input.id)) {
70
+ const suggestions = nearestNames(input.id, new Set(inventory.decisions.map((source) => source.id)));
71
+ throw new ServiceError('DECISION_NOT_FOUND', `No decision ${input.id.slice(0, 256)} is defined${before.complete ? '' : ' in the scanned files (the scan is incomplete)'}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: input.id.slice(0, 256), suggestions, scanComplete: before.complete });
72
+ }
36
73
  const overlay = input.proposedSources === undefined
37
74
  ? undefined
38
75
  : buildProposedSourceOverlay(before, workspace, input.proposedSources);
@@ -149,6 +186,13 @@ export class DecisionAnalyzer {
149
186
  categories: inventory.categories.length,
150
187
  overrides: inventory.overrides.length,
151
188
  scenarios: input.mode === 'inventory' ? 0 : input.scenarios.length,
189
+ // A scoped inventory answers inline: the decisions of that category or the one decision.
190
+ ...(input.mode === 'inventory' && input.id !== undefined
191
+ ? {
192
+ decisionIds: inventory.decisions.slice(0, 64).map(({ id }) => id),
193
+ decisionIdsTruncated: inventory.decisions.length > 64,
194
+ }
195
+ : {}),
152
196
  unresolvedDefinitions: inventory.unresolvedDefinitions.length,
153
197
  ...(inventory.unresolvedDefinitions.length === 0
154
198
  ? {}
@@ -103,11 +103,34 @@ export function selectEventNodes(graph, selector, signal) {
103
103
  signal?.throwIfAborted();
104
104
  return matched.sort((left, right) => compareCodeUnits(left.id, right.id));
105
105
  }
106
- export function discoverEventRoots(graph, signal) {
106
+ export function discoverEventRoots(graph, signal, selector) {
107
+ const roots = allEventRoots(graph, signal);
108
+ if (selector === undefined)
109
+ return roots;
110
+ // A selector keeps the roots among its nodes, the entry points that start them and the
111
+ // cycles through them (#59).
112
+ const selected = new Set(selectEventNodes(graph, selector, signal).map(({ id }) => id));
113
+ const startsSelected = new Set(eventFlowEdges(graph, false)
114
+ .filter(({ to }) => selected.has(to))
115
+ .map(({ from }) => from));
116
+ const ids = new Set(graph.nodes
117
+ .filter(({ id, kind }) => kind === 'event' && selected.has(id))
118
+ .flatMap(({ eventId }) => (eventId === undefined ? [] : [eventId])));
119
+ return {
120
+ entryPoints: roots.entryPoints.filter(({ id }) => selected.has(id) || startsSelected.has(id)),
121
+ automaticEvents: roots.automaticEvents.filter(({ id }) => selected.has(id)),
122
+ knownRootEventIds: roots.knownRootEventIds.filter((id) => ids.has(id)),
123
+ callerlessTriggeredEvents: roots.callerlessTriggeredEvents.filter(({ id }) => selected.has(id)),
124
+ stronglyConnectedComponents: roots.stronglyConnectedComponents.filter(({ nodeIds }) => nodeIds.some((id) => selected.has(id))),
125
+ };
126
+ }
127
+ function allEventRoots(graph, signal) {
107
128
  signal?.throwIfAborted();
108
129
  const edges = eventFlowEdges(graph, false);
109
130
  const incoming = new Map();
110
- for (const [index, edge] of edges.entries()) {
131
+ // An event a scripted effect fires has a caller. Roots do not project helpers, so count the
132
+ // direct edges too, helper edges included.
133
+ for (const [index, edge] of [...edges, ...eventFlowEdges(graph, true)].entries()) {
111
134
  if ((index & 255) === 0)
112
135
  signal?.throwIfAborted();
113
136
  incoming.set(edge.to, (incoming.get(edge.to) ?? 0) + 1);
@@ -6,6 +6,7 @@ import { canonicalJson, canonicalJsonByteLength, compareCodeUnits, hashCanonical
6
6
  import { installedEffectCommands } from '../core/game-documentation.js';
7
7
  import { boundedSourceHashEvidence, publicArtifactLink, } from '../core/artifacts.js';
8
8
  import { ServiceError } from '../core/result.js';
9
+ import { nearestNames } from '../reference/suggestions.js';
9
10
  import { RenderBudget } from '../core/render-budget.js';
10
11
  import { SOURCE_MAX_BYTES } from '../core/source/index.js';
11
12
  import { isPortablePathSegment } from '../core/workspace.js';
@@ -13,7 +14,7 @@ import { PACKAGE_VERSION } from '../version.js';
13
14
  import { buildEventGraph, buildEventGraphAsync } from './graph.js';
14
15
  import { summarizeEventImpact, summarizeEventIssues, summarizeEventPath, summarizeEventRoots, summarizeEventTrace, } from './summary.js';
15
16
  import { EVENT_FRAGMENT_CACHE_MAX_ENTRIES, EVENT_FRAGMENT_CACHE_MAX_SOURCE_BYTES, EVENT_GRAPH_SNAPSHOT_MAX_BYTES, EVENT_PROPOSED_SOURCE_MAX_BYTES, EVENT_PROPOSED_SOURCE_MAX_FILES, } from './limits.js';
16
- import { analyzeEventImpact, discoverEventRoots, explainEventPath, inspectEventStateFlow, lintEventGraph, traceSelectedEvents, } from './queries.js';
17
+ import { analyzeEventImpact, discoverEventRoots, explainEventPath, inspectEventStateFlow, lintEventGraph, selectEventNodes, traceSelectedEvents, } from './queries.js';
17
18
  import { compareEventGraphs, eventGraphHash } from './compare.js';
18
19
  import { selectEventComparison } from './comparison-selection.js';
19
20
  import { eventFlowEdges } from './algorithms.js';
@@ -161,9 +162,15 @@ function engineGeneration(engine, workspaceId) {
161
162
  function eventScanPatterns(workspace, focused = false) {
162
163
  const roots = workspace.registration.roots;
163
164
  const under = (values, glob) => values.map((root) => `${root.replaceAll('\\', '/').replace(/\/$/u, '')}/${glob}`);
164
- if (focused) {
165
- return ['events/**/*.txt', 'common/on_actions/**/*.txt'].sort(compareCodeUnits);
166
- }
165
+ // A focused route still resolves scripted-effect helpers and follows callers back through
166
+ // them, so it scans every folder that can define or call one. Only localisation, which
167
+ // feeds the skipped lint passes, is left out.
168
+ const localisation = focused
169
+ ? []
170
+ : [
171
+ ...under(roots.localisation, 'english/**/*.{yml,yaml}'),
172
+ ...under(roots.localisation, '*.{yml,yaml}'),
173
+ ];
167
174
  return [
168
175
  'events/**/*.txt',
169
176
  'history/countries/**/*.txt',
@@ -182,8 +189,7 @@ function eventScanPatterns(workspace, focused = false) {
182
189
  'common/scripted_effects/**/*.txt',
183
190
  ...under(roots.focus, '**/*.txt'),
184
191
  ...under(roots.scriptedGui, '**/*.txt'),
185
- ...under(roots.localisation, 'english/**/*.{yml,yaml}'),
186
- ...under(roots.localisation, '*.{yml,yaml}'),
192
+ ...localisation,
187
193
  ].sort(compareCodeUnits);
188
194
  }
189
195
  async function scanEventSources(engine, workspaceId, workspace, focused = false, signal) {
@@ -265,6 +271,25 @@ function boundedEvidence(values, limit = EVENT_FOCUSED_EVIDENCE_LIMIT) {
265
271
  inventory: { count: values.length, retainedCount: limit, truncated: true },
266
272
  };
267
273
  }
274
+ /** The not-found for a selector no scanned node matches, with close names where there are any. */
275
+ function selectorNotFound(graph, selector) {
276
+ const close = (value, names) => nearestNames(value, new Set([...names].filter((name) => name !== undefined)));
277
+ const hint = (suggestions) => suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`;
278
+ switch (selector.kind) {
279
+ case 'event': {
280
+ const suggestions = close(selector.eventId, graph.nodes.map(({ eventId }) => eventId));
281
+ return new ServiceError('EVENT_NOT_FOUND', `No scanned file defines or fires event ${selector.eventId.slice(0, 256)}${hint(suggestions)}`, { eventId: selector.eventId.slice(0, 256), suggestions });
282
+ }
283
+ case 'namespace': {
284
+ const suggestions = close(selector.namespace, graph.nodes.map(({ namespace }) => namespace));
285
+ return new ServiceError('EVENT_NAMESPACE_NOT_FOUND', `No scanned event belongs to the namespace ${selector.namespace.slice(0, 256)}${hint(suggestions)}`, { namespace: selector.namespace.slice(0, 256), suggestions });
286
+ }
287
+ case 'node':
288
+ return new ServiceError('EVENT_NODE_NOT_FOUND', `No node ${selector.nodeId.slice(0, 256)} is in the event graph`, { nodeId: selector.nodeId.slice(0, 256) });
289
+ default:
290
+ return new ServiceError('EVENT_SOURCE_NOT_FOUND', 'No event, option or entry point of the event graph is in the selected source', { selector: selector.kind });
291
+ }
292
+ }
268
293
  function boundedUnresolved(graph, selectedNodeIds) {
269
294
  const relevant = selectedNodeIds === undefined
270
295
  ? graph.unresolved
@@ -828,17 +853,32 @@ export class EventChainViewer {
828
853
  ...(input.impactSubject === undefined ? {} : { impactSubject: input.impactSubject }),
829
854
  refresh: input.refresh ?? input.mode === 'scan',
830
855
  };
856
+ // A selector or state subject that matches nothing is not-found, never an empty answer (#59).
857
+ if (input.selector !== undefined &&
858
+ input.mode !== 'impact' &&
859
+ selectEventNodes(graph, input.selector).length === 0)
860
+ throw selectorNotFound(graph, input.selector);
861
+ if (input.mode === 'state_flow' &&
862
+ input.stateSubject !== undefined &&
863
+ !graph.stateAccesses.some(({ kind, name }) => kind === input.stateSubject.kind && name === input.stateSubject.name)) {
864
+ const { kind, name } = input.stateSubject;
865
+ const suggestions = nearestNames(name, new Set(graph.stateAccesses.filter((access) => access.kind === kind).map((a) => a.name)));
866
+ throw new ServiceError('EVENT_STATE_NOT_FOUND', `No scanned file sets, checks or clears the ${kind.replaceAll('_', ' ')} ${name.slice(0, 256)}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { kind, name: name.slice(0, 256), suggestions });
867
+ }
831
868
  let report;
832
869
  let summary;
833
870
  switch (input.mode) {
834
871
  case 'scan':
835
872
  report = eventScanReport(graph);
836
- summary = summarizeEventIssues(graph.issues);
873
+ // A selector narrows the findings to its events, as lint does (#59).
874
+ summary = summarizeEventIssues(input.selector === undefined
875
+ ? graph.issues
876
+ : lintEventGraph(graph, input.selector, input.signal));
837
877
  break;
838
878
  case 'roots':
839
879
  {
840
880
  const unresolved = boundedUnresolved(graph);
841
- const roots = discoverEventRoots(graph, input.signal);
881
+ const roots = discoverEventRoots(graph, input.signal, input.selector);
842
882
  summary = summarizeEventRoots(roots);
843
883
  report = {
844
884
  graphRevision: graph.revision,
@@ -894,13 +934,40 @@ export class EventChainViewer {
894
934
  case 'state_flow':
895
935
  {
896
936
  const unresolved = boundedUnresolved(graph);
897
- const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code));
898
- summary = summarizeEventIssues(stateIssues);
937
+ const subject = input.stateSubject;
938
+ const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code, details }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code) &&
939
+ // A subject narrows the issues as well as the flow. Analysis limits stay, because
940
+ // they make the flow partial.
941
+ (subject === undefined ||
942
+ (typeof details.name === 'string'
943
+ ? details.name === subject.name &&
944
+ (details.stateKind === undefined || details.stateKind === subject.kind)
945
+ : code.endsWith('_LIMIT'))));
946
+ const flow = inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal);
947
+ const where = (accesses) => accesses.slice(0, 8).map(({ location }) => `${location.path}:${location.start.line}`);
948
+ summary = {
949
+ ...summarizeEventIssues(stateIssues),
950
+ // The subject's own flow answers inline; the report holds every access.
951
+ ...(subject === undefined
952
+ ? {}
953
+ : {
954
+ flow: {
955
+ subject: `${subject.kind}:${subject.name}`,
956
+ producers: flow.producers.length,
957
+ consumers: flow.consumers.length,
958
+ clears: flow.clears.length,
959
+ links: flow.links.length,
960
+ unproducedReads: flow.unproducedReads.length,
961
+ producedAt: where(flow.producers),
962
+ readAt: where(flow.consumers),
963
+ },
964
+ }),
965
+ };
899
966
  const issues = boundedEvidence(stateIssues);
900
967
  report = {
901
968
  graphRevision: graph.revision,
902
969
  sourceHashes: graph.sourceHashes,
903
- flow: inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal),
970
+ flow,
904
971
  issues: issues.values,
905
972
  unresolved: unresolved.values,
906
973
  ...(issues.inventory === undefined ? {} : { issueInventory: issues.inventory }),
@@ -3,6 +3,7 @@ import { compareCodeUnits } from '../core/canonical.js';
3
3
  export const EVENT_INLINE_FINDINGS = 10;
4
4
  const EVENT_INLINE_CODES = 10;
5
5
  const EVENT_INLINE_EVENT_IDS = 20;
6
+ const EVENT_INLINE_TRACE_NAMES = 20;
6
7
  const EVENT_INLINE_MESSAGE_LENGTH = 300;
7
8
  const CLASSIFICATION_ORDER = {
8
9
  confirmed_error: 0,
@@ -72,11 +73,19 @@ export function summarizeEventTrace(trace) {
72
73
  const events = trace.nodes
73
74
  .flatMap(({ kind, eventId }) => (kind === 'event' && eventId !== undefined ? [eventId] : []))
74
75
  .sort(compareCodeUnits);
76
+ // Callers that reach an event through scripted effects, decisions or focuses are not events,
77
+ // so name them here as well. Otherwise an upstream trace looks callerless without its report.
78
+ const entries = [
79
+ ...new Set(trace.nodes.flatMap(({ kind, label }) => (kind === 'entry' ? [label] : []))),
80
+ ].sort(compareCodeUnits);
81
+ const helpers = [...new Set(trace.edges.flatMap(({ helperStack }) => helperStack))].sort(compareCodeUnits);
75
82
  return {
76
83
  nodes: trace.nodes.length,
77
84
  edges: trace.edges.length,
78
85
  events: events.length,
79
86
  eventIds: events.slice(0, EVENT_INLINE_EVENT_IDS),
87
+ entryPoints: entries.slice(0, EVENT_INLINE_TRACE_NAMES),
88
+ helpers: helpers.slice(0, EVENT_INLINE_TRACE_NAMES),
80
89
  boundaryNodes: trace.boundaryNodeIds.length,
81
90
  truncated: trace.truncated,
82
91
  };
@@ -1,7 +1,7 @@
1
1
  import { FOCUS_LAYOUT_REQUEST_SCHEMA, runFocusLayoutEngine, } from '../core/engine-client.js';
2
2
  import { ServiceError } from '../core/result.js';
3
3
  import { focusLaneId } from './layout.js';
4
- export const FOCUS_ENGINE_REMEDY = 'Set HOI4_ENGINE to the absolute path of a hoi4-engine binary (cargo build --release -p hoi4-engine-cli in engine/), or install a hoi4-agent-tools release that ships the engine for this platform. layoutMode authored and compact do not need it.';
4
+ export const FOCUS_ENGINE_REMEDY = 'The package bundles hoi4-engine for Windows x64, macOS arm64 and Linux x64 and arm64; reinstall it if the bundled binary fails its checksum. Elsewhere, set HOI4_ENGINE to the absolute path of a hoi4-engine binary (cargo build --release -p hoi4-engine-cli in engine/). layoutMode authored and compact do not need it.';
5
5
  const MOVED_FOCUS_ID_LIMIT = 100;
6
6
  function enginePosition(position) {
7
7
  if (position.mode === 'fixed')
@@ -0,0 +1,72 @@
1
+ import { sharedResidentEngine, } from '../core/resident-engine.js';
2
+ const MAX_LOCALISATION_DEPTH = 4;
3
+ /** A localisation value with `$KEY$` references resolved, or undefined when the key has none. */
4
+ function localised(index, language, key, depth = 0) {
5
+ const entry = index.find('localisation', `${language}:${key}`);
6
+ const value = typeof entry?.metadata.value === 'string' ? entry.metadata.value : undefined;
7
+ if (value === undefined || depth >= MAX_LOCALISATION_DEPTH)
8
+ return value;
9
+ return value.replace(/\$([A-Za-z0-9_.-]+)(?:\|[^$]*)?\$/gu, (whole, inner) => inner === key ? whole : (localised(index, language, inner, depth + 1) ?? whole));
10
+ }
11
+ /** The game's layers in load order: game, DLC, dependencies, then the mod. */
12
+ export function gameLayers(workspace) {
13
+ return workspace.roots
14
+ .filter(({ kind }) => kind === 'game' || kind === 'dlc' || kind === 'dependency' || kind === 'mod')
15
+ .sort((left, right) => left.loadOrder - right.loadOrder)
16
+ .map((root) => ({
17
+ name: 'label' in root && typeof root.label === 'string' ? root.label : root.kind,
18
+ path: root.path,
19
+ replacePaths: root.replacePaths,
20
+ }));
21
+ }
22
+ export async function renderFocusGameView(input) {
23
+ const positions = new Map(input.layout.nodes.map((node) => [node.id, node]));
24
+ const titles = {};
25
+ const focuses = input.plan.focuses.flatMap((focus) => {
26
+ const node = positions.get(focus.id);
27
+ if (node === undefined)
28
+ return [];
29
+ const value = localised(input.index, input.language, focus.localisation.titleKey);
30
+ // The game shows the raw key when a title has no localisation.
31
+ const title = value ?? focus.localisation.titleKey;
32
+ titles[focus.id] = { text: title, resolved: value !== undefined };
33
+ return [
34
+ {
35
+ id: focus.id,
36
+ x: node.x,
37
+ y: node.y,
38
+ ...(focus.icons[0] === undefined ? {} : { icon: focus.icons[0].sprite }),
39
+ title,
40
+ prerequisites: focus.prerequisites.groups.map(({ focusIds }) => focusIds),
41
+ mutuallyExclusive: focus.mutuallyExclusive,
42
+ },
43
+ ];
44
+ });
45
+ const request = { focuses, scale: input.scale, maxPixels: input.maxPixels };
46
+ const engine = input.engine ?? sharedResidentEngine();
47
+ const outcome = await engine.request('focus.render', {
48
+ layers: gameLayers(input.workspace),
49
+ request,
50
+ }, undefined, input.signal === undefined ? {} : { signal: input.signal });
51
+ if (!outcome.ok)
52
+ return outcome.kind === 'error'
53
+ ? { ok: false, code: outcome.code, message: outcome.message }
54
+ : { ok: false, code: outcome.reason, message: outcome.message };
55
+ const result = outcome.response.result;
56
+ const report = result.report;
57
+ if (report === undefined ||
58
+ typeof report.width !== 'number' ||
59
+ !Array.isArray(report.focuses) ||
60
+ !Array.isArray(report.missing) ||
61
+ outcome.response.payload.length === 0)
62
+ return { ok: false, code: 'invalid_output', message: 'The engine returned no focus render' };
63
+ return {
64
+ ok: true,
65
+ png: outcome.response.payload,
66
+ report,
67
+ cache: result.cache ?? {},
68
+ timings: result.timings ?? {},
69
+ titles,
70
+ request,
71
+ };
72
+ }
@@ -0,0 +1,160 @@
1
+ import sharp from 'sharp';
2
+ import { ArtifactStore, boundedSourceHashEvidence, } from '../core/artifacts.js';
3
+ import { canonicalJson, sha256Bytes } from '../core/canonical.js';
4
+ import { PACKAGE_VERSION } from '../version.js';
5
+ /**
6
+ * Artifacts of the game view alone (`view: "game"`): the PNG, a JSON report, an SVG hover map
7
+ * on the same pixels and a self-contained HTML viewer with zoom and hover titles. No schematic is
8
+ * drawn, so this is the fast path an in-app preview calls on every edit.
9
+ */
10
+ const artifacts = new ArtifactStore();
11
+ /** Longest edge of the inline overview. */
12
+ const INLINE_EDGE = 1500;
13
+ /** Largest inline overview, the same budget as the schematic pictures. */
14
+ const INLINE_BYTES = 700_000;
15
+ function escapeXml(value) {
16
+ return value
17
+ .replaceAll('&', '&')
18
+ .replaceAll('<', '&lt;')
19
+ .replaceAll('>', '&gt;')
20
+ .replaceAll('"', '&quot;')
21
+ .replaceAll("'", '&apos;');
22
+ }
23
+ function safeStem(value) {
24
+ const safe = value
25
+ .replace(/[^A-Za-z0-9._-]+/gu, '_')
26
+ .replace(/^[_-]+/u, '')
27
+ .slice(0, 80);
28
+ return safe.length === 0 ? 'focus-tree' : safe;
29
+ }
30
+ export async function gameViewBundle(plan, layout, png, report, titles, request) {
31
+ const boxes = report.focuses
32
+ .map((box) => {
33
+ const title = titles[box.id]?.text ?? box.id;
34
+ return `<rect class="focus" data-focus-id="${escapeXml(box.id)}" x="${box.x}" y="${box.y}" width="${box.width}" height="${box.height}"><title>${escapeXml(`${title} (${box.id})`)}</title></rect>`;
35
+ })
36
+ .join('\n');
37
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${report.width}" height="${report.height}" viewBox="0 0 ${report.width} ${report.height}" role="img" aria-label="${escapeXml(plan.id)} focus tree, game view hover map">
38
+ <style>.focus{fill:transparent;stroke:none}.focus:hover{stroke:#66d9ef;stroke-width:2}</style>
39
+ ${boxes}
40
+ </svg>
41
+ `;
42
+ const json = `${canonicalJson({
43
+ schemaVersion: 1,
44
+ view: 'game',
45
+ tree: {
46
+ id: plan.id,
47
+ sourcePath: plan.provenance.sourcePath,
48
+ sourceHash: plan.provenance.sourceHash,
49
+ focusCount: plan.focuses.length,
50
+ },
51
+ layout: { hash: layout.layoutHash, nodes: layout.nodes.map(({ id, x, y }) => ({ id, x, y })) },
52
+ render: report,
53
+ titles,
54
+ request,
55
+ })}\n`;
56
+ const html = `<!doctype html>
57
+ <html lang="en">
58
+ <head>
59
+ <meta charset="utf-8">
60
+ <meta name="viewport" content="width=device-width,initial-scale=1">
61
+ <title>${escapeXml(plan.id)} focus tree · game view · HOI4 Agent Tools</title>
62
+ <style>
63
+ html,body{margin:0;height:100%;background:#111;color:#ddd;font-family:system-ui,sans-serif}
64
+ #view{position:absolute;inset:0;overflow:hidden;cursor:grab}
65
+ #stage{position:absolute;transform-origin:0 0}
66
+ #stage img,#stage svg{position:absolute;left:0;top:0;display:block}
67
+ #note{position:fixed;left:8px;bottom:8px;font-size:12px;background:#000a;padding:4px 8px;border-radius:4px}
68
+ </style>
69
+ </head>
70
+ <body>
71
+ <div id="view"><div id="stage"><img alt="${escapeXml(plan.id)} focus tree as the game draws it" width="${report.width}" height="${report.height}" src="data:image/png;base64,${png.toString('base64')}">${svg}</div></div>
72
+ <div id="note">${escapeXml(plan.id)} · ${plan.focuses.length} focuses · wheel to zoom, drag to move, hover for titles. Tool render, not a game screenshot.</div>
73
+ <script>
74
+ const view=document.getElementById('view'),stage=document.getElementById('stage');
75
+ let scale=Math.min(1,view.clientWidth/${report.width}),x=0,y=0,drag;
76
+ const apply=()=>{stage.style.transform='translate('+x+'px,'+y+'px) scale('+scale+')'};
77
+ view.addEventListener('wheel',(e)=>{e.preventDefault();const k=Math.exp(-e.deltaY*0.0015),n=Math.min(8,Math.max(0.05,scale*k));x=e.clientX-(e.clientX-x)*n/scale;y=e.clientY-(e.clientY-y)*n/scale;scale=n;apply()},{passive:false});
78
+ view.addEventListener('pointerdown',(e)=>{drag=[e.clientX-x,e.clientY-y];view.setPointerCapture(e.pointerId)});
79
+ view.addEventListener('pointermove',(e)=>{if(drag){x=e.clientX-drag[0];y=e.clientY-drag[1];apply()}});
80
+ view.addEventListener('pointerup',()=>{drag=undefined});
81
+ apply();
82
+ </script>
83
+ </body>
84
+ </html>
85
+ `;
86
+ // The overview shrinks until it fits the inline byte budget, like the schematic pictures.
87
+ let fit = Math.min(1, INLINE_EDGE / Math.max(report.width, report.height));
88
+ let inlinePng = png;
89
+ for (let attempt = 0; attempt < 6; attempt += 1) {
90
+ inlinePng =
91
+ fit >= 1 && png.length <= INLINE_BYTES
92
+ ? png
93
+ : await sharp(png)
94
+ .resize(Math.max(1, Math.round(report.width * fit)), Math.max(1, Math.round(report.height * fit)), { fit: 'fill', kernel: sharp.kernel.lanczos3 })
95
+ .png({ compressionLevel: 9, palette: true, quality: 90 })
96
+ .toBuffer();
97
+ if (inlinePng.length <= INLINE_BYTES)
98
+ break;
99
+ fit *= 0.75;
100
+ }
101
+ return {
102
+ png,
103
+ svg,
104
+ html,
105
+ json,
106
+ hashes: {
107
+ html: sha256Bytes(html),
108
+ svg: sha256Bytes(svg),
109
+ png: sha256Bytes(png),
110
+ json: sha256Bytes(json),
111
+ },
112
+ inline: {
113
+ png: inlinePng,
114
+ width: Math.max(1, Math.round(report.width * fit)),
115
+ height: Math.max(1, Math.round(report.height * fit)),
116
+ },
117
+ };
118
+ }
119
+ export async function storeGameViewArtifacts(workspace, plan, bundle, renderProfile, signal) {
120
+ const stem = safeStem(plan.id);
121
+ const sourceEvidence = boundedSourceHashEvidence({
122
+ [plan.provenance.sourcePath]: plan.provenance.sourceHash,
123
+ });
124
+ const provenance = {
125
+ toolVersion: PACKAGE_VERSION,
126
+ schemaVersion: 'focus-render.v1',
127
+ sourceHashes: sourceEvidence.sourceHashes,
128
+ renderProfile: { renderer: 'hoi4-engine game view', ...renderProfile },
129
+ metadata: { sourceHashInventory: sourceEvidence.inventory },
130
+ };
131
+ const writes = [
132
+ {
133
+ name: `${stem}.focus.png`,
134
+ mimeType: 'image/png',
135
+ content: bundle.png,
136
+ provenance: { ...provenance, kind: 'focus-png' },
137
+ },
138
+ {
139
+ name: `${stem}.focus.json`,
140
+ mimeType: 'application/json',
141
+ content: bundle.json,
142
+ provenance: { ...provenance, kind: 'focus-json' },
143
+ },
144
+ {
145
+ name: `${stem}.focus.svg`,
146
+ mimeType: 'image/svg+xml',
147
+ content: bundle.svg,
148
+ provenance: { ...provenance, kind: 'focus-svg' },
149
+ description: 'Hover map of the game view: one titled box per focus, on the PNG pixels',
150
+ },
151
+ {
152
+ name: `${stem}.focus.html`,
153
+ mimeType: 'text/html',
154
+ content: bundle.html,
155
+ provenance: { ...provenance, kind: 'focus-html' },
156
+ description: 'The game view with zoom, pan and hover titles',
157
+ },
158
+ ];
159
+ return artifacts.withAtomicChunkedWrites(workspace, writes, (stored) => Promise.resolve([...stored]), signal);
160
+ }
@@ -2,10 +2,10 @@
2
2
  * Native effect identifiers used to distinguish direct scripted-effect calls
3
3
  * from engine effects while importing focus completion rewards.
4
4
  *
5
- * Source: the official HOI4 1.19.2 effects documentation reviewed 2026-07-10. This is the
6
- * fallback list; analysis also accepts every effect the installed game documents in
7
- * documentation/effects_documentation.md, so effects added by later patches are recognized.
8
- * Keep this list synchronized during compatibility reviews.
5
+ * Generated by scripts/generate-native-effects.ts from the HOI4 1.19.4.1 effects
6
+ * documentation. This is the fallback list; analysis also accepts every effect the installed
7
+ * game documents in documentation/effects_documentation.md, so effects added by later patches
8
+ * are recognized. The nightly game-update watcher regenerates it for review on a new build.
9
9
  */
10
10
  export const nativeEffectKeys = new Set([
11
11
  'activate_advisor',