@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,215 @@
1
+ import { EventType, URL_RAW, urlForMatch } from '@reticlehq/core';
2
+ import { asNumber, asString } from '@reticlehq/core';
3
+ import { mergeNetworkDetail } from './network-detail-merge.js';
4
+ /**
5
+ * The friendly bucket names reticle_observe's `filters` param advertises → the real event types.
6
+ *
7
+ * The schema promised `dom | net | route | console | animation | signal`, but the handler filtered
8
+ * with `filters.includes(e.type)` against types like `net.request` and `dom.added` — so every
9
+ * documented value matched nothing, and an agent passing `filters:['net']` to trim its payload got an
10
+ * EMPTY timeline instead. Empty reads as "the app did nothing" — a false green produced by using the
11
+ * feature exactly as documented. Mapping the bucket to its member types makes the documented values
12
+ * work; raw types are still accepted (see eventMatchesFilters) so neither spelling surprises a caller.
13
+ */
14
+ export const OBSERVE_FILTER_BUCKETS = {
15
+ dom: [EventType.DOM_ADDED, EventType.DOM_REMOVED, EventType.DOM_ATTR, EventType.DOM_TEXT],
16
+ net: [EventType.NET_REQUEST, EventType.NET_PENDING, EventType.NET_STREAM],
17
+ route: [EventType.ROUTE_CHANGE],
18
+ console: [EventType.CONSOLE_ERROR, EventType.ERROR_UNCAUGHT],
19
+ animation: [EventType.ANIM_START, EventType.ANIM_END],
20
+ signal: [EventType.SIGNAL],
21
+ // perf/state/storage are single-type buckets. They resolve through the raw-type fallback anyway,
22
+ // but naming them keeps the advertised vocabulary and the real one identical — the mismatch between
23
+ // those two is the bug this map exists to fix, so leaving observable types out of it would reopen it.
24
+ perf: [EventType.PERF],
25
+ state: [EventType.STATE_CHANGE],
26
+ storage: [EventType.STORAGE_CHANGE],
27
+ };
28
+ /**
29
+ * True when an event passes an observe `filters` allowlist. A filter entry matches either as a bucket
30
+ * name (`net` keeps every net.* type) or as a raw event type (`net.request`). Unknown entries match
31
+ * nothing rather than throwing — a typo narrows the result, it never crashes the observe.
32
+ */
33
+ export function eventMatchesFilters(e, filters) {
34
+ for (const f of filters) {
35
+ // `Object.hasOwn`, not a bare index: a plain-object map inherits from Object.prototype, so a
36
+ // filter value like "toString" or "hasOwnProperty" would resolve to the inherited FUNCTION and
37
+ // then `.includes` would throw — a crash on an odd-but-harmless agent input. Only an OWN key is a
38
+ // real bucket; anything else falls through to the raw-type comparison.
39
+ const bucket = Object.hasOwn(OBSERVE_FILTER_BUCKETS, f) ? OBSERVE_FILTER_BUCKETS[f] : undefined;
40
+ if (bucket !== undefined ? bucket.includes(e.type) : e.type === f)
41
+ return true;
42
+ }
43
+ return false;
44
+ }
45
+ /**
46
+ * Match a net.request event against optional method/url/status/ok filters (reticle_network).
47
+ *
48
+ * `ok` is the filter the tool's own description points at for desktop IPC, whose 200/500 is derived
49
+ * rather than sent by any server. A still-PENDING call never matches an `ok` filter in either
50
+ * direction: unresolved is not the same as failed, and answering "yes, it failed" about a request
51
+ * still in flight is the false green this whole surface exists to prevent.
52
+ */
53
+ export function matchNet(e, method, urlContains, status, ok) {
54
+ const d = e.data;
55
+ if (method !== undefined && asString(d['method'])?.toUpperCase() !== method.toUpperCase()) {
56
+ return false;
57
+ }
58
+ if (urlContains !== undefined && !urlForMatch(d).includes(urlContains)) {
59
+ return false;
60
+ }
61
+ if (status !== undefined && asNumber(d['status']) !== status)
62
+ return false;
63
+ if (ok !== undefined && d['ok'] !== ok)
64
+ return false;
65
+ return true;
66
+ }
67
+ /**
68
+ * Reconcile network events into completed calls + still-in-flight calls. A NET_PENDING whose
69
+ * `id` never gets a matching NET_REQUEST is an unresolved/hung request — the case
70
+ * completion-only logging is blind to. Pending events are annotated `{ status: 'pending',
71
+ * pending: true }` so a numeric `status` filter excludes them but `urlContains`/`method` match.
72
+ */
73
+ export function reconcileNet(events) {
74
+ // Fold CDP-authoritative detail (driven path) onto the matching in-page request first, so the driven
75
+ // view carries the full headers/status the page-side wrapper couldn't see (no-op when none present).
76
+ events = mergeNetworkDetail(events);
77
+ const completed = events.filter((e) => e.type === EventType.NET_REQUEST);
78
+ const doneIds = new Set(completed.map((e) => asString(e.data['id'])).filter((id) => id !== undefined));
79
+ const unresolved = events
80
+ .filter((e) => {
81
+ if (e.type !== EventType.NET_PENDING)
82
+ return false;
83
+ const id = asString(e.data['id']);
84
+ return id === undefined || !doneIds.has(id);
85
+ })
86
+ .map((e) => ({ ...e, data: { ...e.data, status: 'pending', pending: true } }));
87
+ return [...completed, ...unresolved].sort((a, b) => a.t - b.t);
88
+ }
89
+ /**
90
+ * Strip the grader-only raw URL before an event is rendered to the agent.
91
+ *
92
+ * `urlRaw` exists so `urlContains` can match a path redaction rewrote. It is a secret-bearing field
93
+ * by construction (the whole reason `url` was redacted) and must never appear in observe, evidence,
94
+ * or a network listing.
95
+ */
96
+ export function withoutUrlRaw(event) {
97
+ if (typeof event !== 'object' || null === event)
98
+ return event;
99
+ const rec = event;
100
+ const data = rec['data'];
101
+ if (typeof data !== 'object' || null === data || !(URL_RAW in data))
102
+ return event;
103
+ const { [URL_RAW]: _raw, ...rest } = data;
104
+ return { ...rec, data: rest };
105
+ }
106
+ export function projectNetCall(e, includeBodies = true) {
107
+ const status = e.data['status'];
108
+ const ms = asNumber(e.data['durationMs']);
109
+ const statusText = asString(e.data['statusText']);
110
+ const contentType = asString(e.data['contentType']);
111
+ const responseSize = asNumber(e.data['responseSize']);
112
+ const requestBody = asString(e.data['requestBody']);
113
+ const responseBody = asString(e.data['responseBody']);
114
+ const view = {
115
+ method: asString(e.data['method']) ?? '',
116
+ url: asString(e.data['url']) ?? '',
117
+ };
118
+ if ('number' === typeof status || 'string' === typeof status)
119
+ view.status = status;
120
+ if (statusText !== undefined)
121
+ view.statusText = statusText;
122
+ if (contentType !== undefined)
123
+ view.contentType = contentType;
124
+ if (responseSize !== undefined)
125
+ view.responseSize = responseSize;
126
+ // Bodies dominate the payload of the most-called read tool, and are only occasionally the part
127
+ // anyone wanted — `bodies: false` on reticle_network drops them for a body-free listing (#401).
128
+ if (includeBodies && requestBody !== undefined)
129
+ view.requestBody = requestBody;
130
+ if (includeBodies && responseBody !== undefined)
131
+ view.responseBody = responseBody;
132
+ if (includeBodies &&
133
+ (true === e.data['requestBodyTruncated'] || true === e.data['responseBodyTruncated'])) {
134
+ view.bodyTruncated = true;
135
+ }
136
+ if (ms !== undefined)
137
+ view.ms = ms;
138
+ if (true === e.data['oneWay'])
139
+ view.oneWay = true;
140
+ const headers = e.data['headers'];
141
+ if (headers !== null && 'object' === typeof headers) {
142
+ view.headers = headers;
143
+ }
144
+ return view;
145
+ }
146
+ /**
147
+ * How many stack frames reach the agent.
148
+ *
149
+ * A raw stack is mostly framework internals, and padding a failure report with them is not free —
150
+ * the frames that identify the origin are the first few, and everything after is context the agent
151
+ * has to read past. Four keeps the error line plus the app frames that actually called it.
152
+ */
153
+ const MAX_STACK_FRAMES = 4;
154
+ /** Trim a stack to the frames that locate the fault. */
155
+ function topFrames(stack) {
156
+ return stack.split('\n').slice(0, MAX_STACK_FRAMES).join('\n');
157
+ }
158
+ export function projectConsoleLog(e) {
159
+ const level = e.type === EventType.ERROR_UNCAUGHT ? 'error' : e.type.replace('console.', '');
160
+ const view = { level, text: asString(e.data['message']) ?? '' };
161
+ const stack = asString(e.data['stack']);
162
+ if (stack !== undefined && stack.length > 0)
163
+ view.stack = topFrames(stack);
164
+ // An uncaught error reports its origin as discrete fields rather than in a stack; render them in
165
+ // the same file:line form the element descriptors use so the agent reads one shape everywhere.
166
+ const source = asString(e.data['source']);
167
+ const line = e.data['line'];
168
+ if (source !== undefined && source.length > 0) {
169
+ view.source = 'number' === typeof line ? `${source}:${String(line)}` : source;
170
+ }
171
+ return view;
172
+ }
173
+ /** True for any console.* / uncaught-error event (the reticle_console universe). */
174
+ export function isConsoleEvent(e) {
175
+ return (e.type === EventType.CONSOLE_LOG ||
176
+ e.type === EventType.CONSOLE_WARN ||
177
+ e.type === EventType.CONSOLE_ERROR ||
178
+ e.type === EventType.CONSOLE_INFO ||
179
+ e.type === EventType.CONSOLE_DEBUG ||
180
+ e.type === EventType.ERROR_UNCAUGHT);
181
+ }
182
+ /** Match a console/error event against an optional level filter (reticle_console). */
183
+ export function matchConsole(e, level) {
184
+ if (!isConsoleEvent(e))
185
+ return false;
186
+ if (level === undefined)
187
+ return true;
188
+ return (e.type === `console.${level}` || ('error' === level && e.type === EventType.ERROR_UNCAUGHT));
189
+ }
190
+ /** How many present calls/levels a zero-match hint samples before truncating. */
191
+ const HINT_SAMPLE_MAX = 5;
192
+ export function netEmptyHint(allNet) {
193
+ const present = allNet
194
+ .slice(-HINT_SAMPLE_MAX)
195
+ .reverse()
196
+ .map((e) => {
197
+ const status = asNumber(e.data['status']);
198
+ const base = { method: asString(e.data['method']) ?? '', url: asString(e.data['url']) ?? '' };
199
+ return status === undefined ? base : { ...base, status };
200
+ });
201
+ return { totalInWindow: allNet.length, present };
202
+ }
203
+ export function consoleEmptyHint(allConsole) {
204
+ const byLevel = { log: 0, warn: 0, error: 0 };
205
+ for (const e of allConsole) {
206
+ if (e.type === EventType.CONSOLE_LOG)
207
+ byLevel.log += 1;
208
+ else if (e.type === EventType.CONSOLE_WARN)
209
+ byLevel.warn += 1;
210
+ else if (e.type === EventType.CONSOLE_ERROR || e.type === EventType.ERROR_UNCAUGHT) {
211
+ byLevel.error += 1;
212
+ }
213
+ }
214
+ return { totalInWindow: allConsole.length, byLevel };
215
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Read what CAN be read out of a truncated JSON payload.
3
+ *
4
+ * Response bodies are capped (8192 bytes) so one enormous payload cannot blow the transport budget.
5
+ * The cap is right; treating what it produces as "no body" is not. Measured on a 10,000-row console:
6
+ * the list response is 19,932 bytes, arrives truncated mid-object, `JSON.parse` throws, and every
7
+ * body-based check — currency reconciliation, per-item failures, unit mismatches — silently reported
8
+ * nothing on the one page with the most data to be wrong about.
9
+ *
10
+ * Worse, the tool then advised turning on body capture, which was already on. Advice that cannot
11
+ * work is more expensive than silence: it sends the reader to change a setting that is already
12
+ * correct, and teaches them the tool does not know what it is looking at.
13
+ *
14
+ * A truncated array of records is still mostly complete records. This recovers the ones that closed
15
+ * before the cut and reports how many it had to drop, so a partial answer is delivered AS partial
16
+ * rather than as a clean one.
17
+ */
18
+ interface Salvaged {
19
+ /** Parsed values — one whole body, or the records recovered from a truncated one. */
20
+ values: unknown[];
21
+ /** True when the payload was incomplete and only part of it could be read. */
22
+ partial: boolean;
23
+ }
24
+ /**
25
+ * Parse a body, falling back to whole records when it was cut short.
26
+ *
27
+ * The nesting caveat is real and stated rather than hidden: an object cut mid-nesting contributes its
28
+ * completed CHILDREN instead of itself, so a salvaged set can hold records the envelope would have
29
+ * grouped differently. For field-level comparison — is this id's currency rendered correctly — that
30
+ * costs nothing, because each record still carries its own id and its own fields.
31
+ */
32
+ export declare function salvageJson(raw: string): Salvaged;
33
+ export {};
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Read what CAN be read out of a truncated JSON payload.
3
+ *
4
+ * Response bodies are capped (8192 bytes) so one enormous payload cannot blow the transport budget.
5
+ * The cap is right; treating what it produces as "no body" is not. Measured on a 10,000-row console:
6
+ * the list response is 19,932 bytes, arrives truncated mid-object, `JSON.parse` throws, and every
7
+ * body-based check — currency reconciliation, per-item failures, unit mismatches — silently reported
8
+ * nothing on the one page with the most data to be wrong about.
9
+ *
10
+ * Worse, the tool then advised turning on body capture, which was already on. Advice that cannot
11
+ * work is more expensive than silence: it sends the reader to change a setting that is already
12
+ * correct, and teaches them the tool does not know what it is looking at.
13
+ *
14
+ * A truncated array of records is still mostly complete records. This recovers the ones that closed
15
+ * before the cut and reports how many it had to drop, so a partial answer is delivered AS partial
16
+ * rather than as a clean one.
17
+ */
18
+ /**
19
+ * Complete `{...}` objects inside a truncated payload, in order.
20
+ *
21
+ * NOT top-level ones: a cut body is typically `{"rows":[{…},{…},{…` where the OUTER brace never
22
+ * closes, so nothing at depth 0 completes and a depth-0 scan recovers exactly nothing. The records
23
+ * are one level in.
24
+ *
25
+ * Objects are kept only at the SHALLOWEST depth at which anything closes — that is the record level.
26
+ * Keeping every depth would also return each record's nested children (a shipment's legs, an order's
27
+ * line items), and those carry their own `id` and `status`, which would pollute the comparison with
28
+ * values that were never meant to be rendered as rows.
29
+ */
30
+ function completeObjects(text) {
31
+ const found = [];
32
+ let depth = 0;
33
+ const starts = [];
34
+ let inString = false;
35
+ let escaped = false;
36
+ for (let i = 0; i < text.length; i += 1) {
37
+ const ch = text[i];
38
+ if (inString) {
39
+ if (escaped)
40
+ escaped = false;
41
+ else if ('\\' === ch)
42
+ escaped = true;
43
+ else if ('"' === ch)
44
+ inString = false;
45
+ continue;
46
+ }
47
+ if ('"' === ch) {
48
+ inString = true;
49
+ continue;
50
+ }
51
+ if ('{' === ch) {
52
+ starts.push(i);
53
+ depth += 1;
54
+ continue;
55
+ }
56
+ if ('}' === ch) {
57
+ depth -= 1;
58
+ // A negative depth means the cut removed an opening brace; nothing further is trustworthy.
59
+ if (depth < 0)
60
+ break;
61
+ const start = starts.pop();
62
+ if (start !== undefined)
63
+ found.push({ depth: depth + 1, text: text.slice(start, i + 1) });
64
+ }
65
+ }
66
+ if (0 === found.length)
67
+ return [];
68
+ const shallowest = Math.min(...found.map((f) => f.depth));
69
+ return found.filter((f) => f.depth === shallowest).map((f) => f.text);
70
+ }
71
+ /**
72
+ * Parse a body, falling back to whole records when it was cut short.
73
+ *
74
+ * The nesting caveat is real and stated rather than hidden: an object cut mid-nesting contributes its
75
+ * completed CHILDREN instead of itself, so a salvaged set can hold records the envelope would have
76
+ * grouped differently. For field-level comparison — is this id's currency rendered correctly — that
77
+ * costs nothing, because each record still carries its own id and its own fields.
78
+ */
79
+ export function salvageJson(raw) {
80
+ try {
81
+ return { values: [JSON.parse(raw)], partial: false };
82
+ }
83
+ catch {
84
+ // fall through to record-level recovery
85
+ }
86
+ const values = [];
87
+ for (const chunk of completeObjects(raw)) {
88
+ try {
89
+ values.push(JSON.parse(chunk));
90
+ }
91
+ catch {
92
+ // a chunk that still will not parse is simply not recovered
93
+ }
94
+ }
95
+ return { values, partial: true };
96
+ }
@@ -0,0 +1,8 @@
1
+ import { type ReticleEvent } from '@reticlehq/core';
2
+ /**
3
+ * Fold each NET_DETAIL onto the matching in-page NET_REQUEST (by method+url), enriching it with the
4
+ * authoritative headers/resourceType the page-side wrapper couldn't see — WITHOUT clobbering fields the
5
+ * in-page event already carries. A NET_DETAIL with no matching request is kept as its own event (a
6
+ * response the wrapper missed is signal, never silently dropped). Pure over the event list.
7
+ */
8
+ export declare function mergeNetworkDetail(events: readonly ReticleEvent[]): ReticleEvent[];
@@ -0,0 +1,89 @@
1
+ import { EventType, urlForMatch } from '@reticlehq/core';
2
+ /**
3
+ * Folding the browser's own view of a network request together with the daemon's.
4
+ *
5
+ * Two things watch the same request. The page-side wrapper sees what the app asked for; the daemon,
6
+ * when it drives the browser itself, sees what actually went over the wire. This puts the two
7
+ * records back together into one event, so a reader is not left comparing two half-pictures.
8
+ *
9
+ * It sits with the rules that decide a verdict, not with the code that collects observations,
10
+ * because it is a decision about what happened rather than a way of finding out. Anything the rules
11
+ * need has to travel with them.
12
+ *
13
+ * Example: the app sends `{"qty":"2"}` and the wire carries `{"qty":2}`. The merged event keeps the
14
+ * wire value and marks `requestBodyDivergedFromPage`, so the disagreement survives instead of one
15
+ * side quietly winning.
16
+ */
17
+ /**
18
+ * The merge key: method plus the RAW url when the observation kept one, else the displayed url.
19
+ *
20
+ * Never the displayed url alone. The two sides redact independently, the SDK under the page's own
21
+ * policy and this module under the daemon's, so the one field they were being compared on is the one
22
+ * field redaction is allowed to rewrite. Keying on `urlForMatch` compares what was actually
23
+ * requested, which is identical on both sides by construction.
24
+ */
25
+ function keyOf(data) {
26
+ const method = data['method'];
27
+ const m = 'string' === typeof method ? method.toUpperCase() : '';
28
+ return `${m} ${urlForMatch(data)}`;
29
+ }
30
+ /**
31
+ * Fold each NET_DETAIL onto the matching in-page NET_REQUEST (by method+url), enriching it with the
32
+ * authoritative headers/resourceType the page-side wrapper couldn't see — WITHOUT clobbering fields the
33
+ * in-page event already carries. A NET_DETAIL with no matching request is kept as its own event (a
34
+ * response the wrapper missed is signal, never silently dropped). Pure over the event list.
35
+ */
36
+ export function mergeNetworkDetail(events) {
37
+ const requestByKey = new Map();
38
+ for (const e of events) {
39
+ if (e.type === EventType.NET_REQUEST)
40
+ requestByKey.set(keyOf(e.data), e);
41
+ }
42
+ const out = [];
43
+ const enriched = new Map();
44
+ for (const e of events) {
45
+ if (e.type === EventType.NET_DETAIL) {
46
+ const match = requestByKey.get(keyOf(e.data));
47
+ if (match === undefined) {
48
+ out.push(e); // unmatched detail survives on its own
49
+ continue;
50
+ }
51
+ const base = enriched.get(match) ?? match;
52
+ const data = { ...base.data };
53
+ if (data['headers'] === undefined && e.data['headers'] !== undefined) {
54
+ data['headers'] = e.data['headers'];
55
+ }
56
+ if (data['resourceType'] === undefined && e.data['resourceType'] !== undefined) {
57
+ data['resourceType'] = e.data['resourceType'];
58
+ }
59
+ // The ONLY field that overwrites rather than filling a gap. The in-page value is what the app
60
+ // INTENDED to send; this is what actually went. When they disagree, the disagreement is the
61
+ // finding — that is the whole reason for capturing it — so the authoritative one wins and the
62
+ // divergence is flagged rather than silently resolved.
63
+ const wireBody = e.data['requestBody'];
64
+ if ('string' === typeof wireBody) {
65
+ const pageBody = data['requestBody'];
66
+ if ('string' === typeof pageBody && pageBody !== wireBody) {
67
+ data['requestBodyDivergedFromPage'] = true;
68
+ }
69
+ data['requestBody'] = wireBody;
70
+ // The caveat belongs to the body it describes, and this is the one field that REPLACES
71
+ // rather than fills a gap. Carried over when the wire body was cut, deleted when it was not:
72
+ // a stale `true` from the page capture would caveat a body that is now whole, and a missing
73
+ // one would let a cut body read as complete.
74
+ if (true === e.data['requestBodyTruncated'])
75
+ data['requestBodyTruncated'] = true;
76
+ else
77
+ delete data['requestBodyTruncated'];
78
+ }
79
+ enriched.set(match, { ...base, data });
80
+ continue; // the detail is absorbed into the request
81
+ }
82
+ }
83
+ for (const e of events) {
84
+ if (e.type === EventType.NET_DETAIL)
85
+ continue; // handled above
86
+ out.push(enriched.get(e) ?? e);
87
+ }
88
+ return out;
89
+ }
@@ -0,0 +1,41 @@
1
+ import { type ReticleEvent } from '@reticlehq/core';
2
+ interface RingBufferOptions {
3
+ maxEvents?: number;
4
+ maxAgeMs?: number;
5
+ maxBytes?: number;
6
+ }
7
+ /**
8
+ * Bounded, time-aware event store per session. The single data structure that powers
9
+ * observe/wait_for/assert — it lets us look both backward (recent buffer) and
10
+ * forward (await new events).
11
+ *
12
+ * Eviction advances a HEAD index instead of shift/splice — O(1) per dropped event (was O(n) per
13
+ * shift, i.e. O(n) per push at steady state under the DOM/animation floods). The dead prefix is
14
+ * compacted away once it dominates, so the backing arrays stay bounded (amortized O(1)).
15
+ *
16
+ * `now` is injected so the buffer is deterministically testable (inject the clock, never call
17
+ * Date.now inside logic).
18
+ */
19
+ export declare class RingBuffer {
20
+ #private;
21
+ constructor(options?: RingBufferOptions);
22
+ push(event: ReticleEvent, now: number, byteSize?: number): void;
23
+ /** Events at or after a given timestamp cursor. */
24
+ since(cursor: number): ReticleEvent[];
25
+ /** Events within the last `windowMs`, relative to `now`. */
26
+ window(windowMs: number, now: number): ReticleEvent[];
27
+ /**
28
+ * Did this buffer evict scarce evidence that belonged to a window opened at `cursor`?
29
+ *
30
+ * The one honest input to "was the capture clean". A `false` here means every non-churn event in
31
+ * the window is still held, whatever the drop counter says — and the drop counter says a great
32
+ * deal, because age eviction runs on every push.
33
+ */
34
+ lostSince(cursor: number): boolean;
35
+ /** Snapshot of buffer health for the agent — live events held and cumulative drops since connect. */
36
+ bufferHealth(): {
37
+ total: number;
38
+ dropped: number;
39
+ };
40
+ }
41
+ export {};
@@ -0,0 +1,152 @@
1
+ import { CHURN_TYPES, RING_BUFFER_DEFAULTS } from '@reticlehq/core';
2
+ import { byteSizeOf } from './byte-size.js';
3
+ /** How far forward to look for a churn event to sacrifice before falling back to plain FIFO. */
4
+ const CHURN_SCAN_LIMIT = 256;
5
+ /**
6
+ * Bounded, time-aware event store per session. The single data structure that powers
7
+ * observe/wait_for/assert — it lets us look both backward (recent buffer) and
8
+ * forward (await new events).
9
+ *
10
+ * Eviction advances a HEAD index instead of shift/splice — O(1) per dropped event (was O(n) per
11
+ * shift, i.e. O(n) per push at steady state under the DOM/animation floods). The dead prefix is
12
+ * compacted away once it dominates, so the backing arrays stay bounded (amortized O(1)).
13
+ *
14
+ * `now` is injected so the buffer is deterministically testable (inject the clock, never call
15
+ * Date.now inside logic).
16
+ */
17
+ export class RingBuffer {
18
+ #maxEvents;
19
+ #maxAgeMs;
20
+ #maxBytes;
21
+ #events = [];
22
+ #eventBytes = [];
23
+ /** Index of the first LIVE event; [0, #head) are evicted but not yet compacted out of the arrays. */
24
+ #head = 0;
25
+ #totalBytes = 0;
26
+ #droppedCount = 0;
27
+ /**
28
+ * The timestamp of the newest NON-CHURN event this buffer has ever evicted, or `undefined` if it
29
+ * has never lost one. This — not the drop counter — is what impeaches an observation window.
30
+ *
31
+ * The counter cannot answer the question. It moves for age eviction (everything past 60s, on every
32
+ * push) and for churn eviction (the low-signal floor, sacrificed on purpose so scarce evidence
33
+ * survives), neither of which is evidence lost from the window an agent just observed. See
34
+ * `lostSince` and `ring-buffer-window-loss.test.ts`.
35
+ */
36
+ #lastScarceLossT;
37
+ constructor(options = {}) {
38
+ this.#maxEvents = options.maxEvents ?? RING_BUFFER_DEFAULTS.MAX_EVENTS;
39
+ this.#maxAgeMs = options.maxAgeMs ?? RING_BUFFER_DEFAULTS.MAX_AGE_MS;
40
+ this.#maxBytes = options.maxBytes ?? RING_BUFFER_DEFAULTS.MAX_BYTES;
41
+ }
42
+ #liveCount() {
43
+ return this.#events.length - this.#head;
44
+ }
45
+ push(event, now, byteSize) {
46
+ this.#events.push(event);
47
+ // Prefer the size measured at the parse boundary (the raw wire frame the bridge already has) over
48
+ // re-serializing here — a JSON.stringify per pushed event was the buffer's highest constant cost.
49
+ const bytes = byteSize ?? byteSizeOf(JSON.stringify(event));
50
+ this.#eventBytes.push(bytes);
51
+ this.#totalBytes += bytes;
52
+ this.#evict(now);
53
+ }
54
+ /** Events at or after a given timestamp cursor. */
55
+ since(cursor) {
56
+ return this.#events.slice(this.#lowerBound(cursor));
57
+ }
58
+ /** Events within the last `windowMs`, relative to `now`. */
59
+ window(windowMs, now) {
60
+ return this.#events.slice(this.#lowerBound(now - windowMs));
61
+ }
62
+ /** Binary search over the LIVE window [#head, length) for the first event at/after `target`. */
63
+ #lowerBound(target) {
64
+ let lo = this.#head;
65
+ let hi = this.#events.length;
66
+ while (lo < hi) {
67
+ const mid = (lo + hi) >>> 1;
68
+ if ((this.#events[mid]?.t ?? 0) < target)
69
+ lo = mid + 1;
70
+ else
71
+ hi = mid;
72
+ }
73
+ return lo;
74
+ }
75
+ #evict(now) {
76
+ const cutoff = now - this.#maxAgeMs;
77
+ const before = this.#liveCount();
78
+ // Cap/byte pressure: sacrifice the CHURN floor before scarce evidence. The head is usually churn on
79
+ // a busy page, so this stays the O(1) head-advance; only when the oldest event is worth keeping do we
80
+ // look forward (bounded) for a churn event to drop instead.
81
+ // Byte pressure keeps at least ONE event: a single event larger than the whole byte budget would
82
+ // otherwise be pushed and then immediately self-evicted, so a waiter for it never saw it and only
83
+ // `dropped` moved. Bytes is a soft cap and per-value serialization already bounds any one event, so
84
+ // keeping the sole survivor over the budget is the correct trade. The count cap (maxEvents, ~2000)
85
+ // is a hard bound and stays `> maxEvents`.
86
+ while (this.#liveCount() > this.#maxEvents ||
87
+ (this.#totalBytes > this.#maxBytes && this.#liveCount() > 1)) {
88
+ if (CHURN_TYPES.has(this.#events[this.#head]?.type ?? '')) {
89
+ this.#totalBytes -= this.#eventBytes[this.#head] ?? 0;
90
+ this.#head += 1;
91
+ continue;
92
+ }
93
+ const victim = this.#findChurnAfterHead();
94
+ if (-1 === victim) {
95
+ // Buffer genuinely full of high-signal events — fall back to FIFO so it stays bounded. This
96
+ // is the one eviction path that destroys scarce evidence, and the only one that should ever
97
+ // make a verdict say it could not see.
98
+ this.#noteScarceLoss(this.#head);
99
+ this.#totalBytes -= this.#eventBytes[this.#head] ?? 0;
100
+ this.#head += 1;
101
+ continue;
102
+ }
103
+ this.#totalBytes -= this.#eventBytes[victim] ?? 0;
104
+ this.#events.splice(victim, 1); // order preserved; victim > #head so the head stays valid
105
+ this.#eventBytes.splice(victim, 1);
106
+ }
107
+ while (this.#liveCount() > 0 && (this.#events[this.#head]?.t ?? cutoff) < cutoff) {
108
+ this.#noteScarceLoss(this.#head);
109
+ this.#totalBytes -= this.#eventBytes[this.#head] ?? 0;
110
+ this.#head += 1;
111
+ }
112
+ this.#droppedCount += before - this.#liveCount();
113
+ // Reclaim the dead prefix once it dominates the backing arrays (amortized O(1) compaction).
114
+ if (this.#head > 1024 && this.#head * 2 >= this.#events.length) {
115
+ this.#events = this.#events.slice(this.#head);
116
+ this.#eventBytes = this.#eventBytes.slice(this.#head);
117
+ this.#head = 0;
118
+ }
119
+ }
120
+ /** Record an eviction at `index` as scarce loss, unless it was the churn floor being sacrificed. */
121
+ #noteScarceLoss(index) {
122
+ const victim = this.#events[index];
123
+ if (victim === undefined || CHURN_TYPES.has(victim.type))
124
+ return;
125
+ if (this.#lastScarceLossT === undefined || victim.t > this.#lastScarceLossT) {
126
+ this.#lastScarceLossT = victim.t;
127
+ }
128
+ }
129
+ /**
130
+ * Did this buffer evict scarce evidence that belonged to a window opened at `cursor`?
131
+ *
132
+ * The one honest input to "was the capture clean". A `false` here means every non-churn event in
133
+ * the window is still held, whatever the drop counter says — and the drop counter says a great
134
+ * deal, because age eviction runs on every push.
135
+ */
136
+ lostSince(cursor) {
137
+ return this.#lastScarceLossT !== undefined && this.#lastScarceLossT >= cursor;
138
+ }
139
+ /** First churn event after the head, or -1 if none within the bounded scan (keeps eviction cheap). */
140
+ #findChurnAfterHead() {
141
+ const end = Math.min(this.#events.length, this.#head + CHURN_SCAN_LIMIT);
142
+ for (let i = this.#head + 1; i < end; i++) {
143
+ if (CHURN_TYPES.has(this.#events[i]?.type ?? ''))
144
+ return i;
145
+ }
146
+ return -1;
147
+ }
148
+ /** Snapshot of buffer health for the agent — live events held and cumulative drops since connect. */
149
+ bufferHealth() {
150
+ return { total: this.#liveCount(), dropped: this.#droppedCount };
151
+ }
152
+ }