hoi4-agent-tools 4.16.0 → 4.18.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 (109) hide show
  1. package/CHANGELOG.md +41 -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 +54 -3
  7. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  8. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  9. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  10. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  11. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  12. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  13. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  14. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  15. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  16. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  17. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  18. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  19. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  20. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  21. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  22. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  23. package/dist/hoi4_agent_tools/map/model.js +9 -8
  24. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  25. package/dist/hoi4_agent_tools/map/operations.js +266 -23
  26. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  27. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  28. package/dist/hoi4_agent_tools/map/service.js +25 -12
  29. package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
  30. package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
  31. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  32. package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  34. package/dist/hoi4_agent_tools/map/water.js +13 -10
  35. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  36. package/dist/hoi4_agent_tools/map/world.js +51 -1
  37. package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
  38. package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
  39. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  40. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  41. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  42. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  43. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  44. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  45. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  46. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  47. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  48. package/dist/hoi4_agent_tools/runtime.js +27 -11
  49. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  50. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  51. package/dist/hoi4_agent_tools/schemas/map.js +103 -2
  52. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  53. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  54. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  55. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  56. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  57. package/dist/hoi4_agent_tools/version.js +1 -1
  58. package/docs/configuration.md +1 -1
  59. package/docs/map.md +67 -23
  60. package/docs/research/reference-benchmark.md +64 -0
  61. package/docs/tools.md +20 -20
  62. package/docs/troubleshooting.md +4 -0
  63. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  64. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  65. package/engine/bin/linux-x64/hoi4-engine +0 -0
  66. package/engine/bin/manifest.json +8 -8
  67. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +5 -3
  70. package/schemas/configuration.schema.json +1 -1
  71. package/schemas/continuous-focus-palette.schema.json +1 -1
  72. package/schemas/custom-weighted-pool.schema.json +1 -1
  73. package/schemas/decision-inspect-input.schema.json +1 -1
  74. package/schemas/error-log-input.schema.json +1 -1
  75. package/schemas/event-feature-manifest.schema.json +1 -1
  76. package/schemas/focus-plan.schema.json +1 -1
  77. package/schemas/focus-planning-sidecar.schema.json +1 -1
  78. package/schemas/geography-model.schema.json +1 -1
  79. package/schemas/gui-animation-source.schema.json +1 -1
  80. package/schemas/gui-helper.schema.json +1 -1
  81. package/schemas/gui-scenario.schema.json +1 -1
  82. package/schemas/helper-expansion-request.schema.json +1 -1
  83. package/schemas/helper-expansion-summary.schema.json +1 -1
  84. package/schemas/impact-inspect-input.schema.json +1 -1
  85. package/schemas/map-operation.schema.json +1087 -815
  86. package/schemas/mechanic-test-input.schema.json +1 -1
  87. package/schemas/mod-index-input.schema.json +1 -1
  88. package/schemas/operation-result.schema.json +1 -1
  89. package/schemas/package-check-input.schema.json +1 -1
  90. package/schemas/package-manifest.schema.json +1 -1
  91. package/schemas/probability-analysis-result.schema.json +1 -1
  92. package/schemas/probability-compare-input.schema.json +1 -1
  93. package/schemas/probability-evaluate-input.schema.json +1 -1
  94. package/schemas/probability-inspect-input.schema.json +1 -1
  95. package/schemas/probability-render-input.schema.json +1 -1
  96. package/schemas/probability-scenario-set.schema.json +1 -1
  97. package/schemas/probability-sequence-input.schema.json +1 -1
  98. package/schemas/probability-simulate-input.schema.json +1 -1
  99. package/schemas/probability-sweep-input.schema.json +1 -1
  100. package/schemas/reference-context-input.schema.json +1 -1
  101. package/schemas/reference-read-input.schema.json +1 -1
  102. package/schemas/reference-search-input.schema.json +2 -2
  103. package/schemas/reference-sheets.schema.json +1 -1
  104. package/schemas/scenario-suite.schema.json +1 -1
  105. package/schemas/scenario-test-input.schema.json +1 -1
  106. package/schemas/script-validate-input.schema.json +7 -1
  107. package/schemas/shared-scenario.schema.json +1 -1
  108. package/schemas/source-lookup-input.schema.json +1 -1
  109. package/server.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
