@reticlehq/engine 3.1.0 → 3.2.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.
@@ -1,4 +1,4 @@
1
- import { ContradictionKind, EventType, isAbsenceDerived, isSameDocument, isSameEditEpoch, } from '@reticlehq/core';
1
+ import { ContradictionKind, EventType, REQUEST_SHAPE_FIELD, isAbsenceDerived, isSameDocument, isSameEditEpoch, } from '@reticlehq/core';
2
2
  import { describeSuperseded } from '../question/predicate/observed-in-window.js';
3
3
  import { describe, isMutating, isSameDocumentHashAnchor, isSteadyCadence, netCall, recoveredByRetry, splitForeignTraffic, } from './contradiction-evidence.js';
4
4
  import { findStaleResponses } from './stale-response.js';
@@ -19,6 +19,33 @@ import { runRegisteredFolds } from './contradiction-folds.js';
19
19
  *
20
20
  * Pure: a window of events in, findings out. No session, no IO, no clock.
21
21
  */
22
+ /**
23
+ * What this request CARRIED, as far as the record knows — `undefined` when it does not know.
24
+ *
25
+ * The page's shape fingerprint first: it is present on every request from an instrumented page,
26
+ * including the overwhelming majority where body capture is off. A captured body is the fallback for
27
+ * a realm that records one without a fingerprint (desktop IPC). Neither means the record does not
28
+ * say what this request carried — a body the page could not read as text, or an SDK too old to
29
+ * compute a fingerprint — and that is an ABSENCE of identity, not an identity shared with every
30
+ * other silent request.
31
+ */
32
+ function identityOf(event) {
33
+ const shape = asString(event.data[REQUEST_SHAPE_FIELD]);
34
+ if (shape !== undefined && 0 !== shape.length)
35
+ return shape;
36
+ const body = asString(event.data['requestBody']);
37
+ return body === undefined || 0 === body.length ? undefined : body;
38
+ }
39
+ /** Split calls to one endpoint into the sets that sent the same thing. Callers check first that
40
+ * every identity is known; an unknown one would otherwise pool with every other unknown. */
41
+ function groupByIdentity(calls) {
42
+ const byIdentity = new Map();
43
+ for (const call of calls) {
44
+ const key = call.identity ?? '';
45
+ byIdentity.set(key, [...(byIdentity.get(key) ?? []), call]);
46
+ }
47
+ return [...byIdentity.values()];
48
+ }
22
49
  function uiAdvanced(events) {
23
50
  return events.some((e) => e.type === EventType.DOM_ADDED ||
24
51
  e.type === EventType.DOM_REMOVED ||
@@ -492,13 +519,23 @@ function findWindowContradictions(allEvents, options) {
492
519
  // window the caller handed in turns two legitimate separate saves into a double submit. See
493
520
  // ContradictionOptions.actionSince.
494
521
  //
495
- // A captured request body joins the identity. A command-bus API posts every mutation to one URL
522
+ // What the request CARRIED joins the identity. A command-bus API posts every mutation to one URL
496
523
  // and discriminates on a body field (`{"command":"study.stage.set"}` vs `{"command":"mesh.plan"}`),
497
- // so under URL alone each of those distinct writes read as a repeat of the first, and clean
498
- // verdicts degraded to unknown behind doubles that were never doubles. When no body was captured
499
- // (capture off, or a non-text body, which reports a type marker instead) there is nothing to
500
- // compare and the URL alone stands, as before; a window where only some calls carried bodies
501
- // compares nothing rather than guess.
524
+ // and a submit that intentionally saves and then advances sends two different payloads to the same
525
+ // endpoint; under URL alone each of those distinct writes read as a repeat of the first, and clean
526
+ // verdicts degraded to unknown behind doubles that were never doubles.
527
+ //
528
+ // The discriminator is `REQUEST_SHAPE_FIELD` — a fingerprint of the body's shape that the page can
529
+ // compute with body capture OFF, which is the configuration every session runs in. A captured body
530
+ // is used when there is one and no fingerprint (a realm that records bodies but not shapes).
531
+ //
532
+ // When NEITHER is on the record for any call at a URL, the identity of those writes is not known,
533
+ // and this used to be answered inconsistently and silently: two calls that both lacked a body got
534
+ // the same key and were reported as a duplicate, while two where only ONE carried a body got
535
+ // different keys and were reported as nothing at all — so the guess went one way on a false
536
+ // positive and the other way on a real double submit. An unknown group is now one group, reported
537
+ // with a finding that SAYS the identity could not be established. That is `unknown`, which is the
538
+ // honest verdict for it, rather than `unknown` dressed as an accusation.
502
539
  const actionSince = options.actionSince;
503
540
  if (actionSince !== undefined) {
504
541
  /**
@@ -515,7 +552,7 @@ function findWindowContradictions(allEvents, options) {
515
552
  * distinguishes them.
516
553
  */
517
554
  const navigatedAt = events.find((e) => EventType.ROUTE_CHANGE === e.type && e.t >= actionSince)?.t;
518
- const writeTimes = new Map();
555
+ const writes = new Map();
519
556
  for (const event of events) {
520
557
  if (event.type !== EventType.NET_REQUEST || event.t < actionSince)
521
558
  continue;
@@ -525,14 +562,11 @@ function findWindowContradictions(allEvents, options) {
525
562
  if (!isMutating(call))
526
563
  continue;
527
564
  const label = `${call.method} ${call.url}`;
528
- const body = asString(event.data['requestBody']);
529
- const key = body === undefined || 0 === body.length ? label : `${label} ${body}`;
530
- const entry = writeTimes.get(key) ?? { label, times: [], landed: 0 };
531
- entry.times.push(event.t);
532
- // Counted separately from the occurrences, because the claim is about what APPLIED.
533
- if (false !== call.ok)
534
- entry.landed += 1;
535
- writeTimes.set(key, entry);
565
+ const calls = writes.get(label) ?? [];
566
+ // `landed` is tracked per call rather than counted here, because the claim is about what
567
+ // APPLIED and a group is only formed once the identities are known.
568
+ calls.push({ t: event.t, landed: false !== call.ok, identity: identityOf(event) });
569
+ writes.set(label, calls);
536
570
  }
537
571
  /**
538
572
  * Did the assertion name this endpoint?
@@ -544,38 +578,53 @@ function findWindowContradictions(allEvents, options) {
544
578
  */
545
579
  const named = options.namedNetUrls;
546
580
  const wasNamed = (label) => named === undefined || named.some((u) => label.includes(u));
547
- for (const [, { label, times, landed }] of writeTimes) {
548
- if (times.length < 2)
549
- continue;
550
- // A DOUBLE SUBMIT is a write that landed twice. Two attempts of which one failed is a RETRY,
551
- // and the field case is the commonest retry there is: a 401 that refreshed a token and went
552
- // again, one row created, reported here as `duplicate-request ×2`. Two attempts that both
553
- // failed are not a double submit either — nothing applied even once, so the claim "one user
554
- // action was performed" is not contradicted by them. A call with no verdict at all still
555
- // counts, because absence of a status is not evidence the write was rejected.
556
- if (landed < 2)
557
- continue;
558
- // A steady cadence is a POLL, and a poll is not a double submit. An app that polls could not
559
- // produce a verdict at all: a camera scan loop POSTing until it acquires a lock had every
560
- // assertion that had already seen its consequence come back `unknown` behind writes that
561
- // were the app working correctly (#673).
562
- if (isSteadyCadence(times))
563
- continue;
564
- // A burst the assertion never mentioned is still worth telling the caller about -- a retry
565
- // loop or a bursty beacon is a real finding -- but it is not evidence about the consequence
566
- // they declared, so it is reported and decides nothing. The named case keeps its downgrade:
567
- // "the write you asked about fired twice" is exactly what this rule is for.
568
- const related = wasNamed(label);
569
- found.push({
570
- kind: related
571
- ? ContradictionKind.DUPLICATE_REQUEST
572
- : ContradictionKind.DUPLICATE_REQUEST_UNRELATED,
573
- claim: related
574
- ? 'one user action was performed'
575
- : 'the assertion did not name this endpoint',
576
- counter: `the same write fired ${String(times.length)} times`,
577
- detail: `${label} ×${String(times.length)}`,
578
- });
581
+ for (const [label, calls] of writes) {
582
+ // One unknown identity makes the whole endpoint's traffic one group: the calls that DO have a
583
+ // fingerprint cannot be told apart from the ones that do not, so splitting on it would answer
584
+ // a question the record cannot answer.
585
+ const identified = calls.every((c) => c.identity !== undefined);
586
+ const groups = identified ? [...groupByIdentity(calls)] : [calls];
587
+ for (const group of groups) {
588
+ const times = group.map((c) => c.t);
589
+ const landed = group.filter((c) => c.landed).length;
590
+ if (times.length < 2)
591
+ continue;
592
+ // A DOUBLE SUBMIT is a write that landed twice. Two attempts of which one failed is a RETRY,
593
+ // and the field case is the commonest retry there is: a 401 that refreshed a token and went
594
+ // again, one row created, reported here as `duplicate-request ×2`. Two attempts that both
595
+ // failed are not a double submit either — nothing applied even once, so the claim "one user
596
+ // action was performed" is not contradicted by them. A call with no verdict at all still
597
+ // counts, because absence of a status is not evidence the write was rejected.
598
+ if (landed < 2)
599
+ continue;
600
+ // A steady cadence is a POLL, and a poll is not a double submit. An app that polls could not
601
+ // produce a verdict at all: a camera scan loop POSTing until it acquires a lock had every
602
+ // assertion that had already seen its consequence come back `unknown` behind writes that
603
+ // were the app working correctly (#673).
604
+ if (isSteadyCadence(times))
605
+ continue;
606
+ // A burst the assertion never mentioned is still worth telling the caller about -- a retry
607
+ // loop or a bursty beacon is a real finding -- but it is not evidence about the consequence
608
+ // they declared, so it is reported and decides nothing. The named case keeps its downgrade:
609
+ // "the write you asked about fired twice" is exactly what this rule is for.
610
+ const related = wasNamed(label);
611
+ const count = String(times.length);
612
+ found.push({
613
+ kind: related
614
+ ? ContradictionKind.DUPLICATE_REQUEST
615
+ : ContradictionKind.DUPLICATE_REQUEST_UNRELATED,
616
+ claim: related
617
+ ? 'one user action was performed'
618
+ : 'the assertion did not name this endpoint',
619
+ counter: identified
620
+ ? `the same write fired ${count} times`
621
+ : `this endpoint was written to ${count} times`,
622
+ detail: identified
623
+ ? `${label} ×${count}`
624
+ : `${label} ×${count} — nothing on the record says what these requests carried, ` +
625
+ 'so whether they were one write repeated or different writes could not be established',
626
+ });
627
+ }
579
628
  }
580
629
  }
581
630
  // ── The UI advanced over a request that never came back ─────────────────────────────────────
@@ -57,7 +57,12 @@ export function bodyCaptureRemedy(sdkVersion) {
57
57
  return ENABLE_IT;
58
58
  }
59
59
  /** Clause names that can only be answered from a recorded body. */
60
- const BODY_CLAUSE_FIELDS = ['bodyContains', 'requestBodyContains'];
60
+ const BODY_CLAUSE_FIELDS = [
61
+ 'bodyContains',
62
+ 'bodyMatches',
63
+ 'requestBodyContains',
64
+ 'requestBodyMatches',
65
+ ];
61
66
  /** Does this predicate, or anything nested in it, ask about a body? */
62
67
  function asksAboutBody(predicate) {
63
68
  if (null === predicate || 'object' !== typeof predicate)
@@ -42,6 +42,16 @@ interface HonestyInputs {
42
42
  */
43
43
  coverageNote?: string;
44
44
  truncated?: boolean;
45
+ /**
46
+ * Did the durable event ledger stop accepting writes, on a path this verdict read from?
47
+ *
48
+ * Separate from `truncated`, which means the in-memory ring buffer evicted a window that had aged
49
+ * out. Both make a capture incomplete and both belong in `issues`, but they are opposite kinds of
50
+ * fact for whoever reads the sentence: an eviction is a window that scrolled past, recoverable by
51
+ * looking sooner, while a closed ledger is a file that will not take another byte for the rest of
52
+ * the session. One word for both would tell an agent to re-drive a thing no re-drive can fix.
53
+ */
54
+ ledgerClosed?: boolean;
45
55
  blindSpots?: readonly string[];
46
56
  /**
47
57
  * The machine-readable half of `issues` — WHICH kind of loss, from core's closed `CaptureLoss`.
@@ -35,10 +35,14 @@ export const weakerGrade = (a, b) => GRADE_RANK[a] <= GRADE_RANK[b] ? a : b;
35
35
  const MIN_ENVELOPE_SAMPLES = 3;
36
36
  /** Coverage when the SDK reported no blind spots during the window — it saw everything it can see. */
37
37
  const FULL_COVERAGE_PCT = 100;
38
+ /** What `integrity.issues` says when the durable ledger refused writes — see `ledgerClosed`. */
39
+ const LEDGER_CLOSED_ISSUE = 'durable event ledger closed at its size cap, so evidence after that point is not on disk';
38
40
  export function buildHonestyBlock(inputs) {
39
41
  const issues = [];
40
42
  if (true === inputs.truncated)
41
43
  issues.push('capture truncated');
44
+ if (true === inputs.ledgerClosed)
45
+ issues.push(LEDGER_CLOSED_ISSUE);
42
46
  for (const spot of inputs.blindSpots ?? [])
43
47
  issues.push(`blind spot: ${spot}`);
44
48
  // Report only what was measured. `envelope` used to be emitted unconditionally with samples=0, so
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The one substring hit that cannot mean what the caller meant (#987).
3
+ *
4
+ * Reported from the field as the only false GREEN in that export: `net { bodyContains: "completed" }`
5
+ * returned `verified: "yes"` for a job whose status was `queued`, because the body carried
6
+ * `"completedAt": null` and `completed` is a substring of that KEY.
7
+ *
8
+ * `bodyContains` is a substring test and stays one — "this field is in the response"
9
+ * (`bodyContains: "grand_total"`) and "this value came back" (`bodyContains: '"refunded":11.87'`)
10
+ * are both real assertions people have saved, and neither is expressible if the field starts
11
+ * demanding boundaries. What is detectable without touching that meaning is the single shape where
12
+ * the hit can support NO reading at all: the needle appears only INSIDE a key name, matches no key
13
+ * whole, and appears in no value anywhere in the document. Nobody asserts a fragment of a key — if
14
+ * you mean the key you write the key, and if you mean a value it is not there.
15
+ *
16
+ * So this decides nothing on its own. It only separates "true and meaningless" from a pass.
17
+ */
18
+ /**
19
+ * The key name a needle was found inside, when that is the ONLY place it occurs.
20
+ *
21
+ * `undefined` for every other case — a body that is not JSON (nothing here can tell a key from a
22
+ * word), a needle that matches a key exactly, a needle that appears in any value, and a needle that
23
+ * spans a key and its value, which belongs to neither half alone and is a value assertion.
24
+ */
25
+ export declare function keyFragmentOnly(body: string, needle: string): string | undefined;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The one substring hit that cannot mean what the caller meant (#987).
3
+ *
4
+ * Reported from the field as the only false GREEN in that export: `net { bodyContains: "completed" }`
5
+ * returned `verified: "yes"` for a job whose status was `queued`, because the body carried
6
+ * `"completedAt": null` and `completed` is a substring of that KEY.
7
+ *
8
+ * `bodyContains` is a substring test and stays one — "this field is in the response"
9
+ * (`bodyContains: "grand_total"`) and "this value came back" (`bodyContains: '"refunded":11.87'`)
10
+ * are both real assertions people have saved, and neither is expressible if the field starts
11
+ * demanding boundaries. What is detectable without touching that meaning is the single shape where
12
+ * the hit can support NO reading at all: the needle appears only INSIDE a key name, matches no key
13
+ * whole, and appears in no value anywhere in the document. Nobody asserts a fragment of a key — if
14
+ * you mean the key you write the key, and if you mean a value it is not there.
15
+ *
16
+ * So this decides nothing on its own. It only separates "true and meaningless" from a pass.
17
+ */
18
+ /** Every key and every leaf value in a parsed JSON document, as text. */
19
+ function collect(node, keys, values) {
20
+ if (Array.isArray(node)) {
21
+ for (const item of node)
22
+ collect(item, keys, values);
23
+ return;
24
+ }
25
+ if (null !== node && 'object' === typeof node) {
26
+ for (const [key, value] of Object.entries(node)) {
27
+ keys.push(key);
28
+ collect(value, keys, values);
29
+ }
30
+ return;
31
+ }
32
+ values.push('string' === typeof node ? node : String(node));
33
+ }
34
+ /**
35
+ * The key name a needle was found inside, when that is the ONLY place it occurs.
36
+ *
37
+ * `undefined` for every other case — a body that is not JSON (nothing here can tell a key from a
38
+ * word), a needle that matches a key exactly, a needle that appears in any value, and a needle that
39
+ * spans a key and its value, which belongs to neither half alone and is a value assertion.
40
+ */
41
+ export function keyFragmentOnly(body, needle) {
42
+ let payload;
43
+ try {
44
+ payload = JSON.parse(body);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ const keys = [];
50
+ const values = [];
51
+ collect(payload, keys, values);
52
+ if (keys.includes(needle))
53
+ return undefined;
54
+ if (values.some((value) => value.includes(needle)))
55
+ return undefined;
56
+ return keys.find((key) => key.includes(needle));
57
+ }
@@ -76,6 +76,27 @@ export declare function num(value: unknown): number | undefined;
76
76
  export declare function matchValue(got: unknown, want: unknown): boolean;
77
77
  /** Shallow JSON pattern match: each key in `pattern` must match (see matchValue). */
78
78
  export declare function dataMatches(actual: Record<string, unknown>, pattern: Record<string, unknown>): boolean;
79
+ /**
80
+ * What a field-level clause over a captured body came to.
81
+ *
82
+ * Three outcomes, not two: a key the SDK redacted before recording cannot be judged at all, and
83
+ * grading that a mismatch blames the application for the observer's own redaction.
84
+ */
85
+ export type BodyFieldVerdict = 'match' | 'mismatch' | {
86
+ redacted: string;
87
+ };
88
+ /**
89
+ * Shallow JSON field match over a captured body, for either half of the exchange.
90
+ *
91
+ * One function because both halves ask the identical question, and the request side already had
92
+ * this exact sequence written out — parse, reject a non-object, check the wanted keys for
93
+ * `[REDACTED]`, then `dataMatches`.
94
+ *
95
+ * A body that is not a JSON object counts as a mismatch rather than an error: guessing at form
96
+ * encoding here would answer a different question than the one asked, and the substring clauses
97
+ * exist for those bodies.
98
+ */
99
+ export declare function matchJsonBody(body: string, pattern: Record<string, unknown>): BodyFieldVerdict;
79
100
  /** Enough of a body to see what differed, without paying for a whole payload in the verdict. */
80
101
  export declare function clipBody(body: string): string;
81
102
  /**
@@ -1,4 +1,4 @@
1
- import { PredicateKind } from '@reticlehq/core';
1
+ import { PredicateKind, REDACTED_VALUE } from '@reticlehq/core';
2
2
  export function str(value) {
3
3
  return 'string' === typeof value ? value : undefined;
4
4
  }
@@ -104,6 +104,33 @@ export function dataMatches(actual, pattern) {
104
104
  }
105
105
  return true;
106
106
  }
107
+ /**
108
+ * Shallow JSON field match over a captured body, for either half of the exchange.
109
+ *
110
+ * One function because both halves ask the identical question, and the request side already had
111
+ * this exact sequence written out — parse, reject a non-object, check the wanted keys for
112
+ * `[REDACTED]`, then `dataMatches`.
113
+ *
114
+ * A body that is not a JSON object counts as a mismatch rather than an error: guessing at form
115
+ * encoding here would answer a different question than the one asked, and the substring clauses
116
+ * exist for those bodies.
117
+ */
118
+ export function matchJsonBody(body, pattern) {
119
+ let payload;
120
+ try {
121
+ payload = JSON.parse(body);
122
+ }
123
+ catch {
124
+ return 'mismatch';
125
+ }
126
+ if (null === payload || 'object' !== typeof payload || Array.isArray(payload))
127
+ return 'mismatch';
128
+ const actual = payload;
129
+ const redacted = Object.keys(pattern).find((key) => REDACTED_VALUE === actual[key]);
130
+ if (redacted !== undefined)
131
+ return { redacted };
132
+ return dataMatches(actual, pattern) ? 'match' : 'mismatch';
133
+ }
107
134
  /**
108
135
  * How much of a response body a failure may quote. Enough to see the value that differed on the
109
136
  * bodies this field is used against (a JSON answer), and not a whole payload in every verdict.
@@ -3,7 +3,8 @@ import { describeObserved } from './observed-in-window.js';
3
3
  import { netEvidence } from './net-evidence.js';
4
4
  import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
5
  export { evalConsole } from './predicate-console.js';
6
- import { clipBody, dataMatches, describeNetFilter, num, str, } from './predicate-eval-kit.js';
6
+ import { clipBody, dataMatches, describeNetFilter, matchJsonBody, num, str, } from './predicate-eval-kit.js';
7
+ import { keyFragmentOnly } from './body-key-fragment.js';
7
8
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
8
9
  // The predicate SHAPE — the discriminated union, its aliases and its zod schema — lives in
9
10
  // predicate-schema.ts, and is re-exported here: the two halves are ONE public surface.
@@ -276,6 +277,16 @@ function unobservedChannelReason(p) {
276
277
  const PRE_ATTACH_CAVEAT = ' — note that this window starts where the SDK attached, and requests made before that are never ' +
277
278
  'captured, so a miss here cannot tell a call that was never made apart from one made before the ' +
278
279
  'page connected; if the call is expected during startup, assert on the state it produces instead';
280
+ /**
281
+ * The response-body clause as the caller wrote it, for a verdict that has to quote it.
282
+ *
283
+ * One expression rather than two, because every body verdict below is the same sentence whichever
284
+ * clause asked the question, and printing `undefined` where the clause was `bodyMatches` is how a
285
+ * verdict stops being readable.
286
+ */
287
+ function wantedBody(p) {
288
+ return JSON.stringify(p.bodyContains ?? p.bodyMatches);
289
+ }
279
290
  export function evalNet(events, p) {
280
291
  const since = p.since ?? 0;
281
292
  /**
@@ -309,6 +320,15 @@ export function evalNet(events, p) {
309
320
  * a truncated one cannot (#614).
310
321
  */
311
322
  let truncatedBody;
323
+ /**
324
+ * A `bodyContains` needle that was FOUND, and found only inside a key name (#987).
325
+ *
326
+ * Not a match and not a miss: the substring is there, and it supports no claim about any value.
327
+ * Held with the body it was found in, because the verdict has to show both.
328
+ */
329
+ let keyFragment;
330
+ /** A response key whose captured value is `[REDACTED]`, so a `bodyMatches` clause is unjudgeable. */
331
+ let redactedResponseField;
312
332
  const requestState = newRequestBodyState();
313
333
  const matches = events.filter((e) => {
314
334
  if (e.type !== EventType.NET_REQUEST || e.t < since)
@@ -335,28 +355,45 @@ export function evalNet(events, p) {
335
355
  }
336
356
  if (p.ok !== undefined && callSucceeded(d) !== p.ok)
337
357
  return false;
338
- if (p.bodyContains !== undefined) {
339
- // The RESPONSE body only, and this is the whole point of the field. Searching the request too
340
- // would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app SENT
341
- // that number, so it is in the request whatever the server then did with it. The server's answer
342
- // is the one channel a UI cannot fake.
358
+ if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
359
+ // The RESPONSE body only, and this is the whole point of these fields. Searching the request
360
+ // too would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app
361
+ // SENT that number, so it is in the request whatever the server then did with it. The server's
362
+ // answer is the one channel a UI cannot fake.
343
363
  const response = str(d['responseBody']);
344
364
  if (response === undefined) {
345
365
  matchedButUnrecorded = true;
346
366
  return false;
347
367
  }
348
- if (!response.includes(p.bodyContains)) {
349
- // A needle missing from a body we only hold the FIRST N BYTES of is undecidable, not
350
- // absent: the rest of the response was never recorded, so nothing here can say whether it
351
- // was in there (#614). Grading it `pass: false` with "the response value is what differed"
352
- // is the inversion the honesty rules exist to prevent — an unknown reported as decided,
353
- // against a response that was very likely correct.
354
- if (true === d['responseBodyTruncated']) {
368
+ // A needle missing from a body we only hold the FIRST N BYTES of is undecidable, not absent:
369
+ // the rest of the response was never recorded, so nothing here can say whether it was in
370
+ // there (#614). Grading it `pass: false` with "the response value is what differed" is the
371
+ // inversion the honesty rules exist to prevent — an unknown reported as decided, against a
372
+ // response that was very likely correct.
373
+ const missed = () => {
374
+ if (true === d['responseBodyTruncated'])
355
375
  truncatedBody ??= response;
376
+ else
377
+ bodyMismatch ??= response;
378
+ return false;
379
+ };
380
+ if (p.bodyContains !== undefined) {
381
+ if (!response.includes(p.bodyContains))
382
+ return missed();
383
+ const fragment = keyFragmentOnly(response, p.bodyContains);
384
+ if (fragment !== undefined) {
385
+ keyFragment ??= { key: fragment, body: response };
386
+ return false;
387
+ }
388
+ }
389
+ if (p.bodyMatches !== undefined) {
390
+ const verdict = matchJsonBody(response, p.bodyMatches);
391
+ if ('mismatch' === verdict)
392
+ return missed();
393
+ if ('match' !== verdict) {
394
+ redactedResponseField ??= verdict.redacted;
356
395
  return false;
357
396
  }
358
- bodyMismatch ??= response;
359
- return false;
360
397
  }
361
398
  }
362
399
  if (!checkRequestBody(d, p, requestState))
@@ -380,10 +417,30 @@ export function evalNet(events, p) {
380
417
  pass: false,
381
418
  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 })`,
382
419
  observed: 'a matching call with no recorded body',
383
- expected: `a body containing ${JSON.stringify(p.bodyContains)}`,
420
+ expected: `a body carrying ${wantedBody(p)}`,
384
421
  assertion: 'net.bodyContains',
385
422
  };
386
423
  }
424
+ if (keyFragment !== undefined && 0 === matches.length) {
425
+ // Ranked above every other body verdict, because it is the only one that used to be a PASS.
426
+ return {
427
+ pass: false,
428
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body where ${JSON.stringify(p.bodyContains)} appears ONLY inside the key name ${JSON.stringify(keyFragment.key)} — no value in the response contains it, so this substring proves nothing about what any field holds. Assert the field itself: \`bodyMatches: { "<field>": <value> }\``,
429
+ observed: `response body ${JSON.stringify(clipBody(keyFragment.body))}`,
430
+ expected: `a response body carrying ${JSON.stringify(p.bodyContains)} as a value, or as a whole key`,
431
+ assertion: 'net.bodyContains',
432
+ };
433
+ }
434
+ if (redactedResponseField !== undefined && 0 === matches.length) {
435
+ const field = JSON.stringify(redactedResponseField);
436
+ return {
437
+ pass: false,
438
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered, but its ${field} was REDACTED before the body was recorded, so this clause cannot be judged — a redacted field is unknown, not different. Assert on a non-sensitive key, or on the effect the value had`,
439
+ observed: `a matching response whose ${field} is ${REDACTED_VALUE}`,
440
+ expected: `a response body matching ${JSON.stringify(p.bodyMatches)}`,
441
+ assertion: 'net.bodyMatches',
442
+ };
443
+ }
387
444
  const requestVerdict = requestBodyVerdict(requestState, p, matches.length);
388
445
  if (requestVerdict !== undefined)
389
446
  return requestVerdict;
@@ -393,9 +450,9 @@ export function evalNet(events, p) {
393
450
  if (truncatedBody !== undefined && 0 === matches.length) {
394
451
  return {
395
452
  pass: false,
396
- inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${JSON.stringify(p.bodyContains)} is not in the part that was kept — so this is undecidable, not a failure. Raise the capture cap or assert on something inside the recorded prefix`,
453
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. Raise the capture cap or assert on something inside the recorded prefix`,
397
454
  observed: `the first ${String(truncatedBody.length)} characters of a truncated response body ${JSON.stringify(clipBody(truncatedBody))}`,
398
- expected: `a response body containing ${JSON.stringify(p.bodyContains)}`,
455
+ expected: `a response body carrying ${wantedBody(p)}`,
399
456
  assertion: 'net.bodyContains',
400
457
  };
401
458
  }
@@ -404,9 +461,9 @@ export function evalNet(events, p) {
404
461
  // points at the wiring, which is the one place the defect is not.
405
462
  return {
406
463
  pass: false,
407
- failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not contain ${JSON.stringify(p.bodyContains)} — the request fired, the response value is what differed`,
464
+ failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not carry ${wantedBody(p)} — the request fired, the response value is what differed`,
408
465
  observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}`,
409
- expected: `a response body containing ${JSON.stringify(p.bodyContains)}`,
466
+ expected: `a response body carrying ${wantedBody(p)}`,
410
467
  assertion: 'net.bodyContains',
411
468
  };
412
469
  }
@@ -6,3 +6,10 @@
6
6
  * that depends on what is actually rendered is still decided after the action, where it belongs.
7
7
  */
8
8
  export declare function unevaluablePredicateReason(predicate: unknown): string | undefined;
9
+ /**
10
+ * The reason this predicate proves nothing whatever the app does, or undefined when it makes a claim.
11
+ *
12
+ * Checked at any depth, because a composite inherits it: one unconditionally-true branch of an
13
+ * `anyOf` satisfies the whole thing, so the branch that WOULD have been evidence never has to hold.
14
+ */
15
+ export declare function vacuousPredicateReason(predicate: unknown): string | undefined;
@@ -1,3 +1,21 @@
1
+ /**
2
+ * Refuse an unevaluable predicate BEFORE the action fires.
3
+ *
4
+ * `reticle_act_and_wait` dispatches, then evaluates `until`. So a locator the browser cannot use —
5
+ * one naming fields the element resolver drops — was detected only after the click had landed and
6
+ * the page had already moved. The result came back `verified:"unknown", inconclusive`, which reads
7
+ * as "Reticle could not tell what happened".
8
+ *
9
+ * That is not true, and it is the wrong direction of error for a verification tool. Reticle could
10
+ * tell perfectly well; what it could not do was evaluate a predicate the CALLER wrote badly. Charging
11
+ * that to the app teaches the reader to distrust a verdict that was never about the app, and the
12
+ * action has already been spent by the time they learn.
13
+ *
14
+ * The refusal shape already exists elsewhere and is exactly right: "target matched no element.
15
+ * Nothing was acted on and no verdict is possible… This is a miss, not a Reticle defect: there is
16
+ * nothing to report." This is that, applied one step earlier.
17
+ */
18
+ import { PredicateKind } from '@reticlehq/core';
1
19
  import { residualQueryChecks } from './predicate-schema.js';
2
20
  /** Composite predicates nest; the unusable one can be at any depth. */
3
21
  const NESTED_KEYS = ['predicates', 'predicate'];
@@ -39,3 +57,66 @@ export function unevaluablePredicateReason(predicate) {
39
57
  }
40
58
  return undefined;
41
59
  }
60
+ /**
61
+ * Predicates that are true the moment they are written, and so cannot be evidence of anything.
62
+ *
63
+ * Only `signal` and `net` can be declared with no specifics: both read the event stream from the
64
+ * act's own cursor, so a bare one cannot be answered by something that had already happened. The
65
+ * kinds checked here are read BEFORE the action as well as after (see `already-true.ts`), precisely
66
+ * so a condition that already held cannot be sold as something the action caused — and a bare one of
67
+ * them always already held. There is always a current route, and there is always some store.
68
+ *
69
+ * The result was not an error but a `no-fault` verdict with reason `already_true`: a verdict-shaped
70
+ * object carrying no proof, which an agent skimming for `ok` reads as a pass. A refusal teaches; a
71
+ * no-fault verdict misleads, and it costs the action as well, because the caller only learns after
72
+ * the click has landed and the page has moved.
73
+ */
74
+ const DECLARE_INSTEAD = 'Declare something the action CHANGES: a `signal` (by name) or a `net` call (method, urlContains, ' +
75
+ 'status) can be declared without knowing the app, a `route` needs a `pathname` or `contains`, and ' +
76
+ 'a `state` needs a non-empty `path` or a value to compare. One reticle_observe call gives you the ' +
77
+ "app's real signal names and endpoint paths to name here. Nothing was acted on: this predicate was " +
78
+ 'already true before the action, so the only thing it could ever have proved is that the action ' +
79
+ 'was not needed.';
80
+ /** A `path` that selects the whole store root, in any spelling a caller writes it. */
81
+ function selectsWholeStore(path) {
82
+ return undefined === path || ('string' === typeof path && 0 === path.trim().length);
83
+ }
84
+ /** The reason THIS leaf is unconditionally true, or undefined when it makes a real claim. */
85
+ function vacuousLeafReason(p) {
86
+ if (PredicateKind.ROUTE === p['kind'] &&
87
+ undefined === p['pathname'] &&
88
+ undefined === p['contains'])
89
+ return ('a bare `route` predicate is true the moment it is written — there is always a current route, ' +
90
+ `so ${JSON.stringify(p)} would have held before the action as well as after it. ${DECLARE_INSTEAD}`);
91
+ if (PredicateKind.STATE === p['kind'] &&
92
+ selectsWholeStore(p['path']) &&
93
+ undefined === p['equals'] &&
94
+ undefined === p['satisfies'])
95
+ return ('a `state` predicate with no path and nothing to compare is true the moment it is written — ' +
96
+ `there is always some store, so ${JSON.stringify(p)} would have held before the action as ` +
97
+ `well as after it. ${DECLARE_INSTEAD}`);
98
+ return undefined;
99
+ }
100
+ /**
101
+ * The reason this predicate proves nothing whatever the app does, or undefined when it makes a claim.
102
+ *
103
+ * Checked at any depth, because a composite inherits it: one unconditionally-true branch of an
104
+ * `anyOf` satisfies the whole thing, so the branch that WOULD have been evidence never has to hold.
105
+ */
106
+ export function vacuousPredicateReason(predicate) {
107
+ if (!isRecord(predicate))
108
+ return undefined;
109
+ const leaf = vacuousLeafReason(predicate);
110
+ if (leaf !== undefined)
111
+ return leaf;
112
+ for (const key of NESTED_KEYS) {
113
+ const nested = predicate[key];
114
+ const children = Array.isArray(nested) ? nested : [nested];
115
+ for (const child of children) {
116
+ const reason = vacuousPredicateReason(child);
117
+ if (reason !== undefined)
118
+ return reason;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
@@ -14,7 +14,7 @@
14
14
  * Extracted from `predicate-eval.ts`, which was at the 1000-line cap.
15
15
  */
16
16
  import { REDACTED_VALUE } from '@reticlehq/core';
17
- import { clipBody, dataMatches, describeNetFilter, str, } from './predicate-eval-kit.js';
17
+ import { clipBody, describeNetFilter, matchJsonBody, str, } from './predicate-eval-kit.js';
18
18
  export function newRequestBodyState() {
19
19
  return { unrecorded: false };
20
20
  }
@@ -46,25 +46,16 @@ export function checkRequestBody(data, predicate, state) {
46
46
  return note();
47
47
  if (requestBodyMatches === undefined)
48
48
  return true;
49
- let payload;
50
- try {
51
- payload = JSON.parse(sent);
52
- }
53
- catch {
54
- // Not JSON (a form post, plain text). A shallow key match cannot be applied, and guessing at
55
- // form encoding here would answer a different question than the one asked. Use
56
- // `requestBodyContains` for those.
57
- return note();
58
- }
59
- if (null === payload || typeof payload !== 'object' || Array.isArray(payload))
49
+ // `matchJsonBody` is the shared one, and a body that is not a JSON object counts as a mismatch
50
+ // there for the reason this side already had written down: guessing at form encoding would answer
51
+ // a different question than the one asked, and `requestBodyContains` exists for those bodies.
52
+ const verdict = matchJsonBody(sent, requestBodyMatches);
53
+ if ('match' === verdict)
54
+ return true;
55
+ if ('mismatch' === verdict)
60
56
  return note();
61
- const actual = payload;
62
- const redacted = Object.keys(requestBodyMatches).find((key) => REDACTED_VALUE === actual[key]);
63
- if (redacted !== undefined) {
64
- state.redactedField ??= redacted;
65
- return false;
66
- }
67
- return dataMatches(actual, requestBodyMatches) ? true : note();
57
+ state.redactedField ??= verdict.redacted;
58
+ return false;
68
59
  }
69
60
  /**
70
61
  * The verdict for a request-body clause nothing satisfied, or `undefined` to fall through.
@@ -33,6 +33,8 @@ export type Predicate = {
33
33
  count?: number;
34
34
  /** A substring the RESPONSE body must contain — what the server answered, not what was sent. */
35
35
  bodyContains?: string;
36
+ /** Shallow JSON match over the RESPONSE body: this FIELD holds this value (#987). */
37
+ bodyMatches?: Record<string, unknown>;
36
38
  /** A substring the REQUEST body must contain — what the UI sent, not what came back. */
37
39
  requestBodyContains?: string;
38
40
  /** Shallow JSON match over the REQUEST body, in the style of `signal.dataMatches`. */
@@ -21,7 +21,7 @@ const PREDICATE_ALIASES = {
21
21
  // contains this" is precisely what it does — and asserting a redirect after login is the single
22
22
  // most common thing an agent reaches for here.
23
23
  [PredicateKind.ROUTE]: { path: 'pathname', urlContains: 'contains', url: 'contains' },
24
- [PredicateKind.NET]: { url: 'urlContains' },
24
+ [PredicateKind.NET]: { url: 'urlContains', responseBodyMatches: 'bodyMatches' },
25
25
  // `textContains` on a `console` predicate: the reporter who hit the missing matcher reached for
26
26
  // it first, by analogy with `net { urlContains }` — and that parallel is exactly right, since
27
27
  // both mean "this entry must contain this substring". Accepted as an alias for `contains`.
@@ -266,6 +266,27 @@ function predicateUnion() {
266
266
  * was never recorded rather than reporting an ordinary mismatch.
267
267
  */
268
268
  bodyContains: z.string().min(1).optional(),
269
+ /**
270
+ * Shallow JSON match over the RESPONSE body, keyed like `signal.dataMatches` and sharing its
271
+ * `matchValue` operators (`*`, `$gte`, `$contains`, …) — the field-level half of
272
+ * `bodyContains` (#987).
273
+ *
274
+ * `bodyContains` is a substring test, and the comment above says why that shape was chosen.
275
+ * It leaves one assertion unsayable: "this FIELD holds this value". Reported from the field
276
+ * as the only false green in that export — `bodyContains: "completed"` returned
277
+ * `verified: "yes"` for a job whose status was `queued`, because the body carried
278
+ * `"completedAt": null` and the needle matched the KEY. An enum state in a JSON response is
279
+ * the natural reach for a substring and the one thing a substring cannot decide:
280
+ * `completed`/`completedAt`, `success`/`successRate`, `sent`/`unsent`.
281
+ *
282
+ * `{ bodyMatches: { status: "completed" } }` cannot be satisfied by a key name, by a longer
283
+ * sibling value, or by key order, whitespace and serialisation — all of which a substring
284
+ * answers to. Use `bodyContains` for a non-JSON body, or when the substring IS the claim.
285
+ *
286
+ * A field whose captured value was REDACTED cannot be matched, and the verdict says so
287
+ * instead of reporting a mismatch: a redacted field is unknown, not different.
288
+ */
289
+ bodyMatches: z.record(z.string(), z.unknown()).optional(),
269
290
  /**
270
291
  * A substring the REQUEST body must contain — the other half of `bodyContains`.
271
292
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/engine",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "The rules that decide a verdict: read what happened in a running app and say whether the declared consequence held. No browser, no daemon, no command line - an implementation of the OpenVerification specification you can use on its own.",
5
5
  "keywords": [
6
6
  "verification",
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "zod": "^3.24.1",
59
- "@reticlehq/core": "3.1.0"
59
+ "@reticlehq/core": "3.2.0"
60
60
  },
61
61
  "devDependencies": {
62
62
  "open-verification": "1.0.0"