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
@@ -1,9 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { mkdir, open, readFile, rename, stat, writeFile } from 'node:fs/promises';
2
+ import { mkdir, open, readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
3
3
  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;
@@ -131,6 +132,40 @@ function knownMistakeOf(message) {
131
132
  const rule = knownMistakeForLogMessage(message);
132
133
  return rule === undefined ? {} : { knownMistake: { id: rule.id, fix: rule.fix } };
133
134
  }
135
+ const MOD_SOURCE_FILE = /\.(?:txt|yml|gui|gfx|lua|asset|csv)$/iu;
136
+ const MOD_CHANGE_FILE_LIMIT = 100_000;
137
+ /**
138
+ * The mod's script, localisation and interface files changed after the log was written, so the
139
+ * log describes an older mod. Image and sound files do not change what the log reports on.
140
+ */
141
+ export async function modChangedAfter(modRoot, logModified, signal) {
142
+ const entries = await readdir(modRoot, { recursive: true, withFileTypes: true }).catch(() => []);
143
+ const changed = [];
144
+ let checked = 0;
145
+ for (const entry of entries) {
146
+ if (!entry.isFile() || !MOD_SOURCE_FILE.test(entry.name))
147
+ continue;
148
+ const file = path.join(entry.parentPath, entry.name);
149
+ const relative = path.relative(modRoot, file).replaceAll('\\', '/');
150
+ if (relative.startsWith('.git/') || relative.includes('/.git/'))
151
+ continue;
152
+ if (++checked > MOD_CHANGE_FILE_LIMIT)
153
+ break;
154
+ if ((checked & 255) === 0)
155
+ signal?.throwIfAborted();
156
+ const info = await stat(file).catch(() => undefined);
157
+ if (info !== undefined && info.mtimeMs > logModified)
158
+ changed.push({ file: relative, modified: info.mtimeMs });
159
+ }
160
+ if (changed.length === 0)
161
+ return undefined;
162
+ changed.sort((left, right) => right.modified - left.modified);
163
+ return {
164
+ files: changed.length,
165
+ newestAt: new Date(changed[0].modified).toISOString(),
166
+ examples: changed.slice(0, 5).map(({ file }) => `mod:${file}`),
167
+ };
168
+ }
134
169
  /** The user-data folder that holds `logs/`, in order of preference. */
135
170
  function userDataCandidates(workspace, configured) {
136
171
  const candidates = [];
@@ -154,6 +189,27 @@ function userDataCandidates(workspace, configured) {
154
189
  }
155
190
  return [...new Set(candidates)];
156
191
  }
192
+ /**
193
+ * The mods of the launch that wrote the logs, read from `system.log` beside `error.log`, which
194
+ * the game writes anew on every launch with one `Active Mod: <name>` line per mod.
195
+ */
196
+ async function launchOf(workspace, logs) {
197
+ const file = path.join(logs, 'system.log');
198
+ const info = await stat(file).catch(() => undefined);
199
+ if (info?.isFile() !== true)
200
+ return undefined;
201
+ const { text } = await readTail(file, info.size);
202
+ const activeMods = [...text.matchAll(/\]:\s*Active Mod:\s*(.+?)\s*$/gmu)]
203
+ .map((match) => match[1].slice(0, 256))
204
+ .slice(0, 64);
205
+ const name = (await readModDescriptor(workspace.modRoot))?.name?.trim().toLowerCase();
206
+ return {
207
+ activeMods,
208
+ ...(name === undefined || name === ''
209
+ ? {}
210
+ : { modLoaded: activeMods.some((mod) => mod.trim().toLowerCase() === name) }),
211
+ };
212
+ }
157
213
  async function readTail(file, size) {
158
214
  const start = Math.max(0, size - MAX_LOG_BYTES);
159
215
  const handle = await open(file, 'r');
@@ -309,6 +365,7 @@ export async function readErrorLog(workspace, input, configuredUserRoot, signal)
309
365
  categories.set(entry.category, totals);
310
366
  }
311
367
  const page = selected.slice(input.offset, input.offset + input.limit);
