hoi4-agent-tools 4.15.0 → 4.17.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 (101) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +153 -26
  7. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  8. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  9. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  10. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  11. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  12. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  13. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  14. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  15. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  16. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  17. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  18. package/dist/hoi4_agent_tools/map/model.js +9 -8
  19. package/dist/hoi4_agent_tools/map/operations.js +74 -2
  20. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  21. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  22. package/dist/hoi4_agent_tools/map/service.js +25 -12
  23. package/dist/hoi4_agent_tools/map/territory-operations.js +114 -3
  24. package/dist/hoi4_agent_tools/map/territory-quality.js +39 -0
  25. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  26. package/dist/hoi4_agent_tools/map/tool-operations.js +27 -1
  27. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  28. package/dist/hoi4_agent_tools/map/water.js +13 -10
  29. package/dist/hoi4_agent_tools/map/world-outputs.js +53 -25
  30. package/dist/hoi4_agent_tools/map/world.js +51 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/map.js +23 -0
  32. package/dist/hoi4_agent_tools/mcp/tools/reference.js +2 -2
  33. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  34. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  35. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  36. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  37. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  38. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  39. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  40. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  41. package/dist/hoi4_agent_tools/runtime.js +27 -11
  42. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  43. package/dist/hoi4_agent_tools/schemas/map.js +41 -0
  44. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  45. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  46. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  47. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  48. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/configuration.md +1 -1
  51. package/docs/map.md +14 -10
  52. package/docs/research/reference-benchmark.md +64 -0
  53. package/docs/tools.md +20 -20
  54. package/docs/troubleshooting.md +4 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +8 -8
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +5 -3
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +838 -728
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +2 -2
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +7 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
@@ -0,0 +1,160 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, 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 { compareCodeUnits } from '../core/canonical.js';
7
+ import { locateEngineBinary } from '../core/engine-client.js';
8
+ import { ServiceError } from '../core/result.js';
9
+ import { rgbKey } from './bmp.js';
10
+ /**
11
+ * The province raster from the shared Rust engine (`hoi4-engine map-provinces`, ADR 0084): the
12
+ * province of every pixel, each province's extent, the neighbour graph, seam-only pairs, colours
13
+ * without a definition, coastal provinces and the geometry checks' parts, holes and thin runs.
14
+ * The engine reproduces `buildProvinceRaster` and the TypeScript geometry checks exactly,
15
+ * iteration order included; `scripts/map-raster-parity.ts` compares them on real maps.
16
+ *
17
+ * The call is synchronous because the map model is built in one synchronous pass. It sends the
18
+ * decoded bitmap's bytes and pixel offsets and reads one frame back. A missing engine is
19
+ * `ENGINE_UNAVAILABLE`; nothing falls back to TypeScript.
20
+ */
21
+ export const MAP_PROVINCES_REQUEST_SCHEMA = 'hoi4-map-provinces-request/1';
22
+ const MAP_PROVINCES_TIMEOUT_MS = 120_000;
23
+ const RESPONSE_JSON_MAX_BYTES = 256 * 1024 * 1024;
24
+ const count = z.number().int().min(0);
25
+ const id = z.number().int();
26
+ const responseSchema = z
27
+ .object({
28
+ schema: z.literal('hoi4-map-provinces/1'),
29
+ width: count,
30
+ height: count,
31
+ geometry: z.array(z.tuple([id, count, count, count, count, count, count, count])),
32
+ adjacency: z.array(z.tuple([id, z.array(id)])),
33
+ seamOnlyPairs: z.array(z.tuple([id, id])),
34
+ unknownColors: z.array(z.tuple([count, count, count, count])),
35
+ unknownColorCount: count,
36
+ coastal: z.array(id),
37
+ components: z.array(z.tuple([id, count])),
38
+ holes: z.array(z.tuple([id, z.number().int()])),
39
+ thin: z.array(id),
40
+ })
41
+ .strict();
42
+ const frameSchema = z.union([
43
+ z.object({ ok: z.literal(true), result: z.unknown(), payload: count }).strict(),
44
+ z
45
+ .object({
46
+ ok: z.literal(false),
47
+ error: z.looseObject({ code: z.string(), message: z.string() }),
48
+ })
49
+ .strict(),
50
+ ]);
51
+ function packed(key) {
52
+ const [r, g, b] = key.split(',').map(Number);
53
+ return ((r ?? 0) << 16) | ((g ?? 0) << 8) | (b ?? 0);
54
+ }
55
+ export function engineProvinceRaster(bitmap, definitionsByColor, definitionsById) {
56
+ const located = locateEngineBinary();
57
+ if (!('path' in located))
58
+ throw new ServiceError('ENGINE_UNAVAILABLE', located.message, { reason: located.reason });
59
+ const header = `${JSON.stringify({
60
+ schema: MAP_PROVINCES_REQUEST_SCHEMA,
61
+ width: bitmap.width,
62
+ height: bitmap.height,
63
+ topDown: bitmap.topDown,
64
+ bitsPerPixel: bitmap.bitsPerPixel,
65
+ pixelOffset: bitmap.pixelOffset,
66
+ rowStride: bitmap.rowStride,
67
+ palette: bitmap.palette.map(({ r, g, b }) => [r, g, b]),
68
+ colors: [...definitionsByColor].map(([key, definition]) => [packed(key), definition.id]),
69
+ types: [...definitionsById].map(([provinceId, definition]) => [provinceId, definition.type]),
70
+ payload: bitmap.bytes.length,
71
+ })}\n`;
72
+ const script = /\.(?:c|m)?js$/iu.test(located.path);
73
+ // The frames go through files, not the child's pipes: a synchronous call that wrote hundreds of
74
+ // kilobytes to stdin and read as much from stdout hung until its timeout on macOS runners.
75
+ const directory = mkdtempSync(path.join(tmpdir(), 'hoi4-map-provinces-'));
76
+ const inputPath = path.join(directory, 'request');
77
+ const outputPath = path.join(directory, 'answer');
78
+ let child;
79
+ let stdout;
80
+ try {
81
+ writeFileSync(inputPath, Buffer.concat([Buffer.from(header, 'utf8'), bitmap.bytes]));
82
+ const args = ['map-provinces', '--input', inputPath, '--output', outputPath];
83
+ child = spawnSync(script ? process.execPath : located.path, script ? [located.path, ...args] : args, {
84
+ stdio: ['ignore', 'ignore', 'pipe'],
85
+ maxBuffer: RESPONSE_JSON_MAX_BYTES,
86
+ timeout: MAP_PROVINCES_TIMEOUT_MS,
87
+ windowsHide: true,
88
+ shell: false,
89
+ });
90
+ stdout = existsSync(outputPath) ? readFileSync(outputPath) : Buffer.alloc(0);
91
+ }
92
+ finally {
93
+ rmSync(directory, { recursive: true, force: true });
94
+ }
95
+ const unavailable = (message) => new ServiceError('ENGINE_UNAVAILABLE', message, { reason: 'invalid_output' });
96
+ if (child.error !== undefined)
97
+ throw new ServiceError('ENGINE_UNAVAILABLE', `hoi4-engine map-provinces: ${child.error.message}`, {
98
+ reason: 'spawn_failed',
99
+ });
100
+ const newline = stdout.indexOf(0x0a);
101
+ if (newline < 0)
102
+ throw unavailable(`hoi4-engine map-provinces gave no answer (exit ${child.status ?? 'none'}): ${child.stderr.toString('utf8').slice(-300)}`);
103
+ const frame = frameSchema.safeParse(JSON.parse(stdout.subarray(0, newline).toString('utf8')));
104
+ if (!frame.success)
105
+ throw unavailable('hoi4-engine map-provinces answered an unknown frame');
106
+ if (!frame.data.ok) {
107
+ const { code, message, ...details } = frame.data.error;
108
+ // The engine names a bad palette index the way BmpImage.rgbAt does.
109
+ if (code === 'MAP_BMP_PALETTE_INDEX_INVALID')
110
+ throw new ServiceError(code, message, details);
111
+ throw new ServiceError('MAP_ENGINE_REQUEST_INVALID', message, { code });
112
+ }
113
+ const response = responseSchema.safeParse(frame.data.result);
114
+ const payload = stdout.subarray(newline + 1);
115
+ if (!response.success ||
116
+ response.data.width !== bitmap.width ||
117
+ response.data.height !== bitmap.height ||
118
+ payload.length !== frame.data.payload ||
119
+ payload.length !== bitmap.width * bitmap.height * 4)
120
+ throw unavailable('hoi4-engine map-provinces answered out of shape');
121
+ const result = response.data;
122
+ // Copied so the ids are aligned, whatever offset the payload has in the output buffer.
123
+ const provinceIds = new Int32Array(payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.length));
124
+ const geometry = new Map();
125
+ for (const [provinceId, pixelCount, minX, minY, maxX, maxY, sumX, sumY] of result.geometry)
126
+ geometry.set(provinceId, {
127
+ id: provinceId,
128
+ pixelCount,
129
+ minX,
130
+ minY,
131
+ maxX,
132
+ maxY,
133
+ centerX: sumX / pixelCount,
134
+ centerY: sumY / pixelCount,
135
+ });
136
+ const color = (rgb) => ({ r: (rgb >> 16) & 0xff, g: (rgb >> 8) & 0xff, b: rgb & 0xff });
137
+ return {
138
+ width: result.width,
139
+ height: result.height,
140
+ provinceIds,
141
+ adjacency: new Map(result.adjacency.map(([provinceId, others]) => [provinceId, new Set(others)])),
142
+ seamOnlyPairs: new Set(result.seamOnlyPairs.map(([low, high]) => `${low}:${high}`)),
143
+ geometry,
144
+ unknownColors: result.unknownColors
145
+ .map(([rgb, pixels, firstX, firstY]) => ({
146
+ color: color(rgb),
147
+ count: pixels,
148
+ firstX,
149
+ firstY,
150
+ }))
151
+ .sort((left, right) => compareCodeUnits(rgbKey(left.color), rgbKey(right.color))),
152
+ unknownColorCount: result.unknownColorCount,
153
+ coastalProvinceIds: new Set(result.coastal),
154
+ topology: {
155
+ components: new Map(result.components),
156
+ holes: new Map(result.holes),
157
+ thin: new Set(result.thin),
158
+ },
159
+ };
160
+ }
@@ -1,11 +1,11 @@
1
1
  import { compareCodeUnits } from '../core/canonical.js';
