hoi4-agent-tools 4.20.3 → 4.22.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 (140) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +2 -0
  3. package/dist/bin/setup.js +1 -0
  4. package/dist/bin/stdio.js +1 -0
  5. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  6. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  7. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  8. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  9. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  10. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  12. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  13. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  14. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  15. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  16. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  17. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  18. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  19. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  20. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  21. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  23. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  24. package/dist/hoi4_agent_tools/core/operation-tasks.js +4 -2
  25. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  26. package/dist/hoi4_agent_tools/core/workspace.js +25 -2
  27. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  28. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  29. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  30. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  31. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  32. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  33. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  34. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  35. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  36. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  37. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  38. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  39. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  40. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  41. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  43. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  44. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  45. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  46. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  47. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  48. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  49. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  50. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  51. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  52. package/dist/hoi4_agent_tools/map/model.js +17 -3
  53. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  54. package/dist/hoi4_agent_tools/map/references.js +6 -3
  55. package/dist/hoi4_agent_tools/map/service.js +88 -8
  56. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  57. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  58. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  60. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  61. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  62. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  63. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  64. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  65. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  66. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  67. package/dist/hoi4_agent_tools/runtime.js +83 -3
  68. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  70. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  71. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  72. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  73. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  75. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  76. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  77. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  78. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  79. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  80. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  81. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  82. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  83. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  84. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  85. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  86. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  87. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  88. package/dist/hoi4_agent_tools/version.js +1 -1
  89. package/docs/configuration.md +11 -10
  90. package/docs/jobs.md +2 -2
  91. package/docs/setup.md +1 -0
  92. package/docs/tools.md +16 -2
  93. package/docs/troubleshooting.md +11 -11
  94. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  95. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  96. package/engine/bin/linux-x64/hoi4-engine +0 -0
  97. package/engine/bin/manifest.json +8 -8
  98. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  99. package/npm-shrinkwrap.json +43 -19
  100. package/package.json +2 -2
  101. package/schemas/configuration.schema.json +143 -134
  102. package/schemas/continuous-focus-palette.schema.json +1 -1
  103. package/schemas/custom-weighted-pool.schema.json +1 -1
  104. package/schemas/decision-inspect-input.schema.json +1 -1
  105. package/schemas/error-log-input.schema.json +1 -1
  106. package/schemas/event-feature-manifest.schema.json +1 -1
  107. package/schemas/focus-plan.schema.json +1 -1
  108. package/schemas/focus-planning-sidecar.schema.json +1 -1
  109. package/schemas/geography-model.schema.json +1 -1
  110. package/schemas/gui-animation-source.schema.json +1 -1
  111. package/schemas/gui-helper.schema.json +1 -1
  112. package/schemas/gui-scenario.schema.json +1 -1
  113. package/schemas/helper-expansion-request.schema.json +1 -1
  114. package/schemas/helper-expansion-summary.schema.json +1 -1
  115. package/schemas/impact-inspect-input.schema.json +1 -1
  116. package/schemas/map-operation.schema.json +354 -1
  117. package/schemas/mechanic-test-input.schema.json +1 -1
  118. package/schemas/mod-index-input.schema.json +1 -1
  119. package/schemas/operation-result.schema.json +1 -1
  120. package/schemas/package-check-input.schema.json +1 -1
  121. package/schemas/package-manifest.schema.json +1 -1
  122. package/schemas/probability-analysis-result.schema.json +1 -1
  123. package/schemas/probability-compare-input.schema.json +1 -1
  124. package/schemas/probability-evaluate-input.schema.json +1 -1
  125. package/schemas/probability-inspect-input.schema.json +1 -1
  126. package/schemas/probability-render-input.schema.json +1 -1
  127. package/schemas/probability-scenario-set.schema.json +1 -1
  128. package/schemas/probability-sequence-input.schema.json +1 -1
  129. package/schemas/probability-simulate-input.schema.json +1 -1
  130. package/schemas/probability-sweep-input.schema.json +1 -1
  131. package/schemas/reference-context-input.schema.json +1 -1
  132. package/schemas/reference-read-input.schema.json +1 -1
  133. package/schemas/reference-search-input.schema.json +1 -1
  134. package/schemas/reference-sheets.schema.json +1 -1
  135. package/schemas/scenario-suite.schema.json +1 -1
  136. package/schemas/scenario-test-input.schema.json +1 -1
  137. package/schemas/script-validate-input.schema.json +1 -1
  138. package/schemas/shared-scenario.schema.json +1 -1
  139. package/schemas/source-lookup-input.schema.json +1 -1
  140. package/server.json +2 -2
