@hydranium/core 1.0.0-next.4 → 1.0.0-next.40

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 (228) hide show
  1. package/lib/documents/ast-document-manager.d.ts +42 -5
  2. package/lib/documents/ast-document-manager.d.ts.map +1 -1
  3. package/lib/documents/ast-document-manager.js +9 -12
  4. package/lib/documents/ast-document-manager.js.map +1 -1
  5. package/lib/documents/hydranium-text-documents.d.ts.map +1 -1
  6. package/lib/documents/hydranium-text-documents.js +41 -9
  7. package/lib/documents/hydranium-text-documents.js.map +1 -1
  8. package/lib/documents/language-client-text-shadow.d.ts +24 -1
  9. package/lib/documents/language-client-text-shadow.d.ts.map +1 -1
  10. package/lib/documents/language-client-text-shadow.js +36 -2
  11. package/lib/documents/language-client-text-shadow.js.map +1 -1
  12. package/lib/documents/self-save-registry.d.ts +37 -6
  13. package/lib/documents/self-save-registry.d.ts.map +1 -1
  14. package/lib/documents/self-save-registry.js +28 -15
  15. package/lib/documents/self-save-registry.js.map +1 -1
  16. package/lib/index.d.ts +2 -0
  17. package/lib/index.d.ts.map +1 -1
  18. package/lib/index.js +5 -0
  19. package/lib/index.js.map +1 -1
  20. package/lib/langium/ast-extension/ast-node-builder.d.ts +32 -9
  21. package/lib/langium/ast-extension/ast-node-builder.d.ts.map +1 -1
  22. package/lib/langium/ast-extension/ast-node-builder.js +60 -22
  23. package/lib/langium/ast-extension/ast-node-builder.js.map +1 -1
  24. package/lib/langium/bootstrap.d.ts.map +1 -1
  25. package/lib/langium/bootstrap.js +16 -9
  26. package/lib/langium/bootstrap.js.map +1 -1
  27. package/lib/langium/document-builder/build-pipeline-integration.d.ts +13 -1
  28. package/lib/langium/document-builder/build-pipeline-integration.d.ts.map +1 -1
  29. package/lib/langium/document-builder/build-pipeline-integration.js +1 -1
  30. package/lib/langium/document-builder/build-pipeline-integration.js.map +1 -1
  31. package/lib/langium/document-builder/build-session.d.ts +93 -0
  32. package/lib/langium/document-builder/build-session.d.ts.map +1 -0
  33. package/lib/langium/document-builder/build-session.js +72 -0
  34. package/lib/langium/document-builder/build-session.js.map +1 -0
  35. package/lib/langium/document-builder/document-builder.d.ts +150 -7
  36. package/lib/langium/document-builder/document-builder.d.ts.map +1 -1
  37. package/lib/langium/document-builder/document-builder.js +298 -11
  38. package/lib/langium/document-builder/document-builder.js.map +1 -1
  39. package/lib/langium/document-builder/index.d.ts +1 -0
  40. package/lib/langium/document-builder/index.d.ts.map +1 -1
  41. package/lib/langium/document-builder/index.js +1 -0
  42. package/lib/langium/document-builder/index.js.map +1 -1
  43. package/lib/langium/integration-services.d.ts +45 -1
  44. package/lib/langium/integration-services.d.ts.map +1 -1
  45. package/lib/langium/integration-services.js +10 -5
  46. package/lib/langium/integration-services.js.map +1 -1
  47. package/lib/langium/integrity/integrity-service.d.ts +5 -0
  48. package/lib/langium/integrity/integrity-service.d.ts.map +1 -1
  49. package/lib/langium/integrity/integrity-service.js +34 -1
  50. package/lib/langium/integrity/integrity-service.js.map +1 -1
  51. package/lib/langium/keys/containment.d.ts +64 -0
  52. package/lib/langium/keys/containment.d.ts.map +1 -0
  53. package/lib/langium/keys/containment.js +53 -0
  54. package/lib/langium/keys/containment.js.map +1 -0
  55. package/lib/langium/keys/index.d.ts +1 -0
  56. package/lib/langium/keys/index.d.ts.map +1 -1
  57. package/lib/langium/keys/index.js +1 -0
  58. package/lib/langium/keys/index.js.map +1 -1
  59. package/lib/langium/keys/name-based-key-provider.d.ts +4 -0
  60. package/lib/langium/keys/name-based-key-provider.d.ts.map +1 -1
  61. package/lib/langium/keys/name-based-key-provider.js +4 -0
  62. package/lib/langium/keys/name-based-key-provider.js.map +1 -1
  63. package/lib/langium/model-service/model-service.d.ts +103 -7
  64. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  65. package/lib/langium/model-service/model-service.js +70 -89
  66. package/lib/langium/model-service/model-service.js.map +1 -1
  67. package/lib/langium/module.d.ts +82 -13
  68. package/lib/langium/module.d.ts.map +1 -1
  69. package/lib/langium/module.js +21 -12
  70. package/lib/langium/module.js.map +1 -1
  71. package/lib/langium/naming/name-provider.d.ts +10 -0
  72. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  73. package/lib/langium/naming/name-provider.js.map +1 -1
  74. package/lib/langium/naming/name-separator-validation.d.ts +23 -0
  75. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  76. package/lib/langium/naming/name-separator-validation.js +30 -1
  77. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  78. package/lib/langium/residency/cst-residency-service.d.ts +31 -9
  79. package/lib/langium/residency/cst-residency-service.d.ts.map +1 -1
  80. package/lib/langium/residency/cst-residency-service.js +13 -56
  81. package/lib/langium/residency/cst-residency-service.js.map +1 -1
  82. package/lib/langium/scope/hydranium-scope-provider.d.ts +32 -13
  83. package/lib/langium/scope/hydranium-scope-provider.d.ts.map +1 -1
  84. package/lib/langium/scope/hydranium-scope-provider.js +37 -20
  85. package/lib/langium/scope/hydranium-scope-provider.js.map +1 -1
  86. package/lib/langium/shared-services.d.ts +15 -2
  87. package/lib/langium/shared-services.d.ts.map +1 -1
  88. package/lib/langium/shared-services.js.map +1 -1
  89. package/lib/langium/transfer/transfer-encoder.d.ts +33 -2
  90. package/lib/langium/transfer/transfer-encoder.d.ts.map +1 -1
  91. package/lib/langium/transfer/transfer-encoder.js +14 -3
  92. package/lib/langium/transfer/transfer-encoder.js.map +1 -1
  93. package/lib/langium/validation/document-validator.d.ts +145 -6
  94. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  95. package/lib/langium/validation/document-validator.js +211 -4
  96. package/lib/langium/validation/document-validator.js.map +1 -1
  97. package/lib/langium/workspace/document-uri-policy.d.ts +3 -4
  98. package/lib/langium/workspace/document-uri-policy.d.ts.map +1 -1
  99. package/lib/langium/workspace/document-uri-policy.js +3 -4
  100. package/lib/langium/workspace/document-uri-policy.js.map +1 -1
  101. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts +25 -0
  102. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts.map +1 -1
  103. package/lib/langium/workspace/hydranium-langium-document-factory.js +25 -0
  104. package/lib/langium/workspace/hydranium-langium-document-factory.js.map +1 -1
  105. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +21 -1
  106. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  107. package/lib/langium/workspace/hydranium-workspace-manager.js +28 -0
  108. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  109. package/lib/langium/workspace/in-memory-file-system-provider.d.ts +8 -0
  110. package/lib/langium/workspace/in-memory-file-system-provider.d.ts.map +1 -1
  111. package/lib/langium/workspace/in-memory-file-system-provider.js +11 -2
  112. package/lib/langium/workspace/in-memory-file-system-provider.js.map +1 -1
  113. package/lib/langium/workspace/initialize-workspace.d.ts +22 -2
  114. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  115. package/lib/langium/workspace/initialize-workspace.js +13 -5
  116. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  117. package/lib/langium/workspace/langium-documents.d.ts +79 -17
  118. package/lib/langium/workspace/langium-documents.d.ts.map +1 -1
  119. package/lib/langium/workspace/langium-documents.js +83 -28
  120. package/lib/langium/workspace/langium-documents.js.map +1 -1
  121. package/lib/locale/index.d.ts +10 -0
  122. package/lib/locale/index.d.ts.map +1 -0
  123. package/lib/locale/index.js +10 -0
  124. package/lib/locale/index.js.map +1 -0
  125. package/lib/locale/server-locale.d.ts +73 -0
  126. package/lib/locale/server-locale.d.ts.map +1 -0
  127. package/lib/locale/server-locale.js +61 -0
  128. package/lib/locale/server-locale.js.map +1 -0
  129. package/lib/lsp/hydranium-document-update-handler.js +1 -1
  130. package/lib/lsp/hydranium-document-update-handler.js.map +1 -1
  131. package/lib/messages/carriers.d.ts +54 -0
  132. package/lib/messages/carriers.d.ts.map +1 -0
  133. package/lib/messages/carriers.js +62 -0
  134. package/lib/messages/carriers.js.map +1 -0
  135. package/lib/messages/index.d.ts +25 -0
  136. package/lib/messages/index.d.ts.map +1 -0
  137. package/lib/messages/index.js +25 -0
  138. package/lib/messages/index.js.map +1 -0
  139. package/lib/messages/renderer.d.ts +136 -0
  140. package/lib/messages/renderer.d.ts.map +1 -0
  141. package/lib/messages/renderer.js +159 -0
  142. package/lib/messages/renderer.js.map +1 -0
  143. package/lib/node/node-file-system-provider.d.ts.map +1 -1
  144. package/lib/node/node-file-system-provider.js +1 -40
  145. package/lib/node/node-file-system-provider.js.map +1 -1
  146. package/lib/node/rename-over-open-readers.d.ts +52 -0
  147. package/lib/node/rename-over-open-readers.d.ts.map +1 -0
  148. package/lib/node/rename-over-open-readers.js +66 -0
  149. package/lib/node/rename-over-open-readers.js.map +1 -0
  150. package/lib/testing/fake-document.d.ts +14 -3
  151. package/lib/testing/fake-document.d.ts.map +1 -1
  152. package/lib/testing/fake-document.js +18 -3
  153. package/lib/testing/fake-document.js.map +1 -1
  154. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  155. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  156. package/lib/testing/make-noop-shared-services.js +28 -2
  157. package/lib/testing/make-noop-shared-services.js.map +1 -1
  158. package/lib/testing/make-test-services.d.ts +31 -4
  159. package/lib/testing/make-test-services.d.ts.map +1 -1
  160. package/lib/testing/make-test-services.js +19 -3
  161. package/lib/testing/make-test-services.js.map +1 -1
  162. package/lib/testing/playwright/server-log-capture.d.ts +14 -4
  163. package/lib/testing/playwright/server-log-capture.d.ts.map +1 -1
  164. package/lib/testing/playwright/server-log-capture.js +21 -4
  165. package/lib/testing/playwright/server-log-capture.js.map +1 -1
  166. package/lib/testing/playwright/server-log-rename-reporter.d.ts.map +1 -1
  167. package/lib/testing/playwright/server-log-rename-reporter.js +10 -1
  168. package/lib/testing/playwright/server-log-rename-reporter.js.map +1 -1
  169. package/lib/testing/stub-ast-document-manager.d.ts +3 -4
  170. package/lib/testing/stub-ast-document-manager.d.ts.map +1 -1
  171. package/lib/testing/stub-ast-document-manager.js +2 -5
  172. package/lib/testing/stub-ast-document-manager.js.map +1 -1
  173. package/lib/testing/stub-document-builder.d.ts +8 -0
  174. package/lib/testing/stub-document-builder.d.ts.map +1 -1
  175. package/lib/testing/stub-document-builder.js +22 -3
  176. package/lib/testing/stub-document-builder.js.map +1 -1
  177. package/lib/testing/stub-model-service.d.ts +1 -1
  178. package/lib/testing/stub-model-service.d.ts.map +1 -1
  179. package/lib/testing/stub-model-service.js +2 -2
  180. package/lib/testing/stub-model-service.js.map +1 -1
  181. package/package.json +17 -8
  182. package/src/documents/ast-document-manager.ts +55 -14
  183. package/src/documents/hydranium-text-documents.ts +41 -9
  184. package/src/documents/language-client-text-shadow.ts +38 -2
  185. package/src/documents/self-save-registry.ts +52 -13
  186. package/src/index.ts +5 -0
  187. package/src/langium/ast-extension/ast-node-builder.ts +66 -22
  188. package/src/langium/bootstrap.ts +16 -9
  189. package/src/langium/document-builder/build-pipeline-integration.ts +14 -1
  190. package/src/langium/document-builder/build-session.ts +87 -0
  191. package/src/langium/document-builder/document-builder.ts +339 -11
  192. package/src/langium/document-builder/index.ts +1 -0
  193. package/src/langium/integration-services.ts +67 -6
  194. package/src/langium/integrity/integrity-service.ts +35 -1
  195. package/src/langium/keys/containment.ts +87 -0
  196. package/src/langium/keys/index.ts +1 -0
  197. package/src/langium/keys/name-based-key-provider.ts +4 -0
  198. package/src/langium/model-service/model-service.ts +145 -22
  199. package/src/langium/module.ts +99 -19
  200. package/src/langium/naming/name-provider.ts +10 -0
  201. package/src/langium/naming/name-separator-validation.ts +34 -5
  202. package/src/langium/residency/cst-residency-service.ts +36 -12
  203. package/src/langium/scope/hydranium-scope-provider.ts +40 -22
  204. package/src/langium/shared-services.ts +19 -2
  205. package/src/langium/transfer/transfer-encoder.ts +45 -3
  206. package/src/langium/validation/document-validator.ts +255 -8
  207. package/src/langium/workspace/document-uri-policy.ts +3 -4
  208. package/src/langium/workspace/hydranium-langium-document-factory.ts +34 -0
  209. package/src/langium/workspace/hydranium-workspace-manager.ts +30 -1
  210. package/src/langium/workspace/in-memory-file-system-provider.ts +13 -3
  211. package/src/langium/workspace/initialize-workspace.ts +34 -5
  212. package/src/langium/workspace/langium-documents.ts +106 -33
  213. package/src/locale/index.ts +10 -0
  214. package/src/locale/server-locale.ts +86 -0
  215. package/src/lsp/hydranium-document-update-handler.ts +1 -1
  216. package/src/messages/carriers.ts +78 -0
  217. package/src/messages/index.ts +27 -0
  218. package/src/messages/renderer.ts +204 -0
  219. package/src/node/node-file-system-provider.ts +1 -41
  220. package/src/node/rename-over-open-readers.ts +78 -0
  221. package/src/testing/fake-document.ts +22 -4
  222. package/src/testing/make-noop-shared-services.ts +50 -2
  223. package/src/testing/make-test-services.ts +49 -7
  224. package/src/testing/playwright/server-log-capture.ts +24 -5
  225. package/src/testing/playwright/server-log-rename-reporter.ts +12 -1
  226. package/src/testing/stub-ast-document-manager.ts +5 -10
  227. package/src/testing/stub-document-builder.ts +32 -3
  228. package/src/testing/stub-model-service.ts +2 -2
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { type Clock, type LogThreshold, type MaybeObservableValue, ObservableValue, type Tracer } from '@hydranium/protocol';
11
11
  import {
12
+ type AstNode,
12
13
  type BuildOptions,
13
14
  DefaultDocumentBuilder,
14
15
  type DocumentPhaseListener,
@@ -20,12 +21,17 @@ import {
20
21
  interruptAndCheck,
21
22
  isOperationCancelled
22
23
  } from '@hydranium/langium';
23
- import { CancellationToken, type Diagnostic } from 'vscode-languageserver-protocol';
24
+ // `Diagnostic` as a VALUE: `renderDiagnostics` needs its `getMessageString`
25
+ // namespace helper to read the `string | MarkupContent` union without
26
+ // restating it.
27
+ import { CancellationToken, Diagnostic } from 'vscode-languageserver-protocol';
24
28
  import { type LogNameOptions } from '../diagnostics/logger.js';
29
+ import type { MessageRenderer } from '../../messages/renderer.js';
25
30
  import { CST_REHYDRATION_RESET_STATE, isCstShed } from '../residency/cst-residency-service.js';
26
31
  import { type ExtendedServiceRegistry } from '../service-registry.js';
27
32
  import { type ServerSharedServicesMinimal } from '../shared-services.js';
28
33
  import { type DocumentUriPolicy } from '../workspace/document-uri-policy.js';
34
+ import { BuildSession, type BuildSessionContext } from './build-session.js';
29
35
  import { type LabeledPhaseListener, labelPhaseListener } from './labeled-phase-listener.js';
30
36
 
31
37
  /** Document states a phase-reached line is emitted for by default — every built phase. */
@@ -78,6 +84,18 @@ export interface DocumentBuilderOptions extends LogNameOptions {
78
84
  * logged. Default: `25`. Read per phase; accepts a {@link MaybeObservableValue}.
79
85
  */
80
86
  readonly slowBuildMs?: MaybeObservableValue<number>;
87
+ /**
88
+ * Build duration at or above which a build's phase-reached and slow-listener
89
+ * lines are emitted; they are held for the duration of the build and dropped
90
+ * when it finishes faster. Default `0` — no buffering, every line emitted as
91
+ * it is produced, which is the only setting that keeps lines interleaved with
92
+ * the rest of the log in real time.
93
+ *
94
+ * Set it to make a fast rebuild log nothing but its one build line. The
95
+ * decision needs the build's TOTAL duration, so it cannot be made by any
96
+ * per-line hook. Read once per build; accepts a {@link MaybeObservableValue}.
97
+ */
98
+ readonly phaseDetailMs?: MaybeObservableValue<number>;
81
99
  /**
82
100
  * Refresh cross-document `ComputedScopes` derivations when a referencing
83
101
  * document is cascade-rebuilt (see
@@ -105,15 +123,24 @@ export interface DocumentBuilderOptions extends LogNameOptions {
105
123
  * - **In-place rebuild helpers** — {@link reparse} and
106
124
  * {@link reparseAndRelink} — for a build-phase listener that mutated a
107
125
  * document's AST and must reconcile it within the same build.
108
- * - **Diagnostic dedupe** at `Validated` ({@link dedupeDiagnostics}).
126
+ * - **Diagnostic dedupe** at `Validated` ({@link dedupeDiagnostics}), followed
127
+ * by the **one server-side message render** every head inherits
128
+ * ({@link renderDiagnostics}).
129
+ * - **Build sessions** ({@link BuildSession}): each `update` / `build` call is
130
+ * one correlated unit carrying an id, a trigger label, a start time and
131
+ * cancellation lineage, so every line of a rebuild reads as belonging to it
132
+ * and a preempted build is distinguishable from the winner.
109
133
  * - **Logging instrumentation** (default on, opt-out via `logLevel: 'off'`):
110
- * phase-reached lines, slow-listener breakdowns on `notifyDocumentPhase`,
111
- * and slow-build-phase totals on `notifyBuildPhase`.
134
+ * a per-build line, phase-reached lines, slow-listener breakdowns on
135
+ * `notifyDocumentPhase`, and slow-build-phase totals on `notifyBuildPhase`.
112
136
  *
113
137
  * Adopters extend this class — the configuration knobs cover what most
114
138
  * adopters need; the `format*Line` methods, `formatUri`, and
115
139
  * `collectDeletedURIs` are protected so subclasses can customise wording or
116
- * domain-aware cascades without re-implementing surrounding logic.
140
+ * domain-aware cascades without re-implementing surrounding logic. An adopter
141
+ * with build-scoped state of its own subclasses {@link BuildSession} and
142
+ * overrides {@link createBuildSession}, which puts that state under the same
143
+ * preemption-correct teardown rather than a reimplementation of it.
117
144
  */
118
145
  export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
119
146
  protected readonly tracer: Tracer;
@@ -127,8 +154,11 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
127
154
  protected readonly slowListenerMs: ObservableValue<number>;
128
155
  /** Live slow-build-phase-total threshold; read `.value` per phase. */
129
156
  protected readonly slowBuildMs: ObservableValue<number>;
157
+ /** Live phase-detail buffering threshold; read `.value` once per build, onto the session. */
158
+ protected readonly phaseDetailMs: ObservableValue<number>;
130
159
  protected readonly uriPolicy: DocumentUriPolicy;
131
160
  protected readonly clock: Clock;
161
+ protected readonly messageRenderer: MessageRenderer;
132
162
  /** Narrower handle on the same registry as the inherited `serviceRegistry`, for {@link ExtendedServiceRegistry.registrations}. */
133
163
  protected readonly languageRegistry: ExtendedServiceRegistry;
134
164
  protected languageFileExtensions: string[] = [];
@@ -139,18 +169,36 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
139
169
  protected readonly refreshCrossDocumentComputedScopes: boolean;
140
170
  /** LSP event name (e.g. `'didChangeWatchedFiles'`) staged for the next `update()` call. */
141
171
  protected pendingUpdateReason?: string;
172
+ /**
173
+ * The build currently in progress, or `undefined` between builds.
174
+ *
175
+ * A subclass carrying its own build-scoped state returns a {@link BuildSession}
176
+ * subclass from {@link createBuildSession} and narrows this with a typeguard
177
+ * where it reads that state — rather than redeclaring the field, whose
178
+ * initialiser would run after `super()` and clear a session opened during
179
+ * construction.
180
+ */
181
+ protected activeSession?: BuildSession;
182
+ /**
183
+ * `traceId` of the last build that ended in cancellation, for the successor's
184
+ * "cancels #N" tag. Held here rather than on a session because the session
185
+ * that carries it is already gone by the time its successor is opened.
186
+ */
187
+ protected lastCancelledTraceId?: number;
142
188
 
143
189
  constructor(services: ServerSharedServicesMinimal, options: DocumentBuilderOptions = {}) {
144
190
  super(services);
145
191
  this.languageRegistry = services.ServiceRegistry;
146
192
  this.uriPolicy = services.workspace.DocumentUriPolicy;
147
193
  this.clock = services.Clock;
194
+ this.messageRenderer = services.MessageRenderer;
148
195
  this.tracer = services.Tracer.for(options.logName ?? 'DocumentBuilder').trace('instantiated');
149
196
  this.logLevel = options.logLevel ?? 'debug';
150
197
  this.loggedPhases = options.loggedPhases ?? DEFAULT_LOGGED_PHASES;
151
198
  this.slowPhaseMs = ObservableValue.from(options.slowPhaseMs ?? 25);
152
199
  this.slowListenerMs = ObservableValue.from(options.slowListenerMs ?? 5);
153
200
  this.slowBuildMs = ObservableValue.from(options.slowBuildMs ?? 25);
201
+ this.phaseDetailMs = ObservableValue.from(options.phaseDetailMs ?? 0);
154
202
  this.refreshCrossDocumentComputedScopes = options.refreshCrossDocumentComputedScopes ?? false;
155
203
  if (this.logLevel !== 'off') {
156
204
  this.registerPhaseListeners();
@@ -193,7 +241,16 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
193
241
  const doc = this.langiumDocuments.getDocument(UriUtils.toUri(this.uriPolicy.canonicalUri(uri)));
194
242
  const docState = doc ? DocumentState[doc.state] : 'unknown (document not loaded)';
195
243
  const lastPhase = this.lastPhaseMs > 0 ? `${Math.round(performance.now() - this.lastPhaseMs)}ms ago` : 'no phase observed';
196
- return `current state: '${docState}', last phase: ${lastPhase}`;
244
+ return `current state: '${docState}', last phase: ${lastPhase}, active build: ${this.formatSession(this.activeSession)}`;
245
+ }
246
+
247
+ /** Render a session for a status line. `undefined` — no build in progress — reads as `none`. */
248
+ protected formatSession(session: BuildSession | undefined): string {
249
+ if (!session) {
250
+ return 'none';
251
+ }
252
+ const id = session.traceId !== undefined ? `#${session.traceId}` : 'untimed';
253
+ return `${id} (${session.trigger}, ${Math.round(performance.now() - session.startMs)}ms in)`;
197
254
  }
198
255
 
199
256
  // ============================================================
@@ -409,7 +466,35 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
409
466
  this.ensureLanguageFileExtensions();
410
467
  const changedURIs = changed.flatMap(uri => this.flattenAndAdaptURI(uri));
411
468
  const deletedURIs = deleted.flatMap(uri => this.collectDeletedURIs(uri));
412
- return super.update(changedURIs, deletedURIs, cancelToken);
469
+ return this.runInSession(
470
+ {
471
+ kind: 'update',
472
+ trigger: this.buildTriggerLabel(changedURIs, deletedURIs),
473
+ triggerCountsDocs: changedURIs.length + deletedURIs.length !== 1,
474
+ changed: changedURIs,
475
+ deleted: deletedURIs
476
+ },
477
+ this.rebuildLabel(changedURIs, deletedURIs),
478
+ () => super.update(changedURIs, deletedURIs, cancelToken)
479
+ );
480
+ }
481
+
482
+ /**
483
+ * The workspace-initialization entry point, bracketed by a session like
484
+ * {@link update}. Langium's `update` reaches `buildDocuments` directly rather
485
+ * than through here, so the two never nest.
486
+ */
487
+ override build<T extends AstNode>(
488
+ documents: Array<LangiumDocument<T>>,
489
+ options?: BuildOptions,
490
+ cancelToken?: CancellationToken
491
+ ): Promise<void> {
492
+ const uris = documents.map(document => document.uri);
493
+ return this.runInSession(
494
+ { kind: 'build', trigger: `${documents.length} docs`, triggerCountsDocs: true, changed: uris, deleted: [] },
495
+ `Build documents (${documents.length} docs)`,
496
+ () => super.build(documents, options, cancelToken)
497
+ );
413
498
  }
414
499
 
415
500
  /**
@@ -615,6 +700,149 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
615
700
  ];
616
701
  }
617
702
 
703
+ // ============================================================
704
+ // Build sessions — one rebuild as a correlated unit
705
+ // ============================================================
706
+
707
+ /**
708
+ * Open a session, run `body` inside it, and close it — the bracket every
709
+ * line of a rebuild is emitted within.
710
+ *
711
+ * The session is installed **synchronously**, before the timed body runs, so
712
+ * that state a subclass computed in {@link createBuildSession} is already
713
+ * readable by the time Langium's `update` consults `shouldRelink`.
714
+ *
715
+ * Teardown is preemption-correct, which is the reason this is framework code
716
+ * rather than a recipe. Langium's write mutex cancels an in-flight build when
717
+ * a later one arrives, so two sessions overlap: the successor installs itself
718
+ * as {@link activeSession} while the predecessor is still unwinding, and the
719
+ * predecessor's `finally` runs LAST. Clearing unconditionally there would
720
+ * discard the winner's state mid-build. Only the session that is still
721
+ * current clears — and the check is reference equality on the session object,
722
+ * not on {@link BuildSession.traceId}, which is `undefined` for every build
723
+ * whenever the timing level is suppressed and would compare equal to itself
724
+ * across two different builds.
725
+ *
726
+ * Re-entrancy is not hypothetical even without an adopter: {@link
727
+ * requeueOrphaned} calls `update` from inside a wait, while a build may be
728
+ * running.
729
+ */
730
+ protected runInSession(context: BuildSessionContext, label: string, body: () => Promise<void>): Promise<void> {
731
+ // Read before installing the new session: the id being superseded belongs
732
+ // to the OUTGOING build, or — when the previous one already finished
733
+ // cancelled — to the id it parked for its successor.
734
+ const supersededId = this.activeSession?.traceId ?? this.lastCancelledTraceId;
735
+ this.lastCancelledTraceId = undefined;
736
+ const reason = this.pendingUpdateReason;
737
+ this.pendingUpdateReason = undefined;
738
+ const tags: string[] = [];
739
+ if (reason) {
740
+ tags.push(`event: ${reason}`);
741
+ }
742
+ if (supersededId !== undefined) {
743
+ tags.push(`cancels #${supersededId}`);
744
+ }
745
+
746
+ const session = this.createBuildSession(context);
747
+ this.activeSession = session;
748
+ // A phase's "since previous phase" must measure from the build's start,
749
+ // not from whenever the last build's final phase happened to land.
750
+ this.lastPhaseMs = session.startMs;
751
+ return this.tracer.time(
752
+ label,
753
+ async () => {
754
+ try {
755
+ await body();
756
+ } catch (err: unknown) {
757
+ if (isOperationCancelled(err)) {
758
+ session.cancelled = true;
759
+ }
760
+ throw err;
761
+ } finally {
762
+ this.endSession(session);
763
+ }
764
+ },
765
+ this.logLevel,
766
+ {
767
+ logAfterMs: 0,
768
+ forceMemoryAboveMs: session.buffers ? session.detailThresholdMs : undefined,
769
+ captureId: id => {
770
+ session.traceId = id;
771
+ },
772
+ tags
773
+ }
774
+ );
775
+ }
776
+
777
+ /**
778
+ * Construct the session for one build. Override to return a
779
+ * {@link BuildSession} subclass carrying adopter build-scoped state — it is
780
+ * called before the build body, so anything derived here is readable
781
+ * throughout it.
782
+ */
783
+ protected createBuildSession(context: BuildSessionContext): BuildSession {
784
+ return new BuildSession(performance.now(), context.trigger, context.triggerCountsDocs, this.phaseDetailMs.value);
785
+ }
786
+
787
+ /**
788
+ * Close `session`: flush what it buffered, then release it if it is still the
789
+ * current one (see {@link runInSession} on why that check is conditional).
790
+ * The flush is unconditional — a preempted build's lines still describe work
791
+ * that happened.
792
+ */
793
+ protected endSession(session: BuildSession): void {
794
+ this.flushSession(session);
795
+ if (this.activeSession === session) {
796
+ this.activeSession = undefined;
797
+ if (session.cancelled) {
798
+ this.lastCancelledTraceId = session.traceId;
799
+ }
800
+ }
801
+ }
802
+
803
+ /**
804
+ * Emit the lines `session` held back, if it ran long enough to be worth the
805
+ * detail; drop them otherwise. Emits through {@link emit} rather than
806
+ * {@link log}, which would route them straight back into the buffer.
807
+ */
808
+ protected flushSession(session: BuildSession): void {
809
+ const elapsedMs = performance.now() - session.startMs;
810
+ if (elapsedMs >= session.detailThresholdMs) {
811
+ for (const line of session.bufferedLines) {
812
+ this.emit(line);
813
+ }
814
+ }
815
+ session.bufferedLines.length = 0;
816
+ }
817
+
818
+ /** Label for the build's own log line. Override to customise wording. */
819
+ protected rebuildLabel(changed: URI[], deleted: URI[]): string {
820
+ if (changed.length === 0 && deleted.length === 0) {
821
+ return 'Rebuild documents (nothing to do)';
822
+ }
823
+ if (changed.length === 1 && deleted.length === 0) {
824
+ return `Rebuild document: ${this.formatUri(changed[0])}`;
825
+ }
826
+ if (changed.length === 0 && deleted.length === 1) {
827
+ return `Rebuild after delete: ${this.formatUri(deleted[0])}`;
828
+ }
829
+ return `Rebuild documents (${changed.length} changed, ${deleted.length} deleted)`;
830
+ }
831
+
832
+ /** Short description of what triggered the build, repeated on every phase line. Override to customise wording. */
833
+ protected buildTriggerLabel(changed: URI[], deleted: URI[]): string {
834
+ if (changed.length === 0 && deleted.length === 0) {
835
+ return 'nothing';
836
+ }
837
+ if (changed.length === 1 && deleted.length === 0) {
838
+ return this.formatUri(changed[0]);
839
+ }
840
+ if (changed.length === 0 && deleted.length === 1) {
841
+ return `deleted ${this.formatUri(deleted[0])}`;
842
+ }
843
+ return `${changed.length} changed, ${deleted.length} deleted`;
844
+ }
845
+
618
846
  // ============================================================
619
847
  // Logging — phase-reached listeners
620
848
  // ============================================================
@@ -630,13 +858,35 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
630
858
  const now = performance.now();
631
859
  const elapsedMs = Math.round(now - this.lastPhaseMs);
632
860
  this.lastPhaseMs = now;
861
+ // Counted before the line is formatted, so the formatter stays a pure
862
+ // function of state a caller can also set up in a test.
863
+ if (this.activeSession) {
864
+ this.activeSession.phasesLogged++;
865
+ }
633
866
  this.log(this.phaseReachedLine(state, documents, elapsedMs));
634
867
  }
635
868
 
636
- /** Format the phase-reached log line. Override to customise wording. */
869
+ /**
870
+ * Format the phase-reached log line. Override to customise wording.
871
+ *
872
+ * Within a session the line names what triggered the build, so a phase read
873
+ * in isolation still says which rebuild it belongs to. `elapsedMs` is ignored
874
+ * for the FIRST phase of a session: it measures from the previous build's
875
+ * last phase, an idle gap that says nothing about this build.
876
+ */
637
877
  protected phaseReachedLine(state: DocumentState, documents: LangiumDocument[], elapsedMs: number): string {
638
- const docInfo = documents.length === 1 ? this.formatUri(documents[0].uri) : `${documents.length} docs`;
639
- return `Reached phase '${DocumentState[state]}' [${docInfo}, ${elapsedMs}ms since previous phase]`;
878
+ const session = this.activeSession;
879
+ let docInfo: string;
880
+ if (session) {
881
+ docInfo = session.triggerCountsDocs ? `building ${session.trigger}` : `building ${session.trigger}, ${documents.length} docs`;
882
+ } else {
883
+ docInfo = documents.length === 1 ? this.formatUri(documents[0].uri) : `${documents.length} docs`;
884
+ }
885
+ const elapsedInfo =
886
+ session && session.phasesLogged <= 1
887
+ ? `${Math.round(performance.now() - session.startMs)}ms since build start`
888
+ : `${elapsedMs}ms since previous phase`;
889
+ return `Reached phase '${DocumentState[state]}' [${docInfo}, ${elapsedInfo}]`;
640
890
  }
641
891
 
642
892
  // ============================================================
@@ -651,8 +901,12 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
651
901
  // build settling inside that window therefore appends after this call has
652
902
  // already deduped, and the appended duplicate is published by the listener
653
903
  // of the build that deduped. Only `serializeBuilds` closes the window.
904
+ //
905
+ // Dedupe before rendering: rendering is deterministic, so it cannot
906
+ // change which entries are structurally equal, and fewer survive to render.
654
907
  if (state === DocumentState.Validated) {
655
908
  this.dedupeDiagnostics(document);
909
+ this.renderDiagnostics(document);
656
910
  }
657
911
  if (this.logLevel === 'off') {
658
912
  return super.notifyDocumentPhase(document, state, cancelToken);
@@ -828,12 +1082,86 @@ export class HydraniumDocumentBuilder extends DefaultDocumentBuilder {
828
1082
  }
829
1083
  }
830
1084
 
1085
+ /**
1086
+ * Render every diagnostic on `document` through the bound message renderer,
1087
+ * in ONE pass over the finished list.
1088
+ *
1089
+ * All three heads read `document.diagnostics` — the LSP publish,
1090
+ * `TransferEncoder.toTransferDiagnostic` and the GLSP validation path — so
1091
+ * one pass here is what keeps the render from happening per head. It is also
1092
+ * the only placement that covers lexer and parser errors, which Langium
1093
+ * pushes onto the document without routing them through `toDiagnostic`.
1094
+ *
1095
+ * Running here rather than from a `Validated` phase listener needs no
1096
+ * ordering assumption: Langium publishes from `addDiagnosticsHandler`, a free
1097
+ * function it registers as such a listener, which can only be outrun.
1098
+ *
1099
+ * **It inherits {@link dedupeDiagnostics}'s window, and therefore the same
1100
+ * precondition.** A build settling inside the listener window appends
1101
+ * diagnostics this pass never saw, and the publisher of the build that
1102
+ * rendered sends them — unrendered. `ModelServiceOptions.serializeBuilds`
1103
+ * closes it and defaults to `true`, so "every diagnostic is rendered" holds
1104
+ * by default and is an opt-out rather than a guarantee. Opting out accepts
1105
+ * unrendered diagnostics on exactly the terms it already accepts duplicates.
1106
+ *
1107
+ * Entries are REPLACED rather than mutated: `sendDiagnostics` passes the
1108
+ * array by reference and serialises later, so an in-place message mutation
1109
+ * reaches the wire even when it runs after the publisher — which would make
1110
+ * a test for the ordering pass in either state.
1111
+ */
1112
+ protected renderDiagnostics(document: LangiumDocument): void {
1113
+ const diagnostics = document.diagnostics;
1114
+ if (!diagnostics || diagnostics.length === 0) {
1115
+ return;
1116
+ }
1117
+ let changed = false;
1118
+ // No try/catch: `renderDiagnostic` carries a no-throw contract, because an
1119
+ // error escaping this phase strands the document at `Validated` with
1120
+ // Langium's publisher never invoked.
1121
+ const rendered = diagnostics.map(diagnostic => {
1122
+ const text = this.messageRenderer.renderDiagnostic(diagnostic);
1123
+ // Against the message's STRING FORM, not the field. `renderDiagnostic`
1124
+ // answers a `string` by contract, while `Diagnostic.message` is
1125
+ // `string | MarkupContent` since LSP 3.17 — so comparing the answer
1126
+ // against the field never matches for a markup message, and a pass
1127
+ // that replaced on mismatch flattened every un-identified markup
1128
+ // diagnostic to its own plain text. That is silent data loss on the
1129
+ // path whose whole job is to leave such entries alone.
1130
+ if (text === Diagnostic.getMessageString(diagnostic)) {
1131
+ return diagnostic;
1132
+ }
1133
+ changed = true;
1134
+ return { ...diagnostic, message: text };
1135
+ });
1136
+ if (changed) {
1137
+ document.diagnostics = rendered;
1138
+ }
1139
+ }
1140
+
831
1141
  // ============================================================
832
1142
  // Internal helpers
833
1143
  // ============================================================
834
1144
 
835
- /** Dispatch a log line at the configured log level; a no-op when `logLevel === 'off'`. */
1145
+ /**
1146
+ * Dispatch a log line at the configured log level; a no-op when `logLevel ===
1147
+ * 'off'`.
1148
+ *
1149
+ * Held on the active session when it buffers, so the "was this build worth a
1150
+ * per-phase breakdown" decision — which needs the build's total duration, and
1151
+ * so cannot be taken by anything that runs while the lines are produced — is
1152
+ * deferred to {@link flushSession}.
1153
+ */
836
1154
  protected log(message: string): void {
1155
+ const session = this.activeSession;
1156
+ if (session?.buffers) {
1157
+ session.bufferedLines.push(message);
1158
+ return;
1159
+ }
1160
+ this.emit(message);
1161
+ }
1162
+
1163
+ /** Write a line out, bypassing session buffering. The single sink every framework log line reaches. */
1164
+ protected emit(message: string): void {
837
1165
  this.tracer.logAt(this.logLevel, message);
838
1166
  }
839
1167
  }
