hoi4-agent-tools 4.6.4 → 4.7.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 (89) hide show
  1. package/CHANGELOG.md +22 -5
  2. package/dist/hoi4_agent_tools/core/artifacts.js +9 -2
  3. package/dist/hoi4_agent_tools/core/changed-summary.js +41 -0
  4. package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
  5. package/dist/hoi4_agent_tools/core/job-worker-host.js +5 -1
  6. package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
  7. package/dist/hoi4_agent_tools/focus/compact.js +197 -18
  8. package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
  9. package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
  10. package/dist/hoi4_agent_tools/focus/layout.js +3 -2
  11. package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
  12. package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
  13. package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
  14. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
  15. package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
  16. package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
  17. package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
  18. package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
  19. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +202 -0
  20. package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
  21. package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -0
  22. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
  23. package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
  24. package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
  25. package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
  26. package/dist/hoi4_agent_tools/focus/tool-operations.js +206 -22
  27. package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
  28. package/dist/hoi4_agent_tools/map/references.js +26 -1
  29. package/dist/hoi4_agent_tools/map/render.js +29 -3
  30. package/dist/hoi4_agent_tools/map/service.js +3 -0
  31. package/dist/hoi4_agent_tools/map/tool-operations.js +5 -0
  32. package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
  33. package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
  34. package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
  35. package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
  36. package/dist/hoi4_agent_tools/reference/service.js +92 -21
  37. package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
  38. package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
  39. package/dist/hoi4_agent_tools/version.js +1 -1
  40. package/docs/configuration.md +17 -17
  41. package/docs/focus.md +100 -4
  42. package/docs/map.md +5 -2
  43. package/docs/reference.md +1 -1
  44. package/docs/research/reference-benchmark.md +111 -1
  45. package/docs/setup.md +1 -1
  46. package/docs/tools.md +5 -5
  47. package/docs/troubleshooting.md +12 -11
  48. package/npm-shrinkwrap.json +2 -2
  49. package/package.json +2 -1
  50. package/schemas/configuration.schema.json +1 -1
  51. package/schemas/continuous-focus-palette.schema.json +1 -1
  52. package/schemas/custom-weighted-pool.schema.json +1 -1
  53. package/schemas/decision-inspect-input.schema.json +1 -1
  54. package/schemas/error-log-input.schema.json +1 -1
  55. package/schemas/event-feature-manifest.schema.json +1 -1
  56. package/schemas/focus-plan.schema.json +146 -120
  57. package/schemas/focus-planning-sidecar.schema.json +15 -7
  58. package/schemas/geography-model.schema.json +1 -1
  59. package/schemas/gui-animation-source.schema.json +1 -1
  60. package/schemas/gui-helper.schema.json +1 -1
  61. package/schemas/gui-scenario.schema.json +1 -1
  62. package/schemas/helper-expansion-request.schema.json +1 -1
  63. package/schemas/helper-expansion-summary.schema.json +1 -1
  64. package/schemas/impact-inspect-input.schema.json +1 -1
  65. package/schemas/map-operation.schema.json +1 -1
  66. package/schemas/mechanic-test-input.schema.json +1 -1
  67. package/schemas/mod-index-input.schema.json +1 -1
  68. package/schemas/operation-result.schema.json +1 -1
  69. package/schemas/package-check-input.schema.json +1 -1
  70. package/schemas/package-manifest.schema.json +1 -1
  71. package/schemas/probability-analysis-result.schema.json +1 -1
  72. package/schemas/probability-compare-input.schema.json +1 -1
  73. package/schemas/probability-evaluate-input.schema.json +1 -1
  74. package/schemas/probability-inspect-input.schema.json +1 -1
  75. package/schemas/probability-render-input.schema.json +1 -1
  76. package/schemas/probability-scenario-set.schema.json +1 -1
  77. package/schemas/probability-sequence-input.schema.json +1 -1
  78. package/schemas/probability-simulate-input.schema.json +1 -1
  79. package/schemas/probability-sweep-input.schema.json +1 -1
  80. package/schemas/reference-context-input.schema.json +1 -1
  81. package/schemas/reference-read-input.schema.json +1 -1
  82. package/schemas/reference-search-input.schema.json +1 -1
  83. package/schemas/reference-sheets.schema.json +1 -1
  84. package/schemas/scenario-suite.schema.json +1 -1
  85. package/schemas/scenario-test-input.schema.json +1 -1
  86. package/schemas/script-validate-input.schema.json +1 -1
  87. package/schemas/shared-scenario.schema.json +1 -1
  88. package/schemas/source-lookup-input.schema.json +1 -1
  89. package/server.json +2 -2
@@ -9,9 +9,11 @@ import { autonomousResultArtifacts, } from '../core/transaction-execution.js';
9
9
  import { readDependenciesFromScannedFiles, } from '../core/transactions.js';
