@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
@@ -220,6 +220,17 @@ const DOCUMENT_INITIATORS = new Set([
220
220
  'manifest',
221
221
  'other',
222
222
  ]);
223
+ /**
224
+ * Whether a request was a subresource the DOCUMENT fetched (script, stylesheet, image…), as the
225
+ * resource-timing observer stamps them, rather than one the app sent through fetch, XHR, a beacon or
226
+ * IPC. The capsule's blast radius uses it to keep a page load out of "what this action also did".
227
+ */
228
+ export function isDocumentInitiated(event) {
229
+ if (event.type !== EventType.NET_REQUEST)
230
+ return false;
231
+ const initiator = str(event.data['initiator']);
232
+ return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
233
+ }
223
234
  /**
224
235
  * Did the observer actually report a document-initiated load?
225
236
  *
@@ -232,12 +243,7 @@ const DOCUMENT_INITIATORS = new Set([
232
243
  * document-initiated record anywhere in the window proves the channel works.
233
244
  */
234
245
  function observerSawSubresources(events) {
235
- return events.some((e) => {
236
- if (e.type !== EventType.NET_REQUEST)
237
- return false;
238
- const initiator = str(e.data['initiator']);
239
- return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
240
- });
246
+ return events.some(isDocumentInitiated);
241
247
  }
242
248
  /** The sentence both zero-match branches hand to `inconclusive`. */
