hoi4-agent-tools 4.20.0 → 4.20.1

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 (57) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/hoi4_agent_tools/core/engine-operation.js +27 -0
  3. package/dist/hoi4_agent_tools/core/transactions.js +127 -5
  4. package/dist/hoi4_agent_tools/core/workspace.js +118 -67
  5. package/dist/hoi4_agent_tools/event/algorithms.js +14 -2
  6. package/dist/hoi4_agent_tools/gui/layout.js +10 -6
  7. package/dist/hoi4_agent_tools/gui/renderer.js +74 -34
  8. package/dist/hoi4_agent_tools/gui/source-graph.js +12 -0
  9. package/dist/hoi4_agent_tools/gui/studio.js +2 -0
  10. package/dist/hoi4_agent_tools/version.js +1 -1
  11. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  12. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  13. package/engine/bin/linux-x64/hoi4-engine +0 -0
  14. package/engine/bin/manifest.json +8 -8
  15. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  16. package/npm-shrinkwrap.json +2 -2
  17. package/package.json +1 -1
  18. package/schemas/configuration.schema.json +1 -1
  19. package/schemas/continuous-focus-palette.schema.json +1 -1
  20. package/schemas/custom-weighted-pool.schema.json +1 -1
  21. package/schemas/decision-inspect-input.schema.json +1 -1
  22. package/schemas/error-log-input.schema.json +1 -1
  23. package/schemas/event-feature-manifest.schema.json +1 -1
  24. package/schemas/focus-plan.schema.json +1 -1
  25. package/schemas/focus-planning-sidecar.schema.json +1 -1
  26. package/schemas/geography-model.schema.json +1 -1
  27. package/schemas/gui-animation-source.schema.json +1 -1
  28. package/schemas/gui-helper.schema.json +1 -1
  29. package/schemas/gui-scenario.schema.json +1 -1
  30. package/schemas/helper-expansion-request.schema.json +1 -1
  31. package/schemas/helper-expansion-summary.schema.json +1 -1
  32. package/schemas/impact-inspect-input.schema.json +1 -1
  33. package/schemas/map-operation.schema.json +1 -1
  34. package/schemas/mechanic-test-input.schema.json +1 -1
  35. package/schemas/mod-index-input.schema.json +1 -1
  36. package/schemas/operation-result.schema.json +1 -1
  37. package/schemas/package-check-input.schema.json +1 -1
  38. package/schemas/package-manifest.schema.json +1 -1
  39. package/schemas/probability-analysis-result.schema.json +1 -1
  40. package/schemas/probability-compare-input.schema.json +1 -1
  41. package/schemas/probability-evaluate-input.schema.json +1 -1
  42. package/schemas/probability-inspect-input.schema.json +1 -1
  43. package/schemas/probability-render-input.schema.json +1 -1
  44. package/schemas/probability-scenario-set.schema.json +1 -1
  45. package/schemas/probability-sequence-input.schema.json +1 -1
  46. package/schemas/probability-simulate-input.schema.json +1 -1
  47. package/schemas/probability-sweep-input.schema.json +1 -1
  48. package/schemas/reference-context-input.schema.json +1 -1
  49. package/schemas/reference-read-input.schema.json +1 -1
  50. package/schemas/reference-search-input.schema.json +1 -1
  51. package/schemas/reference-sheets.schema.json +1 -1
  52. package/schemas/scenario-suite.schema.json +1 -1
  53. package/schemas/scenario-test-input.schema.json +1 -1
  54. package/schemas/script-validate-input.schema.json +1 -1
  55. package/schemas/shared-scenario.schema.json +1 -1
  56. package/schemas/source-lookup-input.schema.json +1 -1
  57. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.20.1 - 2026-11-23
