@reticlehq/engine 3.1.0 → 3.3.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 (42) hide show
  1. package/dist/disagreement/body-failures.js +32 -12
  2. package/dist/disagreement/contradiction-evidence.d.ts +1 -1
  3. package/dist/disagreement/contradiction-evidence.js +3 -3
  4. package/dist/disagreement/contradiction-types.d.ts +6 -0
  5. package/dist/disagreement/contradictions.js +101 -50
  6. package/dist/evidence/already-true.js +9 -2
  7. package/dist/evidence/baseline.d.ts +21 -0
  8. package/dist/evidence/baseline.js +129 -0
  9. package/dist/evidence/body-capture-remedy.js +6 -1
  10. package/dist/evidence/honesty.d.ts +10 -0
  11. package/dist/evidence/honesty.js +4 -0
  12. package/dist/evidence/verified.d.ts +7 -0
  13. package/dist/evidence/verified.js +35 -1
  14. package/dist/question/declared.js +2 -1
  15. package/dist/question/lineage.d.ts +14 -5
  16. package/dist/question/lineage.js +65 -10
  17. package/dist/question/predicate/body-key-fragment.d.ts +25 -0
  18. package/dist/question/predicate/body-key-fragment.js +57 -0
  19. package/dist/question/predicate/predicate-element.d.ts +3 -2
  20. package/dist/question/predicate/predicate-element.js +68 -3
  21. package/dist/question/predicate/predicate-eval-kit.d.ts +21 -0
  22. package/dist/question/predicate/predicate-eval-kit.js +28 -1
  23. package/dist/question/predicate/predicate-eval.d.ts +6 -0
  24. package/dist/question/predicate/predicate-eval.js +89 -26
  25. package/dist/question/predicate/predicate-precheck.d.ts +7 -0
  26. package/dist/question/predicate/predicate-precheck.js +81 -0
  27. package/dist/question/predicate/predicate-request-body.d.ts +1 -1
  28. package/dist/question/predicate/predicate-request-body.js +10 -19
  29. package/dist/question/predicate/predicate-route.d.ts +2 -1
  30. package/dist/question/predicate/predicate-schema.d.ts +12 -91
  31. package/dist/question/predicate/predicate-schema.js +15 -267
  32. package/dist/question/predicate/predicate-session.d.ts +15 -1
  33. package/dist/question/predicate/predicate-session.js +25 -1
  34. package/dist/question/predicate/predicate-state.d.ts +15 -0
  35. package/dist/question/predicate/predicate-state.js +317 -0
  36. package/dist/question/predicate/predicate.d.ts +17 -3
  37. package/dist/question/predicate/predicate.js +139 -328
  38. package/dist/question/predicate/property.d.ts +24 -73
  39. package/dist/question/predicate/property.js +134 -20
  40. package/dist/window/json-salvage.d.ts +2 -1
  41. package/dist/window/json-salvage.js +2 -1
  42. package/package.json +2 -2
@@ -16,18 +16,26 @@
16
16
  * one thing a correlation cannot justify;
17
17
  * - no candidate says the value was not seen to pass through one, and reaches for nothing.
18
18
  *
