@hydranium/conformance 1.0.0-next.27 → 1.0.0-next.271

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.
package/src/data/index.ts CHANGED
@@ -10,39 +10,71 @@
10
10
  /**
11
11
  * The `@hydranium/conformance/data` slice — protocol conformance for the
12
12
  * data-server head. The driver port IS the protocol-native
13
- * {@link DataServerProtocol} proxy (plus the captured `onDocumentUpdated`
14
- * events), so no upstream wire-lib dep enters the kit and `DataServerHarness`
15
- * satisfies the port structurally with no adapter.
13
+ * {@link DataServerProtocol} proxy (plus the captured client notifications),
14
+ * so no upstream wire-lib dep enters the kit and `DataServerHarness` satisfies
15
+ * the port structurally with no adapter.
16
16
  */
17
17
 
18
18
  import assert from 'node:assert/strict';
19
- import { TransferDocument, type TransferDiagnostic, type TransferElement } from '@hydranium/protocol';
20
- import type { DataServerProtocol, TransferDocumentUpdatedEvent } from '@hydranium/protocol/data';
19
+ import {
20
+ asModelVersion,
21
+ FRAMEWORK_CLIENT_IDS,
22
+ isConflictError,
23
+ isDocumentNotOpenError,
24
+ isDuplicateClientIdError,
25
+ isReservedClientIdError,
26
+ isSessionClosedError,
27
+ ReferenceSource,
28
+ SyntheticStep,
29
+ SystemClock,
30
+ TransferDocument,
31
+ type TransferDiagnostic,
32
+ type TransferElement,
33
+ UNKNOWN_CLIENT_ID
34
+ } from '@hydranium/protocol';
35
+ import type {
36
+ DataServerProtocol,
37
+ ReferenceServerProtocol,
38
+ TransferDocumentsBuiltEvent,
39
+ TransferDocumentUpdatedEvent
40
+ } from '@hydranium/protocol/data';
21
41
  import { type Harness, waitFor } from '@hydranium/protocol/testing';
22
42
  import type { ConformanceCheck } from '../conformance-suite.js';
23
43
  import { type LanguageFixture, resolveDeferred, resolveModel } from '../model.js';
24
44
 
25
45
  /**
26
46
  * The data-server driver port — a live, connected, READY data-server exposed
27
- * through its protocol-native proxy plus the captured client-side update
28
- * events. The kit names only `@hydranium/protocol` types, so a
47
+ * through its protocol-native proxy plus the captured client-side
48
+ * notifications. The kit names only `@hydranium/protocol` types, so a
29
49
  * `DataServerHarness` satisfies the port structurally (it has `proxy` +
30
- * `events` + `dispose`) with NO adapter. `extends Harness` gives the kit the
50
+ * `events`, `builds` and `dispose`) with NO adapter. `extends Harness` gives the kit the
31
51
  * universal `dispose()` teardown.
32
52
  *
33
- * The kit seeds documents purely through the proxy: `updateModelDocument` is
34
- * an upsert (it creates a cold URI from the payload, not just modifies an
35
- * existing one), so the slice needs no services-level open hook. The adopter
36
- * only has to stand the server up READY in its `connect` — see
37
- * {@link DataConformanceOptions.connect}.
53
+ * The kit seeds documents purely through the proxy, as client sessions: it
54
+ * registers one with `createSession`, opens the document, or creates it with
55
+ * `createModelDocument` when there is no file to open, and writes it. So the
56
+ * head under test must implement sessions, and the slice needs no
57
+ * services-level open hook. The adopter only has to stand the server up READY
58
+ * in its `connect` — see {@link DataConformanceOptions.connect}.
38
59
  */
39
60
  export interface DataConformanceDriver<
40
61
  TTransfer extends TransferElement,
41
62
  TDiagnostic extends TransferDiagnostic = TransferDiagnostic
42
63
  > extends Harness {
43
64
  readonly proxy: DataServerProtocol<TTransfer, TDiagnostic>;
44
- /** Captured `onDocumentUpdated` events, append order — the subscription check's observation target. */
65
+ /** Captured `onDocumentUpdated` events, in append order. */
45
66
  readonly events: ReadonlyArray<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>>;
67
+ /** Captured `onDocumentsBuilt` events, append order — the cascade check's observation target. */
68
+ readonly builds: ReadonlyArray<TransferDocumentsBuiltEvent>;
69
+ /**
70
+ * The opt-in reference surface, when the head serves it.
71
+ *
72
+ * Separate from {@link proxy} because `ReferenceServerProtocol` is NOT part
73
+ * of `DataServerProtocol` — a head may serve documents and no references at
74
+ * all. Absent means the reference check reports skipped with a named reason
75
+ * rather than failing a head that never claimed the surface.
76
+ */
77
+ readonly references?: ReferenceServerProtocol;
46
78
  }
47
79
 
48
80
  /** Options for `runDataConformance`. */
@@ -52,6 +84,10 @@ export interface DataConformanceOptions<TTransfer extends TransferElement, TDiag
52
84
  * once per check for isolation; the kit disposes it after the check. The
53
85
  * adopter must initialise the workspace before returning, so `waitForReady`
54
86
  * resolves rather than hanging.
87
+ *
88
+ * Some checks save documents beside each fixture's `valid`, and nothing in
89
+ * the protocol deletes a file, so give each check a workspace the kit may
90
+ * write to and throw away.
55
91
  */
56
92
  readonly connect: () => DataConformanceDriver<TTransfer, TDiagnostic> | Promise<DataConformanceDriver<TTransfer, TDiagnostic>>;
57
93
  /** Per-language fixtures; the grammar-bearing checks run once per language. */
@@ -67,22 +103,141 @@ export interface DataConformanceOptions<TTransfer extends TransferElement, TDiag
67
103
  * from "never implemented" without the adopter saying which it is.
68
104
  */
69
105
  readonly expectsProjects?: boolean;
70
- /** Suite title override. Default `'conformance: data-server'`. */
106
+ /**
107
+ * Open another connection to the same server as `driver`, for the check
108
+ * that a connection's sessions end with it while the server lives on. That
109
+ * check disposes `driver` and needs its `dispose` to close the connection as
110
+ * the server sees it. Absent, the check reports skipped.
111
+ */
112
+ readonly attach?: (
113
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>
114
+ ) => DataConformanceDriver<TTransfer, TDiagnostic> | Promise<DataConformanceDriver<TTransfer, TDiagnostic>>;
115
+ /** Suite title override. Default `'data-server conformance'`. */
71
116
  readonly suiteTitle?: string;
72
117
  }
73
118
 
74
- /** Client id the kit seeds/edits documents under (the originating author). */
75
- const AUTHOR = 'conformance-author';
76
- /** Client id the kit subscribes under — distinct from {@link AUTHOR} so the echo is recognisable. */
119
+ /** Client id the kit subscribes under; a watch needs no session. */
77
120
  const SUBSCRIBER = 'conformance-subscriber';
