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
@@ -3,6 +3,9 @@ import { ServiceError } from '../core/result.js';
3
3
  import { focusPlanHash, } from './model.js';
4
4
  import { FOCUS_LAYOUT_WORK_MAX } from './limits.js';
5
5
  import { FocusLayoutWorkBudget, layoutFocusTree, layoutFocusTreeAsync } from './layout.js';
6
+ import { evaluateFocusLayoutQuality } from './quality/index.js';
7
+ import { buildQualityGraph } from './quality/graph.js';
8
+ import { measureOrthogonalConnectors } from './quality/orthogonal.js';
6
9
  const COMPACT_SAME_ROW_SPACING = 2;
7
10
  const COMPACT_LANE_SPACING = 8;
8
11
  const SMALL_COMPACT_SCALES = [0.2, 0.3, 0.4, 0.55, 0.7, 0.9];
@@ -44,6 +47,81 @@ function absoluteCompactRegressions(layout) {
44
47
  ...(metrics.symmetry.boundingCenterOffsetTwice > 1 ? ['boundingCenter'] : []),
45
48
  ];
46
49
  }
50
+ /** The curved-connector diagnostics are replaced by the orthogonal model below. */
51
+ const CURVED_CONNECTOR_DIAGNOSTICS = new Set([
52
+ 'FOCUS_LAYOUT_CONNECTOR_CROSSING_UNSATISFIED',
53
+ 'FOCUS_LAYOUT_CONNECTOR_THROUGH_NODE',
54
+ ]);
55
+ const gateReadings = new WeakMap();
56
+ /**
57
+ * Reads a layout under the in-game connector model. Connectors inside an all-to-all bundle share
58
+ * one bar in the game, so a bundle never counts against a layout; the curved model counts every
59
+ * pair inside it as a crossing, which refused every tree that contains one.
60
+ */
61
+ function readGate(side) {
62
+ const cached = gateReadings.get(side.layout);
63
+ if (cached !== undefined)
64
+ return cached;
65
+ const metrics = requiredMetrics(side.layout);
66
+ const orthogonal = measureOrthogonalConnectors(buildQualityGraph(side.plan, side.layout.nodes));
67
+ const reading = {
68
+ hardDiagnostics: side.layout.diagnostics.filter(({ code }) => COMPACT_HARD_DIAGNOSTICS.has(code) && !CURVED_CONNECTOR_DIAGNOSTICS.has(code)).length,
69
+ crossings: orthogonal.crossings.length,
70
+ stemsThroughPlaques: orthogonal.stemsThroughPlaques.length,
71
+ tooCloseSameRow: metrics.spacing.tooCloseSameRowPairCount,
72
+ boundingCenterOffsetTwice: metrics.symmetry.boundingCenterOffsetTwice,
73
+ };
74
+ gateReadings.set(side.layout, reading);
75
+ return reading;
76
+ }
77
+ /**
78
+ * A candidate may not be worse than the layout it replaces, and a new tree starts from zero.
79
+ * Whole-tree reflow also keeps the bounding box centred unless it already was not.
80
+ */
81
+ function bundleAwareRegressions(candidate, baseline, wholeTree) {
82
+ const after = readGate(candidate);
83
+ const before = baseline === undefined
84
+ ? {
85
+ hardDiagnostics: 0,
86
+ crossings: 0,
87
+ stemsThroughPlaques: 0,
88
+ tooCloseSameRow: 0,
89
+ boundingCenterOffsetTwice: 1,
90
+ }
91
+ : readGate(baseline);
92
+ return [
93
+ ...(after.hardDiagnostics > before.hardDiagnostics ? ['hardLayoutDiagnostics'] : []),
94
+ ...(after.crossings > before.crossings ? ['connectorCrossingCount'] : []),
95
+ ...(after.stemsThroughPlaques > before.stemsThroughPlaques
96
+ ? ['connectorNodeIntersections']
97
+ : []),
98
+ ...(after.tooCloseSameRow > before.tooCloseSameRow ? ['sameRowSpacing'] : []),
99
+ ...(wholeTree && after.boundingCenterOffsetTwice > Math.max(1, before.boundingCenterOffsetTwice)
100
+ ? ['boundingCenter']
101
+ : []),
102
+ ];
103
+ }
104
+ /**
105
+ * Regressions that refuse a candidate. A candidate the curved-connector gate accepted is still
106
+ * accepted; one that only failed it because of a bundle or an artefact of the curve model is
107
+ * accepted when it is no worse than the current layout under the in-game connector model.
108
+ */
109
+ function candidateRegressions(candidate, baseline, bounded) {
110
+ const legacy = bounded && baseline !== undefined
111
+ ? relativeCompactRegressions(baseline.layout, candidate.layout)
112
+ : absoluteCompactRegressions(candidate.layout);
113
+ const regressions = legacy.length === 0 ? legacy : bundleAwareRegressions(candidate, baseline, !bounded);
114
+ // Whatever the curve model says, compaction may not leave a layout that hoi4.focus_inspect would
115
+ // judge worse than the one in place.
116
+ if (regressions.length === 0 && baseline !== undefined && worseVerdict(candidate, baseline))
117
+ return ['layoutVerdict'];
118
+ return regressions;
119
+ }
120
+ const VERDICT_RANK = { pass: 0, review: 1, revise: 2, blocked: 3 };
121
+ function worseVerdict(candidate, baseline) {
122
+ const verdictOf = (side) => evaluateFocusLayoutQuality(side.plan, side.layout.nodes).report.verdict;
123
+ return VERDICT_RANK[verdictOf(candidate)] > VERDICT_RANK[verdictOf(baseline)];
124
+ }
47
125
  function prerequisiteIds(plan, focusId) {
48
126
  const focus = plan.focuses.find(({ id }) => id === focusId);
49
127
  return (focus?.prerequisites.groups
@@ -545,6 +623,8 @@ function needsPresentationNormalization(plan) {
545
623
  export function compactFocusTreePlan(plan, requested = {}) {
546
624
  const selection = validatedSelection(plan, requested);
547
625
  const currentLayout = layoutFocusTree(plan, { aggressiveAestheticRepair: true });
626
+ if (alreadyPasses(plan, currentLayout, selection))
627
+ return plan;
548
628
  const normalizedPlan = needsPresentationNormalization(plan)
549
629
  ? compactCandidate(plan, currentLayout, {
550
630
  scale: 1,
@@ -594,17 +674,18 @@ export function compactFocusTreePlan(plan, requested = {}) {
594
674
  }
595
675
  if (fallback === undefined || betterScore(compactScore(layout), compactScore(fallback.layout)))
596
676
  fallback = { plan: candidate, layout };
597
- if ((selection.focusIds === undefined
598
- ? absoluteCompactRegressions(layout)
599
- : relativeCompactRegressions(currentLayout, layout)).length > 0)
677
+ if (candidateRegressions({ plan: candidate, layout }, { plan, layout: currentLayout }, selection.focusIds !== undefined).length > 0)
600
678
  continue;
601
679
  if (selected === undefined || betterScore(compactScore(layout), compactScore(selected.layout)))
602
680
  selected = { plan: candidate, layout };
603
681
  }
604
682
  if (selected !== undefined)
605
- return selected.plan;
683
+ return strictlyBetter(selected.layout, currentLayout) ? selected.plan : plan;
606
684
  if (fallback !== undefined) {
607
- assertCompactLayoutQuality(currentLayout, fallback.layout, selection.focusIds !== undefined);
685
+ const regressions = candidateRegressions({ plan: fallback.plan, layout: fallback.layout }, { plan, layout: currentLayout }, selection.focusIds !== undefined);
686
+ // Every candidate is worse than the layout in place on something the gate protects: keep it.
687
+ if (regressions.length > 0)
688
+ return plan;
608
689
  return fallback.plan;
609
690
  }
610
691
  if (blockedFocusIds.size > 0)
@@ -613,6 +694,44 @@ export function compactFocusTreePlan(plan, requested = {}) {
613
694
  throw new ServiceError('FOCUS_COMPACT_SYMMETRY_CONFLICT', 'No compact candidate satisfies the requested symmetry pairs', { treeId: plan.id, pairs: blockedSymmetry });
614
695
  throw new ServiceError('FOCUS_COMPACT_LAYOUT_REQUIRED', 'Compact focus planning did not produce a measurable layout candidate', { treeId: plan.id });
615
696
  }
697
+ function nothingToImprove(plan, currentLayout, blockedBy, reason) {
698
+ return {
699
+ plan,
700
+ currentLayout,
701
+ proposedLayout: currentLayout,
702
+ outcome: 'nothing_to_improve',
703
+ blockedBy,
704
+ reason,
705
+ };
706
+ }
707
+ /**
708
+ * A whole-tree reflow of a layout that already passes every calibrated metric has nothing to gain
709
+ * and would only cost 20 to 70 seconds and churn in the source; an explicit branch, pins or
710
+ * symmetry request is still honoured.
711
+ */
712
+ function alreadyPasses(plan, layout, selection) {
713
+ if (selection.focusIds !== undefined ||
714
+ selection.pinnedFocusIds.size > 0 ||
715
+ selection.symmetryGroups.length > 0)
716
+ return false;
717
+ const report = evaluateFocusLayoutQuality(plan, layout.nodes).report;
718
+ return report.softMetricsEvaluated && report.verdict === 'pass';
719
+ }
720
+ /**
721
+ * The candidate beats the layout in place. The score tuple is compared without its trailing layout
722
+ * hash, which only breaks ties between equal layouts, and a tree that is off the centre of its
723
+ * bounding box is improved by recentring it even when the score tuple does not change.
724
+ */
725
+ function strictlyBetter(candidate, current) {
726
+ const left = compactScore(candidate).slice(0, -1);
727
+ const right = compactScore(current).slice(0, -1);
728
+ if (betterScore(left, right))
729
+ return true;
730
+ if (betterScore(right, left))
731
+ return false;
732
+ return (requiredMetrics(candidate).symmetry.boundingCenterOffsetTwice <
733
+ requiredMetrics(current).symmetry.boundingCenterOffsetTwice - 1);
734
+ }
616
735
  /**
617
736
  * Cooperative compact planning for protocol handlers. Candidate layouts share
618
737
  * one work budget, and the selected layout is returned for validation/rendering.
@@ -626,6 +745,8 @@ export async function compactFocusTreePlanAsync(plan, options = {}) {
626
745
  ...(options.signal === undefined ? {} : { signal: options.signal }),
627
746
  };
628
747
  const currentLayout = await layoutFocusTreeAsync(plan, layoutOptions);
748
+ if (alreadyPasses(plan, currentLayout, selection))
749
+ return nothingToImprove(plan, currentLayout, [], 'verdict_pass');
629
750
  const normalizedPlan = needsPresentationNormalization(plan)
630
751
  ? compactCandidate(plan, currentLayout, {
631
752
  scale: 1,
@@ -679,21 +800,35 @@ export async function compactFocusTreePlanAsync(plan, options = {}) {
679
800
  }
680
801
  if (fallback === undefined || betterScore(compactScore(layout), compactScore(fallback.layout)))
681
802
  fallback = { plan: candidate, layout };
682
- if ((selection.focusIds === undefined
683
- ? absoluteCompactRegressions(layout)
684
- : relativeCompactRegressions(currentLayout, layout)).length > 0)
803
+ if (candidateRegressions({ plan: candidate, layout }, { plan, layout: currentLayout }, selection.focusIds !== undefined).length > 0)
685
804
  continue;
686
805
  if (selected === undefined || betterScore(compactScore(layout), compactScore(selected.layout)))
687
806
  selected = { plan: candidate, layout };
688
807
  }
689
808
  if (selected !== undefined) {
690
- return { plan: selected.plan, currentLayout, proposedLayout: selected.layout };
809
+ if (!strictlyBetter(selected.layout, currentLayout))
810
+ return nothingToImprove(plan, currentLayout, [], 'no_better_candidate');
811
+ return {
812
+ plan: selected.plan,
813
+ currentLayout,
814
+ proposedLayout: selected.layout,
815
+ outcome: 'improved',
816
+ };
691
817
  }
692
818
  if (exhausted !== undefined)
693
819
  throw exhausted;
694
820
  if (fallback !== undefined) {
695
- assertCompactLayoutQuality(currentLayout, fallback.layout, selection.focusIds !== undefined);
696
- return { plan: fallback.plan, currentLayout, proposedLayout: fallback.layout };
821
+ const regressions = candidateRegressions({ plan: fallback.plan, layout: fallback.layout }, { plan, layout: currentLayout }, selection.focusIds !== undefined);
822
+ // Every candidate is worse than the layout in place on something the gate protects: keep it
823
+ // and name what blocked the best one.
824
+ if (regressions.length > 0)
825
+ return nothingToImprove(plan, currentLayout, regressions, 'candidates_regress');
826
+ return {
827
+ plan: fallback.plan,
828
+ currentLayout,
829
+ proposedLayout: fallback.layout,
830
+ outcome: 'improved',
831
+ };
697
832
  }
698
833
  if (blockedFocusIds.size > 0)
699
834
  throw new ServiceError('FOCUS_COMPACT_ANCHOR_CONFLICT', 'No compact candidate preserves the selected branch boundary and pinned anchors', { treeId: plan.id, movedFocusIds: [...blockedFocusIds].sort(compareCodeUnits) });
@@ -701,18 +836,62 @@ export async function compactFocusTreePlanAsync(plan, options = {}) {
701
836
  throw new ServiceError('FOCUS_COMPACT_SYMMETRY_CONFLICT', 'No compact candidate satisfies the requested symmetry pairs', { treeId: plan.id, pairs: blockedSymmetry });
702
837
  throw new ServiceError('FOCUS_COMPACT_LAYOUT_REQUIRED', 'Compact focus planning did not produce a measurable layout candidate', { treeId: plan.id });
703
838
  }
704
- /** Refuses compact rewrites that still contain invalid or unreadable geometry. */
705
- export function assertCompactLayoutQuality(_current, proposed, relativeToBaseline = false) {
706
- const regressions = [
707
- ...(relativeToBaseline && _current !== undefined
708
- ? relativeCompactRegressions(_current, proposed)
709
- : absoluteCompactRegressions(proposed)),
710
- ].filter((value, index, all) => all.indexOf(value) === index);
839
+ const REGRESSION_REMEDIES = {
840
+ hardLayoutDiagnostics: 'Fix the hard layout errors first (hoi4.focus_inspect lists them: overlaps, a prerequisite that is not above, lane bounds)',
841
+ connectorCrossingCount: 'Move one of the crossing connectors to another column, or declare the crossing group as a bundle by giving every parent the same children',
842
+ connectorNodeIntersections: 'Move the focus a connector runs through out of the column of its parent, or pass compactFocusIds for the branch and pinnedFocusIds for its neighbours',
843
+ sameRowSpacing: 'Keep focuses on one row at least 2 columns apart',
844
+ boundingCenter: 'Recentre the tree: pin the trunk and compact each side with compactFocusIds',
845
+ layoutVerdict: 'The candidate would be judged worse by hoi4.focus_inspect than the layout in place; compact only keeps layouts that are not worse',
846
+ };
847
+ function blockingItems(regressions, proposed, baseline) {
848
+ const after = readGate(proposed);
849
+ const before = baseline === undefined ? undefined : readGate(baseline);
850
+ const reading = {
851
+ layoutVerdict: [
852
+ baseline === undefined
853
+ ? undefined
854
+ : VERDICT_RANK[evaluateFocusLayoutQuality(baseline.plan, baseline.layout.nodes).report.verdict],
855
+ VERDICT_RANK[evaluateFocusLayoutQuality(proposed.plan, proposed.layout.nodes).report.verdict],
856
+ ],
857
+ hardLayoutDiagnostics: [before?.hardDiagnostics, after.hardDiagnostics],
858
+ connectorCrossingCount: [before?.crossings, after.crossings],
859
+ connectorNodeIntersections: [before?.stemsThroughPlaques, after.stemsThroughPlaques],
860
+ sameRowSpacing: [before?.tooCloseSameRow, after.tooCloseSameRow],
861
+ boundingCenter: [before?.boundingCenterOffsetTwice, after.boundingCenterOffsetTwice],
862
+ };
863
+ return regressions.map((name) => ({
864
+ name,
865
+ before: reading[name]?.[0] ?? null,
866
+ after: reading[name]?.[1] ?? 0,
867
+ remedy: REGRESSION_REMEDIES[name] ?? 'Inspect the layout and repair the named metric',
868
+ }));
869
+ }
870
+ /**
871
+ * Refuses compact rewrites that still contain invalid or unreadable geometry. With the plans, the
872
+ * check reads connectors in the in-game model, treats bundles as one bar and only refuses a layout
873
+ * that is worse than the one in place; without them it keeps the strict curved-connector gate.
874
+ */
875
+ export function assertCompactLayoutQuality(_current, proposed, relativeToBaseline = false, plans) {
876
+ const proposedSide = plans === undefined ? undefined : { plan: plans.proposed, layout: proposed };
877
+ const baselineSide = plans?.current === undefined || _current === undefined
878
+ ? undefined
879
+ : { plan: plans.current, layout: _current };
880
+ const regressions = (proposedSide !== undefined
881
+ ? candidateRegressions(proposedSide, baselineSide, relativeToBaseline)
882
+ : [
883
+ ...(relativeToBaseline && _current !== undefined
884
+ ? relativeCompactRegressions(_current, proposed)
885
+ : absoluteCompactRegressions(proposed)),
886
+ ]).filter((value, index, all) => all.indexOf(value) === index);
711
887
  if (regressions.length === 0)
712
888
  return;
713
889
  throw new ServiceError('FOCUS_COMPACT_QUALITY_BLOCKED', 'Compact focus reflow failed the layout-correctness gate', {
714
890
  treeId: proposed.treeId,
715
891
  regressions,
892
+ ...(proposedSide === undefined
893
+ ? {}
894
+ : { blocking: blockingItems(regressions, proposedSide, baselineSide) }),
716
895
  ...(_current === undefined ? {} : { before: requiredMetrics(_current) }),
717
896
  proposed: requiredMetrics(proposed),
718
897
  });
@@ -0,0 +1,201 @@
1
+ import { FOCUS_LAYOUT_REQUEST_SCHEMA, runFocusLayoutEngine, } from '../core/engine-client.js';
2
+ import { ServiceError } from '../core/result.js';
3
+ import { focusLaneId } from './layout.js';
4
+ export const FOCUS_ENGINE_REMEDY = 'Set HOI4_ENGINE to the absolute path of a hoi4-engine binary (cargo build --release -p hoi4-engine-cli in engine/), or install a hoi4-agent-tools release that ships the engine for this platform. layoutMode authored and compact do not need it.';
5
+ const MOVED_FOCUS_ID_LIMIT = 100;
6
+ function enginePosition(position) {
7
+ if (position.mode === 'fixed')
8
+ return { mode: 'fixed', x: position.x, y: position.y };
9
+ if (position.mode === 'relative')
10
+ return { mode: 'relative', x: position.x, y: position.y, relativeTo: position.relativeTo };
11
+ return {
12
+ mode: 'auto',
13
+ ...(position.preferredX === undefined ? {} : { preferredX: position.preferredX }),
14
+ ...(position.preferredY === undefined ? {} : { preferredY: position.preferredY }),
15
+ };
16
+ }
17
+ function placementError(message, details) {
18
+ return new ServiceError('FOCUS_PLACEMENT_INVALID', message, details);
19
+ }
20
+ /** The engine request for one tree; exported for tests. */
21
+ export function focusEngineLayoutRequest(input) {
22
+ const { plan, placement } = input;
23
+ const focusIds = new Set(plan.focuses.map(({ id }) => id));
24
+ const placed = new Set(placement?.focusIds ?? []);
25
+ if (placement !== undefined) {
26
+ const missing = placement.focusIds.filter((id) => !focusIds.has(id));
27
+ if (missing.length > 0)
28
+ throw placementError('placement.focusIds names focuses that are not in the plan', {
29
+ focusIds: missing.slice(0, 100),
30
+ });
31
+ if (input.layoutMode === 'authored' && input.currentFocusIds !== undefined) {
32
+ const existing = placement.focusIds.filter((id) => input.currentFocusIds?.has(id));
33
+ if (existing.length > 0)
34
+ throw placementError('placement in authored layout mode places only focuses the plan adds; use layoutMode engine to move existing focuses', { focusIds: existing.slice(0, 100) });
35
+ }
36
+ const pinned = plan.focuses
37
+ .filter(({ id, position }) => placed.has(id) && position.pinned)
38
+ .map(({ id }) => id);
39
+ if (pinned.length > 0)
40
+ throw placementError('placement.focusIds names pinned focuses, which keep their coordinates', {
41
+ focusIds: pinned.slice(0, 100),
42
+ });
43
+ }
44
+ const unplaced = [];
45
+ const focuses = plan.focuses.map((focus) => {
46
+ let position;
47
+ if (placed.has(focus.id))
48
+ position = focus.position.mode === 'auto' ? enginePosition(focus.position) : { mode: 'auto' };
49
+ else if (placement !== undefined && focus.position.mode === 'auto') {
50
+ const current = input.currentSourcePositions?.get(focus.id);
51
+ if (current === undefined || current.mode === 'auto') {
52
+ unplaced.push(focus.id);
53
+ position = { mode: 'auto' };
54
+ }
55
+ else
56
+ position = enginePosition(current);
57
+ }
58
+ else
59
+ position = enginePosition(focus.position);
60
+ return {
61
+ id: focus.id,
62
+ prerequisites: focus.prerequisites.groups.map(({ focusIds: members }) => [...members]),
63
+ mutuallyExclusive: [...focus.mutuallyExclusive],
64
+ laneId: focusLaneId(plan, focus),
65
+ position,
66
+ pinned: focus.position.mode !== 'auto' && focus.position.pinned,
67
+ };
68
+ });
69
+ if (unplaced.length > 0)
70
+ throw placementError('placement keeps every other focus where it is, but these automatic focuses have no coordinates yet; add them to placement.focusIds or give them x and y', { focusIds: unplaced.slice(0, 100) });
71
+ return {
72
+ schema: FOCUS_LAYOUT_REQUEST_SCHEMA,
73
+ operation: placement === undefined ? 'layout' : 'insert',
74
+ treeId: plan.id,
75
+ lanes: plan.laneGroups.map((lane) => ({
76
+ id: lane.id,
77
+ order: lane.order,
78
+ ...(lane.minimumX === undefined ? {} : { minimumX: lane.minimumX }),
79
+ ...(lane.maximumX === undefined ? {} : { maximumX: lane.maximumX }),
80
+ })),
81
+ focuses,
82
+ ...(placement === undefined
83
+ ? {}
84
+ : {
85
+ insert: {
86
+ focusIds: [...placement.focusIds],
87
+ ...(placement.anchorId === undefined ? {} : { anchorId: placement.anchorId }),
88
+ ...(placement.preferSide === undefined ? {} : { preferSide: placement.preferSide }),
89
+ ...(placement.allowShift === undefined ? {} : { allowShift: placement.allowShift }),
90
+ },
91
+ }),
92
+ };
93
+ }
94
+ /** Engine diagnostics as tool diagnostics; their codes already carry the FOCUS_ENGINE_ prefix. */
95
+ export function focusEngineDiagnostics(response) {
96
+ return response.diagnostics.map((entry) => ({
97
+ code: entry.code,
98
+ severity: entry.severity,
99
+ category: 'layout',
100
+ message: entry.message,
101
+ details: { ...entry.details, focusIds: entry.focusIds.slice(0, 100) },
102
+ }));
103
+ }
104
+ /** The plan with the engine's coordinates: `source` entries become fixed or relative positions. */
105
+ export function applyFocusEngineSource(plan, response) {
106
+ const source = new Map(response.source.map((entry) => [entry.id, entry]));
107
+ return {
108
+ ...plan,
109
+ focuses: plan.focuses.map((focus) => {
110
+ const entry = source.get(focus.id);
111
+ if (entry === undefined)
112
+ throw new ServiceError('FOCUS_ENGINE_LAYOUT_MISMATCH', `The focus layout engine returned no position for ${focus.id}`, { focusId: focus.id });
113
+ const pinned = focus.position.mode !== 'auto' && focus.position.pinned;
114
+ const position = entry.relativeTo === undefined
115
+ ? { mode: 'fixed', x: entry.x, y: entry.y, pinned }
116
+ : { mode: 'relative', x: entry.x, y: entry.y, relativeTo: entry.relativeTo, pinned };
117
+ return { ...focus, position };
118
+ }),
119
+ };
120
+ }
121
+ /** Refuse when the layout that will be written differs from the engine's nodes. */
122
+ export function assertFocusEngineLayoutWritten(response, nodes) {
123
+ const written = new Map(nodes.map((node) => [node.id, node]));
124
+ const differing = response.nodes
125
+ .filter((node) => {
126
+ const actual = written.get(node.id);
127
+ return actual?.x !== node.x || actual.y !== node.y;
128
+ })
129
+ .map(({ id }) => id);
130
+ if (differing.length > 0 || written.size !== response.nodes.length)
131
+ throw new ServiceError('FOCUS_ENGINE_LAYOUT_MISMATCH', 'The coordinates prepared for the source differ from the focus layout engine result; nothing was written', { focusIds: differing.slice(0, 100) });
132
+ }
133
+ const BLOCKED_TEXT_LIMIT = 1_200;
134
+ /**
135
+ * The refusal text carries the engine's reasons and needsRoom, because a failed rewrite reports
136
+ * only its code and message to the agent.
137
+ */
138
+ function blockedMessage(response, diagnostics) {
139
+ const reasons = diagnostics
140
+ .filter(({ severity }) => severity === 'error')
141
+ .slice(0, 3)
142
+ .map(({ code, message, details }) => {
143
+ const ids = details?.focusIds ?? [];
144
+ return `${code}: ${message}${ids.length === 0 ? '' : ` (${ids.slice(0, 8).join(', ')})`}`;
145
+ });
146
+ const text = [
147
+ response.needsRoom === undefined
148
+ ? 'The focus layout engine cannot place the tree without breaking a layout rule. Nothing was written.'
149
+ : 'There is no free place for the new focuses. Nothing was written. Set placement.allowShift to apply the shift in needsRoom, or move the listed focuses yourself.',
150
+ ...reasons,
151
+ ...(response.needsRoom === undefined
152
+ ? []
153
+ : [`needsRoom: ${JSON.stringify(response.needsRoom)}`]),
154
+ ].join(' ');
155
+ return text.length <= BLOCKED_TEXT_LIMIT ? text : `${text.slice(0, BLOCKED_TEXT_LIMIT)}…`;
156
+ }
157
+ /** Run the engine for one tree. Refuses (never falls back) when the engine is unavailable. */
158
+ export async function layoutFocusTreeWithEngine(input, options = {}) {
159
+ const request = focusEngineLayoutRequest(input);
160
+ const result = await runFocusLayoutEngine(request, options);
161
+ if (result.outcome === 'unavailable')
162
+ throw new ServiceError('FOCUS_ENGINE_UNAVAILABLE', `The focus layout engine is unavailable (${result.reason}): ${result.message}. Nothing was written. ${FOCUS_ENGINE_REMEDY}`, {
163
+ reason: result.reason,
164
+ message: result.message,
165
+ remedy: FOCUS_ENGINE_REMEDY,
166
+ ...(result.binary === undefined ? {} : { binarySource: result.binary.source }),
167
+ });
168
+ if (result.outcome === 'invalid_request')
169
+ throw new ServiceError('FOCUS_ENGINE_REQUEST_INVALID', `The focus layout engine refused the tree: ${result.error.message}`, { engineCode: result.error.code, message: result.error.message });
170
+ const { response } = result;
171
+ const diagnostics = focusEngineDiagnostics(response);
172
+ if (response.status === 'blocked' || response.metrics === null)
173
+ throw new ServiceError('FOCUS_ENGINE_BLOCKED', blockedMessage(response, diagnostics), {
174
+ operation: response.operation,
175
+ ...(response.needsRoom === undefined ? {} : { needsRoom: response.needsRoom }),
176
+ diagnostics: diagnostics.slice(0, 20).map(({ code, severity, message, details }) => ({
177
+ code,
178
+ severity,
179
+ message,
180
+ details,
181
+ })),
182
+ hashes: response.hashes,
183
+ });
184
+ const { durationMicros: _durationMicros, ...metrics } = response.metrics;
185
+ const moved = response.nodes.filter(({ moved: changed }) => changed).map(({ id }) => id);
186
+ return {
187
+ plan: applyFocusEngineSource(input.plan, response),
188
+ response,
189
+ diagnostics,
190
+ summary: {
191
+ operation: response.operation,
192
+ status: 'ok',
193
+ hashes: response.hashes,
194
+ metrics,
195
+ movedFocusIds: moved.slice(0, MOVED_FOCUS_ID_LIMIT),
196
+ movedFocusCount: moved.length,
197
+ ...(response.shifted === undefined ? {} : { shifted: response.shifted }),
198
+ binarySource: result.binary.source,
199
+ },
200
+ };
201
+ }
@@ -22,7 +22,9 @@ export function registerFocusJobs(operations, engine) {
22
22
  signal: context.signal,
23
23
  progress: (completed, total, message) => context.progress({ completed, total, message }),
24
24
  });
25
- const wire = wireResult.parse(JSON.parse(JSON.stringify(toolResult(execution.result))));
25
+ const wire = wireResult.parse(JSON.parse(JSON.stringify(toolResult(execution.result, {
26
+ ...(execution.images === undefined ? {} : { images: execution.images }),
27
+ }))));
26
28
  await context.stageResult(wire, { sourceRevision: execution.sourceRevision });
27
29
  return wire;
28
30
  }
@@ -82,7 +82,8 @@ const LONG_CONNECTOR_MANHATTAN_SPAN = 10;
82
82
  function coordinateKey(x, y) {
83
83
  return `${x},${y}`;
84
84
  }
85
- function laneFor(plan, focus) {
85
+ /** The lane a focus is laid out in: its own lane, its branch's lane, its branch, or 'default'. */
86
+ export function focusLaneId(plan, focus) {
86
87
  if (focus.laneId !== undefined)
87
88
  return focus.laneId;
88
89
  if (focus.branchId !== undefined) {
@@ -2228,7 +2229,7 @@ function* layoutFocusTreeSteps(plan, options = {}) {
2228
2229
  }
2229
2230
  focuses.set(focus.id, focus);
2230
2231
  }
2231
- const laneIds = new Map([...focuses.values()].map((focus) => [focus.id, laneFor(plan, focus)]));
2232
+ const laneIds = new Map([...focuses.values()].map((focus) => [focus.id, focusLaneId(plan, focus)]));
2232
2233
  const discoveredLanes = [...new Set(laneIds.values())].sort((left, right) => compareCodeUnits(left, right));
2233
2234
  const nodeSpacing = options.nodeSpacing ?? DEFAULT_NODE_SPACING;
2234
2235
  const siblingLayout = automaticSiblingLayout(plan, focuses, laneIds, nodeSpacing);
@@ -0,0 +1,32 @@
1
+ import { compareCodeUnits } from '../../core/canonical.js';
2
+ /** Groups focuses by their declared or derived branch; trunk and shared focuses form no branch. */
3
+ export function summarizeBranches(graph) {
4
+ const groups = new Map();
5
+ for (const { id } of graph.nodes) {
6
+ const branch = graph.branchOf.get(id) ?? '';
7
+ if (branch === '')
8
+ continue;
9
+ const members = groups.get(branch) ?? [];
10
+ members.push(id);
11
+ groups.set(branch, members);
12
+ }
13
+ return [...groups]
14
+ .map(([branchId, focusIds]) => {
15
+ const points = focusIds.map((focusId) => graph.position.get(focusId));
16
+ const xs = points.map(({ x }) => x);
17
+ const ys = points.map(({ y }) => y);
18
+ return {
19
+ id: branchId,
20
+ declared: graph.branchesDeclared,
21
+ focusCount: focusIds.length,
22
+ focusIds,
23
+ minimumX: Math.min(...xs),
24
+ maximumX: Math.max(...xs),
25
+ minimumY: Math.min(...ys),
26
+ maximumY: Math.max(...ys),
27
+ centroidX: xs.reduce((total, x) => total + x, 0) / xs.length,
28
+ centroidY: ys.reduce((total, y) => total + y, 0) / ys.length,
29
+ };
30
+ })
31
+ .sort((a, b) => a.minimumX - b.minimumX || compareCodeUnits(a.id, b.id));
32
+ }