hoi4-agent-tools 4.17.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 (63) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  3. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  4. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  5. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  6. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  7. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  8. package/dist/hoi4_agent_tools/map/operations.js +246 -18
  9. package/dist/hoi4_agent_tools/map/territory-operations.js +66 -0
  10. package/dist/hoi4_agent_tools/map/territory-quality.js +33 -5
  11. package/dist/hoi4_agent_tools/map/tool-operations.js +52 -2
  12. package/dist/hoi4_agent_tools/mcp/tools/map.js +29 -0
  13. package/dist/hoi4_agent_tools/mcp/tools/reference.js +1 -1
  14. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  15. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  16. package/dist/hoi4_agent_tools/schemas/map.js +70 -2
  17. package/dist/hoi4_agent_tools/version.js +1 -1
  18. package/docs/map.md +58 -16
  19. package/docs/tools.md +1 -1
  20. package/engine/bin/manifest.json +1 -1
  21. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  22. package/npm-shrinkwrap.json +2 -2
  23. package/package.json +1 -1
  24. package/schemas/configuration.schema.json +1 -1
  25. package/schemas/continuous-focus-palette.schema.json +1 -1
  26. package/schemas/custom-weighted-pool.schema.json +1 -1
  27. package/schemas/decision-inspect-input.schema.json +1 -1
  28. package/schemas/error-log-input.schema.json +1 -1
  29. package/schemas/event-feature-manifest.schema.json +1 -1
  30. package/schemas/focus-plan.schema.json +1 -1
  31. package/schemas/focus-planning-sidecar.schema.json +1 -1
  32. package/schemas/geography-model.schema.json +1 -1
  33. package/schemas/gui-animation-source.schema.json +1 -1
  34. package/schemas/gui-helper.schema.json +1 -1
  35. package/schemas/gui-scenario.schema.json +1 -1
  36. package/schemas/helper-expansion-request.schema.json +1 -1
  37. package/schemas/helper-expansion-summary.schema.json +1 -1
  38. package/schemas/impact-inspect-input.schema.json +1 -1
  39. package/schemas/map-operation.schema.json +1004 -821
  40. package/schemas/mechanic-test-input.schema.json +1 -1
  41. package/schemas/mod-index-input.schema.json +1 -1
  42. package/schemas/operation-result.schema.json +1 -1
  43. package/schemas/package-check-input.schema.json +1 -1
  44. package/schemas/package-manifest.schema.json +1 -1
  45. package/schemas/probability-analysis-result.schema.json +1 -1
  46. package/schemas/probability-compare-input.schema.json +1 -1
  47. package/schemas/probability-evaluate-input.schema.json +1 -1
  48. package/schemas/probability-inspect-input.schema.json +1 -1
  49. package/schemas/probability-render-input.schema.json +1 -1
  50. package/schemas/probability-scenario-set.schema.json +1 -1
  51. package/schemas/probability-sequence-input.schema.json +1 -1
  52. package/schemas/probability-simulate-input.schema.json +1 -1
  53. package/schemas/probability-sweep-input.schema.json +1 -1
  54. package/schemas/reference-context-input.schema.json +1 -1
  55. package/schemas/reference-read-input.schema.json +1 -1
  56. package/schemas/reference-search-input.schema.json +1 -1
  57. package/schemas/reference-sheets.schema.json +1 -1
  58. package/schemas/scenario-suite.schema.json +1 -1
  59. package/schemas/scenario-test-input.schema.json +1 -1
  60. package/schemas/script-validate-input.schema.json +1 -1
  61. package/schemas/shared-scenario.schema.json +1 -1
  62. package/schemas/source-lookup-input.schema.json +1 -1
  63. 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';
@@ -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',
@@ -4019,6 +4200,53 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4019
4200
  });
4020
4201
  }
4021
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
+ }
4022
4250
  // The tool's own later edits of world outputs must never read as hand edits at the next
4023
4251
  // create_world, in this request or a later one.
4024
4252
  const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base));
@@ -1,6 +1,7 @@
1
1
  import { ServiceError } from '../core/result.js';
2
2
  import { BORDER_PROVINCE_KIND, buildBorderEdgeTableSteps, scoreBorderAssignment, } from './border-quality.js';