10
10
  import { setInlineFilesScanned } from '../core/operation-result.js';
11
11
  import { PACKAGE_VERSION } from '../version.js';
12
- import { focusPlanHash, focusPresentationEvidence, importContinuousFocusPalettes, assertCompactLayoutQuality, compactFocusTreePlanAsync, linkContinuousFocusPalettes, resolveFocusPresentation, } from './index.js';
12
+ import { focusPlanHash, focusPresentationEvidence, importFocusTrees, importContinuousFocusPalettes, assertCompactLayoutQuality, compactFocusTreePlanAsync, linkContinuousFocusPalettes, resolveFocusPresentation, } from './index.js';
13
13
  import { activeContinuousFocusFiles, activeFocusFiles, activeSidecar, continuousPalettes, importFocusFile, referenceCatalog, selectContinuousPlan, selectedContinuousFocusFile, selectedFocusFile, selectPlan, underConfiguredRoot, validationFromDiagnostics, } from './tool-support.js';
14
14
  import { inspectFocusScenario } from './scenario.js';
15
+ import { assertFocusEngineLayoutWritten, layoutFocusTreeWithEngine, } from './engine-layout.js';
16
+ import { describeLayoutDelta, evaluateFocusLayoutQuality, layoutQualityOutput, layoutValidationCheck, layoutVerdictDiagnostic, withoutCurvedConnectorDiagnostics, worstVerdict, renderInlineImages, } from './quality/index.js';
15
17
  const LARGE_FOCUS_RENDER_NODE_THRESHOLD = 200;
16
18
  const LARGE_FOCUS_RENDER_SCALE = 0.5;
