@reticlehq/engine 3.2.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 (32) 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 +4 -2
  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/verified.d.ts +7 -0
  10. package/dist/evidence/verified.js +35 -1
  11. package/dist/question/declared.js +2 -1
  12. package/dist/question/lineage.d.ts +14 -5
  13. package/dist/question/lineage.js +65 -10
  14. package/dist/question/predicate/predicate-element.d.ts +3 -2
  15. package/dist/question/predicate/predicate-element.js +68 -3
  16. package/dist/question/predicate/predicate-eval.d.ts +6 -0
  17. package/dist/question/predicate/predicate-eval.js +13 -7
  18. package/dist/question/predicate/predicate-request-body.d.ts +1 -1
  19. package/dist/question/predicate/predicate-route.d.ts +2 -1
  20. package/dist/question/predicate/predicate-schema.d.ts +12 -93
  21. package/dist/question/predicate/predicate-schema.js +15 -288
  22. package/dist/question/predicate/predicate-session.d.ts +15 -1
  23. package/dist/question/predicate/predicate-session.js +25 -1
  24. package/dist/question/predicate/predicate-state.d.ts +15 -0
  25. package/dist/question/predicate/predicate-state.js +317 -0
  26. package/dist/question/predicate/predicate.d.ts +17 -3
  27. package/dist/question/predicate/predicate.js +139 -328
  28. package/dist/question/predicate/property.d.ts +24 -73
  29. package/dist/question/predicate/property.js +134 -20
  30. package/dist/window/json-salvage.d.ts +2 -1
  31. package/dist/window/json-salvage.js +2 -1
  32. package/package.json +2 -2
@@ -27,6 +27,36 @@ const ITEM_KEYS = ['results', 'items', 'data', 'records', 'responses'];
27
27
  function isRecord(value) {
28
28
  return 'object' === typeof value && value !== null && !Array.isArray(value);
29
29
  }
30
+ /**
31
+ * Whether the value under an error key carries an actual error.
32
+ *
33
+ * An API that always sends its error slot and leaves it EMPTY is saying the opposite of a failure,
34
+ * and every empty shape below was being read as one — because the test was the key's PRESENCE, with
35
+ * `[]` and `''` carved out by hand and nothing else. Reported from the field on a 200 whose error
36
+ * container was empty: `verified: "no"`, "its body reports the operation FAILED", nothing in the
37
+ * body reporting anything of the kind.
38
+ *
39
+ * `false` and `0` are the two that look like judgement calls and are not. `{"error": false}` is the
40
+ * envelope flag for "there was none" — the exact dual of the `ok`/`success` flags read above — and
41
+ * an errno-style `{"error": 0}` spells the same thing; under the plural key, `{"errors": 0}` is a
42
+ * count of none. Each says "none" in both available readings, and the non-empty side of each is
43
+ * untouched: a populated map, a non-zero code, `error: true` and a real message all still report.
44
+ */
45
+ function carriesError(value) {
46
+ if (value === undefined || null === value)
47
+ return false;
48
+ if (Array.isArray(value))
49
+ return value.length > 0;
50
+ if ('string' === typeof value)
51
+ return value.trim().length > 0;
52
+ if ('boolean' === typeof value)
53
+ return value;
54
+ if ('number' === typeof value)
55
+ return 0 !== value;
56
+ if (isRecord(value))
57
+ return Object.keys(value).length > 0;
58
+ return true;
59
+ }
30
60
  /** Whether one object reports a failure of its own. */
31
61
  function reportsFailure(item) {
32
62
  if (!isRecord(item))
@@ -36,18 +66,8 @@ function reportsFailure(item) {
36
66
  return true;
37
67
  }
38
68
  for (const key of ERROR_KEYS) {
39
- const value = item[key];
40
- if (value === undefined || null === value)
41
- continue;
42
- if (Array.isArray(value)) {
43
- if (value.length > 0)
44
- return true;
45
- continue;
46
- }
47
- // An empty string or an explicit null is an API saying "no error", not an error.
48
- if ('string' === typeof value && 0 === value.length)
49
- continue;
50
- return true;
69
+ if (carriesError(item[key]))
70
+ return true;
51
71
  }
52
72
  return false;
53
73
  }
@@ -76,7 +76,7 @@ export declare function isSameDocumentHashAnchor(event: ReticleEvent): boolean;
76
76
  * every action. The overlay's own 404s and duplicate fetches are the same story on other checks,