3
3
  import { borderQualityInputFromIndex } from './border-quality-input.js';
4
+ import { naturalLandsInputFromIndex, naturalLandsSteps, } from './natural-lands.js';
4
5
  import { cloneState, commitState, currentIndex, uniqueStrings, } from './operations.js';
5
6
  import { clusterProvinces } from './partition-groups.js';
6
7
  import { declaredCountryTags } from './references.js';
@@ -248,12 +249,59 @@ function resolveRef(world, model, ref, label) {
248
249
  }
249
250
  if ('province' in ref)
250
251
  return resolveProvince(world, model, ref.province, label);
252
+ if ('land' in ref) {
253
+ const provinces = landMembers(world, ref.land, label);
254
+ // The province nearest the land's centre, lowest id on a tie.
255
+ const { sumX, sumY, size } = world.graph;
256
+ let totalX = 0;
257
+ let totalY = 0;
258
+ let pixels = 0;
259
+ for (const province of provinces) {
260
+ totalX += sumX[province];
261
+ totalY += sumY[province];
262
+ pixels += size[province];
263
+ }
264
+ const centreX = totalX / Math.max(1, pixels);
265
+ const centreY = totalY / Math.max(1, pixels);
266
+ let best = provinces[0];
267
+ let bestDistance = Infinity;
268
+ for (const province of provinces) {
269
+ const n = Math.max(1, size[province]);
270
+ const distance = (sumX[province] / n - centreX) ** 2 + (sumY[province] / n - centreY) ** 2;
271
+ if (distance < bestDistance) {
272
+ best = province;
273
+ bestDistance = distance;
274
+ }
275
+ }
276
+ return resolveProvince(world, model, best, `${label} in land ${ref.land}`);
277
+ }
251
278
  const raster = world.index.raster;
252
279
  if (ref.x < 0 || ref.y < 0 || ref.x >= raster.width || ref.y >= raster.height)
253
280
  refuse('MAP_TERRITORY_POINT_OUTSIDE_MAP', `${label}: point (${ref.x}, ${ref.y}) is outside the ${raster.width} x ${raster.height} map`, { x: ref.x, y: ref.y });
254
281
  const province = raster.provinceIds[ref.y * raster.width + ref.x];
255
282
  return resolveProvince(world, model, province, `${label} at (${ref.x}, ${ref.y})`);
256
283
  }
284
+ /** The provinces of a natural land the request names. */
285
+ function landMembers(world, land, label) {
286
+ const found = world.lands?.lands.find(({ id }) => id === land);
287
+ if (found === undefined)
288
+ refuse('MAP_NATURAL_LAND_UNKNOWN', `${label}: natural land ${land} does not exist with these landOptions; list the lands with hoi4.map_inspect lands: true and the same options`, { landId: land });
289
+ return found.provinces;
290
+ }
291
+ /** Whether the operation names any natural land, so the lands must be cut. */
292
+ function namesLands(operation) {
293
+ const selections = [
294
+ operation.unowned,
295
+ ...operation.countries.flatMap((country) => [
296
+ country.forced,
297
+ country.blocked,
298
+ country.cores,
299
+ country.claims,
300
+ ]),
301
+ ];
302
+ return (selections.some((selection) => (selection?.landIds?.length ?? 0) > 0) ||
303
+ operation.countries.some((country) => country.seeds.some((seed) => 'land' in seed)));
304
+ }
257
305
  function resolveSelection(world, model, selection, label) {
258
306
  const atoms = new Set();
259
307
  if (selection === undefined)
@@ -279,6 +327,13 @@ function resolveSelection(world, model, selection, label) {
279
327
  for (const province of selection.provinceIds ?? []) {
280
328
  atoms.add(resolveProvince(world, model, province, label));
281
329
  }
330
+ // A land's provinces outside the scope or without a state are left out, as a state's are.
331
+ for (const land of selection.landIds ?? [])
332
+ for (const province of landMembers(world, land, label)) {
333
+ const atom = model.atoms.atomOfProvince[province];
334
+ if (atom >= 0)
335
+ atoms.add(atom);
336
+ }
282
337
  if (selection.regionIds !== undefined) {
283
338
  const wanted = new Set(selection.regionIds);
284
339
  for (const region of wanted)
@@ -433,6 +488,11 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
433
488
  refuse('MAP_TERRITORY_STATE_SIZE_INVALID', 'stateSize.max must not be below stateSize.min');
434
489
  const index = currentIndex(base, changes);
435
490
  const world = yield* buildTerritoryWorld(index, signal);
491
+ if (namesLands(operation))
492
+ world.lands = yield* naturalLandsSteps(naturalLandsInputFromIndex(index).input, {
493
+ ...(operation.landOptions ?? {}),
494
+ ...(signal === undefined ? {} : { signal }),
495
+ });
436
496
  const model = buildAtomModel(world, unit, operation.scope);
437
497
  const atoms = model.atoms;
438
498
  const policy = ownershipPolicy(operation.ownership);
@@ -570,6 +630,9 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
570
630
  mode: operation.borderQuality ?? 'report',
571
631
  layer: 'country',
572
632
  ...(operation.borderTargets === undefined ? {} : { targets: operation.borderTargets }),
633
+ ...(operation.borderQualityScope === undefined
634
+ ? {}
635
+ : { scope: operation.borderQualityScope }),
573
636
  },
574
637
  };
575
638
  const undefinedTags = undefinedTagDiagnostics(index, operation);
@@ -1021,6 +1084,9 @@ export function* applyRepartitionStates(base, changes, allocations, operation, s
1021
1084
  mode: operation.borderQuality ?? 'report',
1022
1085
  layer: 'state',
1023
1086
  ...(operation.borderTargets === undefined ? {} : { targets: operation.borderTargets }),
1087
+ ...(operation.borderQualityScope === undefined
1088
+ ? {}
1089
+ : { scope: operation.borderQualityScope }),
1024
1090
  },
1025
1091
  };
