hoi4-agent-tools 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +32 -13
  3. package/dist/hoi4_agent_tools/core/engine-client.js +74 -5
  4. package/dist/hoi4_agent_tools/core/operation-result.js +9 -0
  5. package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
  6. package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
  7. package/dist/hoi4_agent_tools/decision/service.js +7 -0
  8. package/dist/hoi4_agent_tools/event/service.js +18 -6
  9. package/dist/hoi4_agent_tools/event/summary.js +9 -0
  10. package/dist/hoi4_agent_tools/focus/engine-layout.js +1 -1
  11. package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
  12. package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
  13. package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
  14. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +241 -241
  15. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +30 -19
  16. package/dist/hoi4_agent_tools/focus/quality/schematic.js +5 -3
  17. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +1 -1
  18. package/dist/hoi4_agent_tools/focus/render.js +21 -9
  19. package/dist/hoi4_agent_tools/focus/tool-operations.js +158 -3
  20. package/dist/hoi4_agent_tools/gui/assets.js +18 -0
  21. package/dist/hoi4_agent_tools/gui/dds.js +38 -5
  22. package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
  23. package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
  24. package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
  25. package/dist/hoi4_agent_tools/gui/validators.js +31 -2
  26. package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
  27. package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
  28. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  29. package/dist/hoi4_agent_tools/mcp/tools/event.js +2 -0
  30. package/dist/hoi4_agent_tools/mcp/tools/focus.js +1 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/reference.js +18 -0
  32. package/dist/hoi4_agent_tools/probability/operations.js +27 -1
  33. package/dist/hoi4_agent_tools/probability/service.js +91 -11
  34. package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
  35. package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
  36. package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
  37. package/dist/hoi4_agent_tools/reference/error-log.js +24 -0
  38. package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
  39. package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
  40. package/dist/hoi4_agent_tools/reference/operations.js +68 -2
  41. package/dist/hoi4_agent_tools/reference/ranking.js +32 -0
  42. package/dist/hoi4_agent_tools/reference/script-validation.js +46 -6
  43. package/dist/hoi4_agent_tools/reference/service.js +33 -0
  44. package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
  45. package/dist/hoi4_agent_tools/schemas/focus-requests.js +4 -0
  46. package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
  47. package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
  48. package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/focus.md +9 -5
  51. package/docs/research/reference-benchmark.md +41 -0
  52. package/docs/tools.md +43 -39
  53. package/docs/troubleshooting.md +13 -12
  54. package/engine/README.md +284 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +26 -0
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +4 -1
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +1 -1
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +1 -1
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +1 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
@@ -4,6 +4,7 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { ServiceError } from '../core/result.js';
6
6
  import { knownMistakeForLogMessage } from './known-mistakes.js';
7
+ import { readModDescriptor } from '../core/workspace.js';
7
8
  /** The newest part of a very large log is read; the game writes it anew on every launch. */
8
9
  const MAX_LOG_BYTES = 16 * 1024 * 1024;
9
10
  const MAX_MESSAGE_CHARACTERS = 600;
@@ -154,6 +155,27 @@ function userDataCandidates(workspace, configured) {
154
155
  }
155
156
  return [...new Set(candidates)];
156
157
  }
158
+ /**
159
+ * The mods of the launch that wrote the logs, read from `system.log` beside `error.log`, which
160
+ * the game writes anew on every launch with one `Active Mod: <name>` line per mod.
161
+ */
162
+ async function launchOf(workspace, logs) {
163
+ const file = path.join(logs, 'system.log');
164
+ const info = await stat(file).catch(() => undefined);
165
+ if (info?.isFile() !== true)
166
+ return undefined;
167
+ const { text } = await readTail(file, info.size);
168
+ const activeMods = [...text.matchAll(/\]:\s*Active Mod:\s*(.+?)\s*$/gmu)]
169
+ .map((match) => match[1].slice(0, 256))
170
+ .slice(0, 64);
171
+ const name = (await readModDescriptor(workspace.modRoot))?.name?.trim().toLowerCase();
172
+ return {
173
+ activeMods,
174
+ ...(name === undefined || name === ''
175
+ ? {}
176
+ : { modLoaded: activeMods.some((mod) => mod.trim().toLowerCase() === name) }),
177
+ };
178
+ }
157
179
  async function readTail(file, size) {
158
180
  const start = Math.max(0, size - MAX_LOG_BYTES);
159
181
  const handle = await open(file, 'r');
@@ -309,6 +331,7 @@ export async function readErrorLog(workspace, input, configuredUserRoot, signal)
309
331
  categories.set(entry.category, totals);
310
332
  }