3
+ import { lookupMapCoordinate } from './catalog.js';
3
4
  import { canonicalJson, compareCodeUnits, deterministicId, sha256Bytes, } from '../core/canonical.js';
4
5
  import { ServiceError } from '../core/result.js';
5
6
  import { applyReplacements, assignments, encodeSource, parseLocalisation, parseClausewitz, } from '../core/source/index.js';
@@ -12,7 +13,7 @@ import { resolveEdge } from './world-edge.js';
12
13
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
13
14
  import { planMapPositions, planSupplyRebuild } from './derived.js';
14
15
  import { buildWorldContext, countryTagCatalog, WORLD_COUNTRY_TAG_FILE, } from './world-context.js';
15
- import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
16
+ import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST, } from './world-outputs.js';
16
17
  import { resolvePartitionMode } from './partition.js';
17
18
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
18
19
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -746,7 +747,7 @@ export function indexWithProposedChanges(base, changes, replacedRoots = []) {
746
747
  if (change.content !== null)
747
748
  files.push(syntheticFile(change.relativePath, Buffer.from(change.content), maximumLoadOrder));
748
749
  }
749
- return MapWorkspaceIndex.build(files, base.sourceRoots, base.sharedIndex.rebuild(files));
750
+ return MapWorkspaceIndex.build(files, base.sourceRoots);
750
751
  }
751
752
  export function addChange(changes, relativePath, content, operationId, mediaType) {
752
753
  const key = normalizeRelative(relativePath);
@@ -3100,18 +3101,41 @@ function remapExternalScriptReferences(index, changes, mapping, entity, operatio
3100
3101
  addChange(changes, file.relativePath, applyReplacements(document, replacements), operationId, 'text/plain');
3101
3102
  }
3102
3103
  }
