hoi4-agent-tools 4.19.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 (68) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/hoi4_agent_tools/core/diagnostic-rollup.js +9 -1
  3. package/dist/hoi4_agent_tools/core/domain-validation.js +3 -16
  4. package/dist/hoi4_agent_tools/core/engine-operation.js +27 -0
  5. package/dist/hoi4_agent_tools/core/job-worker-host.js +127 -11
  6. package/dist/hoi4_agent_tools/core/transactions.js +127 -5
  7. package/dist/hoi4_agent_tools/core/workspace.js +118 -67
  8. package/dist/hoi4_agent_tools/event/algorithms.js +14 -2
  9. package/dist/hoi4_agent_tools/gui/layout.js +10 -6
  10. package/dist/hoi4_agent_tools/gui/renderer.js +74 -34
  11. package/dist/hoi4_agent_tools/gui/source-graph.js +12 -0
  12. package/dist/hoi4_agent_tools/gui/studio.js +2 -0
  13. package/dist/hoi4_agent_tools/map/baseline.js +143 -0
  14. package/dist/hoi4_agent_tools/map/diagnostic-limit.js +14 -13
  15. package/dist/hoi4_agent_tools/map/service.js +112 -15
  16. package/dist/hoi4_agent_tools/map/tool-operations.js +10 -0
  17. package/dist/hoi4_agent_tools/map/validation.js +13 -5
  18. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -0
  19. package/dist/hoi4_agent_tools/schemas/map-requests.js +6 -0
  20. package/dist/hoi4_agent_tools/version.js +1 -1
  21. package/docs/map.md +29 -0
  22. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  23. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  24. package/engine/bin/linux-x64/hoi4-engine +0 -0
  25. package/engine/bin/manifest.json +8 -8
  26. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  27. package/npm-shrinkwrap.json +2 -2
  28. package/package.json +1 -1
  29. package/schemas/configuration.schema.json +1 -1
  30. package/schemas/continuous-focus-palette.schema.json +1 -1
  31. package/schemas/custom-weighted-pool.schema.json +1 -1
  32. package/schemas/decision-inspect-input.schema.json +1 -1
  33. package/schemas/error-log-input.schema.json +1 -1
  34. package/schemas/event-feature-manifest.schema.json +1 -1
  35. package/schemas/focus-plan.schema.json +1 -1
  36. package/schemas/focus-planning-sidecar.schema.json +1 -1
  37. package/schemas/geography-model.schema.json +1 -1
  38. package/schemas/gui-animation-source.schema.json +1 -1
  39. package/schemas/gui-helper.schema.json +1 -1
  40. package/schemas/gui-scenario.schema.json +1 -1
  41. package/schemas/helper-expansion-request.schema.json +1 -1
  42. package/schemas/helper-expansion-summary.schema.json +1 -1
  43. package/schemas/impact-inspect-input.schema.json +1 -1
  44. package/schemas/map-operation.schema.json +1 -1
  45. package/schemas/mechanic-test-input.schema.json +1 -1
  46. package/schemas/mod-index-input.schema.json +1 -1
  47. package/schemas/operation-result.schema.json +1 -1
  48. package/schemas/package-check-input.schema.json +1 -1
  49. package/schemas/package-manifest.schema.json +1 -1
  50. package/schemas/probability-analysis-result.schema.json +1 -1
  51. package/schemas/probability-compare-input.schema.json +1 -1
  52. package/schemas/probability-evaluate-input.schema.json +1 -1
  53. package/schemas/probability-inspect-input.schema.json +1 -1
  54. package/schemas/probability-render-input.schema.json +1 -1
  55. package/schemas/probability-scenario-set.schema.json +1 -1
  56. package/schemas/probability-sequence-input.schema.json +1 -1
  57. package/schemas/probability-simulate-input.schema.json +1 -1
  58. package/schemas/probability-sweep-input.schema.json +1 -1
  59. package/schemas/reference-context-input.schema.json +1 -1
  60. package/schemas/reference-read-input.schema.json +1 -1
  61. package/schemas/reference-search-input.schema.json +1 -1
  62. package/schemas/reference-sheets.schema.json +1 -1
  63. package/schemas/scenario-suite.schema.json +1 -1
  64. package/schemas/scenario-test-input.schema.json +1 -1
  65. package/schemas/script-validate-input.schema.json +1 -1
  66. package/schemas/shared-scenario.schema.json +1 -1
  67. package/schemas/source-lookup-input.schema.json +1 -1
  68. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
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
+
18
+ ## 4.20.0 - 2026-11-22
19
+
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.
21
+ - A map write can now go through on a map that already has many validation errors (issue 272, ADR 0090). Before, every error after the change that also existed before kept blocking. Each one also added a `MAP_VALIDATION_OPERATION_UNOWNED` blocker and was counted against the 100-diagnostic review limit. On a map with 3,957 existing findings and 45 new ones, every write was refused with `REWRITE_STRUCTURE_LIMIT`. A full `hoi4.map_inspect` now returns `baselineFingerprint`, a hash of the tool version and every scanned map source. `hoi4.map_rewrite` takes it back as the optional `baselineFingerprint`. The server recomputes the fingerprint on the current source and refuses the write with `MAP_BASELINE_STALE` when the map changed. With a match, both validations keep every finding up to 50,000 instead of 2,000. A pre-existing error that belongs to nothing the write touches is reported as a warning (`attributionStatus: "accepted-baseline"`) and rolled up by code. Pre-existing errors inside the write's footprint still block, and so does every new error. A stated baseline on `create_world` is refused with `MAP_BASELINE_NOT_APPLICABLE`. Without the field, a write is judged exactly as before. Tests cover the unchanged default, an accepted error, an invented and an outdated fingerprint, an error inside the footprint, a new error, and a write over 121 existing errors that passes only with a matching baseline.
22
+
5
23
  ## 4.19.0 - 2026-11-21