@@ -0,0 +1,129 @@
1
+ import { z } from 'zod/v4';
2
+ import { workspaceRelativePathSchema } from './common.js';
3
+ import { geographyModelSchema, geographyPathSchema } from './geography.js';
4
+ /**
5
+ * `add_landmass` (packet T4): one island with relief in open sea on the existing map. The engine
6
+ * (`map.add_landmass`) plans every file; the map rewrite validates and writes them as one
7
+ * transaction. The island always gets its own strategic region and never changes an existing
8
+ * one (issue 223).
9
+ */
10
+ const pixel = z.number().int().min(0).max(16_383);
11
+ const provinceId = z.number().int().min(1).max(65_535);
12
+ const countryTag = z.string().regex(/^[A-Z][A-Z0-9]{2}$/u);
13
+ const nameText = z.string().min(1).max(80);
14
+ export const addLandmassOperationSchema = z
15
+ .object({
16
+ id: z.string().min(1).max(256),
17
+ summary: z.string().max(1000).optional(),
18
+ kind: z.literal('add_landmass'),
19
+ geography: geographyModelSchema
20
+ .optional()
21
+ .describe('Geography model version 1 on the map frame (0..1 of provinces.bmp): exactly one land, the island, plus its ranges, passes, volcanoes, plateaus, rivers and lakes. Seas, regions, biomes, climate, straits, sites, roads and places are refused (MAP_LANDMASS_UNREPRESENTABLE). With maskImage, declare no land. Give exactly one of geography and geographyPath.'),
22
+ geographyPath: geographyPathSchema
23
+ .optional()
24
+ .describe('Workspace-relative .json geography model; give exactly one of geography and geographyPath.'),
25
+ maskImage: z
26
+ .object({
27
+ path: workspaceRelativePathSchema.describe('Workspace-relative PNG, TGA, DDS or BMP: every pixel that is neither black nor fully transparent is land.'),
28
+ x: pixel.describe('Map pixel of the image left edge.'),
29
+ y: pixel.describe('Map pixel of the image top edge.'),
30
+ })
31
+ .strict()
32
+ .optional()
33
+ .describe('A drawn island outline instead of the geography land polygon.'),
34
+ seed: z.number().int().min(0).max(2_147_483_647).default(1),
35
+ relief: z
36
+ .object({
37
+ scale: z.enum(['vanilla', 'low', 'dramatic']).optional(),
38
+ detail: z.number().min(0).max(1).optional(),
39
+ })
40
+ .strict()
41
+ .optional(),
42
+ rivers: z
43
+ .object({
44
+ density: z.number().min(0).max(0.04).optional(),
45
+ count: z.number().int().min(0).max(500).optional(),
46
+ })
47
+ .strict()
48
+ .optional(),
49
+ provinces: z
50
+ .object({
51
+ landProvincePixels: z
52
+ .number()
53
+ .min(20)
54
+ .max(1_000_000)
55
+ .optional()
56
+ .describe('Target land province size in pixels; default the mean land province of the map.'),
57
+ })
58
+ .strict()
59
+ .optional(),
60
+ continent: z
61
+ .string()
62
+ .min(1)
63
+ .max(128)
64
+ .optional()
65
+ .describe('Continent from continent.txt; default the continent of the nearest land province.'),
66
+ states: z
67
+ .object({
68
+ provincesPerState: z.number().int().min(1).max(500).optional(),
69
+ owner: countryTag.optional().describe('Owner and core holder; the tag must exist.'),
70
+ category: z.string().min(1).max(128).optional(),
71
+ manpower: z.number().min(0).max(1e9).optional(),
72
+ buildings: z.record(z.string().min(1).max(128), z.number().min(0).max(1e6)).optional(),
73
+ capitalVictoryPoints: z.number().min(0).max(1000).optional(),
74
+ names: z
75
+ .array(nameText)
76
+ .max(1000)
77
+ .optional()
78
+ .describe('English state names in state order; default the region name, numbered.'),
79
+ })
80
+ .strict()
81
+ .default({}),
82
+ region: z
83
+ .object({
84
+ name: nameText.optional().describe('English region name; default Island.'),
85
+ weatherFromRegion: z.number().int().min(1).optional(),
86
+ })
87
+ .strict()
88
+ .default({}),
89
+ supply: z
90
+ .object({
91
+ nodes: z.boolean().default(false),
92
+ railways: z.boolean().default(false),
93
+ railwayLevel: z.number().int().min(1).max(5).optional(),
94
+ })
95
+ .strict()
96
+ .optional(),
97
+ crossings: z
98
+ .array(z
99
+ .object({
100
+ fromX: pixel,
101
+ fromY: pixel,
102
+ toProvince: provinceId,
103
+ throughProvince: provinceId,
104
+ rule: z.string().min(1).max(128).optional(),
105
+ })
106
+ .strict())
107
+ .max(100)
108
+ .default([]),
109
+ look: z.enum(['vanilla-temperate', 'fertile', 'arid']).optional(),
110
+ absorbCoveredSeaProvinces: z
111
+ .boolean()
112
+ .optional()
113
+ .describe('Opt-in, off by default. A sea province the island covers whole becomes one of its land provinces, keeping its id and colour, in the island’s new strategic region; its old region file loses that id. Refused when anything uses it as sea (adjacencies, supply nodes, railways, naval building positions, states, fleets or other script references: MAP_LANDMASS_SEA_REFERENCED, each listed), when its old region would be empty (MAP_LANDMASS_REGION_EMPTY) or split (MAP_LANDMASS_REGION_SPLIT). Without it, a covered sea province is refused (MAP_LANDMASS_SEA_SPLIT).'),
114
+ localisation: z
115
+ .object({
116
+ file: z
117
+ .string()
118
+ .min(1)
119
+ .max(1000)
120
+ .optional()
121
+ .describe('English localisation file for the state, victory point and region names (STATE_<id>, VICTORY_POINTS_<province>, STRATEGICREGION_<id>); default localisation/english/map_landmass_<id>_l_english.yml.'),
122
+ })
123
+ .strict()
124
+ .optional(),
125
+ })
126
+ .strict()
127
+ .refine((value) => (value.geography === undefined) !== (value.geographyPath === undefined), {
128
+ message: 'Give exactly one of geography and geographyPath',
129
+ });
@@ -27,7 +27,8 @@ export const localisationEntrySchema = z
27
27
  .max(2000)