3103
- function renameLocalisationKeys(index, changes, keys, operationId) {
3104
+ function renameLocalisationKeys(index, changes, keys, operationId,
3105
+ /**
3106
+ * Keys whose entity no longer exists (the state a merge removed): a rename may take them over,
3107
+ * and their entries in the mod's files are removed.
3108
+ */
3109
+ orphaned = new Set()) {
3104
3110
  if (keys.size === 0)
3105
3111
  return;
3106
3112
  for (const [from, to] of keys) {
3107
3113
  const destination = index.localisationEntries.filter(({ entry }) => entry.key === to);
3108
- if (destination.length > 0 && !keys.has(to))
3114
+ if (destination.length > 0 && !keys.has(to) && !orphaned.has(to))
3109
3115
  throw new ServiceError('MAP_LOCALISATION_KEY_COLLISION', `Localisation key ${to} already exists`, { from, to });
3110
3116
  }
3111
3117
  const documents = new Map();
3112
3118
  for (const { file, document, entry } of index.localisationEntries) {
3113
3119
  if (file.rootKind !== 'mod')
3114
3120
  continue;
3121
+ if (orphaned.has(entry.key) && !keys.has(entry.key)) {
3122
+ // The orphaned entry goes, with its line break, so the renamed key is the only one.
3123
+ requireSafeLocalisationDocument(document, file.relativePath);
3124
+ const group = documents.get(file.relativePath) ?? { document, replacements: [] };
3125
+ const breakLength = document.text.startsWith('\r\n', entry.end)
3126
+ ? 2
3127
+ : document.text.startsWith('\n', entry.end)
3128
+ ? 1
3129
+ : 0;
3130
+ group.replacements.push({
3131
+ start: entry.start,
3132
+ end: entry.end + breakLength,
3133
+ text: '',
3134
+ description: 'Remove the localisation of a state that no longer exists',
3135
+ });
3136
+ documents.set(file.relativePath, group);
3137
+ continue;
3138
+ }
3115
3139
  const replacementKey = keys.get(entry.key);
3116
3140
  if (replacementKey === undefined)
3117
3141
  continue;
@@ -3233,22 +3257,7 @@ function applyRenumberMapEntity(base, changes, operation) {
3233
3257
  }
3234
3258
  if (operation.entity === 'state') {
3235
3259
  const mapping = renumberMapping(index.states.map(({ id }) => id), operation);
3236
- const localisationKeys = new Map();
3237
- for (const [fromId, toId] of mapping) {
3238
- const state = required(index.statesById.get(fromId), 'MAP_ENTITY_ID_NOT_FOUND', `State ${fromId} does not exist`);
3239
- const data = cloneState(state);
3240
- data.id = toId;
3241
- const standardName = state.name === `STATE_${fromId}`;
3242
- if (standardName) {
3243
- data.name = `STATE_${toId}`;
3244
- localisationKeys.set(state.name, data.name);
3245
- }
3246
- commitState(changes, state, data, { id: true, ...(standardName ? { name: true } : {}) }, operation.id);
3247
- }
3248
- remapBuildingPositionStateIds(index, changes, mapping, operation.id);
3249
- remapExternalScriptReferences(index, changes, mapping, operation.entity, operation.id);
3250
- if (operation.renameLocalisation ?? true)
3251
- renameLocalisationKeys(currentIndex(base, changes), changes, localisationKeys, operation.id);
3260
+ renumberStates(base, changes, index, mapping, operation.id, operation.renameLocalisation ?? true);
3252
3261
  return;
3253
3262
  }
3254
3263
  const mapping = renumberMapping(index.regions.map(({ id }) => id), operation);
@@ -3269,6 +3278,178 @@ function applyRenumberMapEntity(base, changes, operation) {
3269
3278
  if (operation.renameLocalisation ?? true)
3270
3279
  renameLocalisationKeys(currentIndex(base, changes), changes, localisationKeys, operation.id);
3271
3280
  }
3281
+ /**
3282
+ * Give states new ids by `mapping` in one pass: their files, building positions, script references
3283
+ * and `STATE_<id>` localisation keys. renumber_map_entity and the closing of state-id holes use it.
3284
+ */
3285
+ function renumberStates(base, changes, index, mapping, operationId, renameLocalisation,
3286
+ /** The target ids belong to states that no longer exist; their `STATE_<id>` keys are taken over. */
3287
+ intoHoles = false) {
3288
+ const localisationKeys = new Map();
3289
+ for (const [fromId, toId] of mapping) {
3290
+ const state = required(index.statesById.get(fromId), 'MAP_ENTITY_ID_NOT_FOUND', `State ${fromId} does not exist`);
3291
+ const data = cloneState(state);
3292
+ data.id = toId;
3293
+ const standardName = state.name === `STATE_${fromId}`;
3294
+ if (standardName) {
3295
+ data.name = `STATE_${toId}`;
3296
+ localisationKeys.set(state.name, data.name);
3297
+ }
3298
+ commitState(changes, state, data, { id: true, ...(standardName ? { name: true } : {}) }, operationId);
3299
+ }
3300
+ remapBuildingPositionStateIds(index, changes, mapping, operationId);
3301
+ remapExternalScriptReferences(index, changes, mapping, 'state', operationId);
3302
+ if (renameLocalisation)
3303
+ renameLocalisationKeys(currentIndex(base, changes), changes, localisationKeys, operationId, intoHoles ? new Set([...mapping.values()].map((id) => `STATE_${id}`)) : new Set());
3304
+ }
3305
+ /**
3306
+ * Building positions (`map/buildings.txt`) whose state a request removed (a merge source, a state
3307
+ * assign_territory dissolved) still named the deleted id: ZIN's K128 write left five floating
3308
+ * harbours so. Each such line moves to the state that now holds its province: the last field (the
3309
+ * adjacent sea province, or the harbour's land province), else the province under its map
3310
+ * coordinates. A line neither places is reported.
3311
+ */
3312
+ function reassignOrphanBuildingPositions(base, changes, operationId) {
3313
+ const before = new Set(base.states.map(({ id }) => id));
3314
+ const index = currentIndex(base, changes);
3315
+ const removed = (id) => before.has(id) && !index.statesById.has(id);
3316
+ const orphans = index.buildingPositions.filter(({ stateId }) => removed(stateId));
3317
+ if (orphans.length === 0)
3318
+ return [];
3319
+ const stateOf = (record) => {
3320
+ const byField = index.statesByProvince.get(record.adjacentSeaProvince)?.[0]?.id;
3321
+ if (byField !== undefined)
3322
+ return byField;
3323
+ if (index.raster === undefined)
3324
+ return undefined;
3325
+ const lookup = lookupMapCoordinate(index, { kind: 'map', x: record.x, z: record.z });
3326
+ return lookup.stateIds[0];
3327
+ };
3328
+ const unplaced = [];
3329
+ const moved = [];
3330
+ const documents = new Map(orphans.map((record) => [record.document.file.relativePath, record.document]));
3331
+ for (const [relativePath, document] of documents) {
3332
+ const replacements = [];
3333
+ for (const record of orphans.filter((candidate) => candidate.document === document)) {
3334
+ const target = stateOf(record);
3335
+ const line = document.lines[record.line - 1];
3336
+ if (target === undefined || line === undefined) {
3337
+ unplaced.push({ line: record.line, building: record.building, stateId: record.stateId });
3338
+ continue;
3339
+ }
3340
+ moved.push({
3341
+ line: record.line,
3342
+ building: record.building,
3343
+ from: record.stateId,
3344
+ to: target,
3345
+ });
3346
+ replacements.push({
3347
+ start: line.start,
3348
+ end: line.end,
3349
+ text: replaceDelimitedFields(line.text, new Map([[0, numberText(target)]])),
3350
+ description: 'Move a building position off a removed state',
3351
+ });
3352
+ }
3353
+ if (replacements.length > 0)
3354
+ addChange(changes, relativePath, applyTextRanges(document, replacements), operationId, 'text/plain');
3355
+ }
3356
+ const diagnostics = [];
3357
+ if (moved.length > 0)
3358
+ diagnostics.push({
3359
+ code: 'MAP_BUILDING_POSITIONS_REASSIGNED',
3360
+ severity: 'info',
3361
+ category: 'map',
3362
+ operationId,
3363
+ message: `${moved.length} building position(s) named a state this write removed; each now names the state that holds its province`,
3364
+ details: { moves: moved.slice(0, 200), moveCount: moved.length },
3365
+ });
3366
+ if (unplaced.length > 0)
3367
+ diagnostics.push({
3368
+ code: 'MAP_BUILDING_POSITION_STATE_MISSING',
3369
+ severity: 'warning',
3370
+ category: 'map',
3371
+ operationId,
3372
+ message: `${unplaced.length} building position(s) name a state this write removed, and no state holds their province; remove or move them`,
3373
+ details: { lines: unplaced.slice(0, 200), lineCount: unplaced.length },
3374
+ });
3375
+ return diagnostics;
3376
+ }
3377
+ /** The ids missing from 1 up to the highest id. */
3378
+ function idHoles(ids) {
3379
+ const present = new Set(ids);
3380
+ const highest = Math.max(0, ...present);
3381
+ const holes = [];
3382
+ for (let id = 1; id < highest; id += 1)
3383
+ if (!present.has(id))
3384
+ holes.push(id);
3385
+ return holes;
3386
+ }
3387
+ /**
3388
+ * The game needs every state id from 1 to the highest; a missing one crashes it at setup ("Missing
3389
+ * State ID"). When a request's operations leave holes the mod did not have before (a merge source,
3390
+ * a state assign_territory dissolved), the highest states move into them, with their references,
3391
+ * in the same write. Holes the mod already had are reported, not moved, since closing them renumbers
3392
+ * states the request did not touch.
3393
+ */
3394
+ function closeStateIdHoles(base, changes, operationId,
3395
+ /** State ids the request asked for by name; those states stay where they were asked to go. */
3396
+ requested) {
3397
+ const before = base.states.map(({ id }) => id);
3398
+ const index = currentIndex(base, changes);
3399
+ const after = index.states.map(({ id }) => id);
3400
+ const sameStates = before.length === after.length && new Set([...before, ...after]).size === before.length;
3401
+ if (sameStates)
3402
+ return { diagnostics: [], mapping: new Map() };
3403
+ const existing = new Set(idHoles(before));
3404
+ const holes = idHoles(after);
3405
+ const created = holes.filter((id) => !existing.has(id));
3406
+ const diagnostics = [];
3407
+ const mapping = new Map();
3408
+ const movable = after.filter((id) => !requested.has(id)).sort((a, b) => b - a);
3409
+ for (const hole of created) {
3410
+ const highest = movable[0];
3411
+ if (highest === undefined || highest < hole)
3412
+ break;
3413
+ movable.shift();
3414
+ mapping.set(highest, hole);
3415
+ }
3416
+ if (mapping.size > 0) {
3417
+ try {
3418
+ renumberStates(base, changes, index, mapping, operationId, true, true);
3419
+ }
3420
+ catch (error) {
3421
+ const cause = error instanceof ServiceError ? error : undefined;
3422
+ throw new ServiceError('MAP_STATE_ID_GAP', `The write would leave state ids ${created.join(', ')} without a state, which crashes the game, and moving the highest states into them failed: ${cause?.message ?? (error instanceof Error ? error.message : String(error))}`, { holes: created, ...(cause === undefined ? {} : { cause: cause.code }) });
3423
+ }
3424
+ diagnostics.push({
3425
+ code: 'MAP_STATE_IDS_COMPACTED',
3426
+ severity: 'info',
3427
+ category: 'map',
3428
+ operationId,
3429
+ message: `The write left ${mapping.size} state id(s) without a state; the highest states moved into them, with their references and localisation, so every id from 1 to the highest exists`,
3430
+ details: {
3431
+ moves: [...mapping].map(([from, to]) => ({ from, to })).slice(0, 500),
3432
+ moveCount: mapping.size,
3433
+ },
3434
+ });
3435
+ }
3436
+ const remaining = idHoles(currentIndex(base, changes).states.map(({ id }) => id));
3437
+ // A hole this request makes and cannot close (beside a state id it names) crashes the game at
3438
+ // history setup (SIGSEGV on Linux, 14 November 2026), so the write is refused.
3439
+ const unclosed = remaining.filter((id) => !existing.has(id));
3440
+ if (unclosed.length > 0)
3441
+ throw new ServiceError('MAP_STATE_ID_GAP', `The write would leave state ids ${unclosed.slice(0, 50).join(', ')}${unclosed.length > 50 ? ', ...' : ''} without a state, which crashes the game; name the next free id instead, or renumber the states into the gap in the same request`, { holes: unclosed.slice(0, 500), holeCount: unclosed.length });
3442
+ if (remaining.length > 0)
3443
+ diagnostics.push({
3444
+ code: 'MAP_STATE_ID_GAP',
3445
+ severity: 'warning',
3446
+ category: 'map',
3447
+ operationId,
3448
+ message: `State ids ${remaining.slice(0, 50).join(', ')}${remaining.length > 50 ? ', ...' : ''} have no state; the game needs every id from 1 to the highest. Close each with renumber_map_entity (entity state, the highest id into the hole)`,
3449
+ details: { holes: remaining.slice(0, 500), holeCount: remaining.length },
3450
+ });
3451
+ return { diagnostics, mapping };
3452
+ }
3272
3453
  /** Folders a new world replaces in the base game. */
3273
3454
  export const WORLD_REPLACED_ROOTS = [
3274
3455
  'history/states',
@@ -3750,6 +3931,14 @@ function applyRegenerateMapPositions(base, changes, operation) {
3750
3931
  for (const file of planMapPositions(index, operation))
3751
3932
  addChange(changes, file.relativePath, file.content, operation.id, 'text/plain');
3752
3933
  }
3934
+ /** The map, state and localisation roots a world of this workspace records its outputs under. */
3935
+ function worldOutputRoots(base) {
3936
+ return {
3937
+ mapRoot: base.sourceRoots.map[0] ?? 'map',
3938
+ stateRoots: base.sourceRoots.states,
3939
+ localisationRoots: base.sourceRoots.localisation,
3940
+ };
3941
+ }
3753
3942
  function worldOutputsRefreshedDiagnostic(refresh) {
3754
3943
  return {
3755
3944
  code: 'MAP_WORLD_OUTPUTS_REFRESHED',
@@ -3757,12 +3946,15 @@ function worldOutputsRefreshedDiagnostic(refresh) {
3757
3946
  category: 'map',
3758
3947
  message: `The world output inventory records the new bytes of ${refresh.refreshed.length} output(s) this request wrote` +
3759
3948
  (refresh.dropped.length > 0 ? ` and drops ${refresh.dropped.length} it deleted` : '') +
3949
+ (refresh.added.length > 0 ? `, and adds ${refresh.added.length} it created` : '') +
3760
3950
  (refresh.keptEdited.length > 0
3761
3951
  ? `; ${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)`
3762
3952
  : ''),
3763
3953
  details: {
3764
3954
  refreshed: refresh.refreshed.length,
3765
3955
  dropped: refresh.dropped.length,
3956
+ added: refresh.added.length,
3957
+ addedPaths: refresh.added.slice(0, 200),
3766
3958
  keptEdited: refresh.keptEdited.slice(0, 200),
3767
3959
  keptEditedCount: refresh.keptEdited.length,
3768
3960
  },
@@ -3773,7 +3965,7 @@ function worldOutputsRefreshedDiagnostic(refresh) {
3773
3965
  * the next create_world takes them as the world's own. Recorded files that are gone are dropped.
3774
3966
  */
3775
3967
  function applyRecordWorldOutputs(base, changes, operation) {
3776
- const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), true);
3968
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base), { adoptAll: true, adoptUnrecorded: operation.adoptUnrecorded !== false });
3777
3969
  if (refresh === undefined)
3778
3970
  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`);
3779
3971
  if (refresh.content !== undefined)
@@ -3783,13 +3975,17 @@ function applyRecordWorldOutputs(base, changes, operation) {
3783
3975
  severity: 'info',
3784
3976
  category: 'map',
3785
3977
  operationId: operation.id,
3786
- 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`,
3978
+ 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` : ''}`,
3787
3979
  details: {
3788
3980
  refreshed: refresh.refreshed.length,
3789
3981
  unchanged: refresh.unchanged.length,
3790
3982
  dropped: refresh.dropped.length,
3983
+ added: refresh.added.length,
3984
+ unscanned: refresh.unscanned.length,
3985
+ unscannedPaths: refresh.unscanned.slice(0, 200),
3791
3986
  refreshedPaths: refresh.refreshed.slice(0, 200),
3792
3987
  droppedPaths: refresh.dropped.slice(0, 200),
3988
+ addedPaths: refresh.added.slice(0, 200),
3793
3989
  },
3794
3990
  };
3795
3991
  }
@@ -4004,9 +4200,56 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4004
4200
  });
4005
4201
  }
