hoi4-agent-tools 4.8.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 (79) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/hoi4_agent_tools/core/index.js +28 -0
  3. package/dist/hoi4_agent_tools/decision/service.js +39 -2
  4. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  5. package/dist/hoi4_agent_tools/event/service.js +66 -11
  6. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  7. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  8. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -2
  9. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  10. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  11. package/dist/hoi4_agent_tools/map/world.js +158 -34
  12. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +57 -9
  13. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  14. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  15. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  16. package/dist/hoi4_agent_tools/mcp/tools/event.js +13 -0
  17. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  18. package/dist/hoi4_agent_tools/mcp/tools/reference.js +25 -0
  19. package/dist/hoi4_agent_tools/reference/error-log.js +35 -1
  20. package/dist/hoi4_agent_tools/reference/operations.js +141 -14
  21. package/dist/hoi4_agent_tools/reference/script-validation.js +113 -2
  22. package/dist/hoi4_agent_tools/schemas/ideas.js +4 -4
  23. package/dist/hoi4_agent_tools/schemas/map.js +32 -4
  24. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  25. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  26. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  27. package/dist/hoi4_agent_tools/version.js +1 -1
  28. package/docs/analysis.md +2 -2
  29. package/docs/events.md +1 -1
  30. package/docs/map.md +19 -8
  31. package/docs/tools.md +49 -43
  32. package/engine/README.md +9 -0
  33. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  34. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  35. package/engine/bin/linux-x64/hoi4-engine +0 -0
  36. package/engine/bin/manifest.json +8 -8
  37. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
  40. package/schemas/configuration.schema.json +1 -1
  41. package/schemas/continuous-focus-palette.schema.json +1 -1
  42. package/schemas/custom-weighted-pool.schema.json +1 -1
  43. package/schemas/decision-inspect-input.schema.json +1 -1
  44. package/schemas/error-log-input.schema.json +1 -1
  45. package/schemas/event-feature-manifest.schema.json +1 -1
  46. package/schemas/focus-plan.schema.json +1 -1
  47. package/schemas/focus-planning-sidecar.schema.json +1 -1
  48. package/schemas/geography-model.schema.json +1 -1
  49. package/schemas/gui-animation-source.schema.json +1 -1
  50. package/schemas/gui-helper.schema.json +1 -1
  51. package/schemas/gui-scenario.schema.json +1 -1
  52. package/schemas/helper-expansion-request.schema.json +1 -1
  53. package/schemas/helper-expansion-summary.schema.json +1 -1
  54. package/schemas/impact-inspect-input.schema.json +1 -1
  55. package/schemas/map-operation.schema.json +165 -101
  56. package/schemas/mechanic-test-input.schema.json +1 -1
  57. package/schemas/mod-index-input.schema.json +1 -1
  58. package/schemas/operation-result.schema.json +1 -1
  59. package/schemas/package-check-input.schema.json +1 -1
  60. package/schemas/package-manifest.schema.json +1 -1
  61. package/schemas/probability-analysis-result.schema.json +1 -1
  62. package/schemas/probability-compare-input.schema.json +1 -1
  63. package/schemas/probability-evaluate-input.schema.json +1 -1
  64. package/schemas/probability-inspect-input.schema.json +1 -1
  65. package/schemas/probability-render-input.schema.json +1 -1
  66. package/schemas/probability-scenario-set.schema.json +1 -1
  67. package/schemas/probability-sequence-input.schema.json +1 -1
  68. package/schemas/probability-simulate-input.schema.json +1 -1
  69. package/schemas/probability-sweep-input.schema.json +1 -1
  70. package/schemas/reference-context-input.schema.json +1 -1
  71. package/schemas/reference-read-input.schema.json +1 -1
  72. package/schemas/reference-search-input.schema.json +1 -1
  73. package/schemas/reference-sheets.schema.json +1 -1
  74. package/schemas/scenario-suite.schema.json +1 -1
  75. package/schemas/scenario-test-input.schema.json +1 -1
  76. package/schemas/script-validate-input.schema.json +1 -1
  77. package/schemas/shared-scenario.schema.json +1 -1
  78. package/schemas/source-lookup-input.schema.json +1 -1
  79. package/server.json +2 -2
@@ -101,7 +101,7 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
101
101
  const workspaceId = request.params.arguments