1026
1092
  const diagnostics = [
@@ -1,6 +1,7 @@
1
1
  import { ServiceError } from '../core/result.js';
2
2
  import { borderQualityDiagnostics, borderTargetsForLayer, checkBorderTargets, measureBorderNaturalness, } from './border-quality.js';
3
- import { borderQualityInputFromIndex } from './border-quality-input.js';
3
+ import { borderQualityInputFromIndex, borderQualityScopeIsEmpty, } from './border-quality-input.js';
4
+ import { canonicalJson } from '../core/canonical.js';
4
5
  function targetsFor(layer, overrides) {
5
6
  const targets = { ...borderTargetsForLayer(layer) };
6
7
  if (overrides?.minEnrichment !== undefined)
@@ -14,7 +15,7 @@ function targetsFor(layer, overrides) {
14
15
  function requests(plan) {
15
16
  const result = [];
16
17
  for (const report of plan.territory ?? []) {
17
- const { mode, layer, targets } = report.borderQuality;
18
+ const { mode, layer, targets, scope } = report.borderQuality;
18
19
  if (mode === 'off')
19
20
  continue;
20
21
  result.push({
@@ -24,6 +25,7 @@ function requests(plan) {
24
25
  layers: layer === 'country' ? ['country', 'state'] : ['state'],
25
26
  overrides: targets,
26
27
  enforced: [layer],
28
+ scope: borderQualityScopeIsEmpty(scope) ? undefined : scope,
27
29
  });
28
30
  }
29
31
  const failed = new Set(plan.blockers.map(({ operationId }) => operationId));
@@ -40,6 +42,7 @@ function requests(plan) {
40
42
  layers: ['province', 'state', 'region', 'country'],
41
43
  overrides: operation.data.borderTargets,
42
44
  enforced: ['province', 'state', 'region', 'country'],
45
+ scope: undefined,
43
46
  });
44
47
  }
45
48
  return result;
@@ -53,16 +56,40 @@ function describeFailures(check, layer) {
53
56
  : `natural share ${String(value)} is below ${String(target)}`)
54
57
  .join('; ')}`;
55
58
  }
56
- /** Measure the final index for the operations that asked for border quality. */
59
+ /**
60
+ * Measure the final index for the operations that asked for border quality: once for the whole
61
+ * map and once more for each distinct `borderQualityScope`.
62
+ */
57
63
  export async function evaluateTerritoryQuality(plan, signal) {
58
64
  const asked = requests(plan);
59
65
  if (asked.length === 0)
60
66
  return undefined;
67
+ const groups = new Map();
68
+ for (const request of asked) {
69
+ const key = request.scope === undefined ? '' : canonicalJson(request.scope);
70
+ groups.set(key, [...(groups.get(key) ?? []), request]);
71
+ }
72
+ const results = [];
73
+ for (const key of [...groups.keys()].sort())
74
+ results.push(await evaluateRequests(plan, groups.get(key), signal));
75
+ const whole = results.find((_, index) => [...groups.keys()].sort()[index] === '');
76
+ const report = (whole ?? results[0])?.report;
77
+ return {
78
+ diagnostics: results.flatMap(({ diagnostics }) => diagnostics),
79
+ blockers: results.flatMap(({ blockers }) => blockers),
80
+ operations: results.flatMap(({ operations }) => operations),
81
+ ...(report === undefined ? {} : { report }),
82
+ skippedInputs: results[0]?.skippedInputs ?? [],
83
+ };
84
+ }
85
+ /** Measure the final index once, for requests that share one scope. */
86
+ async function evaluateRequests(plan, asked, signal) {
87
+ const scope = asked[0].scope;
61
88
  const wanted = new Set(asked.flatMap(({ layers }) => layers));
62
89
  let measured;
63
90
  let skipped;
64
91
  try {
65
- const { input, skipped: missing } = borderQualityInputFromIndex(plan.finalIndex);
92
+ const { input, skipped: missing } = borderQualityInputFromIndex(plan.finalIndex, scope);
66
93
  skipped = missing;
67
94
  measured = await measureBorderNaturalness({ ...input, layers: input.layers.filter(({ name }) => wanted.has(name)) }, signal === undefined ? {} : { signal });
68
95
  }
@@ -153,7 +180,7 @@ export async function evaluateTerritoryQuality(plan, signal) {
153
180
  severity: 'info',
154
181
  category: 'map',
155
182
  operationId: request.operationId,
156
- message: `Border naturalness of the proposed map: ${verdicts
183
+ message: `Border naturalness of the proposed map${scope === undefined ? '' : ' inside the scope'}: ${verdicts
157
184
  .map(({ layer, report, check }) => `${layer} enrichment ${report.barrier.enrichment ?? 'n/a'}, natural share ${report.natural.share ?? 'n/a'}${report.straightness.fraction === null ? '' : `, straight ${report.straightness.fraction}`} (${check.passed ? 'meets' : 'misses'} the targets)`)
158
185
  .join('; ')}`,
159
186
  details: {
@@ -168,6 +195,7 @@ export async function evaluateTerritoryQuality(plan, signal) {
168
195
  passed: check.passed,
169
196
  targets,
170
197
  })),
198
+ ...(scope === undefined ? {} : { scope, scopePixels: measured.report.scopePixels ?? null }),
171
199
  },
172
200
  });