17
19
  function automaticFocusRenderScale(focusCount) {
@@ -69,6 +71,10 @@ export function normalizeFocusRenderRequest(input) {
69
71
  export function normalizeFocusRewriteRequest(input) {
70
72
  return input;
71
73
  }
74
+ /** Many trees in one result share the response budget, so each gets less of its scorecard. */
75
+ function inspectDetail(treeCount) {
76
+ return treeCount === 1 ? 'full' : treeCount <= 4 ? 'compact' : 'minimal';
77
+ }
72
78
  function compactDrift(drift) {
73
79
  return {
74
80
  status: drift.status,
@@ -209,15 +215,19 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
209
215
  }
210
216
  else {
211
217
  if (imported === undefined)
212
- throw new ServiceError('FOCUS_COMPACT_SOURCE_REQUIRED', 'Plan-free compact reflow requires an existing national focus source', { relativePath });
213
- compactSourcePlan = selectPlan(imported.result, input.treeId);
214
- compactPlanning = await compactFocusTreePlanAsync(compactSourcePlan, {
215
- ...(context.signal === undefined ? {} : { signal: context.signal }),
216
- ...(input.compactFocusIds === undefined ? {} : { focusIds: input.compactFocusIds }),
217
- ...(input.pinnedFocusIds === undefined ? {} : { pinnedFocusIds: input.pinnedFocusIds }),
218
- ...(input.symmetryGroups === undefined ? {} : { symmetryGroups: input.symmetryGroups }),
219
- });
220
- plan = compactPlanning.plan;
218
+ throw new ServiceError('FOCUS_COMPACT_SOURCE_REQUIRED', 'Plan-free compact or engine layout requires an existing national focus source', { relativePath });
219
+ if (input.layoutMode === 'engine')
220
+ plan = selectPlan(imported.result, input.treeId);
221
+ else {
222
+ compactSourcePlan = selectPlan(imported.result, input.treeId);
223
+ compactPlanning = await compactFocusTreePlanAsync(compactSourcePlan, {
224
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
225
+ ...(input.compactFocusIds === undefined ? {} : { focusIds: input.compactFocusIds }),
226
+ ...(input.pinnedFocusIds === undefined ? {} : { pinnedFocusIds: input.pinnedFocusIds }),
227
+ ...(input.symmetryGroups === undefined ? {} : { symmetryGroups: input.symmetryGroups }),
228
+ });
229
+ plan = compactPlanning.plan;
230
+ }
221
231
  }
222
232
  const currentPlan = imported?.result.plans.find(({ id }) => id === plan.id);
223
233
  if (currentPlan === undefined && !createIfMissing) {
@@ -260,6 +270,28 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
260
270
  : await workbench.layoutAsync(currentPlan, {
261
271
  ...(context.signal === undefined ? {} : { signal: context.signal }),
262
272
  });
273
+ let engineLayout;
274
+ if (input.layoutMode === 'engine' || input.placement !== undefined) {
275
+ await context.progress(1, 5, 'Laying out the tree with the focus layout engine');
276
+ // Raw source coordinates, without the planning sidecar's automatic-placement intent.
277
+ const sourcePlan = imported === undefined
278
+ ? undefined
279
+ : importFocusTrees(imported.document).plans.find(({ id }) => id === plan.id);
280
+ engineLayout = await layoutFocusTreeWithEngine({
281
+ plan,
282
+ layoutMode: input.layoutMode === 'engine' ? 'engine' : 'authored',
283
+ ...(input.placement === undefined ? {} : { placement: input.placement }),
284
+ ...(sourcePlan === undefined
285
+ ? {}
286
+ : {
287
+ currentSourcePositions: new Map(sourcePlan.focuses.map(({ id, position }) => [id, position])),
288
+ }),
289
+ ...(currentPlan === undefined
290
+ ? {}
291
+ : { currentFocusIds: new Set(currentPlan.focuses.map(({ id }) => id)) }),
292
+ }, context.signal === undefined ? {} : { signal: context.signal });
293
+ plan = engineLayout.plan;
294
+ }
263
295
  await context.progress(1, 5, 'Building proposed focus review');
264
296
  const proposedPlanHash = focusPlanHash(plan);
265
297
  const reviewPlan = {
@@ -274,8 +306,13 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
274
306
  (await workbench.layoutAsync(reviewPlan, {
275
307
  ...(context.signal === undefined ? {} : { signal: context.signal }),
276
308
  }));
309
+ if (engineLayout !== undefined)
310
+ assertFocusEngineLayoutWritten(engineLayout.response, proposedLayout.nodes);
277
311
  if (input.layoutMode === 'compact')
278
- assertCompactLayoutQuality(currentLayout, proposedLayout, input.compactFocusIds !== undefined);
312
+ assertCompactLayoutQuality(currentLayout, proposedLayout, input.compactFocusIds !== undefined, {
313
+ ...(currentPlan === undefined ? {} : { current: currentPlan }),
314
+ proposed: plan,
315
+ });
279
316
  const proposed = await workbench.renderAndStore(context.workspaceId, reviewPlan, {
280
317
  ...(context.principal === undefined ? {} : { principal: context.principal }),
281
318
  index: snapshot.index,
@@ -312,6 +349,14 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
312
349
  ...(context.signal === undefined ? {} : { signal: context.signal }),
313
350
  });
314
351
  await context.progress(4, 5, 'Focus rewrite prepared for journaled application');
352
+ const after = evaluateFocusLayoutQuality(plan, planned.layout.nodes);
353
+ const delta = describeLayoutDelta(currentPlan === undefined || currentLayout === undefined
354
+ ? undefined
355
+ : {
356
+ plan: currentPlan,
357
+ nodes: currentLayout.nodes,
358
+ report: evaluateFocusLayoutQuality(currentPlan, currentLayout.nodes).report,
359
+ }, { plan, nodes: planned.layout.nodes, report: after.report });
315
360
  return {
316
361
  transaction: planned.transaction,
317
362
  recipe: focusRewriteRecipeSchema.parse({
@@ -321,6 +366,24 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
321
366
  drift: compactDrift(planned.drift),
322
367
  created: planned.drift.status === 'target_missing',
323
368
  layoutHash: planned.layout.layoutHash,
369
+ layoutQuality: layoutQualityOutput(after.report, 'full'),
370
+ layoutDelta: delta,
371
+ sourcePath: plan.provenance.sourcePath,
372
+ ...(engineLayout === undefined
373
+ ? {}
374
+ : {
375
+ engine: engineLayout.summary,
376
+ engineDiagnostics: engineLayout.diagnostics.slice(0, 50),
377
+ }),
378
+ ...(compactPlanning?.outcome === 'nothing_to_improve'
379
+ ? {
380
+ compactOutcome: {
381
+ outcome: 'nothing_to_improve',
382
+ reason: compactPlanning.reason ?? 'no_better_candidate',
383
+ blockedBy: compactPlanning.blockedBy ?? [],
384
+ },
385
+ }
386
+ : {}),
324
387
  }),
325
388
  filesScanned: [
326
389
  ...new Set([
@@ -331,17 +394,25 @@ export async function prepareFocusRewrite(engine, workbench, input, context) {
331
394
  }),
332
395
  };
333
396
  }
397
+ /** A string recorded in a write recipe, or an empty one. */
398
+ function recipeText(value) {
399
+ return typeof value === 'string' ? value : '';
400
+ }
334
401
  export function completeFocusRewrite(workspaceId, execution, recipe) {
335
402
  const parsed = focusRewriteRecipeSchema.parse(recipe);
336
403
  const transaction = execution.transaction;
337
404
  const mode = parsed.data.mode;
405
+ // Engine diagnostics travel in the recipe and join the result's diagnostics, not its data.
406
+ const { engineDiagnostics, ...data } = parsed.data;
338
407
  const result = emptyServiceResult(workspaceId, {
339
- ...parsed.data,
408
+ ...data,
340
409
  execution: execution.outcome,
341
410
  fileCount: transaction.files.length,
342
411
  artifactCount: transaction.artifacts.length,
343
412
  });
344
413
  result.status = transaction.validation.passed ? 'ok' : 'blocked';
414
+ const quality = parsed.data.layoutQuality;
415
+ const compactOutcome = parsed.data.compactOutcome;
345
416
  result.code =
346
417
  mode === 'continuous'
347
418
  ? execution.outcome === 'applied'
@@ -357,9 +428,57 @@ export function completeFocusRewrite(workspaceId, execution, recipe) {
357
428
  setInlineFilesScanned(result, parsed.filesScanned);
358
429
  result.proposedFiles = transaction.files.slice(0, 100).map(({ relativePath }) => relativePath);
359
430
  result.changedFiles = transaction.appliedFiles.slice(0, 100);
360
- result.diagnostics = transaction.diagnostics.slice(0, 100);
431
+ const sourcePath = recipeText(parsed.data.sourcePath);
432
+ const treeId = recipeText(parsed.data.treeId);
433
+ const noteLocation = sourcePath === ''
434
+ ? undefined
435
+ : {
436
+ path: sourcePath,
437
+ start: { line: 1, column: 1, offset: 0 },
438
+ end: { line: 1, column: 1, offset: 0 },
439
+ };
440
+ const layoutNotes = [
441
+ ...(compactOutcome === undefined
442
+ ? []
443
+ : [
444
+ {
445
+ code: 'FOCUS_COMPACT_NOTHING_TO_IMPROVE',
446
+ severity: 'info',
447
+ category: 'layout',
448
+ message: compactOutcome.reason === 'verdict_pass'
449
+ ? 'The layout already passes every calibrated metric, so compact reflow has nothing to improve; the source is unchanged'
450
+ : compactOutcome.blockedBy.length === 0
451
+ ? 'Compact reflow found no layout that beats the current one under the in-game connector model; the source is unchanged'
452
+ : `Compact reflow found no layout that is at least as good as the current one (${compactOutcome.blockedBy.join(', ')}); the source is unchanged`,
453
+ ...(noteLocation === undefined ? {} : { location: noteLocation }),
454
+ details: {
455
+ reason: compactOutcome.reason,
456
+ blockedBy: compactOutcome.blockedBy,
457
+ verdict: quality?.verdict ?? null,
458
+ },
459
+ },
460
+ ]),
461
+ ...(quality === undefined
462
+ ? []
463
+ : [layoutVerdictDiagnostic(treeId, quality, noteLocation)].filter((entry) => entry !== undefined)),
464
+ ];
465
+ result.diagnostics = [
466
+ ...layoutNotes,
467
+ ...(engineDiagnostics ?? []),
468
+ ...transaction.diagnostics,
469
+ ].slice(0, 100);
361
470
  result.artifacts = autonomousResultArtifacts(execution);
362
- result.validation = transaction.validation;
471
+ result.validation =
472
+ quality === undefined
473
+ ? transaction.validation
474
+ : {
475
+ passed: transaction.validation.passed,
476
+ // First, because the inline list of checks is capped and the layout verdict must stay.
477
+ checks: [
478
+ layoutValidationCheck([{ treeId, report: quality }]),
479
+ ...transaction.validation.checks,
480
+ ],
481
+ };
363
482
  result.blockers = transaction.diagnostics
364
483
  .filter(({ severity }) => severity === 'error' || severity === 'blocker')
365
484
  .map(({ code, message, details }) => ({
@@ -490,10 +609,21 @@ export async function inspectFocus(engine, workbench, input, context) {
490
609
  layout,
491
610
  });
492
611
  diagnostics.push(...lintDiagnostics);
612
+ const quality = evaluateFocusLayoutQuality(plan, layout.nodes);
613
+ const previousLayout = input.previous;
614
+ const delta = previousLayout === undefined
615
+ ? undefined
616
+ : describeLayoutDelta({
617
+ plan,
618
+ nodes: previousLayout.nodes,
619
+ report: evaluateFocusLayoutQuality(plan, previousLayout.nodes).report,
620
+ }, { plan, nodes: layout.nodes, report: quality.report });
493
621
  inspectedPlans.push({
494
622
  plan,
495
623
  layout,
496
- diagnosticCount: lintDiagnostics.length,
624
+ diagnosticCount: withoutCurvedConnectorDiagnostics(lintDiagnostics).length,
625
+ quality,
626
+ ...(delta === undefined ? {} : { delta }),
497
627
  ...(input.scenario === undefined
498
628
  ? {}
499
629
  : { scenario: inspectFocusScenario(plan, input.scenario.completedFocusIds) }),
@@ -520,10 +650,12 @@ export async function inspectFocus(engine, workbench, input, context) {
520
650
  schemaVersion: 1,
521
651
  revision: snapshot.revision,
522
652
  plans,
523
- layouts: inspectedPlans.map(({ plan, layout, diagnosticCount, scenario }) => ({
653
+ layouts: inspectedPlans.map(({ plan, layout, diagnosticCount, scenario, quality, delta }) => ({
524
654
  treeId: plan.id,
525
655
  layout,
526
656
  diagnosticCount,
657
+ layoutQuality: quality.report,
658
+ ...(delta === undefined ? {} : { layoutDelta: delta }),
527
659
  ...(scenario === undefined ? {} : { scenario }),
528
660
  })),
529
661
  continuousFocusPalettes: paletteImport.palettes,
@@ -542,7 +674,10 @@ export async function inspectFocus(engine, workbench, input, context) {
542
674
  revision: snapshot.revision,
543
675
  treeCount: plans.length,
544
676
  paletteCount: paletteImport.palettes.length,
545
- trees: inspectedPlans.slice(0, 100).map(({ plan, layout, diagnosticCount, scenario }) => ({
677
+ layoutVerdict: worstVerdict(inspectedPlans.map(({ quality }) => quality.report.verdict)),
678
+ trees: inspectedPlans
679
+ .slice(0, 100)
680
+ .map(({ plan, layout, diagnosticCount, scenario, quality, delta }) => ({
546
681
  id: plan.id,
547
682
  sourcePath: plan.provenance.sourcePath,
548
683
  focusCount: plan.focuses.length,
@@ -555,6 +690,8 @@ export async function inspectFocus(engine, workbench, input, context) {
555
690
  layoutHash: layout.layoutHash,
556
691
  layoutDecisionCount: layout.decisions.length,
557
692
  layoutMetrics: layout.metrics,
693
+ layoutQuality: layoutQualityOutput(quality.report, inspectDetail(inspectedPlans.length)),
694
+ ...(delta === undefined ? {} : { layoutDelta: delta }),
558
695
  diagnosticCount,
559
696
  ...(scenario === undefined
560
697
  ? {}
@@ -576,9 +713,26 @@ export async function inspectFocus(engine, workbench, input, context) {
576
713
  ...presentation.filesScanned,
577
714
  ]),
578
715
  ].sort((left, right) => compareCodeUnits(left, right)));
579
- result.diagnostics = diagnostics.slice(0, 100);
716
+ // The curved-connector findings are replaced by the in-game connector model in the scorecard;
717
+ // the linked report keeps every raw diagnostic.
718
+ // The verdicts come first: the inline list is capped, and a verdict must never be cut off.
719
+ const reported = [
720
+ ...inspectedPlans.flatMap(({ plan, quality }) => {
721
+ const verdict = layoutVerdictDiagnostic(plan.id, quality.report, plan.sourceLocation);
722
+ return verdict === undefined ? [] : [verdict];
723
+ }),
724
+ ...withoutCurvedConnectorDiagnostics(diagnostics),
725
+ ];
726
+ result.diagnostics = reported.slice(0, 100);
580
727
  result.artifacts = [publicArtifactLink(artifact)];
581
- result.validation = validationFromDiagnostics(diagnostics);
728
+ const structure = validationFromDiagnostics(reported);
729
+ result.validation = {
730
+ passed: structure.passed,
731
+ checks: [
732
+ ...structure.checks,
733
+ layoutValidationCheck(inspectedPlans.map(({ plan, quality }) => ({ treeId: plan.id, report: quality.report }))),
734
+ ],
735
+ };
582
736
  await context.progress(3, 3, 'Focus inspection complete');
583
737
  return { result, sourceRevision: snapshot.revision };
584
738
  }
@@ -674,10 +828,27 @@ export async function renderFocus(engine, workbench, input, context, rasterize)
674
828
  budget: renderBudget,
675
829
  ...(context.signal === undefined ? {} : { signal: context.signal }),
676
830
  });
831
+ const quality = evaluateFocusLayoutQuality(plan, rendered.layout.nodes);
832
+ // The inline pictures are the in-game-style schematic the scorecard measures: right-angle
833
+ // connectors, 1.6-column plaques, cropped to branches and to the places the metrics blame.
834
+ const inline = input.inline === false
835
+ ? undefined
836
+ : await renderInlineImages(quality.graph, quality.report, {
837
+ ...(input.cropBranchIds === undefined ? {} : { cropBranchIds: input.cropBranchIds }),
838
+ ...(input.cropFocusIds === undefined ? {} : { cropFocusIds: input.cropFocusIds }),
839
+ budget: renderBudget,
840
+ }, `${plan.id} · ${plan.focuses.length} focuses · layout ${quality.report.verdict}`);
841
+ // The layout verdict and the crop notes come first: the inline list is capped.
677
842
  const diagnostics = [
843
+ ...[layoutVerdictDiagnostic(plan.id, quality.report, plan.sourceLocation)].filter((entry) => entry !== undefined),
844
+ // A location keeps these in the group of the mod's own findings, which the inline list shows first.
845
+ ...(inline?.diagnostics ?? []).map((diagnostic) => ({
846
+ ...diagnostic,
847
+ ...(plan.sourceLocation === undefined ? {} : { location: plan.sourceLocation }),
848
+ })),
678
849
  ...paletteImport.diagnostics,
679
850
  ...imported.diagnostics,
680
- ...rendered.diagnostics,
851
+ ...withoutCurvedConnectorDiagnostics(rendered.diagnostics),
681
852
  ];
682
853
  const result = emptyServiceResult(context.workspaceId, {
683
854
  mode: 'national',
@@ -686,12 +857,25 @@ export async function renderFocus(engine, workbench, input, context, rasterize)
686
857
  hashes: rendered.bundle.hashes,
687
858
  width: rendered.bundle.width,
688
859
  height: rendered.bundle.height,
860
+ layoutQuality: layoutQualityOutput(quality.report, 'compact'),
861
+ ...(inline === undefined ? {} : { inlineImages: inline.descriptions }),
689
862
  });
690
863
  result.code = rasterize ? 'FOCUS_RASTERIZED' : 'FOCUS_RENDERED';
691
864
  setInlineFilesScanned(result, [...new Set([plan.provenance.sourcePath, ...presentation.filesScanned])].sort((left, right) => compareCodeUnits(left, right)));
692
865
  result.diagnostics = diagnostics.slice(0, 100);
693
866
  result.artifacts = rendered.artifacts.map(publicArtifactLink);
694
- result.validation = validationFromDiagnostics(diagnostics);
867
+ const structure = validationFromDiagnostics(diagnostics);
868
+ result.validation = {
869
+ passed: structure.passed,
870
+ checks: [
871
+ ...structure.checks,
872
+ layoutValidationCheck([{ treeId: plan.id, report: quality.report }]),
873
+ ],
874
+ };
695
875
  await context.progress(4, 4, `Focus ${outputName} complete`);
696
- return { result, sourceRevision: snapshot.revision };
876
+ return {
877
+ result,
878
+ sourceRevision: snapshot.revision,
879
+ ...(inline === undefined || inline.images.length === 0 ? {} : { images: inline.images }),
880
+ };
697
881
  }
@@ -124,7 +124,7 @@ export function validationFromDiagnostics(diagnostics) {
124
124
  id: 'focus-diagnostics',
125
125
  passed: blocking.length === 0,
126
126
  message: blocking.length === 0
127
- ? 'Focus source, references, and layout have no blocking diagnostics'
127
+ ? 'Structure ok: focus source, references, prerequisites and positions have no blocking diagnostics. This is not a layout verdict'
128
128
  : `${blocking.length} blocking focus diagnostics`,
129
129
  },
130
130
  ],
@@ -194,6 +194,9 @@ export function collectMapScriptReferences(files) {
194
194
  const entity = fieldEntity(file.relativePath, key);
195
195
  if (entity === undefined)
196
196
  return;
197
+ // State ids start at 1: `state = 0` (usually `NOT = { state = 0 }`) tests for a valid state.
198
+ if (entity === 'state' && Number(entry.value.value) === 0)
199
+ return;
197
200
  references.push({
198
201
  entity,
199
202
  id: Number(entry.value.value),
@@ -216,6 +219,28 @@ export function missingMapReferenceDiagnostics(references, exists) {
216
219
  if (exists[reference.entity](reference.id))
217
220
  continue;
218
221
  const owned = reference.file.rootKind === 'mod' || reference.file.rootKind === 'fixture';
222
+ if (reference.entity === 'state' &&
223
+ reference.form === 'list' &&
224
+ STATE_LIST_BLOCKS.has(reference.key) &&
225
+ exists.province(reference.id)) {
226
+ // The game's documentation gives `prioritize` state ids only; a province id there (vanilla
227
+ // pairs a state with a port, `prioritize = { 521 7564 }`) is a separate, milder finding.
228
+ diagnostics.push({
229
+ code: 'MAP_SCRIPT_PRIORITIZE_PROVINCE',
230
+ severity: owned ? 'warning' : 'info',
231
+ category: 'map',
232
+ message: `${reference.file.relativePath} lists ${reference.id} in prioritize, which the map defines as a province, not a state; the effects documentation gives prioritize state ids only`,
233
+ location: nodeLocation(reference.document, reference.node),
234
+ details: {
235
+ entity: reference.entity,
236
+ id: reference.id,
237
+ key: reference.key,
238
+ form: reference.form,
239
+ layer: reference.file.rootKind,
240
+ },
241
+ });
242
+ continue;
243
+ }
219
244
  diagnostics.push({
220
245
  code: 'MAP_SCRIPT_REFERENCE_MISSING',
221
246
  severity: owned ? 'error' : 'warning',
@@ -433,7 +458,7 @@ export function mapScriptConsistency(index) {
433
458
  province: (id) => index.definitionsById.has(id),
434
459
  'strategic-region': (id) => index.regionsById.has(id),
435
460
  });
436
- const missing = diagnostics.length;
461
+ const missing = diagnostics.filter(({ code }) => code === 'MAP_SCRIPT_REFERENCE_MISSING').length;
437
462
  const tags = declaredCountryTags(index.sourceFiles);
438
463
  if (tags !== undefined)
439
464
  for (const state of index.states) {
@@ -6,6 +6,8 @@ import { borderQualityInputFromIndex } from './border-quality-input.js';
6
6
  import { borderEdgePixels, forEachBorderEdge, measureBorderNaturalness } from './border-quality.js';
7
7
  import { buildMapCatalog } from './catalog.js';
8
8
  import { validateMapAsync } from './validation.js';
9
+ /** Position records named in a review diff artifact, per kind; the rest are counted. */
10
+ export const MAP_DIFF_POSITION_RECORD_LIMIT = 2_000;
9
11
  function stableColor(key) {
10
12
  const hash = sha256Bytes(key);
11
13
  const first = Number.parseInt(hash.slice(0, 2), 16);
@@ -313,10 +315,13 @@ async function applyOverlays(index, bytes, overlays, signal) {
313
315
  }
314
316
  }
315
317
  }
316
- async function renderMetadata(index, options, signal) {
318
+ async function renderMetadata(index, options, signal, positionRecords = 'all') {
317
319
  const catalog = buildMapCatalog(index);
318
320
  return {
319
321
  ...catalog,
322
+ ...(positionRecords === 'counts'
323
+ ? { buildingPositions: [], unitPositions: [], weatherPositions: [], positionRecords }
324
+ : {}),
320
325
  renderer: 'hoi4-agent-tools-map-workbench',
321
326
  layer: options.layer,
322
327
  overlays: options.overlays,
@@ -486,7 +491,7 @@ export async function renderMap(index, options = {}) {
486
491
  }
487
492
  const png = await encodePng(raw, raster.width, raster.height, resolved.scale);
488
493
  options.signal?.throwIfAborted();
489
- const json = `${canonicalJson(await renderMetadata(index, resolved, options.signal))}\n`;
494
+ const json = `${canonicalJson(await renderMetadata(index, resolved, options.signal, options.positionRecords))}\n`;
490
495
  const provinceHitMap = await encodeProvinceHitMap(index);
491
496
  const html = htmlDocument(`HOI4 map - ${resolved.layer}`, png, provinceHitMap, json, resolved.scale);
492
497
  return {
@@ -693,6 +698,27 @@ export function semanticMapDiff(before, after) {
693
698
  normalAdjacenciesChanged: normalAdjacencies.length > 0,
694
699
  };
695
700
  }
701
+ /**
702
+ * The semantic diff for the artifact, with at most `MAP_DIFF_POSITION_RECORD_LIMIT` building,
703
+ * unit and weather position changes listed per kind: a replaced world changes every position,
704
+ * which would make the review artifact hundreds of megabytes. The counts stay complete.
705
+ */
706
+ export function boundedPositionDiffs(semantic) {
707
+ const kinds = ['buildingPositions', 'unitPositions', 'weatherPositions'];
708
+ const over = kinds.filter((kind) => semantic[kind].length > MAP_DIFF_POSITION_RECORD_LIMIT);
709
+ if (over.length === 0)
710
+ return { semantic };
711
+ const bounded = { ...semantic };
712
+ const positionChanges = {};
713
+ for (const kind of over) {
714
+ bounded[kind] = semantic[kind].slice(0, MAP_DIFF_POSITION_RECORD_LIMIT);
715
+ positionChanges[kind] = {
716
+ total: semantic[kind].length,
717
+ listed: MAP_DIFF_POSITION_RECORD_LIMIT,
718
+ };
719
+ }
720
+ return { semantic: bounded, positionChanges };
721
+ }
696
722
  function uniqueNumbers(values) {
697
723
  return [...new Set(values)].sort((left, right) => left - right);
698
724
  }
@@ -744,7 +770,7 @@ export async function renderMapDiff(before, after, options = {}) {
744
770
  renderer: 'hoi4-agent-tools-map-diff',
745
771
  changedBounds: changedBounds ?? null,
746
772
  changedProvinceIds: [...changedProvinceIds].sort((a, b) => a - b),
747
- semantic,
773
+ ...boundedPositionDiffs(semantic),
748
774
  ...(options.review === undefined ? {} : { review: options.review }),
749
775
  };
750
776
  const json = `${canonicalJson(metadata)}\n`;
@@ -577,6 +577,7 @@ async function wholeMapDiff(after, options) {
577
577
  const rendered = await renderMap(after, {
578
578
  layer: 'state',
579
579
  overlays: ['coastlines', 'ports', 'victory-points', 'supply-nodes', 'railways'],
580
+ positionRecords: 'counts',
580
581
  ...(options?.scale === undefined ? {} : { scale: options.scale }),
581
582
  ...(options?.signal === undefined ? {} : { signal: options.signal }),
582
583
  ...(options?.budget === undefined ? {} : { budget: options.budget }),
@@ -1238,6 +1239,7 @@ export class AgentNudger {
1238
1239
  ? renderMap(snapshot.index, {
1239
1240
  layer: 'state',
1240
1241
  overlays: [...comparisonOverlays],
1242
+ positionRecords: 'counts',
1241
1243
  ...(options.scale === undefined ? {} : { scale: options.scale }),
1242
1244
  ...(options.signal === undefined ? {} : { signal: options.signal }),
1243
1245
  budget,
@@ -1246,6 +1248,7 @@ export class AgentNudger {
1246
1248
  renderMap(plan.finalIndex, {
1247
1249
  layer: 'state',
1248
1250
  overlays: [...comparisonOverlays],
1251
+ positionRecords: 'counts',
1249
1252
  ...(options.scale === undefined ? {} : { scale: options.scale }),
1250
1253
  ...(options.signal === undefined ? {} : { signal: options.signal }),
1251
1254
  budget,
@@ -6,6 +6,7 @@ import { autonomousResultArtifacts, } from '../core/transaction-execution.js';
6
6
  import { emptyServiceResult, ServiceError } from '../core/result.js';
7
7
  import { setInlineFilesScanned } from '../core/operation-result.js';
8
8
  import { PACKAGE_VERSION } from '../version.js';
9
+ import { summarizeChangedFiles } from '../core/changed-summary.js';
9
10
  import { allocateMapIdentifiersAsync, WORLD_OUTPUT_PATH_SAMPLE, } from './operations.js';
10
11
  import { compactTerritoryReport } from './territory-operations.js';
11
12
  import { borderQualityDiagnostics } from './border-quality.js';
@@ -360,6 +361,10 @@ export function completeMapRewrite(workspaceId, execution, recipe) {
360
361
  ...parsed.data,
361
362
  fileCount: transaction.files.length,
362
363
  artifactCount: transaction.artifacts.length,
364
+ // The file list is cut to 100 and a long response is cut again; the counts always arrive.
365
+ ...(execution.outcome === 'applied'
366
+ ? { changedSummary: summarizeChangedFiles(transaction.files) }
367
+ : {}),
363
368
  });
364
369
  result.status = transaction.validation.passed ? 'ok' : 'blocked';
365
370
  result.code =
@@ -1,2 +1,2 @@
1
1
  /** Shared agent-facing guidance for both MCP protocol generations. */
2
- export const SERVER_INSTRUCTIONS = 'Start with the matching inspect tool; use hoi4.probability_inspect for weights and timing. Find local documentation with hoi4.reference_context, hoi4.reference_search and hoi4.reference_read, and source definitions with hoi4.source_lookup. Rewrite tools edit mod source. Results describe offline source and scenario models, not observed game behavior. Unresolved states are not confirmed coverage. Read linked artifacts when summaries omit detail. Long operations support negotiated MCP tasks and hoi4.job_inspect/hoi4.job_cancel; background rewrites need a stable requestKey.';
2
+ export const SERVER_INSTRUCTIONS = 'Start with the matching inspect tool; use hoi4.probability_inspect for weights and timing. Find local documentation with hoi4.reference_context, hoi4.reference_search and hoi4.reference_read, and source definitions with hoi4.source_lookup. Rewrite tools edit mod source. For focus trees: plan lanes first, place with auto positions, render and look, read the layout verdict (revise and blocked mean not finished), then revise only the failing branch. Results describe offline source and scenario models, not observed game behavior. Unresolved states are not confirmed coverage. Read linked artifacts when summaries omit detail. Long operations support negotiated MCP tasks and hoi4.job_inspect/hoi4.job_cancel; background rewrites need a stable requestKey.';