77
77
  * which is why the split happens ONCE here rather than in the one check that reported it.
78
78
  */
79
- export declare function splitForeignTraffic(events: readonly ReticleEvent[], appOrigin: string | undefined): {
79
+ export declare function splitForeignTraffic(events: readonly ReticleEvent[], appOrigin: string | undefined, background?: readonly string[]): {
80
80
  app: readonly ReticleEvent[];
81
81
  ignored: string[];
82
82
  };
@@ -11,7 +11,7 @@
11
11
  * new rule cannot quietly redefine what "in flight" or "ours" means for itself, which is how two
12
12
  * rules end up disagreeing about the same window.
13
13
  */
14
- import { EventType, MUTATING_METHODS, asNumber, asString, isDevToolingUrl, isThirdPartyUrl, urlForMatch, } from '@reticlehq/core';
14
+ import { EventType, MUTATING_METHODS, asNumber, asString, isDevToolingUrl, isForeignTraffic, urlForMatch, } from '@reticlehq/core';
15
15
  export function netCall(e) {
16
16
  const status = asNumber(e.data['status']);
17
17
  return {
@@ -124,7 +124,7 @@ export function isSameDocumentHashAnchor(event) {
124
124
  * every action. The overlay's own 404s and duplicate fetches are the same story on other checks,
125
125
  * which is why the split happens ONCE here rather than in the one check that reported it.
126
126
  */
127
- export function splitForeignTraffic(events, appOrigin) {
127
+ export function splitForeignTraffic(events, appOrigin, background = []) {
128
128
  const ignored = [];
129
129
  const app = events.filter((e) => {
130
130
  if (!NET_TYPES.has(e.type))
@@ -132,7 +132,7 @@ export function splitForeignTraffic(events, appOrigin) {
132
132
  const url = asString(e.data['url']);
133
133
  // Somebody else's code, twice over: the toolchain's own channel, and any site that is not the
134
134
  // app under test. Neither can answer the question every rule below asks.
135
- if (!isDevToolingUrl(url) && !isThirdPartyUrl(url, appOrigin))
135
+ if (!isDevToolingUrl(url) && !isForeignTraffic(url, appOrigin, background))
136
136
  return true;
137
137
  if (url !== undefined && !ignored.includes(url))
138
138
  ignored.push(url);
@@ -151,6 +151,12 @@ export interface ContradictionOptions {
151
151
  * one: a caller that cannot say which page is under test gets the behaviour it had before this.
152
152
  */
153
153
  appOrigin?: string | undefined;
154
+ /**
155
+ * Same-origin endpoints the project declared the app fires on its own (`.reticle.json`
156
+ * `background`). Dropped with the third-party traffic and disclosed the same way; empty or
157
+ * undefined excludes nothing, because same-origin traffic is never guessed at.
158
+ */
159
+ background?: readonly string[] | undefined;
154
160
  /**
155
161
  * The traffic the assertion actually named — `urlContains` from each net clause, `''` for a clause
156
162
  * that named the whole channel.
@@ -193,7 +193,7 @@ export function findContradictions(allEvents, options = {}) {
193
193
  }
194
194
  function findWindowContradictions(allEvents, options) {
195
195
  const found = [];
196
- const { app: allApp, ignored: ignoredForeign } = splitForeignTraffic(allEvents, options.appOrigin);
196
+ const { app: allApp, ignored: ignoredForeign } = splitForeignTraffic(allEvents, options.appOrigin, options.background);
197
197
  // ── Evidence belonging to a document that has since been replaced ───────────────────────────
198
198
  // Scoped ONCE, here, for the same reason the dev-tooling split is: every rule below asks "what
199
199
  // else was in this window", and answering that with a dead page's traffic is a defect in all of
@@ -651,7 +651,9 @@ function findWindowContradictions(allEvents, options) {
651
651
  inFlight.map((p) => describe(p.call)).join('; '),
652
652
  ...(0 === ignoredForeign.length
653
653
  ? []
654
- : [`ignored as dev tooling or third-party: ${ignoredForeign.join(', ')}`]),
654
+ : [
655
+ `ignored as dev tooling, third-party or declared background: ${ignoredForeign.join(', ')}`,
656
+ ]),
655
657
  ].join(' — '),
656
658
  });
657
659
  }
@@ -17,6 +17,7 @@
17
17
  * anything.
18
18
  */
19
19
  import { PredicateKind } from '@reticlehq/core';
20
+ import { asksForComparison } from './baseline.js';
20
21
  export function readsDomState(predicate) {
21
22
  switch (predicate.kind) {
22
23
  // ROUTE is here, and it did not used to be. It was purely event-based — satisfiable only by a
@@ -38,10 +39,16 @@ export function readsDomState(predicate) {
38
39
  // rather than through the floored event buffer. If the store already holds the expected value
39
40
  // before dispatch, an inert click would immediately pass post-dispatch on the pre-existing state.
40
41
  // Evaluating before dispatch routes that pre-existing condition into already_true.
41
- case PredicateKind.ELEMENT:
42
+ //
43
+ // A RELATIVE property is the one exception, and it is excluded by construction rather than by
44
+ // taste: `unchanged` compares this reading with the one taken a microsecond ago and is
45
+ // therefore always true before the action. Pre-checking it would report `already_true` — and
46
+ // so UNKNOWN — for the assertion whose whole purpose is that the value survives what follows.
42
47
  case PredicateKind.TEXT:
43
- case PredicateKind.ROUTE:
44
48
  case PredicateKind.STATE:
49
+ return !asksForComparison(predicate);
50
+ case PredicateKind.ELEMENT:
51
+ case PredicateKind.ROUTE:
45
52
  return true;
46
53
  case PredicateKind.ALL_OF:
47
54
  case PredicateKind.ANY_OF:
@@ -0,0 +1,21 @@
1
+ import type { Predicate } from '../question/predicate/predicate.js';
2
+ import type { Baseline } from '../question/predicate/property.js';
3
+ import type { PredicateSession } from '../question/predicate/predicate-session.js';
4
+ /**
5
+ * Does this leaf's claim compare two readings?
6
+ *
7
+ * Exported because `readsDomState` has to exclude exactly these. A relative property is NEVER
8
+ * answerable before the action — `unchanged` is trivially true against a baseline taken a
9
+ * microsecond earlier — so pre-checking one would report `already_true` for the assertion whose
10
+ * entire purpose is that the value survives what comes next, and turn its verdict into UNKNOWN.
11
+ */
12
+ export declare function asksForComparison(predicate: Predicate): boolean;
13
+ /** Does the whole tree need a pre-action reading at all? One walk, so the caller pays nothing. */
14
+ export declare function needsBaseline(predicate: Predicate | undefined): boolean;
15
+ /**
16
+ * Read what every comparing leaf needs, once, before the action.
17
+ *
18
+ * Keyed by the predicate OBJECT: the same parsed tree is evaluated before and after, so identity
19
+ * is exact and no path or index has to be kept in step with the walk.
20
+ */
21
+ export declare function captureBaselines(session: PredicateSession, predicate: Predicate | undefined): Promise<ReadonlyMap<Predicate, Baseline>>;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The reading taken BEFORE the action, so a predicate can talk about the past.
3
+ *
4
+ * Every leaf in the grammar read the present tense — the DOM now, the store now, the events since a
5
+ * cursor — so the assertions that catch money bugs could not be written: the balance went down by
6
+ * what was charged, the list gained three rows, this field held its value across the re-render.
7
+ *
8
+ * Nothing new is observed to make them writable. `already-true` was already taking a pre-action
9
+ * reading and throwing it away one function short of being this feature; the only change is that a
10
+ * leaf which asked for a comparison gets its own value kept.
11
+ *
12
+ * Deliberately just "before this action" — the window every verdict is already scoped to — and not
13
+ * arbitrary named checkpoints. A `snapshot("cart")` / `compare("cart")` pair is a different feature
14
+ * and has no evidence behind it.
15
+ */
16
+ import { PredicateKind, ReticleCommand } from '@reticlehq/core';
17
+ /** The properties that mean nothing without a before-reading. Mirrors `RELATIVE` in property.ts. */
18
+ const NEEDS_BASELINE = new Set([
19
+ 'changed',
20
+ 'unchanged',
21
+ 'increased',
22
+ 'decreased',
23
+ ]);
24
+ /**
25
+ * Does this leaf's claim compare two readings?
26
+ *
27
+ * Exported because `readsDomState` has to exclude exactly these. A relative property is NEVER
28
+ * answerable before the action — `unchanged` is trivially true against a baseline taken a
29
+ * microsecond earlier — so pre-checking one would report `already_true` for the assertion whose
30
+ * entire purpose is that the value survives what comes next, and turn its verdict into UNKNOWN.
31
+ */
32
+ export function asksForComparison(predicate) {
33
+ if (PredicateKind.STATE === predicate.kind || PredicateKind.TEXT === predicate.kind) {
34
+ return predicate.satisfies !== undefined && NEEDS_BASELINE.has(predicate.satisfies.property);
35
+ }
36
+ return false;
37
+ }
38
+ /** Every leaf that asked for a comparison, composites included. */
39
+ function leavesNeedingBaseline(predicate, into) {
40
+ switch (predicate.kind) {
41
+ case PredicateKind.ALL_OF:
42
+ case PredicateKind.ANY_OF:
43
+ for (const part of predicate.predicates)
44
+ leavesNeedingBaseline(part, into);
45
+ return;
46
+ case PredicateKind.NOT:
47
+ leavesNeedingBaseline(predicate.predicate, into);
48
+ return;
49
+ default:
50
+ if (asksForComparison(predicate))
51
+ into.push(predicate);
52
+ }
53
+ }
54
+ /** Does the whole tree need a pre-action reading at all? One walk, so the caller pays nothing. */
55
+ export function needsBaseline(predicate) {
56
+ if (predicate === undefined)
57
+ return false;
58
+ const found = [];
59
+ leavesNeedingBaseline(predicate, found);
60
+ return found.length > 0;
61
+ }
62
+ async function readStateValue(session, predicate) {
63
+ const args = predicate.store === undefined
64
+ ? { path: predicate.path }
65
+ : { store: predicate.store, path: predicate.path };
66
+ const read = await session.command(ReticleCommand.STATE_READ, args);
67
+ if (!read.ok)
68
+ return undefined;
69
+ const reply = (read.result ?? {});
70
+ // `found: false` is a reading — the path held nothing — and it is NOT the same as "nobody
71
+ // looked". Only an unreadable store returns undefined above.
72
+ return 'boolean' === typeof reply.found ? { taken: true, value: reply.value } : undefined;
73
+ }
74
+ async function readText(session, predicate) {
75
+ const query = {
76
+ ...(predicate.contains === undefined ? {} : { text: predicate.contains }),
77
+ ...(predicate.scope === undefined
78
+ ? {}
79
+ : { scope: predicate.scope, ...(true === predicate.self ? { self: true } : {}) }),
80
+ };
81
+ const match = await session.command(ReticleCommand.MATCH, { query });
82
+ if (!match.ok)
83
+ return undefined;
84
+ const elements = (match.result ?? {}).elements;
85
+ if (!Array.isArray(elements))
86
+ return undefined;
87
+ const text = elements
88
+ .map((element) => {
89
+ if ('object' !== typeof element || null === element)
90
+ return '';
91
+ const value = element.text;
92
+ return 'string' === typeof value ? value : '';
93
+ })
94
+ .join(' ')
95
+ .trim();
96
+ // An empty page is a reading of "": the element was not there, and that is what a later
97
+ // `changed` is comparing against. Refusing here would turn "it appeared" into "nobody looked".
98
+ return { taken: true, value: text };
99
+ }
100
+ /**
101
+ * Read what every comparing leaf needs, once, before the action.
102
+ *
103
+ * Keyed by the predicate OBJECT: the same parsed tree is evaluated before and after, so identity
104
+ * is exact and no path or index has to be kept in step with the walk.
105
+ */
106
+ export async function captureBaselines(session, predicate) {
107
+ const captured = new Map();
108
+ if (predicate === undefined)
109
+ return captured;
110
+ const leaves = [];
111
+ leavesNeedingBaseline(predicate, leaves);
112
+ for (const leaf of leaves) {
113
+ try {
114
+ const reading = PredicateKind.STATE === leaf.kind
115
+ ? await readStateValue(session, leaf)
116
+ : PredicateKind.TEXT === leaf.kind
117
+ ? await readText(session, leaf)
118
+ : undefined;
119
+ if (reading !== undefined)
120
+ captured.set(leaf, reading);
121
+ }
122
+ catch {
123
+ // A reading that could not be taken leaves the leaf with no baseline, which the evaluator
124
+ // reports as `inconclusive`. Throwing here would lose the whole verdict for one unreadable
125
+ // store — and an unevaluated clause is already the honest answer for exactly this.
126
+ }
127
+ }
128
+ return captured;
129
+ }
@@ -2,6 +2,13 @@ import { type ChannelId, Verified, VerifiedReason } from '@reticlehq/core';
2
2
  import { type HonestyBlock } from './honesty.js';
3
3
  import { type UnsettledWindow } from './unsettled.js';
4
4
  interface VerifiedInputs {
5
+ /**
6
+ * The page SDK and daemon wire mismatch, when the handshake found one. Absent means they agree.
7
+ *
8
+ * Carried rather than re-derived: only the bridge sees both halves of the handshake, and a verdict
9
+ * that re-guessed it from versions would disagree with the warning the session already printed.
10
+ */
11
+ versionSkew?: string;
5
12
  /** Did the declared consequence hold? Undefined when the action declared none. */
6
13
  pass?: boolean;
7
14
  /**
@@ -31,7 +31,24 @@ function undeclaredChannels(inputs) {
31
31
  }
32
32
  export function decideVerified(inputs) {
33
33
  const { pass, honesty, contradictions = [], settled, outcomePending, outcomeUnread } = inputs;
34
- // FIRST, ahead of every other clause. A claim that needed to read something nobody was watching
34
+ // Ahead of everything, with `capability-absent` below it and for the same reason: a skewed wire
35
+ // means the ACTION may never have happened, so grading the quality of an observation of it is
36
+ // grading nothing. `session-health` already ranks skew above the throttle warning on this
37
+ // argument; this is the verdict finally agreeing with the warning it was printing beside.
38
+ //
39
+ // UNKNOWN, not NO. Nothing about the app was disproved -- the link under the evidence is what is
40
+ // in doubt. An empty string is not a skew.
41
+ const skew = inputs.versionSkew;
42
+ if (skew !== undefined && skew.length > 0) {
43
+ return {
44
+ verified: Verified.UNKNOWN,
45
+ verifiedReason: VerifiedReason.VERSION_SKEW,
46
+ because: `the page SDK and this daemon are on different wire contracts (${skew}), so dispatched ` +
47
+ 'and settled may be silent no-ops — nothing was proved or disproved about the app. ' +
48
+ 'Converge the versions and re-run',
49
+ };
50
+ }
51
+ // FIRST among the evidence clauses. A claim that needed to read something nobody was watching
35
52
  // was never answerable, and any clause reaching a verdict before this one would report that as
36
53
  // something else -- most often as a failure, which blames the app for a gap in the tooling.
37
54
  const unobservable = undeclaredChannels(inputs);
@@ -207,6 +224,23 @@ export function decideVerified(inputs) {
207
224
  'the store holds) before trusting it',
208
225
  };
209
226
  }
227
+ // `route-rendered-nothing` gets its own sentence for the same reason: the generic one blames churn
228
+ // and a slow app, and here nothing was busy - the URL moved and no view appeared for it. Driven on
229
+ // bench-app with a store that ignored the navigation: the route predicate held, this fired, and the
230
+ // generic sentence sent the reader to wait. UNKNOWN rather than NO because a view revealed from DOM
231
+ // that already existed (a CSS-toggled tab) emits this same window.
232
+ const routeOnly = deciding.length > 0 &&
233
+ deciding.every((c) => c.kind === ContradictionKind.ROUTE_RENDERED_NOTHING);
234
+ if (routeOnly) {
235
+ return {
236
+ verified: Verified.UNKNOWN,
237
+ verifiedReason: VerifiedReason.EVIDENCE_INCOMPLETE,
238
+ because: 'the URL changed, but nothing rendered for it: no content added or removed and no request ' +
239
+ 'made, so the new route may show the old view. A route change alone does not prove the ' +
240
+ 'destination appeared. Assert what the destination shows (its heading or a testid) or the ' +
241
+ 'store value that selects it, rather than the URL',
242
+ };
243
+ }
210
244
  if (deciding.length > 0 && !settlementOnly) {
211
245
  const kinds = deciding.map((c) => c.kind).join(', ');
212
246
  return {
@@ -97,8 +97,9 @@ export function declaredExpectations(predicate) {
97
97
  case PredicateKind.TEXT:
98
98
  if (true !== p.absent) {
99
99
  rendersContent = true;
100
- if (isDenialPhrase(p.contains))
100
+ if (p.contains !== undefined && isDenialPhrase(p.contains)) {
101
101
  pushAuthDenialStatuses(netFailures);
102
+ }
102
103
  }
103
104
  return;
104
105
  default:
@@ -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,
@@ -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
  }
@@ -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;