@reticlehq/engine 3.1.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 (123) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -0
  3. package/dist/disagreement/body-failures.d.ts +4 -0
  4. package/dist/disagreement/body-failures.js +113 -0
  5. package/dist/disagreement/contradiction-evidence.d.ts +122 -0
  6. package/dist/disagreement/contradiction-evidence.js +194 -0
  7. package/dist/disagreement/contradiction-folds.d.ts +61 -0
  8. package/dist/disagreement/contradiction-folds.js +71 -0
  9. package/dist/disagreement/contradiction-types.d.ts +164 -0
  10. package/dist/disagreement/contradiction-types.js +1 -0
  11. package/dist/disagreement/contradictions.d.ts +5 -0
  12. package/dist/disagreement/contradictions.js +613 -0
  13. package/dist/disagreement/echo-mismatch.d.ts +10 -0
  14. package/dist/disagreement/echo-mismatch.js +299 -0
  15. package/dist/disagreement/reconcile.d.ts +39 -0
  16. package/dist/disagreement/reconcile.js +211 -0
  17. package/dist/disagreement/stale-response.d.ts +3 -0
  18. package/dist/disagreement/stale-response.js +186 -0
  19. package/dist/disagreement/unit-mismatch.d.ts +16 -0
  20. package/dist/disagreement/unit-mismatch.js +167 -0
  21. package/dist/disagreement/witness-disagreement.d.ts +42 -0
  22. package/dist/disagreement/witness-disagreement.js +43 -0
  23. package/dist/evidence/accepted-write.d.ts +35 -0
  24. package/dist/evidence/accepted-write.js +54 -0
  25. package/dist/evidence/already-true.d.ts +16 -0
  26. package/dist/evidence/already-true.js +89 -0
  27. package/dist/evidence/blind-spots.d.ts +133 -0
  28. package/dist/evidence/blind-spots.js +253 -0
  29. package/dist/evidence/body-capture-remedy.d.ts +42 -0
  30. package/dist/evidence/body-capture-remedy.js +96 -0
  31. package/dist/evidence/gap-ledger.d.ts +52 -0
  32. package/dist/evidence/gap-ledger.js +63 -0
  33. package/dist/evidence/honesty.d.ts +113 -0
  34. package/dist/evidence/honesty.js +105 -0
  35. package/dist/evidence/instrumentation-gaps.d.ts +91 -0
  36. package/dist/evidence/instrumentation-gaps.js +102 -0
  37. package/dist/evidence/learned-guards.d.ts +75 -0
  38. package/dist/evidence/learned-guards.js +78 -0
  39. package/dist/evidence/observability.d.ts +38 -0
  40. package/dist/evidence/observability.js +40 -0
  41. package/dist/evidence/page-teardown.d.ts +15 -0
  42. package/dist/evidence/page-teardown.js +17 -0
  43. package/dist/evidence/step-effect.d.ts +41 -0
  44. package/dist/evidence/step-effect.js +27 -0
  45. package/dist/evidence/uncaptured-bodies.d.ts +23 -0
  46. package/dist/evidence/uncaptured-bodies.js +41 -0
  47. package/dist/evidence/undeclared-change.d.ts +51 -0
  48. package/dist/evidence/undeclared-change.js +56 -0
  49. package/dist/evidence/unread-outcome.d.ts +10 -0
  50. package/dist/evidence/unread-outcome.js +77 -0
  51. package/dist/evidence/unsettled.d.ts +58 -0
  52. package/dist/evidence/unsettled.js +127 -0
  53. package/dist/evidence/verdict-intent-gap.d.ts +30 -0
  54. package/dist/evidence/verdict-intent-gap.js +35 -0
  55. package/dist/evidence/verified.d.ts +158 -0
  56. package/dist/evidence/verified.js +378 -0
  57. package/dist/index.d.ts +30 -0
  58. package/dist/index.js +25 -0
  59. package/dist/question/declared.d.ts +74 -0
  60. package/dist/question/declared.js +171 -0
  61. package/dist/question/lineage.d.ts +52 -0
  62. package/dist/question/lineage.js +122 -0
  63. package/dist/question/predicate/net-evidence.d.ts +21 -0
  64. package/dist/question/predicate/net-evidence.js +81 -0
  65. package/dist/question/predicate/observed-in-window.d.ts +24 -0
  66. package/dist/question/predicate/observed-in-window.js +38 -0
  67. package/dist/question/predicate/predicate-asks.d.ts +28 -0
  68. package/dist/question/predicate/predicate-asks.js +46 -0
  69. package/dist/question/predicate/predicate-console.d.ts +13 -0
  70. package/dist/question/predicate/predicate-console.js +138 -0
  71. package/dist/question/predicate/predicate-element.d.ts +13 -0
  72. package/dist/question/predicate/predicate-element.js +214 -0
  73. package/dist/question/predicate/predicate-eval-kit.d.ts +90 -0
  74. package/dist/question/predicate/predicate-eval-kit.js +126 -0
  75. package/dist/question/predicate/predicate-eval.d.ts +24 -0
  76. package/dist/question/predicate/predicate-eval.js +710 -0
  77. package/dist/question/predicate/predicate-parse.d.ts +15 -0
  78. package/dist/question/predicate/predicate-parse.js +173 -0
  79. package/dist/question/predicate/predicate-precheck.d.ts +8 -0
  80. package/dist/question/predicate/predicate-precheck.js +41 -0
  81. package/dist/question/predicate/predicate-request-body.d.ts +50 -0
  82. package/dist/question/predicate/predicate-request-body.js +120 -0
  83. package/dist/question/predicate/predicate-route.d.ts +66 -0
  84. package/dist/question/predicate/predicate-route.js +293 -0
  85. package/dist/question/predicate/predicate-schema.d.ts +170 -0
  86. package/dist/question/predicate/predicate-schema.js +509 -0
  87. package/dist/question/predicate/predicate-session.d.ts +72 -0
  88. package/dist/question/predicate/predicate-session.js +1 -0
  89. package/dist/question/predicate/predicate-to-links.d.ts +13 -0
  90. package/dist/question/predicate/predicate-to-links.js +38 -0
  91. package/dist/question/predicate/predicate.d.ts +26 -0
  92. package/dist/question/predicate/predicate.js +785 -0
  93. package/dist/question/predicate/property.d.ts +102 -0
  94. package/dist/question/predicate/property.js +135 -0
  95. package/dist/question/predicate/split-text-miss.d.ts +32 -0
  96. package/dist/question/predicate/split-text-miss.js +51 -0
  97. package/dist/question/predicate/testid-near-miss.d.ts +22 -0
  98. package/dist/question/predicate/testid-near-miss.js +33 -0
  99. package/dist/question/reaction.d.ts +17 -0
  100. package/dist/question/reaction.js +67 -0
  101. package/dist/window/adversary.d.ts +28 -0
  102. package/dist/window/adversary.js +90 -0
  103. package/dist/window/ambient.d.ts +63 -0
  104. package/dist/window/ambient.js +76 -0
  105. package/dist/window/appearance-budget.d.ts +41 -0
  106. package/dist/window/appearance-budget.js +47 -0
  107. package/dist/window/asset-noise.d.ts +42 -0
  108. package/dist/window/asset-noise.js +35 -0
  109. package/dist/window/body-relevance.d.ts +54 -0
  110. package/dist/window/body-relevance.js +78 -0
  111. package/dist/window/byte-size.d.ts +1 -0
  112. package/dist/window/byte-size.js +16 -0
  113. package/dist/window/engine-host.d.ts +35 -0
  114. package/dist/window/engine-host.js +20 -0
  115. package/dist/window/event-filters.d.ts +121 -0
  116. package/dist/window/event-filters.js +215 -0
  117. package/dist/window/json-salvage.d.ts +33 -0
  118. package/dist/window/json-salvage.js +96 -0
  119. package/dist/window/network-detail-merge.d.ts +8 -0
  120. package/dist/window/network-detail-merge.js +89 -0
  121. package/dist/window/ring-buffer.d.ts +41 -0
  122. package/dist/window/ring-buffer.js +152 -0
  123. package/package.json +71 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * What the caller DECLARED before acting — the oracle, read back.
