hoi4-agent-tools 4.6.5 → 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 (80) hide show
  1. package/CHANGELOG.md +16 -5
  2. package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
  3. package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
  4. package/dist/hoi4_agent_tools/focus/compact.js +197 -18
  5. package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
  6. package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
  7. package/dist/hoi4_agent_tools/focus/layout.js +3 -2
  8. package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
  9. package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
  10. package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
  11. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
  12. package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
  13. package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
  14. package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
  15. package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
  16. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +202 -0
  17. package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
  18. package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -0
  19. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
  20. package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
  21. package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
  22. package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
  23. package/dist/hoi4_agent_tools/focus/tool-operations.js +206 -22
  24. package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
  25. package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
  26. package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
  27. package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
  28. package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
  29. package/dist/hoi4_agent_tools/reference/service.js +92 -21
  30. package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
  31. package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
  32. package/dist/hoi4_agent_tools/version.js +1 -1
  33. package/docs/configuration.md +17 -17
  34. package/docs/focus.md +100 -4
  35. package/docs/reference.md +1 -1
  36. package/docs/research/reference-benchmark.md +111 -1
  37. package/docs/setup.md +1 -1
  38. package/docs/tools.md +5 -5
  39. package/npm-shrinkwrap.json +2 -2
  40. package/package.json +2 -1
  41. package/schemas/configuration.schema.json +1 -1
  42. package/schemas/continuous-focus-palette.schema.json +1 -1
  43. package/schemas/custom-weighted-pool.schema.json +1 -1
  44. package/schemas/decision-inspect-input.schema.json +1 -1
  45. package/schemas/error-log-input.schema.json +1 -1
  46. package/schemas/event-feature-manifest.schema.json +1 -1
  47. package/schemas/focus-plan.schema.json +146 -120
  48. package/schemas/focus-planning-sidecar.schema.json +15 -7
  49. package/schemas/geography-model.schema.json +1 -1
  50. package/schemas/gui-animation-source.schema.json +1 -1
  51. package/schemas/gui-helper.schema.json +1 -1
  52. package/schemas/gui-scenario.schema.json +1 -1
  53. package/schemas/helper-expansion-request.schema.json +1 -1
  54. package/schemas/helper-expansion-summary.schema.json +1 -1
  55. package/schemas/impact-inspect-input.schema.json +1 -1
  56. package/schemas/map-operation.schema.json +1 -1
  57. package/schemas/mechanic-test-input.schema.json +1 -1
  58. package/schemas/mod-index-input.schema.json +1 -1
  59. package/schemas/operation-result.schema.json +1 -1
  60. package/schemas/package-check-input.schema.json +1 -1
  61. package/schemas/package-manifest.schema.json +1 -1
  62. package/schemas/probability-analysis-result.schema.json +1 -1
  63. package/schemas/probability-compare-input.schema.json +1 -1
  64. package/schemas/probability-evaluate-input.schema.json +1 -1
  65. package/schemas/probability-inspect-input.schema.json +1 -1
  66. package/schemas/probability-render-input.schema.json +1 -1
  67. package/schemas/probability-scenario-set.schema.json +1 -1
  68. package/schemas/probability-sequence-input.schema.json +1 -1
  69. package/schemas/probability-simulate-input.schema.json +1 -1
  70. package/schemas/probability-sweep-input.schema.json +1 -1
  71. package/schemas/reference-context-input.schema.json +1 -1
  72. package/schemas/reference-read-input.schema.json +1 -1
  73. package/schemas/reference-search-input.schema.json +1 -1
  74. package/schemas/reference-sheets.schema.json +1 -1
  75. package/schemas/scenario-suite.schema.json +1 -1
  76. package/schemas/scenario-test-input.schema.json +1 -1
  77. package/schemas/script-validate-input.schema.json +1 -1
  78. package/schemas/shared-scenario.schema.json +1 -1
  79. package/schemas/source-lookup-input.schema.json +1 -1
  80. 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
  ],
@@ -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.';
@@ -1,7 +1,7 @@
1
1
  import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
2
2
  import { z } from 'zod/v4';
3
3
  import { computeFocusVisualRevisions as computeCoreFocusVisualRevisions, } from '../../focus/tool-operations.js';
4
- import { focusLayoutMetricsSchema } from '../../schemas/focus.js';
4
+ import { focusLayoutDeltaSchema, focusLayoutMetricsSchema, focusLayoutQualitySchema, } from '../../schemas/focus.js';
5
5
  import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../../schemas/focus-requests.js';
