@reticlehq/engine 3.8.2 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/disagreement/body-failures.js +16 -2
  2. package/dist/disagreement/contradiction-evidence.d.ts +119 -0
  3. package/dist/disagreement/contradiction-evidence.js +360 -48
  4. package/dist/disagreement/contradiction-types.d.ts +25 -0
  5. package/dist/disagreement/contradictions.d.ts +17 -1
  6. package/dist/disagreement/contradictions.js +146 -78
  7. package/dist/disagreement/echo-mismatch.js +205 -32
  8. package/dist/disagreement/stale-response.d.ts +10 -1
  9. package/dist/disagreement/stale-response.js +122 -47
  10. package/dist/evidence/already-true.d.ts +1 -1
  11. package/dist/evidence/already-true.js +13 -7
  12. package/dist/evidence/baseline.d.ts +1 -0
  13. package/dist/evidence/baseline.js +28 -12
  14. package/dist/evidence/blind-spots.d.ts +20 -3
  15. package/dist/evidence/blind-spots.js +127 -21
  16. package/dist/evidence/step-effect.d.ts +5 -0
  17. package/dist/evidence/step-effect.js +5 -2
  18. package/dist/evidence/verified.d.ts +23 -0
  19. package/dist/evidence/verified.js +53 -2
  20. package/dist/question/declared.d.ts +27 -0
  21. package/dist/question/declared.js +64 -13
  22. package/dist/question/predicate/net-blind-spots.d.ts +40 -1
  23. package/dist/question/predicate/net-blind-spots.js +110 -1
  24. package/dist/question/predicate/predicate-animation.d.ts +52 -0
  25. package/dist/question/predicate/predicate-animation.js +258 -0
  26. package/dist/question/predicate/predicate-compare.js +53 -26
  27. package/dist/question/predicate/predicate-element.d.ts +20 -2
  28. package/dist/question/predicate/predicate-element.js +207 -45
  29. package/dist/question/predicate/predicate-eval-kit.d.ts +2 -0
  30. package/dist/question/predicate/predicate-eval-kit.js +19 -0
  31. package/dist/question/predicate/predicate-eval.d.ts +1 -4
  32. package/dist/question/predicate/predicate-eval.js +41 -47
  33. package/dist/question/predicate/predicate-parse.js +132 -4
  34. package/dist/question/predicate/predicate-route.js +81 -27
  35. package/dist/question/predicate/predicate-schema.js +84 -34
  36. package/dist/question/predicate/predicate-session.d.ts +5 -0
  37. package/dist/question/predicate/predicate.js +119 -50
  38. package/dist/question/predicate/truncated-body-advice.d.ts +5 -0
  39. package/dist/question/predicate/truncated-body-advice.js +25 -0
  40. package/dist/state-bookkeeping.d.ts +24 -0
  41. package/dist/state-bookkeeping.js +31 -0
  42. package/dist/window/event-filters.d.ts +64 -0
  43. package/dist/window/event-filters.js +149 -20
  44. package/dist/window/network-detail-merge.d.ts +6 -0
  45. package/dist/window/network-detail-merge.js +43 -2
  46. package/package.json +3 -3