2
2
  import path from 'node:path';
3
- import { SymbolIndex } from '../core/index.js';
4
3
  import { assertRenderDimensions } from '../core/render-budget.js';
5
4
  import { addMapDiagnostic, addMapDiagnostics } from './diagnostic-limit.js';
6
5
  import { ServiceError } from '../core/result.js';
7
6
  import { assignments, assertSourceEncodingPreserved, childBlocks, decodeSource, encodeSource, firstScalar, nodeLocation, parseClausewitz, parseLocalisation, } from '../core/source/index.js';
8
7
  import { BmpImage, rgbKey } from './bmp.js';
8
+ import { engineProvinceRaster } from './engine-raster.js';
9
9
  const defaultMapIndexSourceRoots = {
10
10
  map: ['map'],
11
11
  states: ['history/states'],
@@ -966,6 +966,10 @@ function addNeighbor(adjacency, left, right) {
966
966
  adjacency.set(left, leftSet);
967
967
  adjacency.set(right, rightSet);
968
968
  }
969
+ /**
970
+ * The TypeScript raster, kept as the reference the engine's (`engineProvinceRaster`, ADR 0084)
971
+ * is checked against in tests and `scripts/map-raster-parity.ts`. The map model uses the engine.
972
+ */
969
973
  export function buildProvinceRaster(bitmap, definitionsByColor, definitionsById) {
970
974
  assertRenderDimensions(bitmap.width, bitmap.height, 'map province raster', {
971
975
  maximumPixels: MAP_PROVINCE_ENGINE_MAX_PIXELS,
@@ -1098,8 +1102,6 @@ export class MapWorkspaceIndex {
1098
1102
  /** Every scanned root file, including entries shadowed by a higher-load-order root. */
1099
1103
  sourceFiles;
1100
1104
  sourceRoots;
1101
- /** Shared cross-domain symbol/reference authority for these exact source bytes. */
1102
- sharedIndex;
1103
1105
  activeFiles;
1104
1106
  earliestBookmark;
1105
1107
  diagnostics = [];
@@ -1182,9 +1184,8 @@ export class MapWorkspaceIndex {
1182
1184
  const color = this.#heightmap.palette[index];
1183
1185
  return (color === undefined ? index : color.r) / 10;
1184
1186
  }
1185
- constructor(files, sourceRoots = defaultMapIndexSourceRoots, sharedIndex = SymbolIndex.build(files)) {
1187
+ constructor(files, sourceRoots = defaultMapIndexSourceRoots) {
1186
1188
  this.sourceFiles = [...files];
1187
- this.sharedIndex = sharedIndex;
1188
1189
  this.sourceRoots = {
1189
1190
  map: sourceRoots.map.map(normalizeConfiguredRoot),
1190
1191
  states: sourceRoots.states.map(normalizeConfiguredRoot),
@@ -1243,7 +1244,7 @@ export class MapWorkspaceIndex {
1243
1244
  }
1244
1245
  }
1245
1246
  if (this.provinceBitmap !== undefined) {
1246
- this.raster = buildProvinceRaster(this.provinceBitmap, this.definitionsByColor, this.definitionsById);
1247
+ this.raster = engineProvinceRaster(this.provinceBitmap, this.definitionsByColor, this.definitionsById);
1247
1248
  }
1248
1249
  const stateFiles = this.activeFiles.all.filter((file) => inConfiguredRoot(file.relativePath, this.sourceRoots.states));
1249
1250
  const activeStatePaths = new Set(stateFiles.map(({ displayPath }) => displayPath));
@@ -1440,8 +1441,8 @@ export class MapWorkspaceIndex {
1440
1441
  });
1441
1442
  }
1442
1443
  }
1443
- static build(files, sourceRoots = defaultMapIndexSourceRoots, sharedIndex = SymbolIndex.build(files)) {
1444
- return new MapWorkspaceIndex(files, sourceRoots, sharedIndex);
1444
+ static build(files, sourceRoots = defaultMapIndexSourceRoots) {
1445
+ return new MapWorkspaceIndex(files, sourceRoots);
1445
1446
  }
1446
1447
  provinceAtMapCoordinate(x, z) {
1447
1448
  if (this.raster === undefined)
@@ -12,7 +12,7 @@ import { resolveEdge } from './world-edge.js';
12
12
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
13
13
  import { planMapPositions, planSupplyRebuild } from './derived.js';
14
14
  import { buildWorldContext, countryTagCatalog, WORLD_COUNTRY_TAG_FILE, } from './world-context.js';
15
- import { planWorldOutputs } from './world-outputs.js';
15
+ import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST, } from './world-outputs.js';
16
16
  import { resolvePartitionMode } from './partition.js';
17
17
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
18
18
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -746,7 +746,7 @@ export function indexWithProposedChanges(base, changes, replacedRoots = []) {
746
746
  if (change.content !== null)
747
747
  files.push(syntheticFile(change.relativePath, Buffer.from(change.content), maximumLoadOrder));
748
748
  }
749
- return MapWorkspaceIndex.build(files, base.sourceRoots, base.sharedIndex.rebuild(files));
749
+ return MapWorkspaceIndex.build(files, base.sourceRoots);
750
750
  }
751
751
  export function addChange(changes, relativePath, content, operationId, mediaType) {
752
752
  const key = normalizeRelative(relativePath);
@@ -3750,6 +3750,64 @@ function applyRegenerateMapPositions(base, changes, operation) {
3750
3750
  for (const file of planMapPositions(index, operation))
3751
3751
  addChange(changes, file.relativePath, file.content, operation.id, 'text/plain');
3752
3752
  }
3753
+ /** The map, state and localisation roots a world of this workspace records its outputs under. */
3754
+ function worldOutputRoots(base) {
3755
+ return {
3756
+ mapRoot: base.sourceRoots.map[0] ?? 'map',
3757
+ stateRoots: base.sourceRoots.states,
3758
+ localisationRoots: base.sourceRoots.localisation,
3759
+ };
3760
+ }
3761
+ function worldOutputsRefreshedDiagnostic(refresh) {
3762
+ return {
3763
+ code: 'MAP_WORLD_OUTPUTS_REFRESHED',
3764
+ severity: refresh.keptEdited.length > 0 ? 'warning' : 'info',
3765
+ category: 'map',
3766
+ message: `The world output inventory records the new bytes of ${refresh.refreshed.length} output(s) this request wrote` +
3767
+ (refresh.dropped.length > 0 ? ` and drops ${refresh.dropped.length} it deleted` : '') +
3768
+ (refresh.added.length > 0 ? `, and adds ${refresh.added.length} it created` : '') +
3769
+ (refresh.keptEdited.length > 0
3770
+ ? `; ${refresh.keptEdited.length} output(s) were edited before this request and keep their recorded hash, so the next create_world still refuses them (record_world_outputs adopts them)`
3771
+ : ''),
3772
+ details: {
3773
+ refreshed: refresh.refreshed.length,
3774
+ dropped: refresh.dropped.length,
3775
+ added: refresh.added.length,
3776
+ addedPaths: refresh.added.slice(0, 200),
3777
+ keptEdited: refresh.keptEdited.slice(0, 200),
3778
+ keptEditedCount: refresh.keptEdited.length,
3779
+ },
3780
+ };
3781
+ }
3782
+ /**
3783
+ * `record_world_outputs`: adopt the current bytes of every output the world inventory records, so
3784
+ * the next create_world takes them as the world's own. Recorded files that are gone are dropped.
3785
+ */
3786
+ function applyRecordWorldOutputs(base, changes, operation) {
3787
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base), { adoptAll: true, adoptUnrecorded: operation.adoptUnrecorded !== false });
3788
+ if (refresh === undefined)
3789
+ throw new ServiceError('MAP_WORLD_OUTPUTS_MISSING', `The workspace has no world output inventory (${WORLD_OUTPUT_MANIFEST}) to record; only a mod written by create_world has one`);
3790
+ if (refresh.content !== undefined)
3791
+ addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, operation.id, 'application/json');
3792
+ return {
3793
+ code: 'MAP_WORLD_OUTPUTS_RECORDED',
3794
+ severity: 'info',
3795
+ category: 'map',
3796
+ operationId: operation.id,
3797
+ message: `The world output inventory now records the current bytes of its outputs: ${refresh.refreshed.length} refreshed, ${refresh.unchanged.length} unchanged, ${refresh.dropped.length} dropped because the file is gone${refresh.unscanned.length > 0 ? `, ${refresh.unscanned.length} kept unread` : ''}${operation.adoptUnrecorded !== false ? `, ${refresh.added.length} added that it lacked` : ''}`,
3798
+ details: {
3799
+ refreshed: refresh.refreshed.length,
3800
+ unchanged: refresh.unchanged.length,
3801
+ dropped: refresh.dropped.length,
3802
+ added: refresh.added.length,
3803
+ unscanned: refresh.unscanned.length,
3804
+ unscannedPaths: refresh.unscanned.slice(0, 200),
3805
+ refreshedPaths: refresh.refreshed.slice(0, 200),
3806
+ droppedPaths: refresh.dropped.slice(0, 200),
3807
+ addedPaths: refresh.added.slice(0, 200),
3808
+ },
3809
+ };
3810
+ }
3753
3811
  function applyRebuildSupply(base, changes, operation) {
3754
3812
  const index = currentIndex(base, changes);
3755
3813
  for (const file of planSupplyRebuild(index, operation))
@@ -3922,6 +3980,8 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
3922
3980
  applyRegenerateMapPositions(base, changes, operation);
3923
3981
  else if (operation.kind === 'rebuild_supply')
3924
3982
  applyRebuildSupply(base, changes, operation);
3983
+ else if (operation.kind === 'record_world_outputs')
3984
+ diagnostics.push(applyRecordWorldOutputs(base, changes, operation));
3925
3985
  else
3926
3986
  handleSimpleOperation(base, changes, operation);
3927
3987
  diagnostics.push(...(diagnosticsByPlan.get(changes) ?? []));
@@ -3959,6 +4019,18 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
3959
4019
  });
3960
4020
  }