121
+
122
+ /**
123
+ * A fresh session id per check. A fixed one would be refused as a duplicate
124
+ * by a head whose `connect` reuses one server across checks, whenever an
125
+ * earlier check failed before ending its session.
126
+ */
127
+ function sessionId(label = 'conformance-session'): string {
128
+ return `${label}#${globalThis.crypto.randomUUID()}`;
129
+ }
130
+
131
+ /** Register a session under a fresh id labelled `label`, and answer the id. */
132
+ async function startSession<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
133
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
134
+ label: string
135
+ ): Promise<string> {
136
+ const clientId = sessionId(label);
137
+ await driver.proxy.createSession({ clientId, label });
138
+ return clientId;
139
+ }
140
+
141
+ /**
142
+ * Create `model` for the session `clientId`, then open it, since a fixture may
143
+ * name a document that exists nowhere but in the kit. A failed create is
144
+ * dropped when the open succeeds, so a head whose create is broken fails only
145
+ * the create check; an open that fails reports both failures.
146
+ */
147
+ async function openOrCreate<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
148
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
149
+ clientId: string,
150
+ model: { readonly uri: string; readonly text: string }
151
+ ): Promise<void> {
152
+ const created = await rejectionOf(driver.proxy.createModelDocument({ uri: model.uri, clientId, text: model.text }));
153
+ const opened = await rejectionOf(driver.proxy.openModelDocument({ uri: model.uri, clientId }));
154
+ if (opened !== undefined) {
155
+ throw new Error(`Could not seed ${model.uri}: ${String(opened)}; creating it failed with ${String(created)}`, { cause: opened });
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Write `model` to its URI under a new session labelled `label`, and answer the
161
+ * session's id. The session keeps the document open until the driver is
162
+ * disposed: closing it would revert the document to its file, which holds
163
+ * another text or none.
164
+ */
165
+ async function seed<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
166
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
167
+ model: { readonly uri: string; readonly text: string },
168
+ label = 'conformance-seeder'
169
+ ): Promise<string> {
170
+ const clientId = await startSession(driver, label);
171
+ await openOrCreate(driver, clientId, model);
172
+ await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' });
173
+ return clientId;
174
+ }
175
+
176
+ /** A new session labelled `label` with `uri` open, for a write after the seed; answers its id. */
177
+ async function openAs<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
178
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
179
+ uri: string,
180
+ label = 'conformance-author'
181
+ ): Promise<string> {
182
+ const clientId = await startSession(driver, label);
183
+ await driver.proxy.openModelDocument({ uri, clientId });
184
+ return clientId;
185
+ }
186
+
78
187
  /**
79
- * Client id for a write made BEFORE any subscription exists. Distinct from
80
- * {@link AUTHOR} so an event caused by it is recognisable: a head that fans
81
- * notifications out regardless of its subscription table is otherwise
82
- * indistinguishable from one that honours the table, since both deliver
83
- * something for the post-subscribe write.
188
+ * Register `clientId` on `driver`, retrying while the server still refuses it
189
+ * as a duplicate, for up to `boundMs`; the last refusal is thrown.
84
190
  */
85
- const SEEDER = 'conformance-seeder';
191
+ async function registerWithin<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
192
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
193
+ clientId: string,
194
+ boundMs: number
195
+ ): Promise<void> {
196
+ const waited = new SystemClock().stopwatch();
197
+ for (;;) {
198
+ const refusal = await rejectionOf(driver.proxy.createSession({ clientId }));
199
+ if (refusal === undefined) {
200
+ return;
201
+ }
202
+ if (!isDuplicateClientIdError(refusal) || waited.elapsedMs >= boundMs) {
203
+ throw refusal;
204
+ }
205
+ await new Promise(resolveDelay => setTimeout(resolveDelay, 20));
206
+ }
207
+ }
208
+
209
+ /** A URI beside `uri` in its folder, its file name prefixed with `prefix`, so the language and project stay the fixture's. */
210
+ function siblingOf(uri: string, prefix: string): string {
211
+ const slash = uri.lastIndexOf('/') + 1;
212
+ return `${uri.slice(0, slash)}${prefix}${uri.slice(slash)}`;
213
+ }
214
+
215
+ /**
216
+ * Read `uri` until `settled` holds of the answer, for up to two seconds; fail
217
+ * with `message` after that. For an effect a head may finish after its request
218
+ * answered, such as the revert of a last close. A refused read reaches
219
+ * `settled` as `undefined`.
220
+ */
221
+ async function readUntil<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
222
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
223
+ uri: string,
224
+ settled: (document: TransferDocument<TTransfer, TDiagnostic> | undefined) => boolean,
225
+ message: string
226
+ ): Promise<void> {
227
+ const waited = new SystemClock().stopwatch();
228
+ while (!settled(await driver.proxy.getModelDocument({ uri }).catch(() => undefined))) {
229
+ assert.ok(waited.elapsedMs < 2_000, message);
230
+ await new Promise(resolveDelay => setTimeout(resolveDelay, 20));
231
+ }
232
+ }
233
+
234
+ /** Settle `promise` into its rejection, or `undefined` when it resolved. */
235
+ async function rejectionOf(promise: Promise<unknown>): Promise<unknown> {
236
+ return promise.then(
237
+ () => undefined,
238
+ (error: unknown) => error
239
+ );
240
+ }
86
241
 
87
242
  /**
88
243
  * Build the data-server check battery: server-level checks once, then the
@@ -91,13 +246,13 @@ const SEEDER = 'conformance-seeder';
91
246
  * unit tests; adopters call `runDataConformance`.
92
247
  *
93
248
  * `LanguageFixture.edit` is read HERE and nowhere else in the kit, and is
94
- * optional: its two checks report skipped when it is absent. See
249
+ * optional: every check that needs one reports skipped when it is absent. See
95
250
  * {@link LanguageFixture} for which slice reads which field.
96
251
  */
97
252
  export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic = TransferDiagnostic>(
98
253
  options: DataConformanceOptions<TTransfer, TDiagnostic>
99
254
  ): ConformanceCheck[] {
100
- const { connect, expectsProjects } = options;
255
+ const { connect, attach, expectsProjects } = options;
101
256
  const checks: ConformanceCheck[] = [];
102
257
 
103
258
  // Split from `waitForReady` so a failure names which of the two broke.
@@ -162,6 +317,46 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
162
317
  : undefined
163
318
  });
164
319
 