6
6
  import { nonNegativeIntegerSchema, renderHashesSchema, sha256Schema, } from '../server/output-schemas.js';
7
7
  import { strictOperationResultSchema } from '../server/result.js';
@@ -9,6 +9,7 @@ const focusInspectOutputSchema = strictOperationResultSchema(z
9
9
  .object({
10
10
  mode: z.enum(['national', 'continuous']),
11
11
  revision: sha256Schema,
12
+ layoutVerdict: z.enum(['blocked', 'revise', 'review', 'pass']).optional(),
12
13
  treeCount: nonNegativeIntegerSchema,
13
14
  paletteCount: nonNegativeIntegerSchema,
14
15
  trees: z
@@ -29,6 +30,8 @@ const focusInspectOutputSchema = strictOperationResultSchema(z
29
30
  layoutHash: sha256Schema,
30
31
  layoutDecisionCount: nonNegativeIntegerSchema,
31
32
  layoutMetrics: focusLayoutMetricsSchema,
33
+ layoutQuality: focusLayoutQualitySchema.optional(),
34
+ layoutDelta: focusLayoutDeltaSchema.optional(),
32
35
  diagnosticCount: nonNegativeIntegerSchema,
33
36
  scenarioSummary: z
34
37
  .object({
@@ -64,6 +67,28 @@ const focusRenderOutputSchema = strictOperationResultSchema(z.discriminatedUnion
64
67
  hashes: renderHashesSchema,
65
68
  width: nonNegativeIntegerSchema,
66
69
  height: nonNegativeIntegerSchema,
70
+ layoutQuality: focusLayoutQualitySchema.optional(),
71
+ inlineImages: z
72
+ .array(z
73
+ .object({
74
+ kind: z.enum(['overview', 'branch', 'focus', 'problem']),
75
+ label: z.string().max(300),
76
+ focusIds: z.array(z.string().max(256)).max(50),
77
+ region: z
78
+ .object({
79
+ minimumX: z.number().int(),
80
+ maximumX: z.number().int(),
81
+ minimumY: z.number().int(),
82
+ maximumY: z.number().int(),
83
+ })
84
+ .strict(),
85
+ width: nonNegativeIntegerSchema,
86
+ height: nonNegativeIntegerSchema,
87
+ bytes: nonNegativeIntegerSchema,
88
+ })
89
+ .strict())
90
+ .max(6)
91
+ .optional(),
67
92
  })
68
93
  .strict(),
69
94
  z
@@ -93,6 +118,42 @@ const focusDriftOutputSchema = z
93
118
  planChanged: z.boolean(),
94
119
  })
95
120
  .strict();
121
+ const engineShiftOutputSchema = z
122
+ .object({
123
+ fromX: z.number().int(),
124
+ columns: z.number().int().min(1),
125
+ direction: z.enum(['right', 'left']),
126
+ focusIds: z.array(z.string().max(256)),
127
+ })
128
+ .strict();
129
+ /** What the focus layout engine did (layoutMode engine or placement). */
130
+ const focusEngineLayoutOutputSchema = z
131
+ .object({
132
+ operation: z.enum(['layout', 'insert']),
133
+ status: z.literal('ok'),
134
+ hashes: z
135
+ .object({
136
+ layout: sha256Schema.nullable(),
137
+ untouched: sha256Schema,
138
+ prerequisites: sha256Schema,
139
+ exclusions: sha256Schema,
140
+ })
141
+ .strict(),
142
+ metrics: z
143
+ .object({
144
+ columns: nonNegativeIntegerSchema,
145
+ rows: nonNegativeIntegerSchema,
146
+ orthogonalCrossings: nonNegativeIntegerSchema,
147
+ stemsThroughPlaques: nonNegativeIntegerSchema,
148
+ mergedBars: nonNegativeIntegerSchema,
149
+ })
150
+ .strict(),
151
+ movedFocusIds: z.array(z.string().max(256)).max(100),
152
+ movedFocusCount: nonNegativeIntegerSchema,
153
+ shifted: z.array(engineShiftOutputSchema).optional(),
154
+ binarySource: z.enum(['environment', 'package']),
155
+ })
156
+ .strict();
96
157
  const focusPlanOutputSchema = strictOperationResultSchema(z.discriminatedUnion('mode', [
97
158
  z
98
159
  .object({
@@ -102,6 +163,17 @@ const focusPlanOutputSchema = strictOperationResultSchema(z.discriminatedUnion('
102
163
  created: z.boolean(),
103
164
  execution: z.enum(['applied', 'blocked', 'unchanged']),
104
165
  layoutHash: sha256Schema,
166
+ layoutQuality: focusLayoutQualitySchema.optional(),
167
+ layoutDelta: focusLayoutDeltaSchema.optional(),
168
+ compactOutcome: z
169
+ .object({
170
+ outcome: z.literal('nothing_to_improve'),
171
+ reason: z.enum(['verdict_pass', 'no_better_candidate', 'candidates_regress']),
172
+ blockedBy: z.array(z.string().max(64)).max(10),
173
+ })
174
+ .strict()
175
+ .optional(),
176
+ engine: focusEngineLayoutOutputSchema.optional(),
105
177
  fileCount: nonNegativeIntegerSchema,
106
178
  artifactCount: nonNegativeIntegerSchema,
107
179
  })
@@ -135,7 +207,7 @@ export const focusTaskTools = [
135
207
  {
136
208
  name: 'hoi4.focus_inspect',
137
209
  title: 'Inspect focus trees',
138
- description: 'Find focus branches, prerequisites, layout problems and missing references in national trees and continuous-focus palettes. Example: {"treeId":"my_focus_tree"}. Returns counts and the main diagnostics inline; the full report is a linked resource.',
210
+ description: 'Check a focus tree\'s structure and layout. Returns blocking errors, a layout verdict (pass, review, revise, blocked) with the metrics behind it, a fix for each failing metric and next actions. Revise or blocked means the tree is not finished, however clean its structure; review is advisory, so look at hoi4.focus_render. Example: {"treeId":"my_focus_tree"}. The full report is a linked resource.',
139
211
  inputSchema: focusInspectRequestSchema,
140
212
  outputSchema: focusInspectOutputSchema,
141
213
  annotations: artifactProducing,
@@ -143,7 +215,7 @@ export const focusTaskTools = [
143
215
  {
144
216
  name: 'hoi4.focus_render',
145
217
  title: 'Preview a focus tree or continuous palette',
146
- description: 'Preview a focus tree or palette with its icons. Export PNG, HTML, SVG and JSON source maps; png:false skips the PNG and cropFocusIds adds close-ups. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree"}. Images are linked artifacts, not inline.',
218
+ description: 'Render a focus tree in the in-game style (right-angle connectors) and return it inline, with close-ups of the worst places; cropBranchIds and cropFocusIds add more. Look before you judge a layout: metrics cannot see composition. Also exports PNG with icons, HTML, SVG and JSON as linked artifacts. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree"}.',
147
219
  inputSchema: focusRenderRequestSchema,
148
220
  outputSchema: focusRenderOutputSchema,
149
221
  annotations: artifactProducing,
@@ -151,7 +223,7 @@ export const focusTaskTools = [
151
223
  {
152
224
  name: 'hoi4.focus_rewrite',
153
225
  title: 'Build or arrange a focus tree',
154
- description: 'Create focus trees and continuous-focus palettes, or rearrange existing branches. Use createIfMissing with a complete plan to create content, or layoutMode to arrange an existing tree. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}. Returns the changed files.',
226
+ description: 'Create or repair a focus tree or palette. New trees: lanes and position mode auto; x/y only for exact anchors. layoutMode compact repairs a layout (compactFocusIds picks a branch, pinnedFocusIds keeps neighbours); engine lays out with the Rust engine; placement adds focuses, moving no others; both need hoi4-engine. Keeps prerequisites and rewards. Returns files, layout verdict and delta. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}.',
155
227
  inputSchema: focusRewriteRequestSchema,
156
228
  outputSchema: focusPlanOutputSchema,
157
229
  annotations: {
@@ -0,0 +1,109 @@
1
+ import { readFile, realpath, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { sha256Bytes } from '../core/canonical.js';
4
+ import { isWithin } from '../core/workspace.js';
5
+ /**
6
+ * The words a player reads for script commands and modifiers.
7
+ *
8
+ * The game's English localisation names each command's tooltip after it: `TRIGGER_IS_COASTAL`
9
+ * reads "Is coastal", `TRIGGER_HAS_IDEA_COUNTRY` reads "Has national spirit", and
10
+ * `MODIFIER_SUPPLY_CONSUMPTION_FACTOR` reads "Supply Consumption". These are the words a
11
+ * modder uses to describe the command, so search adds them to the command's entries.
12
+ */
13
+ const files = ['effects_l_english.yml', 'triggers_l_english.yml', 'modifiers_l_english.yml'];
14
+ const MAX_FILE_BYTES = 2_000_000;
15
+ const entry = /^\s*([A-Za-z0-9_.]+):\d*\s*"(.*)"\s*(?:#.*)?$/u;
16
+ // Negated and descriptive variants of a key describe the same command.
17
+ const keyNoise = /(?:^|_)(?:NOT|NO|YES|TT|DESC|TOOLTIP|DETAILED|HEADER)(?=_|$)/gu;
18
+ const empty = { revision: 'none', texts: new Map() };
19
+ const cache = new Map();
20
+ /** Plain words of a localisation value, without formatting codes or placeholders. */
21
+ export function plainLocalisation(value) {
22
+ return value
23
+ .replaceAll('\\n', ' ')
24
+ .replace(/\$[^$]*\$/gu, ' ')
25
+ .replace(/§.|£\S*/gu, ' ')
26
+ .replace(/\[[^\]]*\]|@\S*/gu, ' ')
27
+ .replace(/\s+/gu, ' ')
28
+ .trim();
29
+ }
30
+ export async function readGameText(gameRoot) {
31
+ if (gameRoot === undefined)
32
+ return empty;
33
+ let root;
34
+ try {
35
+ root = await realpath(path.join(gameRoot, 'localisation', 'english'));
36
+ }
37
+ catch {
38
+ return empty;
39
+ }
40
+ if (!isWithin(await realpath(gameRoot), root))
41
+ return empty;
42
+ const stamps = [];
43
+ const paths = [];
44
+ for (const name of files) {
45
+ try {
46
+ const file = path.join(root, name);
47
+ const metadata = await stat(file);
48
+ if (!metadata.isFile() || metadata.size > MAX_FILE_BYTES)
49
+ continue;
50
+ stamps.push(`${name}:${metadata.size}:${metadata.mtimeMs}:${metadata.ino}`);
51
+ paths.push(file);
52
+ }
53
+ catch {
54
+ // A missing file leaves its commands without in-game text.
55
+ }
56
+ }
57
+ const stamp = stamps.join('|');
58
+ const known = cache.get(root);
59
+ if (known?.stamp === stamp)
60
+ return known.text;
61
+ const texts = new Map();
62
+ const hashes = [];
63
+ for (const file of paths) {
64
+ const bytes = await readFile(file);
65
+ hashes.push(sha256Bytes(bytes));
66
+ const content = bytes.toString('utf8');
67
+ for (const line of (content.charCodeAt(0) === 0xfeff ? content.slice(1) : content).split(/\r?\n/u)) {
68
+ const match = entry.exec(line);
69
+ const prefix = match === null ? null : /^(?:EFFECT|TRIGGER|MODIFIER)_/u.exec(match[1]);
70
+ if (match === null || prefix === null)
71
+ continue;
72
+ const key = match[1]
73
+ .slice(prefix[0].length)
74
+ .replace(keyNoise, '')
75
+ .replace(/__+/gu, '_')
76
+ .replace(/^_|_$/gu, '')
77
+ .toLowerCase();
78
+ const value = plainLocalisation(match[2]);
79
+ if (key.length === 0 || value.length === 0)
80
+ continue;
81
+ const list = texts.get(key) ?? [];
82
+ list.push(value);
83
+ texts.set(key, list);
84
+ }
85
+ }
86
+ const text = { revision: sha256Bytes(Buffer.from(hashes.join('\n'), 'utf8')), texts };
87
+ cache.set(root, { stamp, text });
88
+ return text;
89
+ }
90
+ /**
91
+ * The game texts for each command name: an exact key, or the longest command that a key
92
+ * extends at an underscore (`has_idea_country` describes `has_idea`).
93
+ */
94
+ export function commandTexts(commands, text) {
95
+ const result = new Map();
96
+ for (const [key, values] of text.texts) {
97
+ let name = key;
98
+ while (!commands.has(name)) {
99
+ const cut = name.lastIndexOf('_');
100
+ if (cut <= 0)
101
+ break;
102
+ name = name.slice(0, cut);
103
+ }
104
+ if (!commands.has(name))
105
+ continue;
106
+ result.set(name, [...(result.get(name) ?? []), ...values]);
107
+ }
108
+ return result;
109
+ }