243
249
  function unobservedChannelReason(p) {
@@ -450,7 +456,7 @@ export function evalNet(events, p) {
450
456
  if (truncatedBody !== undefined && 0 === matches.length) {
451
457
  return {
452
458
  pass: false,
453
- inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. Raise the capture cap or assert on something inside the recorded prefix`,
459
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. The cap is per-body and set where the app calls connect(): \`reticle.connect({ captureNetworkBodies: true, networkBodyMaxChars: 65536 })\`, or for the Vite plugin \`reticle({ networkBodyMaxChars: 65536 })\` / VITE_RETICLE_BODY_MAX_CHARS=65536 (default 8192, max 262144). An SDK older than this daemon ignores the option; a version skew on the session says so. Raise it past this response's size and re-run, or assert on something inside the recorded prefix`,
454
460
  observed: `the first ${String(truncatedBody.length)} characters of a truncated response body ${JSON.stringify(clipBody(truncatedBody))}`,
455
461
  expected: `a response body carrying ${wantedBody(p)}`,
456
462
  assertion: 'net.bodyContains',
@@ -16,7 +16,7 @@ interface RequestBodyPredicate {
16
16
  * Accumulated during the single pass over events rather than recomputed after it, the way the
17
17
  * response-side trackers already are.
18
18
  */
19
- export interface RequestBodyState {
19
+ interface RequestBodyState {
20
20
  /** A call matched everything else but carried no recorded request body. */
21
21
  unrecorded: boolean;
22
22
  /** The request body a clause was checked against and did not match. */
@@ -38,7 +38,7 @@ export declare function routePathOf(pathname: string, hash: string): string;
38
38
  * is the NAVIGABLE value a `reticle_navigate` can be pointed at. Call sites pick; collapsing
39
39
  * them into one string is how a hash-router miss lands as "every page is `/`".
40
40
  */
41
- export interface RouteParts {
41
+ interface RouteParts {
42
42
  routePath: string;
43
43
  docPath: string;
44
44
  hash: string;
@@ -64,3 +64,4 @@ export declare function evalRoute(events: ReticleEvent[], p: Extract<Predicate,
64
64
  currentUrl?: string,
65
65
  /** Event-time floor for the window, so a request already in flight before it is not counted. */
66
66
  since?: number): EvalResult;
67
+ export {};
@@ -1,95 +1,16 @@
1
- import { ElementState, PredicateKind, type ElementDescriptor, type ElementQuery } from '@reticlehq/core';
1
+ /**
2
+ * What the predicate engine adds to the CONTRACT: the fields a browser locator drops, and the
3
+ * introspection the tool surface builds its descriptions from.
4
+ *
5
+ * The shape itself — `Predicate`, `PredicateSchema`, the aliases and the union — moved to
6
+ * `@reticlehq/core`, because a saved flow now carries one and core has to be able to parse what it
7
+ * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
+ * from here, so every existing importer of this module keeps working unchanged.
9
+ */
2
10
  import { z } from 'zod';
3
- import { type PropertyAssertion } from './property.js';
4
- export type Predicate = {
5
- kind: typeof PredicateKind.ELEMENT;
6
- query: ElementQuery;
7
- state?: ElementState;
8
- absent?: boolean;
9
- } | {
10
- kind: typeof PredicateKind.TEXT;
11
- contains: string;
12
- visible?: boolean;
13
- absent?: boolean;
14
- /**
15
- * Restrict the match to a subtree, as a CSS selector or a ref — the same field, and the same
16
- * meaning, as `scope` on an element query.
17
- *
18
- * Without it the match is page-wide, and a word that appears both in a background tab label
19
- * and in the dialog that just opened satisfies the predicate BEFORE the action runs, so
20
- * `act_and_wait` reports `already_true` for an action that did exactly the right thing.
21
- */
22
- scope?: string;
23
- /** Match the scope root itself and check its combined subtree text. Requires `scope`. */
24
- self?: boolean;
25
- } | {
26
- kind: typeof PredicateKind.NET;
27
- method?: string;
28
- urlContains?: string;
29
- status?: number;
30
- /** Did the call succeed? The honest field for IPC, which has no status code. */
31
- ok?: boolean;
32
- since?: number;
33
- count?: number;
34
- /** A substring the RESPONSE body must contain — what the server answered, not what was sent. */
35
- bodyContains?: string;
36
- /** Shallow JSON match over the RESPONSE body: this FIELD holds this value (#987). */
37
- bodyMatches?: Record<string, unknown>;
38
- /** A substring the REQUEST body must contain — what the UI sent, not what came back. */
39
- requestBodyContains?: string;
40
- /** Shallow JSON match over the REQUEST body, in the style of `signal.dataMatches`. */
41
- requestBodyMatches?: Record<string, unknown>;
42
- } | {
43
- kind: typeof PredicateKind.ROUTE;
44
- pathname?: string;
45
- contains?: string;
46
- since?: number;
47
- } | {
48
- kind: typeof PredicateKind.CONSOLE;
49
- level?: string;
50
- /**
51
- * A substring the captured message must contain. With `absent: true` this flips the meaning
52
- * from "no console entries at all" to "THIS message did not appear" — the assertion people
53
- * actually write regression checks for (deprecation warnings, no-op handler notices).
54
- */
55
- contains?: string;
56
- absent?: boolean;
57
- since?: number;
58
- } | {
59
- kind: typeof PredicateKind.ANIMATION;
60
- name?: string;
61
- target?: string;
62
- completed?: boolean;
63
- since?: number;
64
- } | {
65
- kind: typeof PredicateKind.SIGNAL;
66
- name?: string;
67
- dataMatches?: Record<string, unknown>;
68
- /**
69
- * Exact number of matching signals in the window — the same cardinality assertion `net`
70
- * carries, on the channel the app itself speaks. Omit for presence (≥1).
71
- */
72
- count?: number;
73
- since?: number;
74
- } | {
75
- kind: typeof PredicateKind.STATE;
76
- store?: string;
77
- path: string;
78
- equals?: unknown;
79
- satisfies?: PropertyAssertion;
80
- } | {
81
- kind: typeof PredicateKind.SETTLED;
82
- quietMs?: number;
83
- } | {
84
- kind: typeof PredicateKind.ALL_OF;
85
- predicates: Predicate[];
86
- } | {
87
- kind: typeof PredicateKind.ANY_OF;
88
- predicates: Predicate[];
89
- } | {
90
- kind: typeof PredicateKind.NOT;
91
- predicate: Predicate;
92
- };
11
+ import { type ElementDescriptor, type ElementQuery } from '@reticlehq/core';
12
+ export { PredicateSchema } from '@reticlehq/core';
13
+ export type { Predicate, PropertyAssertion } from '@reticlehq/core';
93
14
  interface ResidualQueryChecks {
94
15
  /** Dropped fields this side CAN check, as [field, wanted value] pairs. */
95
16
  checks: [string, string][];
@@ -109,7 +30,6 @@ export declare function residualQueryChecks(query: ElementQuery): ResidualQueryC
109
30
  export declare function satisfiesResiduals(element: ElementDescriptor, checks: readonly [string, string][]): boolean;
110
31
  /** How the element's own reading of a dropped field should be REPORTED back on a failure. */
111
32
  export declare function describeResidual(element: ElementDescriptor, field: string): string;
112
- export declare const PredicateSchema: z.ZodType<Predicate>;
113
33
  /**
114
34
  * The fields a given predicate kind accepts, read off the schema itself.
115
35
  *
@@ -169,4 +89,3 @@ export declare function nestedKeysOf(schema: z.ZodTypeAny | undefined): readonly
169
89
  * list is worse than none, because the agent trusts it and retries into the same wall.
170
90
  */
171
91
  export declare function predicateNestedFieldsFor(kind: string): Readonly<Record<string, readonly string[]>>;
172
- export {};
@@ -1,54 +1,17 @@
1
- import { ElementQuerySchema, ElementState, PredicateKind, QueryBy, } from '@reticlehq/core';
2
- import { z } from 'zod';
3
- import { propertyAssertionSchema } from './property.js';
4
- /**
5
- * Spellings an agent plausibly reaches for, mapped to the real field.
6
- *
7
- * `route` spells its field `pathname` while `state`, in the same union, spells its `path`. Every one
8
- * of these was silently DROPPED before, and because these kinds have all-optional fields, dropping
9
- * the only key supplied left a predicate that asserts nothing and passes on anything.
10
- */
11
- const PREDICATE_ALIASES = {
12
- // `text`/`value` on a `text` predicate: the kind is called "text", so `text:` is the first thing
13
- // anyone writes for it, and `value` follows from the element query's own `value` field. Both were
14
- // hard rejections, and a rejected predicate produces NO verdict at all — the drive ends with
15
- // nothing rather than with a failure, which is the worst outcome of the three.
16
- [PredicateKind.TEXT]: { text: 'contains', value: 'contains' },
17
- // `urlContains`/`url` reported from the field: an agent that had just written
18
- // `net { urlContains }` applied the same word to `route`, which spells it `contains`, and got
19
- // `unrecognized_keys` with no list of what would have worked. The parallel it assumed is a fair
20
- // one — route's `contains` matches the WHOLE route (path + query + fragment), so "the URL
21
- // contains this" is precisely what it does — and asserting a redirect after login is the single
22
- // most common thing an agent reaches for here.
23
- [PredicateKind.ROUTE]: { path: 'pathname', urlContains: 'contains', url: 'contains' },
24
- [PredicateKind.NET]: { url: 'urlContains', responseBodyMatches: 'bodyMatches' },
25
- // `textContains` on a `console` predicate: the reporter who hit the missing matcher reached for
26
- // it first, by analogy with `net { urlContains }` — and that parallel is exactly right, since
27
- // both mean "this entry must contain this substring". Accepted as an alias for `contains`.
28
- [PredicateKind.CONSOLE]: { textContains: 'contains' },
29
- [PredicateKind.SIGNAL]: { data: 'dataMatches' },
30
- // `of` on a composite: it reads naturally, several assertion libraries spell it that way, and it has
31
- // no other meaning here. Observed twice in one drive on a real app, and each rejection cost a round
32
- // trip AND produced no verdict — a composite is what an agent reaches for precisely when it has two
33
- // things to prove at once, so failing it is expensive at the worst moment.
34
- [PredicateKind.ALL_OF]: { of: 'predicates' },
35
- [PredicateKind.ANY_OF]: { of: 'predicates' },
36
- // `of` on `not` for the same reason it is accepted on the composites above — an agent that learned
37
- // the spelling one line earlier applies it to the third composite, and `not` was the one that
38
- // rejected it. The refusal did name `predicate`, but naming a field still costs the round trip
39
- // that produced no verdict, and the guess is unambiguous: `not` has exactly one child.
40
- [PredicateKind.NOT]: { of: 'predicate' },
41
- };
42
1
  /**
43
- * The word half the assertion world spells `kind`.
2
+ * What the predicate engine adds to the CONTRACT: the fields a browser locator drops, and the
3
+ * introspection the tool surface builds its descriptions from.
44
4
  *
45
- * A discriminated union rejects `{ type: "text", ... }` with "Invalid discriminator value" on a field
46
- * the caller never wrote, so the reply reads as being about `kind` — which is absent — and never
47
- * says the word `type`. Observed on a live drive as the first rung of a ladder: one field name
48
- * learned per rejected call, each costing a verdict. No predicate kind declares a `type` field, so
49
- * lifting it is unambiguous, and an explicit `kind` still wins.
5
+ * The shape itself — `Predicate`, `PredicateSchema`, the aliases and the union — moved to
6
+ * `@reticlehq/core`, because a saved flow now carries one and core has to be able to parse what it
7
+ * reads off disk. Core is the contract; this is the reasoning over it. Both halves are re-exported
8
+ * from here, so every existing importer of this module keeps working unchanged.
50
9
  */
51
- const KIND_SPELLING = 'type';
10
+ import { z } from 'zod';
11
+ import { PredicateKind, PredicateSchema, QueryBy, predicateShapeFor, } from '@reticlehq/core';
12
+ // One public surface, two packages. A caller asking this module for the shape is asking the right
13
+ // module; it simply no longer OWNS it.
14
+ export { PredicateSchema } from '@reticlehq/core';
52
15
  /**
53
16
  * Element-query fields an agent writes FLAT on an `element` predicate instead of nested under
54
17
  * `query`. `reticle_query` takes exactly these at the top level, so an agent that has just located
@@ -164,236 +127,6 @@ export function describeResidual(element, field) {
164
127
  : element.name;
165
128
  return `${element.role} "${element.name}" ${field}=${JSON.stringify(reading)}`;
166
129
  }
167
- /** `type` read as the discriminator when — and only when — `kind` is absent. */
168
- function renameKindSpelling(obj) {
169
- if (obj['kind'] !== undefined || 'string' !== typeof obj[KIND_SPELLING])
170
- return obj;
171
- const out = { ...obj, kind: obj[KIND_SPELLING] };
172
- delete out[KIND_SPELLING];
173
- return out;
174
- }
175
- /** Rename known aliases before parse; an explicit canonical key always wins. */
176
- function applyPredicateAliases(input) {
177
- if (typeof input !== 'object' || null === input || Array.isArray(input))
178
- return input;
179
- const given = input;
180
- const obj = renameKindSpelling(given);
181
- const kind = 'string' === typeof obj['kind'] ? obj['kind'] : '';
182
- const aliases = PREDICATE_ALIASES[kind];
183
- let out = obj;
184
- if (aliases !== undefined) {
185
- out = { ...obj };
186
- for (const [from, to] of Object.entries(aliases)) {
187
- if (out[from] === undefined)
188
- continue;
189
- if (out[to] === undefined)
190
- out[to] = out[from];
191
- delete out[from];
192
- }
193
- }
194
- return PredicateKind.ELEMENT === kind ? liftElementQuery(out) : out;
195
- }
196
- /**
197
- * Fold flat query fields into `query`. An explicit `query` wins outright — a caller that supplied
198
- * both told us which one it meant, and merging the two would invent a locator neither side wrote.
199
- */
200
- function liftElementQuery(obj) {
201
- const loose = ELEMENT_QUERY_FIELDS.filter((field) => obj[field] !== undefined);
202
- if (0 === loose.length)
203
- return obj;
204
- const out = { ...obj };
205
- const query = {};
206
- for (const field of loose) {
207
- query[field] = out[field];
208
- delete out[field];
209
- }
210
- if (out['query'] === undefined)
211
- out['query'] = query;
212
- return out;
213
- }
214
- /**
215
- * Strict on every branch. A key that is nobody's spelling is now a schema error naming it, instead of
216
- * a stripped field and a green — see predicate-strict.test.ts for the MCP session that found this.
217
- *
218
- * Built on demand rather than at module scope: the `allOf`/`anyOf`/`not` branches reference
219
- * `PredicateSchema` itself, which does not exist yet while this module is initialising. Calling it
220
- * after init is what makes the union introspectable — see `predicateFieldsFor`.
221
- */
222
- function predicateUnion() {
223
- return z.discriminatedUnion('kind', [
224
- z
225
- .object({
226
- kind: z.literal(PredicateKind.ELEMENT),
227
- query: ElementQuerySchema,
228
- state: z.nativeEnum(ElementState).optional(),
229
- absent: z.boolean().optional(),
230
- })
231
- .strict(),
232
- z
233
- .object({
234
- kind: z.literal(PredicateKind.TEXT),
235
- contains: z.string(),
236
- visible: z.boolean().optional(),
237
- absent: z.boolean().optional(),
238
- scope: z.string().optional(),
239
- self: z.boolean().optional(),
240
- })
241
- .strict(),
242
- z
243
- .object({
244
- kind: z.literal(PredicateKind.NET),
245
- method: z.string().optional(),
246
- urlContains: z.string().optional(),
247
- status: z.number().optional(),
248
- ok: z.boolean().optional(),
249
- since: z.number().optional(),
250
- count: z.number().int().nonnegative().optional(),
251
- /**
252
- * A substring the call's RESPONSE body must contain - what the server answered.
253
- *
254
- * The only channel that can catch a UI echoing its own input instead of the server's answer.
255
- * Reported from a real payments UI: a refund posted `{"amount":"1187.01"}`, the server read it
256
- * as paise and answered 200 with `{"refunded":11.87}`, and the page displayed the number the
257
- * user had typed. Request fired, exactly once, status 200, console clean, page settled — every
258
- * assertable channel green on a hundred-fold wrong refund, so the verdict was `yes`.
259
- *
260
- * A substring rather than a JSON path, deliberately: `"refunded":11.87` is the whole assertion
261
- * for the money case, it needs no schema for the body, and it works the same on JSON, form
262
- * encoding and plain text. A path-and-equals form can be added later if a real case needs one;
263
- * this is the shape that turns "a blob I read" into a verdict.
264
- *
265
- * Requires body capture (`reticle({ captureNetworkBodies: true })`), and says so when the body
266
- * was never recorded rather than reporting an ordinary mismatch.
267
- */
268
- bodyContains: z.string().min(1).optional(),
269
- /**
270
- * Shallow JSON match over the RESPONSE body, keyed like `signal.dataMatches` and sharing its
271
- * `matchValue` operators (`*`, `$gte`, `$contains`, …) — the field-level half of
272
- * `bodyContains` (#987).
273
- *
274
- * `bodyContains` is a substring test, and the comment above says why that shape was chosen.
275
- * It leaves one assertion unsayable: "this FIELD holds this value". Reported from the field
276
- * as the only false green in that export — `bodyContains: "completed"` returned
277
- * `verified: "yes"` for a job whose status was `queued`, because the body carried
278
- * `"completedAt": null` and the needle matched the KEY. An enum state in a JSON response is
279
- * the natural reach for a substring and the one thing a substring cannot decide:
280
- * `completed`/`completedAt`, `success`/`successRate`, `sent`/`unsent`.
281
- *
282
- * `{ bodyMatches: { status: "completed" } }` cannot be satisfied by a key name, by a longer
283
- * sibling value, or by key order, whitespace and serialisation — all of which a substring
284
- * answers to. Use `bodyContains` for a non-JSON body, or when the substring IS the claim.
285
- *
286
- * A field whose captured value was REDACTED cannot be matched, and the verdict says so
287
- * instead of reporting a mismatch: a redacted field is unknown, not different.
288
- */
289
- bodyMatches: z.record(z.string(), z.unknown()).optional(),
290
- /**
291
- * A substring the REQUEST body must contain — the other half of `bodyContains`.
292
- *
293
- * `bodyContains` deliberately searches only the response, and the comment above says why:
294
- * searching the request too would let it pass on the very defect it exists to catch. That
295
- * reasoning is sound and it leaves a real gap. For a filter, a search or a form, the thing
296
- * under test IS the outgoing payload: "applying this filter actually sends it" had no
297
- * verdict at all, only `reticle_network { bodies: true }` and a human reading `requestBody`
298
- * by eye (#798).
299
- *
300
- * A separate field rather than a mode on `bodyContains`, so neither assertion can ever be
301
- * satisfied by the wrong half of the exchange.
302
- *
303
- * Requires body capture, and says so when the request body was never recorded rather than
304
- * reporting an ordinary mismatch.
305
- */
306
- requestBodyContains: z.string().min(1).optional(),
307
- /**
308
- * Shallow JSON match over the REQUEST body, keyed like `signal.dataMatches` and sharing its
309
- * `matchValue` operators (`*`, `$gte`, `$contains`, …).
310
- *
311
- * `{ requestBodyMatches: { filter: "manual_review" } }` is the one-call verdict for "the UI
312
- * put the selected value into the payload", and it does not care about key order,
313
- * whitespace or how the client serialised the object — all of which a substring does.
314
- *
315
- * A field whose captured value was REDACTED cannot be matched, and the verdict says so
316
- * instead of reporting a mismatch: a redacted field is unknown, not different.
317
- */
318
- requestBodyMatches: z.record(z.string(), z.unknown()).optional(),
319
- })
320
- .strict(),
321
- z
322
- .object({
323
- kind: z.literal(PredicateKind.ROUTE),
324
- pathname: z.string().optional(),
325
- contains: z.string().optional(),
326
- since: z.number().optional(),
327
- })
328
- .strict(),
329
- z
330
- .object({
331
- kind: z.literal(PredicateKind.CONSOLE),
332
- level: z.string().optional(),
333
- contains: z.string().min(1).optional(),
334
- absent: z.boolean().optional(),
335
- since: z.number().optional(),
336
- })
337
- .strict(),
338
- z
339
- .object({
340
- kind: z.literal(PredicateKind.ANIMATION),
341
- name: z.string().optional(),
342
- target: z.string().optional(),
343
- completed: z.boolean().optional(),
344
- since: z.number().optional(),
345
- })
346
- .strict(),
347
- z
348
- .object({
349
- kind: z.literal(PredicateKind.SIGNAL),
350
- name: z.string().optional(),
351
- dataMatches: z.record(z.unknown()).optional(),
352
- /**
353
- * Exact number of matching signals since the action — presence becomes cardinality.
354
- *
355
- * The double-fire is the defect no state-only oracle can see: a handler wired twice fires
356
- * the signal twice, the store ends up in the right shape either way, and a presence check
357
- * is green on both. The wrong-name variant is the same blind spot from the other side — the
358
- * intended signal fires once while a mistyped sibling fires alongside it, and only a count
359
- * scoped to the matched name tells the two apart. Omit = presence (≥1); `0` asserts the
360
- * signal never fired, which is a claim in its own right and NOT the same as omitting it.
361
- */
362
- count: z.number().int().nonnegative().optional(),
363
- since: z.number().optional(),
364
- })
365
- .strict(),
366
- z
367
- .object({
368
- kind: z.literal(PredicateKind.STATE),
369
- store: z.string().optional(),
370
- path: z.string(),
371
- equals: z.unknown().optional(),
372
- /*
373
- * Assert a PROPERTY instead of exact bytes, for output that is right differently every run.
374
- * `equals` cannot express a generated summary, a classification or a computed total; this
375
- * can, and stays decidable here with no model and no network. Supplying both is allowed and
376
- * both must hold.
377
- */
378
- satisfies: propertyAssertionSchema.optional(),
379
- })
380
- .strict(),
381
- z
382
- .object({
383
- kind: z.literal(PredicateKind.SETTLED),
384
- quietMs: z.number().positive().optional(),
385
- })
386
- .strict(),
387
- z
388
- .object({ kind: z.literal(PredicateKind.ALL_OF), predicates: z.array(PredicateSchema) })
389
- .strict(),
390
- z
391
- .object({ kind: z.literal(PredicateKind.ANY_OF), predicates: z.array(PredicateSchema) })
392
- .strict(),
393
- z.object({ kind: z.literal(PredicateKind.NOT), predicate: PredicateSchema }).strict(),
394
- ]);
395
- }
396
- export const PredicateSchema = z.lazy(() => z.preprocess(applyPredicateAliases, predicateUnion()));
397
130
  /**
398
131
  * The fields a given predicate kind accepts, read off the schema itself.
399
132
  *
@@ -411,17 +144,11 @@ export function predicateFieldsFor(kind) {
411
144
  * The union option for `kind`, or null when the kind is not one.
412
145
  *
413
146
  * One place that walks the union, so the field list and the nested lookup cannot disagree about
414
- * which option a kind resolves to — and so adding a third reader is a call rather than a fourth
415
- * copy of the same loop.
147
+ * which option a kind resolves to. The walk itself is now core's, because the union is: a second
148
+ * copy here would be a second answer to "what fields does this kind take", and the rejection
149
+ * messages built from it would eventually name a field set the schema no longer has.
416
150
  */
417
- function shapeForKind(kind) {
418
- for (const option of predicateUnion().options) {
419
- const literal = option.shape['kind'];
420
- if (literal instanceof z.ZodLiteral && literal.value === kind)
421
- return option.shape;
422
- }
423
- return null;
424
- }
151
+ const shapeForKind = predicateShapeFor;
425
152
  /**
426
153
  * Is this tool parameter ACTUALLY the predicate union?
427
154
  *
@@ -10,7 +10,8 @@ import type { AmbientCounts } from '../../window/ambient.js';
10
10
  */
11
11
  /** The subset of Session the predicate engine needs — keeps it testable with a fake. */
12
12
  export interface PredicateSession {
13
- command(name: string, args?: Record<string, unknown>): Promise<CommandResult>;
13
+ /** `timeoutMs` bounds the page's answer; omitted, the session's own default applies. */
14
+ command(name: string, args?: Record<string, unknown>, timeoutMs?: number): Promise<CommandResult>;
14
15
  eventsSince(cursor: number): ReticleEvent[];
15
16
  onEvent(listener: (event: ReticleEvent) => void): () => void;
16
17
  /** Milliseconds since connect — the same clock that stamps event `t` (injected, testable). */
@@ -70,3 +71,16 @@ export interface PredicateSession {
70
71
  */
71
72
  keepCallerContext?: KeepCallerContextFn;
72
73
  }
74
+ /**
75
+ * The least time a page read is given, even at the very end of a budget: the final read at the
76
+ * deadline must still be able to hear a live page answer.
77
+ */
78
+ export declare const MIN_READ_MS = 1500;
79
+ /**
80
+ * `session`, with every page command bounded by what the caller's budget has left.
81
+ *
82
+ * Without it each read carried the session's fixed command timeout, so a `timeout_ms: 3000` assert on
83
+ * a page that never answered came back after eight seconds. A Proxy rather than a copy because the
84
+ * real Session keeps `#private` fields: every other member is forwarded bound to the original.
85
+ */
86
+ export declare function withinBudget(session: PredicateSession, remainingMs: () => number): PredicateSession;
@@ -1 +1,25 @@
1
- export {};
1
+ /**
2
+ * The least time a page read is given, even at the very end of a budget: the final read at the
3
+ * deadline must still be able to hear a live page answer.
4
+ */
5
+ export const MIN_READ_MS = 1_500;
6
+ /**
7
+ * `session`, with every page command bounded by what the caller's budget has left.
8
+ *
9
+ * Without it each read carried the session's fixed command timeout, so a `timeout_ms: 3000` assert on
10
+ * a page that never answered came back after eight seconds. A Proxy rather than a copy because the
11
+ * real Session keeps `#private` fields: every other member is forwarded bound to the original.
12
+ */
13
+ export function withinBudget(session, remainingMs) {
14
+ return new Proxy(session, {
15
+ get(target, key) {
16
+ if ('command' === key) {
17
+ return (name, args) => target.command(name, args, Math.max(MIN_READ_MS, remainingMs()));
18
+ }
19
+ const value = Reflect.get(target, key, target);
20
+ return 'function' === typeof value
21
+ ? value.bind(target)
22
+ : value;
23
+ },
24
+ });
25
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The `state` predicate: everything that reads a registered store.
3
+ *
4
+ * Split out of `predicate.ts` when it crossed the file cap, and it is a cohesive unit on its own
5
+ * terms — one command (`STATE_READ`), one kind, and the whole scoped-vs-whole-store negotiation
6
+ * that exists because an older SDK ignores `path` and answers with the entire store. Nothing else
7
+ * in the predicate layer talks to that command.
8
+ */
9
+ import { PredicateKind } from '@reticlehq/core';
10
+ import { type EvalResult, type Predicate } from './predicate-eval.js';
11
+ import { type Baseline } from './property.js';
12
+ import type { PredicateSession } from './predicate-session.js';
13
+ export declare function evalState(session: PredicateSession, p: Extract<Predicate, {
14
+ kind: typeof PredicateKind.STATE;
15
+ }>, baseline?: Baseline): Promise<EvalResult>;