3961
4021
  }
4022
+ // The tool's own later edits of world outputs must never read as hand edits at the next
4023
+ // create_world, in this request or a later one.
4024
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base));
4025
+ if (refresh?.content !== undefined) {
4026
+ const [first, ...rest] = refresh.operationIds;
4027
+ addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, first, 'application/json');
4028
+ for (const id of rest)
4029
+ changes.get(normalizeRelative(WORLD_OUTPUT_MANIFEST)).operationIds.add(id);
4030
+ diagnostics.push(worldOutputsRefreshedDiagnostic(refresh));
4031
+ }
4032
+ else if (refresh !== undefined && refresh.keptEdited.length > 0)
4033
+ diagnostics.push(worldOutputsRefreshedDiagnostic(refresh));
3962
4034
  const finalized = proposedChanges(changes);
3963
4035
  yield* cancellationCheckpoint(signal);
3964
4036
  const finalIndex = indexWithProposedChanges(base, finalized, replacedRootsByPlan.get(changes) ?? []);
@@ -1,7 +1,7 @@
1
1
  import { ServiceError } from '../core/result.js';
2
2
  import { assembleWorldProvinces, assertProvinceMaskFeasible } from './world-provinces.js';
3
3
  import { assertPartitionFields, PARTITION_KIND, PARTITION_TERRAIN, WALL_SIDE, } from './partition-fields.js';