28
28
  .refine((value) => !FORBIDDEN_TEXT.test(value), {
29
29
  message: 'text must be one line; write a line break as \\n',
30
- }),
30
+ })
31
+ .describe('The value only, without the key and the surrounding quotes.'),
31
32
  })
32
33
  .strict();
33
34
  export const localisationWriteRequestSchema = z
@@ -70,6 +71,14 @@ export const localisationWriteRequestSchema = z
70
71
  message: `${entry.key} appears twice in entries`,
71
72
  });
72
73
  seen.add(entry.key);
74
+ // A whole line of the file in text would be written inside a second pair of quotes.
75
+ const line = /^\s*([A-Za-z0-9_.-]+):[0-9]*\s*".*"\s*$/u.exec(entry.text);
76
+ if (line?.[1] === entry.key)
77
+ context.addIssue({
78
+ code: 'custom',
79
+ path: ['entries', index, 'text'],
80
+ message: `text is a whole localisation line; pass only what is between the quotes of ${entry.key}`,
81
+ });
73
82
  }
74
83
  }
75
84
  if (value.paths !== undefined)
@@ -199,7 +199,7 @@ export const mapRewriteRequestSchema = z
199
199
  .string()
200
200
  .regex(MAP_BASELINE_FINGERPRINT_PATTERN)
201
201
  .optional()
202
- .describe('Opt-in: baselineFingerprint from a full hoi4.map_inspect of the untouched map. Pre-existing errors outside the write stop blocking; a changed map is refused.'),
202
+ .describe('Use when the map already has many validation errors (a new mod on the vanilla map): baselineFingerprint from a full hoi4.map_inspect of the untouched map. Pre-existing errors outside the write stop blocking; a changed map is refused.'),
203
203
  requestKey: backgroundRequestKeySchema.optional(),