173
201
  }
@@ -11,6 +11,7 @@ import { allocateMapIdentifiersAsync, WORLD_OUTPUT_PATH_SAMPLE, } from './operat
11
11
  import { compactTerritoryReport } from './territory-operations.js';
12
12
  import { borderQualityDiagnostics } from './border-quality.js';
13
13
  import { measureIndexBorderNaturalness, summarizeBorderQuality, } from './border-quality-input.js';
14
+ import { naturalLandsFromIndex, summarizeNaturalLands, } from './natural-lands.js';
14
15
  import { buildMapCatalog, lookupMapCoordinate, searchMapCatalog, } from './catalog.js';
15
16
  /** Matches named inline, so a lookup answers without reading its artifact. */
16
17
  const INLINE_MATCH_LIMIT = 20;
@@ -797,14 +798,14 @@ export async function inspectMap(engine, nudger, input, context) {
797
798
  // Check the ids on the cached scan before the full validation.
798
799
  if (input.stateIds.length + input.provinceIds.length + input.regionIds.length > 0)
799
800
  assertKnownMapEntities(await nudger.scan(context.workspaceId, context.principal, context.signal), input);
800
- const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality);
801
+ const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality || input.lands);
801
802
  const sharedRevision = snapshot.revision;
802
803
  let borderQuality;
