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
@@ -0,0 +1,549 @@
1
+ import { compareCodeUnits } from '../../core/canonical.js';
2
+ import { calibrationBucketFor, limitsFor, softMetricStatus, softVerdict, QUALITY_METRICS, qualityMetricInfo, supportsSoftMetrics, bucketIdForFocusCount, } from './calibration.js';
3
+ import { summarizeBranches } from './branches.js';
4
+ import { CONVERGENCE_ROW_WINDOW } from './metrics.js';
5
+ const WHERE_LIMIT = 8;
6
+ const STATUS_ORDER = {
7
+ blocked: 0,
8
+ revise: 1,
9
+ review: 2,
10
+ flag: 3,
11
+ ok: 4,
12
+ not_evaluated: 5,
13
+ };
14
+ /** What the tool never judges; echoed in every response so "ok" cannot read as "done". */
15
+ export const QUALITY_NOT_EVALUATED = [
16
+ 'gameplay and balance',
17
+ 'visual review: call hoi4.focus_render and look at the image',
18
+ 'in-game connector geometry: the orthogonal model is read from one screenshot and is advisory until confirmed in the game',
19
+ ];
20
+ function format(value) {
21
+ if (Number.isInteger(value))
22
+ return String(value);
23
+ return Math.abs(value) >= 10 ? value.toFixed(1) : value.toFixed(2);
24
+ }
25
+ function percent(value) {
26
+ return `${Math.round(value * 100)}%`;
27
+ }
28
+ function cap(ids) {
29
+ return ids.slice(0, WHERE_LIMIT);
30
+ }
31
+ function listIds(ids, limit = 4) {
32
+ const shown = ids.slice(0, limit).join(', ');
33
+ return ids.length > limit ? `${shown} and ${ids.length - limit} more` : shown;
34
+ }
35
+ function exceeds(info, value, limit) {
36
+ return info.direction === 'high' ? value > limit : value < limit;
37
+ }
38
+ function nearestBranches(branches, centreX, centreY, count = 2) {
39
+ return branches
40
+ .filter(({ id }) => id !== '')
41
+ .map((branch) => ({
42
+ branch,
43
+ distance: Math.hypot(branch.centroidX - centreX, (branch.centroidY - centreY) * 2),
44
+ }))
45
+ .sort((a, b) => a.distance - b.distance || compareCodeUnits(a.branch.id, b.branch.id))
46
+ .slice(0, count)
47
+ .map(({ branch }) => branch);
48
+ }
49
+ function draftFor(id, measurement, graph, branches) {
50
+ const { locators, counts, values, width, rows, nodeCount } = measurement;
51
+ const value = values[id] ?? 0;
52
+ const position = (focusId) => graph.position.get(focusId);
53
+ switch (id) {
54
+ case 'H1': {
55
+ const first = locators.duplicateCoordinates[0];
56
+ return {
57
+ where: cap(locators.duplicateCoordinates.flatMap(({ focusIds }) => focusIds)),
58
+ message: first === undefined
59
+ ? 'No two focuses share a coordinate'
60
+ : `${listIds(first.focusIds)} share (${first.x}, ${first.y}); give each its own grid cell`,
61
+ ...(first === undefined
62
+ ? {}
63
+ : {
64
+ fix: {
65
+ action: 'separate_focuses',
66
+ targetFocusIds: cap(first.focusIds.slice(1)),
67
+ suggested: `Move ${first.focusIds[1]} to a free cell on row ${first.y}, at least 2 columns from its neighbours`,
68
+ expectedMetricChange: 'H1 reaches 0',
69
+ preservesGameplay: true,
70
+ },
71
+ }),
72
+ };
73
+ }
74
+ case 'H2': {
75
+ const first = locators.parentNotAbove[0];
76
+ return {
77
+ where: cap(locators.parentNotAbove.flatMap(({ parentId, childId }) => [parentId, childId])),
78
+ message: first === undefined
79
+ ? 'Every prerequisite sits above its dependants'
80
+ : `${first.parentId} is not above ${first.childId}; a prerequisite must sit on an earlier row`,
81
+ ...(first === undefined
82
+ ? {}
83
+ : {
84
+ fix: {
85
+ action: 'move_prerequisite_up',
86
+ targetFocusIds: [first.childId],
87
+ suggested: `Move ${first.childId} to row ${position(first.parentId).y + 1} or lower`,
88
+ expectedMetricChange: 'H2 reaches 0',
89
+ preservesGameplay: true,
90
+ },
91
+ }),
92
+ };
93
+ }
94
+ case 'H3': {
95
+ const first = locators.overlaps[0];
96
+ return {
97
+ where: cap(locators.overlaps.flatMap(({ leftId, rightId }) => [leftId, rightId])),
98
+ message: first === undefined
99
+ ? 'No two plaques overlap on a row'
100
+ : `${first.leftId} and ${first.rightId} are ${format(first.distance)} column apart on row ${first.y}, but a plaque is about 1.6 columns wide; spread them to 2`,
101
+ ...(first === undefined
102
+ ? {}
103
+ : {
104
+ fix: {
105
+ action: 'separate_focuses',
106
+ targetFocusIds: [first.rightId],
107
+ suggested: `Move ${first.rightId} to x=${position(first.leftId).x + 2} (or ${first.leftId} to x=${position(first.rightId).x - 2})`,
108
+ expectedMetricChange: `H3 falls from ${counts.overlaps} to ${Math.max(0, counts.overlaps - 1)} or less`,
109
+ preservesGameplay: true,
110
+ },
111
+ }),
112
+ };
113
+ }
114
+ case 'H4': {
115
+ const first = locators.stemsThroughPlaques[0];
116
+ return {
117
+ where: cap(locators.stemsThroughPlaques.flatMap(({ parentId, childId, focusId }) => [
118
+ parentId,
119
+ childId,
120
+ focusId,
121
+ ])),
122
+ message: first === undefined
123
+ ? 'No connector runs through an unrelated plaque'
124
+ : `${counts.stemsThroughPlaques} connector stems run through plaques; ${first.parentId} to ${first.childId} passes ${first.focusId}`,
125
+ ...(first === undefined
126
+ ? {}
127
+ : {
128
+ fix: {
129
+ action: 'reroute_connector',
130
+ targetFocusIds: [first.focusId],
131
+ suggested: `Move ${first.focusId} out of the column of ${first.parentId}, or move ${first.childId} closer to ${first.parentId}`,
132
+ expectedMetricChange: 'H4 falls toward 0 per 100 links',
133
+ preservesGameplay: true,
134
+ },
135
+ }),
136
+ };
137
+ }
138
+ case 'H5': {
139
+ const first = locators.crossings[0];
140
+ return {
141
+ where: cap(locators.crossings.flatMap(({ firstParentId, firstChildId, secondParentId, secondChildId }) => [
142
+ firstParentId,
143
+ firstChildId,
144
+ secondParentId,
145
+ secondChildId,
146
+ ])),
147
+ message: first === undefined
148
+ ? 'No unrelated connectors cross'
149
+ : `${counts.crossings} unrelated connectors cross; ${first.firstParentId} to ${first.firstChildId} crosses ${first.secondParentId} to ${first.secondChildId}`,
150
+ ...(first === undefined
151
+ ? {}
152
+ : {
153
+ fix: {
154
+ action: 'reroute_connector',
155
+ targetFocusIds: [first.firstChildId, first.secondChildId],
156
+ suggested: `Swap the columns of ${first.firstChildId} and ${first.secondChildId}, or move one of them to the other side of ${first.firstParentId}`,
157
+ expectedMetricChange: 'H5 falls toward 0 per 100 links',
158
+ preservesGameplay: true,
159
+ },
160
+ }),
161
+ };
162
+ }
163
+ case 'S1': {
164
+ const region = locators.emptyRectangle;
165
+ if (region === null)
166
+ return { where: [], message: 'No empty area' };
167
+ const near = nearestBranches(branches, (region.minimumX + region.maximumX) / 2, (region.minimumY + region.maximumY) / 2);
168
+ return {
169
+ where: cap(near.map(({ id }) => id)),
170
+ message: `A ${region.maximumX - region.minimumX + 1} by ${region.maximumY - region.minimumY + 1} cell area (${percent(value)} of the canvas) is empty at columns ${region.minimumX} to ${region.maximumX}, rows ${region.minimumY} to ${region.maximumY}${near.length > 0 ? `; nearest branches: ${near.map(({ id }) => id).join(', ')}` : ''}`,
171
+ fix: {
172
+ action: 'fill_empty_area',
173
+ targetFocusIds: cap(near.map(({ id }) => id)),
174
+ suggested: 'Lengthen the short branch, move it under the heavier branch, or recentre the trunk on the heavier subtree; this is a design call',
175
+ expectedMetricChange: `S1 falls from ${format(value)} toward the vanilla median`,
176
+ preservesGameplay: true,
177
+ },
178
+ };
179
+ }
180
+ case 'S2':
181
+ case 'S3': {
182
+ const heavySide = locators.sides.left >= locators.sides.right ? 'left' : 'right';
183
+ const heavy = branches
184
+ .filter(({ id, centroidX }) => id !== '' &&
185
+ (heavySide === 'left'
186
+ ? centroidX < locators.sides.centre
187
+ : centroidX > locators.sides.centre))
188
+ .sort((a, b) => b.focusCount - a.focusCount || compareCodeUnits(a.id, b.id))[0];
189
+ return {
190
+ where: heavy === undefined ? [] : [heavy.id],
191
+ message: id === 'S2'
192
+ ? `${locators.sides.left} focuses sit left of column ${format(locators.sides.centre)} and ${locators.sides.right} right of it`
193
+ : `The focus mass sits ${format(value * 100)}% of the half width off the canvas centre`,
194
+ fix: {
195
+ action: 'rebalance_branches',
196
+ targetFocusIds: heavy === undefined ? [] : [heavy.id],
197
+ suggested: `Recentre the trunk on the ${heavySide} side${heavy === undefined ? '' : ` (largest branch: ${heavy.id}, ${heavy.focusCount} focuses)`}, or move a branch to the lighter side`,
198
+ expectedMetricChange: `${id} falls from ${format(value)} toward the vanilla median`,
199
+ preservesGameplay: true,
200
+ },
201
+ };
202
+ }
203
+ case 'S4':
204
+ return {
205
+ where: [],
206
+ message: `${nodeCount} focuses cover ${width + 1} columns by ${rows} rows, a fill of ${format(value)}`,
207
+ fix: {
208
+ action: 'tighten_layout',
209
+ targetFocusIds: [],
210
+ suggested: 'Pull lanes closer together and close empty rows with focus_rewrite layoutMode compact',
211
+ expectedMetricChange: `S4 rises from ${format(value)} toward the vanilla median`,
212
+ preservesGameplay: true,
213
+ },
214
+ };
215
+ case 'S5': {
216
+ const centroids = locators.rowCentroids;
217
+ return {
218
+ where: [],
219
+ message: centroids === null
220
+ ? 'Row centres stay aligned'
221
+ : `Row centres wander ${format(centroids.maximumMean - centroids.minimumMean)} columns: row ${centroids.minimumRow} is centred at x=${format(centroids.minimumMean)} and row ${centroids.maximumRow} at x=${format(centroids.maximumMean)}`,
222
+ fix: {
223
+ action: 'straighten_trunk',
224
+ targetFocusIds: [],
225
+ suggested: 'Straighten the trunk so each generation stays under its parent instead of stepping sideways',
226
+ expectedMetricChange: `S5 falls from ${format(value)} toward the vanilla median`,
227
+ preservesGameplay: true,
228
+ },
229
+ };
230
+ }
231
+ case 'S6': {
232
+ const first = locators.detours[0];
233
+ return {
234
+ where: cap(locators.detours.flatMap(({ parentId, childId }) => [parentId, childId])),
235
+ message: first === undefined
236
+ ? 'Single-focus chains run straight down'
237
+ : `${counts.detours} single-focus links jog sideways; ${first.parentId} to ${first.childId} is ${Math.abs(first.dx)} column${Math.abs(first.dx) === 1 ? '' : 's'} off`,
238
+ ...(first === undefined
239
+ ? {}
240
+ : {
241
+ fix: {
242
+ action: 'align_under_parent',
243
+ targetFocusIds: cap(locators.detours.map(({ childId }) => childId)),
244
+ suggested: `Place ${first.childId} at x=${position(first.parentId).x}, directly under ${first.parentId}, together with its subtree`,
245
+ expectedMetricChange: `S6 falls by ${format(100 / Math.max(1, measurement.edgeCount))} per 100 links per straightened link`,
246
+ preservesGameplay: true,
247
+ },
248
+ }),
249
+ };
250
+ }
251
+ case 'S7': {
252
+ const first = locators.interleavedPairs[0];
253
+ return {
254
+ where: cap(locators.interleavedPairs.flatMap(({ firstChildId, secondChildId }) => [
255
+ firstChildId,
256
+ secondChildId,
257
+ ])),
258
+ message: first === undefined
259
+ ? 'Sibling subtrees stay in their own columns'
260
+ : `The subtrees of ${first.firstChildId} and ${first.secondChildId} (children of ${first.parentId}) share columns on the same rows`,
261
+ ...(first === undefined
262
+ ? {}
263
+ : {
264
+ fix: {
265
+ action: 'untangle_siblings',
266
+ targetFocusIds: [first.firstChildId, first.secondChildId],
267
+ suggested: `Give ${first.firstChildId} and ${first.secondChildId} separate column bands`,
268
+ expectedMetricChange: 'S7 falls toward 0',
269
+ preservesGameplay: true,
270
+ },
271
+ }),
272
+ };
273
+ }
274
+ case 'S8': {
275
+ const first = locators.offCenterCohorts[0];
276
+ return {
277
+ where: cap(locators.offCenterCohorts.flatMap(({ parentId, childIds }) => [parentId, ...childIds])),
278
+ message: first === undefined
279
+ ? 'Fan-outs are centred under their parents'
280
+ : `Children of ${first.parentId} (${listIds(first.childIds)}) are centred at x=${format(first.centre)} but ${first.parentId} is at x=${position(first.parentId).x}`,
281
+ ...(first === undefined
282
+ ? {}
283
+ : {
284
+ fix: {
285
+ action: 'recentre_cohort',
286
+ targetFocusIds: cap(first.childIds),
287
+ suggested: `Move the children by ${format(position(first.parentId).x - first.centre)} columns, or move ${first.parentId} to x=${format(first.centre)}`,
288
+ expectedMetricChange: 'S8 for this fan-out falls to 0',
289
+ preservesGameplay: true,
290
+ },
291
+ }),
292
+ };
293
+ }
294
+ case 'S9': {
295
+ const first = locators.mergedBars[0];
296
+ return {
297
+ where: cap(locators.mergedBars.flatMap(({ firstParentId, firstChildId, secondParentId, secondChildId }) => [
298
+ firstParentId,
299
+ firstChildId,
300
+ secondParentId,
301
+ secondChildId,
302
+ ])),
303
+ message: first === undefined
304
+ ? 'No unrelated connectors share a bar'
305
+ : `${counts.mergedBars} pairs of unrelated connectors share a bar or stem; ${first.firstParentId} to ${first.firstChildId} overlaps ${first.secondParentId} to ${first.secondChildId}`,
306
+ ...(first === undefined
307
+ ? {}
308
+ : {
309
+ fix: {
310
+ action: 'reroute_connector',
311
+ targetFocusIds: [first.firstChildId, first.secondChildId],
312
+ suggested: 'Offset one child by a column so the two connectors no longer share a bar',
313
+ expectedMetricChange: 'S9 falls toward 0 per 100 links',
314
+ preservesGameplay: true,
315
+ },
316
+ }),
317
+ };
318
+ }
319
+ case 'S10': {
320
+ const first = locators.slackChildren[0];
321
+ return {
322
+ where: cap(locators.slackChildren.map(({ childId }) => childId)),
323
+ message: first === undefined
324
+ ? 'No focus waits below an empty row'
325
+ : `${first.childId} sits ${first.slack} row${first.slack === 1 ? '' : 's'} below the row after its lowest prerequisite`,
326
+ ...(first === undefined
327
+ ? {}
328
+ : {
329
+ fix: {
330
+ action: 'close_row_gap',
331
+ targetFocusIds: [first.childId],
332
+ suggested: `Move ${first.childId} and its subtree up ${first.slack} row${first.slack === 1 ? '' : 's'}`,
333
+ expectedMetricChange: 'S10 falls toward 1',
334
+ preservesGameplay: true,
335
+ },
336
+ }),
337
+ };
338
+ }
339
+ case 'S11': {
340
+ const first = locators.mixedRowCohorts[0];
341
+ return {
342
+ where: cap(locators.mixedRowCohorts.flatMap(({ parentId, childIds }) => [parentId, ...childIds])),
343
+ message: first === undefined
344
+ ? 'Sibling groups sit on one row'
345
+ : `Children of ${first.parentId} (${listIds(first.childIds)}) sit on different rows`,
346
+ ...(first === undefined
347
+ ? {}
348
+ : {
349
+ fix: {
350
+ action: 'tighten_layout',
351
+ targetFocusIds: cap(first.childIds),
352
+ suggested: `Put the children of ${first.parentId} on one row unless the stagger is intended`,
353
+ expectedMetricChange: 'S11 falls toward 0',
354
+ preservesGameplay: true,
355
+ },
356
+ }),
357
+ };
358
+ }
359
+ case 'D1':
360
+ return {
361
+ where: cap(locators.longestChain),
362
+ message: `${locators.longestChain.length} single-successor focuses in a row (${locators.longestChain[0]} to ${locators.longestChain[locators.longestChain.length - 1]}); the player makes no choice along the way`,
363
+ fix: {
364
+ action: 'review_design',
365
+ targetFocusIds: cap(locators.longestChain),
366
+ suggested: 'Merge steps, add a branch or a choice, or confirm the chain is intended',
367
+ expectedMetricChange: 'D1 falls to the vanilla range',
368
+ preservesGameplay: false,
369
+ },
370
+ };
371
+ case 'D2':
372
+ return {
373
+ where: [],
374
+ message: `${counts.leaves} of ${nodeCount} focuses (${percent(value)}) are leaves with no follow-up`,
375
+ fix: {
376
+ action: 'review_design',
377
+ targetFocusIds: [],
378
+ suggested: 'Check that every leaf is a real payoff or give it a follow-up',
379
+ expectedMetricChange: 'D2 falls to the vanilla range',
380
+ preservesGameplay: false,
381
+ },
382
+ };
383
+ case 'D3': {
384
+ const first = locators.convergingChoices[0];
385
+ return {
386
+ where: cap(locators.convergingChoices.flatMap(({ choiceIds, convergenceId }) => [
387
+ ...choiceIds,
388
+ convergenceId,
389
+ ])),
390
+ message: first === undefined
391
+ ? 'Exclusive choices keep distinct outcomes'
392
+ : `Choices ${listIds(first.choiceIds)} all reconverge at ${first.convergenceId}, ${first.rows} rows later (within ${CONVERGENCE_ROW_WINDOW} rows), so the exclusivity has no lasting consequence in the drawn tree`,
393
+ ...(first === undefined
394
+ ? {}
395
+ : {
396
+ fix: {
397
+ action: 'review_design',
398
+ targetFocusIds: cap([...first.choiceIds, first.convergenceId]),
399
+ suggested: 'Confirm the brief wants the choices to rejoin, or give each route its own continuation',
400
+ expectedMetricChange: 'D3 reaches 0 or is confirmed intended',
401
+ preservesGameplay: false,
402
+ },
403
+ }),
404
+ };
405
+ }
406
+ case 'D4':
407
+ return {
408
+ where: [],
409
+ message: `The canvas is ${rows} rows tall for ${format(width / 2)} plaque columns, which reads as a ribbon`,
410
+ fix: {
411
+ action: 'review_design',
412
+ targetFocusIds: [],
413
+ suggested: 'Add parallel lanes or shorten the tree so it reads as a shape',
414
+ expectedMetricChange: 'D4 falls below 2.5',
415
+ preservesGameplay: false,
416
+ },
417
+ };
418
+ }
419
+ }
420
+ function excessRatio(info, value, limits) {
421
+ const span = Math.abs(limits.revise - limits.review);
422
+ const beyond = info.direction === 'high' ? value - limits.review : limits.review - value;
423
+ if (beyond <= 0)
424
+ return 0;
425
+ return span > 0 ? beyond / span : 1;
426
+ }
427
+ /** Applies the calibration to a measurement and produces the verdict, scorecard and fix hints. */
428
+ export function reportLayoutQuality(graph, measurement, calibration, options = {}) {
429
+ const focusCount = measurement.nodeCount;
430
+ const bucketId = bucketIdForFocusCount(focusCount);
431
+ const bucket = calibrationBucketFor(calibration, focusCount);
432
+ const softEvaluated = supportsSoftMetrics(focusCount);
433
+ const rules = calibration.verdictRules;
434
+ const branches = summarizeBranches(graph);
435
+ const vanillaMedian = (id) => bucket.statistics[id]?.p50 ?? null;
436
+ const rows = [];
437
+ let scorePenalty = 0;
438
+ for (const info of QUALITY_METRICS) {
439
+ const value = measurement.values[info.id];
440
+ if (value === undefined)
441
+ continue;
442
+ const limits = limitsFor(bucket, info.id);
443
+ const draft = draftFor(info.id, measurement, graph, branches);
444
+ const isSoft = info.group !== 'H' || info.calibrated;
445
+ const inVerdict = info.id !== 'S8';
446
+ // Limits are stored with four decimals, so compare the value at the same precision.
447
+ const comparable = Number(value.toFixed(4));
448
+ let status = 'ok';
449
+ if (!softEvaluated && (isSoft || info.group === 'D'))
450
+ status = 'not_evaluated';
451
+ else if (info.group === 'H' && !info.calibrated)
452
+ status = value > 0 ? 'blocked' : 'ok';
453
+ else if (info.group === 'D') {
454
+ const flagLimit = limits?.revise ?? Number.POSITIVE_INFINITY;
455
+ status = exceeds(info, comparable, flagLimit) ? 'flag' : 'ok';
456
+ }
457
+ else if (limits !== undefined) {
458
+ status = softMetricStatus(info.id, value, limits, bucketId, rules);
459
+ }
460
+ const row = {
461
+ id: info.id,
462
+ name: info.name,
463
+ group: info.group,
464
+ value: Number(value.toFixed(4)),
465
+ unit: info.unit,
466
+ reviewLimit: limits?.review ?? null,
467
+ reviseLimit: limits?.revise ?? null,
468
+ vanillaMedian: vanillaMedian(info.id),
469
+ status,
470
+ inVerdict,
471
+ where: status === 'ok' || status === 'not_evaluated' ? [] : draft.where,
472
+ message: draft.message,
473
+ ...(draft.fix === undefined || status === 'ok' || status === 'not_evaluated'
474
+ ? {}
475
+ : { fix: draft.fix }),
476
+ };
477
+ rows.push(row);
478
+ if (status === 'blocked')
479
+ scorePenalty += 25;
480
+ else if (status === 'flag')
481
+ scorePenalty += 5;
482
+ else if (limits !== undefined && inVerdict && info.calibrated) {
483
+ const weight = calibration.scoreWeights[info.id] ?? 1;
484
+ scorePenalty += weight * Math.min(2, excessRatio(info, value, limits)) * 20;
485
+ }
486
+ }
487
+ const scoredRows = rows.filter(({ inVerdict, group, id: rowId }) => inVerdict && (group === 'S' || rowId === 'H4' || rowId === 'H5'));
488
+ const beyondReview = scoredRows.filter(({ status }) => status === 'review' || status === 'revise');
489
+ const flags = rows.filter(({ status }) => status === 'flag');
490
+ const soft = softVerdict(scoredRows.flatMap(({ id: rowId, status }) => status === 'ok' || status === 'review' || status === 'revise' ? [{ id: rowId, status }] : []), bucketId, rules);
491
+ let verdict = 'pass';
492
+ if (rows.some(({ status }) => status === 'blocked'))
493
+ verdict = 'blocked';
494
+ else if (soft === 'revise')
495
+ verdict = 'revise';
496
+ else if (soft === 'review' || flags.length > 0)
497
+ verdict = 'review';
498
+ rows.sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] ||
499
+ a.group.localeCompare(b.group) ||
500
+ compareCodeUnits(a.id, b.id));
501
+ const parts = [];
502
+ const beyond = beyondReview.length;
503
+ if (rows.some(({ status }) => status === 'blocked'))
504
+ parts.push(`${rows.filter(({ status }) => status === 'blocked').length} hard defect group(s)`);
505
+ if (beyond > 0)
506
+ parts.push(`${beyond} metric${beyond === 1 ? '' : 's'} beyond the vanilla range`);
507
+ if (flags.length > 0)
508
+ parts.push(`${flags.length} design flag${flags.length === 1 ? '' : 's'}`);
509
+ const summary = `layout verdict: ${verdict}${parts.length > 0 ? ` (${parts.join('; ')})` : ''}${softEvaluated ? '' : '; too few focuses for the vanilla-calibrated metrics'}`;
510
+ const nextActions = nextActionsFor(verdict, rows, branches, options.treeId);
511
+ return {
512
+ verdict,
513
+ score: Math.max(0, Math.round(100 - scorePenalty)),
514
+ summary,
515
+ focusCount,
516
+ bucket: bucketId,
517
+ softMetricsEvaluated: softEvaluated,
518
+ scorecard: rows,
519
+ nextActions,
520
+ notEvaluated: [...QUALITY_NOT_EVALUATED, ...measurement.notEvaluated],
521
+ branches,
522
+ };
523
+ }
524
+ function nextActionsFor(verdict, rows, branches, treeId) {
525
+ const failing = rows.filter(({ status, inVerdict }) => inVerdict && (status === 'blocked' || status === 'revise' || status === 'review'));
526
+ const names = failing.map(({ id: rowId }) => rowId).join(', ');
527
+ const target = treeId === undefined ? '' : `"treeId":"${treeId}",`;
528
+ const actions = [];
529
+ if (verdict === 'blocked')
530
+ actions.push(`Fix the hard defects (${rows
531
+ .filter(({ status }) => status === 'blocked')
532
+ .map(({ id: rowId }) => rowId)
533
+ .join(', ')}) before anything else; then call hoi4.focus_inspect again`);
534
+ if (verdict === 'blocked' || verdict === 'revise') {
535
+ const culprit = branches.find(({ id: branchId }) => failing.some(({ where }) => where.includes(branchId)));
536
+ actions.push(culprit === undefined
537
+ ? `Repair the layout: hoi4.focus_rewrite {${target}"layoutMode":"compact"}; failing metrics: ${names}`
538
+ : `Repair one branch: hoi4.focus_rewrite {${target}"layoutMode":"compact","compactFocusIds":[...focuses of ${culprit.id}],"pinnedFocusIds":[trunk]}; failing metrics: ${names}`);
539
+ actions.push('A tree is not finished while the verdict is revise or blocked, however clean the structure is');
540
+ }
541
+ else if (verdict === 'review') {
542
+ actions.push(`Look at the picture before you decide: call hoi4.focus_render and judge ${names === '' ? 'the design flags' : names}; review is advisory`);
543
+ }
544
+ else {
545
+ actions.push('Call hoi4.focus_render and look at the picture; metrics cannot judge composition');
546
+ }
547
+ return actions;
548
+ }
549
+ export { QUALITY_METRICS, qualityMetricInfo };
@@ -0,0 +1,7 @@
1
+ import calibrationFile from './focus-quality-calibration.json' with { type: 'json' };
2
+ /**
3
+ * Statistics of the vanilla focus trees, computed by `npm run focus:calibrate` from the installed
4
+ * game. Only derived numbers are stored, never game files. A test recomputes it whenever the game
5
+ * is installed and fails when this file drifts.
6
+ */
7
+ export const STORED_QUALITY_CALIBRATION = calibrationFile;
@@ -0,0 +1,113 @@
1
+ /** Inline rows are bounded; the linked artifact holds the whole scorecard. */
2
+ export const INLINE_SCORECARD_ROWS = 12;
3
+ const INLINE_BRANCHES = 12;
4
+ /**
5
+ * Diagnostics of the curved connector model. The game draws right-angle connectors, so a curve
6
+ * crossing or passing a plaque is mostly an artefact (766 reported crossings on 54 vanilla trees
7
+ * against 86 in the in-game model, and every connector of an all-to-all bundle counted against
8
+ * the rest). The scorecard reports the in-game model instead.
9
+ */
10
+ export const CURVED_CONNECTOR_DIAGNOSTIC_CODES = new Set([
11
+ 'FOCUS_LAYOUT_CONNECTOR_CROSSING_UNSATISFIED',
12
+ 'FOCUS_AVOIDABLE_CONNECTOR_CROSSING',
13
+ 'FOCUS_LAYOUT_CONNECTOR_THROUGH_NODE',
14
+ ]);
15
+ export function withoutCurvedConnectorDiagnostics(diagnostics) {
16
+ return diagnostics.filter(({ code }) => !CURVED_CONNECTOR_DIAGNOSTIC_CODES.has(code));
17
+ }
18
+ function trimText(value, limit) {
19
+ return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
20
+ }
21
+ function trimRow(row) {
22
+ return {
23
+ ...row,
24
+ message: trimText(row.message, 500),
25
+ ...(row.fix === undefined
26
+ ? {}
27
+ : {
28
+ fix: {
29
+ ...row.fix,
30
+ targetFocusIds: row.fix.targetFocusIds.slice(0, 16),
31
+ suggested: trimText(row.fix.suggested, 400),
32
+ expectedMetricChange: trimText(row.fix.expectedMetricChange, 200),
33
+ },
34
+ }),
35
+ };
36
+ }
37
+ const FAILING = new Set(['blocked', 'revise', 'review', 'flag']);
38
+ const DETAIL = {
39
+ full: { rows: INLINE_SCORECARD_ROWS, actions: 6, notes: 6, branches: INLINE_BRANCHES },
40
+ compact: { rows: 6, actions: 3, notes: 0, branches: 0 },
41
+ minimal: { rows: 0, actions: 1, notes: 0, branches: 0 },
42
+ };
43
+ /** The part of a report an operation result carries inline. */
44
+ export function layoutQualityOutput(report, detail = 'full') {
45
+ const limits = DETAIL[detail];
46
+ const failing = report.scorecard.filter(({ status }) => FAILING.has(status));
47
+ return {
48
+ verdict: report.verdict,
49
+ score: report.score,
50
+ summary: trimText(report.summary, 480),
51
+ focusCount: report.focusCount,
52
+ bucket: report.bucket,
53
+ softMetricsEvaluated: report.softMetricsEvaluated,
54
+ scorecard: report.scorecard
55
+ .slice(0, limits.rows)
56
+ .map((row) => (FAILING.has(row.status) ? trimRow(row) : { ...row, message: '', where: [] })),
57
+ failingRowCount: failing.length,
58
+ nextActions: report.nextActions.slice(0, limits.actions).map((action) => trimText(action, 400)),
59
+ notEvaluated: report.notEvaluated.slice(0, limits.notes).map((entry) => trimText(entry, 300)),
60
+ branches: report.branches.slice(0, limits.branches).map((branch) => ({
61
+ id: branch.id,
62
+ focusCount: branch.focusCount,
63
+ minimumX: branch.minimumX,
64
+ maximumX: branch.maximumX,
65
+ minimumY: branch.minimumY,
66
+ maximumY: branch.maximumY,
67
+ })),
68
+ };
69
+ }
70
+ const VERDICT_RANK = { pass: 0, review: 1, revise: 2, blocked: 3 };
71
+ export function worstVerdict(verdicts) {
72
+ return verdicts.reduce((worst, verdict) => (VERDICT_RANK[verdict] > VERDICT_RANK[worst] ? verdict : worst), 'pass');
73
+ }
74
+ /** One diagnostic per tree whose verdict asks for attention, so the verdict reaches `diagnostics`. */
75
+ export function layoutVerdictDiagnostic(treeId, report, location) {
76
+ if (report.verdict === 'pass')
77
+ return undefined;
78
+ const failing = report.scorecard.filter(({ status }) => FAILING.has(status) && status !== 'flag');
79
+ return {
80
+ code: `FOCUS_LAYOUT_VERDICT_${report.verdict.toUpperCase()}`,
81
+ severity: report.verdict === 'review' ? 'info' : 'warning',
82
+ category: 'layout',
83
+ message: report.verdict === 'review'
84
+ ? `Layout of ${treeId} needs a visual review: ${report.summary}`
85
+ : `Layout of ${treeId} is not finished: ${report.summary}. Structure ok never means the layout is good`,
86
+ ...(location === undefined ? {} : { location }),
87
+ details: {
88
+ treeId,
89
+ verdict: report.verdict,
90
+ score: report.score,
91
+ metrics: failing.slice(0, 8).map(({ id, value, status }) => ({ id, value, status })),
92
+ nextActions: report.nextActions.slice(0, 3).map((action) => trimText(action, 300)),
93
+ },
94
+ };
95
+ }
96
+ /**
97
+ * The check that keeps "structure ok" from reading as "done". It never changes `validation.passed`,
98
+ * which stays the structural answer; callers that gate on layout read `passed` of this check.
99
+ */
100
+ export function layoutValidationCheck(entries) {
101
+ const worst = worstVerdict(entries.map(({ report }) => report.verdict));
102
+ const detail = entries.length === 1
103
+ ? entries[0].report.summary
104
+ : `layout verdicts: ${entries
105
+ .slice(0, 8)
106
+ .map(({ treeId, report }) => `${treeId} ${report.verdict}`)
107
+ .join(', ')}${entries.length > 8 ? ` and ${entries.length - 8} more` : ''}`;
108
+ return {
109
+ id: 'focus-layout-verdict',
110
+ passed: worst === 'pass' || worst === 'review',
111
+ message: trimText(`${detail}. Not evaluated: gameplay and balance, visual review (call hoi4.focus_render), in-game connector geometry`, 1000),
112
+ };
113
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Shared types of the focus layout quality rubric. Everything under `focus/quality` is pure:
3
+ * it reads resolved grid coordinates and prerequisite links and never touches source files.
4
+ */
5
+ export {};