6
+
7
+ - The canonical-path checks of workspace-relative paths run on the shared Rust engine (ADR 0089, step 2, first piece). `WorkspaceResolver.resolvePath` and `resolvePathInRoot`, which every tool uses to turn a `relativePath` into a file, now ask the resident engine's new `paths.resolve` operation. It refuses an empty, NUL, absolute, `..`, colon or non-portable path, and `.hoi4-agent`, artifact and cache storage as mod source, with the same codes and messages as before. It resolves the path in the highest-loading allowed root through its nearest existing ancestor, and answers only when the real path stays inside that root, so a link or junction out of a root is still never followed. A write still needs the existing parent inside the root. The workspace lookup and grants stay in TypeScript, and an unsafe path is still refused before an unknown workspace. A missing engine answers `ENGINE_UNAVAILABLE`, as the index does. An answer that is out of shape or names a root the workspace does not have is refused the same way. `scripts/workspace-paths-parity.ts` compares the old and the new resolution on the installed game and the benchmark mods: 1,107,695 resolutions in all, with 0 differences (vanilla 101,850, chaos_redux 195,719, one more mod 172,154, ito 116,108, atlantis 131,402, kaiserreich 200,616 and owb 189,846). The script refuses an engine binary without `paths.resolve` and reports the full number of differences. Workspace registration, discovery and the other core services follow.
8
+ - The Rust engine is laid out for porting the server in parallel (ADR 0091, a step of ADR 0089). Sixteen new crates hold the pieces still to move: the core contract, the atomic rewrite engine, artifacts and diffs, jobs, the analyzers, the writers, GUI, map, reference search and the MCP transport. `hoi4-engine serve` now dispatches through an operation registry each crate fills, and refuses to start when an operation name is registered twice or shadows a built-in one. `hoi4-core` holds the diagnostic, canonical JSON (byte-equal to the TypeScript server), scanned-file and rewrite-plan types. Writers return a plan and never write files themselves. The server calls registered operations through one schema-checked helper, which reports a missing engine or operation as `ENGINE_UNAVAILABLE` and passes an operation's own refusal code through. No tool changes its behavior.
9
+ - Fixed `hoi4.event_inspect` `explain_path` reporting no path between two events that the trace shows connected through a scripted-effect helper (issue 278). With helpers collapsed, the path search on a focused graph read only the helper-free edges and so skipped every route through a helper; it now collapses helpers lazily, as the trace does.
10
+ - `hoi4.gui_render` and `hoi4.gui_inspect` read a mod's `localisation/replace/` folder, which they skipped before. Within one root, a key in `localisation/replace/` or `localisation/<language>/replace/` now wins over the same key in the root's other files, as in the game. Windows showed the base game's text, such as "Trade" or "Production", where a mod replaces it.
11
+ - `hoi4.gui_render` now reads a text box's `text_color_code` (for example `"Y"`) and draws its text in that colour, looked up like in-text `§` codes: the font's own `textcolors` first, then the standard codes. In-text markup that ends with `§!` returns to that colour. An unknown code keeps the font's colour.
12
+ - `hoi4.gui_render` writes each texture into an SVG once and draws every use of it by reference. A nine-slice texture used to be written nine times per element that drew it, so one large texture shared by a few dozen elements could reach the artifact ceiling (`ARTIFACT_LOGICAL_BATCH_LIMIT`).
13
+ - Adds the synthetic symbol index fixture to `engine/fixtures/symbol-index/` for the Rust engine port. The file is copied unchanged from `tests/fixtures/symbol-index/expected.json`. No runtime behavior changes.
14
+ - The engine's TypeScript-compatible source reader now exposes its position table and a per-document token count, so the pieces moving to Rust (ADR 0089, ADR 0091) report source locations and token ceilings exactly as the TypeScript server does. No tool changes its behavior.
15
+ - When an apply's automatic rollback is refused (`TRANSACTION_ROLLBACK_STALE`, for example because another writer changed a target meanwhile), the rewrite engine now removes the in-workspace `.backup` files of every target still at its written bytes; their before-bytes stay in the journal. Only the conflicting targets keep a backup, and the refusal names them (`retainedBackups`, `retainedBackupCount`). Before, every backup stayed in the mod tree.
16
+ - Pruning now reclaims an expired `failed` journal once the workspace holds all of its written bytes, and library callers can discard a failed journal with `TransactionManager.discardFailed`. Before, a failed journal counted against the journal quota for good. No MCP tool exposes the discard.
17
+
5
18
  ## 4.20.0 - 2026-11-22
6
19
 
7
20
  - The call that follows a rewrite now reads the index the rewrite just built (issue 137, maintainer decision D-98). A rewrite's after-edit check builds the workspace's new index in the job worker that ran the rewrite, but the next call took whichever warm worker was used last, and after a `hoi4.focus_rewrite` with `answerBeforeCheck: true` that worker was still busy, so the `hoi4.focus_inspect` sent right after the answer started another worker and built the index again, from nothing in a new process. A job for a workspace now goes to the worker that ran that workspace's last job when it is idle, else to another idle worker that scanned the workspace before, which rescans only the changed files. Only when no such worker is idle does it wait, at most 15 s, for the worker still finishing a rewrite; it never waits for a read. The after-edit check of a focus rewrite also fills the same reference catalog the inspect reads, so the inspect no longer builds it a second time. The reused index is still checked against the files on every call: the worker scans again, and any file changed after the rewrite is indexed again, so a stale answer is never served. The durable write is unchanged: the journal still syncs the backups, the manifest and the written files before the call answers. `scripts/bench/focus-gesture-timing.ts` times the gesture (a changed-tree rewrite, then an inspect) on the four-focus probe tree and on the benchmark mods.