4006
4202
  }
4203
+ // A write never leaves a state id without a state (issue 182): close the holes this request made.
4204
+ const lastOperation = operations.at(-1);
4205
+ if (blockers.length === 0 && lastOperation !== undefined) {
4206
+ try {
4207
+ const requested = new Set();
4208
+ for (const operation of operations) {
4209
+ if ('stateId' in operation && typeof operation.stateId === 'number')
4210
+ requested.add(operation.stateId);
4211
+ if (operation.kind === 'renumber_map_entity' && operation.entity === 'state')
4212
+ requested.add(operation.toId);
4213
+ }
4214
+ diagnostics.push(...reassignOrphanBuildingPositions(base, changes, lastOperation.id));
4215
+ const closed = closeStateIdHoles(base, changes, lastOperation.id, requested);
4216
+ diagnostics.push(...closed.diagnostics);
4217
+ // Reports name the ids the states have after the write.
4218
+ const moved = (id) => closed.mapping.get(id) ?? id;
4219
+ for (const report of territory) {
4220
+ report.states.created = report.states.created.map(moved);
4221
+ report.states.changed = report.states.changed.map(moved);
4222
+ }
4223
+ for (const allocation of allocations)
4224
+ if (allocation.kind === 'state-id' && typeof allocation.allocated === 'number')
4225
+ allocation.allocated = moved(allocation.allocated);
4226
+ }
4227
+ catch (error) {
4228
+ if (signal?.aborted)
4229
+ throw error;
4230
+ const serviceError = error instanceof ServiceError
4231
+ ? error
4232
+ : new ServiceError('MAP_STATE_ID_GAP', error instanceof Error ? error.message : String(error));
4233
+ blockers.push({
4234
+ code: serviceError.code,
4235
+ message: serviceError.message,
4236
+ operationId: lastOperation.id,
4237
+ ...(Object.keys(serviceError.details).length === 0
4238
+ ? {}
4239
+ : { details: serviceError.details }),
4240
+ });
4241
+ diagnostics.push({
4242
+ code: serviceError.code,
4243
+ severity: 'blocker',
4244
+ category: 'map',
4245
+ message: serviceError.message,
4246
+ operationId: lastOperation.id,
4247
+ });
4248
+ }
4249
+ }
4007
4250
  // The tool's own later edits of world outputs must never read as hand edits at the next
4008
4251
  // create_world, in this request or a later one.
4009
- const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes));
4252
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base));
4010
4253
  if (refresh?.content !== undefined) {
4011
4254
  const [first, ...rest] = refresh.operationIds;
4012
4255
  addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, first, 'application/json');
@@ -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)