@@ -8,5 +8,6 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  export * from './build-pipeline-integration.js';
11
+ export * from './build-session.js';
11
12
  export * from './document-builder.js';
12
13
  export * from './labeled-phase-listener.js';
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { inject, type Module } from '@hydranium/langium';
10
+ import { type DeepPartial, inject, type Module } from '@hydranium/langium';
11
11
  import {
12
12
  createDefaultModule,
13
13
  createDefaultSharedModule,
@@ -98,6 +98,31 @@ export interface IntegrationServicesOptions<
98
98
  * it is silently inert.
99
99
  */
100
100
  extra?: ReadonlyArray<Module<TShared, PartialLangiumSharedServices>>;
101
+ /**
102
+ * Shared modules composed LAST — after `adopter` — and partial over
103
+ * `TShared` rather than over Langium's shared services.
104
+ *
105
+ * Both differences are the point, and neither is served by
106
+ * {@link extra}. Most framework shared services are constructed with
107
+ * no options (`ModelService: services => new DefaultModelService(services)`),
108
+ * so rebinding the slot is the only way to boot one configured
109
+ * differently; a caller that needs that is usually a test, and the slot
110
+ * it needs is as often a framework ADDITION (`Clock`, `Tracer`,
111
+ * `ProjectManager`) as a Langium one. `extra` can express neither: it
112
+ * is typed `DeepPartial<LangiumSharedServices>`, and it loses to
113
+ * `adopter` on every slot the adopter binds.
114
+ *
115
+ * Kept separate rather than widening `extra` because `extra` is the
116
+ * protocol-head tier, and a head must NOT outrank the adopter. Widening
117
+ * it also does not typecheck — `Module<I, T>` puts `T` in factory
118
+ * return position, so a head module declaring Langium slot types stops
119
+ * being assignable once `T` becomes `DeepPartial<TShared>`.
120
+ *
121
+ * Composing last means an override wins over everything, including the
122
+ * adopter. That is what makes it usable for the slots an adopter binds
123
+ * itself, and why production code should not reach for it.
124
+ */
125
+ overrides?: ReadonlyArray<Module<TShared, DeepPartial<TShared>>>;
101
126
  };
