hoi4-agent-tools 4.20.2 → 4.21.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 (99) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bin/stdio.js +5 -2
  3. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  4. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  5. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  6. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  7. package/dist/hoi4_agent_tools/core/engine.js +77 -17
  8. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  9. package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
  10. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  11. package/dist/hoi4_agent_tools/core/workspace.js +130 -19
  12. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  13. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  14. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  15. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  16. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  17. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  18. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  19. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  20. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  21. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  22. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  23. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  24. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  25. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  26. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  27. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  28. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  29. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  30. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  31. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  32. package/dist/hoi4_agent_tools/map/model.js +17 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  34. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +9 -0
  35. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +4 -0
  36. package/dist/hoi4_agent_tools/mcp/server/startup-failure.js +19 -0
  37. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  38. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  39. package/dist/hoi4_agent_tools/runtime.js +85 -19
  40. package/dist/hoi4_agent_tools/schemas/transaction.js +3 -2
  41. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  42. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  43. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  44. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  45. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  46. package/dist/hoi4_agent_tools/technology/source-analysis.js +3 -1
  47. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  48. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  49. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  50. package/dist/hoi4_agent_tools/version.js +1 -1
  51. package/docs/configuration.md +11 -10
  52. package/docs/troubleshooting.md +11 -11
  53. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  54. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  55. package/engine/bin/linux-x64/hoi4-engine +0 -0
  56. package/engine/bin/manifest.json +8 -8
  57. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  58. package/npm-shrinkwrap.json +2 -2
  59. package/package.json +2 -2
  60. package/schemas/configuration.schema.json +143 -134
  61. package/schemas/continuous-focus-palette.schema.json +1 -1
  62. package/schemas/custom-weighted-pool.schema.json +1 -1
  63. package/schemas/decision-inspect-input.schema.json +1 -1
  64. package/schemas/error-log-input.schema.json +1 -1
  65. package/schemas/event-feature-manifest.schema.json +1 -1
  66. package/schemas/focus-plan.schema.json +1 -1
  67. package/schemas/focus-planning-sidecar.schema.json +1 -1
  68. package/schemas/geography-model.schema.json +1 -1
  69. package/schemas/gui-animation-source.schema.json +1 -1
  70. package/schemas/gui-helper.schema.json +1 -1
  71. package/schemas/gui-scenario.schema.json +1 -1
  72. package/schemas/helper-expansion-request.schema.json +1 -1
  73. package/schemas/helper-expansion-summary.schema.json +1 -1
  74. package/schemas/impact-inspect-input.schema.json +1 -1
  75. package/schemas/map-operation.schema.json +1 -1
  76. package/schemas/mechanic-test-input.schema.json +1 -1
  77. package/schemas/mod-index-input.schema.json +1 -1
  78. package/schemas/operation-result.schema.json +1 -1
  79. package/schemas/package-check-input.schema.json +1 -1
  80. package/schemas/package-manifest.schema.json +1 -1
  81. package/schemas/probability-analysis-result.schema.json +1 -1
  82. package/schemas/probability-compare-input.schema.json +1 -1
  83. package/schemas/probability-evaluate-input.schema.json +1 -1
  84. package/schemas/probability-inspect-input.schema.json +1 -1
  85. package/schemas/probability-render-input.schema.json +1 -1
  86. package/schemas/probability-scenario-set.schema.json +1 -1
  87. package/schemas/probability-sequence-input.schema.json +1 -1
  88. package/schemas/probability-simulate-input.schema.json +1 -1
  89. package/schemas/probability-sweep-input.schema.json +1 -1
  90. package/schemas/reference-context-input.schema.json +1 -1
  91. package/schemas/reference-read-input.schema.json +1 -1
  92. package/schemas/reference-search-input.schema.json +1 -1
  93. package/schemas/reference-sheets.schema.json +1 -1
  94. package/schemas/scenario-suite.schema.json +1 -1
  95. package/schemas/scenario-test-input.schema.json +1 -1
  96. package/schemas/script-validate-input.schema.json +1 -1
  97. package/schemas/shared-scenario.schema.json +1 -1
  98. package/schemas/source-lookup-input.schema.json +1 -1
  99. package/server.json +2 -2
@@ -1,4 +1,3 @@
1
- import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
2
1
  import { sortDiagnostics } from '../core/diagnostics.js';