4
- import { PARTITION_PROVINCE_ERROR } from './partition-tuning.js';
4
+ import { areaRowFactor, PARTITION_PROVINCE_ERROR } from './partition-tuning.js';
5
5
  import { hash32, placeSeeds, STEP_UNIT, unit32, weightedWatershed } from './partition-watershed.js';
6
6
  /**
7
7
  * Feature-aware provinces (ADR 0058). The land is cut by a marker-controlled watershed whose
@@ -343,7 +343,11 @@ function planAreas(fields, tuning, coastDistance, seaDistance) {
343
343
  : area > t.maxProvincePixels
344
344
  ? t.maxProvincePixels
345
345
  : area;
346
- const land = (pixel) => clampArea(landRaw(pixel) * landScale);
346
+ // areaByRow applies after the scale to the base area, so rows with factor 1 keep their sizes.
347
+ const rowFactor = new Float64Array(height);
348
+ for (let y = 0; y < height; y += 1)
349
+ rowFactor[y] = areaRowFactor(t.areaByRow, y, height);
350
+ const land = (pixel) => clampArea(landRaw(pixel) * landScale * rowFactor[Math.floor(pixel / width)]);
347
351
  const sea = (pixel) => kind[pixel] === LAKE ? t.lakeArea : clampArea(seaRaw(pixel) * seaScale);
348
352
  let minLand = Infinity;
349
353
  let minSea = Infinity;
@@ -12,6 +12,27 @@ export const PARTITION_DEFAULTS = {
12
12
  minProvincePixels: 40,
13
13
  narrowStraitPx: 24,
14
14
  };
15
+ /** The smallest and largest `areaByRow` factor. */
16
+ export const AREA_BY_ROW_FACTOR = [0.25, 8];
17
+ /**
18
+ * The `areaByRow` factor of a pixel row: linear between the points, held beyond the ends, 1
19
+ * without points.
20
+ */
21
+ export function areaRowFactor(points, y, height) {
22
+ if (points === undefined || points.length === 0)
23
+ return 1;
24
+ const row = (y + 0.5) / height;
25
+ if (row <= points[0][0])
26
+ return points[0][1];
27
+ for (let index = 1; index < points.length; index += 1) {
28
+ const [r1, f1] = points[index];
29
+ if (row <= r1) {
30
+ const [r0, f0] = points[index - 1];
31
+ return f0 + ((f1 - f0) * (row - r0)) / (r1 - r0);
32
+ }
33
+ }
34
+ return points[points.length - 1][1];
35
+ }
15
36
  /** The province count above which the wiki and the text-table limit advise against a map. */
