@reticlehq/engine 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/disagreement/contradiction-evidence.d.ts +70 -3
  2. package/dist/disagreement/contradiction-evidence.js +156 -7
  3. package/dist/disagreement/contradiction-types.d.ts +8 -0
  4. package/dist/disagreement/contradictions.js +21 -16
  5. package/dist/disagreement/stale-response.js +54 -15
  6. package/dist/evidence/baseline.js +1 -1
  7. package/dist/evidence/body-capture-remedy.d.ts +1 -15
  8. package/dist/evidence/body-capture-remedy.js +9 -2
  9. package/dist/evidence/step-effect.d.ts +20 -1
  10. package/dist/evidence/step-effect.js +30 -2
  11. package/dist/evidence/uncaptured-bodies.d.ts +18 -1
  12. package/dist/evidence/uncaptured-bodies.js +22 -1
  13. package/dist/evidence/unread-outcome.d.ts +7 -0
  14. package/dist/evidence/unread-outcome.js +22 -0
  15. package/dist/evidence/unsettled.js +25 -0
  16. package/dist/evidence/verified.d.ts +2 -0
  17. package/dist/evidence/verified.js +1 -1
  18. package/dist/exact-count.d.ts +19 -0
  19. package/dist/exact-count.js +25 -0
  20. package/dist/question/predicate/predicate-compare.js +7 -2
  21. package/dist/question/predicate/predicate-console.js +23 -10
  22. package/dist/question/predicate/predicate-element.d.ts +10 -1
  23. package/dist/question/predicate/predicate-element.js +138 -17
  24. package/dist/question/predicate/predicate-eval-kit.d.ts +3 -3
  25. package/dist/question/predicate/predicate-eval-kit.js +3 -7
  26. package/dist/question/predicate/predicate-eval.d.ts +10 -0
  27. package/dist/question/predicate/predicate-eval.js +169 -68
  28. package/dist/question/predicate/predicate-parse.d.ts +1 -1
  29. package/dist/question/predicate/predicate-parse.js +1 -1
  30. package/dist/question/predicate/predicate-request-body.d.ts +13 -0
  31. package/dist/question/predicate/predicate-request-body.js +23 -1
  32. package/dist/question/predicate/predicate-schema.d.ts +1 -1
  33. package/dist/question/predicate/predicate-schema.js +6 -5
  34. package/dist/question/predicate/predicate.js +54 -8
  35. package/dist/question/predicate/split-text-miss.d.ts +1 -0
  36. package/dist/question/predicate/split-text-miss.js +8 -1
  37. package/dist/state-bookkeeping.d.ts +2 -0
  38. package/dist/state-bookkeeping.js +4 -0
  39. package/dist/window/adversary.js +46 -40
  40. package/dist/window/network-detail-merge.d.ts +3 -4
  41. package/dist/window/network-detail-merge.js +43 -13
  42. package/package.json +3 -3