3
2
  import { assertRenderDimensions } from '../core/render-budget.js';
4
3
  import { addActiveMapDiagnostic, addMapDiagnostic } from './diagnostic-limit.js';
@@ -6,6 +5,7 @@ import { validateAppearance } from './appearance-validation.js';
6
5
  import { validateCrossings } from './gameplay/crossing-validation.js';
7
6
  import { rgbKey } from './bmp.js';
8
7
  import { MAP_PROVINCE_ENGINE_MAX_PIXELS } from './model.js';
8
+ import { engineValidateMapAsync, engineValidateMapSync } from './engine-validation.js';
9
9
  const MAP_DIAGNOSTIC_DETAIL_SAMPLE_LIMIT = 100;
10
10
  function* cancellationCheckpoint(signal, iteration = 0, stride = 1) {
11
11
  if (iteration % stride !== 0)
@@ -20,20 +20,6 @@ function completeSynchronously(steps) {
20
20
  return step.value;
21
21
  }
22
22
  }
23
- async function completeCooperatively(steps, signal) {
24
- let yieldDeadline = performance.now() + 8;
25
- for (;;) {
26
- const step = steps.next();
27
- if (step.done)
28
- return step.value;
29
- signal?.throwIfAborted();
30
- if (performance.now() < yieldDeadline)
31
- continue;
32
- await yieldToEventLoop();
33
- signal?.throwIfAborted();
34
- yieldDeadline = performance.now() + 8;
35
- }
36
- }
37
23
  function lineLocation(document, oneBasedLine) {
38
24
  const line = document.lines[oneBasedLine - 1];
39
25
  if (line === undefined)
@@ -1356,10 +1342,18 @@ export function mapValidationChecks(diagnostics) {
1356
1342
  },
1357
1343
  ];
1358
1344
  }
1345
+ /**
1346
+ * Validates the map on the engine (`map.validate`, ADR 0089 step 6). Synchronous callers get a
1347
+ * one-shot engine; a missing engine is `ENGINE_UNAVAILABLE`.
1348
+ */
1359
1349
  export function validateMap(index, options = {}) {
1360
- return completeSynchronously(validateMapSteps(index, options));
1350
+ return engineValidateMapSync(index, options);
1361
1351
  }
1362
- /** Validates map geometry and records while yielding so protocol cancellation can be delivered. */
1352
+ /** Validates the map on the resident engine; `signal` cancels the call. */
1363
1353
  export async function validateMapAsync(index, options = {}) {
1364
- return completeCooperatively(validateMapSteps(index, options), options.signal);
1354
+ return engineValidateMapAsync(index, options);
1355
+ }
1356
+ /** The TypeScript validation, kept only for `scripts/map-validation-parity.ts` until parity is clean. */
1357
+ export function typeScriptValidateMap(index, options = {}) {
1358
+ return completeSynchronously(validateMapSteps(index, options));
1365
1359
  }
@@ -17,6 +17,7 @@ import { referenceTools } from '../tools/reference.js';
17
17
  import { isReferenceTool, ReferenceToolService } from '../../reference/operations.js';
18
18
  import { ModernTaskAdapter, TASKS_EXTENSION } from './modern-tasks.js';
19
19
  import { SERVER_INSTRUCTIONS } from './instructions.js';
20
+ import { startupFailureResult } from './startup-failure.js';
20
21
  import { jobProgressReporter, modernProgressReporter, withProgressHeartbeat } from './progress.js';
21
22
  import { taskToolCatalog } from './task-tool-catalog.js';
22
23
  import { isListed, profileInstructions, resolveProfiles } from './tool-profiles.js';
@@ -100,6 +101,14 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
100
101
  const definition = definitions.find(({ name }) => name === request.params.name);
101
102
  if (definition === undefined)
102
103
  throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown tool');
104
+ const startupFailure = startupFailureResult(engine, definition.name);
105
+ if (startupFailure !== undefined)
106
+ return CallToolResultSchema.parse({
107
+ ...startupFailure,
108
+ resultType: 'complete',
109
+ ttlMs: 0,
110
+ cacheScope: 'private',
111
+ });
103
112
  const input = definition.inputSchema.safeParse(normalizeToolArguments(definition.name, request.params.arguments ?? {}));