204
204
  })
205
205
  .strict();
@@ -3,6 +3,7 @@ import { renderDimensionViolation, RENDER_MAX_DIMENSION } from '../core/render-b
3
3
  import { MAP_MASK_CELL_LIMIT, MAP_SELECTED_PIXEL_LIMIT, NATURAL_LAND_ID_PATTERN, NATURAL_TERRAIN_CLASSES, } from '../map/limits.js';
4
4
  import { workspaceRelativePathSchema } from './common.js';
5
5
  import { geographyModelSchema, geographyPathSchema } from './geography.js';
6
+ import { addLandmassOperationSchema } from './landmass.js';
6
7
  import { referenceSheetsDocumentSchema, referenceSheetsPathSchema } from './reference-sheets.js';
7
8
  const identifier = z.string().min(1).max(256);
8
9
  // eslint-disable-next-line no-control-regex -- portable JSON Schema pattern rejects grammar-breaking controls.
@@ -1468,6 +1469,7 @@ export const mapOperationSchema = z.discriminatedUnion('kind', [
1468
1469
  position: z.tuple([z.number(), z.number(), z.number()]),
1469
1470
  })
1470
1471
  .strict(),
1472
+ addLandmassOperationSchema,
1471
1473
  ]);
1472
1474
  export const mapAllocationRequestSchema = z.discriminatedUnion('kind', [
1473
1475
  z.object({ kind: z.literal('state'), requestedId: stateId.optional() }).strict(),
@@ -11,7 +11,11 @@ export const techWriteRequestSchema = z
11
11
  /** add only: create the file named by file when the mod has no such common/technologies file. */
12
12
  createFile: z.boolean().optional(),
13
13
  /** The text between the technology braces. Required by add and replace, refused by remove. */
14
- body: z.string().max(32_000).optional(),
14
+ body: z
15
+ .string()
16
+ .max(32_000)
17
+ .optional()
18
+ .describe('Only the text between the technology braces, not the whole tech_id = {...} block.'),
15
19
  /** The common/technologies file. Omit it for replace and remove, and for an add when the mod has one technologynologies file. */
16
20
  file: workspaceRelativePathSchema.max(512).optional(),
17
21
  apply: z
@@ -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
  });
@@ -15,7 +15,7 @@ import { buildGuiSourceGraph } from '../gui/source-graph.js';
15
15
  import { compareTechnologyGraphs } from './compare.js';
16
16
  import { buildTechnologyGraph, buildTechnologyGraphAsync, technologyAssetPatterns, } from './graph.js';
17
17
  import { TECHNOLOGY_GRAPH_SCHEMA_VERSION } from './model.js';
18
- import { analyzeTechnologyImpact, discoverTechnologyFolders, explainTechnology, inspectTechnologyUnlocks, lintTechnologyGraph, technologyBonusCoverage, technologyScanReport, traceTechnology, } from './queries.js';
18
+ import { buildTechnologyGraphOnEngine, queryTechnologyGraph } from './engine-graph.js';
19
19
  import { renderTechnologyGraph, technologyRenderIconSprites, } from './render.js';
20
20
  const FRAGMENT_CACHE_ENTRIES = 8_192;
21
21
  const FRAGMENT_CACHE_BYTES = 134_217_728;
@@ -70,7 +70,7 @@ function sharedState(engine) {
70
70
  }
71
71
  return state;
72
72
  }