3
+ *
4
+ * `act_and_wait` asks the agent to name the expected consequence BEFORE the action, and that
5
+ * declaration was then thrown away: everything downstream judged the window as if nobody had said
6
+ * what they were expecting. Two measured consequences, one bug:
7
+ *
8
+ * - An error path can be declared exactly — `{ net, POST, /api/login, status: 500 }` — and the
9
+ * contradiction hunter still reported `ui-advanced-request-failed`, because a failed request plus
10
+ * a moved DOM is all it can see. The failure was EXPECTED and said so in the predicate, so a
11
+ * verdict of "channels disagree" is a statement about a disagreement nobody had.
12
+ * - A destination whose content was asserted and FOUND was still reported as
13
+ * `route-rendered-nothing`, a clause the element evidence beside it disproves.
14
+ *
15
+ * Deliberately conservative about what counts as declared. Only what the caller REQUIRED is read:
16
+ * the top level and `allOf` chains. An `anyOf` branch may never have held, and a `not` declares the
17
+ * opposite of a consequence — honouring either would suppress a real finding on the strength of
18
+ * something that never happened. Pure: a predicate in, a description out.
19
+ */
20
+ import type { Predicate } from './predicate/predicate-eval.js';
21
+ /** A failing call the caller named in advance — matched against the window's real calls. */
22
+ export interface DeclaredNetFailure {
23
+ method?: string;
24
+ urlContains?: string;
25
+ status?: number;
26
+ }
27
+ interface DeclaredExpectations {
28
+ /** Requests the caller declared would FAIL, so failing is the expected outcome, not a disagreement. */
29
+ netFailures: readonly DeclaredNetFailure[];
30
+ /** The caller required something to be ON SCREEN — an element or text, present rather than absent. */
31
+ rendersContent: boolean;
32
+ /**
33
+ * The `urlContains` of every net clause the predicate carries, failure or not.
34
+ *
35
+ * Distinct from `netFailures`, which is about EXPECTED failures. This answers a different
36
+ * question: which traffic did the caller actually mention? A rule that reports on writes the
37
+ * assertion never named is reporting on something else, and must not decide this verdict (#673).
38
+ *
39
+ * A net clause with no `urlContains` names ALL traffic — it asked about the whole channel — which
40
+ * is why an empty-string entry is meaningful and is preserved rather than skipped.
41
+ */
42
+ netUrls: readonly string[];
43
+ }
44
+ export declare function declaredExpectations(predicate: Predicate | undefined): DeclaredExpectations;
45
+ /**
46
+ * Did the caller name a consequence that does not depend on the response body?
47
+ *
48
+ * The unread-body clause exists for the case where the body is the ONLY channel that could have
49
+ * contradicted the screen — a 200 with per-item failures inside, a GraphQL error that is also a
50
+ * 200. A declared string on screen, store path, signal, route, or an element located by role /
51
+ * name / testid that held is a different channel, and grading `unknown` there costs a real
52
+ * verdict (measured: a 201 plus the unique row, unread body, agent went to enable capture instead
53
+ * of finishing the drive).
54
+ *
55
+ * Same conservatism as `declaredExpectations`: only the top level and `allOf`. An `anyOf` branch
56
+ * may never have held, and honouring it would skip the unread caveat on the strength of a net
57
+ * success that was the branch that actually matched. An `absent` element is not a consequence the
58
+ * body cannot own.
59
+ */
60
+ export declare function declaresBodyIndependentChannel(predicate: Predicate | undefined): boolean;
61
+ /**
62
+ * Does a call the window recorded match a failure the caller declared?
63
+ *
64
+ * Every field the caller named must agree — a declaration about `POST /api/login → 500` says nothing
65
+ * about `POST /api/orders`, and treating it as a blanket amnesty for failed requests would remove
66
+ * the check rather than inform it. Fields the caller left out are not constraints.
67
+ */
68
+ export declare function matchesDeclaredFailure(call: {
69
+ method: string;
70
+ url: string;
71
+ matchUrl?: string;
72
+ status: number | undefined;
73
+ }, declared: readonly DeclaredNetFailure[]): boolean;
74
+ export {};
@@ -0,0 +1,171 @@
1
+ /**
2
+ * What the caller DECLARED before acting — the oracle, read back.
3
+ *
4
+ * `act_and_wait` asks the agent to name the expected consequence BEFORE the action, and that
5
+ * declaration was then thrown away: everything downstream judged the window as if nobody had said
6
+ * what they were expecting. Two measured consequences, one bug:
7
+ *
8
+ * - An error path can be declared exactly — `{ net, POST, /api/login, status: 500 }` — and the
9
+ * contradiction hunter still reported `ui-advanced-request-failed`, because a failed request plus
10
+ * a moved DOM is all it can see. The failure was EXPECTED and said so in the predicate, so a
11
+ * verdict of "channels disagree" is a statement about a disagreement nobody had.
12
+ * - A destination whose content was asserted and FOUND was still reported as
13
+ * `route-rendered-nothing`, a clause the element evidence beside it disproves.
14
+ *
15
+ * Deliberately conservative about what counts as declared. Only what the caller REQUIRED is read:
16
+ * the top level and `allOf` chains. An `anyOf` branch may never have held, and a `not` declares the
17
+ * opposite of a consequence — honouring either would suppress a real finding on the strength of
18
+ * something that never happened. Pure: a predicate in, a description out.
19
+ */
20
+ import { PredicateKind, QueryBy } from '@reticlehq/core';
21
+ /** Below this, a status is a success or a redirect: not a declared failure. */
22
+ const FAILURE_STATUS_MIN = 400;
23
+ /** Statuses that mean the caller was refused — the proof of an auth/authz denial, not a fault. */
24
+ const AUTH_DENIAL_STATUSES = [401, 403];
25
+ /** ARIA roles that ARE the error UI — waiting for an alert is how the first report asserted a 401. */
26
+ const DENIAL_ROLES = new Set(['alert', 'alertdialog']);
27
+ /**
28
+ * Phrases that name a denial rather than a success. Conservative and multi-word where a short
29
+ * token would match a greeting ("invalid date" is not an auth failure).
30
+ */
31
+ const DENIAL_TEXT_MARKERS = [
32
+ 'access denied',
33
+ 'unauthorized',
34
+ 'forbidden',
35
+ 'invalid key',
36
+ 'invalid credentials',
37
+ 'incorrect email',
38
+ 'incorrect password',
39
+ 'not authorized',
40
+ 'permission denied',
41
+ 'unauthenticated',
42
+ 'not allowed',
43
+ ];
44
+ function isDenialPhrase(text) {
45
+ const lower = text.toLowerCase();
46
+ return DENIAL_TEXT_MARKERS.some((marker) => lower.includes(marker));
47
+ }
48
+ function isDenialRole(role) {
49
+ return DENIAL_ROLES.has(role.toLowerCase());
50
+ }
51
+ function isDenialQuery(query) {
52
+ if (undefined !== query.role && isDenialRole(query.role))
53
+ return true;
54
+ if (QueryBy.ROLE === query.by && undefined !== query.value && isDenialRole(query.value)) {
55
+ return true;
56
+ }
57
+ for (const field of [query.name, query.text, query.value, query.label]) {
58
+ if ('string' === typeof field && isDenialPhrase(field))
59
+ return true;
60
+ }
61
+ return false;
62
+ }
63
+ function pushAuthDenialStatuses(into) {
64
+ for (const status of AUTH_DENIAL_STATUSES) {
65
+ into.push({ status });
66
+ }
67
+ }
68
+ export function declaredExpectations(predicate) {
69
+ const netFailures = [];
70
+ const netUrls = [];
71
+ let rendersContent = false;
72
+ const walk = (p) => {
73
+ switch (p.kind) {
74
+ case PredicateKind.ALL_OF:
75
+ for (const child of p.predicates)
76
+ walk(child);
77
+ return;
78
+ case PredicateKind.NET: {
79
+ netUrls.push(p.urlContains ?? '');
80
+ const declaredFailure = false === p.ok || (p.status !== undefined && p.status >= FAILURE_STATUS_MIN);
81
+ if (!declaredFailure)
82
+ return;
83
+ netFailures.push({
84
+ ...(p.method === undefined ? {} : { method: p.method }),
85
+ ...(p.urlContains === undefined ? {} : { urlContains: p.urlContains }),
86
+ ...(p.status === undefined ? {} : { status: p.status }),
87
+ });
88
+ return;
89
+ }
90
+ case PredicateKind.ELEMENT:
91
+ if (true !== p.absent) {
92
+ rendersContent = true;
93
+ if (isDenialQuery(p.query))
94
+ pushAuthDenialStatuses(netFailures);
95
+ }
96
+ return;
97
+ case PredicateKind.TEXT:
98
+ if (true !== p.absent) {
99
+ rendersContent = true;
100
+ if (isDenialPhrase(p.contains))
101
+ pushAuthDenialStatuses(netFailures);
102
+ }
103
+ return;
104
+ default:
105
+ return;
106
+ }
107
+ };
108
+ if (predicate !== undefined)
109
+ walk(predicate);
110
+ return { netFailures, rendersContent, netUrls };
111
+ }
112
+ /**
113
+ * Did the caller name a consequence that does not depend on the response body?
114
+ *
115
+ * The unread-body clause exists for the case where the body is the ONLY channel that could have
116
+ * contradicted the screen — a 200 with per-item failures inside, a GraphQL error that is also a
117
+ * 200. A declared string on screen, store path, signal, route, or an element located by role /
118
+ * name / testid that held is a different channel, and grading `unknown` there costs a real
119
+ * verdict (measured: a 201 plus the unique row, unread body, agent went to enable capture instead
120
+ * of finishing the drive).
121
+ *
122
+ * Same conservatism as `declaredExpectations`: only the top level and `allOf`. An `anyOf` branch
123
+ * may never have held, and honouring it would skip the unread caveat on the strength of a net
124
+ * success that was the branch that actually matched. An `absent` element is not a consequence the
125
+ * body cannot own.
126
+ */
127
+ export function declaresBodyIndependentChannel(predicate) {
128
+ if (predicate === undefined)
129
+ return false;
130
+ const walk = (p) => {
131
+ switch (p.kind) {
132
+ case PredicateKind.ALL_OF:
133
+ return p.predicates.some(walk);
134
+ case PredicateKind.TEXT:
135
+ return true !== p.absent;
136
+ case PredicateKind.SIGNAL:
137
+ case PredicateKind.STATE:
138
+ case PredicateKind.ROUTE:
139
+ return true;
140
+ case PredicateKind.ELEMENT:
141
+ return (true !== p.absent &&
142
+ (p.query.value !== undefined ||
143
+ p.query.text !== undefined ||
144
+ p.query.role !== undefined ||
145
+ p.query.name !== undefined ||
146
+ p.query.testid !== undefined));
147
+ default:
148
+ return false;
149
+ }
150
+ };
151
+ return walk(predicate);
152
+ }
153
+ /**
154
+ * Does a call the window recorded match a failure the caller declared?
155
+ *
156
+ * Every field the caller named must agree — a declaration about `POST /api/login → 500` says nothing
157
+ * about `POST /api/orders`, and treating it as a blanket amnesty for failed requests would remove
158
+ * the check rather than inform it. Fields the caller left out are not constraints.
159
+ */
160
+ export function matchesDeclaredFailure(call, declared) {
161
+ return declared.some((d) => {
162
+ if (d.method !== undefined && d.method.toUpperCase() !== call.method.toUpperCase())
163
+ return false;
164
+ const haystack = call.matchUrl ?? call.url;
165
+ if (d.urlContains !== undefined && !haystack.includes(d.urlContains))
166
+ return false;
167
+ if (d.status !== undefined && d.status !== call.status)
168
+ return false;
169
+ return true;
170
+ });
171
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Where a runtime value came from: state path ← the signal that preceded it ← the request behind it.
3
+ *
4
+ * Prior art (`firatorhan/sentinel`'s `get_lineage`) builds the same chain by
5
+ * picking "the most recent action whose payload contains this value", then "an API call whose type
6
+ * matches". That is CORRELATION, and for a devtool a human reads it is the right trade — the reader
7
+ * discounts it on sight.
8
+ *
9
+ * Reticle's output is read by an agent that acts on it, so the same chain presented as fact is the
10
+ * false-green shape this project exists to refuse. The join here is deliberately no cleverer than
11
+ * theirs; what is different is that every link carries how much it is worth:
12
+ *
13
+ * - a state path that changed is OBSERVED — we have the event;
14
+ * - "this signal caused it" is INFERRED, and the wording says so;
15
+ * - several candidates are NAMED rather than narrowed to the most recent, because choosing is the
16
+ * one thing a correlation cannot justify;
17
+ * - no candidate says the value was not seen to pass through one, and reaches for nothing.
18
+ *
19
+ * Read-only. Produces no verdict, is not reachable from an assert path, and changes nothing.
20
+ */
21
+ import { type ReticleEvent } from '@reticlehq/core';
22
+ /** What the caller is asking about. `value` narrows a path that changed more than once. */
23
+ export interface LineageQuery {
24
+ path: string;
25
+ value?: string;
26
+ }
27
+ /** 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';
31
+ /** The rendered line, already carrying its own hedge. */
32
+ text: string;
33
+ /** True only when this is an event we hold. A join is never observed. */
34
+ observed: boolean;
35
+ /** Every candidate, when more than one could explain the link. Present only when ambiguous. */
36
+ candidates?: string[];
37
+ }
38
+ export interface Lineage {
39
+ /** False when the path was never seen to change — a different answer from an empty chain. */
40
+ found: boolean;
41
+ chain: LineageLink[];
42
+ /** Why the chain stops where it does, when it stops early. */
43
+ note?: string;
44
+ }
45
+ /**
46
+ * The chain, most recent change first.
47
+ *
48
+ * Stops at the first link with nothing to point at, and says why. Walking past a gap would mean
49
+ * joining across a hole in the evidence, which is exactly the step that turns a correlation into a
50
+ * claim.
51
+ */
52
+ export declare function traceLineage(events: readonly ReticleEvent[], query: LineageQuery): Lineage;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Where a runtime value came from: state path ← the signal that preceded it ← the request behind it.
3
+ *
4
+ * Prior art (`firatorhan/sentinel`'s `get_lineage`) builds the same chain by
5
+ * picking "the most recent action whose payload contains this value", then "an API call whose type
6
+ * matches". That is CORRELATION, and for a devtool a human reads it is the right trade — the reader
7
+ * discounts it on sight.
8
+ *
9
+ * Reticle's output is read by an agent that acts on it, so the same chain presented as fact is the
10
+ * false-green shape this project exists to refuse. The join here is deliberately no cleverer than
11
+ * theirs; what is different is that every link carries how much it is worth:
12
+ *
13
+ * - a state path that changed is OBSERVED — we have the event;
14
+ * - "this signal caused it" is INFERRED, and the wording says so;
15
+ * - several candidates are NAMED rather than narrowed to the most recent, because choosing is the
16
+ * one thing a correlation cannot justify;
17
+ * - no candidate says the value was not seen to pass through one, and reaches for nothing.
18
+ *
19
+ * Read-only. Produces no verdict, is not reachable from an assert path, and changes nothing.
20
+ */
21
+ import { EventType } from '@reticlehq/core';
22
+ import { asString } from '@reticlehq/core';
23
+ /**
24
+ * How far back to look for a cause.
25
+ *
26
+ * Wide enough for a fetch → dispatch → render sequence, narrow enough that an unrelated signal a
27
+ * page-load earlier cannot be offered as a candidate. Not a correctness bound: widening it produces
28
+ * MORE named candidates, never a wrong single answer, because ambiguity is reported rather than
29
+ * resolved.
30
+ */
31
+ const CAUSE_WINDOW_MS = 5_000;
32
+ function stateChangesFor(events, query) {
33
+ return events.filter((e) => {
34
+ if (e.type !== EventType.STATE_CHANGE)
35
+ return false;
36
+ const path = asString(e.data['path']);
37
+ if (path === undefined || !path.includes(query.path))
38
+ return false;
39
+ if (query.value === undefined)
40
+ return true;
41
+ return String(e.data['value']) === query.value;
42
+ });
43
+ }
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);
47
+ }
48
+ /**
49
+ * Render an inferred link, hedged according to how many things could explain it.
50
+ *
51
+ * The wording IS the deliverable. `← USER_FETCH_SUCCESS` reads as fact; the two forms below read as
52
+ * what they are, and a reader who skims still sees the hedge because it is in the first few words.
53
+ */
54
+ function inferredLink(kind, labels) {
55
+ const one = labels[0] ?? '';
56
+ if (1 === labels.length) {
57
+ return { kind, text: `← likely ${one} (inferred from timing, 1 candidate)`, observed: false };
58
+ }
59
+ return {
60
+ kind,
61
+ text: `← ambiguous: ${String(labels.length)} candidates (${labels.join(', ')}) — not resolved, because timing alone cannot choose between them`,
62
+ observed: false,
63
+ candidates: labels,
64
+ };
65
+ }
66
+ function signalLabel(e) {
67
+ return asString(e.data['name']) ?? '(unnamed signal)';
68
+ }
69
+ function netLabel(e) {
70
+ const method = asString(e.data['method']) ?? 'GET';
71
+ const url = asString(e.data['url']) ?? '(unknown url)';
72
+ const status = e.data['status'];
73
+ return `${method} ${url}${'number' === typeof status ? ` (${String(status)})` : ''}`;
74
+ }
75
+ /**
76
+ * The chain, most recent change first.
77
+ *
78
+ * Stops at the first link with nothing to point at, and says why. Walking past a gap would mean
79
+ * joining across a hole in the evidence, which is exactly the step that turns a correlation into a
80
+ * claim.
81
+ */
82
+ export function traceLineage(events, query) {
83
+ const changes = stateChangesFor(events, query);
84
+ const latest = changes[changes.length - 1];
85
+ if (latest === undefined) {
86
+ return {
87
+ found: false,
88
+ chain: [],
89
+ note: `'${query.path}' was never seen to change in this window, so there is nothing to trace back from. It may be set before Reticle connected, or held somewhere no registered store exposes.`,
90
+ };
91
+ }
92
+ const observedValue = String(latest.data['value']);
93
+ const chain = [
94
+ {
95
+ kind: 'state',
96
+ text: `${asString(latest.data['path']) ?? query.path} = ${observedValue} (observed: state change at ${String(latest.t)}ms)`,
97
+ observed: true,
98
+ },
99
+ ];
100
+ const signals = precursors(events, EventType.SIGNAL, latest.t);
101
+ 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
+ };
107
+ }
108
+ chain.push(inferredLink('signal', signals.map(signalLabel)));
109
+ // Anchored on the OLDEST candidate signal: a request that preceded any of them could have produced
110
+ // it, and narrowing to the newest would quietly discard candidates for the link below.
111
+ const anchor = signals[0]?.t ?? latest.t;
112
+ const calls = precursors(events, EventType.NET_REQUEST, anchor);
113
+ if (0 === calls.length) {
114
+ return {
115
+ found: true,
116
+ chain,
117
+ note: 'No request preceded that signal in the window, so the chain stops there rather than joining across a gap in the evidence.',
118
+ };
119
+ }
120
+ chain.push(inferredLink('net', calls.map(netLabel)));
121
+ return { found: true, chain };
122
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * What a network verdict returns as its PROOF.
3
+ *
4
+ * Split out of predicate-eval.ts, which sits at the size backstop, and split HERE because this is a
5
+ * separate question from "did the predicate hold": that file decides the answer, this one decides
6
+ * what is shown to justify it. The two failure modes differ too. A wrong verdict is a wrong verdict;
7
+ * wrong evidence is a verdict nobody can check, or one that costs forty times what it is worth.
8
+ */
9
+ import { PredicateKind } from '@reticlehq/core';
10
+ import type { Predicate } from './predicate-schema.js';
11
+ /**
12
+ * The matched call, as the proof of the claim that was actually made.
13
+ *
14
+ * A predicate asking about status and url is proved by status and url; returning the whole payload
15
+ * beside them is cost with no bearing on the verdict. A predicate asking `bodyContains` is proved BY
16
+ * the body, and that one keeps it in full — clipping a body a check consumed would be weakening the
17
+ * check to make it cheaper, which is the trade this codebase does not make.
18
+ */
19
+ export declare function netEvidence(data: Record<string, unknown>, p: Extract<Predicate, {
20
+ kind: typeof PredicateKind.NET;
21
+ }>): unknown;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * What a network verdict returns as its PROOF.
3
+ *
4
+ * Split out of predicate-eval.ts, which sits at the size backstop, and split HERE because this is a
5
+ * separate question from "did the predicate hold": that file decides the answer, this one decides
6
+ * what is shown to justify it. The two failure modes differ too. A wrong verdict is a wrong verdict;
7
+ * wrong evidence is a verdict nobody can check, or one that costs forty times what it is worth.
8
+ */
9
+ import { PredicateKind } from '@reticlehq/core';
10
+ import { withoutUrlRaw } from '../../window/event-filters.js';
11
+ /**
12
+ * How much of a body the evidence for a PASS may carry when the check never read it.
13
+ *
14
+ * Enough to see the shape of what the server answered — a JSON document's opening keys — and not the
15
+ * document itself. Unbounded, a run of `act_and_wait` calls asserting only `{ urlContains, status
16
+ * 200 }` against one endpoint each return the server's whole answer — nearly the same document every
17
+ * time — so the evidence block dwarfs the result and almost all of it is a re-send of what the agent
18
+ * already had.
19
+ *
20
+ * Larger than `MAX_BODY_IN_FAILURE`, and deliberately: a failure quotes the value that DIFFERED and
21
+ * knows which one that is, while a pass is showing the caller what came back and has no such anchor.
22
+ */
23
+ const MAX_BODY_IN_EVIDENCE = 512;
24
+ /** Body fields a net predicate can read, and the clause that reads each. */
25
+ const BODY_EVIDENCE_FIELDS = {
26
+ responseBody: 'bodyContains',
27
+ requestBody: 'requestBodyContains',
28
+ };
29
+ /**
30
+ * How much of the body around a matched needle is quoted.
31
+ *
32
+ * Enough to see the needle in its structure — the key it sits under, the value beside it — without
33
+ * the document it came from.
34
+ */
35
+ const BODY_MATCH_CONTEXT = 120;
36
+ /** Where a quoted window starts, and the elision markers that keep it honest at both ends. */
37
+ function windowAround(body, at, needle) {
38
+ const from = Math.max(0, at - BODY_MATCH_CONTEXT);
39
+ const to = Math.min(body.length, at + needle.length + BODY_MATCH_CONTEXT);
40
+ return `${from > 0 ? '…' : ''}${body.slice(from, to)}${to < body.length ? '…' : ''}`;
41
+ }
42
+ /** The head of a body, for a claim that never read it. Elision is VISIBLE — see the note below. */
43
+ function headOf(body) {
44
+ return body.length <= MAX_BODY_IN_EVIDENCE ? body : `${body.slice(0, MAX_BODY_IN_EVIDENCE)}…`;
45
+ }
46
+ /**
47
+ * The matched call, as the proof of the claim that was actually made.
48
+ *
49
+ * A predicate asking about status and url is proved by status and url; returning the whole payload
50
+ * beside them is cost with no bearing on the verdict. A predicate asking `bodyContains` is proved BY
51
+ * the body, and that one keeps it in full — clipping a body a check consumed would be weakening the
52
+ * check to make it cheaper, which is the trade this codebase does not make.
53
+ */
54
+ export function netEvidence(data, p) {
55
+ const stripped = withoutUrlRaw({ data }).data;
56
+ if (null === stripped || 'object' !== typeof stripped)
57
+ return stripped;
58
+ const clause = p;
59
+ const out = { ...stripped };
60
+ for (const [field, askedBy] of Object.entries(BODY_EVIDENCE_FIELDS)) {
61
+ const body = out[field];
62
+ if ('string' !== typeof body || body.length <= MAX_BODY_IN_EVIDENCE)
63
+ continue;
64
+ const needle = clause[askedBy];
65
+ const at = 'string' === typeof needle ? body.indexOf(needle) : -1;
66
+ if (at < 0) {
67
+ // No clause read this body, or the pass came from elsewhere: the head shows the shape of the
68
+ // answer. The ellipsis is load-bearing — a silently shortened body reads as "the server
69
+ // answered this much", a different and wrong fact — and `responseSize` rides alongside
70
+ // untouched, so the real length stays available and `reticle_network` fetches the rest.
71
+ out[field] = headOf(body);
72
+ continue;
73
+ }
74
+ // The clause matched. What proves it is the MATCH, not the document it was found in: the needle
75
+ // in its context, plus where it was. Six field verdicts each returned the same 8KB interview
76
+ // document to prove one substring of it, and the document proved nothing the window does not.
77
+ out[field] = windowAround(body, at, needle);
78
+ out['bodyMatchAt'] = at;
79
+ }
80
+ return out;
81
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * What DID happen, when the thing you asserted did not.
3
+ *
4
+ * "signal 'x' never fired" and "no matching network call" are true and useless: a typo'd name and a
5
+ * genuinely broken app produce the same sentence, and the agent cannot tell them apart without a
6
+ * round trip it does not know to make. `{ kind:'state' }` already answers a bad path by naming the
7
+ * stores that exist; this gives `signal` and `net` the same courtesy.
8
+ *
9
+ * It also distinguishes the two failures that matter: NOTHING happened in the window (the action did
10
+ * not do what you thought) versus things happened but not that one (you named it wrong).
11
+ */
12
+ export declare function describeObserved(noun: string, seen: readonly string[]): string;
13
+ /**
14
+ * The third answer, and the one this file existed to make room for: things happened, and they belong
15
+ * to a document that has since been replaced.
16
+ *
17
+ * `describeObserved` already separates "nothing happened" from "things happened but not that one",
18
+ * because those need different fixes. A window whose evidence was discarded as superseded is a third
19
+ * case needing a third fix, and it is the one that reads most like the first: everything that could
20
+ * have answered the question is gone, so a bare "nothing happened in this window" is available and
21
+ * wrong. The remedy is in the sentence, because an agent that cannot act on a caveat learns to skip
22
+ * it — here the remedy is to drive the action again against the page now on screen.
23
+ */
24
+ export declare function describeSuperseded(noun: string, count: number): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What DID happen, when the thing you asserted did not.
3
+ *
4
+ * "signal 'x' never fired" and "no matching network call" are true and useless: a typo'd name and a
5
+ * genuinely broken app produce the same sentence, and the agent cannot tell them apart without a
6
+ * round trip it does not know to make. `{ kind:'state' }` already answers a bad path by naming the
7
+ * stores that exist; this gives `signal` and `net` the same courtesy.
8
+ *
9
+ * It also distinguishes the two failures that matter: NOTHING happened in the window (the action did
10
+ * not do what you thought) versus things happened but not that one (you named it wrong).
11
+ */
12
+ /** Enough to recognise the one you meant; not so many that a chatty window floods the message. */
13
+ const MAX_LISTED = 8;
14
+ export function describeObserved(noun, seen) {
15
+ const unique = [...new Set(seen.filter((s) => s.length > 0))];
16
+ if (0 === unique.length)
17
+ return `no ${noun} at all in this window`;
18
+ const shown = unique.slice(0, MAX_LISTED);
19
+ const rest = unique.length - shown.length;
20
+ return `${noun} seen in this window: ${shown.join(', ')}${rest > 0 ? `, and ${String(rest)} more` : ''}`;
21
+ }
22
+ /**
23
+ * The third answer, and the one this file existed to make room for: things happened, and they belong
24
+ * to a document that has since been replaced.
25
+ *
26
+ * `describeObserved` already separates "nothing happened" from "things happened but not that one",
27
+ * because those need different fixes. A window whose evidence was discarded as superseded is a third
28
+ * case needing a third fix, and it is the one that reads most like the first: everything that could
29
+ * have answered the question is gone, so a bare "nothing happened in this window" is available and
30
+ * wrong. The remedy is in the sentence, because an agent that cannot act on a caveat learns to skip
31
+ * it — here the remedy is to drive the action again against the page now on screen.
32
+ */
33
+ export function describeSuperseded(noun, count) {
34
+ return (`no ${noun} belong to the document currently on screen: ${String(count)} ${noun} were observed ` +
35
+ `and every one of them belongs to a document that has since been replaced (the page reloaded or ` +
36
+ `navigated). This says nothing about the app — the evidence went away with the page that produced ` +
37
+ `it. Re-drive the action against the page now on screen`);
38
+ }
@@ -0,0 +1,28 @@
1
+ import type { Predicate } from './predicate-schema.js';
2
+ /**
3
+ * Did the caller's predicate ask about registered state?
4
+ *
5
+ * Walks composites, because `allOf[{net}, {state}]` asks about state exactly as much as a bare
6
+ * `{state}` does — and the gap that reveals is the same one either way.
7
+ *
8
+ * Lives here rather than at a call site because both the act path and the assert path need it, and
9
+ * two walkers over one predicate tree is two chances to disagree about what counts as asking.
10
+ *
11
+ * Named `predicate-asks` rather than `predicate-shape` because `predicate-shape.test.ts` already
12
+ * exists and is about something else entirely — a file that reads as the subject of an unrelated
13
+ * test is a half-hour somebody loses later.
14
+ */
15
+ export declare function declaresState(predicate: Predicate): boolean;
16
+ /**
17
+ * Does the caller's predicate judge the DOM — an `element` or `text` clause anywhere in the tree?
18
+ *
19
+ * The question behind it is where a verdict is allowed to point. A DOM predicate has its own locus:
20
+ * the element it matched, whose `file:line` the descriptor already carries. A `signal`/`net`/`state`
21
+ * failure has none — there is no node for "the request was never made" — and that is the one case
22
+ * where the verdict borrows the last driven control's line, because the handler that should have
23
+ * fired lives there.
24
+ *
25
+ * Walks composites for the same reason `declaresState` does: `allOf[{element}, {signal}]` looked at
26
+ * the DOM exactly as much as a bare `{element}` did.
27
+ */
28
+ export declare function declaresDom(predicate: Predicate): boolean;
@@ -0,0 +1,46 @@
1
+ import { PredicateKind } from '@reticlehq/core';
2
+ /**
3
+ * Did the caller's predicate ask about registered state?
4
+ *
5
+ * Walks composites, because `allOf[{net}, {state}]` asks about state exactly as much as a bare
6
+ * `{state}` does — and the gap that reveals is the same one either way.
7
+ *
8
+ * Lives here rather than at a call site because both the act path and the assert path need it, and
9
+ * two walkers over one predicate tree is two chances to disagree about what counts as asking.
10
+ *
11
+ * Named `predicate-asks` rather than `predicate-shape` because `predicate-shape.test.ts` already
12
+ * exists and is about something else entirely — a file that reads as the subject of an unrelated
13
+ * test is a half-hour somebody loses later.
14
+ */
15
+ export function declaresState(predicate) {
16
+ if (predicate.kind === PredicateKind.STATE)
17
+ return true;
18
+ if (predicate.kind === PredicateKind.ALL_OF || predicate.kind === PredicateKind.ANY_OF) {
19
+ return predicate.predicates.some(declaresState);
20
+ }
21
+ if (predicate.kind === PredicateKind.NOT)
22
+ return declaresState(predicate.predicate);
23
+ return false;
24
+ }
25
+ /**
26
+ * Does the caller's predicate judge the DOM — an `element` or `text` clause anywhere in the tree?
27
+ *
28
+ * The question behind it is where a verdict is allowed to point. A DOM predicate has its own locus:
29
+ * the element it matched, whose `file:line` the descriptor already carries. A `signal`/`net`/`state`
30
+ * failure has none — there is no node for "the request was never made" — and that is the one case
31
+ * where the verdict borrows the last driven control's line, because the handler that should have
32
+ * fired lives there.
33
+ *
34
+ * Walks composites for the same reason `declaresState` does: `allOf[{element}, {signal}]` looked at
35
+ * the DOM exactly as much as a bare `{element}` did.
36
+ */
37
+ export function declaresDom(predicate) {
38
+ if (predicate.kind === PredicateKind.ELEMENT || predicate.kind === PredicateKind.TEXT)
39
+ return true;
40
+ if (predicate.kind === PredicateKind.ALL_OF || predicate.kind === PredicateKind.ANY_OF) {
41
+ return predicate.predicates.some(declaresDom);
42
+ }
43
+ if (predicate.kind === PredicateKind.NOT)
44
+ return declaresDom(predicate.predicate);
45
+ return false;
46
+ }