hoi4-agent-tools 3.0.8 → 3.1.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 (135) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/README.md +4 -0
  3. package/dist/bin/stdio.js +23 -12
  4. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +82 -0
  5. package/dist/hoi4_agent_tools/core/artifact-resource.js +173 -0
  6. package/dist/hoi4_agent_tools/core/artifacts.js +84 -2
  7. package/dist/hoi4_agent_tools/core/condition-evaluator.js +399 -0
  8. package/dist/hoi4_agent_tools/core/condition-model.js +1 -0
  9. package/dist/hoi4_agent_tools/core/condition-schema.js +42 -0
  10. package/dist/hoi4_agent_tools/core/dependency-pages.js +216 -0
  11. package/dist/hoi4_agent_tools/core/dependency-walk.js +266 -0
  12. package/dist/hoi4_agent_tools/core/domain-validation.js +188 -0
  13. package/dist/hoi4_agent_tools/core/engine.js +48 -5
  14. package/dist/hoi4_agent_tools/core/helper-expansion.js +186 -0
  15. package/dist/hoi4_agent_tools/core/index-segments.js +137 -0
  16. package/dist/hoi4_agent_tools/core/index.js +47 -4
  17. package/dist/hoi4_agent_tools/core/job-controls.js +109 -0
  18. package/dist/hoi4_agent_tools/core/job-executor.js +190 -0
  19. package/dist/hoi4_agent_tools/core/job-service.js +112 -0
  20. package/dist/hoi4_agent_tools/core/job-store.js +641 -0
  21. package/dist/hoi4_agent_tools/core/job-transactions.js +126 -0
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +200 -0
  23. package/dist/hoi4_agent_tools/core/job-worker.js +62 -0
  24. package/dist/hoi4_agent_tools/core/operation-context.js +31 -0
  25. package/dist/hoi4_agent_tools/core/operation-result.js +412 -0
  26. package/dist/hoi4_agent_tools/core/operation-tasks.js +382 -0
  27. package/dist/hoi4_agent_tools/core/persistent-analysis-cache.js +383 -0
  28. package/dist/hoi4_agent_tools/core/result.js +1 -0
  29. package/dist/hoi4_agent_tools/core/scanner.js +15 -75
  30. package/dist/hoi4_agent_tools/core/scenario-state.js +97 -0
  31. package/dist/hoi4_agent_tools/core/semantic-dependencies.js +233 -0
  32. package/dist/hoi4_agent_tools/core/shared-request-capacity.js +74 -25
  33. package/dist/hoi4_agent_tools/core/source/cache.js +107 -0
  34. package/dist/hoi4_agent_tools/core/source/parser.js +11 -1
  35. package/dist/hoi4_agent_tools/core/transaction-execution.js +134 -0
  36. package/dist/hoi4_agent_tools/core/transactions.js +80 -27
  37. package/dist/hoi4_agent_tools/event/graph.js +214 -290
  38. package/dist/hoi4_agent_tools/event/helper-expansion.js +33 -0
  39. package/dist/hoi4_agent_tools/event/job-operations.js +51 -0
  40. package/dist/hoi4_agent_tools/event/operations.js +179 -0
  41. package/dist/hoi4_agent_tools/event/service.js +67 -15
  42. package/dist/hoi4_agent_tools/event/source-analysis.js +5 -4
  43. package/dist/hoi4_agent_tools/focus/job-operations.js +77 -0
  44. package/dist/hoi4_agent_tools/focus/tool-operations.js +669 -0
  45. package/dist/hoi4_agent_tools/focus/tool-support.js +123 -0
  46. package/dist/hoi4_agent_tools/gui/job-operations.js +81 -0
  47. package/dist/hoi4_agent_tools/gui/scenario-conditions.js +119 -0
  48. package/dist/hoi4_agent_tools/gui/scenario-generator.js +59 -73
  49. package/dist/hoi4_agent_tools/gui/scenario.js +3 -0
  50. package/dist/hoi4_agent_tools/gui/studio.js +5 -2
  51. package/dist/hoi4_agent_tools/gui/tool-operations.js +270 -0
  52. package/dist/hoi4_agent_tools/map/job-operations.js +76 -0
  53. package/dist/hoi4_agent_tools/map/tool-operations.js +493 -0
  54. package/dist/hoi4_agent_tools/mcp/prompts/probability.js +25 -0
  55. package/dist/hoi4_agent_tools/mcp/prompts/register-modern.js +29 -0
  56. package/dist/hoi4_agent_tools/mcp/resources/register-modern.js +34 -0
  57. package/dist/hoi4_agent_tools/mcp/resources/register.js +4 -150
  58. package/dist/hoi4_agent_tools/mcp/server/base-tools.js +3 -219
  59. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +188 -0
  60. package/dist/hoi4_agent_tools/mcp/server/create.js +16 -6
  61. package/dist/hoi4_agent_tools/mcp/server/instructions.js +2 -0
  62. package/dist/hoi4_agent_tools/mcp/server/job-task-store.js +67 -0
  63. package/dist/hoi4_agent_tools/mcp/server/legacy-task-tools.js +20 -0
  64. package/dist/hoi4_agent_tools/mcp/server/modern-tasks.js +168 -0
  65. package/dist/hoi4_agent_tools/mcp/server/progress.js +17 -15
  66. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +43 -0
  67. package/dist/hoi4_agent_tools/mcp/server/result.js +2 -412
  68. package/dist/hoi4_agent_tools/mcp/server/task-request-context.js +9 -0
  69. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +14 -0
  70. package/dist/hoi4_agent_tools/mcp/server/task-tool-definition.js +1 -0
  71. package/dist/hoi4_agent_tools/mcp/server/transaction-execution.js +1 -123
  72. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +38 -21
  73. package/dist/hoi4_agent_tools/mcp/tools/event.js +24 -315
  74. package/dist/hoi4_agent_tools/mcp/tools/focus.js +34 -1039
  75. package/dist/hoi4_agent_tools/mcp/tools/gui.js +19 -504
  76. package/dist/hoi4_agent_tools/mcp/tools/job.js +46 -0
  77. package/dist/hoi4_agent_tools/mcp/tools/map.js +21 -600
  78. package/dist/hoi4_agent_tools/mcp/tools/probability.js +39 -463
  79. package/dist/hoi4_agent_tools/mcp/tools/technology.js +40 -304
  80. package/dist/hoi4_agent_tools/mcp/transports/http.js +58 -1
  81. package/dist/hoi4_agent_tools/mcp/transports/modern-task-routing.js +109 -0
  82. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +121 -0
  83. package/dist/hoi4_agent_tools/probability/job-operations.js +58 -0
  84. package/dist/hoi4_agent_tools/probability/operations.js +183 -0
  85. package/dist/hoi4_agent_tools/probability/scenario-state.js +2 -95
  86. package/dist/hoi4_agent_tools/probability/service.js +24 -3
  87. package/dist/hoi4_agent_tools/probability/trigger-evaluator.js +1 -287
  88. package/dist/hoi4_agent_tools/schemas/common.js +2 -0
  89. package/dist/hoi4_agent_tools/schemas/event.js +72 -1
  90. package/dist/hoi4_agent_tools/schemas/focus-requests.js +189 -0
  91. package/dist/hoi4_agent_tools/schemas/gui-requests.js +193 -0
  92. package/dist/hoi4_agent_tools/schemas/helper-expansion.js +58 -0
  93. package/dist/hoi4_agent_tools/schemas/map-requests.js +85 -0
  94. package/dist/hoi4_agent_tools/schemas/probability-requests.js +168 -0
  95. package/dist/hoi4_agent_tools/schemas/technology.js +90 -1
  96. package/dist/hoi4_agent_tools/schemas/transaction.js +1 -0
  97. package/dist/hoi4_agent_tools/technology/graph.js +83 -78
  98. package/dist/hoi4_agent_tools/technology/helper-expansion.js +33 -0
  99. package/dist/hoi4_agent_tools/technology/job-operations.js +60 -0
  100. package/dist/hoi4_agent_tools/technology/operations.js +125 -0
  101. package/dist/hoi4_agent_tools/technology/service.js +89 -15
  102. package/dist/hoi4_agent_tools/technology/source-analysis.js +2 -1
  103. package/dist/hoi4_agent_tools/version.js +1 -1
  104. package/docs/README.md +2 -0
  105. package/docs/development.md +2 -0
  106. package/docs/events.md +7 -2
  107. package/docs/gui.md +3 -1
  108. package/docs/helper-expansion.md +78 -0
  109. package/docs/http.md +2 -0
  110. package/docs/jobs.md +85 -0
  111. package/docs/technology.md +6 -2
  112. package/package.json +11 -5
  113. package/schemas/configuration.schema.json +1 -1
  114. package/schemas/continuous-focus-palette.schema.json +1 -1
  115. package/schemas/custom-weighted-pool.schema.json +1 -1
  116. package/schemas/event-feature-manifest.schema.json +1 -1
  117. package/schemas/focus-plan.schema.json +1 -1
  118. package/schemas/focus-planning-sidecar.schema.json +1 -1
  119. package/schemas/gui-animation-source.schema.json +1 -1
  120. package/schemas/gui-helper.schema.json +1 -1
  121. package/schemas/gui-scenario.schema.json +189 -33
  122. package/schemas/helper-expansion-request.schema.json +44 -0
  123. package/schemas/helper-expansion-summary.schema.json +70 -0
  124. package/schemas/map-operation.schema.json +1 -1
  125. package/schemas/operation-result.schema.json +1 -1
  126. package/schemas/probability-analysis-result.schema.json +1 -1
  127. package/schemas/probability-compare-input.schema.json +1 -1
  128. package/schemas/probability-evaluate-input.schema.json +1 -1
  129. package/schemas/probability-inspect-input.schema.json +1 -1
  130. package/schemas/probability-render-input.schema.json +1 -1
  131. package/schemas/probability-scenario-set.schema.json +1 -1
  132. package/schemas/probability-sequence-input.schema.json +1 -1
  133. package/schemas/probability-simulate-input.schema.json +1 -1
  134. package/schemas/probability-sweep-input.schema.json +1 -1
  135. package/server.json +2 -2