368
+ const launch = await launchOf(workspace, path.dirname(found.file));
312
369
  return {
313
370
  log: {
314
371
  path: 'user:logs/error.log',
@@ -317,6 +374,7 @@ export async function readErrorLog(workspace, input, configuredUserRoot, signal)
317
374
  truncated,
318
375
  entries: raw.length,
319
376
  },
377
+ ...(launch === undefined ? {} : { launch }),
320
378
  scope: input.scope,
321
379
  totalEntries: selected.reduce((sum, entry) => sum + entry.count, 0),
322
380
  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",
@@ -7,9 +7,15 @@ import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSea
7
7
  import { ReferenceService } from './service.js';
8
8
  import { sourceLookup } from './source-lookup.js';
9
9
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../schemas/script-validation.js';
10
- import { validateScript } from './script-validation.js';
11
- import { readErrorLog } from './error-log.js';
10
+ import { identifierArgumentCommands, validateScript, } from './script-validation.js';
11
+ import { modChangedAfter, 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 { inspectAssets, inspectSystem, inspectUnits } from '../system/inspect.js';
17
+ import { assetInspectDataSchema, assetInspectRequestSchema, systemInspectDataSchema, systemInspectRequestSchema, unitInspectDataSchema, unitInspectRequestSchema, } from '../schemas/system.js';
18
+ import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../schemas/localisation.js';
13
19
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../schemas/mod-tools.js';
14
20
  import { eventPopupDefinitions } from './event-popups.js';
15
21
  import { locatePatterns, selectFile } from './source-locate.js';
@@ -48,7 +54,19 @@ const schemas = {
48
54
  'hoi4.script_validate': scriptValidateRequestSchema,
49
55
  'hoi4.error_log': errorLogRequestSchema,
50
56
  'hoi4.mod_index': modIndexRequestSchema,
57
+ 'hoi4.localisation_inspect': localisationInspectRequestSchema,
58
+ 'hoi4.idea_inspect': ideaInspectRequestSchema,
59
+ 'hoi4.system_inspect': systemInspectRequestSchema,
60
+ 'hoi4.unit_inspect': unitInspectRequestSchema,
61
+ 'hoi4.asset_inspect': assetInspectRequestSchema,
51
62
  };
63
+ /** Asset findings players would not notice: uneven frames, sprites the game fills itself, hidden pictures and flags one pixel off. */
64
+ const ASSET_INFORMATION = new Set([
65
+ 'ASSET_FRAMES_MISMATCH',
66
+ 'ASSET_TEXTURE_NONE',
67
+ 'ASSET_TEXTURE_EMPTY',
68
+ 'ASSET_FLAG_SIZE_CLOSE',
69
+ ]);
52
70
  export function isReferenceTool(name) {
53
71
  return Object.hasOwn(schemas, name);
54
72
  }
@@ -81,14 +99,46 @@ export class ReferenceToolService {
81
99
  ? await modIndex(this.engine, workspaceId, modIndexRequestSchema.parse(parsed), context.principal, signal)
82
100
  : name === 'hoi4.script_validate'
83
101
  ? await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse(parsed), context.principal, signal)
84
- : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
102
+ : name === 'hoi4.idea_inspect'
103
+ ? await inspectIdeas(workspace, ideaInspectRequestSchema.parse(parsed), signal)
104
+ : name === 'hoi4.system_inspect'
105
+ ? await inspectSystem(workspace, systemInspectRequestSchema.parse(parsed), signal)
106
+ : name === 'hoi4.asset_inspect'
107
+ ? await inspectAssets(workspace, assetInspectRequestSchema.parse(parsed), signal)
108
+ : name === 'hoi4.unit_inspect'
109
+ ? await inspectUnits(workspace, unitInspectRequestSchema.parse(parsed), signal)
110
+ : name === 'hoi4.localisation_inspect'
111
+ ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
112
+ : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
85
113
  const result = emptyServiceResult(workspaceId, data);
86
114
  if (name === 'hoi4.error_log') {
87
115
  const log = errorLogDataSchema.parse(data);
88
116
  result.code = 'ERROR_LOG_READ';
117
+ // A log from a launch without the mod says nothing about the mod.
118
+ const otherLaunch = log.launch?.modLoaded === false;
119
+ // A log older than the mod's files describes an older mod (#65).
120
+ const stale = await modChangedAfter(workspace.modRoot, Date.parse(log.log.modifiedAt), signal);
89
121
  result.validation = {
90
- passed: log.modEntries === 0,
122
+ passed: log.modEntries === 0 && !otherLaunch && stale === undefined,
91
123
  checks: [
124
+ ...(otherLaunch
125
+ ? [
126
+ {
127
+ id: 'error-log-launch',
128
+ passed: false,
129
+ 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`,
130
+ },
131
+ ]
132
+ : []),
133
+ ...(stale === undefined
134
+ ? []
135
+ : [
136
+ {
137
+ id: 'error-log-age',
138
+ passed: false,
139
+ message: `The log was written at ${log.log.modifiedAt}, before ${stale.files} of the mod's files changed (the newest at ${stale.newestAt}, ${stale.examples[0] ?? ''}), so it does not show errors in the current source; relaunch the game to check them`,
140
+ },
141
+ ]),
92
142
  {
93
143
  id: 'error-log-mod-entries',
94
144
  passed: log.modEntries === 0,
@@ -103,6 +153,119 @@ export class ReferenceToolService {
103
153
  const index = modIndexDataSchema.parse(data);
104
154
  result.code = index.complete ? 'MOD_INDEXED' : 'MOD_INDEXED_PARTIAL';
105
155
  }
156
+ if (name === 'hoi4.idea_inspect') {
157
+ const inspected = ideaInspectDataSchema.parse(data);
158
+ result.code = inspected.audit === undefined ? 'IDEA_INSPECTED' : 'IDEAS_AUDITED';
159
+ // A missing name may be intended (generic leaders), so it is information, not a problem.
160
+ const warnings = inspected.audit === undefined
161
+ ? (inspected.inspection?.problems ?? []).filter(({ severity }) => severity === 'warning')
162
+ .length
163
+ : Object.entries(inspected.audit.counts)
164
+ .filter(([code]) => !code.endsWith('_NAME_MISSING'))
165
+ .reduce((sum, [, count]) => sum + count, 0);
166
+ result.validation = {
167
+ passed: warnings === 0,
168
+ checks: [
169
+ {
170
+ id: 'idea-checks',
171
+ passed: warnings === 0,
172
+ message: warnings === 0
173
+ ? 'No problems players would see'
174
+ : `${warnings} problems players would see`,
175
+ },
176
+ ],
177
+ };
178
+ }
179
+ if (name === 'hoi4.system_inspect') {
180
+ const inspected = systemInspectDataSchema.parse(data);
181
+ result.code = inspected.audit === undefined ? 'SYSTEM_INSPECTED' : 'SYSTEM_AUDITED';
182
+ // Missing names and undocumented hooks may be intended, so they are information.
183
+ const warnings = inspected.audit === undefined
184
+ ? (inspected.inspection?.problems ?? []).filter(({ severity }) => severity === 'warning')
185
+ .length
186
+ : Object.entries(inspected.audit.counts)
187
+ .filter(([code]) => code !== 'SYSTEM_NAME_MISSING' && code !== 'ON_ACTION_HOOK_UNDOCUMENTED')
188
+ .reduce((sum, [, count]) => sum + count, 0);
189
+ result.validation = {
190
+ passed: warnings === 0,
191
+ checks: [
192
+ {
193
+ id: 'system-checks',
194
+ passed: warnings === 0,
195
+ message: warnings === 0
196
+ ? 'No problems players would see'
197
+ : `${warnings} problems players would see`,
198
+ },
199
+ ],
200
+ };
201
+ }
202
+ if (name === 'hoi4.unit_inspect') {
203
+ const inspected = unitInspectDataSchema.parse(data);
204
+ result.code = inspected.audit === undefined ? 'UNIT_INSPECTED' : 'UNIT_AUDITED';
205
+ // A missing name or description may be intended, so it is information.
206
+ const warnings = inspected.audit === undefined
207
+ ? (inspected.inspection?.problems ?? []).filter(({ severity }) => severity === 'warning')
208
+ .length
209
+ : Object.entries(inspected.audit.counts)
210
+ .filter(([code]) => code !== 'UNIT_NAME_MISSING')
211
+ .reduce((sum, [, count]) => sum + count, 0);
212
+ result.validation = {
213
+ passed: warnings === 0,
214
+ checks: [
215
+ {
216
+ id: 'unit-checks',
217
+ passed: warnings === 0,
218
+ message: warnings === 0
219
+ ? 'No problems players would see'
220
+ : `${warnings} problems players would see`,
221
+ },
222
+ ],
223
+ };
224
+ }
225
+ if (name === 'hoi4.asset_inspect') {
226
+ const inspected = assetInspectDataSchema.parse(data);
227
+ result.code = inspected.audit === undefined ? 'ASSET_INSPECTED' : 'ASSET_AUDITED';
228
+ const warnings = inspected.audit === undefined
229
+ ? (inspected.inspection?.problems ?? []).filter(({ severity }) => severity === 'warning')
230
+ .length
231
+ : Object.entries(inspected.audit.counts)
232
+ .filter(([code]) => !ASSET_INFORMATION.has(code))
233
+ .reduce((sum, [, count]) => sum + count, 0);
234
+ result.validation = {
235
+ passed: warnings === 0,
236
+ checks: [
237
+ {
238
+ id: 'asset-checks',
239
+ passed: warnings === 0,
240
+ message: warnings === 0
241
+ ? 'No problems players would see'
242
+ : `${warnings} problems players would see`,
243
+ },
244
+ ],
245
+ };
246
+ }
247
+ if (name === 'hoi4.localisation_inspect') {
248
+ const inspected = localisationInspectDataSchema.parse(data);
249
+ result.code = 'LOCALISATION_INSPECTED';
250
+ if (inspected.audit !== undefined) {
251
+ // Information (text shown as written on purpose) is not a problem players see.
252
+ const warnings = Object.entries(inspected.audit.counts)
253
+ .filter(([code]) => code !== 'LOC_SCRIPTED_TEXT_LITERAL' && code !== 'LOC_PLACEHOLDER_MISSING')
254
+ .reduce((sum, [, count]) => sum + count, 0);
255
+ result.validation = {
256
+ passed: warnings === 0,
257
+ checks: [
258
+ {
259
+ id: 'localisation-audit',
260
+ passed: warnings === 0,
261
+ message: warnings === 0
262
+ ? 'No localisation problems players would see'
263
+ : `${warnings} localisation problems players would see`,
264
+ },
265
+ ],
266
+ };
267
+ }
268
+ }
106
269
  if (name === 'hoi4.script_validate') {
107
270
  const checked = scriptValidateDataSchema.parse(data);
108
271
  result.code = checked.valid === null ? 'SCRIPT_CHECK_PARTIAL' : 'SCRIPT_CHECKED';
@@ -116,7 +279,7 @@ export class ReferenceToolService {
116
279
  ? 'Syntax, native command kinds and declared scopes match the selected documentation'
117
280
  : checked.valid === false
118
281
  ? 'Script checks found an error'
119
- : 'Script checks have unresolved coverage',
282
+ : `Script checks are partial: ${(checked.partialReasons ?? ['coverage is unresolved']).join('; ')}`,
120
283
  },
121
284
  ],
122
285
  };
@@ -147,20 +310,23 @@ export class ReferenceToolService {
147
310
  #playerText = new Map();
148
311
  /** File mode reads the scanned file and the mod's scripted helper names from one scan. */
149
312
  async validateScript(workspaceId, workspace, request, principal, signal) {
313
+ // Every file check of the supported families shares one scan, so checking files across
314
+ // folders reuses one snapshot and its incremental index; other folders add their own.
315
+ const scan = (extra) => this.engine.scan(workspaceId, { patterns: [...fileCheckPatterns, ...extra] }, principal, signal);
150
316
  if (request.path === undefined) {
317
+ // A snippet that names definitions is checked against a scan; others need none.
318
+ const named = new RegExp(`\\b(?:${[...identifierArgumentCommands].join('|')})\\s*=`, 'u').test(request.source ?? '');
319
+ const identifiers = named ? identifierContext(await scan([])) : undefined;
151
320
  if (request.kind !== undefined)
152
- return validateScript(this.references, workspace, request, signal);
321
+ return validateScript(this.references, workspace, request, signal, undefined, identifiers);
153
322
  // A snippet without a kind is checked as an effect and as a trigger; the reading with
154
323
  // fewer errors and unresolved commands is the one the author meant.
155
- const effect = await validateScript(this.references, workspace, { ...request, kind: 'effect' }, signal);
156
- const trigger = await validateScript(this.references, workspace, { ...request, kind: 'trigger' }, signal);
324
+ const effect = await validateScript(this.references, workspace, { ...request, kind: 'effect' }, signal, undefined, identifiers);
325
+ const trigger = await validateScript(this.references, workspace, { ...request, kind: 'trigger' }, signal, undefined, identifiers);
157
326
  const misses = (checked) => checked.findings.filter(({ status }) => status === 'error').length * 100_000 +
158
327
  checked.unresolvedCount;
159
328
  return misses(trigger) < misses(effect) ? trigger : effect;
160
329
  }
161
- // Every file check of the supported families shares one scan, so checking files across
162
- // folders reuses one snapshot and its incremental index; other folders add their own.
163
- const scan = (extra) => this.engine.scan(workspaceId, { patterns: [...fileCheckPatterns, ...extra] }, principal, signal);
164
330
  let snapshot = await scan([]);
165
331
  let file;
166
332
  try {
@@ -186,7 +352,7 @@ export class ReferenceToolService {
186
352
  ...(playerText === undefined ? {} : { playerText }),
187
353
  eventPopups: this.eventPopupContext(workspaceId, snapshot),
188
354
  knownMistakes: { eventNamespaces: this.eventNamespaces(workspaceId, snapshot) },
189
- });
355
+ }, identifierContext(snapshot));
190
356
  }
191
357
  #eventNamespaces = new Map();
192
358
  /** Namespaces declared with `add_namespace` in every active events file, cached by hash. */
@@ -289,7 +455,34 @@ const fileCheckPatterns = [
289
455
  ...Object.keys(implicitTriggerSources).map((folder) => `common/${folder}/*.txt`),
290
456
  'localisation/**/*_l_english.yml',
291
457
  'common/scripted_localisation/**/*.txt',
458
+ // Definitions that identifier arguments name.
459
+ 'common/ideas/**/*.txt',
460
+ 'common/technologies/**/*.txt',
461
+ // Advisors' idea tokens are ideas.
462
+ 'common/characters/**/*.txt',
292
463
  ];
464
+ /** Index kinds whose ids identifier arguments name. */
465
+ const identifierKinds = {
466
+ idea: 'idea',
467
+ event: 'event',
468
+ decision: 'decision',
469
+ focus: 'focus',
470
+ continuous_focus: 'focus',
471
+ technology: 'technology',
472
+ };
473
+ function identifierContext(snapshot) {
474
+ const ids = new Map();
475
+ for (const symbol of snapshot.index.symbols) {
476
+ const kind = identifierKinds[symbol.kind];
477
+ if (kind === undefined)
478
+ continue;
479
+ let set = ids.get(kind);
480
+ if (set === undefined)
481
+ ids.set(kind, (set = new Set()));
482
+ set.add(symbol.id);
483
+ }
484
+ return { ids, complete: snapshot.complete };
485
+ }
293
486
  function playerTextSource(relativePath) {
294
487
  const file = relativePath.replaceAll('\\', '/').toLowerCase();
295
488
  return ((file.startsWith('localisation/') && file.endsWith('_l_english.yml')) ||
@@ -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. */