6
24
 
7
25
  - Add `hoi4.idea_write` (issue 158): add, replace or remove one idea (national spirit, law or advisor idea) in a mod `common/ideas` file in one call. It changes only that block: comments, neighbouring ideas, line endings and the byte order mark come back byte for byte, and the result is parsed again and refused if it has syntax errors or touched another definition. `add` needs `category` and `body` (the text between the braces) and refuses a duplicate id, an unknown category (it lists the categories the file has) or a body that is not one block; `replace` and `remove` find the idea in the mod, and refuse one that only the game defines. `apply: false` returns the diff; `apply: true` writes it as one journaled transaction. A missing English localisation key or picture sprite is a warning, not a refusal. It is in the `advanced` profile. New categories, new files and characters follow.
@@ -45,7 +45,9 @@ export function rollupRepeatedSoftDiagnostics(diagnostics, evidence) {
45
45
  hard.push(diagnostic);
46
46
  continue;
47
47
  }
48
- const key = `${diagnostic.severity}:${diagnostic.code}`;
48
+ // Pre-existing errors a stated map baseline accepted (ADR 0090) roll up apart from warnings.
49
+ const accepted = diagnostic.details?.attributionStatus === 'accepted-baseline';
50
+ const key = `${diagnostic.severity}:${diagnostic.code}${accepted ? ':accepted-baseline' : ''}`;
49
51
  const group = groups.get(key) ?? [];
50
52
  group.push(diagnostic);
51
53
  groups.set(key, group);