@@ -0,0 +1,266 @@
1
+ import { z } from 'zod/v4';
2
+ import { hashCanonical } from './canonical.js';
3
+ import { currentAnalysisCheckpoints } from './analysis-checkpoints.js';
4
+ import { ServiceError } from './result.js';
5
+ const ordinal = z.number().int().nonnegative();
6
+ const pathSchema = z.object({ edge: ordinal, parent: ordinal.nullable() }).strict();
7
+ const recordSchema = z
8
+ .object({
9
+ kind: z.enum(['visit', 'terminal', 'cycle', 'depth']),
10
+ root: ordinal,
11
+ path: ordinal,
12
+ })
13
+ .strict();
14
+ const stateSchema = z
15
+ .object({
16
+ version: z.literal(1),
17
+ key: z.string(),
18
+ root: ordinal,
19
+ steps: ordinal,
20
+ paths: z.array(pathSchema),
21
+ records: z.array(recordSchema),
22
+ stack: z.array(ordinal),
23
+ visited: z.array(z.string()),
24
+ current: z.object({ path: ordinal, edge: ordinal }).strict().nullable(),
25
+ started: z.boolean(),
26
+ complete: z.boolean(),
27
+ })
28
+ .strict();
29
+ /** A bounded, serializable DFS frontier; paths share prefixes instead of copying source data. */
30
+ export class DependencyWalk {
31
+ input;
32
+ state;
33
+ key;
34
+ edges;
35
+ outgoing = new Map();
36
+ branches;
37
+ visited;
38
+ constructor(input, restored) {
39
+ this.input = input;
40
+ this.key = hashCanonical({ algorithm: 'dependency-walk.v1', ...input });
41
+ this.edges = new Map(input.edges.map(({ id }, index) => [id, index]));
42
+ if (this.edges.size !== input.edges.length || input.roots.some((id) => !this.edges.has(id)))
43
+ throw new ServiceError('DEPENDENCY_WALK_INPUT_INVALID', 'Dependency edge identities must be unique and roots must exist');
44
+ if (!Number.isSafeInteger(input.maximumDepth) ||
45
+ input.maximumDepth < 1 ||
46
+ !Number.isSafeInteger(input.maximumSteps) ||
47
+ input.maximumSteps < 1)
48
+ throw new ServiceError('DEPENDENCY_WALK_INPUT_INVALID', 'Dependency traversal requires finite positive bounds');
49
+ this.branches = new Set(input.branches);
50
+ for (const [index, edge] of input.edges.entries()) {
51
+ const values = this.outgoing.get(edge.from) ?? [];
52
+ values.push(index);
53
+ this.outgoing.set(edge.from, values);
54
+ }
55
+ if (input.reverseEdges)
56
+ for (const values of this.outgoing.values())
57
+ values.reverse();
58
+ const decoded = restored === undefined ? undefined : stateSchema.safeParse(restored);
59
+ if (decoded !== undefined && !decoded.success)
60
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_INVALID', 'Dependency checkpoint has an invalid state schema');
61
+ this.state = decoded?.data ?? {
62
+ version: 1,
63
+ key: this.key,
64
+ root: 0,
65
+ steps: 0,
66
+ paths: [],
67
+ records: [],
68
+ stack: [],
69
+ visited: [],
70
+ current: null,
71
+ started: false,
72
+ complete: input.roots.length === 0,
73
+ };
74
+ if (this.state.key !== this.key ||
75
+ this.state.root > input.roots.length ||
76
+ this.state.steps > input.maximumSteps)
77
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_STALE', 'Dependency checkpoint does not match this exact source graph and traversal contract');
78
+ this.validateState();
79
+ this.visited = new Set(this.state.visited);
80
+ }
81
+ validateState() {
82
+ const invalid = (message) => {
83
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_INVALID', message);
84
+ };
85
+ if (this.state.complete !== (this.state.root === this.input.roots.length) ||
86
+ (!this.state.started && (this.state.current !== null || this.state.stack.length !== 0)) ||
87
+ (this.state.complete && this.state.started) ||
88
+ this.state.paths.length > this.state.steps ||
89
+ this.state.records.length > this.state.steps ||
90
+ new Set(this.state.stack).size !== this.state.stack.length ||
91
+ new Set(this.state.visited).size !== this.state.visited.length)
92
+ invalid('Dependency checkpoint has inconsistent lifecycle or retained work');
93
+ const roots = [];
94
+ const rootEdges = new Set(this.input.roots.map((id) => this.edges.get(id)));
95
+ for (const [index, path] of this.state.paths.entries()) {
96
+ if (path.edge >= this.input.edges.length || (path.parent !== null && path.parent >= index))
97
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_INVALID', 'Dependency checkpoint contains an invalid path');
98
+ if (path.parent === null) {
99
+ if (!rootEdges.has(path.edge))
100
+ invalid('Dependency path starts outside the requested roots');
101
+ roots.push(path.edge);
102
+ }
103
+ else {
104
+ const previous = this.input.edges[this.state.paths[path.parent].edge];
105
+ if (previous.to !== this.input.edges[path.edge].from)
106
+ invalid('Dependency checkpoint path is disconnected from its parent edge');
107
+ roots.push(roots[path.parent]);
108
+ }
109
+ }
110
+ for (const index of [
111
+ ...this.state.stack,
112
+ ...(this.state.current === null ? [] : [this.state.current.path]),
113
+ ])
114
+ if (index >= this.state.paths.length ||
115
+ this.input.edges[roots[index]].id !== this.input.roots[this.state.root])
116
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_INVALID', 'Dependency frontier points outside its retained paths');
117
+ if (this.state.current !== null) {
118
+ const { path, edge } = this.state.current;
119
+ const node = this.input.edges[this.state.paths[path].edge].to;
120
+ if (edge > (this.outgoing.get(node)?.length ?? 0) || this.state.stack.includes(path))
121
+ invalid('Dependency adjacency cursor is outside its current node or duplicates the frontier');
122
+ }
123
+ for (const record of this.state.records)
124
+ if (record.root >= this.input.roots.length ||
125
+ record.path >= this.state.paths.length ||
126
+ this.input.edges[roots[record.path]].id !== this.input.roots[record.root])
127
+ throw new ServiceError('DEPENDENCY_CHECKPOINT_INVALID', 'Dependency evidence points outside its retained graph');
128
+ }
129
+ path(index) {
130
+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.state.paths.length)
131
+ throw new ServiceError('DEPENDENCY_PATH_INVALID', 'Dependency path ordinal is outside the retained frontier');
132
+ const values = [];
133
+ let cursor = index;
134
+ while (cursor !== null) {
135
+ const path = this.state.paths[cursor];
136
+ values.push(this.input.edges[path.edge]);
137
+ cursor = path.parent;
138
+ }
139
+ return values.reverse();
140
+ }
141
+ addPath(edge, parent) {
142
+ this.state.paths.push({ edge, parent });
143
+ return this.state.paths.length - 1;
144
+ }
145
+ record(kind, path) {
146
+ this.state.records.push({ kind, path, root: this.state.root });
147
+ }
148
+ /** Advance at most this many elementary transitions, including wide adjacency lists. */
149
+ advance(maximumSteps, signal) {
150
+ if (!Number.isSafeInteger(maximumSteps) || maximumSteps < 1)
151
+ throw new ServiceError('DEPENDENCY_BATCH_INVALID', 'Dependency batch size must be positive');
152
+ const end = this.state.steps + maximumSteps;
153
+ while (!this.state.complete && this.state.steps < end) {
154
+ signal?.throwIfAborted();
155
+ if (this.state.steps >= this.input.maximumSteps)
156
+ throw new ServiceError('DEPENDENCY_WORK_LIMIT', 'Dependency expansion reached its explicit work ceiling', {
157
+ maximum: this.input.maximumSteps,
158
+ completedRoots: this.state.root,
159
+ totalRoots: this.input.roots.length,
160
+ });
161
+ this.state.steps++;
162
+ if (!this.state.started) {
163
+ const edge = this.edges.get(this.input.roots[this.state.root]);
164
+ const rootPath = this.addPath(edge, null);
165
+ this.state.stack.push(rootPath);
166
+ this.visited.clear();
167
+ if (this.input.visitPolicy === 'node')
168
+ this.visited.add(this.input.edges[edge].to);
169
+ this.state.started = true;
170
+ continue;
171
+ }
172
+ if (this.state.current === null) {
173
+ const path = this.state.stack.pop();
174
+ if (path === undefined) {
175
+ this.state.root++;
176
+ this.state.started = false;
177
+ this.state.complete = this.state.root === this.input.roots.length;
178
+ continue;
179
+ }
180
+ if (this.input.visitPolicy === 'path') {
181
+ const key = this.path(path)
182
+ .map(({ to }) => to)
183
+ .join('\0');
184
+ if (this.visited.has(key))
185
+ continue;
186
+ this.visited.add(key);
187
+ }
188
+ this.record('visit', path);
189
+ this.state.current = { path, edge: 0 };
190
+ continue;
191
+ }
192
+ const current = this.state.current;
193
+ const node = this.input.edges[this.state.paths[current.path].edge].to;
194
+ const candidates = this.outgoing.get(node) ?? [];
195
+ const edgeIndex = candidates[current.edge++];
196
+ if (edgeIndex === undefined) {
197
+ this.state.current = null;
198
+ continue;
199
+ }
200
+ const edge = this.input.edges[edgeIndex];
201
+ if (!this.branches.has(edge.to)) {
202
+ this.record('terminal', this.addPath(edgeIndex, current.path));
203
+ continue;
204
+ }
205
+ const ancestors = this.path(current.path).map(({ to }) => to);
206
+ if (ancestors.includes(edge.to)) {
207
+ this.record('cycle', this.addPath(edgeIndex, current.path));
208
+ continue;
209
+ }
210
+ if (ancestors.length >= this.input.maximumDepth) {
211
+ this.record('depth', this.addPath(edgeIndex, current.path));
212
+ continue;
213
+ }
214
+ const visitKey = this.input.visitPolicy === 'node' ? edge.to : [...ancestors, edge.to].join('\0');
215
+ if (this.input.visitPolicy === 'node') {
216
+ if (this.visited.has(visitKey))
217
+ continue;
218
+ this.visited.add(visitKey);
219
+ }
220
+ this.state.stack.push(this.addPath(edgeIndex, current.path));
221
+ }
222
+ return this.state.complete;
223
+ }
224
+ checkpoint() {
225
+ this.state.visited = [...this.visited];
226
+ return this.state;
227
+ }
228
+ }
229
+ export function walkDependencies(input, signal) {
230
+ const walk = new DependencyWalk(input);
231
+ while (!walk.state.complete)
232
+ walk.advance(256, signal);
233
+ return walk;
234
+ }
235
+ export async function walkDependenciesAsync(input, signal, checkpointSteps = 2_048) {
236
+ signal?.throwIfAborted();
237
+ if (!Number.isSafeInteger(checkpointSteps) || checkpointSteps < 1)
238
+ throw new ServiceError('DEPENDENCY_BATCH_INVALID', 'Checkpoint interval must be positive');
239
+ const checkpoints = currentAnalysisCheckpoints();
240
+ const key = hashCanonical({ algorithm: 'dependency-walk.v1', ...input });
241
+ const restored = await checkpoints?.load(key, input.sourceRevision, stateSchema);
242
+ const walk = new DependencyWalk(input, restored);
243
+ let savedAt = walk.state.steps;
244
+ while (!walk.state.complete) {
245
+ const complete = walk.advance(256, signal);
246
+ if ((complete && savedAt > 0) || walk.state.steps - savedAt >= checkpointSteps) {
247
+ await checkpoints?.save(key, input.sourceRevision, walk.checkpoint(), walk.state.root, input.roots.length);
248
+ savedAt = walk.state.steps;
249
+ }
250
+ await new Promise((resolve) => setImmediate(resolve));
251
+ signal?.throwIfAborted();
252
+ }
253
+ return walk;
254
+ }
255
+ export function runDependencyAnalysis(analysis, signal) {
256
+ let next = analysis.next();
257
+ while (!next.done)
258
+ next = analysis.next(walkDependencies(next.value, signal));
259
+ return next.value;
260
+ }
261
+ export async function runDependencyAnalysisAsync(analysis, signal) {
262
+ let next = analysis.next();
263
+ while (!next.done)
264
+ next = analysis.next(await walkDependenciesAsync(next.value, signal));
265
+ return next.value;
266
+ }
@@ -0,0 +1,188 @@
1
+ import { boundedSourceHashEvidence, publicArtifactLink } from './artifacts.js';
2
+ import { canonicalJson } from './canonical.js';
3
+ import { exactChangedFilePatterns, focusDomainScanPatterns } from './domain-scan-patterns.js';
4
+ import { parseClausewitz } from './source/index.js';
5
+ import { TRANSACTION_MAX_DIAGNOSTICS } from './transaction-limits.js';
6
+ import { importContinuousFocusPalettes, importFocusTrees, layoutFocusTreeAsync, lintContinuousFocusPalette, lintFocusTree, } from '../focus/index.js';
7
+ import { ScriptedGuiStudio } from '../gui/index.js';
8
+ import { AgentNudger, attributeMapValidationDiagnostics } from '../map/index.js';
9
+ import { PACKAGE_VERSION } from '../version.js';
10
+ function sourcePathComparisonKey(value) {
11
+ const normalized = value.replaceAll('\\', '/');
12
+ return process.platform === 'win32' ? normalized.toLocaleLowerCase('en-US') : normalized;
13
+ }
14
+ function focusReferences(engineSnapshot) {
15
+ const active = (kind) => engineSnapshot.index
16
+ .findAll(kind)
17
+ .filter(({ overridden }) => !overridden)
18
+ .map(({ id }) => id);
19
+ return {
20
+ decision: active('decision'),
21
+ decision_category: active('decision_category'),
22
+ event: active('event'),
23
+ idea: active('idea'),
24
+ leader: active('leader'),
25
+ formable: active('formable'),
26
+ helper: active('scripted_effect'),
27
+ };
28
+ }
29
+ export async function postValidateTransaction(engine, transaction, principal, signal) {
30
+ engine.invalidate(transaction.workspaceId);
31
+ const workspace = engine.resolver.get(transaction.workspaceId, principal);
32
+ const focusTransaction = transaction.operationKind === 'focus-plan-changes' ||
33
+ transaction.operationKind === 'continuous-focus-plan-changes';
34
+ const snapshot = await engine.scan(transaction.workspaceId, {
35
+ patterns: focusTransaction
36
+ ? focusDomainScanPatterns(workspace)
37
+ : exactChangedFilePatterns(transaction.files.map(({ relativePath }) => relativePath)),
38
+ }, principal, signal);
39
+ const changed = new Set(transaction.files.map(({ relativePath }) => sourcePathComparisonKey(relativePath)));
40
+ const diagnostics = snapshot.diagnostics.filter(({ location }) => {
41
+ if (location === undefined)
42
+ return false;
43
+ const sourcePath = sourcePathComparisonKey(location.path);
44
+ return [...changed].some((relativePath) => sourcePath.endsWith(`:${relativePath}`));
45
+ });
46
+ const checks = [];
47
+ if (transaction.operationKind === 'focus-plan-changes') {
48
+ const catalog = focusReferences(snapshot);
49
+ for (const file of snapshot.files.filter(({ shadowedBy, relativePath }) => shadowedBy === undefined &&
50
+ relativePath.toLowerCase().endsWith('.txt') &&
51
+ changed.has(sourcePathComparisonKey(relativePath)))) {
52
+ const document = parseClausewitz(file.bytes, file.displayPath);
53
+ const imported = importFocusTrees(document, { references: catalog });
54
+ diagnostics.push(...imported.diagnostics);
55
+ for (const plan of imported.plans) {
56
+ const layout = await layoutFocusTreeAsync(plan, signal === undefined ? {} : { signal });
57
+ diagnostics.push(...lintFocusTree(plan, {
58
+ index: snapshot.index,
59
+ references: catalog,
60
+ layout,
61
+ }));
62
+ }
63
+ }
64
+ const passed = !diagnostics.some(({ severity }) => severity === 'error' || severity === 'blocker');
65
+ checks.push({
66
+ id: 'post-write-focus',
67
+ passed,
68
+ message: passed
69
+ ? 'The focus result re-imported, laid out, and linted successfully'
70
+ : 'The focus result failed post-write import or lint',
71
+ });
72
+ }
73
+ else if (transaction.operationKind === 'continuous-focus-plan-changes') {
74
+ for (const file of snapshot.files.filter(({ shadowedBy, relativePath }) => shadowedBy === undefined &&
75
+ relativePath.toLowerCase().endsWith('.txt') &&
76
+ changed.has(sourcePathComparisonKey(relativePath)))) {
77
+ const imported = importContinuousFocusPalettes(parseClausewitz(file.bytes, file.displayPath));
78
+ diagnostics.push(...imported.diagnostics);
79
+ for (const plan of imported.continuousFocusPalettes) {
80
+ diagnostics.push(...lintContinuousFocusPalette(plan));
81
+ }
82
+ }
83
+ const passed = !diagnostics.some(({ severity }) => severity === 'error' || severity === 'blocker');
84
+ checks.push({
85
+ id: 'post-write-continuous-focus',
86
+ passed,
87
+ message: passed
88
+ ? 'The continuous focus result re-imported and linted successfully'
89
+ : 'The continuous focus result failed post-write import or lint',
90
+ });
91
+ }
92
+ else if (transaction.operationKind === 'gui-source-change' ||
93
+ transaction.operationKind === 'gui-helper-compilation') {
94
+ const studio = new ScriptedGuiStudio(engine);
95
+ const scanned = await studio.scan(transaction.workspaceId, principal, signal);
96
+ diagnostics.push(...scanned.graph.diagnostics);
97
+ const passed = !scanned.graph.diagnostics.some(({ severity }) => severity === 'error' || severity === 'blocker');
98
+ checks.push({
99
+ id: 'post-write-gui-graph',
100
+ passed,
101
+ message: passed
102
+ ? 'The GUI graph rebuilt successfully'
103
+ : 'The GUI graph has blocking diagnostics',
104
+ });
105
+ }
106
+ else if (transaction.operationKind === 'agent-nudger-map-changes') {
107
+ const nudger = new AgentNudger(engine);
108
+ const validated = await nudger.validate(transaction.workspaceId, principal, signal);
109
+ const mapDiagnostics = attributeMapValidationDiagnostics({
110
+ diagnostics: [...diagnostics, ...validated.validation.diagnostics],
111
+ operations: transaction.operations,
112
+ changes: transaction.files,
113
+ });
114
+ diagnostics.length = 0;
115
+ diagnostics.push(...mapDiagnostics);
116
+ checks.push(...validated.validation.checks);
117
+ checks.push({
118
+ id: 'post-write-map',
119
+ passed: validated.validation.passed,
120
+ message: validated.validation.passed
121
+ ? 'The map result rescanned and validated successfully'
122
+ : 'The map result failed post-write validation',
123
+ });
124
+ }
125
+ const passed = !diagnostics.some(({ severity }) => severity === 'error' || severity === 'blocker');
126
+ checks.unshift({
127
+ id: 'post-write-shared-index',
128
+ passed,
129
+ message: passed
130
+ ? 'Changed files reparsed and reindexed successfully'
131
+ : 'Changed files have blocking post-write diagnostics',
132
+ });
133
+ const availableDiagnostics = Math.max(0, TRANSACTION_MAX_DIAGNOSTICS - transaction.diagnostics.length);
134
+ if (diagnostics.length > availableDiagnostics) {
135
+ const workspace = engine.resolver.get(transaction.workspaceId, principal);
136
+ const sourceEvidence = boundedSourceHashEvidence(Object.fromEntries(transaction.files.flatMap(({ relativePath, afterSha256 }) => afterSha256 === null ? [] : [[relativePath, afterSha256]])));
137
+ const artifact = await engine.artifacts.putChunked(workspace, `${transaction.operationKind}.post-validation.json`, 'application/json', `${canonicalJson({
138
+ schemaVersion: 1,
139
+ operationKind: transaction.operationKind,
140
+ diagnosticCount: diagnostics.length,
141
+ checks,
142
+ diagnostics,
143
+ })}\n`, {
144
+ kind: 'rewrite-post-validation',
145
+ toolVersion: PACKAGE_VERSION,
146
+ schemaVersion: 'rewrite-post-validation.v1',
147
+ sourceHashes: sourceEvidence.sourceHashes,
148
+ metadata: { sourceHashInventory: sourceEvidence.inventory },
149
+ }, 'Complete diagnostics from post-write validation', signal);
150
+ const retainedLimit = Math.max(0, availableDiagnostics - 1);
151
+ const hard = diagnostics.filter(({ severity }) => severity === 'error' || severity === 'blocker');
152
+ const retainedHard = hard.slice(0, retainedLimit);
153
+ const retainedSoft = diagnostics
154
+ .filter(({ severity }) => severity !== 'error' && severity !== 'blocker')
155
+ .slice(0, retainedLimit - retainedHard.length);
156
+ const omittedHard = hard.length - retainedHard.length;
157
+ const artifactLink = publicArtifactLink(artifact);
158
+ checks.push({
159
+ id: 'post-write-diagnostics-artifact',
160
+ passed: omittedHard === 0,
161
+ message: `Complete post-write diagnostics are stored at ${artifactLink.uri}`,
162
+ });
163
+ return {
164
+ diagnostics: availableDiagnostics === 0
165
+ ? []
166
+ : [
167
+ ...retainedHard,
168
+ ...retainedSoft,
169
+ {
170
+ code: 'POST_VALIDATION_DIAGNOSTICS_IN_ARTIFACT',
171
+ severity: omittedHard > 0 ? 'blocker' : 'warning',
172
+ category: 'validation',
173
+ message: `Complete post-write validation contains ${diagnostics.length} diagnostics and is stored as an artifact`,
174
+ details: {
175
+ total: diagnostics.length,
176
+ returned: availableDiagnostics,
177
+ omitted: diagnostics.length - retainedLimit,
178
+ omittedHard,
179
+ artifact: artifactLink,
180
+ },
181
+ },
182
+ ],
183
+ checks,
184
+ artifacts: [artifactLink],
185
+ };
186
+ }
187
+ return { diagnostics, checks, artifacts: [] };
188
+ }
@@ -1,10 +1,14 @@
1
1
  import { compareCodeUnits, hashCanonical } from './canonical.js';