102
102
  ?.workspaceId;
103
103
  return CallToolResultSchema.parse({
104
- ...invalidArgumentsResult(definition.name, input.error, workspaceId),
104
+ ...invalidArgumentsResult(definition.name, input.error, workspaceId, definition.inputSchema),
105
105
  resultType: 'complete',
106
106
  ttlMs: 0,
107
107
  cacheScope: 'private',
@@ -34,7 +34,7 @@ export function installRequestLifecycle(server, engine) {
34
34
  const schema = params.task === undefined ? inputSchema(params.name) : undefined;
35
35
  const parsed = schema?.safeParse(params.arguments ?? {});
36
36
  if (parsed !== undefined && !parsed.success)
37
- return Promise.resolve(invalidArgumentsResult(params.name, parsed.error, params.arguments?.workspaceId));
37
+ return Promise.resolve(invalidArgumentsResult(params.name, parsed.error, params.arguments?.workspaceId, schema));
38
38
  }
39
39
  const progress = progressReporter(extra);
40
40
  const taskCall = CallToolRequestSchema.safeParse(request);
@@ -37,6 +37,8 @@ const decisionOutputSchema = strictOperationResultSchema(z
37
37
  overrides: nonNegativeIntegerSchema,
38
38
  scenarios: nonNegativeIntegerSchema,
39
39
  unresolvedDefinitions: nonNegativeIntegerSchema,
40
+ decisionIds: z.array(z.string()).max(64).optional(),
41
+ decisionIdsTruncated: z.boolean().optional(),
40
42
  unresolvedSample: z
41
43
  .array(z.object({ id: z.string(), path: z.string(), reason: z.string() }).strict())
42
44
  .max(8)
@@ -141,7 +143,7 @@ export const analysisTaskTools = [
141
143
  {
142
144
  name: 'hoi4.decision_inspect',
143
145
  title: 'Inspect decisions and missions',
144
- description: 'Explain why a decision or mission is hidden, unavailable or unaffordable. Inspect conditions, costs and lifecycle for declared actors and targets, or compare proposed source. Example: {"mode":"inspect","id":"my_decision","scenarios":[{"id":"base","actor":"GER","state":{}}]}. Returns each scenario outcome inline; full evidence is linked.',
146
+ description: 'Explain why a decision or mission is hidden, unavailable or unaffordable. Inspect conditions, costs and lifecycle for declared actors and targets, or compare proposed source. Example: {"mode":"inspect","id":"my_decision","scenarios":[{"id":"base","actor":"GER","state":{}}]}. Inventory mode with an id lists only that category\'s decisions, or that one decision. Returns each scenario outcome inline; full evidence is linked.',
145
147
  inputSchema: decisionInspectRequestSchema,
146
148
  outputSchema: decisionOutputSchema,
147
149
  annotations: readOnlyAnalysisTool,
@@ -149,7 +151,7 @@ export const analysisTaskTools = [
149
151
  {
150
152
  name: 'hoi4.mechanic_test',
151
153
  title: 'Test scripted effects',
152
- description: 'Test what an effect, event option, decision or focus reward does to a declared state. Run steps and check assertions; unsupported effects stay unresolved. See docs/mechanics.md. Example: {"test":{"id":"t","scenario":{"schemaVersion":"1.0","id":"t","state":{"treasury":10}},"steps":[...],"assertions":[...]}}.',
154
+ description: 'Test what an effect, option, decision or focus reward does to a declared state (docs/mechanics.md). Example: {"test":{"id":"t","scenario":{"schemaVersion":"1.0","id":"t","state":{}},"steps":[{"kind":"effect","source":{"kind":"scripted_effect","id":"e"}}],"assertions":[{"id":"a","kind":"conservation","paths":[{"key":"x"},{"key":"y"}]}]}}.',
153
155
  inputSchema: mechanicInputSchema,
154
156
  outputSchema: mechanicOutputSchema,
155
157
  annotations: readOnlyAnalysisTool,
@@ -111,6 +111,19 @@ const eventInspectSummarySchema = z
111
111
  })
112
112
  .strict()
113
113
  .optional(),
114
+ flow: z
115
+ .object({
116
+ subject: z.string().max(1024),
117
+ producers: nonNegativeIntegerSchema,
118
+ consumers: nonNegativeIntegerSchema,
119
+ clears: nonNegativeIntegerSchema,
120
+ links: nonNegativeIntegerSchema,
121
+ unproducedReads: nonNegativeIntegerSchema,
122
+ producedAt: z.array(z.string().max(1100)).max(8),
123
+ readAt: z.array(z.string().max(1100)).max(8),
124
+ })
125
+ .strict()
126
+ .optional(),
114
127
  entryPoints: nonNegativeIntegerSchema.optional(),
115
128
  entryKinds: countMapSchema.optional(),
116
129
  automaticEvents: nonNegativeIntegerSchema.optional(),
@@ -88,7 +88,7 @@ export const guiTaskTools = [
88
88
  {
89
89
  name: 'hoi4.gui_rewrite',
90
90
  title: 'Create or edit a window',
91
- description: 'Create or edit a window using complete source, structured helpers or exact patches. Include related text files with additionalFiles; binary art must already be in the mod. Example: {"mode":"helpers","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"helper":{...}}. Returns the changed files.',
91
+ description: 'Create or edit a window from complete source, structured helpers or exact patches. Add related text files in additionalFiles; binary art must already be in the mod. Example: {"mode":"helpers","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"helper":{"root":{"id":"w","kind":"column","name":"my_window"}}}.',
92
92
  inputSchema: guiRewriteRequestSchema,
93
93
  outputSchema: guiPlanOutputSchema,
94
94
  annotations: {
@@ -2,6 +2,7 @@ import { errorResult, strictOperationResultSchema } from '../../core/operation-r
2
2
  import { ReferenceToolService } from '../../reference/operations.js';
3
3
  import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, referenceContextDataSchema, referenceReadDataSchema, referenceSearchDataSchema, sourceLookupDataSchema, } from '../../schemas/reference.js';
4
4
  import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../../schemas/localisation.js';
5
+ import { systemInspectDataSchema, systemInspectRequestSchema, unitInspectDataSchema, unitInspectRequestSchema, assetInspectDataSchema, assetInspectRequestSchema, } from '../../schemas/system.js';
5
6
  import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../../schemas/ideas.js';
6
7
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../../schemas/mod-tools.js';
7
8
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../../schemas/script-validation.js';
@@ -84,6 +85,30 @@ export const referenceTools = [
84
85
  outputSchema: strictOperationResultSchema(ideaInspectDataSchema),
85
86
  annotations: readOnly,
86
87
  },
88
+ {
89
+ name: 'hoi4.system_inspect',
90
+ title: 'Check newer game systems',
91
+ description: 'Read one definition of a newer system, or audit every one the mod makes: on_actions hooks, MIOs and policies, balance of power, special projects, operations and raids. Returns its parts, each reference with whether it exists, pictures, names in every language and problems. Example: {"kind":"mio","id":"my_organization"} or {"kind":"on_actions","audit":true}.',
92
+ inputSchema: systemInspectRequestSchema,
93
+ outputSchema: strictOperationResultSchema(systemInspectDataSchema),
94
+ annotations: readOnly,
95
+ },
96
+ {
97
+ name: 'hoi4.unit_inspect',
98
+ title: 'Check units and equipment',
99
+ description: 'Read one order of battle (history/units), sub-unit, equipment or module, or equipment variant, or audit every one the mod makes. Checks template grids, divisions, fleets, air wings, equipment slots and modules, and each name they use. Example: {"kind":"oob","id":"GER_1936"} or {"kind":"variant","audit":true}.',
100
+ inputSchema: unitInspectRequestSchema,
101
+ outputSchema: strictOperationResultSchema(unitInspectDataSchema),
102
+ annotations: readOnly,
103
+ },
104
+ {
105
+ name: 'hoi4.asset_inspect',
106
+ title: 'Check sprites, sounds and flags',
107
+ description: 'Read one sprite (texture size, format and frames), sound, sound effect or music track (audio file, sounds it plays), or flag (all three sizes), or audit every one the mod defines. Flags BC7 textures, missing files and wrong flag sizes. Example: {"kind":"sprite","id":"GFX_my_icon"} or {"kind":"flag","audit":true}.',
108
+ inputSchema: assetInspectRequestSchema,
109
+ outputSchema: strictOperationResultSchema(assetInspectDataSchema),
110
+ annotations: readOnly,
111
+ },
87
112
  ];
88
113
  export function registerReferenceTools(server, engine, context) {
89
114
  const service = new ReferenceToolService(engine);
@@ -1,5 +1,5 @@
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';
@@ -132,6 +132,40 @@ function knownMistakeOf(message) {
132
132
  const rule = knownMistakeForLogMessage(message);
133
133
  return rule === undefined ? {} : { knownMistake: { id: rule.id, fix: rule.fix } };
134
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
+ }
135
169
  /** The user-data folder that holds `logs/`, in order of preference. */
136
170
  function userDataCandidates(workspace, configured) {
137
171
  const candidates = [];
@@ -7,12 +7,14 @@ 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
13
  import { inspectLocalisation } from '../localisation/inspect.js';
14
14
  import { inspectIdeas } from '../ideas/inspect.js';
15
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';
16
18
  import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../schemas/localisation.js';
17
19
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../schemas/mod-tools.js';
18
20
  import { eventPopupDefinitions } from './event-popups.js';
@@ -54,7 +56,17 @@ const schemas = {
54
56
  'hoi4.mod_index': modIndexRequestSchema,
55
57
  'hoi4.localisation_inspect': localisationInspectRequestSchema,
56
58
  'hoi4.idea_inspect': ideaInspectRequestSchema,
59
+ 'hoi4.system_inspect': systemInspectRequestSchema,
60
+ 'hoi4.unit_inspect': unitInspectRequestSchema,
61
+ 'hoi4.asset_inspect': assetInspectRequestSchema,
57
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
+ ]);
58
70
  export function isReferenceTool(name) {
59
71
  return Object.hasOwn(schemas, name);
60
72
  }
@@ -89,17 +101,25 @@ export class ReferenceToolService {
89
101
  ? await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse(parsed), context.principal, signal)
90
102
  : name === 'hoi4.idea_inspect'
91
103
  ? 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);
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);
95
113
  const result = emptyServiceResult(workspaceId, data);
96
114
  if (name === 'hoi4.error_log') {
97
115
  const log = errorLogDataSchema.parse(data);
98
116
  result.code = 'ERROR_LOG_READ';
99
117
  // A log from a launch without the mod says nothing about the mod.
100
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);
101
121
  result.validation = {
102
- passed: log.modEntries === 0 && !otherLaunch,
122
+ passed: log.modEntries === 0 && !otherLaunch && stale === undefined,
103
123
  checks: [
104
124
  ...(otherLaunch
105
125
  ? [
@@ -110,6 +130,15 @@ export class ReferenceToolService {
110
130
  },
111
131
  ]
112
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
+ ]),
113
142
  {
114
143
  id: 'error-log-mod-entries',
115
144
  passed: log.modEntries === 0,
@@ -147,6 +176,74 @@ export class ReferenceToolService {
147
176
  ],
148
177
  };
149
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
+ }
150
247
  if (name === 'hoi4.localisation_inspect') {
151
248
  const inspected = localisationInspectDataSchema.parse(data);
152
249
  result.code = 'LOCALISATION_INSPECTED';
@@ -182,7 +279,7 @@ export class ReferenceToolService {
182
279
  ? 'Syntax, native command kinds and declared scopes match the selected documentation'
183
280
  : checked.valid === false
184
281
  ? 'Script checks found an error'
185
- : 'Script checks have unresolved coverage',
282
+ : `Script checks are partial: ${(checked.partialReasons ?? ['coverage is unresolved']).join('; ')}`,
186
283
  },
187
284
  ],
188
285
  };
@@ -213,20 +310,23 @@ export class ReferenceToolService {
213
310
  #playerText = new Map();
214
311
  /** File mode reads the scanned file and the mod's scripted helper names from one scan. */
215
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);
216
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;
217
320
  if (request.kind !== undefined)
218
- return validateScript(this.references, workspace, request, signal);
321
+ return validateScript(this.references, workspace, request, signal, undefined, identifiers);
219
322
  // A snippet without a kind is checked as an effect and as a trigger; the reading with
220
323
  // fewer errors and unresolved commands is the one the author meant.
221
- const effect = await validateScript(this.references, workspace, { ...request, kind: 'effect' }, signal);
222
- 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);
223
326
  const misses = (checked) => checked.findings.filter(({ status }) => status === 'error').length * 100_000 +
224
327
  checked.unresolvedCount;
225
328
  return misses(trigger) < misses(effect) ? trigger : effect;
226
329
  }
227
- // Every file check of the supported families shares one scan, so checking files across
228
- // folders reuses one snapshot and its incremental index; other folders add their own.
229
- const scan = (extra) => this.engine.scan(workspaceId, { patterns: [...fileCheckPatterns, ...extra] }, principal, signal);
230
330
  let snapshot = await scan([]);
231
331
  let file;
232
332
  try {
@@ -252,7 +352,7 @@ export class ReferenceToolService {
252
352
  ...(playerText === undefined ? {} : { playerText }),
253
353
  eventPopups: this.eventPopupContext(workspaceId, snapshot),
254
354
  knownMistakes: { eventNamespaces: this.eventNamespaces(workspaceId, snapshot) },
255
- });
355
+ }, identifierContext(snapshot));
256
356
  }