803
804
  const qualityDiagnostics = [];
804
805
  if (input.quality) {
805
806
  await context.progress(1, 3, 'Measuring how natural the borders are');
806
807
  try {
807
- const measured = await measureIndexBorderNaturalness(snapshot.index, context.signal === undefined ? {} : { signal: context.signal });
808
+ const measured = await measureIndexBorderNaturalness(snapshot.index, context.signal === undefined ? {} : { signal: context.signal }, input.qualityScope);
808
809
  borderQuality = {
809
810
  report: measured.report,
810
811
  summary: summarizeBorderQuality(measured.report, measured.skipped),
@@ -823,6 +824,34 @@ export async function inspectMap(engine, nudger, input, context) {
823
824
  });
824
825
  }
825
826
  }
827
+ let naturalLands;
828
+ if (input.lands) {
829
+ await context.progress(1, 3, 'Cutting the land into natural lands');
830
+ try {
831
+ const computed = await naturalLandsFromIndex(snapshot.index, {
832
+ ...(input.landOptions ?? {}),
833
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
834
+ });
835
+ naturalLands = {
836
+ result: computed.result,
837
+ summary: summarizeNaturalLands(computed.result, computed.skipped),
838
+ };
839
+ }
840
+ catch (error) {
841
+ if (!(error instanceof ServiceError) ||
842
+ !(error.code === 'MAP_NATURAL_LANDS_RASTER_MISSING' ||
843
+ error.code === 'MAP_NATURAL_LANDS_INPUT_INVALID' ||
844
+ error.code === 'MAP_BORDER_QUALITY_RASTER_MISSING'))
845
+ throw error;
846
+ qualityDiagnostics.push({
847
+ code: 'MAP_NATURAL_LANDS_UNAVAILABLE',
848
+ severity: 'warning',
849
+ category: 'map',
850
+ message: `Natural lands could not be computed: ${error.message}`,
851
+ details: { reason: error.code, ...error.details },
852
+ });
853
+ }
854
+ }
826
855
  const catalog = buildMapCatalog(snapshot.index);
827
856
  const queryMatches = input.query === undefined ? [] : searchMapCatalog(catalog, input.query, input.queryLimit);
828
857
  const coordinateMatches = input.coordinates.map((coordinate) => lookupMapCoordinate(snapshot.index, coordinate));
@@ -910,6 +939,26 @@ export async function inspectMap(engine, nudger, input, context) {
910
939
  },
911
940
  description: 'Border naturalness: alignment with rivers, slopes, lake shores and terrain changes, enrichment over chance, straightness and the worst artificial runs for each border layer',
912
941
  });
942
+ if (naturalLands !== undefined)
943
+ artifactWrites.push({
944
+ name: `map-natural-lands.${snapshot.revision.slice(0, 16)}.json`,
945
+ mimeType: 'application/json',
946
+ content: `${canonicalJson({
947
+ revision: snapshot.revision,
948
+ ...naturalLands.result,
949
+ skippedInputs: naturalLands.summary.skippedInputs,
950
+ sourceHashes: sourceEvidence.complete,
951
+ })}
952
+ `,
953
+ provenance: {
954
+ kind: 'map-natural-lands',
955
+ toolVersion: PACKAGE_VERSION,
956
+ schemaVersion: 'map-natural-lands.v1',
957
+ sourceHashes: sourceEvidence.bounded.sourceHashes,
958
+ metadata: { sharedRevision, sourceHashInventory: sourceEvidence.bounded.inventory },
959
+ },
960
+ description: 'Natural lands: every land with its kind, provinces, terrain shares, coast, and the river, crest, terrain and divide lengths of its lines to each neighbouring land',
961
+ });
913
962
  if (overviewRendered) {
914
963
  const overviewLayer = 'state';
915
964
  const overviewOverlays = [
@@ -1005,6 +1054,7 @@ export async function inspectMap(engine, nudger, input, context) {
1005
1054
  missingGeometryProvinceIds: provinceGeometry?.missingGeometryProvinceIds ?? [],
1006
1055
  ...(scriptReferences === undefined ? {} : { scriptReferences }),
1007
1056
  ...(borderQuality === undefined ? {} : { quality: borderQuality.summary }),
1057
+ ...(naturalLands === undefined ? {} : { lands: naturalLands.summary }),
1008
1058
  });
1009
1059
  result.code = 'MAP_INSPECTED';
1010
1060
  setInlineFilesScanned(result, snapshot.files.map(({ displayPath }) => displayPath));
@@ -1,6 +1,7 @@
1
1
  import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
2
2
  import { z } from 'zod/v4';
3
3
  import { mapInspectRequestSchema, mapRewriteRequestSchema } from '../../schemas/map-requests.js';
4
+ import { NATURAL_LAND_KINDS, NATURAL_LANDS_INLINE_LIMIT } from '../../map/natural-lands.js';
4
5
  import { allocationEvidenceSchema, bitmapRenderHashesSchema, nonNegativeIntegerSchema, operationBlockerDataSchema, sha256Schema, } from '../server/output-schemas.js';
5
6
  import { strictOperationResultSchema } from '../server/result.js';
6
7
  const changedBoundsSchema = z
@@ -96,9 +97,36 @@ const borderQualitySummarySchema = z
96
97
  skippedInputs: z
97
98
  .array(z.object({ input: z.string().max(32), reason: z.string().max(256) }).strict())
98
99
  .max(8),
100
+ scopePixels: nonNegativeIntegerSchema
101
+ .optional()
102
+ .describe('Pixels inside qualityScope; absent when the whole map was measured.'),
99
103
  layers: z.array(borderLayerSummarySchema).max(8),
100
104
  })