16
37
  export const PARTITION_PROVINCE_WARNING = 14_000;
17
38
  export const PARTITION_PROVINCE_ERROR = 21_000;
@@ -78,6 +99,19 @@ export function resolvePartitionTuning(tuning, base) {
78
99
  refuse('MAP_PARTITION_STRENGTH_INVALID', 'partition barrierStrength must be from 0 to 60', {
79
100
  barrierStrength: strength,
80
101
  });
102
+ const areaByRow = tuning?.areaByRow;
103
+ if (areaByRow !== undefined) {
104
+ const valid = areaByRow.length > 0 &&
105
+ areaByRow.every(([row, factor], index) => Number.isFinite(row) &&
106
+ row >= 0 &&
107
+ row <= 1 &&
108
+ Number.isFinite(factor) &&
109
+ factor >= AREA_BY_ROW_FACTOR[0] &&
110
+ factor <= AREA_BY_ROW_FACTOR[1] &&
111
+ (index === 0 || row > areaByRow[index - 1][0]));
112
+ if (!valid)
113
+ refuse('MAP_PARTITION_AREA_BY_ROW_INVALID', `partition areaByRow must be [row, factor] points with rows from 0 to 1 in increasing order and factors from ${AREA_BY_ROW_FACTOR[0]} to ${AREA_BY_ROW_FACTOR[1]}`, { areaByRow });
114
+ }
81
115
  const strait = tuning?.narrowStraitPx ?? PARTITION_DEFAULTS.narrowStraitPx;
82
116
  if (!Number.isInteger(strait) || strait < 4 || strait > 64)
83
117
  refuse('MAP_PARTITION_STRENGTH_INVALID', 'partition narrowStraitPx must be from 4 to 64', {
@@ -94,6 +128,9 @@ export function resolvePartitionTuning(tuning, base) {
94
128
  minProvincePixels,
95
129
  narrowStraitPx: strait,
96
130
  maxProvincePixels: cellLimit,
131
+ ...(areaByRow === undefined
132
+ ? {}
133
+ : { areaByRow: areaByRow.map(([row, factor]) => [row, factor]) }),
97
134
  normalizeLand: bands === undefined || Object.keys(bands).length === 0,
98
135
  normalizeSea: sea === undefined || Object.keys(sea).length === 0,
99
136
  landBase: land,
@@ -6,7 +6,6 @@ import { canonicalJson, compareCodeUnits, hashCanonical, sha256Bytes } from '../
6
6
  import { sortDiagnostics } from '../core/diagnostics.js';
7
7
  import { diagnosticSeverityCounts, rollupRepeatedSoftDiagnostics, } from '../core/diagnostic-rollup.js';
8
8
  import { CoreEngine } from '../core/engine.js';
9
- import { SymbolIndex } from '../core/index.js';
10
9
  import { RenderBudget } from '../core/render-budget.js';
11
10
  import { ServiceError } from '../core/result.js';
12
11
  import { WorkspaceScanner } from '../core/scanner.js';
@@ -23,7 +22,7 @@ import { WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
23
22
  import { renderMap, renderMapDiff, } from './render.js';
24
23
  import { validateMapAsync } from './validation.js';
25
24
  import { buildWorldPreviewArtifacts, generatedWorldOperationIds } from './world-preview.js';
26
- import { evaluateTerritoryQuality, territoryArtifactContent, } from './territory-quality.js';
25
+ import { evaluateTerritoryQuality, territoryAssignmentContent, territoryArtifactContent, } from './territory-quality.js';
27
26
  /**
28
27
  * Evidence of an imported reference: registered sheets, an exact or frame-fitted picture, or a
29
28
  * geography model beside the picture. Plain pictures keep their previous output.
@@ -635,19 +634,19 @@ export class AgentNudger {
635
634
  states: workspace.registration.roots.states,
636
635
  localisation: workspace.registration.roots.localisation,
637
636
  };
638
- const selectorSnapshot = await this.engine.scan(workspaceId, { patterns: defaultMapPatterns(sourceRoots) }, principal, signal);
637
+ const selectorSnapshot = await this.engine.scanFiles(workspaceId, { patterns: defaultMapPatterns(sourceRoots) }, principal, signal);
639
638
  const bitmapPatterns = provinceBitmapPatterns(selectorSnapshot.files, sourceRoots.map, includeAppearance || includeBorderInputs
640
639
  ? BORDER_BITMAP_SELECTORS
641
640
  : PROVINCE_BITMAP_SELECTORS);
642
- const contentSnapshot = await this.engine.scan(workspaceId, { patterns: [...sourceTextPatterns(sourceRoots), ...bitmapPatterns] }, principal, signal);
643
- const locatorSnapshot = await this.engine.scan(workspaceId, { patterns: ['**/*.asset'], rootKinds: ['mod', 'fixture'] }, principal, signal);
641
+ const contentSnapshot = await this.engine.scanFiles(workspaceId, { patterns: [...sourceTextPatterns(sourceRoots), ...bitmapPatterns] }, principal, signal);
642
+ const locatorSnapshot = await this.engine.scanFiles(workspaceId, { patterns: ['**/*.asset'], rootKinds: ['mod', 'fixture'] }, principal, signal);
644
643
  const externalScriptSnapshot = includeExternalScriptReferences
645
- ? await this.engine.scan(workspaceId, {
644
+ ? await this.engine.scanFiles(workspaceId, {
646
645
  patterns: [...MAP_REFERENCE_SCRIPT_PATTERNS],
647
646
  }, principal, signal)
648
647
  : undefined;
649
648
  const worldContextSnapshot = includeWorldContext
650
- ? await this.engine.scan(workspaceId, {
649
+ ? await this.engine.scanFiles(workspaceId, {
651
650
  patterns: [
652
651
  'common/state_category/**/*.txt',
653
652
  'common/country_tags/*.txt',
@@ -656,7 +655,7 @@ export class AgentNudger {
656
655
  }, principal, signal)
657
656
  : undefined;
658
657
  const generatedOutputsSnapshot = includeWorldContext
659
- ? await this.engine.scan(workspaceId, {
658
+ ? await this.engine.scanFiles(workspaceId, {
660
659
  rootKinds: ['mod'],
661
660
  patterns: [
662
661
  'common/countries/*.txt',
@@ -673,7 +672,7 @@ export class AgentNudger {
673
672
  : undefined;
674
673
  // Appearance validation reads the bitmaps and colour maps the mod itself ships.
675
674
  const appearanceSnapshot = includeAppearance
676
- ? await this.engine.scan(workspaceId, {
675
+ ? await this.engine.scanFiles(workspaceId, {
677
676
  rootKinds: ['mod', 'fixture'],
678
677
  patterns: [
679
678
  ...provinceBitmapPatterns(selectorSnapshot.files, sourceRoots.map, APPEARANCE_BITMAP_SELECTORS),
@@ -690,7 +689,7 @@ export class AgentNudger {
690
689
  : undefined;
691
690
  // Scripts that may name a continent, read when a new world drops the inherited continents.
692
691
  const continentSnapshot = includeContinentReferences
693
- ? await this.engine.scan(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
692
+ ? await this.engine.scanFiles(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
694
693
  : undefined;
695
694
  signal?.throwIfAborted();
696
695
  const collected = [
@@ -711,7 +710,7 @@ export class AgentNudger {
711
710
  workspaceId,
712
711
  revision,
713
712
  files,
714
- index: MapWorkspaceIndex.build(files, sourceRoots, SymbolIndex.build(files)),
713
+ index: MapWorkspaceIndex.build(files, sourceRoots),
715
714
  };
716
715
  }
717
716
  async validate(workspaceId, principal, signal, scripts = false, includeAppearance = false) {
@@ -744,7 +743,9 @@ export class AgentNudger {
744
743
  signal?.throwIfAborted();
745
744
  const snapshot = await this.scan(workspaceId, principal, signal, operations.some((operation) => operation.kind === 'renumber_map_entity' ||
746
745
  operation.kind === 'remap_map_references' ||
747
- 'remapReferences' in operation), operations.some((operation) => operation.kind === 'create_world'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'));
746
+ 'remapReferences' in operation),
747
+ // record_world_outputs needs every world output scanned, as create_world does.
748
+ operations.some((operation) => operation.kind === 'create_world' || operation.kind === 'record_world_outputs'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'));
748
749
  const referenceWorlds = new Map();
749
750
  const referenceImages = [];
750
751
  const referenceLoads = new Map();
@@ -1369,6 +1370,18 @@ export class AgentNudger {
1369
1370
  schemaVersion: 'map-territory.v1',
1370
1371
  },
1371
1372
  });
1373
+ if (prepared.territory.reports.length > 0)
1374
+ writes.push({
1375
+ name: 'map-territory-assignment.json',
1376
+ mimeType: 'application/json',
1377
+ content: `${canonicalJson(territoryAssignmentContent(prepared.territory.reports, plan.finalIndex))}
1378
+ `,
1379
+ provenance: {
1380
+ ...provenance,
1381
+ kind: 'map-territory-assignment',
1382
+ schemaVersion: 'map-territory-assignment.v1',
1383
+ },
1384
+ });
1372
1385
  for (const [ordinal, imported] of prepared.imports.entries())
1373
1386
  writes.push(...(await buildImportArtifacts(imported, ordinal)));
1374
1387
  if (plan.worldOutputs !== undefined)