320
+ checks.push({
321
+ title: 'createSession refuses an id already live, and frees it once the session ends',
322
+ body: async () => {
323
+ const driver = await connect();
324
+ try {
325
+ const clientId = await startSession(driver, 'conformance-session');
326
+ const duplicate = await rejectionOf(driver.proxy.createSession({ clientId }));
327
+ assert.ok(isDuplicateClientIdError(duplicate), `a second createSession under a live id was not refused: ${String(duplicate)}`);
328
+ await driver.proxy.closeSession({ clientId });
329
+ // The other half: a head that refused every id would pass the
330
+ // assertion above on its own.
331
+ await driver.proxy.createSession({ clientId });
332
+ await driver.proxy.closeSession({ clientId });
333
+ } finally {
334
+ driver.dispose();
335
+ }
336
+ }
337
+ });
338
+
339
+ checks.push({
340
+ title: 'createSession refuses every id the framework reserves, not as a duplicate',
341
+ body: async () => {
342
+ const driver = await connect();
343
+ try {
344
+ // Every id: a head that refuses only some passes a single case. A
345
+ // reserved id never frees up, so a caller retrying on a duplicate
346
+ // has to be able to tell this refusal apart.
347
+ for (const clientId of FRAMEWORK_CLIENT_IDS) {
348
+ const refusal = await rejectionOf(driver.proxy.createSession({ clientId }));
349
+ assert.ok(
350
+ isReservedClientIdError(refusal),
351
+ `createSession under the reserved id ${clientId} was not refused as reserved: ${String(refusal)}`
352
+ );
353
+ }
354
+ } finally {
355
+ driver.dispose();
356
+ }
357
+ }
358
+ });
359
+
165
360
  checks.push({
166
361
  title: 'waitForReady resolves rather than hanging or rejecting',
167
362
  body: async () => {
@@ -178,7 +373,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
178
373
  });
179
374
 
180
375
  for (const language of options.languages) {
181
- const { valid, invalid, edit } = language;
376
+ const { valid, invalid, edit, dependent } = language;
182
377
  const tag = `[${valid.languageId}]`;
183
378
 
184
379
  checks.push({
@@ -189,7 +384,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
189
384
  // Resolved AFTER `connect`, which is the whole point of allowing a
190
385
  // thunk: the fixture may name a workspace `connect` just created.
191
386
  const model = resolveModel(valid);
192
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
387
+ await seed(driver, model);
193
388
  // `includeDiagnostics` for the same reason the invalid check
194
389
  // passes it: a synchronous read settles at the integrity-settled
195
390
  // phase, so an empty array without it can mean "validation has
@@ -200,7 +395,8 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
200
395
  // a shaped-but-contentless envelope for a document it did parse
201
396
  // would pass. `$type` is the one field every TransferElement
202
397
  // carries, so it is assertable with no fixture knowledge.
203
- const { root } = TransferDocument.assertLoaded(document);
398
+ const { model: snapshot } = TransferDocument.assertLoaded(document);
399
+ const { root } = snapshot;
204
400
  assert.ok(
205
401
  typeof root.$type === 'string' && root.$type.length > 0,
206
402
  `getModelDocument(valid) returned a root with no $type: ${JSON.stringify(root)}`
@@ -208,10 +404,11 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
208
404
  // `version` is the conflict token every later update gates on, so
209
405
  // an envelope that omits it is unusable however good the root is.
210
406
  assert.ok(
211
- Number.isInteger(document.version),
212
- `getModelDocument(valid) returned a non-integer version: ${String(document.version)}`
407
+ Number.isInteger(snapshot.version),
408
+ `getModelDocument(valid) returned a non-integer version: ${String(snapshot.version)}`
213
409
  );
214
- assert.deepStrictEqual(document.diagnostics, []);
410
+ assert.strictEqual(typeof snapshot.hash, 'string', 'getModelDocument(valid) returned a model with no hash');
411
+ assert.deepStrictEqual(snapshot.diagnostics, []);
215
412
  } finally {
216
413
  driver.dispose();
217
414
  }
@@ -224,21 +421,454 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
224
421
  const driver = await connect();
225
422
  try {
226
423
  const model = resolveModel(invalid);
227
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
424
+ await seed(driver, model);
228
425
  // Diagnostics are a validation-phase product; a synchronous read settles at the
229
426
  // integrity-settled phase by default, so request validation explicitly here.
230
427
  // Safe despite `includeDiagnostics` waiting rather than forcing a build: the
231
428
  // update above has already driven this document through validation.
232
429
  const document = await driver.proxy.getModelDocument({ uri: model.uri, includeDiagnostics: true });
233
- assert.ok(document.diagnostics.length >= 1, 'getModelDocument(invalid) reported no diagnostics');
430
+ assert.ok((document.model?.diagnostics?.length ?? 0) >= 1, 'getModelDocument(invalid) reported no diagnostics');
234
431
  } finally {
235
432
  driver.dispose();
236
433
  }
237
434
  }
238
435
  });
239
436
 
240
- // Opt-in: both remaining checks need a second, observably different model
241
- // text, which only `edit` supplies.
437
+ checks.push({
438
+ title: `a diagnostic carrying a framework message code also carries its params ${tag}`,
439
+ body: async () => {
440
+ const driver = await connect();
441
+ try {
442
+ const model = resolveModel(invalid);
443
+ await seed(driver, model);
444
+ const document = await driver.proxy.getModelDocument({ uri: model.uri, includeDiagnostics: true });
445
+
446
+ // Conditional rather than fixture-driven, and deliberately so: what
447
+ // an `invalid` fixture provokes is the adopter's choice, and a
448
+ // syntactic error legitimately carries no identity at all. The
449
+ // invariant is that the identity travels WHOLE or not — a `code`
450
+ // without `params` is the half-state that renders a translated
451
+ // template with its placeholders left standing, and it is
452
+ // reachable only by overriding `toTransferDiagnostic`.
453
+ const halfIdentities = (document.model?.diagnostics ?? []).filter(
454
+ diagnostic =>
455
+ typeof diagnostic.code === 'string' && diagnostic.code.startsWith('hydranium/') && diagnostic.params === undefined
456
+ );
457
+ assert.deepStrictEqual(
458
+ halfIdentities.map(diagnostic => diagnostic.code),
459
+ [],
460
+ 'diagnostics carry a framework message code with no params, so a translating surface cannot render them'
461
+ );
462
+ } finally {
463
+ driver.dispose();
464
+ }
465
+ }
466
+ });
467
+
468
+ checks.push({
469
+ title: `a session writes only a document it has open ${tag}`,
470
+ body: async () => {
471
+ const driver = await connect();
472
+ try {
473
+ const model = resolveModel(valid);
474
+ await seed(driver, model);
475
+ const clientId = await startSession(driver, 'conformance-session');
476
+ const write = { uri: model.uri, clientId, model: model.text, baseVersion: 'any' } as const;
477
+
478
+ const unopened = await rejectionOf(driver.proxy.updateModelDocument(write));
479
+ assert.ok(isDocumentNotOpenError(unopened), `a session wrote a document it never opened: ${String(unopened)}`);
480
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
481
+ await driver.proxy.updateModelDocument(write);
482
+ await driver.proxy.closeModelDocument({ uri: model.uri, clientId });
483
+ const closed = await rejectionOf(driver.proxy.updateModelDocument(write));
484
+ assert.ok(isDocumentNotOpenError(closed), `a session wrote a document after closing it: ${String(closed)}`);
485
+ await driver.proxy.closeSession({ clientId });
486
+ } finally {
487
+ driver.dispose();
488
+ }
489
+ }
490
+ });
491
+
492
+ checks.push({
493
+ title: `a session saves only a document it has open ${tag}`,
494
+ body: async () => {
495
+ const driver = await connect();
496
+ try {
497
+ const model = resolveModel(valid);
498
+ await seed(driver, model);
499
+ const clientId = await startSession(driver, 'conformance-session');
500
+ const save = { uri: model.uri, clientId, model: model.text, baseVersion: 'any' } as const;
501
+
502
+ const unopened = await rejectionOf(driver.proxy.saveModelDocument(save));
503
+ assert.ok(isDocumentNotOpenError(unopened), `a session saved a document it never opened: ${String(unopened)}`);
504
+ // The other half: a head refusing every session save would pass
505
+ // the assertion above on its own.
506
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
507
+ await driver.proxy.saveModelDocument(save);
508
+ await driver.proxy.closeSession({ clientId });
509
+ } finally {
510
+ driver.dispose();
511
+ }
512
+ }
513
+ });
514
+
515
+ checks.push({
516
+ title: `a document request under an id no session was registered for fails ${tag}`,
517
+ body: async () => {
518
+ const driver = await connect();
519
+ try {
520
+ const model = resolveModel(valid);
521
+ await seed(driver, model);
522
+ const clientId = sessionId('conformance-unregistered');
523
+
524
+ // Opened or written under an id that is no session, a document
525
+ // would stay open for a client whose end nothing ever reports.
526
+ const open = await rejectionOf(driver.proxy.openModelDocument({ uri: model.uri, clientId }));
527
+ assert.ok(isSessionClosedError(open), `a document opened under an unregistered id: ${String(open)}`);
528
+ const write = await rejectionOf(
529
+ driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
530
+ );
531
+ assert.ok(isSessionClosedError(write), `a document was written under an unregistered id: ${String(write)}`);
532
+ } finally {
533
+ driver.dispose();
534
+ }
535
+ }
536
+ });
537
+
538
+ checks.push({
539
+ title: `ending a connection ends its sessions ${tag}`,
540
+ skipReason: attach ? undefined : 'options supply no `attach` (a second connection to the same server outlives the ended one)',
541
+ body: attach
542
+ ? async () => {
543
+ const driver = await connect();
544
+ let driverOpen = true;
545
+ try {
546
+ const model = resolveModel(valid);
547
+ await seed(driver, model);
548
+ const clientId = await startSession(driver, 'conformance-session');
549
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
550
+ const sibling = await attach(driver);
551
+ try {
552
+ driverOpen = false;
553
+ driver.dispose();
554
+ // Refused as a duplicate while the ended connection's
555
+ // session lives on, which over a socket it does until the
556
+ // server has seen the close; so retried, within a bound.
557
+ await registerWithin(sibling, clientId, 2_000);
558
+ const write = await rejectionOf(
559
+ sibling.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
560
+ );
561
+ assert.ok(isDocumentNotOpenError(write), `a document stayed open after its connection ended: ${String(write)}`);
562
+ await sibling.proxy.closeSession({ clientId });
563
+ } finally {
564
+ sibling.dispose();
565
+ }
566
+ } finally {
567
+ if (driverOpen) {
568
+ driver.dispose();
569
+ }
570
+ }
571
+ }
572
+ : undefined
573
+ });
574
+
575
+ checks.push({
576
+ title: `closeSession closes every document the session had open ${tag}`,
577
+ body: async () => {
578
+ const driver = await connect();
579
+ try {
580
+ const model = resolveModel(valid);
581
+ await seed(driver, model);
582
+ const clientId = await startSession(driver, 'conformance-session');
583
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
584
+
585
+ await driver.proxy.closeSession({ clientId });
586
+
587
+ // Observed through a new session under the same id: one that
588
+ // inherited the ended session's open would write without opening.
589
+ await driver.proxy.createSession({ clientId });
590
+ const write = await rejectionOf(
591
+ driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
592
+ );
593
+ assert.ok(isDocumentNotOpenError(write), `a document stayed open after its session ended: ${String(write)}`);
594
+ await driver.proxy.closeSession({ clientId });
595
+ } finally {
596
+ driver.dispose();
597
+ }
598
+ }
599
+ });
600
+
601
+ checks.push({
602
+ title: `createModelDocument creates a document open for the session, and refuses one that exists ${tag}`,
603
+ body: async () => {
604
+ const driver = await connect();
605
+ try {
606
+ const model = resolveModel(valid);
607
+ await seed(driver, model);
608
+ const clientId = await startSession(driver, 'conformance-session');
609
+ const createdUri = siblingOf(model.uri, 'conformance-created-');
610
+
611
+ const created = await driver.proxy.createModelDocument({ uri: createdUri, clientId, text: model.text });
612
+ const { model: createdModel } = TransferDocument.assertLoaded(created);
613
+ // Written without an open: only the create can have opened it.
614
+ await driver.proxy.updateModelDocument({ uri: createdUri, clientId, model: model.text, baseVersion: createdModel.version });
615
+
616
+ const existing = await rejectionOf(driver.proxy.createModelDocument({ uri: model.uri, clientId, text: model.text }));
617
+ assert.ok(existing !== undefined, `createModelDocument accepted ${model.uri}, which already exists`);
618
+ await driver.proxy.closeSession({ clientId });
619
+ } finally {
620
+ driver.dispose();
621
+ }
622
+ }
623
+ });
624
+
625
+ checks.push({
626
+ title: `a write of the invalid model answers with its diagnostics ${tag}`,
627
+ body: async () => {
628
+ const driver = await connect();
629
+ try {
630
+ const model = resolveModel(invalid);
631
+ const clientId = await startSession(driver, 'conformance-session');
632
+ await openOrCreate(driver, clientId, model);
633
+ // Another text first, so that the invalid one is a change: the
634
+ // answer to a write that changes nothing can carry the
635
+ // diagnostics of an earlier validation. This does not prove the
636
+ // answer waited for this write's validation, only that it
637
+ // carries diagnostics at all.
638
+ const firstText = resolveDeferred(valid.text);
639
+ await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: firstText, baseVersion: 'any' });
640
+ // The answer alone, with no read after it: a caller that shows
641
+ // the problems of what it wrote should not need a second
642
+ // request, and a read could find a later write's state.
643
+ const answer = await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' });
644
+ assert.ok((answer.model?.diagnostics?.length ?? 0) >= 1, 'writing the invalid model answered with no diagnostics');
645
+ await driver.proxy.closeSession({ clientId });
646
+ } finally {
647
+ driver.dispose();
648
+ }
649
+ }
650
+ });
651
+
652
+ checks.push({
653
+ title: `a created document never saved leaves with its last close ${tag}`,
654
+ body: async () => {
655
+ const driver = await connect();
656
+ try {
657
+ const model = resolveModel(valid);
658
+ const uri = siblingOf(model.uri, 'conformance-unsaved-');
659
+ const clientId = await startSession(driver, 'conformance-session');
660
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
661
+ // Served before the close, so an envelope without a model after
662
+ // it is the close's doing and not the head's answer for every
663
+ // created document.
664
+ TransferDocument.assertLoaded(await driver.proxy.getModelDocument({ uri }));
665
+ await driver.proxy.closeSession({ clientId });
666
+ // It has no file to go back to, so no text is left to serve, and
667
+ // the protocol answers a URI with no document with an envelope
668
+ // that has no model, not with a refusal.
669
+ await readUntil(
670
+ driver,
671
+ uri,
672
+ document => document !== undefined && !TransferDocument.isLoaded(document),
673
+ `${uri}, created and never saved, was not answered with an envelope without a model after its last close`
674
+ );
675
+ } finally {
676
+ driver.dispose();
677
+ }
678
+ }
679
+ });
680
+
681
+ checks.push({
682
+ title: `a document is dirty while its text differs from its file, and clean once saved ${tag}`,
683
+ body: async () => {
684
+ const driver = await connect();
685
+ try {
686
+ const model = resolveModel(valid);
687
+ // Only `dirty` is asserted, so any second text serves.
688
+ const unsaved = resolveDeferred(invalid.text);
689
+ const uri = siblingOf(model.uri, `conformance-saved-${globalThis.crypto.randomUUID()}-`);
690
+ const clientId = await startSession(driver, 'conformance-session');
691
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
692
+
693
+ const saved = await driver.proxy.saveModelDocument({ uri, clientId, model: model.text, baseVersion: 'any' });
694
+ assert.strictEqual(saved.text?.dirty, false, `the save of ${uri} answered dirty: ${String(saved.text?.dirty)}, not false`);
695
+ assert.strictEqual(
696
+ saved.persisted?.version,
697
+ saved.text?.version,
698
+ `the save of ${uri} answered it wrote v${String(saved.persisted?.version)}, not the v${String(saved.text?.version)} it holds`
699
+ );
700
+ const edited = await driver.proxy.updateModelDocument({ uri, clientId, model: unsaved, baseVersion: 'any' });
701
+ assert.strictEqual(
702
+ edited.text?.dirty,
703
+ true,
704
+ `an unsaved write of ${uri} answered dirty: ${String(edited.text?.dirty)}, not true`
705
+ );
706
+ const resaved = await driver.proxy.saveModelDocument({ uri, clientId, model: unsaved, baseVersion: 'any' });
707
+ assert.strictEqual(
708
+ resaved.text?.dirty,
709
+ false,
710
+ `the second save of ${uri} answered dirty: ${String(resaved.text?.dirty)}, not false`
711
+ );
712
+ await driver.proxy.closeSession({ clientId });
713
+ } finally {
714
+ driver.dispose();
715
+ }
716
+ }
717
+ });
718
+
719
+ checks.push({
720
+ title: `persisting writes the text a document holds as it is, and refuses a stale base version ${tag}`,
721
+ body: async () => {
722
+ const driver = await connect();
723
+ try {
724
+ const model = resolveModel(valid);
725
+ // Trailing blank lines no serialiser writes, so a head that
726
+ // persists a re-serialised model rather than the text shows.
727
+ const held = `${model.text}\n\n`;
728
+ const uri = siblingOf(model.uri, `conformance-persisted-${globalThis.crypto.randomUUID()}-`);
729
+ const writer = await startSession(driver, 'conformance-writer');
730
+ const created = await driver.proxy.createModelDocument({ uri, clientId: writer, text: model.text });
731
+ const written = await driver.proxy.updateModelDocument({ uri, clientId: writer, model: held, baseVersion: 'any' });
732
+ const persister = await openAs(driver, uri, 'conformance-persister');
733
+
734
+ const stale = await rejectionOf(
735
+ driver.proxy.persistModelDocument({
736
+ uri,
737
+ clientId: persister,
738
+ baseVersion: TransferDocument.assertLoaded(created).model.version
739
+ })
740
+ );
741
+ assert.ok(isConflictError(stale), `persisting ${uri} on a stale base version did not conflict: ${String(stale)}`);
742
+ const base = TransferDocument.assertLoaded(written).model.version;
743
+ const persisted = await driver.proxy.persistModelDocument({ uri, clientId: persister, baseVersion: base });
744
+ assert.strictEqual(
745
+ persisted.persisted?.version,
746
+ base,
747
+ `the persist of ${uri} answered it wrote v${String(persisted.persisted?.version)}, not the v${base} it was based on`
748
+ );
749
+ assert.strictEqual(persisted.text?.dirty, false, `the persist of ${uri} answered dirty: ${String(persisted.text?.dirty)}`);
750
+ assert.strictEqual(persisted.text?.hash, written.text?.hash, `persisting ${uri} changed the text it holds`);
751
+
752
+ // Read after the last close, which serves the file: read before
753
+ // it, the held text answers and a file written wrong passes.
754
+ await driver.proxy.closeSession({ clientId: writer });
755
+ await driver.proxy.closeSession({ clientId: persister });
756
+ const reader = await openAs(driver, uri, 'conformance-reader');
757
+ const reread = await driver.proxy.getModelDocument({ uri });
758
+ assert.strictEqual(reread.text?.hash, written.text?.hash, `the file persisted for ${uri} is not the text it held`);
759
+ await driver.proxy.closeSession({ clientId: reader });
760
+ } finally {
761
+ driver.dispose();
762
+ }
763
+ }
764
+ });
765
+
766
+ checks.push({
767
+ title: `a document's text hash is equal for equal text and differs for different text ${tag}`,
768
+ body: async () => {
769
+ const driver = await connect();
770
+ try {
771
+ const model = resolveModel(valid);
772
+ // Only the text is compared, so any second text serves.
773
+ const other = resolveDeferred(invalid.text);
774
+ const uri = siblingOf(model.uri, `conformance-hashed-${globalThis.crypto.randomUUID()}-`);
775
+ const clientId = await startSession(driver, 'conformance-session');
776
+ const created = await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
777
+ const edited = await driver.proxy.updateModelDocument({ uri, clientId, model: other, baseVersion: 'any' });
778
+ // Back to the first text at a later version: the hash follows
779
+ // the text, which is what a client compares across a revert.
780
+ const restored = await driver.proxy.updateModelDocument({ uri, clientId, model: model.text, baseVersion: 'any' });
781
+
782
+ assert.strictEqual(typeof created.text?.hash, 'string', `the create of ${uri} answered with no text hash`);
783
+ assert.notStrictEqual(
784
+ edited.text?.hash,
785
+ created.text?.hash,
786
+ `${uri} hashed a different text alike: ${String(edited.text?.hash)}`
787
+ );
788
+ assert.strictEqual(
789
+ restored.text?.hash,
790
+ created.text?.hash,
791
+ `${uri} hashed its first text again as ${String(restored.text?.hash)}`
792
+ );
793
+ const read = await driver.proxy.getModelDocument({ uri });
794
+ assert.strictEqual(read.text?.hash, restored.text?.hash, `a read of ${uri} hashed its text as ${String(read.text?.hash)}`);
795
+ const absent = await driver.proxy.getModelDocument({
796
+ uri: siblingOf(model.uri, `conformance-absent-${globalThis.crypto.randomUUID()}-`)
797
+ });
798
+ assert.strictEqual(absent.text, undefined, `an envelope with no document carried text ${JSON.stringify(absent.text)}`);
799
+ await driver.proxy.closeSession({ clientId });
800
+ } finally {
801
+ driver.dispose();
802
+ }
803
+ }
804
+ });
805
+
806
+ // The create-dialog query, and the reason it is its own check: it is the
807
+ // only request a head receives whose URI names no file. Everything else
808
+ // in this battery addresses a document, so a head that routes purely by
809
+ // URI extension passes all of them and still cannot open a create dialog.
810
+ //
811
+ // Doubly opt-in — the fixture must name a query AND the driver must serve
812
+ // the reference surface — because either half missing means the head never
813
+ // claimed this behaviour. The reasons are reported separately so a skip
814
+ // says which half is absent.
815
+ const referenceQuery = language.referenceQuery;
816
+ const referenceSkipReason = !referenceQuery
817
+ ? 'fixture supplies no `referenceQuery` (omit it if this language has no create-element dialog)'
818
+ : undefined;
819
+
820
+ checks.push({
821
+ title: `findReferenceCandidates answers for a synthetic source at a folder URI ${tag}`,
822
+ skipReason: referenceSkipReason,
823
+ body: referenceQuery
824
+ ? async () => {
825
+ const driver = await connect();
826
+ try {
827
+ if (!driver.references) {
828
+ // Checked here rather than in `skipReason`: the driver only
829
+ // exists once `connect` has run, and skip reasons are
830
+ // computed while the battery is being planned.
831
+ return;
832
+ }
833
+ const model = resolveModel(valid);
834
+ await seed(driver, model);
835
+
836
+ // Default to the folder holding the valid model: a sibling of
837
+ // it is where a create flow would put the new file.
838
+ const folderUri = referenceQuery.folderUri
839
+ ? resolveDeferred(referenceQuery.folderUri)
840
+ : model.uri.slice(0, model.uri.lastIndexOf('/'));
841
+ assert.ok(
842
+ folderUri.length > 0 && folderUri !== model.uri,
843
+ `could not derive a folder URI from ${model.uri}; supply referenceQuery.folderUri`
844
+ );
845
+
846
+ const candidates = await driver.references.findReferenceCandidates({
847
+ source: ReferenceSource.synthetic(folderUri, referenceQuery.type),
848
+ syntheticPath: referenceQuery.path?.map(([containerProperty, type]) => SyntheticStep.of(containerProperty, type)),
849
+ property: referenceQuery.property
850
+ });
851
+
852
+ // The expected label, not merely a non-empty array: the defect
853
+ // this guards against answers `[]`, and an empty result is
854
+ // also what a head with a genuinely empty index answers, so
855
+ // only a named candidate tells the two apart.
856
+ const labels = candidates.map(candidate => candidate.label);
857
+ assert.ok(
858
+ labels.includes(referenceQuery.expectCandidate),
859
+ `findReferenceCandidates at the folder ${folderUri} did not offer ${JSON.stringify(
860
+ referenceQuery.expectCandidate
861
+ )}; got [${labels.join(', ')}]`
862
+ );
863
+ } finally {
864
+ driver.dispose();
865
+ }
866
+ }
867
+ : undefined
868
+ });
869
+
870
+ // Opt-in: a check that needs a second, observably different model text
871
+ // takes it from `edit`, and skips without one.
242
872
  const editSkipReason = 'fixture supplies no `edit` (data-slice only; omit it if this language is not driven through the data head)';