@@ -0,0 +1,27 @@
1
+ import { sharedResidentEngine, } from './resident-engine.js';
2
+ import { ServiceError } from './result.js';
3
+ const TOOL_CODE = /^[A-Z][A-Z0-9_]*$/u;
4
+ export async function callEngineOperation(call) {
5
+ const engine = call.engine ?? sharedResidentEngine();
6
+ const outcome = await engine.request(call.op, call.body ?? {}, call.payload, call.options ?? {});
7
+ if (outcome.ok) {
8
+ const parsed = call.result.safeParse(outcome.response.result);
9
+ if (!parsed.success)
10
+ throw new ServiceError('ENGINE_UNAVAILABLE', `hoi4-engine ${call.op} answered out of shape`, {
11
+ op: call.op,
12
+ reason: 'invalid_response',
13
+ });
14
+ return { result: parsed.data, payload: outcome.response.payload };
15
+ }
16
+ if (outcome.kind === 'error' && TOOL_CODE.test(outcome.code))
17
+ throw new ServiceError(outcome.code, outcome.message, outcome.details);
18
+ if (outcome.kind === 'error')
19
+ throw new ServiceError('ENGINE_UNAVAILABLE', outcome.message, {
20
+ op: call.op,
21
+ reason: outcome.code,
22
+ });
23
+ throw new ServiceError('ENGINE_UNAVAILABLE', outcome.message, {
24
+ op: call.op,
25
+ reason: outcome.reason,
26
+ });
27
+ }
@@ -170,6 +170,16 @@ function manifestAuthenticationPayload(manifest) {
170
170
  const { authenticationTag: _authenticationTag, ...payload } = manifest;
171
171
  return payload;
172
172
  }
173
+ /** The paths whose rollback backups stay in the workspace, added to a rollback refusal. */
174
+ function withRetainedBackups(error, retained) {
175
+ if (retained.length === 0)
176
+ return error;
177
+ return new ServiceError(error.code, error.message, {
178
+ ...error.details,
179
+ retainedBackupCount: retained.length,
180
+ retainedBackups: retained.slice(0, 20),
181
+ });
182
+ }
173
183
  export function transactionRootFingerprint(workspace) {
174
184
  return resolvedWorkspaceIdentity(workspace);
175
185
  }
@@ -670,8 +680,11 @@ export class TransactionManager {
670
680
  }
671
681
  manifest.state = manifest.rollbackStatus === 'applied' ? 'rolled_back' : 'failed';
672
682
  await this.writeManifest(workspace, manifest, options.hooks);
673
- if (rollbackError instanceof ServiceError)
674
- throw rollbackError;
683
+ if (rollbackError !== undefined) {
684
+ const retained = await this.discardSettledBackups(workspace, manifest, options.principal);
685
+ if (rollbackError instanceof ServiceError)
686
+ throw withRetainedBackups(rollbackError, retained);
687
+ }
675
688
  if (rollbackError !== undefined) {
676
689
  throw new ServiceError('TRANSACTION_ROLLBACK_FAILED', 'Automatic rollback could not safely complete');
677
690
  }
@@ -801,8 +814,9 @@ export class TransactionManager {
801
814
  manifest.state = 'failed';
802
815
  manifest.failure = this.safeFailure(error, 'TRANSACTION_RECOVERY_FAILED', 'Interrupted transaction could not be recovered safely');
803
816
  await this.writeManifest(workspace, manifest);
817
+ const retained = await this.discardSettledBackups(workspace, manifest, principal);
804
818
  if (error instanceof ServiceError)
805
- throw error;
819
+ throw withRetainedBackups(error, retained);
806
820
  throw new ServiceError('TRANSACTION_RECOVERY_FAILED', 'Interrupted transaction could not be recovered safely');
807
821
  }
808
822
  }
@@ -868,6 +882,106 @@ export class TransactionManager {
868
882
  }
869
883
  return recovered;
870
884
  }