@@ -77,6 +79,12 @@ export function rollupRepeatedSoftDiagnostics(diagnostics, evidence) {
77
79
  ...(operationIds.length === 1 ? { operationId: operationIds[0] } : {}),
78
80
  details: {
79
81
  rollup: 'repeated-soft-diagnostics.v1',
82
+ ...(first.details?.attributionStatus === 'accepted-baseline'
83
+ ? {
84
+ attributionStatus: 'accepted-baseline',
85
+ baselineSeverity: first.details.baselineSeverity,
86
+ }
87
+ : {}),
80
88
  occurrenceCount: occurrences,
81
89
  retainedSamples: Math.min(SAMPLE_LIMIT, group.length),
82
90
  samples: group.slice(0, SAMPLE_LIMIT),
@@ -5,6 +5,7 @@ import { rollupRepeatedSoftDiagnostics } from './diagnostic-rollup.js';
5
5
  import { parseClausewitz } from './source/index.js';
6
6
  import { TRANSACTION_MAX_DIAGNOSTICS } from './transaction-limits.js';
7
7
  import { importContinuousFocusPalettes, importFocusTrees, layoutFocusTreeAsync, lintContinuousFocusPalette, lintFocusTree, } from '../focus/index.js';
8
+ import { referenceCatalog } from '../focus/tool-support.js';
8
9
  import { ScriptedGuiStudio } from '../gui/index.js';
9
10
  import { AgentNudger, attributeMapValidationDiagnostics } from '../map/index.js';
10
11
  import { PACKAGE_VERSION } from '../version.js';
@@ -12,21 +13,6 @@ function sourcePathComparisonKey(value) {
12
13
  const normalized = value.replaceAll('\\', '/');
13
14
  return process.platform === 'win32' ? normalized.toLocaleLowerCase('en-US') : normalized;
14
15
  }
15
- function focusReferences(engineSnapshot) {
16
- const active = (kind) => engineSnapshot.index
17
- .findAll(kind)
18
- .filter(({ overridden }) => !overridden)
19
- .map(({ id }) => id);
20
- return {
21
- decision: active('decision'),
22
- decision_category: active('decision_category'),
23
- event: active('event'),
24
- idea: active('idea'),
25
- leader: active('leader'),
26
- formable: active('formable'),
27
- helper: active('scripted_effect'),
28
- };
29
- }
30
16
  export async function postValidateTransaction(engine, transaction, principal, signal) {
31
17
  engine.invalidate(transaction.workspaceId);
32
18
  const workspace = engine.resolver.get(transaction.workspaceId, principal);
@@ -51,7 +37,8 @@ export async function postValidateTransaction(engine, transaction, principal, si
51
37
  });
52
38
  const checks = [];
53
39
  if (transaction.operationKind === 'focus-plan-changes') {
54
- const catalog = focusReferences(snapshot);
40
+ // The catalog the inspect after this rewrite reads too, so it is built once per snapshot.
41
+ const catalog = referenceCatalog(snapshot);
55
42
  for (const file of snapshot.files.filter(({ shadowedBy, relativePath }) => shadowedBy === undefined &&
56
43
  relativePath.toLowerCase().endsWith('.txt') &&
57
44
  changed.has(sourcePathComparisonKey(relativePath)))) {
@@ -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
+ }
@@ -20,6 +20,12 @@ const WORKER_EXIT_MESSAGE = 'The worker stopped without publishing a terminal jo
20
20
  const STDERR_TAIL_BYTES = 16_384;
21
21
  /** Standard-error logs of workers that exited unexpectedly kept for diagnosis. */
22
22
  const RETAINED_STDERR_LOGS = 10;
23
+ /**
24
+ * Longest wait for the worker that holds a workspace's newest index while it finishes a rewrite's
25
+ * after-edit check (decision D-98). That check rebuilds the same index a second worker would
26
+ * rebuild, so waiting for it is the cheaper path; past this bound the job takes another worker.
27
+ */
28
+ export const WORKSPACE_WORKER_WAIT_MS = 15_000;
23
29
  // Native and IPC codes are fixed vocabulary. Error messages can contain paths or source
24
30
  // text, so only an allowlisted code and the fixed coordination stage are reported.
25
31
  const nativeFailureCodes = new Set([
@@ -96,6 +102,19 @@ function readTail(file) {
96
102
  }
97
103
  }
98
104
  /** Keep only the newest few worker logs; the rest are older diagnostics. */
105
+ /** A started worker whose process and channel are still up. */
106
+ function usableWorker(child) {
107
+ return (child.connected &&
108
+ child.exitCode === null &&
109
+ child.signalCode === null &&
110
+ child.pid !== undefined);
111
+ }
112
+ /** Let a worker taken from the idle list keep the event loop alive while it runs a job. */
113
+ function refWorker(child) {
114
+ child.ref();
115
+ child.channel?.ref();
116
+ return child;
117
+ }
99
118
  function pruneWorkerLogs(logRoot) {
100
119
  try {
101
120
  const logs = readdirSync(logRoot)
@@ -177,6 +196,11 @@ export class JobWorkerHost {
177
196
  if (!isDomainToolName(initial.request.toolName))
178
197
  throw new ServiceError('JOB_OPERATION_UNAVAILABLE', 'This domain has not yet been registered for worker execution');
179
198
  const signal = new AbortController().signal;
199
+ // A rewrite that answered before its after-edit check is still building the workspace's new
200
+ // index in its worker. When no idle worker has scanned the workspace yet, the next call on it
201
+ // waits for that worker and reads its index instead of building one from nothing.
202
+ if (this.engine.resolver.config().jobWorkerIdleSeconds > 0)
203
+ await this.awaitWorkspaceWorker(workspaceId, WORKSPACE_WORKER_WAIT_MS);
180
204
  const recovered = new Set();
181
205
  const progress = { stage: 'admission' };
182
206
  let preDispatchRecoveries = 0;
@@ -271,7 +295,7 @@ export class JobWorkerHost {
271
295
  };
272
296
  const warm = configuration.jobWorkerIdleSeconds > 0;
273
297
  progress.stage = 'startup';
274
- const reused = warm ? this.takeIdleWorker() : undefined;
298
+ const reused = warm ? this.takeIdleWorker(workspaceId) : undefined;
275
299
  const child = reused ?? (await this.startWorker(configuration.jobWorkerMaxHeapMiB));
276
300
  try {
277
301
  progress.stage = 'handoff';
@@ -287,6 +311,12 @@ export class JobWorkerHost {
287
311
  }
288
312
  progress.stage = 'dispatch';
289
313
  await this.dispatch(child, message, reused !== undefined);
314
+ // After this job the worker holds the workspace's newest scan and index.
315
+ if (warm) {
316
+ this.workspaceWorkers.set(workspaceId, { child, mutation: current.request.mutation });
317
+ const scanned = this.scannedWorkers.get(workspaceId) ?? new Set();
318
+ this.scannedWorkers.set(workspaceId, scanned.add(child));
319
+ }
290
320
  // Without warm reuse the persistent job, not the launcher's lifetime, owns execution once
291
321
  // the child confirmed receipt, so close the channel.
292
322
  if (!warm && child.connected)
@@ -363,20 +393,95 @@ export class JobWorkerHost {
363
393
  if (child.connected)
364
394
  child.disconnect();
365
395
  }
366
- takeIdleWorker() {
396
+ /** The worker that ran each workspace's last job, and whether that job was a rewrite. */
397
+ workspaceWorkers = new Map();
398
+ /** Every warm worker that ran a job on each workspace and so holds a scan of it, maybe older. */
399
+ scannedWorkers = new Map();
400
+ /** Jobs waiting for a busy worker to finish, by worker. */
401
+ idleWaiters = new Map();
402
+ /**
403
+ * An idle warm worker for a job on `workspaceId`: the one that ran the workspace's last job, which
404
+ * holds its newest scan and index, else the most recently used one that scanned the workspace
405
+ * before, else the most recently used one. A reused index is still checked against the files:
406
+ * the worker scans again and rebuilds whatever changed (D-98).
407
+ */
408
+ takeIdleWorker(workspaceId) {
409
+ const preferred = workspaceId === undefined ? undefined : this.workspaceWorkers.get(workspaceId)?.child;
410
+ const position = preferred === undefined ? -1 : this.idleWorkers.indexOf(preferred);
411
+ if (position >= 0) {
412
+ this.idleWorkers.splice(position, 1);
413
+ if (usableWorker(preferred))
414
+ return refWorker(preferred);
415
+ }
416
+ const scanned = this.idleScannedWorker(workspaceId);
417
+ if (scanned !== undefined) {
418
+ this.idleWorkers.splice(this.idleWorkers.indexOf(scanned), 1);
419
+ return refWorker(scanned);
420
+ }
367
421
  for (;;) {
368
422
  const child = this.idleWorkers.pop();
369
423
  if (child === undefined)
370
424
  return undefined;
371
- if (child.connected &&
372
- child.exitCode === null &&
373
- child.signalCode === null &&
374
- child.pid !== undefined) {
375
- child.ref();
376
- child.channel?.ref();
425
+ if (usableWorker(child))
426
+ return refWorker(child);
427
+ }
428
+ }
429
+ /** The most recently used idle, usable worker that scanned `workspaceId` before, if any. */
430
+ idleScannedWorker(workspaceId) {
431
+ const scanned = workspaceId === undefined ? undefined : this.scannedWorkers.get(workspaceId);
432
+ if (scanned === undefined)
433
+ return undefined;
434
+ for (const child of scanned)
435
+ if (!usableWorker(child))
436
+ scanned.delete(child);
437
+ for (let index = this.idleWorkers.length - 1; index >= 0; index -= 1) {
438
+ const child = this.idleWorkers[index];
439
+ if (scanned.has(child) && usableWorker(child))
377
440
  return child;
378
- }
379
441
  }
442
+ return undefined;
443
+ }
444
+ /**
445
+ * Wait, at most `limitMs`, while the worker that last ran a rewrite on `workspaceId` is still busy
446
+ * with it, typically the after-edit check of a rewrite that answered early. Returns whether a
447
+ * worker with a scan of the workspace is idle now. No wait happens when another idle worker
448
+ * scanned the workspace before: it rescans only the changed files, which is no slower than
449
+ * waiting for the check. A read that is still running is not waited for: it may run for minutes.
450
+ */
451
+ async awaitWorkspaceWorker(workspaceId, limitMs) {
452
+ const newest = this.workspaceWorkers.get(workspaceId);
453
+ if (newest === undefined || !usableWorker(newest.child))
454
+ return false;
455
+ if (this.idleWorkers.includes(newest.child))
456
+ return true;
457
+ if (this.idleScannedWorker(workspaceId) !== undefined)
458
+ return true;
459
+ if (!newest.mutation)
460
+ return false;
461
+ const { child } = newest;
462
+ return new Promise((resolve) => {
463
+ const waiters = this.idleWaiters.get(child) ?? new Set();
464
+ this.idleWaiters.set(child, waiters);
465
+ const timer = setTimeout(() => finish(false), limitMs);
466
+ const onExit = () => finish(false);
467
+ function finish(idle) {
468
+ clearTimeout(timer);
469
+ waiters.delete(finish);
470
+ child.off('exit', onExit);
471
+ resolve(idle);
472
+ }
473
+ waiters.add(finish);
474
+ child.once('exit', onExit);
475
+ });
476
+ }
477
+ /** Tell the jobs waiting for `child` that it finished its job, kept warm or not. */
478
+ notifyIdleWaiters(child, idle) {
479
+ const waiters = this.idleWaiters.get(child);
480
+ if (waiters === undefined)
481
+ return;
482
+ this.idleWaiters.delete(child);
483
+ for (const finish of [...waiters])
484
+ finish(idle);
380
485
  }
381
486
  /** Start a fixed-entry worker and wait for its readiness handshake. */
382
487
  async startWorker(maxHeapMiB) {
@@ -489,8 +594,18 @@ export class JobWorkerHost {
489
594
  * and keep it for the next job. A worker that does not report idle is left to exit.
490
595
  */
491
596
  async keepWarm(child, lease) {
597
+ let idle = false;
598
+ try {
599
+ idle = await this.parkWorker(child, lease);
600
+ }
601
+ finally {
602
+ this.notifyIdleWaiters(child, idle);
603
+ }
604
+ }
605
+ /** Put a worker that finished its job into the idle list; returns whether it is there. */
606
+ async parkWorker(child, lease) {
492
607
  if (!child.connected || child.exitCode !== null || child.signalCode !== null)
493
- return;
608
+ return false;
494
609
  const idle = await new Promise((resolve) => {
495
610
  if (this.reportedIdle.has(child)) {
496
611
  resolve(true);
@@ -516,12 +631,13 @@ export class JobWorkerHost {
516
631
  if (!idle || !connected()) {
517
632
  if (connected())
518
633
  child.disconnect();
519
- return;
634
+ return false;
520
635
  }
521
636
  await lease.reclaimFromProcess();
522
637
  // An idle worker must not keep this server's event loop alive.
523
638
  child.unref();
524
639
  child.channel?.unref();
525
640
  this.idleWorkers.push(child);
641
+ return true;
526
642
  }
527
643
  }
@@ -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