102
127
 
103
128
  /**
@@ -134,6 +159,23 @@ export interface IntegrationServicesOptions<
134
159
  * still win over heads.
135
160
  */
136
161
  extra?: ReadonlyArray<Module<TLanguage, PartialLangiumServices>>;
162
+ /**
163
+ * Modules composed LAST, after `adopter`, and partial over `TLanguage`
164
+ * rather than over Langium's per-language services. The language-tier
165
+ * twin of {@link IntegrationServicesOptions.sharedModules}'s
166
+ * `overrides`, and both differences carry the same weight they do
167
+ * there.
168
+ *
169
+ * A per-language framework service is constructed by the framework's
170
+ * own module with no options
171
+ * (`IntegrityService: services => new DefaultIntegrityService(services)`),
172
+ * so booting one configured differently means rebinding the slot.
173
+ * {@link extra} serves neither half of that: it composes BEFORE
174
+ * `adopter` and so loses every slot the adopter binds, and it is typed
175
+ * `PartialLangiumServices`, which cannot express a framework ADDITION
176
+ * like `IntegrityService` or `AstExtensionService` at all.
177
+ */
178
+ overrides?: ReadonlyArray<Module<TLanguage, DeepPartial<TLanguage>>>;
137
179
  };
138
180
 
139
181
  /**
@@ -197,6 +239,8 @@ export interface AdditionalLanguageModules<
197
239
  adopter?: (shared: TShared) => Module<TLanguage, PartialLangiumServices>;
198
240
  /** Protocol-head modules for this language. Defaults to the primary language's. */