73
- function technologyScanPatterns(workspace) {
73
+ export function technologyScanPatterns(workspace) {
74
74
  const roots = workspace.registration.roots;
75
75
  const under = (values, glob) => values.map((root) => `${root.replaceAll('\\', '/').replace(/\/$/u, '')}/${glob}`);
76
76
  return [
@@ -97,7 +97,7 @@ function technologyScanPatterns(workspace) {
97
97
  ...under(roots.localisation, '*.{yml,yaml}'),
98
98
  ].sort(compareCodeUnits);
99
99
  }
100
- async function scanTechnologySources(engine, workspaceId, workspace, principal, signal, renderOnly = false) {
100
+ export async function scanTechnologySources(engine, workspaceId, workspace, principal, signal, renderOnly = false) {
101
101
  const patterns = technologyScanPatterns(workspace).filter((pattern) => !renderOnly ||
102
102
  !/^(?:events|history|common\/(?:national_focus|decisions|scripted_effects|on_actions|ideas|characters))\//u.test(pattern));
103
103
  const snapshot = await engine.scan(workspaceId, { patterns }, principal, signal);
@@ -454,11 +454,9 @@ export class TechnologyTreeViewer {
454
454
  const unchangedSource = cached?.generation === generation && cached.snapshot.revision === snapshot.revision;
455
455
  const preliminary = unchangedSource
456
456
  ? cached.graph
457
- : await buildTechnologyGraphAsync(snapshot, {
457
+ : await buildTechnologyGraphOnEngine(snapshot, {
458
458
  workspaceIdentity: workspace.workspaceIdentity,
459
- cache: this.#state.fragments,
460
459
  ...(analysisMode === undefined ? {} : { analysisMode }),
461
- ...(options.signal === undefined ? {} : { signal: options.signal }),
462
460
  });
463
461
  const guiSprites = [
464
462
  ...preliminary.itemLayouts.flatMap(({ designTeamIcon }) => designTeamIcon === undefined ? [] : [designTeamIcon.sprite]),
@@ -494,12 +492,10 @@ export class TechnologyTreeViewer {
494
492
  })));
495
493
  if (unchangedSource && assetIdentity(assetFiles) === assetIdentity(cached.assetFiles))
496
494
  return cached.graph;
497
- const graph = await buildTechnologyGraphAsync(snapshot, {
495
+ const graph = await buildTechnologyGraphOnEngine(snapshot, {
498
496
  workspaceIdentity: workspace.workspaceIdentity,
499
- cache: this.#state.fragments,
500
497
  assetFiles,
501
498
  ...(analysisMode === undefined ? {} : { analysisMode }),
502
- ...(options.signal === undefined ? {} : { signal: options.signal }),
503
499
  });
504
500
  if (options.renderOnly === true)
505
501
  graph.analysisBoundary.assumptions.push('Folder renders scan technology definitions, layouts, unlock targets and assets; inbound grants and references require technology inspection.');
@@ -531,60 +527,32 @@ export class TechnologyTreeViewer {
531
527
  ...(input.principal === undefined ? {} : { principal: input.principal }),
532
528
  ...(input.signal === undefined ? {} : { signal: input.signal }),
533
529
  });
534
- let report;
535
- switch (input.mode) {
536
- case 'scan':
537
- report = technologyScanReport(graph);
538
- break;
539
- case 'folders':
540
- report = discoverTechnologyFolders(graph, input.folderId);
541
- break;
542
- case 'trace':
543
- if (input.technologyId === undefined)
544
- throw new ServiceError('TECHNOLOGY_REQUIRED', 'Technology trace requires technologyId');
545
- report = traceTechnology(graph, {
546
- technologyId: input.technologyId,
530
+ if (input.mode === 'trace' && input.technologyId === undefined)
531
+ throw new ServiceError('TECHNOLOGY_REQUIRED', 'Technology trace requires technologyId');
532
+ if (input.mode === 'explain' && input.technologyId === undefined)
533
+ throw new ServiceError('TECHNOLOGY_REQUIRED', 'Technology explanation requires technologyId');
534
+ if (input.mode === 'impact' && input.impact === undefined)
535
+ throw new ServiceError('TECH_IMPACT_REQUIRED', 'Technology impact analysis requires a subject');
536
+ const answer = await queryTechnologyGraph(graph, {
537
+ mode: input.mode,
538
+ ...(input.folderId === undefined ? {} : { folderId: input.folderId }),
539
+ ...(input.technologyId === undefined ? {} : { technologyId: input.technologyId }),
540
+ ...(input.categoryId === undefined ? {} : { categoryId: input.categoryId }),
541
+ ...(input.targetKind === undefined ? {} : { targetKind: input.targetKind }),
542
+ ...(input.targetId === undefined ? {} : { targetId: input.targetId }),
543
+ ...(input.mode !== 'trace'
544
+ ? {}
545
+ : {
547
546
  direction: input.direction ?? 'both',
548
547
  maxDepth: input.maxDepth ?? 32,
549
548
  maxNodes: input.maxNodes ?? 2_000,
550
549
  includeSubTechnologies: input.includeSubTechnologies ?? true,
551
- ...(input.signal === undefined ? {} : { signal: input.signal }),
552
- });
553
- break;
554
- case 'explain':
555
- if (input.technologyId === undefined)
556
- throw new ServiceError('TECHNOLOGY_REQUIRED', 'Technology explanation requires technologyId');
557
- report = explainTechnology(graph, input.technologyId, input.signal);
558
- break;
559
- case 'unlocks':
560
- report = inspectTechnologyUnlocks(graph, {
561
- ...(input.technologyId === undefined ? {} : { technologyId: input.technologyId }),
562
- ...(input.targetKind === undefined ? {} : { targetKind: input.targetKind }),
563
- ...(input.targetId === undefined ? {} : { targetId: input.targetId }),
564
- });
565
- break;
566
- case 'bonus_coverage':
567
- report = technologyBonusCoverage(graph, {
568
- ...(input.categoryId === undefined ? {} : { categoryId: input.categoryId }),
569
- ...(input.technologyId === undefined ? {} : { technologyId: input.technologyId }),
570
- });
571
- break;
572
- case 'lint':
573
- report = lintTechnologyGraph(graph, {
574
- ...(input.classifications === undefined
575
- ? {}
576
- : { classifications: input.classifications }),
577
- ...(input.codes === undefined ? {} : { codes: input.codes }),
578
- ...(input.folderId === undefined ? {} : { folderId: input.folderId }),
579
- ...(input.technologyId === undefined ? {} : { technologyId: input.technologyId }),
580
- });
581
- break;
582
- case 'impact':
583
- if (input.impact === undefined)
584
- throw new ServiceError('TECH_IMPACT_REQUIRED', 'Technology impact analysis requires a subject');
585
- report = analyzeTechnologyImpact(graph, input.impact);
586
- break;
587
- }
550
+ }),
551
+ ...(input.classifications === undefined ? {} : { classifications: input.classifications }),
552
+ ...(input.codes === undefined ? {} : { codes: input.codes }),
553
+ ...(input.impact === undefined ? {} : { impact: input.impact }),
554
+ });
555
+ const report = answer.report;
588
556
  const reportJson = `${canonicalJson({
589
557
  schemaVersion: 'technology-analysis.v1',
590
558
  workspaceId: graph.workspaceId,
@@ -624,6 +592,9 @@ export class TechnologyTreeViewer {
624
592
  report,
625
593
  reportJson,
626
594
  artifacts: [artifact, ...(graphArtifact === undefined ? [] : [graphArtifact])],
595
+ ...(answer.summary === undefined || answer.summary === null
596
+ ? {}
597
+ : { explainSummary: answer.summary }),
627
598
  };
628
599
  }
629
600
  async renderAndStore(input) {
@@ -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 { toolResult } from '../core/operation-result.js';
4
4
  import { ServiceError } from '../core/result.js';
5
5
  import { techWriteRequestSchema } from '../schemas/tech-write.js';
@@ -12,7 +12,7 @@ function wire(result) {
12
12
  /** Registers `hoi4.tech_write`: a read-only preview, or one journaled transaction. */
13
13
  export function registerTechWriteJobs(operations, engine) {
14
14
  const viewer = new TechnologyTreeViewer(engine);
15
- const lifetime = new IdleCacheLifetime(() => viewer.clearCaches());
15
+ const lifetime = idleCacheLifetime(engine, () => viewer.clearCaches());
16
16
  operations.registerWrite('hoi4.tech_write', techWriteRequestSchema, async (input, context) => {
17
17
  if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
18
18
  throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
@@ -133,7 +133,7 @@ export async function computeTechWrite(engine, input, context, applied) {
133
133
  let plan;
134
134
  if ('file' in target) {
135
135
  file = target.file;
136
- plan = planTechWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
136
+ plan = await planTechWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
137
137
  }
138
138
  else {
139
139
  const inMod = snapshot.index
@@ -144,7 +144,7 @@ export async function computeTechWrite(engine, input, context, applied) {
144
144
  id: input.id,
145
145
  path: inMod.path,
146
146
  });
147
- plan = planNewTechFile(target.newPath, planInput);
147
+ plan = await planNewTechFile(target.newPath, planInput);
148
148
  }
149
149
  const missing = {
150
150
  localisation: [],