311
333
  const page = selected.slice(input.offset, input.offset + input.limit);
334
+ const launch = await launchOf(workspace, path.dirname(found.file));
312
335
  return {
313
336
  log: {
314
337
  path: 'user:logs/error.log',
@@ -317,6 +340,7 @@ export async function readErrorLog(workspace, input, configuredUserRoot, signal)
317
340
  truncated,
318
341
  entries: raw.length,
319
342
  },
343
+ ...(launch === undefined ? {} : { launch }),
320
344
  scope: input.scope,
321
345
  totalEntries: selected.reduce((sum, entry) => sum + entry.count, 0),
322
346
  distinctEntries: selected.length,
@@ -184,17 +184,19 @@ const detectors = {
184
184
  : [];
185
185
  }),
186
186
  event_namespace_missing: (document, _family, context) => {
187
- const declared = new Set(context.eventNamespaces ?? []);
187
+ // Namespaces match in any letter case: vanilla 1.19.4.1 declares TAOG_news and uses
188
+ // taog_news.1, and declares nsb_news and uses NSB_news.200.
189
+ const declared = new Set([...(context.eventNamespaces ?? [])].map((namespace) => namespace.toLowerCase()));
188
190
  for (const node of assignmentsOf(document.root))
189
191
  if (node.key.value === 'add_namespace' && node.value.type === 'scalar')
190
- declared.add(node.value.value);
192
+ declared.add(node.value.value.toLowerCase());
191
193
  return eventsOf(document).flatMap(({ body, id }) => {
192
194
  const idNode = field(body, 'id');
193
195
  const dot = id?.lastIndexOf('.') ?? -1;
194
196
  if (idNode === undefined || id === undefined || dot < 1)
195
197
  return [];
196
198
  const namespace = id.slice(0, dot);
197
- return declared.has(namespace)
199
+ return declared.has(namespace.toLowerCase())
198
200
  ? []
199
201
  : [
200
202
  {
@@ -210,12 +212,13 @@ const detectors = {
210
212
  if (idNode === undefined || id === undefined || dot < 1)
211
213
  return [];
212
214
  const number = id.slice(dot + 1);
213
- if (/^\d+$/u.test(number) && Number(number) < 100_000)
215
+ // A text suffix loads: vanilla ships BBA_italy_missiolinis.02_north and its siblings.
216
+ if (!/^\d+$/u.test(number) || Number(number) < 100_000)
214
217
  return [];
215
218
  return [
216
219
  {
217
220
  node: idNode,
218
- message: `${id} ends in "${number}", which is not a whole number from 0 to 99999`,
221
+ message: `${id} ends in ${number}, which reaches the next namespace (the limit is 99999)`,
219
222
  },
220
223
  ];
221
224
  }),
@@ -106,10 +106,10 @@
106
106
  "status": "active",
107
107
  "severity": "error",
108
108
  "surfaces": ["event"],
109
- "title": "Event number that is not a whole number below 100000",
110
- "mistake": "The part of an event id after the last dot is not an integer, or is 100000 or more.",
111
- "symptom": "Every non-integer id becomes number 0, and numbers from 100000 reach the next namespace, so events share one internal id and one fires the other (\"Failed to create id ... Already exists in game\").",
112
- "fix": "End the id with a whole number from 0 to 99999, unique within its namespace.",
109
+ "title": "Event number of 100000 or more",
110
+ "mistake": "The part of an event id after the last dot is a whole number of 100000 or more. A text suffix is not flagged: vanilla 1.19.4.1 ships ids such as BBA_italy_missiolinis.02_north and tutorial ids, and a game launch that loads them logs no id collision.",
111
+ "symptom": "Numbers from 100000 reach the next namespace, so events share one internal id and one fires the other (\"Failed to create id ... Already exists in game\").",
112
+ "fix": "End the id with a number from 0 to 99999, unique within its namespace.",
113
113
  "sources": [
114
114
  {
115
115
  "kind": "wiki",
@@ -10,6 +10,10 @@ import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../schem
10
10
  import { validateScript } from './script-validation.js';
11
11
  import { readErrorLog } from './error-log.js';
12
12
  import { modIndex } from './mod-index.js';
13
+ import { inspectLocalisation } from '../localisation/inspect.js';
14
+ import { inspectIdeas } from '../ideas/inspect.js';
15
+ import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../schemas/ideas.js';
16
+ import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../schemas/localisation.js';
13
17
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../schemas/mod-tools.js';
14
18
  import { eventPopupDefinitions } from './event-popups.js';
15
19
  import { locatePatterns, selectFile } from './source-locate.js';
@@ -48,6 +52,8 @@ const schemas = {
48
52
  'hoi4.script_validate': scriptValidateRequestSchema,
49
53
  'hoi4.error_log': errorLogRequestSchema,
50
54
  'hoi4.mod_index': modIndexRequestSchema,
55
+ 'hoi4.localisation_inspect': localisationInspectRequestSchema,
56
+ 'hoi4.idea_inspect': ideaInspectRequestSchema,
51
57
  };
52
58
  export function isReferenceTool(name) {
53
59
  return Object.hasOwn(schemas, name);
@@ -81,14 +87,29 @@ export class ReferenceToolService {
81
87
  ? await modIndex(this.engine, workspaceId, modIndexRequestSchema.parse(parsed), context.principal, signal)
82
88
  : name === 'hoi4.script_validate'
83
89
  ? await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse(parsed), context.principal, signal)
84
- : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
90
+ : name === 'hoi4.idea_inspect'
91
+ ? await inspectIdeas(workspace, ideaInspectRequestSchema.parse(parsed), signal)
92
+ : name === 'hoi4.localisation_inspect'
93
+ ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
94
+ : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
85
95
  const result = emptyServiceResult(workspaceId, data);
86
96
  if (name === 'hoi4.error_log') {
87
97
  const log = errorLogDataSchema.parse(data);
88
98
  result.code = 'ERROR_LOG_READ';
99
+ // A log from a launch without the mod says nothing about the mod.
100
+ const otherLaunch = log.launch?.modLoaded === false;
89
101
  result.validation = {
90
- passed: log.modEntries === 0,
102
+ passed: log.modEntries === 0 && !otherLaunch,
91
103
  checks: [
104
+ ...(otherLaunch
105
+ ? [
106
+ {
107
+ id: 'error-log-launch',
108
+ passed: false,
109
+ message: `The last game launch did not load this mod (it ran with ${log.launch.activeMods.join(', ') || 'no mods'}), so its log does not show this mod's errors`,
110
+ },
111
+ ]
112
+ : []),
92
113
  {
93
114
  id: 'error-log-mod-entries',
94
115
  passed: log.modEntries === 0,
@@ -103,6 +124,51 @@ export class ReferenceToolService {
103
124
  const index = modIndexDataSchema.parse(data);
104
125
  result.code = index.complete ? 'MOD_INDEXED' : 'MOD_INDEXED_PARTIAL';
105
126
  }
127
+ if (name === 'hoi4.idea_inspect') {
128
+ const inspected = ideaInspectDataSchema.parse(data);
129
+ result.code = inspected.audit === undefined ? 'IDEA_INSPECTED' : 'IDEAS_AUDITED';
130
+ // A missing name may be intended (generic leaders), so it is information, not a problem.
131
+ const warnings = inspected.audit === undefined
132
+ ? (inspected.inspection?.problems ?? []).filter(({ severity }) => severity === 'warning')
133
+ .length
134
+ : Object.entries(inspected.audit.counts)
135
+ .filter(([code]) => !code.endsWith('_NAME_MISSING'))
136
+ .reduce((sum, [, count]) => sum + count, 0);
137
+ result.validation = {
138
+ passed: warnings === 0,
139
+ checks: [
140
+ {
141
+ id: 'idea-checks',
142
+ passed: warnings === 0,
143
+ message: warnings === 0
144
+ ? 'No problems players would see'
145
+ : `${warnings} problems players would see`,
146
+ },
147
+ ],
148
+ };
149
+ }
150
+ if (name === 'hoi4.localisation_inspect') {
151
+ const inspected = localisationInspectDataSchema.parse(data);
152
+ result.code = 'LOCALISATION_INSPECTED';
153
+ if (inspected.audit !== undefined) {
154
+ // Information (text shown as written on purpose) is not a problem players see.
155
+ const warnings = Object.entries(inspected.audit.counts)
156
+ .filter(([code]) => code !== 'LOC_SCRIPTED_TEXT_LITERAL' && code !== 'LOC_PLACEHOLDER_MISSING')
157
+ .reduce((sum, [, count]) => sum + count, 0);
158
+ result.validation = {
159
+ passed: warnings === 0,
160
+ checks: [
161
+ {
162
+ id: 'localisation-audit',
163
+ passed: warnings === 0,
164
+ message: warnings === 0
165
+ ? 'No localisation problems players would see'
166
+ : `${warnings} localisation problems players would see`,
167
+ },
168
+ ],
169
+ };
170
+ }
171
+ }
106
172
  if (name === 'hoi4.script_validate') {
107
173
  const checked = scriptValidateDataSchema.parse(data);
108
174
  result.code = checked.valid === null ? 'SCRIPT_CHECK_PARTIAL' : 'SCRIPT_CHECKED';
@@ -167,6 +167,7 @@ export function sectionTerms(title, heading, lines) {
167
167
  ? 'define'
168
168
  : undefined,
169
169
  role: commandRole(title, heading.trim()),
170
+ verb: commandRole(title, heading.trim()) === undefined ? undefined : heading.trim().split('_')[0],
170
171
  };
171
172
  }
172
173
  function commandRole(title, heading) {
@@ -189,6 +190,27 @@ const actionWords = new Set(('add give make set remove change create increase de
189
190
  'annex move start spawn build rename switch kill transfer fire hide run pick free put queue ' +
190
191
  'improve tell gain lose destroy release puppet end apply load swap upgrade unlock').split(' '));
191
192
  const timingWords = new Set(['when', 'whenever', 'happens', 'happen', 'after', 'once']);
193
+ /**
194
+ * Command names open with a verb from a small closed set. A question that grants something
195
+ * asks for an `add_`, `create_` or `give_` command and not for its `remove_` counterpart.
196
+ */
197
+ const grantVerbs = new Set(['add', 'give', 'create', 'unlock', 'activate', 'start', 'spawn']);
198
+ const revokeVerbs = new Set('remove clear clr delete destroy cancel end deactivate retire kill subtract'.split(' '));
199
+ const questionDirection = new Map([
200
+ ...'add give grant create gain unlock activate start spawn award'
201
+ .split(' ')
202
+ .map((word) => [word, 'grant']),
203
+ ...'remove delete clear cancel end stop lose destroy kill free revoke retire deactivate drop strip'
204
+ .split(' ')
205
+ .map((word) => [word, 'revoke']),
206
+ ]);
207
+ const verbDirection = (verb) => verb === undefined
208
+ ? undefined
209
+ : grantVerbs.has(verb)
210
+ ? 'grant'
211
+ : revokeVerbs.has(verb)
212
+ ? 'revoke'
213
+ : undefined;
192
214
  /** A command of another kind than the question asks for keeps this share of its score. */
193
215
  const intentPenalty = 0.6;
194
216
  function questionIntent(normalized) {
@@ -207,6 +229,7 @@ function questionIntent(normalized) {
207
229
  : undefined,
208
230
  onAction,
209
231
  variable: raw.some((word) => word.startsWith('variable')),
232
+ direction: first === undefined ? undefined : questionDirection.get(first),
210
233
  };
211
234
  }
212
235
  /** Script names abbreviate counts as `num_`, as in `num_divisions` or `num_of_factories`. */
@@ -307,8 +330,12 @@ export class RankingIndex {
307
330
  else if (plan.identifiers.has(headingText))
308
331
  score += 40;
309
332
  // A short heading whose every word the question names is usually the topic itself.
333
+ const direction = verbDirection(entry.verb);
310
334
  if (entry.headingWords.length > 0) {
311
335
  const queryTerms = new Set(plan.terms.map(({ term }) => term));
336
+ // "Give a war goal" names `create_wargoal` as fully as "create a war goal" would.
337
+ if (direction !== undefined && direction === plan.wants.direction)
338
+ queryTerms.add(stemTerm(entry.verb));
312
339
  const covered = entry.headingWords.filter((word) => queryTerms.has(word));
313
340
  const fraction = covered.length / entry.headingWords.length;
314
341
  score += fraction * fraction * covered.reduce((sum, word) => sum + this.idf(word), 0) * 0.6;
@@ -328,6 +355,11 @@ export class RankingIndex {
328
355
  else if (plan.wants.role !== undefined && role !== undefined && role !== plan.wants.role)
329
356
  score *= intentPenalty;
330
357
  }
358
+ // A `remove_` command rarely answers a question about adding, and the other way round.
359
+ if (direction !== undefined &&
360
+ plan.wants.direction !== undefined &&
361
+ direction !== plan.wants.direction)
362
+ score *= intentPenalty;
331
363
  return score;
332
364
  }
333
365
  /** Extra credit for query words that appear next to each other in the section. */
@@ -13,22 +13,43 @@ const MAX_FILE_COMMANDS = 50_000;
13
13
  const UNKNOWN_SCOPE = 'unknown';
14
14
  /**
15
15
  * Scope links from the wiki Scopes page: the scopes each link is usable in and the scope it
16
- * enters. The engine accepts these keys in any letter case.
16
+ * enters. The engine accepts these keys in any letter case. The game's documentation does not
17
+ * list scope links, so vanilla script that loads widens the wiki's list: vanilla 1.19.4.1 uses
18
+ * `controller` in country scope (common/decisions/ENG.txt, common/national_focus/sweden.txt)
19
+ * and `capital_scope` in state scope (common/decisions/SOV.txt).
17
20
  */
18
21
  const scopeLinks = {
19
22
  owner: { from: ['state', 'character', 'combatant'], to: 'country' },
20
- controller: { from: ['state'], to: 'country' },
21
- capital_scope: { from: ['country'], to: 'state' },
23
+ controller: { from: ['state', 'country'], to: 'country' },
24
+ capital_scope: { from: ['country', 'state'], to: 'state' },
22
25
  overlord: { from: ['country'], to: 'country' },
23
26
  faction_leader: { from: ['country'], to: 'country' },
24
27
  };
28
+ /** A scope a link can be compared with: a keyword chain, a country tag or a saved target. */
29
+ const scopeTargetPattern = /^(?:(?:ROOT|THIS|PREV|FROM|root|this|prev|from)(?:\.(?:ROOT|THIS|PREV|FROM|OWNER|CONTROLLER|root|this|prev|from|owner|controller))*|[A-Z][A-Z0-9]{2}|(?:event_target|var):[\w.@:]+)$/u;
30
+ /**
31
+ * The scope an event's trigger, immediate and options run in. In a unit leader event ROOT and
32
+ * THIS are the general and FROM is the country, yet country effects run there without a scope
33
+ * error (in-game check 2026-11-02, run26), as vanilla options use them; `unit_leader` accepts
34
+ * both kinds. An operative leader event runs in the operative (vanilla LaR_agent_events.txt).
35
+ */
25
36
  const eventScopes = {
26
37
  country_event: 'country',
27
38
  news_event: 'country',
28
39
  state_event: 'state',
29
- unit_leader_event: 'character',
40
+ unit_leader_event: 'unit_leader',
30
41
  operative_leader_event: 'character',
31
42
  };
43
+ /** A command or link documented for `scopes` is usable in `scope`. */
44
+ function scopeAccepts(scopes, scope) {
45
+ return (scopes.includes(scope) ||
46
+ (scope === 'unit_leader' && (scopes.includes('character') || scopes.includes('country'))));
47
+ }
48
+ /** Triggers that test what a scope link would enter, for links misused as triggers. */
49
+ const linkTriggers = {
50
+ owner: 'is_owned_by',
51
+ controller: 'is_controlled_by',
52
+ };
32
53
  const optionMetadata = new Set([
33
54
  'name',
34
55
  'ai_chance',
@@ -311,10 +332,29 @@ export async function validateScript(references, workspace, input, signal, file)
311
332
  walk(entry.value, kind, explicitScope ?? fixedScope, scope);
312
333
  continue;
313
334
  }
335
+ // `owner = ROOT` or `owner = GER` is not a trigger: the game drops it at load ("Unknown
336
+ // trigger-type: owner", in-game check 2026-11-02, run26) and the surrounding limit then
337
+ // passes. The trigger that tests the linked scope is named instead.
338
+ const compared = scopeLinks[raw.toLowerCase()];
339
+ if (compared !== undefined &&
340
+ kind === 'trigger' &&
341
+ entry.value.type === 'scalar' &&
342
+ entry.operator.text === '=' &&
343
+ scopeTargetPattern.test(entry.value.value)) {
344
+ checkedCommands++;
345
+ const replacement = linkTriggers[raw.toLowerCase()];
346
+ report(entry, kind, scope, {
347
+ code: 'SCRIPT_SCOPE_LINK_AS_TRIGGER',
348
+ status: 'error',
349
+ message: `${raw} is a scope link, not a trigger; the game drops it and the condition always passes${replacement === undefined ? '' : `. Use ${replacement} = ${entry.value.value.slice(0, 64)}`}`,
350
+ suggestions: replacement === undefined ? [] : [replacement],
351
+ });
352
+ continue;
353
+ }
314
354
  const link = entry.value.type === 'block' ? scopeLinks[raw.toLowerCase()] : undefined;
315
355
  if (link !== undefined && entry.value.type === 'block') {
316
356
  checkedCommands++;
317
- if (scope !== UNKNOWN_SCOPE && !link.from.includes(scope))
357
+ if (scope !== UNKNOWN_SCOPE && !scopeAccepts(link.from, scope))
318
358
  report(entry, kind, scope, {
319
359
  code: 'SCRIPT_SCOPE_LINK_WRONG_SCOPE',
320
360
  status: 'error',
@@ -388,7 +428,7 @@ export async function validateScript(references, workspace, input, signal, file)
388
428
  if (signature !== undefined) {
389
429
  const wrongScope = scope !== UNKNOWN_SCOPE &&
390
430
  !signature.scopes.includes('any') &&
391
- !signature.scopes.includes(scope);
431
+ !scopeAccepts(signature.scopes, scope);
392
432
  report(entry, kind, scope, {
393
433
  code: signature.conflict
394
434
  ? 'SCRIPT_DOCUMENTATION_CONFLICT'
@@ -7,6 +7,7 @@ import { ServiceError } from '../core/result.js';
7
7
  import { isWithin } from '../core/workspace.js';
8
8
  import { prepareSource, verifySource, readBoundedFile, } from '../core/scanner.js';
9
9
  import { decodeSource } from '../core/source/encoding.js';
10
+ import commandPhrases from './command-phrases.json' with { type: 'json' };
10
11
  import { activeKnownMistakes } from './known-mistakes.js';
11
12
  import { readBoundedJsonLines } from './lines.js';
12
13
  import { commandTexts, readGameText } from './game-text.js';
@@ -224,6 +225,30 @@ const gameDocNames = {
224
225
  ai: ['common/ai_strategy/_documentation', 'documentation/triggers_documentation'],
225
226
  };
226
227
  const commandHeading = /^[a-z][a-z0-9_]*$/u;
228
+ /**
229
+ * Plain-word phrasings count this many times a game text word, because they name the
230
+ * command the way a question does rather than the way a tooltip labels it.
231
+ */
232
+ const PHRASE_WEIGHT = 4;
233
+ let phraseTerms;
234
+ /**
235
+ * The terms of `command-phrases.json`: four plain-word phrasings of each documented effect,
236
+ * trigger and modifier, such as "state on the coast" for `is_coastal`, written once from
237
+ * the command's documentation and in-game text (ADR 0078). A command the file does not
238
+ * name, such as one a later game version adds, keeps only its documentation and game text.
239
+ */
240
+ function phraseCards() {
241
+ if (phraseTerms !== undefined)
242
+ return phraseTerms;
243
+ phraseTerms = new Map();
244
+ for (const [name, phrases] of Object.entries(commandPhrases)) {
245
+ const card = new Map();
246
+ for (const term of phrases.flatMap((text) => textTerms(text)))
247
+ card.set(term, Math.min((card.get(term) ?? 0) + PHRASE_WEIGHT, 3 * PHRASE_WEIGHT));
248
+ phraseTerms.set(name, card);
249
+ }
250
+ return phraseTerms;
251
+ }
227
252
  /**
228
253
  * For each entry about one command, the words the game shows players for it: the installed
229
254
  * documentation says "check if state is coastal" and the tooltip "Is coastal"; a modifier
@@ -241,6 +266,14 @@ function commandCards(sections, gameText) {
241
266
  card.set(term, Math.min((card.get(term) ?? 0) + 1, 3));
242
267
  spoken.set(name, card);
243
268
  }
269
+ for (const [name, card] of phraseCards()) {
270
+ if (!commands.has(name))
271
+ continue;
272
+ const merged = new Map(spoken.get(name));
273
+ for (const [term, weight] of card)
274
+ merged.set(term, (merged.get(term) ?? 0) + weight);
275
+ spoken.set(name, merged);
276
+ }
244
277
  const cards = new Map();
245
278
  for (const section of sections) {
246
279
  if (section.terms.specialty !== undefined || section.terms.navigation)
@@ -150,6 +150,14 @@ export async function sourceLookup(engine, workspaceId, input, principal, signal
150
150
  path: entry.path,
151
151
  line: entry.location?.start.line ?? null,
152
152
  }));
153
+ // A complete index that neither defines nor uses the symbol answers not-found, never an
154
+ // empty success.
155
+ if (matchedDefinitions.length === 0 && matchedReferences.length === 0 && snapshot.complete) {
156
+ const suggestions = nearestNames(symbol, new Set(snapshot.index.symbols
157
+ .filter((entry) => input.kind === undefined || entry.kind === input.kind)
158
+ .map(({ id }) => id)));
159
+ throw new ServiceError('SYMBOL_NOT_FOUND', `No indexed file defines${input.includeReferences ? ' or uses' : ''} ${symbol.slice(0, 256)}${input.kind === undefined ? '' : ` as a ${input.kind}`}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { symbol: symbol.slice(0, 256), suggestions });
160
+ }
153
161
  const result = {
154
162
  sourceScope: input.kind === 'event'
155
163
  ? input.includeReferences
@@ -94,6 +94,10 @@ export const focusRenderRequestSchema = z
94
94
  .boolean()
95
95
  .optional()
96
96
  .describe('Default true: add a PNG with decoded source icons. False returns only the faster HTML, SVG and JSON.'),
97
+ view: z
98
+ .enum(['full', 'game'])
99
+ .optional()
100
+ .describe('Default full. game: only the tree as the game draws it (PNG, hover map, zoomable HTML, inline overview), without the schematic; fast enough to call after every edit. Needs hoi4-engine.'),
97
101
  })
98
102
  .strict()
99
103
  .superRefine((value, context) => {
@@ -0,0 +1,142 @@
1
+ import { z } from 'zod/v4';
2
+ import { workspaceIdSchema } from './common.js';
3
+ /** `hoi4.idea_inspect`, answered by `hoi4-engine ideas` (ADR 0074). */
4
+ export const ideaInspectRequestSchema = z
5
+ .object({
6
+ workspaceId: workspaceIdSchema,
7
+ /** idea: a national spirit, law or advisor idea. character: a leader, advisor or commander. */
8
+ kind: z.enum(['idea', 'character']).default('idea'),
9
+ /** The idea or character to inspect. Leave it out with audit. */
10
+ id: z.string().min(1).max(256).optional(),
11
+ /** Check every idea or character the mod defines instead of one. */
12
+ audit: z.boolean().default(false),
13
+ /** One: mentions listed. Audit: examples kept per problem code. */
14
+ limit: z.number().int().min(1).max(50).default(5),
15
+ })
16
+ .strict()
17
+ .refine((input) => input.audit || input.id !== undefined, {
18
+ message: 'pass an id, or audit: true',
19
+ path: ['id'],
20
+ });
21
+ const placeSchema = z
22
+ .object({
23
+ path: z.string().max(1024),
24
+ line: z.number().int().min(0),
25
+ layer: z.string().max(256),
26
+ layerKind: z.enum(['game', 'dlc', 'dependency', 'mod']),
27
+ })
28
+ .strict();
29
+ const fieldSchema = z
30
+ .object({ name: z.string().max(128), text: z.string().max(2400), line: z.number().int() })
31
+ .strict();
32
+ const problemSchema = z
33
+ .object({
34
+ code: z.string().max(64),
35
+ severity: z.enum(['warning', 'info']),
36
+ message: z.string().max(1200),
37
+ line: z.number().int().min(0),
38
+ })
39
+ .strict();
40
+ const textSchema = z
41
+ .object({
42
+ language: z.string().max(64),
43
+ text: z.string().max(2400),
44
+ path: z.string().max(1024),
45
+ line: z.number().int().min(0),
46
+ layer: z.string().max(256),
47
+ layerKind: z.enum(['game', 'dlc', 'dependency', 'mod']),
48
+ replace: z.boolean(),
49
+ })
50
+ .strict();
51
+ /** One idea or character, as the engine answers it. */
52
+ export const ideaEngineInspectionSchema = z
53
+ .object({
54
+ kind: z.enum(['idea', 'character']),
55
+ id: z.string().max(256),
56
+ found: z.boolean(),
57
+ definitions: z.array(placeSchema).max(256),
58
+ category: z.string().max(128).optional(),
59
+ picture: z
60
+ .object({
61
+ sprite: z.string().max(512),
62
+ defined: z.boolean(),
63
+ texture: z.string().max(1024).nullable(),
64
+ textureExists: z.boolean().nullable(),
65
+ })
66
+ .strict()
67
+ .optional(),
68
+ modifiers: z
69
+ .array(z
70
+ .object({
71
+ block: z.string().max(64),
72
+ key: z.string().max(256),
73
+ value: z.string().max(256),
74
+ known: z.boolean(),
75
+ line: z.number().int(),
76
+ })
77
+ .strict())
78
+ .max(512)
79
+ .optional(),
80
+ fields: z.array(fieldSchema).max(128).optional(),
81
+ roles: z
82
+ .array(z
83
+ .object({
84
+ role: z.string().max(64),
85
+ instance: z.number().int().min(0).nullable(),
86
+ fields: z.array(fieldSchema).max(64),
87
+ traits: z
88
+ .array(z.object({ name: z.string().max(256), known: z.boolean() }).strict())
89
+ .max(64),
90
+ line: z.number().int(),
91
+ })
92
+ .strict())
93
+ .max(64)
94
+ .optional(),
95
+ portraits: z
96
+ .array(z
97
+ .object({ slot: z.string().max(64), value: z.string().max(1024), exists: z.boolean() })
98
+ .strict())
99
+ .max(128)
100
+ .optional(),
101
+ advisorOf: z.string().max(256).optional(),
102
+ texts: z
103
+ .array(z.object({ key: z.string().max(256), texts: z.array(textSchema).max(64) }).strict())
104
+ .max(4),
105
+ mentions: z
106
+ .array(z
107
+ .object({ path: z.string().max(1024), line: z.number().int(), layer: z.string() })
108
+ .strict())
109
+ .max(100),
110
+ mentionsTruncated: z.boolean(),
111
+ problems: z.array(problemSchema).max(256),
112
+ suggestions: z.array(z.string().max(256)).max(3).optional(),
113
+ })
114
+ .strict();
115
+ /** Every idea or character of the mod, as the engine answers an audit. */
116
+ export const ideaEngineAuditSchema = z
117
+ .object({
118
+ kind: z.enum(['idea', 'character']),
119
+ checked: z.number().int().min(0),
120
+ counts: z.record(z.string(), z.number().int().min(0)),
121
+ problems: z
122
+ .array(z
123
+ .object({
124
+ code: z.string().max(64),
125
+ severity: z.enum(['warning', 'info']),
126
+ id: z.string().max(256),
127
+ path: z.string().max(1024),
128
+ line: z.number().int().min(0),
129
+ message: z.string().max(1200),
130
+ })
131
+ .strict())
132
+ .max(1000),
133
+ truncated: z.boolean(),
134
+ })
135
+ .strict();
136
+ export const ideaInspectDataSchema = z
137
+ .object({
138
+ inspection: ideaEngineInspectionSchema.optional(),
139
+ audit: ideaEngineAuditSchema.optional(),
140
+ durationMs: z.number().int().min(0),
141
+ })
142
+ .strict();