199
241
  extra?: ReadonlyArray<Module<TLanguage, PartialLangiumServices>>;
242
+ /** Last-composed overrides for this language. Defaults to the primary language's. */
243
+ overrides?: ReadonlyArray<Module<TLanguage, DeepPartial<TLanguage>>>;
200
244
  }
201
245
 
202
246
  /**
@@ -247,7 +291,9 @@ export function createIntegrationServices<
247
291
  sharedModules.generated,
248
292
  sharedModule,
249
293
  ...(sharedModules.extra ?? []),
250
- sharedModules.adopter
294
+ sharedModules.adopter,
295
+ // Last, so an override outranks the adopter too — see `overrides`.
296
+ ...((sharedModules.overrides ?? []) as ReadonlyArray<Module<TShared, PartialLangiumSharedServices>>)
251
297
  ) as unknown as TShared;
252
298
 
253
299
  // Each language gets its OWN `createDefaultModule({ shared })` — the
@@ -256,19 +302,34 @@ export function createIntegrationServices<
256
302
  const composeLanguage = (
257
303
  generated: Module<TLanguage, PartialLangiumServices>,
258
304
  adopter: (shared: TShared) => Module<TLanguage, PartialLangiumServices>,
259
- extra: ReadonlyArray<Module<TLanguage, PartialLangiumServices>>
305
+ extra: ReadonlyArray<Module<TLanguage, PartialLangiumServices>>,
306
+ overrides: ReadonlyArray<Module<TLanguage, DeepPartial<TLanguage>>>
260
307
  ): TLanguage => {
261
308
  const defaultLanguageModule = createDefaultModule({ shared }) as unknown as Module<TLanguage, PartialLangiumServices>;
262
309
  const serverLanguageModule = createServerLanguageModule(context) as unknown as Module<TLanguage, PartialLangiumServices>;
263
- return inject(defaultLanguageModule, generated, serverLanguageModule, ...extra, adopter(shared)) as unknown as TLanguage;
310
+ return inject(
311
+ defaultLanguageModule,
312
+ generated,
313
+ serverLanguageModule,
314
+ ...extra,
315
+ adopter(shared),
316
+ // Last, so an override outranks the adopter too — see `overrides`.
317
+ ...(overrides as ReadonlyArray<Module<TLanguage, PartialLangiumServices>>)
318
+ ) as unknown as TLanguage;
264
319
  };
265
320
 
266
321
  const primaryExtra = (languageModules.extra ?? []) as ReadonlyArray<Module<TLanguage, PartialLangiumServices>>;
267
- const language = composeLanguage(languageModules.generated, languageModules.adopter, primaryExtra);
322
+ const primaryOverrides = languageModules.overrides ?? [];
323
+ const language = composeLanguage(languageModules.generated, languageModules.adopter, primaryExtra, primaryOverrides);
268
324
  const languages = [
269
325
  language,
270
326
  ...additionalLanguages.map(additional =>
271
- composeLanguage(additional.generated, additional.adopter ?? languageModules.adopter, additional.extra ?? primaryExtra)
327
+ composeLanguage(
328
+ additional.generated,
329
+ additional.adopter ?? languageModules.adopter,
330
+ additional.extra ?? primaryExtra,
331
+ additional.overrides ?? primaryOverrides
332
+ )
272
333
  )
273
334
  ];
274
335
 
@@ -75,6 +75,11 @@ export namespace IntegrityService {
75
75
  * at `DocumentState.Validated` and delivered separately via `publishDiagnostics`
76
76
  * or the `onModelUpdated` event.
77
77
  *
78
+ * The AST is what this guarantees, not the text. For a closed document whose
79
+ * repair was STAGED rather than written (`'editor'` sync mode),
80
+ * `textDocument` still mirrors disk — read the repair off the AST, or from
81
+ * the staged content the next open consumes.
82
+ *
78
83
  * Invariant: integrity rules only register at Parsed or Linked, so the build
79
84
  * is guaranteed post-integrity once it advances past `onBuildPhase(Linked)`
80
85
  * into `IndexedReferences`. {@link IntegrityService.register} enforces this at
@@ -317,10 +322,11 @@ export class DefaultIntegrityService<TRoot extends AstNode = AstNode> implements
317
322
  return;
318
323
  }
319
324
 
325
+ const version = document.textDocument.version;
320
326
  // Keep the same version so HydraniumTextDocuments doesn't reject subsequent client edits.
321
327
  // Use manager.update so the `instanceof FullTextDocument` gate in the bare
322
328
  // `TextDocument.update` doesn't trip on adopter-custom text-document types.
323
- const textDocument = this.textDocuments.update(document.textDocument, [{ text: newText }], document.textDocument.version);
329
+ const textDocument = this.textDocuments.update(document.textDocument, [{ text: newText }], version);
324
330
 
325
331
  await this.syncCorrections(textDocument);
326
332
 
@@ -328,6 +334,14 @@ export class DefaultIntegrityService<TRoot extends AstNode = AstNode> implements
328
334
  // Parsed-phase correction: re-parse only. The build pipeline still runs
329
335
  // IndexedContent → ComputedScopes → Linked → … on the fresh AST afterwards,
330
336
  // so the document reconciles naturally with no extra work here.
337
+ //
338
+ // Except for a closed document whose repair did not reach disk — `'editor'`
339
+ // sync mode stages it instead of writing it — where the re-parse is SKIPPED:
340
+ // Langium's factory gates the parse on the CST's `fullText`, which still
341
+ // equals the disk text the same call re-reads and redefines `textDocument`
342
+ // over. So `document.textDocument` is NOT post-integrity for such a
343
+ // document — it mirrors disk, and the AST is the only place the repair is
344
+ // legible, until an open consumes the staging.
331
345
  await this.documentBuilder.reparse(document, cancelToken);
332
346
  } else {
333
347
  // Linked-phase (or later) correction. The rule mutated the AST in place but
@@ -340,6 +354,26 @@ export class DefaultIntegrityService<TRoot extends AstNode = AstNode> implements
340
354
  // stays in the builder, its proper home, rather than being duplicated here.
341
355
  await this.documentBuilder.reparseAndRelink(document, cancelToken);
342
356
  }
357
+
358
+ // Re-version against the REPAIRED text, after either branch. The repair is
359
+ // a content change the store has not seen: whatever reconciliation ran
360
+ // during the re-parse saw the text on disk, which in `'editor'` sync mode
361
+ // is the PRE-repair text. Leave the sequence describing that and the next
362
+ // open hashes the repair, finds a mismatch and steps the version again, so
363
+ // every `baseVersion` taken from this build is stale before it is used.
364
+ // Falls back to the pre-re-parse number for a URI the store never tracked,
365
+ // where there is no sequence to advance; an OPEN document answers
366
+ // `undefined` and keeps the store's own version, which is not this
367
+ // method's to move.
368
+ //
369
+ // Deliberately NOT gated on cancellation, unlike the entry to this method:
370
+ // `syncCorrections` has already written or staged the repair by now, so a
371
+ // preempted build that skipped this would leave the sequence describing
372
+ // text that is no longer there.
373
+ const reconciled = this.textDocuments.reconcileExternalContent(document.textDocument.uri, newText) ?? version;
374
+ if (document.textDocument.version !== reconciled) {
375
+ this.textDocuments.update(document.textDocument, [], reconciled);
376
+ }
343
377
  }
344
378
 
345
379
  /**