243
873
 
244
874
  checks.push({
@@ -249,10 +879,72 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
249
879
  const driver = await connect();
250
880
  try {
251
881
  const model = resolveModel(valid);
252
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
253
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: resolveDeferred(edit.to) });
882
+ const seeder = await seed(driver, model);
883
+ await driver.proxy.updateModelDocument({
884
+ uri: model.uri,
885
+ clientId: seeder,
886
+ model: resolveDeferred(edit.to),
887
+ baseVersion: 'any'
888
+ });
254
889
  const document = await driver.proxy.getModelDocument({ uri: model.uri });
255
- assert.ok(edit.expect(document.root), 'edit.expect(root) was false — the edit was not reflected by a follow-up get');
890
+ assert.ok(
891
+ edit.expect(document.model?.root),
892
+ 'edit.expect(root) was false — the edit was not reflected by a follow-up get'
893
+ );
894
+ } finally {
895
+ driver.dispose();
896
+ }
897
+ }
898
+ : undefined
899
+ });
900
+
901
+ checks.push({
902
+ title: `updateModelDocument arms the conflict gate on a base version ${tag}`,
903
+ skipReason: edit ? undefined : editSkipReason,
904
+ body: edit
905
+ ? async () => {
906
+ const driver = await connect();
907
+ try {
908
+ const model = resolveModel(valid);
909
+ const seeder = await seed(driver, model);
910
+ const author = await openAs(driver, model.uri);
911
+
912
+ // The version the gate is meant to accept, read BEFORE the
913
+ // foreign edit that supersedes it.
914
+ const stale = await driver.proxy.getModelDocument({ uri: model.uri });
915
+ await driver.proxy.updateModelDocument({
916
+ uri: model.uri,
917
+ clientId: seeder,
918
+ model: resolveDeferred(edit.to),
919
+ baseVersion: 'any'
920
+ });
921
+
922
+ let rejection: unknown;
923
+ await driver.proxy
924
+ .updateModelDocument({
925
+ uri: model.uri,
926
+ clientId: author,
927
+ model: model.text,
928
+ baseVersion: TransferDocument.assertLoaded(stale).model.version
929
+ })
930
+ .catch((error: unknown) => {
931
+ rejection = error;
932
+ });
933
+ assert.ok(
934
+ isConflictError(rejection),
935
+ `a write based on the superseded v${String(stale.model?.version)} was not refused: ${String(rejection)}`
936
+ );
937
+
938
+ // The other half, and it is not optional: a head that refused
939
+ // EVERY write would satisfy the assertion above on its own, so
940
+ // the gate has to be shown accepting a current snapshot too.
941
+ const fresh = await driver.proxy.getModelDocument({ uri: model.uri });
942
+ await driver.proxy.updateModelDocument({
943
+ uri: model.uri,
944
+ clientId: author,
945
+ model: resolveDeferred(edit.to),
946
+ baseVersion: TransferDocument.assertLoaded(fresh).model.version
947
+ });
256
948
  } finally {
257
949
  driver.dispose();
258
950
  }
@@ -260,6 +952,221 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
260
952
  : undefined
261
953
  });
262
954
 
955
+ checks.push({
956
+ title: `the last close drops a document's unsaved text and keeps what its save wrote ${tag}`,
957
+ skipReason: edit ? undefined : editSkipReason,
958
+ body: edit
959
+ ? async () => {
960
+ const driver = await connect();
961
+ try {
962
+ const model = resolveModel(valid);
963
+ const edited = resolveDeferred(edit.to);
964
+ const uri = siblingOf(model.uri, `conformance-reverted-${globalThis.crypto.randomUUID()}-`);
965
+ const writer = await startSession(driver, 'conformance-writer');
966
+ // Created with the edit, so that going back to the created
967
+ // text instead of the saved one shows.
968
+ await driver.proxy.createModelDocument({ uri, clientId: writer, text: edited });
969
+ const saved = await driver.proxy.saveModelDocument({ uri, clientId: writer, model: model.text, baseVersion: 'any' });
970
+ assert.ok(
971
+ !edit.expect(saved.model?.root),
972
+ 'edit.expect holds of the valid text, so this check cannot tell the edit apart'
973
+ );
974
+ const reader = await openAs(driver, uri, 'conformance-reader');
975
+ await driver.proxy.updateModelDocument({ uri, clientId: writer, model: edited, baseVersion: 'any' });
976
+
977
+ // Not the last close: the reader still shows the writer's
978
+ // text. Read at once, so a head that reverts after answering
979
+ // could still pass this half.
980
+ await driver.proxy.closeSession({ clientId: writer });
981
+ const held = await driver.proxy.getModelDocument({ uri });
982
+ assert.ok(edit.expect(held.model?.root), `closing one of two sessions dropped the unsaved text of ${uri}`);
983
+
984
+ await driver.proxy.closeSession({ clientId: reader });
985
+ await readUntil(
986
+ driver,
987
+ uri,
988
+ document => document?.model !== undefined && !edit.expect(document.model.root),
989
+ `${uri} did not go back to the text its save wrote after its last close`
990
+ );
991
+ } finally {
992
+ driver.dispose();
993
+ }
994
+ }
995
+ : undefined
996
+ });
997
+
998
+ // Opt-in twice over: the cascade needs an edit to provoke it AND a second
999
+ // document that references the first to be provoked.
1000
+ const cascadeSkipReason =
1001
+ 'fixture supplies no `dependent` (a document referencing `valid`), so no cascade can be provoked over the protocol';
1002
+
1003
+ checks.push({
1004
+ title: `updateModelDocuments writes a set all or none ${tag}`,
1005
+ skipReason:
1006
+ edit && dependent
1007
+ ? undefined
1008
+ : dependent
1009
+ ? editSkipReason
1010
+ : 'fixture supplies no `dependent`, the second document a set needs besides `valid`',
1011
+ body:
1012
+ edit && dependent
1013
+ ? async () => {
1014
+ const driver = await connect();
1015
+ try {
1016
+ const model = resolveModel(valid);
1017
+ const other = resolveModel(dependent);
1018
+ await seed(driver, model);
1019
+ await seed(driver, other);
1020
+ const clientId = await startSession(driver, 'conformance-session');
1021
+ const { model: first } = TransferDocument.assertLoaded(
1022
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId })
1023
+ );
1024
+ const { model: second } = TransferDocument.assertLoaded(
1025
+ await driver.proxy.openModelDocument({ uri: other.uri, clientId })
1026
+ );
1027
+ const edited = resolveDeferred(edit.to);
1028
+
1029
+ // The stale member comes LAST, so a head that checks and
1030
+ // applies one document at a time has applied the first.
1031
+ const stale = await rejectionOf(
1032
+ driver.proxy.updateModelDocuments({
1033
+ clientId,
1034
+ updates: [
1035
+ { uri: model.uri, model: edited, baseVersion: first.version },
1036
+ { uri: other.uri, model: other.text, baseVersion: asModelVersion(second.version + 1) }
1037
+ ]
1038
+ })
1039
+ );
1040
+ assert.ok(isConflictError(stale), `a set with a stale member was not refused: ${String(stale)}`);
1041
+ const untouched = await driver.proxy.getModelDocument({ uri: model.uri });
1042
+ assert.strictEqual(untouched.model?.version, first.version, 'a refused set applied its first document');
1043
+
1044
+ await driver.proxy.updateModelDocuments({
1045
+ clientId,
1046
+ updates: [
1047
+ { uri: model.uri, model: edited, baseVersion: first.version },
1048
+ { uri: other.uri, model: other.text, baseVersion: second.version }
1049
+ ]
1050
+ });
1051
+ const applied = await driver.proxy.getModelDocument({ uri: model.uri });
1052
+ assert.ok(edit.expect(applied.model?.root), 'edit.expect(root) was false — a current set was not applied');
1053
+ await driver.proxy.closeSession({ clientId });
1054
+ } finally {
1055
+ driver.dispose();
1056
+ }
1057
+ }
1058
+ : undefined
1059
+ });
1060
+
1061
+ checks.push({
1062
+ title: `editing a document reports its unwatched dependent as built ${tag}`,
1063
+ skipReason: edit && dependent ? undefined : dependent ? editSkipReason : cascadeSkipReason,
1064
+ body:
1065
+ edit && dependent
1066
+ ? async () => {
1067
+ const driver = await connect();
1068
+ try {
1069
+ const model = resolveModel(valid);
1070
+ const other = resolveModel(dependent);
1071
+ await seed(driver, model);
1072
+ await seed(driver, other);
1073
+ // Watch ONLY the referenced document. The dependent is left
1074
+ // unwatched on purpose: that is the state in which no other
1075
+ // channel can report it, and the state a workspace view is in
1076
+ // for every document it displays without opening.
1077
+ await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
1078
+ const author = await openAs(driver, model.uri);
1079
+ const before = driver.builds.length;
1080
+
1081
+ await driver.proxy.updateModelDocument({
1082
+ uri: model.uri,
1083
+ clientId: author,
1084
+ model: resolveDeferred(edit.to),
1085
+ baseVersion: 'any'
1086
+ });
1087
+
1088
+ await waitFor(() => driver.builds.slice(before).some(event => event.uris.includes(other.uri)), {
1089
+ message: `no onDocumentsBuilt event named ${other.uri} after editing the document it references`
1090
+ });
1091
+ const reported = driver.builds.slice(before).flatMap(event => [...event.uris]);
1092
+ // The watched document is excluded: its watcher already heard
1093
+ // about it on the update channel, and repeating it here would
1094
+ // be the bandwidth the per-URI gate exists to avoid.
1095
+ assert.ok(
1096
+ !reported.includes(model.uri),
1097
+ `onDocumentsBuilt named the WATCHED ${model.uri}; it is reported on the update channel instead`
1098
+ );
1099
+ } finally {
1100
+ driver.dispose();
1101
+ }
1102
+ }
1103
+ : undefined
1104
+ });
1105
+
1106
+ const breakingEdit = language.breakingEdit;
1107
+ checks.push({
1108
+ title: `an edit that changes a watched dependent credits the dependent's event to no client ${tag}`,
1109
+ skipReason: !dependent
1110
+ ? cascadeSkipReason
1111
+ : breakingEdit === undefined
1112
+ ? 'fixture supplies no `breakingEdit` (a text for `valid` that changes what `dependent` shows)'
1113
+ : undefined,
1114
+ body:
1115
+ dependent && breakingEdit !== undefined
1116
+ ? async () => {
1117
+ const driver = await connect();
1118
+ try {
1119
+ const model = resolveModel(valid);
1120
+ const other = resolveModel(dependent);
1121
+ const eventsFor = (uri: string, from = 0): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[] =>
1122
+ driver.events.slice(from).filter(event => event.document.uri === uri);
1123
+ await seed(driver, model);
1124
+ // The dependent's seeder keeps it open: an open document is
1125
+ // the one a head could wrongly credit to its opener.
1126
+ await seed(driver, other);
1127
+ // Watched after the seeds: a seed that changes nothing, over
1128
+ // a fixture file that holds its text already, sends a watcher
1129
+ // nothing to wait for.
1130
+ await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
1131
+ await driver.proxy.watchModelDocument({ uri: other.uri, clientId: SUBSCRIBER });
1132
+ const author = await openAs(driver, model.uri);
1133
+ const before = driver.events.length;
1134
+
1135
+ const answer = await driver.proxy.updateModelDocument({
1136
+ uri: model.uri,
1137
+ clientId: author,
1138
+ model: resolveDeferred(breakingEdit),
1139
+ baseVersion: 'any'
1140
+ });
1141
+
1142
+ const written = (): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> | undefined =>
1143
+ eventsFor(model.uri, before).find(event => event.document.model?.version === answer.model?.version);
1144
+ await waitFor(() => written() !== undefined && eventsFor(other.uri, before).length > 0, {
1145
+ message: `no onDocumentUpdated event for both ${model.uri} and its dependent ${other.uri} after the breaking edit`
1146
+ });
1147
+ assert.deepStrictEqual(
1148
+ { reason: written()?.reason, sourceClientId: written()?.sourceClientId },
1149
+ { reason: 'changed', sourceClientId: author },
1150
+ 'the written document’s event is not the author’s change'
1151
+ );
1152
+ // A recipient drops an event naming its own id as its echo, so
1153
+ // a dependent's event credited to the author, or to the client
1154
+ // that has the dependent open, is lost to exactly the client
1155
+ // that would show it.
1156
+ for (const event of eventsFor(other.uri, before)) {
1157
+ assert.deepStrictEqual(
1158
+ { reason: event.reason, sourceClientId: event.sourceClientId },
1159
+ { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID },
1160
+ 'the dependent’s event is not a rebuild that names no client'
1161
+ );
1162
+ }
1163
+ } finally {
1164
+ driver.dispose();
1165
+ }
1166
+ }
1167
+ : undefined
1168
+ });
1169
+
263
1170
  checks.push({
264
1171
  title: `subscribe + update delivers an onDocumentUpdated event with the originating clientId ${tag}`,
265
1172
  skipReason: edit ? undefined : editSkipReason,
@@ -268,21 +1175,36 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
268
1175
  const driver = await connect();
269
1176
  try {
270
1177
  const model = resolveModel(valid);
271
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: SEEDER, model: model.text });
1178
+ // The seeder's write comes BEFORE any subscription, under an id
1179
+ // distinct from the author's so an event it caused is
1180
+ // recognisable: a head that fans notifications out regardless
1181
+ // of its subscription table is otherwise indistinguishable from
1182
+ // one that honours the table, since both deliver something for
1183
+ // the post-subscribe write.
1184
+ const seeder = await seed(driver, model);
1185
+ const author = await openAs(driver, model.uri);
272
1186
  await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
273
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: resolveDeferred(edit.to) });
274
- await waitFor(() => driver.events.some(event => event.sourceClientId === AUTHOR), {
1187
+ await driver.proxy.updateModelDocument({
1188
+ uri: model.uri,
1189
+ clientId: author,
1190
+ model: resolveDeferred(edit.to),
1191
+ baseVersion: 'any'
1192
+ });
1193
+ await waitFor(() => driver.events.some(event => event.sourceClientId === author), {
275
1194
  message: `no onDocumentUpdated event for ${model.uri} after the post-subscription update`
276
1195
  });
277
1196
  const last = driver.events[driver.events.length - 1];
278
1197
  assert.strictEqual(last.document.uri, model.uri);
279
- assert.strictEqual(last.sourceClientId, AUTHOR);
1198
+ assert.strictEqual(last.sourceClientId, author);
1199
+ // The first delivery of the author's version is a change;
1200
+ // reported as rebuilt, it says the event echoes no write.
1201
+ assert.strictEqual(last.reason, 'changed');
280
1202
  // Nothing from before the subscription. Waiting for the
281
1203
  // post-subscribe event first is what makes this provable: the
282
1204
  // two notifications share one ordered connection, so a seeding
283
1205
  // event that was ever going to arrive has arrived by now.
284
1206
  assert.ok(
285
- !driver.events.some(event => event.sourceClientId === SEEDER),
1207
+ !driver.events.some(event => event.sourceClientId === seeder),
286
1208
  'an onDocumentUpdated event arrived for the update made BEFORE watchModelDocument'
287
1209
  );
288
1210
  } finally {