104
113
  if (!input.success) {
105
114
  // A tool error, not a protocol error, so the model sees which field to correct.
@@ -4,6 +4,7 @@ import { normalizeToolArguments } from '../../schemas/lenient-arguments.js';
4
4
  import { referenceTools } from '../tools/reference.js';
5
5
  import { jobControlTools } from '../tools/job.js';
6
6
  import { invalidArgumentsResult } from './argument-errors.js';
7
+ import { startupFailureResult } from './startup-failure.js';
7
8
  import { taskToolCatalog } from './task-tool-catalog.js';
8
9
  import { jobProgressReporter, progressReporter, withProgressHeartbeat } from './progress.js';
9
10
  import { withTaskRequestSignal } from './task-request-context.js';
@@ -37,6 +38,9 @@ export function installRequestLifecycle(server, engine) {
37
38
  return handler(request, extra);
38
39
  const params = request.params;
39
40
  if (params !== undefined && typeof params.name === 'string') {
41
+ const failed = startupFailureResult(engine, params.name);
42
+ if (failed !== undefined)
43
+ return Promise.resolve(failed);
40
44
  params.arguments = normalizeToolArguments(params.name, params.arguments);
41
45
  // Answer invalid arguments with a tool error that names the fields and a working call.
42
46
  const schema = params.task === undefined ? inputSchema(params.name) : undefined;
@@ -0,0 +1,19 @@
1
+ import { DOMAIN_TOOL_NAMES } from '../../core/domain-tools.js';
2
+ import { isJobControlTool } from '../../core/job-controls.js';
3
+ import { errorResult } from '../../core/operation-result.js';
4
+ const domainTools = new Set(DOMAIN_TOOL_NAMES);
5
+ /**
6
+ * The answer to a call that needs a workspace when the server could not load its workspaces: the
7
+ * error that stopped the startup, in the ordinary tool-error envelope with its code. The stdio
8
+ * server keeps running after such an error (it answered the handshake before loading), and the
9
+ * client library would otherwise reduce the thrown error to its message. Tools that need no
10
+ * workspace, and every call on a server that started, get `undefined` and run as usual.
11
+ */
12
+ export function startupFailureResult(engine, toolName) {
13
+ const failure = engine.resolver.startupError();
14
+ if (failure === undefined)
15
+ return undefined;
16
+ if (!domainTools.has(toolName) && !isJobControlTool(toolName))
17
+ return undefined;
18
+ return errorResult(failure);
19
+ }
@@ -6,9 +6,10 @@ import { BoundedStdioServerTransport, STDIO_MAX_FRAME_BYTES } from './bounded-st
6
6
  import { FinalProtocolTransport } from './protocol-gate.js';
7
7
  const MAX_QUEUED_MESSAGES = 128;
8
8
  /**
9
- * Requests that only describe the server. They are answered while startup recovery still runs;
10
- * every other message waits for it, in arrival order, so no request reads or writes a workspace
11
- * whose interrupted rewrite is not yet recovered.
9
+ * Requests that only describe the server. They are answered at once and start nothing: an idle
10
+ * server loads no workspace. The first other message starts the engine's startup (`recovered()`)
11
+ * and waits for it, with every later one in arrival order, so no request reads or writes a
12
+ * workspace that is not loaded yet.
12
13
  */
13
14
  const ANSWERED_BEFORE_RECOVERY = new Set([
14
15
  'initialize',
@@ -141,7 +142,7 @@ export async function serveNegotiatedStdio(engine, options) {
141
142
  }
142
143
  pinned.receive(message);
143
144
  };
144
- // Startup recovery: `held` until it ends, then `open`; `closed` drops every later message.
145
+ // Startup: `held` until it ends, then `open`; `closed` drops every later message.
145
146
  let recovery = 'held';
146
147
  let heldBytes = 0;
147
148
  const held = [];
@@ -151,19 +152,25 @@ export async function serveNegotiatedStdio(engine, options) {
151
152
  heldBytes = 0;
152
153
  void physical.close();
153
154
  };
154
- engine.recovered().then(() => {
155
- if (recovery === 'closed')
156
- return;
157
- recovery = 'open';
158
- heldBytes = 0;
159
- for (const message of held.splice(0))
160
- deliver(message);
161
- }, (error) => {
162
- if (recovery === 'closed')
155
+ let started = false;
156
+ const start = () => {
157
+ if (started)
163
158
  return;
164
- options.onFailure(error);
165
- closeHeld();
166
- });
159
+ started = true;
160
+ engine.recovered().then(() => {
161
+ if (recovery === 'closed')
162
+ return;
163
+ recovery = 'open';
164
+ heldBytes = 0;
165
+ for (const message of held.splice(0))
166
+ deliver(message);
167
+ }, (error) => {
168
+ if (recovery === 'closed')
169
+ return;
170
+ options.onFailure(error);
171
+ closeHeld();
172
+ });
173
+ };
167
174
  physical.onmessage = (message) => {
168
175
  observer?.received(message);
169
176
  if (recovery === 'closed')
@@ -174,6 +181,7 @@ export async function serveNegotiatedStdio(engine, options) {
174
181
  deliver(message);
175
182
  return;
176
183
  }
184
+ start();
177
185
  const bytes = Buffer.byteLength(JSON.stringify(message)) + 1;
178
186
  if (held.length >= MAX_QUEUED_MESSAGES || bytes > STDIO_MAX_FRAME_BYTES - heldBytes) {
179
187
  reportError(new Error('Requests held during startup recovery exceeded their bounded limit'));
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { IdleCacheLifetime } from '../core/idle-cache-lifetime.js';
2
+ import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
3
3
  import { errorResult, toolResult } from '../core/operation-result.js';
4
4
  import { ServiceError } from '../core/result.js';
5
5
  import { probabilityAnalyzeRequestSchema, probabilityInspectRequestSchema, } from '../schemas/probability-requests.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers probability operations without invoking transport handlers. */
10
10
  export function registerProbabilityJobs(operations, engine) {
11
11
  const analyzer = new ProbabilityAnalyzer(engine);
12
- const lifetime = new IdleCacheLifetime(() => analyzer.clearCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => analyzer.clearCaches());
13
13
  function register(name, schema, normalize, execute, message) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -2,6 +2,7 @@ import { lstat, readdir, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { homedir, tmpdir } from 'node:os';
4
4
  import { loadConfiguration, serverConfigurationSchema, } from './core/configuration.js';
5
+ import { canonicalJson } from './core/canonical.js';
5
6
  import { CoreEngine } from './core/engine.js';
6
7
  import { ServiceError } from './core/result.js';
7
8
  import { WorkspaceResolver } from './core/workspace.js';
@@ -238,10 +239,9 @@ async function configurationExists(configPath) {
238
239
  return false;
239
240
  }
240
241
  }
241
- export async function createEngine(configPath = configurationPath(), options = {}) {
242
- let configuration;
242
+ async function loadStartupConfiguration(configPath) {
243
243
  try {
244
- configuration = await loadConfiguration(configPath);
244
+ return await loadConfiguration(configPath);
245
245
  }
246
246
  catch (error) {
247
247
  const useAutomaticConfiguration = configPath === defaultConfigurationPath() &&
@@ -252,18 +252,22 @@ export async function createEngine(configPath = configurationPath(), options = {
252
252
  if (!useAutomaticConfiguration)
253
253
  throw error;
254
254
  // Outside a mod there is no workspace, and the documentation tools still answer.
255
- configuration = await automaticConfiguration(process.cwd(), { allowNoMod: true });
255
+ return automaticConfiguration(process.cwd(), { allowNoMod: true });
256
256
  }
257
- // The stdio server lists the core tools unless the client or the file asks for more.
258
- const profiles = parseProfilesEnv(process.env[PROFILES_ENV]) ??
259
- configuration.profiles ??
260
- options.defaultProfiles;
261
- if (profiles !== undefined)
262
- configuration = { ...configuration, profiles: [...profiles] };
263
- // The command-line servers read a fetched docs pack from the user's data folder by default.
264
- if (configuration.docsRoot === undefined)
265
- configuration = { ...configuration, docsRoot: defaultDocsRoot() };
266
- const resolver = await WorkspaceResolver.create(configuration);
257
+ }
258
+ /** A startup failure on stderr, where the operator's log shows why the server cannot serve. */
259
+ function reportStartupFailure(error) {
260
+ process.stderr.write(`${canonicalJson({
261
+ level: 'error',
262
+ event: 'startup_failed',
263
+ code: typeof error === 'object' && error !== null && 'code' in error
264
+ ? String(error.code)
265
+ : 'INTERNAL_ERROR',
266
+ message: error instanceof Error ? error.message : String(error),
267
+ })}
268
+ `);
269
+ }
270
+ async function sweepTemporaryDirectoriesOf(resolver) {
267
271
  await sweepTemporaryDirectories(tmpdir(), {
268
272
  protectedRoots: [
269
273
  ...resolver
@@ -276,11 +280,73 @@ export async function createEngine(configPath = configurationPath(), options = {
276
280
  ...(resolver.serverState() === undefined ? [] : [resolver.serverState().root]),
277
281
  ],
278
282
  }).catch(() => undefined);
283
+ }
284
+ export async function createEngine(configPath = configurationPath(), options = {}) {
285
+ const background = options.workspaces === 'background';
286
+ // The error that stops the server, which a background start reports instead of throwing.
287
+ let startupError;
288
+ let configuration;
289
+ try {
290
+ configuration = await loadStartupConfiguration(configPath);
291
+ }
292
+ catch (error) {
293
+ if (!background)
294
+ throw error;
295
+ startupError = error;
296
+ // The tool list still comes from the profiles, and the documentation tools still answer.
297
+ configuration = serverConfigurationSchema.parse({ version: CONFIG_VERSION });
298
+ }
299
+ // The stdio server lists the core tools unless the client or the file asks for more.
300
+ const profiles = parseProfilesEnv(process.env[PROFILES_ENV]) ??
301
+ configuration.profiles ??
302
+ options.defaultProfiles;
303
+ if (profiles !== undefined)
304
+ configuration = { ...configuration, profiles: [...profiles] };
305
+ // The command-line servers read a fetched docs pack from the user's data folder by default.
306
+ if (configuration.docsRoot === undefined)
307
+ configuration = { ...configuration, docsRoot: defaultDocsRoot() };
308
+ if (!background) {
309
+ const resolver = await WorkspaceResolver.create(configuration);
310
+ await sweepTemporaryDirectoriesOf(resolver);
311
+ const engine = new CoreEngine(resolver);
312
+ // A failed background recovery is the caller's to report through `engine.recovered()`.
313
+ if (options.recovery === 'background')
314
+ engine.initialize().catch(() => undefined);
315
+ else
316
+ await engine.initialize();
317
+ return engine;
318
+ }
319
+ let resolver;
320
+ try {
321
+ resolver = await WorkspaceResolver.prepare(configuration);
322
+ }
323
+ catch (error) {
324
+ startupError ??= error;
325
+ resolver = await WorkspaceResolver.prepare({
326
+ ...serverConfigurationSchema.parse({ version: CONFIG_VERSION }),
327
+ ...(configuration.profiles === undefined ? {} : { profiles: configuration.profiles }),
328
+ ...(configuration.docsRoot === undefined ? {} : { docsRoot: configuration.docsRoot }),
329
+ });
330
+ }
279
331
  const engine = new CoreEngine(resolver);
280
- // A failed background recovery is the caller's to report through `engine.recovered()`.
281
- if (options.recovery === 'background')
282
- engine.initialize().catch(() => undefined);
283
- else
284
- await engine.initialize();
332
+ if (startupError !== undefined) {
333
+ resolver.failStartup(startupError);
334
+ reportStartupFailure(startupError);
335
+ return engine;
336
+ }
337
+ // Neither the loading nor the recovery of a workspace starts until a request needs one: the
338
+ // transport asks `engine.recovered()` for the first such request, and each workspace
339
+ // recovers on its first use.
340
+ engine.recoverOnDemand();
341
+ engine.deferStartup(async () => {
342
+ try {
343
+ await resolver.populate();
344
+ }
345
+ catch (error) {
346
+ reportStartupFailure(error);
347
+ return;
348
+ }
349
+ await sweepTemporaryDirectoriesOf(resolver);
350
+ });
285
351
  return engine;
286
352
  }
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { TRANSACTION_MAX_APPLIED_FILES, TRANSACTION_MAX_ARTIFACTS, TRANSACTION_MAX_DIAGNOSTICS, TRANSACTION_MAX_FILES, TRANSACTION_MAX_OPERATIONS, TRANSACTION_MAX_PENDING_FILES, TRANSACTION_MAX_READ_DEPENDENCIES, TRANSACTION_MAX_VALIDATION_CHECKS, } from '../core/transaction-limits.js';
2
+ import { TRANSACTION_MAX_APPLIED_FILES, TRANSACTION_MAX_ARTIFACTS, TRANSACTION_MAX_BATCH_FILES, TRANSACTION_MAX_DIAGNOSTICS, TRANSACTION_MAX_FILES, TRANSACTION_MAX_OPERATIONS, TRANSACTION_MAX_READ_DEPENDENCIES, TRANSACTION_MAX_VALIDATION_CHECKS, } from '../core/transaction-limits.js';
3
3
  import { TRANSACTION_VERSION } from '../version.js';
4
4
  import { diagnosticSchema, workspaceIdSchema, workspaceRelativePathSchema } from './common.js';
5
5
  const sha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -113,7 +113,8 @@ export const transactionManifestSchema = z
113
113
  stagedIdentity: fileIdentitySchema.nullable(),
114
114
  })
115
115
  .strict())
116
- .max(TRANSACTION_MAX_PENDING_FILES)
116
+ // A batch records one pending entry per file, and large applies use batches up to this size.
117
+ .max(TRANSACTION_MAX_BATCH_FILES)
117
118
  .optional(),
118
119
  rollbackStatus: z.enum(['available', 'applied', 'failed']),
119
120
  failure: z.object({ code: identifierSchema, message: summarySchema }).strict().optional(),
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod/v4';
2
+ import { callEngineOperation } from '../core/engine-operation.js';
3
+ import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
4
+ import { decodeSource } from '../core/source/encoding.js';
5
+ /**
6
+ * The call every script writer makes (ADR 0089, ADR 0091, packet P10): the engine plans the edit of
7
+ * one definition and answers with the plan's JSON and the bytes of the file after the edit. The
8
+ * writer never touches the disk. This side adds the decoded text and the unified diff, which move to
9
+ * the engine with the diff service.
10
+ */
11
+ /** One replacement. `start` and `end` are byte offsets of the decoded text (UTF-8 after the byte order mark), not UTF-16 offsets. */
12
+ export const replacementSchema = z.object({
13
+ start: z.number().int().nonnegative(),
14
+ end: z.number().int().nonnegative(),
15
+ text: z.string(),
16
+ description: z.string(),
17
+ });
18
+ export async function callWritePlan(call) {
19
+ const answer = await callEngineOperation({
20
+ op: call.op,
21
+ body: { input: call.input, path: call.path, newFile: call.source === undefined },
22
+ ...(call.source === undefined ? {} : { payload: Buffer.from(call.source) }),
23
+ result: call.result,
24
+ });
25
+ const text = decodeSource(answer.payload).text;
26
+ const before = call.source === undefined ? '' : decodeSource(call.source).text;
27
+ return {
28
+ result: answer.result,
29
+ bytes: answer.payload,
30
+ text,
31
+ diff: unifiedTextDiff(before, text, `a/${call.path}`, `b/${call.path}`, {
32
+ context: DIFF_CONTEXT_LINES,
33
+ }),
34
+ };
35
+ }
36
+ /** Asks the engine a question about one source file, such as the categories it has. */
37
+ export async function callSourceQuery(op, path, source, result) {
38
+ const answer = await callEngineOperation({
39
+ op,
40
+ body: { path },
41
+ payload: Buffer.from(source),
42
+ result: result,
43
+ });
44
+ return answer.result;
45
+ }
@@ -0,0 +1,156 @@
1
+ import { z } from 'zod/v4';
2
+ import { currentAnalysisCheckpoints } from '../core/analysis-checkpoints.js';
3
+ import { canonicalJson, hashCanonical } from '../core/canonical.js';
4
+ import { callEngineOperation } from '../core/engine-operation.js';
5
+ import { ServiceError } from '../core/result.js';
6
+ /**
7
+ * The technology graph and its read-only queries on the Rust engine (ADR 0089, packet P5).
8
+ * `tech.analyze` reads the sources and answers which sprites and localisation keys the graph
9
+ * needs, `tech.graph` assembles the graph from the index lookups sent back, and `tech.query`
10
+ * answers one query of a graph the engine holds by revision. The graph is the same snapshot the
11
+ * TypeScript builder produced, so rendering and comparison read it unchanged.
12
+ */
13
+ const analyzeSchema = z
14
+ .object({
15
+ session: z.string(),
16
+ wants: z.object({ sprites: z.array(z.string()), localisation: z.array(z.string()) }).strict(),
17
+ })
18
+ .strict();
19
+ const answerSchema = z.object({ format: z.literal('json') }).strict();
20
+ /** The graph payload is parsed JSON from outside the process: only its shape is checked here, and the engine owns the content. */
21
+ const graphPayloadSchema = z.looseObject({
22
+ schemaVersion: z.literal(2),
23
+ technologies: z.array(z.unknown()),
24
+ });
25
+ const scanCheckpointSchema = z.object({ stage: z.literal('scanned'), files: z.number() }).strict();
26
+ const querySchema = z.object({ report: z.unknown(), summary: z.unknown().optional() }).strict();
27
+ function wireFile(file) {
28
+ return {
29
+ absolutePath: file.absolutePath,
30
+ displayPath: file.displayPath,
31
+ relativePath: file.relativePath,
32
+ rootKind: file.rootKind,
33
+ loadOrder: file.loadOrder,
34
+ size: Math.trunc(file.size),
35
+ modifiedMs: Math.trunc(file.modifiedMs),
36
+ sha256: file.sha256,
37
+ ...(file.shadowedBy === undefined ? {} : { shadowedBy: file.shadowedBy }),
38
+ };
39
+ }
40
+ const analyses = new WeakMap();
41
+ function helperIds(snapshot) {
42
+ return snapshot.index
43
+ .findAll('scripted_effect')
44
+ .filter(({ overridden, sourceShadowed }) => !overridden && !sourceShadowed)
45
+ .map(({ id }) => id);
46
+ }
47
+ async function analyze(snapshot) {
48
+ const { result } = await callEngineOperation({
49
+ op: 'tech.analyze',
50
+ body: { files: snapshot.files.map(wireFile), helperIds: helperIds(snapshot) },
51
+ result: analyzeSchema,
52
+ });
53
+ analyses.set(snapshot, result);
54
+ return result;
55
+ }
56
+ /**
57
+ * Records the finished source scan as the job's analysis checkpoint, bound to the scan's source
58
+ * revision, before the engine analyses it. A recovered job reuses the record only when the
59
+ * revision still matches; after the sources changed it records the new scan instead. The
60
+ * engine's analysis itself is atomic, so this is the one interruption point of the build.
61
+ */
62
+ async function recordScanCheckpoint(snapshot, analysisMode) {
63
+ const checkpoints = currentAnalysisCheckpoints();
64
+ if (checkpoints === undefined)
65
+ return;
66
+ const key = hashCanonical({
67
+ algorithm: 'technology-engine-graph.v1',
68
+ analysisMode: analysisMode ?? 'full',
69
+ });
70
+ const restored = await checkpoints.load(key, snapshot.revision, scanCheckpointSchema);
71
+ if (restored !== undefined)
72
+ return;
73
+ await checkpoints.save(key, snapshot.revision, { stage: 'scanned', files: snapshot.files.length }, 1, 2);
74
+ }
75
+ /** `buildTechnologyGraph` on the engine. */
76
+ export async function buildTechnologyGraphOnEngine(snapshot, options) {
77
+ await recordScanCheckpoint(snapshot, options.analysisMode);
78
+ const lookups = (analysis) => {
79
+ const sprites = {};
80
+ for (const name of analysis.wants.sprites) {
81
+ const sprite = snapshot.index.find('sprite', name);
82
+ if (sprite === undefined)
83
+ continue;
84
+ const texture = sprite.metadata.texture;
85
+ sprites[name] = [sprite.path, typeof texture === 'string' ? texture : null];
86
+ }
87
+ const localisation = {};
88
+ for (const key of analysis.wants.localisation) {
89
+ const value = snapshot.index.find('localisation', `l_english:${key}`)?.metadata.value;
90
+ if (typeof value === 'string')
91
+ localisation[key] = value;
92
+ }
93
+ return {
94
+ sprites,
95
+ skippedSpriteSource: snapshot.index.hasSkippedSourceForKind('sprite'),
96
+ localisation,
97
+ skippedLocalisationSource: snapshot.index.hasSkippedSourceForKind('localisation'),
98
+ };
99
+ };
100
+ const request = (analysis) => ({
101
+ op: 'tech.graph',
102
+ body: {
103
+ session: analysis.session,
104
+ scan: {
105
+ workspaceId: snapshot.workspaceId,
106
+ workspaceIdentity: options.workspaceIdentity,
107
+ revision: snapshot.revision,
108
+ complete: snapshot.complete,
109
+ skippedSourceCount: snapshot.skippedSourceCount,
110
+ skippedSources: snapshot.skippedSources,
111
+ diagnostics: snapshot.diagnostics,
112
+ assetFiles: (options.assetFiles ?? []).map(wireFile),
113
+ ...(options.analysisMode === undefined ? {} : { analysisMode: options.analysisMode }),
114
+ },
115
+ lookups: lookups(analysis),
116
+ },
117
+ result: answerSchema,
118
+ });
119
+ const graphOf = (answer) => {
120
+ const graph = JSON.parse(answer.payload.toString('utf8'));
121
+ if (!graphPayloadSchema.safeParse(graph).success)
122
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine tech.graph answered out of shape', {
123
+ op: 'tech.graph',
124
+ reason: 'invalid_response',
125
+ });
126
+ return graph;
127
+ };
128
+ let analysis = analyses.get(snapshot) ?? (await analyze(snapshot));
129
+ try {
130
+ return graphOf(await callEngineOperation(request(analysis)));
131
+ }
132
+ catch (error) {
133
+ if (!(error instanceof Error) || error.code !== 'TECH_SESSION_EXPIRED')
134
+ throw error;
135
+ analysis = await analyze(snapshot);
136
+ return graphOf(await callEngineOperation(request(analysis)));
137
+ }
138
+ }
139
+ /** One read-only query of a graph, answered by the engine; the graph is sent again if it expired. */
140
+ export async function queryTechnologyGraph(graph, query) {
141
+ const body = { revision: graph.revision, ...query };
142
+ const answerOf = (answer) => querySchema.parse(JSON.parse(answer.payload.toString('utf8')));
143
+ try {
144
+ return answerOf(await callEngineOperation({ op: 'tech.query', body, result: answerSchema }));
145
+ }
146
+ catch (error) {
147
+ if (!(error instanceof Error) || error.code !== 'TECH_GRAPH_EXPIRED')
148
+ throw error;
149
+ }
150
+ return answerOf(await callEngineOperation({
151
+ op: 'tech.query',
152
+ body: { ...body, graphInPayload: true },
153
+ payload: Buffer.from(canonicalJson(graph), 'utf8'),
154
+ result: answerSchema,
155
+ }));
156
+ }
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { IdleCacheLifetime } from '../core/idle-cache-lifetime.js';
2
+ import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
3
3
  import { errorResult, toolResult } from '../core/operation-result.js';
4
4
  import { ServiceError } from '../core/result.js';
5
5
  import { technologyInspectRequestSchema, technologyRenderRequestSchema, } from '../schemas/technology.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers typed technology operations without invoking transport handlers. */
10
10
  export function registerTechnologyJobs(operations, engine) {
11
11
  const viewer = new TechnologyTreeViewer(engine);
12
- const lifetime = new IdleCacheLifetime(() => viewer.clearCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => viewer.clearCaches());
13
13
  function register(name, schema, normalize, execute, message) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -4,7 +4,6 @@ import { compareCodeUnits, hashCanonical } from '../core/canonical.js';
4
4
  import { emptyServiceResult } from '../core/result.js';
5
5
  import { setInlineFilesScanned } from '../core/operation-result.js';
6
6
  import { technologyCompareRequestSchema, technologyInspectRequestSchema, splitTechnologyInspectRequest, technologyRenderRequestSchema, } from '../schemas/technology.js';
7
- import { technologyExplainSummary } from './queries.js';
8
7
  import { technologyDiagnostics } from './service.js';
9
8
  export function normalizeTechnologyInspectionRequest(input) {
10
9
  return JSON.parse(JSON.stringify(technologyInspectRequestSchema.parse(input)));
@@ -109,7 +108,7 @@ export async function inspectTechnologies(viewer, input) {
109
108
  counts: technologyCounts(output.graph, output.artifacts.length),
110
109
  ...(output.helperExpansion === undefined ? {} : { helperExpansion: output.helperExpansion }),
111
110
  ...(() => {
112
- const technology = input.mode === 'explain' ? technologyExplainSummary(output.report) : undefined;
111
+ const technology = input.mode === 'explain' ? output.explainSummary : undefined;
113
112
  return technology === undefined ? {} : { technology };
114
113
  })(),
115
114
  });