@@ -57,8 +57,9 @@ function isRecord(value) {
57
57
  * silently excluded every desktop write from this check — the exact platform the finding came from.
58
58
  */
59
59
  function parse(raw) {
60
- if (typeof raw !== 'string' || 0 === raw.length)
60
+ if (typeof raw !== 'string' || 0 === raw.length) {
61
61
  return undefined;
62
+ }
62
63
  try {
63
64
  return JSON.parse(raw);
64
65
  }
@@ -80,19 +81,48 @@ function normalizeString(value) {
80
81
  const trimmed = value.trim();
81
82
  if (ISO_INSTANT.test(trimmed)) {
82
83
  const instant = Date.parse(trimmed);
83
- if (Number.isFinite(instant))
84
+ if (Number.isFinite(instant)) {
84
85
  return new Date(instant).toISOString().toLowerCase();
86
+ }
87
+ }
88
+ if (PLAIN_DECIMAL.test(trimmed)) {
89
+ return canonicalDecimal(trimmed);
90
+ }
91
+ if (PHONE_LIKE.test(trimmed) && MIN_PHONE_DIGITS <= trimmed.replace(/\D/g, '').length) {
92
+ return trimmed.replace(PHONE_SEPARATORS, '');
85
93
  }
86
94
  return trimmed.toLowerCase();
87
95
  }
96
+ /** A decimal written in plain digits: `18.5`, `-0.50`, `2`. No exponent and no thousands separator. */
97
+ const PLAIN_DECIMAL = /^-?\d+(?:\.\d+)?$/;
98
+ /**
99
+ * The same decimal in one spelling: trailing zeros of the fraction go, so a fixed-point column that
100
+ * echoes `18.500` for `18.5` is the same value (#1646). Done on the text, never through `Number`,
101
+ * so two long ids that differ past the 15th digit stay different. Leading zeros stay: a ZIP code
102
+ * `02134` stored as `2134` lost data.
103
+ */
104
+ function canonicalDecimal(text) {
105
+ if (!text.includes('.')) {
106
+ return text;
107
+ }
108
+ return text.replace(/0+$/, '').replace(/\.$/, '');
109
+ }
110
+ /** Digits with the separators a phone number is written with, and an optional leading `+`. */
111
+ const PHONE_LIKE = /^\+?[\d\s().-]+$/;
112
+ const PHONE_SEPARATORS = /[\s().-]/g;
113
+ /** Fewer digits than this is a short code (`12-34`), where a separator can carry meaning. */
114
+ const MIN_PHONE_DIGITS = 7;
88
115
  /** Comparable form of a scalar. Non-scalars return undefined and are never compared. */
89
116
  function normalize(value) {
90
- if ('string' === typeof value)
117
+ if ('string' === typeof value) {
91
118
  return normalizeString(value);
92
- if ('number' === typeof value)
93
- return Number.isFinite(value) ? String(value) : undefined;
94
- if ('boolean' === typeof value)
119
+ }
120
+ if ('number' === typeof value) {
121
+ return Number.isFinite(value) ? canonicalDecimal(String(value)) : undefined;
122
+ }
123
+ if ('boolean' === typeof value) {
95
124
  return String(value);
125
+ }
96
126
  return undefined;
97
127
  }
98
128
  /**
@@ -124,7 +154,31 @@ function isVersionKey(key) {
124
154
  '_version' === lower ||
125
155
  'etag' === lower ||
126
156
  'rev' === lower ||
127
- 'revision' === lower);
157
+ 'revision' === lower ||
158
+ 'concurrencystamp' === lower);
159
+ }
160
+ const WHOLE_NUMBER = /^\d+$/;
161
+ const VERSION_WORD = 'version';
162
+ /** The Mongoose document version key. */
163
+ const MONGOOSE_VERSION_KEY = '__v';
164
+ /**
165
+ * A lock counter under another name: a key whose last word is `version` (`lock_version`,
166
+ * `lockVersion`, `rowVersion`) or `__v`. The name alone does not make it a token, because
167
+ * `targetVersion: "1.4"` is a field the caller sets. So it is a token only when the request and the
168
+ * echo are whole numbers and the echo is larger.
169
+ */
170
+ function isBumpedLockCounter(key, wanted, echoed) {
171
+ if (MONGOOSE_VERSION_KEY !== key && keyWords(key).at(-1) !== VERSION_WORD) {
172
+ return false;
173
+ }
174
+ const [want] = [...wanted];
175
+ if (want === undefined || echoed === undefined || 0 === echoed.size) {
176
+ return false;
177
+ }
178
+ if (!WHOLE_NUMBER.test(want)) {
179
+ return false;
180
+ }
181
+ return [...echoed].every((got) => WHOLE_NUMBER.test(got) && Number(got) > Number(want));
128
182
  }
129
183
  /**
130
184
  * Audit columns the server stamps with its own clock on every write. A client that sends one back
@@ -142,6 +196,78 @@ const AUDIT_TIMESTAMP_KEYS = new Set([
142
196
  function isAuditTimestampKey(key) {
143
197
  return AUDIT_TIMESTAMP_KEYS.has(key.toLowerCase());
144
198
  }
199
+ /**
200
+ * A word of a key that names a value computed FROM the record: a content hash, a digest, a checksum
201
+ * (#1522). A new record has a new one, so a different value is not a dropped write, the same way a
202
+ * create's assigned `id` is not. Matched on whole words of the key (`contentHash`, `content_sha256`),
203
+ * never as a substring, so `shape`, `shared` and `hashtag` are still compared.
204
+ */
205
+ const CONTENT_DIGEST_WORD = /^(?:hash|sha\d*|md5|checksum|digest|crc\d*)$/;
206
+ /** The lowercase words of a key: split at `_`, `-`, `.` and at a lower-to-upper camelCase step. */
207
+ function keyWords(key) {
208
+ return key
209
+ .replace(/([a-z\d])([A-Z])/g, '$1_$2')
210
+ .toLowerCase()
211
+ .split(/[^a-z\d]+/)
212
+ .filter((word) => 0 < word.length);
213
+ }
214
+ function isContentDigestKey(key) {
215
+ return keyWords(key).some((word) => CONTENT_DIGEST_WORD.test(word));
216
+ }
217
+ /** An optional algorithm label, as in `sha256:ab12...`. */
218
+ const DIGEST_ALGORITHM_PREFIX = /^[a-z]+\d*:/i;
219
+ /** Hex digits, at least one a letter: a run of only digits is a number, not a digest. */
220
+ const HEX_DIGEST = /^(?=[0-9a-f]*[a-f])[0-9a-f]{8,}$/i;
221
+ /** Base64 or base64url. Long, and with a digit, because `everyday` is valid base64 too. */
222
+ const BASE64_DIGEST = /^(?=[a-z+/_-]*\d)[a-z\d+/_-]{16,}={0,2}$/i;
223
+ /**
224
+ * Does a value look computed from content? The key name alone does not say: `digest` and `hash` are
225
+ * also settings words (`weeklyDigest: true`, `email_digest: 'daily'`, `hashRouting: false`), and
226
+ * those are fields a server can ignore.
227
+ */
228
+ function looksLikeDigest(value) {
229
+ const body = value.replace(DIGEST_ALGORITHM_PREFIX, '');
230
+ return HEX_DIGEST.test(body) || BASE64_DIGEST.test(body);
231
+ }
232
+ /** A content hash: the key names one AND the requested value is one. */
233
+ function isContentDigest(key, wanted) {
234
+ const [want] = [...wanted];
235
+ return want !== undefined && isContentDigestKey(key) && looksLikeDigest(want);
236
+ }
237
+ /**
238
+ * How many compared keys must ALL disagree before the response can be read as a different record.
239
+ *
240
+ * One disagreeing key alone stays a finding, because that is the archetype this kind exists for
241
+ * (`{qty: 5}` answered with `{qty: 3}`). See `isNewRecord` for the rest of the rule.
242
+ */
243
+ const NEW_RECORD_MIN_KEYS = 2;
244
+ /** Methods that change THE record named in the URL. Their answer is never a different record. */
245
+ const UPDATE_METHODS = new Set(['PUT', 'PATCH']);
246
+ /**
247
+ * Is this response a DIFFERENT record of the same type, rather than an ignored write (#1522)?
248
+ *
249
+ * "Every compared key differs" alone is also the worst case of this finding: a server that ignored
250
+ * the whole write (`PATCH {name, email}` answered with the old name and the old email). So the
251
+ * response has to be clearly a new record. It is never one for an update (PUT, PATCH) or an
252
+ * addressed write, and it is one only when it carries an identity, an id or a content hash, that
253
+ * differs from the one the request sent: a derive endpoint answers with a new artifact's own hash.
254
+ */
255
+ function isNewRecord(method, addressed, asked, echoed) {
256
+ if (addressed || UPDATE_METHODS.has(method.toUpperCase())) {
257
+ return false;
258
+ }
259
+ for (const [key, wanted] of asked) {
260
+ if (1 !== wanted.size || !(isIdentityKey(key) || isContentDigest(key, wanted))) {
261
+ continue;
262
+ }
263
+ const values = echoed.get(key);
264
+ const [want] = [...wanted];
265
+ if (values !== undefined && want !== undefined && !values.has(want)) {
266
+ return true;
267
+ }
268
+ }
269
+ return false;
270
+ }
145
271
  /**
146
272
  * Every scalar value the response carries for each key, at any depth.
147
273
  *
@@ -150,18 +276,22 @@ function isAuditTimestampKey(key) {
150
276
  * Collecting ALL values for a key is what makes the "echoes both old and new" case safe.
151
277
  */
152
278
  function scalarsByKey(body, into = new Map(), depth = 0, omitSentinels = false) {
153
- if (depth > 6 || into.size > MAX_ECHO_KEYS)
279
+ if (depth > 6 || into.size > MAX_ECHO_KEYS) {
154
280
  return into;
281
+ }
155
282
  if (Array.isArray(body)) {
156
- for (const item of body)
283
+ for (const item of body) {
157
284
  scalarsByKey(item, into, depth + 1, omitSentinels);
285
+ }
158
286
  return into;
159
287
  }
160
- if (!isRecord(body))
288
+ if (!isRecord(body)) {
161
289
  return into;
290
+ }
162
291
  for (const [key, value] of Object.entries(body)) {
163
- if (omitSentinels && isSentinelValue(value))
292
+ if (omitSentinels && isSentinelValue(value)) {
164
293
  continue;
294
+ }
165
295
  const scalar = normalize(value);
166
296
  if (scalar === undefined) {
167
297
  scalarsByKey(value, into, depth + 1, omitSentinels);
@@ -173,6 +303,13 @@ function scalarsByKey(body, into = new Map(), depth = 0, omitSentinels = false)
173
303
  }
174
304
  return into;
175
305
  }
306
+ /** A boolean as the bit MySQL and SQLite store it as, and many APIs echo. */
307
+ const BOOLEAN_AS_BIT = { true: '1', false: '0' };
308
+ /** Did the response echo `want`? A boolean echoed as its stored bit (`false` → `0`) is the same value. */
309
+ function echoedAs(want, values) {
310
+ const bit = BOOLEAN_AS_BIT[want];
311
+ return values.has(want) || (bit !== undefined && values.has(bit));
312
+ }
176
313
  const OK_MIN = 200;
177
314
  const OK_MAX = 300;
178
315
  /**
@@ -223,10 +360,12 @@ function isAddressedWrite(asked) {
223
360
  let container = false;
224
361
  for (const key of asked.keys()) {
225
362
  const lower = key.toLowerCase();
226
- if (ADDRESSING_KEYS.has(lower))
363
+ if (ADDRESSING_KEYS.has(lower)) {
227
364
  addressed = true;
228
- if (CONTAINER_KEYS.has(lower))
365
+ }
366
+ if (CONTAINER_KEYS.has(lower)) {
229
367
  container = true;
368
+ }
230
369
  }
231
370
  return addressed && container;
232
371
  }
@@ -244,26 +383,32 @@ const MIN_SHARED_KEYS = 2;
244
383
  function responseRestatesRequest(asked, echoed) {
245
384
  const comparable = [];
246
385
  for (const [key, wanted] of asked) {
247
- if (1 === wanted.size)
386
+ if (1 === wanted.size) {
248
387
  comparable.push(key);
388
+ }
249
389
  }
250
- if (0 === comparable.length)
390
+ if (0 === comparable.length) {
251
391
  return false;
392
+ }
252
393
  let present = 0;
253
394
  for (const key of comparable) {
254
- if (echoed.has(key))
395
+ if (echoed.has(key)) {
255
396
  present += 1;
397
+ }
256
398
  }
257
399
  let requestHasDiscriminator = false;
258
400
  let responseHasDiscriminator = false;
259
401
  for (const key of Object.values(EchoDiscriminator)) {
260
- if (asked.has(key))
402
+ if (asked.has(key)) {
261
403
  requestHasDiscriminator = true;
262
- if (echoed.has(key))
404
+ }
405
+ if (echoed.has(key)) {
263
406
  responseHasDiscriminator = true;
407
+ }
264
408
  }
265
- if (requestHasDiscriminator && !responseHasDiscriminator)
409
+ if (requestHasDiscriminator && !responseHasDiscriminator) {
266
410
  return false;
411
+ }
267
412
  if (echoed.size > comparable.length * SNAPSHOT_KEY_RATIO && present < MIN_SHARED_KEYS) {
268
413
  return false;
269
414
  }
@@ -279,8 +424,9 @@ function responseRestatesRequest(asked, echoed) {
279
424
  export function findEchoMismatches(events, actionSince) {
280
425
  const found = [];
281
426
  for (const event of events) {
282
- if (event.type !== EventType.NET_REQUEST)
427
+ if (event.type !== EventType.NET_REQUEST) {
283
428
  continue;
429
+ }
284
430
  // `MUTATING_METHODS` is the one definition of "is this a write" in the codebase — the same list
285
431
  // `contradictions.ts`'s `isMutating` reads. A read has no fields to half-apply.
286
432
  //
@@ -294,51 +440,78 @@ export function findEchoMismatches(events, actionSince) {
294
440
  // real dropped write. A false negative here is a missed bug in someone's app, and that is not a
295
441
  // trade this file makes to quieten a false positive.
296
442
  const method = 'string' === typeof event.data['method'] ? event.data['method'] : '';
297
- if (!MUTATING_METHODS.includes(method.toUpperCase()))
443
+ if (!MUTATING_METHODS.includes(method.toUpperCase())) {
298
444
  continue;
445
+ }
299
446
  // IPC reports `ok` rather than a status; HTTP reports a status. Either must say success — a write
300
447
  // that already failed is a different (and louder) finding than one that half-applied.
301
448
  const status = event.data['status'];
302
449
  const httpOk = 'number' === typeof status && status >= OK_MIN && status < OK_MAX;
303
- if (!httpOk && event.data['ok'] !== true)
450
+ if (!httpOk && event.data['ok'] !== true) {
304
451
  continue;
452
+ }
305
453
  const request = parse(event.data['requestBody']);
306
454
  const response = parse(event.data['responseBody']);
307
- if (request === undefined || response === undefined)
455
+ if (request === undefined || response === undefined) {
308
456
  continue;
457
+ }
309
458
  const echoed = scalarsByKey(response);
310
459
  const asked = scalarsByKey(request, new Map(), 0, true);
311
- if (!responseRestatesRequest(asked, echoed))
460
+ if (!responseRestatesRequest(asked, echoed)) {
312
461
  continue;
462
+ }
313
463
  // See ADDRESSING_KEYS: on an addressed write the container key names nothing on its own, so
314
464
  // comparing it by name across the two documents compares two different fields.
315
465
  const addressed = isAddressedWrite(asked);
316
466
  const dropped = [];
467
+ let compared = 0;
317
468
  for (const [key, wanted] of asked) {
318
- if (addressed && CONTAINER_KEYS.has(key.toLowerCase()))
469
+ if (addressed && CONTAINER_KEYS.has(key.toLowerCase())) {
319
470
  continue;
471
+ }
320
472
  // More than one requested value for a key (a before/after pair, a list of items) makes "what
321
473
  // was asked for" ambiguous, and a guess here is exactly how this kind would earn a reputation
322
474
  // for crying wolf.
323
- if (wanted.size !== 1)
475
+ if (wanted.size !== 1) {
476
+ continue;
477
+ }
478
+ if (isIdentityKey(key)) {
324
479
  continue;
325
- if (isIdentityKey(key))
480
+ }
481
+ if (isVersionKey(key)) {
326
482
  continue;
327
- if (isVersionKey(key))
483
+ }
484
+ if (isAuditTimestampKey(key)) {
328
485
  continue;
329
- if (isAuditTimestampKey(key))
486
+ }
487
+ if (isContentDigest(key, wanted)) {
330
488
  continue;
489
+ }
331
490
  const values = echoed.get(key);
491
+ if (isBumpedLockCounter(key, wanted, values)) {
492
+ continue;
493
+ }
332
494
  // Not echoed at all = no evidence either way. Only a key the server chose to report back can
333
495
  // contradict the request, and silence is not a contradiction.
334
- if (values === undefined || 0 === values.size)
496
+ if (values === undefined || 0 === values.size) {
335
497
  continue;
498
+ }
499
+ compared += 1;
336
500
  const [want] = [...wanted];
337
- if (want !== undefined && !values.has(want))
501
+ if (want !== undefined && !echoedAs(want, values)) {
338
502
  dropped.push(`${key}: asked ${want}, got ${[...values].join('/')}`);
503
+ }
504
+ }
505
+ if (0 === dropped.length) {
506
+ continue;
339
507
  }
340
- if (0 === dropped.length)
508
+ // Nothing the response shares with the request came back as sent, AND it names a different
509
+ // identity: a different record, not a half-applied write. See isNewRecord.
510
+ if (compared >= NEW_RECORD_MIN_KEYS &&
511
+ dropped.length === compared &&
512
+ isNewRecord(method, addressed, asked, echoed)) {
341
513
  continue;
514
+ }
342
515
  const url = 'string' === typeof event.data['url'] ? event.data['url'] : '';
343
516
  const attribution = actionSince !== undefined && event.t < actionSince
344
517
  ? ' — this request completed before the action being verified, so the finding is not about that change'
@@ -1,3 +1,12 @@
1
1
  import { type ReticleEvent } from '@reticlehq/core';
2
2
  import type { OwnContradiction } from './contradiction-types.js';
3
- export declare function findStaleResponses(events: readonly ReticleEvent[]): OwnContradiction[];
3
+ /**
4
+ * `oneIntent`: the window was opened by one discrete action (a click, a select) and holds only what
5
+ * followed it. A superseding race needs a second intent issued while the first read is in flight, so
6
+ * such a window has none: two reads of one path are panels the action loaded, not a filter that
7
+ * changed. Known blind spot: one click whose effect fetches with a stale dependency and then the fresh
8
+ * one is also one intent, and is not reported.
9
+ */
10
+ export declare function findStaleResponses(events: readonly ReticleEvent[], options?: {
11
+ oneIntent?: boolean;
12
+ }): OwnContradiction[];
@@ -55,8 +55,9 @@ function enumerates(key, one, other) {
55
55
  if (POSITION_PARAMS.has(name)) {
56
56
  return WHOLE_NUMBER.test(one ?? '') && WHOLE_NUMBER.test(other ?? '');
57
57
  }
58
- if (CURSOR_PARAMS.has(name))
58
+ if (CURSOR_PARAMS.has(name)) {
59
59
  return !DATE.test(one ?? '') && !DATE.test(other ?? '');
60
+ }
60
61
  return false;
61
62
  }
62
63
  /** Whether the two queries differ ONLY in how much of the same collection they ask for. */
@@ -66,10 +67,12 @@ function differsOnlyByEnumeration(first, second) {
66
67
  const keys = new Set([...a.keys(), ...b.keys()]);
67
68
  let differed = false;
68
69
  for (const key of keys) {
69
- if (a.get(key) === b.get(key))
70
+ if (a.get(key) === b.get(key)) {
70
71
  continue;
71
- if (!enumerates(key, a.get(key), b.get(key)))
72
+ }
73
+ if (!enumerates(key, a.get(key), b.get(key))) {
72
74
  return false;
75
+ }
73
76
  differed = true;
74
77
  }
75
78
  return differed;
@@ -81,6 +84,13 @@ function differsOnlyByEnumeration(first, second) {
81
84
  const IDENTITY_PARAMS = new Set(['id', 'ids', 'uuid', 'slug', 'key']);
82
85
  /** Different projections ask for differently shaped answers, both of which the app may need. */
83
86
  const PROJECTION_PARAMS = new Set(['select', 'fields', 'columns', 'include', 'expand']);
87
+ /**
88
+ * Parameters that pick the OPERATION on one route (`?action=candles`, `?action=news`). Two reads
89
+ * that differ in one of these call two handlers whose answers feed two parts of the page, so neither
90
+ * can be stale for the other. `type` and `kind` are not here: they are usually filters, and a filter
91
+ * change is the race this rule exists for.
92
+ */
93
+ const OPERATION_PARAMS = new Set(['action', 'op', 'operation', 'endpoint', 'resource', 'method']);
84
94
  /**
85
95
  * Issued this close together, two requests came from one task (a `Promise.all`, two effects in one
86
96
  * commit), so no later intent superseded the first: they are a fan-out, not a race (#1225).
@@ -98,14 +108,24 @@ function couldSupersede(first, second) {
98
108
  const b = new URLSearchParams(second);
99
109
  const keysA = [...new Set(a.keys())].sort().join('&');
100
110
  const keysB = [...new Set(b.keys())].sort().join('&');
101
- if (keysA !== keysB)
111
+ if (keysA !== keysB) {
102
112
  return false;
103
- for (const key of IDENTITY_PARAMS)
104
- if (a.get(key) !== b.get(key))
113
+ }
114
+ for (const key of IDENTITY_PARAMS) {
115
+ if (a.get(key) !== b.get(key)) {
116
+ return false;
117
+ }
118
+ }
119
+ for (const key of PROJECTION_PARAMS) {
120
+ if (a.get(key) !== b.get(key)) {
105
121
  return false;
106
- for (const key of PROJECTION_PARAMS)
107
- if (a.get(key) !== b.get(key))
122
+ }
123
+ }
124
+ for (const key of OPERATION_PARAMS) {
125
+ if (a.get(key) !== b.get(key)) {
108
126
  return false;
127
+ }
128
+ }
109
129
  return !differsOnlyByEnumeration(first, second);
110
130
  }
111
131
  /** Pair NET_PENDING with its NET_REQUEST by the id both carry. Unpaired events are still in flight. */
@@ -114,8 +134,9 @@ function flights(events) {
114
134
  const out = [];
115
135
  for (const event of events) {
116
136
  const id = 'string' === typeof event.data['id'] ? event.data['id'] : undefined;
117
- if (id === undefined)
137
+ if (id === undefined) {
118
138
  continue;
139
+ }
119
140
  const at = 'number' === typeof event.t ? event.t : 0;
120
141
  if (event.type === EventType.NET_PENDING) {
121
142
  const url = 'string' === typeof event.data['url'] ? event.data['url'] : '';
@@ -123,11 +144,13 @@ function flights(events) {
123
144
  issued.set(id, { url, method, at });
124
145
  continue;
125
146
  }
126
- if (event.type !== EventType.NET_REQUEST)
147
+ if (event.type !== EventType.NET_REQUEST) {
127
148
  continue;
149
+ }
128
150
  const start = issued.get(id);
129
- if (start === undefined)
130
- continue; // started before this window — its ordering is unknowable
151
+ if (start === undefined) {
152
+ continue;
153
+ } // started before this window — its ordering is unknowable
131
154
  out.push({
132
155
  id,
133
156
  url: start.url,
@@ -172,6 +195,38 @@ const APPLY_WINDOW_MS = 500;
172
195
  * because synthetic events are written with the reaction placed after the cause.
173
196
  */
174
197
  const APPLY_SLACK_MS = 100;
198
+ /** The store path or DOM text element a comparable reaction changed, when the event names one. */
199
+ function reactionTarget(event) {
200
+ if (event.type === EventType.STATE_CHANGE) {
201
+ const path = event.data['path'];
202
+ if ('string' !== typeof path) {
203
+ return undefined;
204
+ }
205
+ const name = 'string' === typeof event.data['name'] ? event.data['name'] : '';
206
+ return `state:${name}:${path}`;
207
+ }
208
+ return event.type === EventType.DOM_TEXT && event.ref !== undefined
209
+ ? `dom:${event.ref}`
210
+ : undefined;
211
+ }
212
+ /** Whether a reaction belongs to this flight rather than another completion or request start. */
213
+ function belongsTo(event, flight, all) {
214
+ if (event.t < flight.settledAt - APPLY_SLACK_MS || event.t > flight.settledAt + APPLY_WINDOW_MS) {
215
+ return false;
216
+ }
217
+ const reacts = event.type === EventType.STATE_CHANGE ||
218
+ event.type === EventType.SIGNAL ||
219
+ event.type === EventType.DOM_TEXT ||
220
+ event.type === EventType.DOM_ADDED ||
221
+ event.type === EventType.DOM_REMOVED ||
222
+ event.type === EventType.DOM_ATTR;
223
+ // A reaction belongs to the completion nearest it. The slack also admits the newer response's
224
+ // render before the loser and a later request's loading write, so compare request starts too.
225
+ const own = Math.abs(event.t - flight.settledAt);
226
+ return (reacts &&
227
+ !all.some((other) => other.id !== flight.id &&
228
+ (Math.abs(event.t - other.settledAt) < own || Math.abs(event.t - other.issuedAt) < own)));
229
+ }
175
230
  /**
176
231
  * Did the app REACT to this response — did anything user-visible move after it landed?
177
232
  *
@@ -183,37 +238,48 @@ const APPLY_SLACK_MS = 100;
183
238
  * detector that accuses correct code teaches people to ignore it, and it takes the true positives
184
239
  * down with it.
185
240
  */
186
- function appliedAfter(events, loser, all) {
187
- const { settledAt } = loser;
241
+ function appliedAfter(events, loser, winner, all) {
242
+ const winnerReactions = events.filter((event) => belongsTo(event, winner, all));
243
+ const winnerTargets = new Set(winnerReactions.map(reactionTarget).filter((target) => target !== undefined));
244
+ const winnerTargetKinds = new Set([...winnerTargets].map((target) => target.slice(0, target.indexOf(':'))));
245
+ const winnerChangedDomStructure = winnerReactions.some((event) => event.type === EventType.DOM_ADDED || event.type === EventType.DOM_REMOVED);
188
246
  return events.some((event) => {
189
- if (event.t < settledAt - APPLY_SLACK_MS || event.t > settledAt + APPLY_WINDOW_MS)
247
+ if (!belongsTo(event, loser, all)) {
190
248
  return false;
191
- const reacts = event.type === EventType.STATE_CHANGE ||
192
- event.type === EventType.SIGNAL ||
193
- event.type === EventType.DOM_TEXT ||
194
- event.type === EventType.DOM_ADDED ||
195
- event.type === EventType.DOM_REMOVED ||
196
- event.type === EventType.DOM_ATTR;
197
- // A reaction belongs to the completion nearest it. The slack lets a render stamped a moment
198
- // early count, and so it also took in the NEWER response's own render landing just before the
199
- // loser: a correct app that dropped the loser was accused (seen intermittently on a bench twin).
200
- // It also belongs to a request being ISSUED nearer it: an action's own write ("loading", the
201
- // requested value) lands with its request, and a fast burst of clicks puts the next one a few
202
- // ms after a slow loser lands (seen 1 run in 2 on a correctly guarded quote desk).
203
- const own = Math.abs(event.t - settledAt);
204
- return (reacts &&
205
- !all.some((f) => f.id !== loser.id &&
206
- (Math.abs(event.t - f.settledAt) < own || Math.abs(event.t - f.issuedAt) < own)));
249
+ }
250
+ // Different known targets rule out an overwrite only when they are comparable. Signals, older SDK
251
+ // events and targets of another kind keep the timing fallback because the stream cannot compare them.
252
+ const target = reactionTarget(event);
253
+ if (target === undefined) {
254
+ return true;
255
+ }
256
+ // A structural change can contain the loser's text target, so different refs are not comparable.
257
+ if (event.type === EventType.DOM_TEXT && winnerChangedDomStructure) {
258
+ return true;
259
+ }
260
+ const kind = target.slice(0, target.indexOf(':'));
261
+ return !winnerTargetKinds.has(kind) || winnerTargets.has(target);
207
262
  });
208
263
  }
209
- export function findStaleResponses(events) {
264
+ /**
265
+ * `oneIntent`: the window was opened by one discrete action (a click, a select) and holds only what
266
+ * followed it. A superseding race needs a second intent issued while the first read is in flight, so
267
+ * such a window has none: two reads of one path are panels the action loaded, not a filter that
268
+ * changed. Known blind spot: one click whose effect fetches with a stale dependency and then the fresh
269
+ * one is also one intent, and is not reported.
270
+ */
271
+ export function findStaleResponses(events, options = {}) {
272
+ if (true === options.oneIntent) {
273
+ return [];
274
+ }
210
275
  // Grouped by path first: two reads of DIFFERENT endpoints can never race, and comparing them was
211
276
  // the bulk of the work on any real page, which talks to many endpoints at once.
212
277
  const byPath = new Map();
213
278
  const all = flights(events);
214
279
  for (const flight of all) {
215
- if (flight.method !== 'GET')
280
+ if (flight.method !== 'GET') {
216
281
  continue;
282
+ }
217
283
  const path = pathOf(flight.url);
218
284
  const group = byPath.get(path) ?? [];
219
285
  group.push(flight);
@@ -222,32 +288,41 @@ export function findStaleResponses(events) {
222
288
  for (const group of byPath.values()) {
223
289
  const reads = group.slice(-MAX_FLIGHTS_PER_PATH);
224
290
  const found = raceIn(reads, events, all);
225
- if (found !== undefined)
291
+ if (found !== undefined) {
226
292
  return [found];
293
+ }
227
294
  }
228
295
  return [];
229
296
  }
230
297
  function raceIn(reads, events, all) {
231
298
  for (const first of reads) {
232
299
  for (const second of reads) {
233
- if (first.id === second.id)
300
+ if (first.id === second.id) {
301
+ continue;
302
+ }
303
+ if (second.issuedAt <= first.issuedAt) {
304
+ continue;
305
+ } // `first` must be the earlier request
306
+ if (second.issuedAt >= first.settledAt) {
307
+ continue;
308
+ } // sequential, not overlapping
309
+ if (second.settledAt >= first.settledAt) {
310
+ continue;
311
+ } // settled in order — no race
312
+ if (queryOf(first.url) === queryOf(second.url)) {
313
+ continue;
314
+ } // a retry, not a superseding query
315
+ if (second.issuedAt - first.issuedAt < SAME_TASK_MS) {
234
316
  continue;
235
- if (second.issuedAt <= first.issuedAt)
236
- continue; // `first` must be the earlier request
237
- if (second.issuedAt >= first.settledAt)
238
- continue; // sequential, not overlapping
239
- if (second.settledAt >= first.settledAt)
240
- continue; // settled in order — no race
241
- if (queryOf(first.url) === queryOf(second.url))
242
- continue; // a retry, not a superseding query
243
- if (second.issuedAt - first.issuedAt < SAME_TASK_MS)
244
- continue; // one task's fan-out
245
- if (!couldSupersede(queryOf(first.url), queryOf(second.url)))
317
+ } // one task's fan-out
318
+ if (!couldSupersede(queryOf(first.url), queryOf(second.url))) {
246
319
  continue;
320
+ }
247
321
  // The race happened. Whether it MATTERS is whether the app acted on the loser — an app that
248
322
  // drops superseded responses races just as visibly and is not broken.
249
- if (!appliedAfter(events, first, all))
323
+ if (!appliedAfter(events, first, second, all)) {
250
324
  continue;
325
+ }
251
326
  return {
252
327
  kind: ContradictionKind.STALE_RESPONSE_APPLIED,
253
328
  claim: `both reads of ${pathOf(first.url)} returned successfully and the page settled`,
@@ -1,5 +1,5 @@
1
1
  import type { Predicate } from '../question/predicate/predicate.js';
2
- export declare function readsDomState(predicate: Predicate): boolean;
2
+ export declare function readsDomState(predicate: Predicate, since?: number): boolean;
3
3
  /**
4
4
  * #889: an `already_true` verdict says the declared consequence held before the action, so nothing
5
5
  * was proven — but a `text`/`element` predicate matches DOM presence by default, not visibility (a