19
+ * One more source, read rather than recomputed: the SDK stamps `actionId` + `attribution` onto every
20
+ * event observed while a driven action is active (see `core/messages.ts`). That is a time-window
21
+ * heuristic too — `EventAttribution.WINDOW`'s own comment says so — but it is the same tier, already
22
+ * computed, already labelled, and narrower than a fresh look-back, so the join reads it two ways:
23
+ * a candidate stamped with a DIFFERENT act is not a candidate for this one (the stamp rules out; it
24
+ * never rules in), and a stamped change with no signal behind it names the act rather than calling
25
+ * its cause "not in evidence" when the evidence is on the event (#939).
26
+ *
19
27
  * Read-only. Produces no verdict, is not reachable from an assert path, and changes nothing.
20
28
  */
21
29
  import { type ReticleEvent } from '@reticlehq/core';
22
30
  /** What the caller is asking about. `value` narrows a path that changed more than once. */
23
- export interface LineageQuery {
31
+ interface LineageQuery {
24
32
  path: string;
25
33
  value?: string;
26
34
  }
27
35
  /** One line of the chain, with the confidence that produced it. */
28
- export interface LineageLink {
29
- /** Which stream this came from. */
30
- kind: 'state' | 'signal' | 'net';
36
+ interface LineageLink {
37
+ /** Which stream this came from. `act` is the driven action the event was stamped with. */
38
+ kind: 'state' | 'act' | 'signal' | 'net';
31
39
  /** The rendered line, already carrying its own hedge. */
32
40
  text: string;
33
41
  /** True only when this is an event we hold. A join is never observed. */
@@ -35,7 +43,7 @@ export interface LineageLink {
35
43
  /** Every candidate, when more than one could explain the link. Present only when ambiguous. */
36
44
  candidates?: string[];
37
45
  }
38
- export interface Lineage {
46
+ interface Lineage {
39
47
  /** False when the path was never seen to change — a different answer from an empty chain. */
40
48
  found: boolean;
41
49
  chain: LineageLink[];
@@ -50,3 +58,4 @@ export interface Lineage {
50
58
  * claim.
51
59
  */
52
60
  export declare function traceLineage(events: readonly ReticleEvent[], query: LineageQuery): Lineage;
61
+ export {};
@@ -16,6 +16,14 @@
16
16
  * one thing a correlation cannot justify;
17
17
  * - no candidate says the value was not seen to pass through one, and reaches for nothing.
18
18
  *
19
+ * One more source, read rather than recomputed: the SDK stamps `actionId` + `attribution` onto every
20
+ * event observed while a driven action is active (see `core/messages.ts`). That is a time-window
21
+ * heuristic too — `EventAttribution.WINDOW`'s own comment says so — but it is the same tier, already
22
+ * computed, already labelled, and narrower than a fresh look-back, so the join reads it two ways:
23
+ * a candidate stamped with a DIFFERENT act is not a candidate for this one (the stamp rules out; it
24
+ * never rules in), and a stamped change with no signal behind it names the act rather than calling
25
+ * its cause "not in evidence" when the evidence is on the event (#939).
26
+ *
19
27
  * Read-only. Produces no verdict, is not reachable from an assert path, and changes nothing.
20
28
  */
21
29
  import { EventType } from '@reticlehq/core';
@@ -41,9 +49,39 @@ function stateChangesFor(events, query) {
41
49
  return String(e.data['value']) === query.value;
42
50
  });
43
51
  }
44
- /** Events of one kind inside the causal window before `t`, oldest first. */
45
- function precursors(events, type, t) {
46
- return events.filter((e) => e.type === type && e.t < t && e.t >= t - CAUSE_WINDOW_MS);
52
+ /**
53
+ * Events of one kind inside the causal window before `t`, oldest first.
54
+ *
55
+ * When the change being traced carries an `actionId`, a candidate stamped with a DIFFERENT one is
56
+ * dropped: the SDK observed it under another driven action, and five seconds spans several of
57
+ * those. An UNSTAMPED candidate stays. A request fired just before dispatch carries no stamp and its
58
+ * response can still land inside the act — the stamp proves an event belongs elsewhere, it cannot
59
+ * prove an unstamped one is unrelated. Rules out, never rules in.
60
+ */
61
+ function precursors(events, type, t, actionId) {
62
+ return events.filter((e) => e.type === type &&
63
+ e.t < t &&
64
+ e.t >= t - CAUSE_WINDOW_MS &&
65
+ (actionId === undefined || e.actionId === undefined || e.actionId === actionId));
66
+ }
67
+ /**
68
+ * The link from a stamped change to the act that was active when it was observed.
69
+ *
70
+ * Rendered from the tier the event carries, not asserted: `attribution` is present iff `actionId`
71
+ * is, and today there is one tier. It is not an observation — the SDK stamped an id across a span
72
+ * of time — and the text says what that span is, so a reader who acts on the arrow has been told
73
+ * what the arrow is worth.
74
+ */
75
+ function actLink(actionId, attribution) {
76
+ // Rendered from the tier the EVENT carries, never from a constant of our own. The schema says
77
+ // `attribution` is present iff `actionId` is, so on this path it always is; the guard against
78
+ // its absence exists so a contract slip renders a shorter sentence rather than a wrong one.
79
+ const tier = attribution === undefined ? '' : ` — ${attribution} tier`;
80
+ return {
81
+ kind: 'act',
82
+ text: `← attributed to action ${actionId}${tier}: the SDK stamped this action's id on every event between its dispatch and settle. A time window, not dataflow.`,
83
+ observed: false,
84
+ };
47
85
  }
48
86
  /**
49
87
  * Render an inferred link, hedged according to how many things could explain it.
@@ -97,19 +135,36 @@ export function traceLineage(events, query) {
97
135
  observed: true,
98
136
  },
99
137
  ];
100
- const signals = precursors(events, EventType.SIGNAL, latest.t);
138
+ const actionId = latest.actionId;
139
+ const signals = precursors(events, EventType.SIGNAL, latest.t, actionId);
101
140
  if (0 === signals.length) {
102
- return {
103
- found: true,
104
- chain,
105
- note: 'No signal fired in the window before this change, so the value was not seen to pass through one. Nothing further is claimed — the change is real, its cause is not in evidence.',
106
- };
141
+ if (actionId === undefined) {
142
+ return {
143
+ found: true,
144
+ chain,
145
+ note: 'No signal fired in the window before this change, so the value was not seen to pass through one. Nothing further is claimed — the change is real, its cause is not in evidence.',
146
+ };
147
+ }
148
+ // The common case: `reticle.signal()` is a call the APP must make, and most apps never do. But
149
+ // this change was observed under a driven action, and that is on the event. Saying its cause is
150
+ // "not in evidence" would be a factual claim, and a false one.
151
+ chain.push(actLink(actionId, latest.attribution));
152
+ const driven = precursors(events, EventType.NET_REQUEST, latest.t, actionId);
153
+ if (0 === driven.length) {
154
+ return {
155
+ found: true,
156
+ chain,
157
+ note: 'No signal fired, and no request in the window carries this action or none at all, so the chain stops at the act rather than joining across a gap in the evidence.',
158
+ };
159
+ }
160
+ chain.push(inferredLink('net', driven.map(netLabel)));
161
+ return { found: true, chain };
107
162
  }
108
163
  chain.push(inferredLink('signal', signals.map(signalLabel)));
109
164
  // Anchored on the OLDEST candidate signal: a request that preceded any of them could have produced
110
165
  // it, and narrowing to the newest would quietly discard candidates for the link below.
111
166
  const anchor = signals[0]?.t ?? latest.t;
112
- const calls = precursors(events, EventType.NET_REQUEST, anchor);
167
+ const calls = precursors(events, EventType.NET_REQUEST, anchor, actionId);
113
168
  if (0 === calls.length) {
114
169
  return {
115
170
  found: true,
@@ -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
+ }
@@ -6,8 +6,9 @@
6
6
  * back (`residualQueryChecks`), the absent/present asymmetry, and the near-miss diagnostics that only
7
7
  * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
8
  */
9
- import { type ElementQuery, type ElementState, type MatchResult } from '@reticlehq/core';
9
+ import { type ElementQuery, type ElementState } from '@reticlehq/core';
10
10
  import { type EvalResult } from './predicate-eval.js';
11
11
  import type { PredicateSession } from './predicate-session.js';
12
- export declare function matchOnce(session: PredicateSession, query: ElementQuery, state: ElementState | undefined): Promise<MatchResult>;
12
+ import { type Baseline, type PropertyAssertion } from './property.js';
13
13
  export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean): Promise<EvalResult>;
14
+ export declare function withTextProperty(base: EvalResult, assertion: PropertyAssertion, subject: string, baseline?: Baseline): EvalResult;
@@ -10,7 +10,20 @@ import { ReticleCommand, } from '@reticlehq/core';
10
10
  import { residualQueryChecks, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
11
11
  import { describeTestidMiss } from './testid-near-miss.js';
12
12
  import { describeSplitTextMiss } from './split-text-miss.js';
13
- export async function matchOnce(session, query, state) {
13
+ import { satisfiesProperty } from './property.js';
14
+ /**
15
+ * The caveat for a present-testid list that was cut at its cap, or nothing when it was whole.
16
+ *
17
+ * Phrased as what the list IS — "the first N of M in document order" — rather than as an apology,
18
+ * because the agent's next move depends on knowing the shape: a region absent from a capped list is
19
+ * unexamined, not absent. Empty when nothing was cut, so an ordinary miss keeps the message it had.
20
+ */
21
+ function describePresentTestidsCut(shown, total) {
22
+ if (total === undefined || total <= shown)
23
+ return '';
24
+ return ` (the present-testid list shows the first ${String(shown)} of ${String(total)} in document order — absence from it proves nothing)`;
25
+ }
26
+ async function matchOnce(session, query, state) {
14
27
  const res = await session.command(ReticleCommand.MATCH, { query, state });
15
28
  if (!res.ok)
16
29
  return { matched: false, count: 0, elements: [] };
@@ -203,12 +216,64 @@ export async function evalElement(session, query, state, absent, diagnose) {
203
216
  const splitText = describeSplitTextMiss(match.hint?.splitText, query.text);
204
217
  const clause = splitText ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
205
218
  const suffix = clause === undefined ? '' : ` — ${clause}`;
219
+ // The evidence list is capped in document order, so a region low on the page is exactly what it
220
+ // drops. Handed back with no marker it reads as the whole page, and the field report this came
221
+ // from read a missing detail panel as proof the panel never rendered. Say the cut happened (#793).
222
+ const total = match.hint?.presentTestidsTotal;
223
+ const cut = describePresentTestidsCut(present.length, total);
206
224
  return {
207
225
  pass: false,
208
- failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}`,
226
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}${cut}`,
209
227
  observed: `no matching element on the page${suffix}`,
210
228
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
211
229
  assertion: 'element.present',
212
- ...(present.length > 0 ? { evidence: { presentTestids: present } } : {}),
230
+ ...(present.length > 0
231
+ ? {
232
+ evidence: {
233
+ presentTestids: present,
234
+ ...(total === undefined ? {} : { presentTestidsTotal: total }),
235
+ },
236
+ }
237
+ : {}),
238
+ };
239
+ }
240
+ /**
241
+ * Narrow a passing text match with a PROPERTY of the text it found.
242
+ *
243
+ * Sits here rather than in the evaluator because the descriptors it reads are this module's own
244
+ * output shape, and because it must run only over a match that already held: a property asserted
245
+ * against the text of an element that is not there is a statement about nothing.
246
+ *
247
+ * Several matches are JOINED before the property runs. `scope` + `self` reads one subtree and is
248
+ * the shape this is for; a locator broad enough to return several is asking about the text they
249
+ * make together, and testing only the first would pass on a page where the rest is the failure.
250
+ */
251
+ /** The text an element descriptor reported, or ''. Never `String(unknown)` — see `show` in property.ts. */
252
+ function textOf(element) {
253
+ if ('object' !== typeof element || null === element)
254
+ return '';
255
+ const value = element.text;
256
+ return 'string' === typeof value ? value : '';
257
+ }
258
+ export function withTextProperty(base, assertion, subject, baseline) {
259
+ if (!base.pass)
260
+ return base;
261
+ const described = Array.isArray(base.evidence) ? base.evidence : [];
262
+ const text = described.map(textOf).join(' ').trim();
263
+ const result = satisfiesProperty(text, assertion, baseline);
264
+ // Nothing was compared — a relative property with no before-reading. See the twin in `evalState`.
265
+ if (true === result.unevaluated) {
266
+ return { pass: false, failureReason: result.because, inconclusive: result.because };
267
+ }
268
+ if (result.ok) {
269
+ return { pass: true, evidence: { ...{ matched: described }, satisfied: result.because } };
270
+ }
271
+ return {
272
+ pass: false,
273
+ failureReason: `text of ${subject} ${result.because}`,
274
+ observed: `text of ${subject} = ${JSON.stringify(text)}`,
275
+ expected: `text of ${subject} to satisfy ${assertion.property}`,
276
+ assertion: `text.${assertion.property}`,
277
+ evidence: described,
213
278
  };
214
279
  }
@@ -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.
@@ -4,6 +4,12 @@ import type { Predicate } from './predicate-schema.js';
4
4
  import { type EvalResult } from './predicate-eval-kit.js';
5
5
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, type EvalResult, } from './predicate-eval-kit.js';
6
6
  export * from './predicate-schema.js';
7
+ /**
8
+ * Whether a request was a subresource the DOCUMENT fetched (script, stylesheet, image…), as the
9
+ * resource-timing observer stamps them, rather than one the app sent through fetch, XHR, a beacon or
10
+ * IPC. The capsule's blast radius uses it to keep a page load out of "what this action also did".
11
+ */
12
+ export declare function isDocumentInitiated(event: ReticleEvent): boolean;
7
13
  export declare function evalNet(events: ReticleEvent[], p: Extract<Predicate, {
8
14
  kind: typeof PredicateKind.NET;
9
15
  }>): EvalResult;
@@ -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.
@@ -219,6 +220,17 @@ const DOCUMENT_INITIATORS = new Set([
219
220
  'manifest',
220
221
  'other',
221
222
  ]);
223
+ /**
224
+ * Whether a request was a subresource the DOCUMENT fetched (script, stylesheet, image…), as the
225
+ * resource-timing observer stamps them, rather than one the app sent through fetch, XHR, a beacon or
226
+ * IPC. The capsule's blast radius uses it to keep a page load out of "what this action also did".
227
+ */
228
+ export function isDocumentInitiated(event) {
229
+ if (event.type !== EventType.NET_REQUEST)
230
+ return false;
231
+ const initiator = str(event.data['initiator']);
232
+ return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
233
+ }
222
234
  /**
223
235
  * Did the observer actually report a document-initiated load?
224
236
  *
@@ -231,12 +243,7 @@ const DOCUMENT_INITIATORS = new Set([
231
243
  * document-initiated record anywhere in the window proves the channel works.
232
244
  */
233
245
  function observerSawSubresources(events) {
234
- return events.some((e) => {
235
- if (e.type !== EventType.NET_REQUEST)
236
- return false;
237
- const initiator = str(e.data['initiator']);
238
- return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
239
- });
246
+ return events.some(isDocumentInitiated);
240
247
  }
241
248
  /** The sentence both zero-match branches hand to `inconclusive`. */
242
249
  function unobservedChannelReason(p) {
@@ -276,6 +283,16 @@ function unobservedChannelReason(p) {
276
283
  const PRE_ATTACH_CAVEAT = ' — note that this window starts where the SDK attached, and requests made before that are never ' +
277
284
  'captured, so a miss here cannot tell a call that was never made apart from one made before the ' +
278
285
  'page connected; if the call is expected during startup, assert on the state it produces instead';
286
+ /**
287
+ * The response-body clause as the caller wrote it, for a verdict that has to quote it.
288
+ *
289
+ * One expression rather than two, because every body verdict below is the same sentence whichever
290
+ * clause asked the question, and printing `undefined` where the clause was `bodyMatches` is how a
291
+ * verdict stops being readable.
292
+ */
293
+ function wantedBody(p) {
294
+ return JSON.stringify(p.bodyContains ?? p.bodyMatches);
295
+ }
279
296
  export function evalNet(events, p) {
280
297
  const since = p.since ?? 0;
281
298
  /**
@@ -309,6 +326,15 @@ export function evalNet(events, p) {
309
326
  * a truncated one cannot (#614).
310
327
  */
311
328
  let truncatedBody;
329
+ /**
330
+ * A `bodyContains` needle that was FOUND, and found only inside a key name (#987).
331
+ *
332
+ * Not a match and not a miss: the substring is there, and it supports no claim about any value.
333
+ * Held with the body it was found in, because the verdict has to show both.
334
+ */
335
+ let keyFragment;
336
+ /** A response key whose captured value is `[REDACTED]`, so a `bodyMatches` clause is unjudgeable. */
337
+ let redactedResponseField;
312
338
  const requestState = newRequestBodyState();
313
339
  const matches = events.filter((e) => {
314
340
  if (e.type !== EventType.NET_REQUEST || e.t < since)
@@ -335,28 +361,45 @@ export function evalNet(events, p) {
335
361
  }
336
362
  if (p.ok !== undefined && callSucceeded(d) !== p.ok)
337
363
  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.
364
+ if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
365
+ // The RESPONSE body only, and this is the whole point of these fields. Searching the request
366
+ // too would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app
367
+ // SENT that number, so it is in the request whatever the server then did with it. The server's
368
+ // answer is the one channel a UI cannot fake.
343
369
  const response = str(d['responseBody']);
344
370
  if (response === undefined) {
345
371
  matchedButUnrecorded = true;
346
372
  return false;
347
373
  }
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']) {
374
+ // A needle missing from a body we only hold the FIRST N BYTES of is undecidable, not absent:
375
+ // the rest of the response was never recorded, so nothing here can say whether it was in
376
+ // there (#614). Grading it `pass: false` with "the response value is what differed" is the
377
+ // inversion the honesty rules exist to prevent — an unknown reported as decided, against a
378
+ // response that was very likely correct.
379
+ const missed = () => {
380
+ if (true === d['responseBodyTruncated'])
355
381
  truncatedBody ??= response;
382
+ else
383
+ bodyMismatch ??= response;
384
+ return false;
385
+ };
386
+ if (p.bodyContains !== undefined) {
387
+ if (!response.includes(p.bodyContains))
388
+ return missed();
389
+ const fragment = keyFragmentOnly(response, p.bodyContains);
390
+ if (fragment !== undefined) {
391
+ keyFragment ??= { key: fragment, body: response };
392
+ return false;
393
+ }
394
+ }
395
+ if (p.bodyMatches !== undefined) {
396
+ const verdict = matchJsonBody(response, p.bodyMatches);
397
+ if ('mismatch' === verdict)
398
+ return missed();
399
+ if ('match' !== verdict) {
400
+ redactedResponseField ??= verdict.redacted;
356
401
  return false;
357
402
  }
358
- bodyMismatch ??= response;
359
- return false;
360
403
  }
361
404
  }
362
405
  if (!checkRequestBody(d, p, requestState))
@@ -380,10 +423,30 @@ export function evalNet(events, p) {
380
423
  pass: false,
381
424
  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
425
  observed: 'a matching call with no recorded body',
383
- expected: `a body containing ${JSON.stringify(p.bodyContains)}`,
426
+ expected: `a body carrying ${wantedBody(p)}`,
427
+ assertion: 'net.bodyContains',
428
+ };
429
+ }
430
+ if (keyFragment !== undefined && 0 === matches.length) {
431
+ // Ranked above every other body verdict, because it is the only one that used to be a PASS.
432
+ return {
433
+ pass: false,
434
+ 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> }\``,
435
+ observed: `response body ${JSON.stringify(clipBody(keyFragment.body))}`,
436
+ expected: `a response body carrying ${JSON.stringify(p.bodyContains)} as a value, or as a whole key`,
384
437
  assertion: 'net.bodyContains',
385
438
  };
386
439
  }
440
+ if (redactedResponseField !== undefined && 0 === matches.length) {
441
+ const field = JSON.stringify(redactedResponseField);
442
+ return {
443
+ pass: false,
444
+ 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`,
445
+ observed: `a matching response whose ${field} is ${REDACTED_VALUE}`,
446
+ expected: `a response body matching ${JSON.stringify(p.bodyMatches)}`,
447
+ assertion: 'net.bodyMatches',
448
+ };
449
+ }
387
450
  const requestVerdict = requestBodyVerdict(requestState, p, matches.length);
388
451
  if (requestVerdict !== undefined)
389
452
  return requestVerdict;
@@ -393,9 +456,9 @@ export function evalNet(events, p) {
393
456
  if (truncatedBody !== undefined && 0 === matches.length) {
394
457
  return {
395
458
  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`,
459
+ 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. The cap is per-body and set where the app calls connect(): \`reticle.connect({ captureNetworkBodies: true, networkBodyMaxChars: 65536 })\`, or for the Vite plugin \`reticle({ networkBodyMaxChars: 65536 })\` / VITE_RETICLE_BODY_MAX_CHARS=65536 (default 8192, max 262144). An SDK older than this daemon ignores the option; a version skew on the session says so. Raise it past this response's size and re-run, or assert on something inside the recorded prefix`,
397
460
  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)}`,
461
+ expected: `a response body carrying ${wantedBody(p)}`,
399
462
  assertion: 'net.bodyContains',
400
463
  };
401
464
  }
@@ -404,9 +467,9 @@ export function evalNet(events, p) {
404
467
  // points at the wiring, which is the one place the defect is not.
405
468
  return {
406
469
  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`,
470
+ 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
471
  observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}`,
409
- expected: `a response body containing ${JSON.stringify(p.bodyContains)}`,
472
+ expected: `a response body carrying ${wantedBody(p)}`,
410
473
  assertion: 'net.bodyContains',
411
474
  };
412
475
  }
@@ -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;