2
2
  import { SymbolIndex } from './index.js';
3
+ import { IndexSegmentCache } from './index-segments.js';
4
+ import { PersistentAnalysisCache, } from './persistent-analysis-cache.js';
5
+ import { sourceDocuments } from './source/cache.js';
3
6
  import { WorkspaceScanner } from './scanner.js';
4
7
  import { ArtifactStore } from './artifacts.js';
5
- import { TransactionManager } from './transactions.js';
8
+ import { TransactionManager, transactionRootFingerprint } from './transactions.js';
6
9
  import { RequestScheduler } from './request-scheduler.js';
7
10
  import { SharedRequestCapacity } from './shared-request-capacity.js';
11
+ import { JobStore } from './job-store.js';
8
12
  const RECOVERY_TTL_SECONDS = 3_600;
9
13
  const RECOVERY_MAX_BYTES = 536_870_912;
10
14
  const RECOVERY_MAX_RECORDS = 128;
@@ -81,6 +85,8 @@ export class CoreEngine {
81
85
  scanner;
82
86
  artifacts;
83
87
  transactions;
88
+ indexSegments;
89
+ persistentAnalysisCache;
84
90
  #scanCache = new Map();
85
91
  #scanFlights = new Map();
86
92
  #scanGenerations = new Map();
@@ -88,14 +94,30 @@ export class CoreEngine {
88
94
  #activeScanAdmissions = new Set();
89
95
  constructor(resolver, services = {}) {
90
96
  this.resolver = resolver;
97
+ this.indexSegments = services.indexSegments ?? new IndexSegmentCache();
98
+ const state = resolver.serverState();
99
+ this.persistentAnalysisCache =
100
+ services.persistentAnalysisCache === null || state === undefined
101
+ ? undefined
102
+ : Promise.resolve(services.persistentAnalysisCache ?? PersistentAnalysisCache.create(state));
91
103
  this.requests = new RequestScheduler(resolver.config().maxConcurrentTools);
92
104
  this.sharedRequests = new SharedRequestCapacity(resolver.serverState()?.root, resolver.config().maxSharedTools);
93
105
  this.scanner =
94
106
  services.scanner ??
95
107
  new WorkspaceScanner(resolver.config().scanMaxFiles, resolver.config().scanMaxBytes, resolver.config().scanMaxFileBytes);
108
+ let retentionJobs;
96
109
  this.artifacts =
97
110
  services.artifacts ??
98
- new ArtifactStore(resolver.config().artifactMaxBytes, resolver.config().artifactMaxEntries, resolver.config().artifactMaxSingleBytes);
111
+ new ArtifactStore(resolver.config().artifactMaxBytes, resolver.config().artifactMaxEntries, resolver.config().artifactMaxSingleBytes, state === undefined
112
+ ? undefined
113
+ : async (workspace, signal) => {
114
+ retentionJobs ??= JobStore.create(state);
115
+ return (await retentionJobs).checkpointResources({
116
+ workspaceId: workspace.id,
117
+ workspaceIdentity: workspace.workspaceIdentity,
118
+ rootFingerprint: transactionRootFingerprint(workspace),
119
+ }, signal);
120
+ });
99
121
  this.transactions =
100
122
  services.transactions ??
101
123
  new TransactionManager(resolver, this.artifacts, RECOVERY_TTL_SECONDS, RECOVERY_MAX_BYTES, RECOVERY_MAX_RECORDS, resolver.serverState());
@@ -160,12 +182,28 @@ export class CoreEngine {
160
182
  signal: controller.signal,
161
183
  });
162
184
  controller.signal.throwIfAborted();
163
- const revision = hashCanonical(files.map(({ displayPath, loadOrder, sha256 }) => ({ displayPath, loadOrder, sha256 })));
185
+ const persistentAnalysisCache = await this.persistentAnalysisCache;
186
+ const analysisScope = {
187
+ workspaceIdentity: workspace.workspaceIdentity,
188
+ rootFingerprint: transactionRootFingerprint(workspace),
189
+ principal: principal ?? null,
190
+ };
191
+ await persistentAnalysisCache?.hydrate(analysisScope, files, sourceDocuments, this.indexSegments, controller.signal);
192
+ const revision = hashCanonical(files.map(({ absolutePath, displayPath, relativePath, rootKind, loadOrder, shadowedBy, sha256, }) => ({
193
+ absolutePath,
194
+ displayPath,
195
+ relativePath,
196
+ rootKind,
197
+ loadOrder,
198
+ shadowedBy: shadowedBy ?? null,
199
+ sha256,
200
+ })));
164
201
  const cacheKey = `${requestKey}:${revision}`;
165
202
  const cached = this.#scanCache.get(cacheKey);
166
203
  if (cached !== undefined)
167
204
  return cached;
168
- const index = await SymbolIndex.buildAsync(files, controller.signal);
205
+ const index = await SymbolIndex.buildAsync(files, controller.signal, this.indexSegments);
206
+ await persistentAnalysisCache?.persist(analysisScope, files, sourceDocuments, this.indexSegments, controller.signal);
169
207
  const snapshot = {
170
208
  workspaceId,
171
209
  revision,
@@ -219,12 +257,17 @@ export class CoreEngine {
219
257
  /** Drop completed scan buffers without invalidating revisions or interrupting active scans. */
220
258
  releaseScanCaches() {
221
259
  this.#scanCache.clear();
260
+ this.indexSegments.clear();
261
+ sourceDocuments.clear();
222
262
  this.scanner.clearCaches();
223
263
  }
224
264
  /** Monotonic cache generation used by domain services to invalidate derived snapshots. */
225
265
  generation(workspaceId) {
226
266
  return this.#scanGenerations.get(workspaceId) ?? 0;
227
267
  }
268
+ async persistentAnalysisCacheStatistics() {
269
+ return (await this.persistentAnalysisCache)?.statistics();
270
+ }
228
271
  awaitScanFlight(requestKey, flight, signal) {
229
272
  signal?.throwIfAborted();
230
273
  flight.waiters += 1;
@@ -342,6 +385,6 @@ export class CoreEngine {
342
385
  }
343
386
  }
344
387
  indexFiles(files) {
345
- return SymbolIndex.build(files);
388
+ return SymbolIndex.build(files, this.indexSegments);
346
389
  }
347
390
  }