@@ -1,10 +1,13 @@
1
- import { EventType, NetInitiator, PredicateKind, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
1
+ import { EventType, NetInitiator, PredicateKind, ResponseBodyReason, SettledChannel, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
2
+ import { isReticleVoice } from '../../state-bookkeeping.js';
2
3
  import { describeObserved } from './observed-in-window.js';
3
4
  import { netEvidence } from './net-evidence.js';
4
- import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
+ import { mergeNetworkDetail } from '../../window/network-detail-merge.js';
6
+ import { checkRequestBody, REMEDY_BODY_CAPTURE, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
7
  export { evalConsole } from './predicate-console.js';
6
8
  import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
7
9
  import { keyFragmentOnly } from './body-key-fragment.js';
10
+ import { evalExactCount } from '../../exact-count.js';
8
11
  import { PRE_ATTACH_CAVEAT, nativeDownloadReason, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
9
12
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
10
13
  /** The oracle a net body clause reports, so an agent can branch on which one decided. */
@@ -32,8 +35,9 @@ export * from './predicate-schema.js';
32
35
  * This exists so an agent can assert on the OUTCOME rather than on a number Reticle invented.
33
36
  */
34
37
  function callSucceeded(data) {
35
- if ('boolean' === typeof data['ok'])
38
+ if ('boolean' === typeof data['ok']) {
36
39
  return data['ok'];
40
+ }
37
41
  const status = num(data['status']);
38
42
  return status === undefined || status < 400;
39
43
  }
@@ -61,8 +65,9 @@ const REDACTED_PATH_HINT = 'this path segment was redacted — the literal you m
61
65
  function observedNetCalls(events, urlContains) {
62
66
  const calls = events.filter((e) => e.type === EventType.NET_REQUEST);
63
67
  const base = describeObserved('calls', calls.map(describeCall));
64
- if (urlContains === undefined)
68
+ if (urlContains === undefined) {
65
69
  return base;
70
+ }
66
71
  const encoded = encodeURIComponent(REDACTED_VALUE);
67
72
  const redacted = calls.some((e) => {
68
73
  const url = str(e.data['url']) ?? '';
@@ -75,33 +80,10 @@ function describeSignalFilter(p) {
75
80
  const { kind: _kind, count: _count, since: _since, ...filter } = p;
76
81
  return JSON.stringify(filter);
77
82
  }
78
- /**
79
- * Exact cardinality, once, for every channel that can count its matches.
80
- *
81
- * `net` and `signal` are the same assertion over different evidence — "this happened EXACTLY n
82
- * times" — and the interesting half is the same on both: an over-count is `decided`, because a
83
- * window only accumulates and a count cannot come back down, so waiting out the rest of the budget
84
- * to report a double-fire buys nothing but latency.
85
- *
86
- * `noun` names the population in prose ("network call(s)", "signal(s)"), `filter` is the matcher as
87
- * applied, and `assertion` is the oracle that judged it.
88
- */
89
- function evalExactCount(args) {
90
- const { matched, want, noun, filter, assertion } = args;
91
- if (matched === want)
92
- return { pass: true, evidence: { matched } };
93
- return {
94
- pass: false,
95
- ...(matched > want ? { decided: true } : {}),
96
- failureReason: `expected ${String(want)} ${noun} matching ${filter}, saw ${String(matched)}`,
97
- observed: `${String(matched)} matching ${noun}`,
98
- expected: `exactly ${String(want)} matching ${filter}`,
99
- assertion,
100
- };
101
- }
102
83
  function nativeDownloadMiss(events, p) {
103
- if (!targetsNativeDownload(p.urlContains))
84
+ if (!targetsNativeDownload(p.urlContains)) {
104
85
  return undefined;
86
+ }
105
87
  const reason = nativeDownloadReason(describeNetFilter(p));
106
88
  return {
107
89
  pass: false,
@@ -133,8 +115,9 @@ const DOCUMENT_INITIATORS = new Set([
133
115
  * IPC. The capsule's blast radius uses it to keep a page load out of "what this action also did".
134
116
  */
135
117
  export function isDocumentInitiated(event) {
136
- if (event.type !== EventType.NET_REQUEST)
118
+ if (event.type !== EventType.NET_REQUEST) {
137
119
  return false;
120
+ }
138
121
  const initiator = str(event.data['initiator']);
139
122
  return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
140
123
  }
@@ -162,7 +145,43 @@ function observerSawSubresources(events) {
162
145
  function wantedBody(p) {
163
146
  return JSON.stringify(p.bodyContains ?? p.bodyMatches);
164
147
  }
148
+ /**
149
+ * The remedy for a body the SDK skipped ON PURPOSE with capture on, or `undefined` (#1520).
150
+ *
151
+ * Shared by every message that would otherwise say "enable captureNetworkBodies": that advice is
152
+ * wrong when capture is already on and the body was a stream, a binary type, or a read that did
153
+ * not finish. `undefined` means no reason was stamped: capture was off, or the SDK predates it.
154
+ */
155
+ export function skippedBodyRemedy(reason) {
156
+ if (ResponseBodyReason.STREAMING === reason) {
157
+ return 'The body was streamed in an unsupported format (such as ndjson), and capture is already on. Assert the result in the DOM or in state instead, or use a non-streaming endpoint.';
158
+ }
159
+ if (ResponseBodyReason.NOT_TEXT === reason) {
160
+ return 'The body is not text (binary, or a content type that is not recorded), and capture is already on. Assert the result in the DOM or in state instead.';
161
+ }
162
+ if (ResponseBodyReason.UNREADABLE === reason) {
163
+ return 'The body is not available yet or could not be read, and capture is already on. SSE capture can take up to 10 seconds. Use wait_for with a sufficient timeout to retry the body assertion. If the body remains unavailable, assert the result in the DOM or in state instead.';
164
+ }
165
+ return undefined;
166
+ }
167
+ /** The skip reason every one of these calls carries, when they all carry the same one. */
168
+ export function sharedSkipReason(reasons) {
169
+ const [first] = reasons;
170
+ if (first === undefined) {
171
+ return undefined;
172
+ }
173
+ return reasons.every((r) => r === first) ? first : undefined;
174
+ }
175
+ /** Why a matched call's body could not answer a body clause, and what to do instead (#1520). */
176
+ function unrecordedBodyReason(p, reason) {
177
+ const head = `a call matching ${describeNetFilter(p)} was answered, but its body was not recorded, so ${wantedBody(p)} could not be checked, which is not the same as absent.`;
178
+ return `${head} ${skippedBodyRemedy(reason) ?? REMEDY_BODY_CAPTURE}`;
179
+ }
165
180
  export function evalNet(events, p) {
181
+ // SSE headers close the request immediately. A later detail supplies its captured body without another call.
182
+ if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
183
+ events = mergeNetworkDetail(events);
184
+ }
166
185
  const since = p.since ?? 0;
167
186
  /**
168
187
  * Computed once: the gate every zero-match downgrade below reads. True means the resource-timing
@@ -178,6 +197,8 @@ export function evalNet(events, p) {
178
197
  * because it is the same pass over the same events.
179
198
  */
180
199
  let matchedButUnrecorded = false;
200
+ /** Why the SDK skipped that body, when it said (#1520). Absent: capture off, or an older SDK. */
201
+ let unrecordedReason;
181
202
  /** A call matched url/method but carried NO readable status (document-initiated subresource). */
182
203
  let unobservableStatus = false;
183
204
  /**
@@ -208,8 +229,9 @@ export function evalNet(events, p) {
208
229
  let redactedResponseField;
209
230
  const requestState = newRequestBodyState();
210
231
  const matches = events.filter((e) => {
211
- if (e.type !== EventType.NET_REQUEST || e.t < since)
232
+ if (e.type !== EventType.NET_REQUEST || e.t < since) {
212
233
  return false;
234
+ }
213
235
  const d = e.data;
214
236
  if (p.method !== undefined && str(d['method'])?.toUpperCase() !== p.method.toUpperCase()) {
215
237
  return false;
@@ -227,13 +249,16 @@ export function evalNet(events, p) {
227
249
  unobservableStatus = true;
228
250
  return false;
229
251
  }
230
- if (status !== p.status)
252
+ if (status !== p.status) {
231
253
  return false;
254
+ }
232
255
  }
233
- if (p.ok !== undefined && callSucceeded(d) !== p.ok)
256
+ if (p.ok !== undefined && callSucceeded(d) !== p.ok) {
234
257
  return false;
235
- if (!checkRequestBody(d, p, requestState))
258
+ }
259
+ if (!checkRequestBody(d, p, requestState)) {
236
260
  return false;
261
+ }
237
262
  if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
238
263
  // The RESPONSE body only, and this is the whole point of these fields. Searching the request
239
264
  // too would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app
@@ -242,6 +267,7 @@ export function evalNet(events, p) {
242
267
  const response = str(d['responseBody']);
243
268
  if (response === undefined) {
244
269
  matchedButUnrecorded = true;
270
+ unrecordedReason ??= d['responseBodyReason'];
245
271
  return false;
246
272
  }
247
273
  // A needle missing from a body we only hold the FIRST N BYTES of is undecidable, not absent:
@@ -254,13 +280,15 @@ export function evalNet(events, p) {
254
280
  truncatedBody ??= response;
255
281
  truncatedClause ??= clause;
256
282
  }
257
- else
283
+ else {
258
284
  bodyMismatch ??= response;
285
+ }
259
286
  return false;
260
287
  };
261
288
  if (p.bodyContains !== undefined) {
262
- if (!response.includes(p.bodyContains))
289
+ if (!response.includes(p.bodyContains)) {
263
290
  return missed(NetBodyAssertion.CONTAINS);
291
+ }
264
292
  const fragment = keyFragmentOnly(response, p.bodyContains);
265
293
  if (fragment !== undefined) {
266
294
  keyFragment ??= { key: fragment, body: response };
@@ -269,8 +297,9 @@ export function evalNet(events, p) {
269
297
  }
270
298
  if (p.bodyMatches !== undefined) {
271
299
  const verdict = matchJsonBody(response, p.bodyMatches);
272
- if ('mismatch' === verdict)
300
+ if ('mismatch' === verdict) {
273
301
  return missed(NetBodyAssertion.MATCHES);
302
+ }
274
303
  if ('match' !== verdict) {
275
304
  redactedResponseField ??= verdict.redacted;
276
305
  return false;
@@ -292,9 +321,13 @@ export function evalNet(events, p) {
292
321
  };
293
322
  }
294
323
  if (matchedButUnrecorded && 0 === matches.length) {
324
+ // Inconclusive, never a plain failure: nothing says the body lacked the text, only that nobody
325
+ // read it (#1520). The same family as evicted evidence answering `no` (#1231).
326
+ const reason = unrecordedBodyReason(p, unrecordedReason);
295
327
  return {
296
328
  pass: false,
297
- failureReason: `a call matched but its body was not recorded, so \`bodyContains\` could not be checked — enable it where the app calls connect(): reticle({ captureNetworkBodies: true })`,
329
+ failureReason: reason,
330
+ inconclusive: reason,
298
331
  observed: 'a matching call with no recorded body',
299
332
  expected: `a body carrying ${wantedBody(p)}`,
300
333
  assertion: NetBodyAssertion.CONTAINS,
@@ -340,8 +373,9 @@ export function evalNet(events, p) {
340
373
  };
341
374
  }
342
375
  const requestVerdict = requestBodyVerdict(requestState, p, matches.length, bodyMismatch);
343
- if (requestVerdict !== undefined)
376
+ if (requestVerdict !== undefined) {
344
377
  return requestVerdict;
378
+ }
345
379
  if (bodyMismatch !== undefined && 0 === matches.length) {
346
380
  // The call is there and its body is there; only the VALUE differs. Counting it as zero matches
347
381
  // points at the wiring, which is the one place the defect is not. A field clause also names the
@@ -362,8 +396,9 @@ export function evalNet(events, p) {
362
396
  if (p.count !== undefined) {
363
397
  if (0 === matches.length) {
364
398
  const download = nativeDownloadMiss(events, p);
365
- if (download !== undefined)
399
+ if (download !== undefined) {
366
400
  return download;
401
+ }
367
402
  }
368
403
  if (matches.length !== p.count &&
369
404
  0 === matches.length &&
@@ -394,8 +429,9 @@ export function evalNet(events, p) {
394
429
  const hit = matches[0];
395
430
  if (hit === undefined) {
396
431
  const download = nativeDownloadMiss(events, p);
397
- if (download !== undefined)
432
+ if (download !== undefined) {
398
433
  return download;
434
+ }
399
435
  }
400
436
  if (hit === undefined && targetsUnobservedChannel(p.urlContains) && !sawSubresources) {
401
437
  const reason = unobservedChannelReason(describeNetFilter(p));
@@ -423,12 +459,17 @@ export function evalNet(events, p) {
423
459
  export function evalAnimation(events, p) {
424
460
  const wantType = true === p.completed ? EventType.ANIM_END : EventType.ANIM_START;
425
461
  const hit = events.find((e) => {
426
- if (e.type !== wantType)
462
+ if (e.type !== wantType) {
427
463
  return false;
428
- if (p.name !== undefined && str(e.data['name']) !== p.name)
464
+ }
465
+ const name = str(e.data['name']);
466
+ // A check with no name asks about the app, so Reticle's own bookkeeping signals do not count.
467
+ if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name) {
429
468
  return false;
430
- if (p.target !== undefined && e.ref !== p.target)
469
+ }
470
+ if (p.target !== undefined && e.ref !== p.target) {
431
471
  return false;
472
+ }
432
473
  return true;
433
474
  });
434
475
  return hit !== undefined
@@ -449,10 +490,14 @@ export function evalSignal(events, p) {
449
490
  */
450
491
  let redactedField;
451
492
  const isMatch = (e) => {
452
- if (e.type !== EventType.SIGNAL)
493
+ if (e.type !== EventType.SIGNAL) {
453
494
  return false;
454
- if (p.name !== undefined && str(e.data['name']) !== p.name)
495
+ }
496
+ const name = str(e.data['name']);
497
+ // A check with no name asks about the app, so Reticle's own bookkeeping signals do not count.
498
+ if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name) {
455
499
  return false;
500
+ }
456
501
  if (p.dataMatches !== undefined) {
457
502
  const payload = (e.data['data'] ?? {});
458
503
  const hidden = 'object' === typeof payload
@@ -462,14 +507,16 @@ export function evalSignal(events, p) {
462
507
  redactedField ??= hidden;
463
508
  return false;
464
509
  }
465
- if (!dataMatches(payload, p.dataMatches))
510
+ if (!dataMatches(payload, p.dataMatches)) {
466
511
  return false;
512
+ }
467
513
  }
468
514
  return true;
469
515
  };
470
516
  const redactedVerdict = () => {
471
- if (redactedField === undefined)
517
+ if (redactedField === undefined) {
472
518
  return undefined;
519
+ }
473
520
  const field = JSON.stringify(redactedField);
474
521
  return {
475
522
  pass: false,
@@ -488,8 +535,9 @@ export function evalSignal(events, p) {
488
535
  const matched = events.filter(isMatch).length;
489
536
  // A redacted payload might have been one of the matches, so no count over it is decided.
490
537
  const unjudgeable = redactedVerdict();
491
- if (unjudgeable !== undefined)
538
+ if (unjudgeable !== undefined) {
492
539
  return unjudgeable;
540
+ }
493
541
  return evalExactCount({
494
542
  matched,
495
543
  want: p.count,
@@ -499,12 +547,14 @@ export function evalSignal(events, p) {
499
547
  });
500
548
  }
501
549
  const hit = events.find(isMatch);
502
- if (hit !== undefined)
550
+ if (hit !== undefined) {
503
551
  return { pass: true, evidence: hit.data };
552
+ }
504
553
  // `find` scanned every event to get here, so a redacted payload has been seen if there was one.
505
554
  const unjudgeable = redactedVerdict();
506
- if (unjudgeable !== undefined)
555
+ if (unjudgeable !== undefined) {
507
556
  return unjudgeable;
557
+ }
508
558
  // Near-miss: show signals that fired with the same name (so the agent sees the real data).
509
559
  const sameName = events
510
560
  .filter((e) => e.type === EventType.SIGNAL && (p.name === undefined || str(e.data['name']) === p.name))
@@ -556,6 +606,10 @@ const SETTLE_ACTIVITY = new Set([
556
606
  EventType.DOM_REMOVED,
557
607
  EventType.DOM_ATTR,
558
608
  ]);
609
+ /** An app-scoped settle: the default's activity, and every framework render commit. */
610
+ const APP_ACTIVITY = new Set([...SETTLE_ACTIVITY, EventType.RENDER_COMMIT]);
611
+ /** The quiet window of a network-scoped settle: a completed request is the only activity. */
612
+ const NETWORK_ACTIVITY = new Set([EventType.NET_REQUEST]);
559
613
  /** The three net-shaped event types a URL can be read off — the only ones dev tooling can produce. */
560
614
  const NET_TYPES = new Set([
561
615
  EventType.NET_PENDING,
@@ -564,6 +618,8 @@ const NET_TYPES = new Set([
564
618
  ]);
565
619
  /** Default quiet window — enough to absorb a render+xhr settle without waiting on slow polls. */
566
620
  const DEFAULT_QUIET_MS = 500;
621
+ /** Work the app declared (`reticle.busy`; core's `RETICLE_BUSY_SIGNAL`); not imported: coupling only shrinks. */
622
+ const RETICLE_BUSY_SIGNAL = 'reticle:busy';
567
623
  /**
568
624
  * Did the browser LEAVE for this record, rather than make a request whose result we will see?
569
625
  *
@@ -608,8 +664,9 @@ export function evalSettled(allEvents, p, now, scope) {
608
664
  const ignoredForeign = [];
609
665
  const ignoredDepartures = [];
610
666
  const events = allEvents.filter((e) => {
611
- if (!NET_TYPES.has(e.type))
667
+ if (!NET_TYPES.has(e.type)) {
612
668
  return true;
669
+ }
613
670
  // Classified by `urlForMatch`, DISCLOSED by `url`: redaction rewrites sensitive path segments at
614
671
  // emit time (`/auth/token/refresh-context` -> `/auth/token/[REDACTED]`), and a declared
615
672
  // `background` pattern is matched with `String.includes` — so classifying on the displayed URL
@@ -619,20 +676,23 @@ export function evalSettled(allEvents, p, now, scope) {
619
676
  const matchUrl = urlForMatch(e.data);
620
677
  const shown = str(e.data['url']);
621
678
  if (isDevToolingUrl(matchUrl)) {
622
- if (shown !== undefined && !ignoredDevTooling.includes(shown))
679
+ if (shown !== undefined && !ignoredDevTooling.includes(shown)) {
623
680
  ignoredDevTooling.push(shown);
681
+ }
624
682
  return false;
625
683
  }
626
684
  // Departure first: a departure to the app's own origin is still a request whose result nobody
627
685
  // will see, and reporting it as somebody else's host would be the wrong explanation.
628
686
  if (isDeparture(e.data)) {
629
- if (shown !== undefined && !ignoredDepartures.includes(shown))
687
+ if (shown !== undefined && !ignoredDepartures.includes(shown)) {
630
688
  ignoredDepartures.push(shown);
689
+ }
631
690
  return false;
632
691
  }
633
692
  if (isForeignTraffic(matchUrl, scope?.appUrl, scope?.background ?? [])) {
634
- if (shown !== undefined && !ignoredForeign.includes(shown))
693
+ if (shown !== undefined && !ignoredForeign.includes(shown)) {
635
694
  ignoredForeign.push(shown);
695
+ }
636
696
  return false;
637
697
  }
638
698
  return true;
@@ -660,15 +720,18 @@ export function evalSettled(allEvents, p, now, scope) {
660
720
  for (const e of events) {
661
721
  if (e.type === EventType.NET_PENDING) {
662
722
  const id = str(e.data['id']);
663
- if (id === undefined)
723
+ if (id === undefined) {
664
724
  unkeyedPending += 1;
665
- else
725
+ }
726
+ else {
666
727
  pendingById.set(id, (pendingById.get(id) ?? 0) + 1);
728
+ }
667
729
  }
668
730
  else if (e.type === EventType.NET_REQUEST) {
669
731
  const id = str(e.data['id']);
670
- if (id !== undefined)
732
+ if (id !== undefined) {
671
733
  doneById.set(id, (doneById.get(id) ?? 0) + 1);
734
+ }
672
735
  }
673
736
  }
674
737
  let inFlight = unkeyedPending;
@@ -682,24 +745,53 @@ export function evalSettled(allEvents, p, now, scope) {
682
745
  // way as a pending with no completion.
683
746
  const openStreams = new Set();
684
747
  for (const e of events) {
685
- if (e.type !== EventType.NET_STREAM)
748
+ if (e.type !== EventType.NET_STREAM) {
686
749
  continue;
750
+ }
687
751
  const id = str(e.data['id']);
688
- if (id === undefined)
752
+ if (id === undefined) {
689
753
  continue;
754
+ }
690
755
  const direction = str(e.data['direction']);
691
- if (StreamDirection.OPEN === direction)
756
+ if (StreamDirection.OPEN === direction) {
692
757
  openStreams.add(id);
693
- else if (StreamDirection.CLOSE === direction)
758
+ }
759
+ else if (StreamDirection.CLOSE === direction) {
694
760
  openStreams.delete(id);
761
+ }
695
762
  }
696
763
  const streaming = openStreams.size;
764
+ // Work only the app can see (`reticle.busy`): starts minus ends, in order, never below zero, so an
765
+ // end whose start fell before this window is not credit against work started inside it.
766
+ let appBusy = 0;
767
+ for (const e of events) {
768
+ if (e.type !== EventType.SIGNAL || RETICLE_BUSY_SIGNAL !== e.data['name']) {
769
+ continue;
770
+ }
771
+ const delta = e.data['data']?.delta;
772
+ if ('number' === typeof delta) {
773
+ appBusy = Math.max(0, appBusy + Math.sign(delta));
774
+ }
775
+ }
776
+ if (appBusy > 0 && 0 === inFlight + streaming) {
777
+ const what = `${String(appBusy)} app task(s) still pending`;
778
+ return {
779
+ pass: false,
780
+ failureReason: `not settled: ${what}`,
781
+ observed: what,
782
+ expected: 'no work the app declared still pending',
783
+ assertion: 'settled.app-busy',
784
+ evidence: { settled: false, appBusy, ...disclosure },
785
+ };
786
+ }
697
787
  if (inFlight + streaming > 0) {
698
- const what = 0 === streaming
699
- ? `${String(inFlight)} request(s) still in flight`
700
- : 0 === inFlight
701
- ? `${String(streaming)} response body(ies) still streaming`
702
- : `${String(inFlight)} request(s) in flight and ${String(streaming)} response body(ies) still streaming`;
788
+ let what = `${String(inFlight)} request(s) in flight and ${String(streaming)} response body(ies) still streaming`;
789
+ if (0 === streaming) {
790
+ what = `${String(inFlight)} request(s) still in flight`;
791
+ }
792
+ else if (0 === inFlight) {
793
+ what = `${String(streaming)} response body(ies) still streaming`;
794
+ }
703
795
  return {
704
796
  pass: false,
705
797
  failureReason: `not settled: ${what}`,
@@ -714,10 +806,19 @@ export function evalSettled(allEvents, p, now, scope) {
714
806
  },
715
807
  };
716
808
  }
809
+ // A network-scoped settle reads only completed requests for the quiet window; the in-flight checks
810
+ // above already ran for every scope.
811
+ let activity = SETTLE_ACTIVITY;
812
+ if (SettledChannel.NETWORK === p.channel) {
813
+ activity = NETWORK_ACTIVITY;
814
+ }
815
+ else if (SettledChannel.APP === p.channel) {
816
+ activity = APP_ACTIVITY;
817
+ }
717
818
  let lastT = -1;
718
819
  let lastType;
719
820
  for (const e of events) {
720
- if (SETTLE_ACTIVITY.has(e.type) && e.t > lastT) {
821
+ if (activity.has(e.type) && e.t > lastT) {
721
822
  lastT = e.t;
722
823
  lastType = e.type;
723
824
  }
@@ -10,6 +10,6 @@
10
10
  * This wraps it once, so every caller gets the same shape rather than each growing its own catch —
11
11
  * the pattern #108 asks for: name the parameter, say whether anything ran, show a valid call.
12
12
  */
13
- import { z } from 'zod';
13
+ import * as z from 'zod';
14
14
  import { PredicateSchema } from './predicate-eval.js';
15
15
  export declare function parsePredicate(input: unknown): z.infer<typeof PredicateSchema>;
@@ -10,7 +10,7 @@
10
10
  * This wraps it once, so every caller gets the same shape rather than each growing its own catch —
11
11
  * the pattern #108 asks for: name the parameter, say whether anything ran, show a valid call.
12
12
  */
13
- import { z } from 'zod';
13
+ import * as z from 'zod';
14
14
  import { PredicateKind } from '@reticlehq/core';
15
15
  import { PredicateSchema, predicateFieldsFor, predicateNestedFieldsFor } from './predicate-eval.js';
16
16
  /**
@@ -19,6 +19,8 @@ interface RequestBodyPredicate {
19
19
  interface RequestBodyState {
20
20
  /** A call matched everything else but carried no recorded request body. */
21
21
  unrecorded: boolean;
22
+ /** The body type the SDK named for an unrecorded request body, which it does only with capture on. */
23
+ unrecordedType?: unknown;
22
24
  /** The request body a clause was checked against and did not match. */
23
25
  mismatch?: string;
24
26
  /** The prefix of a TRUNCATED request body the clause did not hold over — undecidable, not absent. */
@@ -33,6 +35,17 @@ interface RequestBodyState {
33
35
  */
34
36
  redactedField?: string;
35
37
  }
38
+ /** What the SDK keeps with no setting, so an agent does not switch capture on for a body it has. */
39
+ export declare const BODY_CAPTURE_DEFAULTS: string;
40
+ /** The remedy when capture is off: the defaults, then where the setting goes. */
41
+ export declare const REMEDY_BODY_CAPTURE: string;
42
+ /**
43
+ * The remedy for a request body the SDK did not record although capture is on, or `undefined`.
44
+ *
45
+ * With capture on, the SDK names the type of a body it cannot stringify (`requestBodyType`: a
46
+ * `Blob`, a `FormData`, a stream). "Enable captureNetworkBodies" is then wrong advice (#1520).
47
+ */
48
+ export declare function requestBodySkipRemedy(bodyType: unknown): string | undefined;
36
49
  export declare function newRequestBodyState(): RequestBodyState;
37
50
  /**
38
51
  * Does this event satisfy the predicate's request-body clauses? Records why not in `state`.
@@ -15,6 +15,24 @@
15
15
  */
16
16
  import { REDACTED_VALUE } from '@reticlehq/core';
17
17
  import { clipBody, describeBodyFieldMiss, describeNetFilter, matchJsonBody, str, } from './predicate-eval-kit.js';
18
+ /** What the SDK keeps with no setting, so an agent does not switch capture on for a body it has. */
19
+ export const BODY_CAPTURE_DEFAULTS = 'A failed response (HTTP 400 and up) keeps its body by default. A request body, and the body of ' +
20
+ 'a successful response, need `captureNetworkBodies: true`.';
21
+ /** The remedy when capture is off: the defaults, then where the setting goes. */
22
+ export const REMEDY_BODY_CAPTURE = `${BODY_CAPTURE_DEFAULTS} Turn it on where the app calls connect(): ` +
23
+ '`reticle.connect({ captureNetworkBodies: true })`, or in the Vite plugin: ' +
24
+ '`reticle({ captureNetworkBodies: true })`.';
25
+ /**
26
+ * The remedy for a request body the SDK did not record although capture is on, or `undefined`.
27
+ *
28
+ * With capture on, the SDK names the type of a body it cannot stringify (`requestBodyType`: a
29
+ * `Blob`, a `FormData`, a stream). "Enable captureNetworkBodies" is then wrong advice (#1520).
30
+ */
31
+ export function requestBodySkipRemedy(bodyType) {
32
+ if ('string' !== typeof bodyType || 0 === bodyType.length)
33
+ return undefined;
34
+ return `the request body was a ${bodyType}, which the SDK does not record as text, and capture is already on. Assert on the response or on the effect the request had instead`;
35
+ }
18
36
  export function newRequestBodyState() {
19
37
  return { unrecorded: false };
20
38
  }
@@ -30,6 +48,7 @@ export function checkRequestBody(data, predicate, state) {
30
48
  const sent = str(data['requestBody']);
31
49
  if (sent === undefined) {
32
50
  state.unrecorded = true;
51
+ state.unrecordedType ??= data['requestBodyType'];
33
52
  return false;
34
53
  }
35
54
  const wasTruncated = true === data['requestBodyTruncated'];
@@ -83,9 +102,12 @@ export function requestBodyVerdict(state, predicate, matchCount, responseMismatc
83
102
  };
84
103
  }
85
104
  if (state.unrecorded) {
105
+ // Unknown, not different: nothing was read, so nothing says the body did not match (#1520).
106
+ const reason = `a call matched but its REQUEST body was not recorded, so the request-body clause could not be checked — ${requestBodySkipRemedy(state.unrecordedType) ?? REMEDY_BODY_CAPTURE}`;
86
107
  return {
87
108
  pass: false,
88
- failureReason: `a call matched but its REQUEST body was not recorded, so the request-body clause could not be checked — enable it where the app calls connect(): reticle({ captureNetworkBodies: true })`,
109
+ failureReason: reason,
110
+ inconclusive: reason,
89
111
  observed: 'a matching call with no recorded request body',
90
112
  expected: `a request body matching ${wanted}`,
91
113
  assertion: 'net.requestBody',
@@ -7,7 +7,7 @@
7
7
  * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
8
  * from here, so every existing importer of this module keeps working unchanged.
9
9
  */
10
- import { z } from 'zod';
10
+ import * as z from 'zod';
11
11
  import { type ElementDescriptor, type ElementQuery } from '@reticlehq/core';
12
12
  export { PredicateSchema } from '@reticlehq/core';
13
13
  export type { Predicate, PropertyAssertion } from '@reticlehq/core';
@@ -7,7 +7,7 @@
7
7
  * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
8
  * from here, so every existing importer of this module keeps working unchanged.
9
9
  */
10
- import { z } from 'zod';
10
+ import * as z from 'zod';
11
11
  import { PredicateKind, PredicateSchema, QueryBy, predicateShapeFor, } from '@reticlehq/core';
12
12
  // One public surface, two packages. A caller asking this module for the shape is asking the right
13
13
  // module; it simply no longer OWNS it.
@@ -317,18 +317,19 @@ export function nestedKeysOf(schema) {
317
317
  return [];
318
318
  return Object.keys(inner.shape);
319
319
  }
320
- /** Peel optional/nullable/default/effects wrappers off a field to reach the schema underneath. */
320
+ /** Peel optional/nullable/default/pipe wrappers off a field to reach the schema underneath. */
321
321
  function unwrapSchema(schema) {
322
322
  let current = schema;
323
323
  for (;;) {
324
324
  if (current instanceof z.ZodOptional ||
325
325
  current instanceof z.ZodNullable ||
326
326
  current instanceof z.ZodDefault) {
327
- current = current._def.innerType;
327
+ current = current.def.innerType;
328
328
  continue;
329
329
  }
330
- if (current instanceof z.ZodEffects) {
331
- current = current._def.schema;
330
+ // A transform is a pipe from the schema into the transform; a preprocess is the other way round.
331
+ if (current instanceof z.ZodPipe) {
332
+ current = (current.in instanceof z.ZodTransform ? current.out : current.in);
332
333
  continue;
333
334
  }
334
335
  return current;