hoi4-agent-tools 4.20.3 → 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 (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  3. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  4. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  5. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  6. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  7. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  8. package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
  9. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  10. package/dist/hoi4_agent_tools/core/workspace.js +14 -1
  11. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  12. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  13. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  14. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  15. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  16. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  17. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  18. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  19. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  20. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  21. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  22. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  23. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  24. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  25. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  26. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  27. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  28. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  29. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  30. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  31. package/dist/hoi4_agent_tools/map/model.js +17 -3
  32. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  33. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  34. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  35. package/dist/hoi4_agent_tools/runtime.js +4 -2
  36. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  37. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  38. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  39. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  40. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  41. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  43. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  44. package/dist/hoi4_agent_tools/version.js +1 -1
  45. package/docs/configuration.md +11 -10
  46. package/docs/troubleshooting.md +11 -11
  47. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  48. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  49. package/engine/bin/linux-x64/hoi4-engine +0 -0
  50. package/engine/bin/manifest.json +8 -8
  51. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  52. package/npm-shrinkwrap.json +2 -2
  53. package/package.json +2 -2
  54. package/schemas/configuration.schema.json +143 -134
  55. package/schemas/continuous-focus-palette.schema.json +1 -1
  56. package/schemas/custom-weighted-pool.schema.json +1 -1
  57. package/schemas/decision-inspect-input.schema.json +1 -1
  58. package/schemas/error-log-input.schema.json +1 -1
  59. package/schemas/event-feature-manifest.schema.json +1 -1
  60. package/schemas/focus-plan.schema.json +1 -1
  61. package/schemas/focus-planning-sidecar.schema.json +1 -1
  62. package/schemas/geography-model.schema.json +1 -1
  63. package/schemas/gui-animation-source.schema.json +1 -1
  64. package/schemas/gui-helper.schema.json +1 -1
  65. package/schemas/gui-scenario.schema.json +1 -1
  66. package/schemas/helper-expansion-request.schema.json +1 -1
  67. package/schemas/helper-expansion-summary.schema.json +1 -1
  68. package/schemas/impact-inspect-input.schema.json +1 -1
  69. package/schemas/map-operation.schema.json +1 -1
  70. package/schemas/mechanic-test-input.schema.json +1 -1
  71. package/schemas/mod-index-input.schema.json +1 -1
  72. package/schemas/operation-result.schema.json +1 -1
  73. package/schemas/package-check-input.schema.json +1 -1
  74. package/schemas/package-manifest.schema.json +1 -1
  75. package/schemas/probability-analysis-result.schema.json +1 -1
  76. package/schemas/probability-compare-input.schema.json +1 -1
  77. package/schemas/probability-evaluate-input.schema.json +1 -1
  78. package/schemas/probability-inspect-input.schema.json +1 -1
  79. package/schemas/probability-render-input.schema.json +1 -1
  80. package/schemas/probability-scenario-set.schema.json +1 -1
  81. package/schemas/probability-sequence-input.schema.json +1 -1
  82. package/schemas/probability-simulate-input.schema.json +1 -1
  83. package/schemas/probability-sweep-input.schema.json +1 -1
  84. package/schemas/reference-context-input.schema.json +1 -1
  85. package/schemas/reference-read-input.schema.json +1 -1
  86. package/schemas/reference-search-input.schema.json +1 -1
  87. package/schemas/reference-sheets.schema.json +1 -1
  88. package/schemas/scenario-suite.schema.json +1 -1
  89. package/schemas/scenario-test-input.schema.json +1 -1
  90. package/schemas/script-validate-input.schema.json +1 -1
  91. package/schemas/shared-scenario.schema.json +1 -1
  92. package/schemas/source-lookup-input.schema.json +1 -1
  93. package/server.json +2 -2
@@ -0,0 +1,230 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { z } from 'zod/v4';
6
+ import { callEngineOperation } from '../core/engine-operation.js';
7
+ import { locateEngineBinary } from '../core/engine-client.js';
8
+ import { ServiceError } from '../core/result.js';
9
+ import { PACKAGE_VERSION } from '../version.js';
10
+ /**
11
+ * Map validation on the engine (`map.validate`, ADR 0089 step 6, packet P13a). The engine builds
12
+ * its own map index from the scanned files of the request. A file scanned from disk goes as its
13
+ * metadata and absolute path (the scan has already checked the path against its roots): the
14
+ * engine reads it and refuses it (`MAP_SOURCE_STALE`) when its size or SHA-256 changed since the
15
+ * scan. A file held only in memory (a proposed edit, `virtual://`) goes as bytes in the payload.
16
+ * The answer comes back in the payload (`{format:'json'}`), so a large finding list never meets
17
+ * the header limit. A missing engine, an
18
+ * engine without the op or an answer out of shape is `ENGINE_UNAVAILABLE`; nothing falls back to
19
+ * TypeScript.
20
+ *
21
+ * `validateMapAsync` calls the resident engine. `validateMap` is synchronous, because the map
22
+ * model and its callers are, so it runs one `hoi4-engine serve` over request and answer files: a
23
+ * synchronous call that piped hundreds of megabytes hung on macOS runners (see engine-raster.ts).
24
+ */
25
+ export const MAP_VALIDATE_OP = 'map.validate';
26
+ /** The engine's request payload ceiling for in-memory files; a larger request is refused, never cut. */
27
+ export const MAP_ENGINE_PAYLOAD_LIMIT = 256 * 1024 * 1024;
28
+ const MAP_VALIDATE_TIMEOUT_MS = 600_000;
29
+ const location = z.looseObject({ path: z.string() });
30
+ const answerHeaderSchema = z.object({ format: z.literal('json') }).strict();
31
+ const diagnosticSchema = z
32
+ .object({
33
+ code: z.string(),
34
+ severity: z.enum(['info', 'warning', 'error', 'blocker']),
35
+ category: z.enum([
36
+ 'syntax',
37
+ 'reference',
38
+ 'layout',
39
+ 'design',
40
+ 'rendering',
41
+ 'security',
42
+ 'validation',
43
+ 'map',
44
+ 'configuration',
45
+ ]),
46
+ message: z.string(),
47
+ location: location.optional(),
48
+ related: z.array(location).optional(),
49
+ operationId: z.string().optional(),
50
+ details: z.record(z.string(), z.unknown()).optional(),
51
+ })
52
+ .strict();
53
+ export const mapValidateAnswerSchema = z
54
+ .object({
55
+ passed: z.boolean(),
56
+ diagnostics: z.array(diagnosticSchema),
57
+ checks: z.array(z.object({ id: z.string(), passed: z.boolean(), message: z.string() }).strict()),
58
+ baselineFingerprint: z.string().optional(),
59
+ })
60
+ .strict();
61
+ /** The request body and payload: every scanned file of the index, and the options. */
62
+ export function mapValidateRequest(index, options = {}) {
63
+ const chunks = [];
64
+ const files = index.sourceFiles.map((file) => {
65
+ const common = {
66
+ displayPath: file.displayPath,
67
+ relativePath: file.relativePath,
68
+ rootKind: file.rootKind,
69
+ loadOrder: file.loadOrder,
70
+ size: file.size,
71
+ sha256: file.sha256,
72
+ };
73
+ // A scanned file is read by the engine; one with no real path (a proposed edit) travels.
74
+ if (path.isAbsolute(file.absolutePath))
75
+ return { ...common, path: file.absolutePath };
76
+ chunks.push(file.bytes);
77
+ return { ...common, length: file.bytes.length };
78
+ });
79
+ const baselineBitmap = options.baseline?.provinceBitmap?.bytes;
80
+ if (baselineBitmap !== undefined)
81
+ chunks.push(baselineBitmap);
82
+ const body = {
83
+ files,
84
+ sourceRoots: index.sourceRoots,
85
+ toolVersion: PACKAGE_VERSION,
86
+ options: {
87
+ ...(options.operationId === undefined ? {} : { operationId: options.operationId }),
88
+ ...(options.expectedChangedBounds === undefined
89
+ ? {}
90
+ : { expectedChangedBounds: options.expectedChangedBounds }),
91
+ ...(options.baseline === undefined
92
+ ? {}
93
+ : {
94
+ baseline: {
95
+ stateIds: [...options.baseline.statesById.keys()],
96
+ ...(baselineBitmap === undefined
97
+ ? {}
98
+ : { provinceBitmapLength: baselineBitmap.length }),
99
+ },
100
+ }),
101
+ includeBaselineDiagnostics: options.includeBaselineDiagnostics === true,
102
+ ...(options.diagnosticLimit === undefined
103
+ ? {}
104
+ : { diagnosticLimit: options.diagnosticLimit }),
105
+ ...(options.edgeMode === undefined ? {} : { edgeMode: options.edgeMode }),
106
+ },
107
+ };
108
+ const bytes = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
109
+ if (bytes > MAP_ENGINE_PAYLOAD_LIMIT)
110
+ throw new ServiceError('MAP_ENGINE_PAYLOAD_LIMIT', `The map's scanned files hold ${bytes} bytes, above the ${MAP_ENGINE_PAYLOAD_LIMIT}-byte limit of one engine request; the map is not validated in part`, { bytes, limit: MAP_ENGINE_PAYLOAD_LIMIT, files: files.length });
111
+ return { body, payload: Buffer.concat(chunks) };
112
+ }
113
+ function result(answer) {
114
+ return {
115
+ passed: answer.passed,
116
+ diagnostics: answer.diagnostics,
117
+ checks: answer.checks,
118
+ };
119
+ }
120
+ /** `map.validate` on the resident engine. */
121
+ export async function engineValidateMapAsync(index, options = {}) {
122
+ options.signal?.throwIfAborted();
123
+ const { body, payload } = mapValidateRequest(index, options);
124
+ const answer = await callEngineOperation({
125
+ op: MAP_VALIDATE_OP,
126
+ body,
127
+ payload,
128
+ result: answerHeaderSchema,
129
+ options: {
130
+ timeoutMs: MAP_VALIDATE_TIMEOUT_MS,
131
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
132
+ },
133
+ });
134
+ return result(parseAnswerPayload(answer.payload));
135
+ }
136
+ function parseAnswerPayload(payload) {
137
+ let json;
138
+ try {
139
+ json = JSON.parse(payload.toString('utf8'));
140
+ }
141
+ catch {
142
+ json = undefined;
143
+ }
144
+ const parsed = mapValidateAnswerSchema.safeParse(json);
145
+ if (!parsed.success)
146
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine map.validate answered out of shape', {
147
+ op: MAP_VALIDATE_OP,
148
+ reason: 'invalid_response',
149
+ });
150
+ return parsed.data;
151
+ }
152
+ const frameSchema = z.union([
153
+ z.object({ id: z.number(), ok: z.literal(true), result: z.unknown() }).loose(),
154
+ z
155
+ .object({
156
+ id: z.number(),
157
+ ok: z.literal(false),
158
+ error: z.looseObject({ code: z.string(), message: z.string() }),
159
+ })
160
+ .loose(),
161
+ ]);
162
+ const TOOL_CODE = /^[A-Z][A-Z0-9_]*$/u;
163
+ /** `map.validate` on a one-shot engine, for the synchronous callers. */
164
+ export function engineValidateMapSync(index, options = {}) {
165
+ return result(engineMapOperationSync(MAP_VALIDATE_OP, mapValidateRequest(index, options), answerHeaderSchema, parseAnswerPayload));
166
+ }
167
+ /** One registered engine operation on a one-shot `hoi4-engine serve`, over files. */
168
+ export function engineMapOperationSync(op, request, schema, fromPayload) {
169
+ const located = locateEngineBinary();
170
+ if (!('path' in located))
171
+ throw new ServiceError('ENGINE_UNAVAILABLE', located.message, { reason: located.reason });
172
+ const header = `${JSON.stringify({ ...request.body, id: 1, op, payload: request.payload.length })}\n`;
173
+ const script = /\.(?:c|m)?js$/iu.test(located.path);
174
+ const directory = mkdtempSync(path.join(tmpdir(), 'hoi4-map-validate-'));
175
+ const inputPath = path.join(directory, 'request');
176
+ const outputPath = path.join(directory, 'answer');
177
+ let child;
178
+ let answer;
179
+ try {
180
+ writeFileSync(inputPath, Buffer.concat([Buffer.from(header, 'utf8'), request.payload]));
181
+ const input = openSync(inputPath, 'r');
182
+ const output = openSync(outputPath, 'w');
183
+ try {
184
+ child = spawnSync(script ? process.execPath : located.path, script ? [located.path, 'serve'] : ['serve'], {
185
+ stdio: [input, output, 'pipe'],
186
+ timeout: MAP_VALIDATE_TIMEOUT_MS,
187
+ windowsHide: true,
188
+ shell: false,
189
+ });
190
+ }
191
+ finally {
192
+ closeSync(input);
193
+ closeSync(output);
194
+ }
195
+ answer = existsSync(outputPath) ? readFileSync(outputPath) : Buffer.alloc(0);
196
+ }
197
+ finally {
198
+ rmSync(directory, { recursive: true, force: true });
199
+ }
200
+ const unavailable = (message, reason) => new ServiceError('ENGINE_UNAVAILABLE', message, { op, reason });
201
+ if (child.error !== undefined)
202
+ throw unavailable(`hoi4-engine ${op}: ${child.error.message}`, 'spawn_failed');
203
+ const newline = answer.indexOf(0x0a);
204
+ if (newline < 0)
205
+ throw unavailable(`hoi4-engine ${op} gave no answer (exit ${child.status ?? 'none'}): ${child.stderr.toString('utf8').slice(-300)}`, 'invalid_output');
206
+ let parsedFrame;
207
+ try {
208
+ parsedFrame = JSON.parse(answer.subarray(0, newline).toString('utf8'));
209
+ }
210
+ catch {
211
+ throw unavailable(`hoi4-engine ${op} answered an unreadable frame`, 'invalid_output');
212
+ }
213
+ const frame = frameSchema.safeParse(parsedFrame);
214
+ if (!frame.success)
215
+ throw unavailable(`hoi4-engine ${op} answered an unknown frame`, 'invalid_output');
216
+ if (!frame.data.ok) {
217
+ const { code, message, ...details } = frame.data.error;
218
+ if (TOOL_CODE.test(code))
219
+ throw new ServiceError(code, message, details);
220
+ throw unavailable(message, code);
221
+ }
222
+ const parsed = schema.safeParse(frame.data.result);
223
+ if (!parsed.success)
224
+ throw unavailable(`hoi4-engine ${op} answered out of shape`, 'invalid_response');
225
+ const announced = parsedFrame.payload;
226
+ const length = typeof announced === 'number' && Number.isSafeInteger(announced) ? announced : 0;
227
+ if (length < 0 || answer.length < newline + 1 + length)
228
+ throw unavailable(`hoi4-engine ${op} answered a short payload`, 'invalid_output');
229
+ return fromPayload(answer.subarray(newline + 1, newline + 1 + length));
230
+ }
@@ -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 { MAP_VIEW_FIELDS, mapInspectRequestSchema, mapRewriteRequestSchema, } from '../schemas/map-requests.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers read-only map operations without invoking transport handlers. */
10
10
  export function registerMapJobs(operations, engine) {
11
11
  const nudger = new AgentNudger(engine);
12
- const lifetime = new IdleCacheLifetime(() => engine.releaseScanCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => engine.releaseScanCaches());
13
13
  function register(name, schema, normalize, execute) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -24,12 +24,19 @@ const MAP_TEXT_FIELD_LIMIT = 10_000;
24
24
  const MAP_MODEL_MAX_SCRIPT_FILES = 5_000;
25
25
  const MAP_MODEL_MAX_SOURCE_TOKENS = 1_000_000;
26
26
  const MAP_MODEL_MAX_RECORDS = 500_000;
27
+ /**
28
+ * Building, unit and weather positions have their own ceiling (issue 172): they are fixed-size
29
+ * rows, and a mod with large position tables (Old World Blues, 533,984 records) exceeded the
30
+ * domain-record ceiling with them. The engine model (`hoi4-map`) uses the same ceilings.
31
+ */
32
+ export const MAP_MODEL_MAX_POSITION_RECORDS = 2_000_000;
27
33
  const MAP_MODEL_MAX_LOCALISATION_RECORDS = 2_000_000;
28
34
  const MAP_MODEL_MAX_MEMBERSHIP_EDGES = 1_000_000;
29
35
  class MapModelBudget {
30
36
  #documents = new Set();
31
37
  #tokens = 0;
32
38
  #records = 0;
39
+ #positionRecords = 0;
33
40
  #localisationRecords = 0;
34
41
  #membershipEdges = 0;
35
42
  assertScriptFiles(count) {
@@ -52,6 +59,13 @@ class MapModelBudget {
52
59
  this.block('domain records', this.#records, MAP_MODEL_MAX_RECORDS);
53
60
  }
54
61
  }
62
+ addPositionRecords(count) {
63
+ this.#positionRecords += count;
64
+ if (!Number.isSafeInteger(this.#positionRecords) ||
65
+ this.#positionRecords > MAP_MODEL_MAX_POSITION_RECORDS) {
66
+ this.block('position records', this.#positionRecords, MAP_MODEL_MAX_POSITION_RECORDS);
67
+ }
68
+ }
55
69
  addLocalisationRecords(count) {
56
70
  this.#localisationRecords += count;
57
71
  if (!Number.isSafeInteger(this.#localisationRecords) ||
@@ -1367,17 +1381,17 @@ export class MapWorkspaceIndex {
1367
1381
  const buildingsFile = mapFile(this.activeFiles, 'buildings.txt', this.sourceRoots.map);
1368
1382
  this.buildingPositions =
1369
1383
  buildingsFile === undefined ? [] : parseBuildingPositions(buildingsFile, this.diagnostics);
1370
- modelBudget.addRecords(this.buildingPositions.length);
1384
+ modelBudget.addPositionRecords(this.buildingPositions.length);
1371
1385
  const unitstacksFile = mapFile(this.activeFiles, 'unitstacks.txt', this.sourceRoots.map);
1372
1386
  const positionsFile = mapFile(this.activeFiles, defaultMapSelectorValue(this.defaultMapFile, 'positions', 'positions.txt'), this.sourceRoots.map);
1373
1387
  this.unitPositions = [unitstacksFile, positionsFile]
1374
1388
  .filter((file) => file !== undefined && file.size > 0)
1375
1389
  .flatMap((file) => parseUnitPositions(file, this.diagnostics));
1376
- modelBudget.addRecords(this.unitPositions.length);
1390
+ modelBudget.addPositionRecords(this.unitPositions.length);
1377
1391
  const weatherFile = mapFile(this.activeFiles, 'weatherpositions.txt', this.sourceRoots.map);
1378
1392
  this.weatherPositions =
1379
1393
  weatherFile === undefined ? [] : parseWeatherPositions(weatherFile, this.diagnostics);
1380
- modelBudget.addRecords(this.weatherPositions.length);
1394
+ modelBudget.addPositionRecords(this.weatherPositions.length);
1381
1395
  this.entityLocators = this.activeFiles.all
1382
1396
  .filter((file) => (file.rootKind === 'mod' || file.rootKind === 'fixture') &&
1383
1397
  normalizedPath(file.relativePath).endsWith('.asset') &&
@@ -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
  }
@@ -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();
@@ -334,6 +334,10 @@ export async function createEngine(configPath = configurationPath(), options = {
334
334
  reportStartupFailure(startupError);
335
335
  return engine;
336
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();
337
341
  engine.deferStartup(async () => {
338
342
  try {
339
343
  await resolver.populate();
@@ -343,8 +347,6 @@ export async function createEngine(configPath = configurationPath(), options = {
343
347
  return;
344
348
  }
345
349
  await sweepTemporaryDirectoriesOf(resolver);
346
- // A failed recovery is reported through `engine.recovered()`.
347
- engine.initialize().catch(() => undefined);
348
350
  });
349
351
  return engine;
350
352
  }
@@ -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
+ }