885
+ /**
886
+ * After a rollback that could not complete, a file still holding this transaction's
887
+ * after-bytes keeps its result, and its before-bytes are in the journal's verified blobs. Its
888
+ * in-workspace backup would only linger in the mod tree, where searches, syncs and packagers
889
+ * would pick it up, so it is removed. A file in any other state keeps its backup. Returns the
890
+ * workspace-relative paths whose backups remain. Cleanup never masks the original failure.
891
+ */
892
+ async discardSettledBackups(workspace, manifest, principal) {
893
+ const retained = [];
894
+ for (const file of manifest.files) {
895
+ try {
896
+ const { path: target } = await this.resolver.resolvePath(workspace.id, file.relativePath, 'write', ['mod'], principal);
897
+ const backup = `${target}.hoi4-agent-${manifest.transactionId}.backup`;
898
+ if (!(await fileExists(backup)))
899
+ continue;
900
+ const current = (await fileExists(target)) ? sha256Bytes(await readFile(target)) : null;
901
+ let settled = file.beforeSha256 !== null &&
902
+ current === file.afterSha256 &&
903
+ sha256Bytes(await readFile(backup)) === file.beforeSha256;
904
+ if (settled) {
905
+ try {
906
+ await this.readVerifiedBlob(workspace, manifest, file, 'before');
907
+ }
908
+ catch {
909
+ settled = false;
910
+ }
911
+ }
912
+ if (settled)
913
+ await unlink(backup);
914
+ else
915
+ retained.push(file.relativePath);
916
+ }
917
+ catch {
918
+ retained.push(file.relativePath);
919
+ }
920
+ }
921
+ return retained.sort((left, right) => compareCodeUnits(left, right));
922
+ }
923
+ /** The current file of each change equals its after-bytes and no backup of it remains. */
924
+ async workspaceAtAfterState(workspace, manifest) {
925
+ try {
926
+ await this.verifyCurrentFiles(workspace, manifest, 'after', manifest.principal ?? undefined);
927
+ }
928
+ catch {
929
+ return false;
930
+ }
931
+ return ((await this.discardSettledBackups(workspace, manifest, manifest.principal ?? undefined))
932
+ .length === 0);
933
+ }
934
+ /**
935
+ * Discard a failed transaction's journal for good: the owner accepts the workspace as it is.
936
+ * Its remaining in-workspace backups are removed when they still hold the recorded
937
+ * before-bytes; any other file of that name is left alone and reported. Library callers only;
938
+ * no MCP tool exposes this.
939
+ */
940
+ async discardFailed(workspaceId, transactionId, principal, signal) {
941
+ signal?.throwIfAborted();
942
+ const workspace = this.resolver.get(workspaceId, principal);
943
+ const initial = await this.load(workspace, transactionId, {
944
+ headMode: 'none',
945
+ ...(signal === undefined ? {} : { signal }),
946
+ });
947
+ if ((initial.principal ?? null) !== (principal ?? null)) {
948
+ throw new ServiceError('TRANSACTION_PRINCIPAL_MISMATCH', 'Transaction belongs to another principal');
949
+ }
950
+ return this.withWorkspaceLock(workspace, transactionId, async () => {
951
+ signal?.throwIfAborted();
952
+ const manifest = await this.load(workspace, transactionId, {
953
+ headMode: 'reconcile',
954
+ ...(signal === undefined ? {} : { signal }),
955
+ });
956
+ if ((manifest.principal ?? null) !== (principal ?? null)) {
957
+ throw new ServiceError('TRANSACTION_PRINCIPAL_MISMATCH', 'Transaction belongs to another principal');
958
+ }
959
+ if (manifest.state !== 'failed') {
960
+ throw new ServiceError('TRANSACTION_STATE_INVALID', 'Only a failed transaction can be discarded', { state: manifest.state });
961
+ }
962
+ let removedBackups = 0;
963
+ const retainedBackups = [];
964
+ for (const file of manifest.files) {
965
+ const { path: target } = await this.resolver.resolvePath(workspace.id, file.relativePath, 'write', ['mod'], principal);
966
+ const backup = `${target}.hoi4-agent-${manifest.transactionId}.backup`;
967
+ if (!(await fileExists(backup)))
968
+ continue;
969
+ if (file.beforeSha256 !== null &&
970
+ sha256Bytes(await readFile(backup)) === file.beforeSha256) {
971
+ await unlink(backup);
972
+ removedBackups += 1;
973
+ }
974
+ else
975
+ retainedBackups.push(file.relativePath);
976
+ }
977
+ const transactionsDirectory = await containedGeneratedPath(workspace.cacheRoot, 'transactions');
978
+ await this.reclaimJournal(workspace, transactionsDirectory, transactionId);
979
+ return {
980
+ removedBackups,
981
+ retainedBackups: retainedBackups.sort((left, right) => compareCodeUnits(left, right)),
982
+ };
983
+ });
984
+ }
871
985
  async restoreBeforeState(workspace, manifest, principal, hooks) {
872
986
  const restorations = [];
873
987
  // Prove that every required rollback source is intact before changing any
@@ -1196,7 +1310,15 @@ export class TransactionManager {
1196
1310
  continue;
1197
1311
  }
1198
1312
  if (reclaimApplied && manifest.state === 'applied') {
1199
- await this.reclaimAutonomousAppliedJournal(workspace, transactionsDirectory, entry.name);
1313
+ await this.reclaimJournal(workspace, transactionsDirectory, entry.name);
1314
+ }
1315
+ else if (Date.parse(manifest.expiresAt) <= now &&
1316
+ manifest.state === 'failed' &&
1317
+ (await this.workspaceAtAfterState(workspace, manifest))) {
1318
+ // A failed journal whose workspace still holds every after-byte, with no backup left,
1319
+ // is an applied journal in all but name. Once expired it stops counting against the
1320
+ // quota; one whose files changed since stays until its owner discards it.
1321
+ await this.reclaimJournal(workspace, transactionsDirectory, entry.name);
1200
1322
  }
1201
1323
  else if (Date.parse(manifest.expiresAt) <= now &&
1202
1324
  (manifest.state === 'planned' || manifest.state === 'rolled_back')) {
@@ -1206,7 +1328,7 @@ export class TransactionManager {
1206
1328
  }
1207
1329
  }
1208
1330
  }