101
105
  .strict();
106
+ const naturalLandKindSchema = z.enum(NATURAL_LAND_KINDS);
107
+ const naturalLandsSummarySchema = z
108
+ .object({
109
+ count: nonNegativeIntegerSchema,
110
+ landProvinces: nonNegativeIntegerSchema,
111
+ counts: z.record(naturalLandKindSchema, nonNegativeIntegerSchema),
112
+ inputs: z.object({ heights: z.boolean(), rivers: z.boolean() }).strict(),
113
+ skippedInputs: z
114
+ .array(z.object({ input: z.string().max(32), reason: z.string().max(256) }).strict())
115
+ .max(8),
116
+ undersized: nonNegativeIntegerSchema,
117
+ lands: z
118
+ .array(z
119
+ .object({
120
+ id: z.string().max(16),
121
+ kind: naturalLandKindSchema,
122
+ provinces: nonNegativeIntegerSchema,
123
+ coast: z.boolean(),
124
+ })
125
+ .strict())
126
+ .max(NATURAL_LANDS_INLINE_LIMIT),
127
+ truncated: z.boolean(),
128
+ })
129
+ .strict();
102
130
  const mapWorkspaceInspectDataSchema = z
103
131
  .object({
104
132
  revision: sha256Schema,
@@ -150,6 +178,7 @@ const mapWorkspaceInspectDataSchema = z
150
178
  .strict()
151
179
  .optional(),
152
180
  quality: borderQualitySummarySchema.optional(),
181
+ lands: naturalLandsSummarySchema.optional(),
153
182
  })
154
183
  .strict();
155
184
  const mapRenderDataSchema = z
@@ -91,7 +91,7 @@ export const referenceTools = [
91
91
  {
92
92
  name: 'hoi4.mod_index',
93
93
  title: 'Explore mod content and find free IDs',
94
- description: 'Summarize the content in a mod or find a free event ID across the mod, game and dependencies. Use overview for descriptors, folders and definitions, or next_id with a namespace or prefix. Example: {"mode":"next_id","kind":"event","namespace":"my_mod"}. Returns a compact summary; the first call indexes the mod, which takes seconds on a large one.',
94
+ description: 'Summarize the content in a mod or find a free event ID across the mod, game and dependencies. Use overview for descriptors, folders and definitions (the 50 busiest namespaces; pass a namespace or prefix to list those starting with it), or next_id with a namespace or prefix. Example: {"mode":"next_id","kind":"event","namespace":"my_mod"}. Returns a compact summary; the first call indexes the mod, which takes seconds on a large one.',
95
95
  inputSchema: modIndexRequestSchema,
96
96
  outputSchema: strictOperationResultSchema(modIndexDataSchema),
97
97
  annotations: readOnly,