257
357
  #eventNamespaces = new Map();
258
358
  /** Namespaces declared with `add_namespace` in every active events file, cached by hash. */
@@ -355,7 +455,34 @@ const fileCheckPatterns = [
355
455
  ...Object.keys(implicitTriggerSources).map((folder) => `common/${folder}/*.txt`),
356
456
  'localisation/**/*_l_english.yml',
357
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',
358
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
+ }
359
486
  function playerTextSource(relativePath) {
360
487
  const file = relativePath.replaceAll('\\', '/').toLowerCase();
361
488
  return ((file.startsWith('localisation/') && file.endsWith('_l_english.yml')) ||
@@ -11,6 +11,32 @@ const MAX_COMMANDS = 256;
11
11
  const MAX_FILE_COMMANDS = 50_000;
12
12
  /** A block whose scope the file's structure does not determine; scope checks are skipped. */
13
13
  const UNKNOWN_SCOPE = 'unknown';
14
+ /**
15
+ * Commands whose arguments name a definition: the bare value (`add_ideas = X`, also a list
16
+ * `add_ideas = { X Y }`) or named fields of the argument block. From the effects and triggers
17
+ * documentation of 1.19.4.1.
18
+ */
19
+ const identifierArguments = {
20
+ add_ideas: { value: 'idea' },
21
+ remove_ideas: { value: 'idea' },
22
+ has_idea: { value: 'idea' },
23
+ add_timed_idea: { fields: { idea: 'idea' } },
24
+ modify_timed_idea: { fields: { idea: 'idea' } },
25
+ activate_decision: { value: 'decision' },
26
+ activate_targeted_decision: { fields: { decision: 'decision' } },
27
+ has_completed_focus: { value: 'focus' },
28
+ complete_national_focus: { value: 'focus' },
29
+ uncomplete_national_focus: { value: 'focus' },
30
+ has_tech: { value: 'technology' },
31
+ country_event: { value: 'event', fields: { id: 'event' } },
32
+ news_event: { value: 'event', fields: { id: 'event' } },
33
+ state_event: { value: 'event', fields: { id: 'event' } },
34
+ unit_leader_event: { value: 'event', fields: { id: 'event' } },
35
+ operative_leader_event: { value: 'event', fields: { id: 'event' } },
36
+ };
37
+ export const identifierArgumentCommands = new Set(Object.keys(identifierArguments));
38
+ /** Values that are computed or substituted, so their target cannot be read from source. */
39
+ const dynamicValue = /[[\]$@:]|^(?:yes|no)$/u;
14
40
  /**
15
41
  * Scope links from the wiki Scopes page: the scopes each link is usable in and the scope it
16
42
  * enters. The engine accepts these keys in any letter case. The game's documentation does not
@@ -195,7 +221,7 @@ const iteratorParameters = new Set([
195
221
  'count',
196
222
  ]);
197
223
  /** Check only rules explicitly available from one selected documentation authority. */
198
- export async function validateScript(references, workspace, input, signal, file) {
224
+ export async function validateScript(references, workspace, input, signal, file, identifiers) {
199
225
  if (file === undefined && Buffer.byteLength(input.source ?? '', 'utf8') > 64_000)
200
226
  throw new ServiceError('SCRIPT_SOURCE_TOO_LARGE', 'Snippet exceeds 64000 UTF-8 bytes');
201
227
  const inventory = await references.inventory(workspace, signal, [input.documentation]);
@@ -289,6 +315,58 @@ export async function validateScript(references, workspace, input, signal, file)
289
315
  message: diagnostic.message.slice(0, 500),
290
316
  suggestions: [],
291
317
  });
318
+ /** Identifier sets in lower case, built once per kind. */
319
+ const foldedIds = new Map();
320
+ /** Reports identifier arguments of a native command that name nothing the workspace defines. */
321
+ const checkIdentifiers = (entry, kind, scope) => {
322
+ const rule = identifierArguments[entry.key.value];
323
+ if (rule === undefined || identifiers === undefined)
324
+ return;
325
+ const values = [];
326
+ if (entry.value.type === 'scalar' && rule.value !== undefined)
327
+ values.push({ node: entry, value: entry.value.value, target: rule.value });
328
+ else if (entry.value.type === 'block')
329
+ for (const child of entry.value.entries) {
330
+ if (child.type === 'scalar' && rule.value !== undefined)
331
+ values.push({ node: entry, value: child.value, target: rule.value });
332
+ else if (child.type === 'assignment' && child.value.type === 'scalar') {
333
+ const target = rule.fields?.[child.key.value];
334
+ if (target !== undefined)
335
+ values.push({ node: child, value: child.value.value, target });
336
+ }
337
+ }
338
+ for (const { node, value, target } of values) {
339
+ if (dynamicValue.test(value))
340
+ continue;
341
+ const known = identifiers.ids.get(target);
342
+ if (known === undefined || known.has(value))
343
+ continue;
344
+ // The game finds these ids without case: vanilla fires `NSB_news.2` for `nsb_news.2`, and
345
+ // Kaiserreich adds `spr_carlism1` for `SPR_carlism1`.
346
+ let lower = foldedIds.get(target);
347
+ if (lower === undefined)
348
+ foldedIds.set(target, (lower = new Set([...known].map((id) => id.toLowerCase()))));
349
+ if (lower.has(value.toLowerCase()))
350
+ continue;
351
+ const suggestions = value.length > 128
352
+ ? []
353
+ : [...known]
354
+ .filter((candidate) => Math.abs(candidate.length - value.length) <= 3)
355
+ .filter(() => suggestionBudget-- > 0)
356
+ .map((candidate) => ({ candidate, distance: editDistance(value, candidate) }))
357
+ .filter(({ distance }) => distance <= 3)
358
+ .sort((a, b) => a.distance - b.distance || a.candidate.localeCompare(b.candidate, 'en'))
359
+ .slice(0, 3)
360
+ .map(({ candidate }) => candidate);
361
+ report(node, kind, scope, {
362
+ code: 'SCRIPT_ARGUMENT_UNKNOWN_ID',
363
+ // The game loads the file and the command does nothing, as vanilla's own dangling ids show.
364
+ status: identifiers.complete ? 'warning' : 'unresolved',
365
+ message: `${entry.key.value} names ${target} ${value.slice(0, 256)}, which ${identifiers.complete ? 'no loaded file defines' : 'the indexed files do not define (the index is incomplete)'}`,
366
+ suggestions,
367
+ });
368
+ }
369
+ };
292
370
  const walk = (block, kind, scope, previous) => {
293
371
  for (const entry of block.entries) {
294
372
  signal?.throwIfAborted();
@@ -444,6 +522,7 @@ export async function validateScript(references, workspace, input, signal, file)
444
522
  ? `Supported scopes: ${signature.scopes.join(', ')}`
445
523
  : 'Command kind and declared scope match the selected documentation',
446
524
  });
525
+ checkIdentifiers(entry, kind, scope);
447
526
  }
448
527
  const iterator = /^(?:every|random|any|all)_(?:(?:owned|controlled|neighbor)_)?(state|country)$/u.exec(name);
449
528
  if (entry.value.type !== 'block') {
@@ -557,6 +636,36 @@ export async function validateScript(references, workspace, input, signal, file)
557
636
  inventory.skipped > 0 ||
558
637
  (file === undefined ? catalogs[input.kind].size === 0 : plan.roots.length === 0) ||
559
638
  unknownScopeRoots > 0;
639
+ // A partial result names what is partial (#65), so `null` is never a bare "not sure".
640
+ const unknownScopeLines = plan.roots
641
+ .filter(({ scope }) => scope === UNKNOWN_SCOPE)
642
+ .slice(0, 8)
643
+ .map(({ block }) => locationFor(documentPath, document.lineIndex, block.start, block.end).start.line);
644
+ const partialReasons = [
645
+ ...(unresolvedCount > 0
646
+ ? [
647
+ `${unresolvedCount === 1 ? '1 command' : `${unresolvedCount} commands`} could not be resolved (see findings with status unresolved)`,
648
+ ]
649
+ : []),
650
+ ...(truncated ? [`only the first ${commandLimit} commands were checked`] : []),
651
+ ...(inventory.skipped > 0
652
+ ? [
653
+ `${inventory.skipped === 1 ? '1 documentation source' : `${inventory.skipped} documentation sources`} could not be read`,
654
+ ]
655
+ : []),
656
+ ...((file === undefined ? catalogs[input.kind].size === 0 : plan.roots.length === 0)
657
+ ? [
658
+ file === undefined
659
+ ? `the documentation lists no ${input.kind} commands`
660
+ : `no effect or trigger block of a known file family was found in ${file.path}`,
661
+ ]
662
+ : []),
663
+ ...(unknownScopeRoots > 0
664
+ ? [
665
+ `${unknownScopeRoots === 1 ? '1 block runs' : `${unknownScopeRoots} blocks run`} in a scope this file does not fix (a scripted helper or on_action, at line${unknownScopeLines.length === 1 ? '' : 's'} ${unknownScopeLines.join(', ')}${unknownScopeRoots > unknownScopeLines.length ? ' and more' : ''}), so scope rules were not applied there`,
666
+ ]
667
+ : []),
668
+ ];
560
669
  const order = { error: 0, unresolved: 1, warning: 2, supported: 3 };
561
670
  findings.sort((a, b) => order[a.status] - order[b.status] ||
562
671
  a.line - b.line ||
@@ -571,8 +680,9 @@ export async function validateScript(references, workspace, input, signal, file)
571
680
  ...(playerTextChecked ? ['player_text'] : []),
572
681
  ...(eventPopups === undefined ? [] : ['event_popups']),
573
682
  ...(knownMistakes === undefined ? [] : ['known_mistakes']),
683
+ ...(identifiers === undefined ? [] : ['identifier_arguments']),
574
684
  ],
575
- parametersChecked: false,
685
+ parametersChecked: identifiers !== undefined,
576
686
  documentation: {
577
687
  source: input.documentation,
578
688
  revision: hashCanonical([...sources].sort()),
@@ -587,6 +697,7 @@ export async function validateScript(references, workspace, input, signal, file)
587
697
  unresolvedCount,
588
698
  truncated,
589
699
  argumentBlocksUnchecked,
700
+ ...(partialReasons.length === 0 ? {} : { partialReasons }),
590
701
  ...(file === undefined
591
702
  ? {}
592
703
  : {
@@ -18,7 +18,7 @@ export const ideaInspectRequestSchema = z
18
18
  message: 'pass an id, or audit: true',
19
19
  path: ['id'],
20
20
  });
21
- const placeSchema = z
21
+ export const placeSchema = z
22
22
  .object({
23
23
  path: z.string().max(1024),
24
24
  line: z.number().int().min(0),
@@ -26,10 +26,10 @@ const placeSchema = z
26
26
  layerKind: z.enum(['game', 'dlc', 'dependency', 'mod']),
27
27
  })
28
28
  .strict();
29
- const fieldSchema = z
29
+ export const fieldSchema = z
30
30
  .object({ name: z.string().max(128), text: z.string().max(2400), line: z.number().int() })
31
31
  .strict();
32
- const problemSchema = z
32
+ export const problemSchema = z
33
33
  .object({
34
34
  code: z.string().max(64),
35
35
  severity: z.enum(['warning', 'info']),
@@ -37,7 +37,7 @@ const problemSchema = z
37
37
  line: z.number().int().min(0),
38
38
  })
39
39
  .strict();
40
- const textSchema = z
40
+ export const textSchema = z
41
41
  .object({
42
42
  language: z.string().max(64),
43
43
  text: z.string().max(2400),