1209
- async reclaimAutonomousAppliedJournal(workspace, transactionsDirectory, transactionId) {
1331
+ async reclaimJournal(workspace, transactionsDirectory, transactionId) {
1210
1332
  const directory = await this.transactionDirectory(workspace, transactionId);
1211
1333
  const reclamationDirectory = await containedGeneratedPath(transactionsDirectory, `.reclaiming-${transactionId}`);
1212
1334
  // The atomic rename is the durable reclamation marker. It moves the journal
@@ -2,6 +2,8 @@ import { lstat, mkdir, opendir, readFile, readdir, realpath } from 'node:fs/prom
2
2
  import path from 'node:path';
3
3
  import { WORKSPACE_MAX_REGISTRATIONS, workspaceRegistrationSchema, } from './configuration.js';
4
4
  import { compareCodeUnits, hashCanonical, sha256Bytes } from './canonical.js';
5
+ import { z } from 'zod/v4';
6
+ import { sharedResidentEngine } from './resident-engine.js';
5
7
  import { ServiceError } from './result.js';
6
8
  import { ServerState } from './server-state.js';
7
9
  import { parseClausewitz } from './source/parser.js';
@@ -299,30 +301,77 @@ export async function containedGeneratedPath(root, ...segments) {
299
301
  }
300
302
  return candidate;
301
303
  }
302
- function assertRelative(relativePath) {
303
- if (relativePath.length === 0)
304
- throw new ServiceError('PATH_EMPTY', 'Workspace-relative path cannot be empty');
305
- if (relativePath.includes('\0'))
306
- throw new ServiceError('PATH_NUL', 'Path contains a NUL byte');
307
- if (path.isAbsolute(relativePath)) {
308
- throw new ServiceError('PATH_ABSOLUTE_REJECTED', 'Only workspace-relative paths are accepted');
309
- }
310
- const segments = relativePath.replaceAll('\\', '/').split('/');
311
- if (segments.some((segment) => segment === '..')) {
312
- throw new ServiceError('PATH_TRAVERSAL', 'Parent path segments are not allowed', {
313
- relativePath,
314
- });
315
- }
316
- if (segments.some((segment) => segment.includes(':'))) {
317
- throw new ServiceError('PATH_ALTERNATE_STREAM', 'Colon characters and alternate data streams are not allowed', {
318
- relativePath,
319
- });
320
- }
321
- if (segments.some((segment) => segment !== '.' && segment.length > 0 && !isPortablePathSegment(segment))) {
322
- throw new ServiceError('PATH_WINDOWS_DEVICE', 'Portable paths cannot contain device names, control characters, or ambiguous characters', {
323
- relativePath,
324
- });
325
- }
304
+ /** The refusals that name the offending relative path in their details. */
305
+ const PATH_REFUSALS_WITH_PATH = new Set([
306
+ 'PATH_TRAVERSAL',
307
+ 'PATH_ALTERNATE_STREAM',
308
+ 'PATH_WINDOWS_DEVICE',
309
+ ]);
310
+ const enginePathAnswerSchema = z.union([
311
+ z
312
+ .object({
313
+ resolved: z
314
+ .object({ path: z.string().min(1), root: z.number().int().nonnegative() })
315
+ .strict()
316
+ .nullable(),
317
+ })
318
+ .strict(),
319
+ z
320
+ .object({ refusal: z.object({ code: z.string().min(1), message: z.string() }).strict() })
321
+ .strict(),
322
+ ]);
323
+ /**
324
+ * Resolve a workspace-relative path in `roots` with the engine's `paths.resolve` (ADR 0089): its
325
+ * refusal, its real path and the index of the root it resolved in, or `undefined` when no root
326
+ * holds it. A missing engine is `ENGINE_UNAVAILABLE`; a file system failure is rethrown with its
327
+ * error code, as the TypeScript walk threw it.
328
+ */
329
+ async function engineResolvePath(request) {
330
+ const outcome = await sharedResidentEngine().request('paths.resolve', {
331
+ relativePath: request.relativePath,
332
+ access: request.access,
333
+ roots: request.roots.map(({ path: rootPath, kind, loadOrder, writable }) => ({
334
+ path: rootPath,
335
+ kind,
336
+ loadOrder,
337
+ writable,
338
+ })),
339
+ ...(request.rootKinds === undefined ? {} : { rootKinds: request.rootKinds }),
340
+ ...(request.reserved === undefined ? {} : { reserved: request.reserved }),
341
+ ...(request.inRoot === true ? { inRoot: true } : {}),
342
+ });
343
+ if (!outcome.ok) {
344
+ if (outcome.kind === 'error' && outcome.code === 'io_error')
345
+ throw Object.assign(new Error(outcome.message), {
346
+ code: typeof outcome.details.errno === 'string' ? outcome.details.errno : 'EIO',
347
+ });
348
+ throw new ServiceError('ENGINE_UNAVAILABLE', outcome.message, outcome.kind === 'unavailable' ? { reason: outcome.reason } : { code: outcome.code });
349
+ }
350
+ const parsed = enginePathAnswerSchema.safeParse(outcome.response.result);
351
+ if (!parsed.success)
352
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine paths.resolve answered out of shape');
353
+ const answer = parsed.data;
354
+ if ('refusal' in answer)
355
+ return { refusal: answer.refusal };
356
+ if (answer.resolved === null)
357
+ return undefined;
358
+ if (answer.resolved.root >= request.roots.length)
359
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine paths.resolve named an unknown root');
360
+ return answer.resolved;
361
+ }
362
+ function pathRefusal(refusal, relativePath) {
363
+ return new ServiceError(refusal.code, refusal.message, PATH_REFUSALS_WITH_PATH.has(refusal.code) ? { relativePath } : undefined);
364
+ }
365
+ /**
366
+ * Refuse a relative path that could leave a root or is not portable, without resolving it. The
367
+ * `.hoi4-agent` rule needs a workspace, so it is left to the resolution itself.
368
+ */
369
+ async function refuseUnsafeRelativePath(relativePath) {
370
+ const checked = await engineResolvePath({ relativePath, access: 'read', roots: [] });
371
+ if (checked !== undefined &&
372
+ 'refusal' in checked &&
373
+ checked.refusal.code !== 'PATH_GENERATED_STORAGE_RESERVED')
374
+ throw pathRefusal(checked.refusal, relativePath);
326
375
  }
327
376
  export class WorkspaceResolver {
328
377
  configuration;
@@ -612,61 +661,63 @@ export class WorkspaceResolver {
612
661
  return workspace;
613
662
  }
614
663
  async resolvePath(workspaceId, relativePath, access, rootKinds, principal) {
615
- assertRelative(relativePath);
616
- const workspace = this.get(workspaceId, principal);
617
- const firstSegment = path.posix
618
- .normalize(relativePath.replaceAll('\\', '/'))
619
- .split('/')
620
- .find((segment) => segment !== '.' && segment.length > 0)
621
- ?.toLowerCase();
622
- // Server storage holds other principals' proposals and journals; it is never mod source,
623
- // for reads as well as writes.
624
- if (firstSegment === '.hoi4-agent') {
625
- throw new ServiceError('PATH_GENERATED_STORAGE_RESERVED', 'Generated .hoi4-agent storage cannot be targeted as mod source');
626
- }
627
- const roots = workspace.roots.filter((root) => (rootKinds === undefined || rootKinds.includes(root.kind)) &&
628
- (access === 'read' || root.writable));
629
- for (const root of roots.sort((a, b) => b.loadOrder - a.loadOrder)) {
630
- const candidate = await canonicalPath(path.join(root.path, relativePath));
631
- if (!isWithin(root.path, candidate))
632
- continue;
633
- if (access === 'read' && !(await exists(candidate)))
634
- continue;
635
- if (root.kind === 'mod' &&
636
- (pathsOverlap(workspace.artifactRoot, candidate) ||
637
- pathsOverlap(workspace.cacheRoot, candidate))) {
638
- throw new ServiceError('PATH_GENERATED_STORAGE_RESERVED', 'Artifact and cache storage cannot be targeted as mod source');
639
- }
640
- if (access === 'write') {
641
- const existingParent = await canonicalPath(path.dirname(candidate));
642
- if (!isWithin(root.path, existingParent))
643
- continue;
644
- }
645
- return { path: candidate, root };
646
- }
664
+ // The engine checks the path, resolves it in the roots and refuses an escape (ADR 0089). Server
665
+ // storage (`.hoi4-agent`, artifacts, cache) holds other principals' proposals and journals; it
666
+ // is never mod source, for reads as well as writes.
667
+ const workspace = await this.getAfterPathCheck(workspaceId, relativePath, principal);
668
+ const resolved = await engineResolvePath({
669
+ relativePath,
670
+ access,
671
+ roots: workspace.roots,
672
+ ...(rootKinds === undefined ? {} : { rootKinds: [...rootKinds] }),
673
+ reserved: [workspace.artifactRoot, workspace.cacheRoot],
674
+ });
675
+ if (resolved !== undefined && 'refusal' in resolved)
676
+ throw pathRefusal(resolved.refusal, relativePath);
677
+ if (resolved !== undefined)
678
+ return { path: resolved.path, root: workspace.roots[resolved.root] };
647
679
  throw new ServiceError(access === 'write' ? 'PATH_WRITE_OUTSIDE_ROOTS' : 'PATH_NOT_FOUND_IN_ROOTS', `Path cannot be resolved for ${access} access`, { workspaceId, relativePath, rootKinds });
648
680
  }
649
681
  async resolvePathInRoot(workspaceId, relativePath, rootKind, loadOrder, principal) {
650
- assertRelative(relativePath);
651
- const workspace = this.get(workspaceId, principal);
682
+ const workspace = await this.getAfterPathCheck(workspaceId, relativePath, principal);
652
683
  const root = workspace.roots.find((candidate) => candidate.kind === rootKind && candidate.loadOrder === loadOrder);
653
684
  if (root === undefined) {
685
+ await refuseUnsafeRelativePath(relativePath);
654
686
  throw new ServiceError('PATH_ROOT_NOT_FOUND', 'Configured source root no longer exists', {
655
687
  workspaceId,
656
688
  rootKind,
657
689
  loadOrder,
658
690
  });
659
691
  }
660
- const candidate = await canonicalPath(path.join(root.path, relativePath));
661
- if (!isWithin(root.path, candidate) || !(await exists(candidate))) {
662
- throw new ServiceError('PATH_NOT_FOUND_IN_ROOT', 'Path cannot be resolved in the selected source root', {
663
- workspaceId,
664
- relativePath,
665
- rootKind,
666
- loadOrder,
667
- });
692
+ const resolved = await engineResolvePath({
693
+ relativePath,
694
+ access: 'read',
695
+ roots: [root],
696
+ inRoot: true,
697
+ });
698
+ if (resolved !== undefined && 'refusal' in resolved)
699
+ throw pathRefusal(resolved.refusal, relativePath);
700
+ if (resolved !== undefined)
701
+ return { path: resolved.path, root };
702
+ throw new ServiceError('PATH_NOT_FOUND_IN_ROOT', 'Path cannot be resolved in the selected source root', {
703
+ workspaceId,
704
+ relativePath,
705
+ rootKind,
706
+ loadOrder,
707
+ });
708
+ }
709
+ /**
710
+ * `get`, except that an unsafe relative path is refused first, as the path check ran before the
711
+ * workspace lookup when it was TypeScript.
712
+ */
713
+ async getAfterPathCheck(workspaceId, relativePath, principal) {
714
+ try {
715
+ return this.get(workspaceId, principal);
716
+ }
717
+ catch (error) {
718
+ await refuseUnsafeRelativePath(relativePath);
719
+ throw error;
668
720
  }
669
- return { path: candidate, root };
670
721
  }
671
722
  allowedWorkspaceIds(principal) {
672
723
  const token = this.configuration.http.tokens.find((entry) => entry.principal === principal);
@@ -304,7 +304,19 @@ export function shortestEventPath(graph, fromNodeIds, toNodeIds, options, signal
304
304
  const nodes = nodeMap(graph);
305
305
  const starts = sortedUnique(fromNodeIds).filter((id) => nodes.has(id));
306
306
  const targets = new Set(toNodeIds.filter((id) => nodes.has(id)));
307
- const maps = edgeMaps(eventFlowEdges(graph, options.expandHelpers));
307
+ // Issue 278: a focused graph has helper nodes and no derived edge, so the collapsed projection
308
+ // is built lazily per node, exactly as the trace does. Reading only the flow edges would drop
309
+ // every route that passes through a helper, although the trace reports it.
310
+ const lazyCollapse = !options.expandHelpers &&
311
+ !graph.edges.some(({ derived }) => derived) &&
312
+ graph.nodes.some(({ kind }) => kind === 'helper');
313
+ const structural = lazyCollapse
314
+ ? edgeMaps(graph.edges.filter(({ derived }) => !derived))
315
+ : undefined;
316
+ const maps = edgeMaps(lazyCollapse ? [] : eventFlowEdges(graph, options.expandHelpers));
317
+ const outgoingOf = (nodeId) => structural === undefined
318
+ ? (maps.outgoing.get(nodeId) ?? [])
319
+ : lazyCollapsedEdges(nodes, nodeId, 'downstream', structural, Math.max(256, options.maxNodes * 2), signal);
308
320
  const queue = starts.map((nodeId) => ({ nodeId, depth: 0 }));
309
321
  const visited = new Set(starts);
310
322
  const predecessor = new Map();
@@ -316,7 +328,7 @@ export function shortestEventPath(graph, fromNodeIds, toNodeIds, options, signal
316
328
  const current = queue[cursor++];
317
329
  if (current.depth >= options.maxDepth)
318
330
  continue;
319
- for (const edge of maps.outgoing.get(current.nodeId) ?? []) {
331
+ for (const edge of outgoingOf(current.nodeId)) {
320
332
  if (visited.has(edge.to))
321
333
  continue;
322
334
  if (visited.size >= options.maxNodes)
@@ -1510,10 +1510,14 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1510
1510
  displayText = `\u00a7R${rawText}_MISSING\u00a7!`;
1511
1511
  const fontName = scalarString(property(definition.attributes, 'font', 'buttonFont'));
1512
1512
  const fontDefinition = fontName === undefined ? undefined : catalog.fontDefinition(fontName);
1513
- const visibleText = visibleHoiText(displayText, {
1514
- ...context.graph.textColours,
1515
- ...fontDefinition?.textColours,
1516
- });
1513
+ const textColours = { ...context.graph.textColours, ...fontDefinition?.textColours };
1514
+ // `text_color_code` names the box's base colour with the same codes as in-text § markup;
1515
+ // an unknown code leaves the font's own colour.
1516
+ const colourCode = scalarString(property(definition.attributes, 'text_color_code'));
1517
+ const baseColour = (colourCode === undefined
1518
+ ? undefined
1519
+ : (textColours[colourCode] ?? hoi4TextColours[colourCode])) ?? fontDefinition?.colour;
1520
+ const visibleText = visibleHoiText(displayText, textColours);
1517
1521
  displayText = visibleText.text;
1518
1522
  context.work.admitText(displayText, `GUI text for ${definition.name}`);
1519
1523
  const resolvedFontMetrics = catalog.resolvedFontMetrics(fontName);
@@ -1574,7 +1578,7 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1574
1578
  inlineIcons.push(...shaped.icons);
1575
1579
  }
1576
1580
  const colourRuns = visibleText.hasColourMarkup
1577
- ? wrapped.lines.map((line, index) => colourRunsForLine(catalog, fontName, line, wrapped.colourLines[index] ?? [], fontSize * scale, context.work, resolvedInlineIcons, fontDefinition?.colour ?? defaultTextColour))
1581
+ ? wrapped.lines.map((line, index) => colourRunsForLine(catalog, fontName, line, wrapped.colourLines[index] ?? [], fontSize * scale, context.work, resolvedInlineIcons, baseColour ?? defaultTextColour))
1578
1582
  : undefined;
1579
1583
  const maximumLineWidth = wrapped.widths.reduce((maximum, value) => Math.max(maximum, value), 0);
1580
1584
  if (width === 0 && inferWidth)
@@ -1594,7 +1598,7 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1594
1598
  metricSource: wrapped.metricSource,
1595
1599
  ...alignment(definition.attributes, embeddedButtonText),
1596
1600
  ...(fontName === undefined ? {} : { fontName }),
1597
- ...(fontDefinition?.colour === undefined ? {} : { colour: fontDefinition.colour }),
1601
+ ...(baseColour === undefined ? {} : { colour: baseColour }),
1598
1602
  ...(fontDefinition?.borderColour === undefined
1599
1603
  ? {}
1600
1604
  : { borderColour: fontDefinition.borderColour }),