@reticlehq/core 3.2.0 → 3.4.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 (91) hide show
  1. package/README.md +1 -1
  2. package/dist/artifacts/flow-composition.d.ts +3 -2
  3. package/dist/artifacts/flow-constants.d.ts +68 -2
  4. package/dist/artifacts/flow-constants.js +84 -2
  5. package/dist/artifacts/flow-expect-flat.d.ts +260 -0
  6. package/dist/artifacts/flow-expect-flat.js +284 -0
  7. package/dist/artifacts/flow-mutation-target.d.ts +0 -1
  8. package/dist/artifacts/flow-mutation-target.js +30 -2
  9. package/dist/artifacts/flow-step-tool.d.ts +2 -0
  10. package/dist/artifacts/flow-types.d.ts +1285 -1343
  11. package/dist/artifacts/flow-types.js +111 -140
  12. package/dist/artifacts/impact.d.ts +48 -20
  13. package/dist/artifacts/impact.js +11 -0
  14. package/dist/artifacts/journal.d.ts +34 -6
  15. package/dist/artifacts/journal.js +13 -0
  16. package/dist/hooks/hook-events.d.ts +18 -18
  17. package/dist/hud-entry.d.ts +9 -0
  18. package/dist/hud-entry.js +9 -0
  19. package/dist/identity/source-constants.d.ts +11 -0
  20. package/dist/identity/source-constants.js +11 -0
  21. package/dist/index.d.ts +9 -0
  22. package/dist/index.js +25 -1
  23. package/dist/onboarding.d.ts +2 -2
  24. package/dist/realm/registry.d.ts +0 -8
  25. package/dist/realm/registry.js +1 -11
  26. package/dist/registry/daemon-registry.d.ts +14 -4
  27. package/dist/registry/daemon-registry.js +20 -4
  28. package/dist/schema/event-message.json +3 -1
  29. package/dist/schema/event-payloads.json +72 -0
  30. package/dist/schema/event-type.json +3 -1
  31. package/dist/schema/reticle-event.json +3 -1
  32. package/dist/schema/reticle-message.json +3 -1
  33. package/dist/source-constants.cjs +1 -0
  34. package/dist/source-constants.d.cts +1 -0
  35. package/dist/telemetry-feedback.d.ts +6 -6
  36. package/dist/telemetry-refusal.d.ts +5 -4
  37. package/dist/telemetry-session.d.ts +25 -2
  38. package/dist/telemetry-session.js +13 -0
  39. package/dist/telemetry.d.ts +130 -102
  40. package/dist/verdict/compare-source.d.ts +80 -0
  41. package/dist/verdict/compare-source.js +93 -0
  42. package/dist/verdict/consequence.d.ts +12 -0
  43. package/dist/verdict/consequence.js +15 -0
  44. package/dist/verdict/instrumentation-gap.js +1 -1
  45. package/dist/verdict/intent.d.ts +24 -0
  46. package/dist/verdict/intent.js +66 -10
  47. package/dist/verdict/predicate-tree.d.ts +82 -0
  48. package/dist/verdict/predicate-tree.js +186 -0
  49. package/dist/verdict/predicate.d.ts +138 -0
  50. package/dist/verdict/predicate.js +430 -0
  51. package/dist/verdict/property-assertion.d.ts +191 -0
  52. package/dist/verdict/property-assertion.js +42 -0
  53. package/dist/verdict/security.js +16 -4
  54. package/dist/verdict/verdict-attribution.d.ts +52 -0
  55. package/dist/verdict/verdict-attribution.js +87 -0
  56. package/dist/verdict/verification-run.d.ts +330 -83
  57. package/dist/verdict/verification-run.js +44 -1
  58. package/dist/verdict/verified-constants.d.ts +9 -0
  59. package/dist/verdict/verified-constants.js +9 -0
  60. package/dist/wire/channel.d.ts +10 -0
  61. package/dist/wire/channel.js +25 -0
  62. package/dist/wire/constants/constants.d.ts +65 -102
  63. package/dist/wire/constants/constants.js +79 -101
  64. package/dist/wire/constants/discovery.d.ts +25 -0
  65. package/dist/wire/constants/discovery.js +25 -0
  66. package/dist/wire/constants/event-types.d.ts +122 -0
  67. package/dist/wire/constants/event-types.js +121 -0
  68. package/dist/wire/constants/hud-controls.d.ts +19 -0
  69. package/dist/wire/constants/hud-controls.js +95 -0
  70. package/dist/wire/constants/hud-use.d.ts +27 -0
  71. package/dist/wire/constants/hud-use.js +24 -0
  72. package/dist/wire/constants/session-constants.d.ts +10 -0
  73. package/dist/wire/constants/session-constants.js +10 -0
  74. package/dist/wire/event-payloads.d.ts +72 -13
  75. package/dist/wire/event-payloads.js +26 -4
  76. package/dist/wire/messages.d.ts +97 -56
  77. package/dist/wire/messages.js +17 -0
  78. package/dist/wire/net.d.ts +35 -0
  79. package/dist/wire/net.js +41 -0
  80. package/dist/wire/redaction.js +17 -0
  81. package/dist/wire/state-select.d.ts +2 -1
  82. package/dist/wire/state-select.js +56 -3
  83. package/dist/wire/toon.d.ts +1 -1
  84. package/dist/wire/toon.js +30 -8
  85. package/dist/wire/types.d.ts +119 -94
  86. package/dist/wire/types.js +23 -1
  87. package/dist/words/no-session-reason.d.ts +7 -0
  88. package/dist/words/no-session-reason.js +7 -0
  89. package/dist/words/notices.d.ts +7 -0
  90. package/dist/words/notices.js +9 -2
  91. package/package.json +7 -2
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The predicate: what a caller can declare, as a shape that crosses the wire.
3
+ *
4
+ * This is the CONTRACT half of the predicate language, and it is here for the reason everything
5
+ * else in this package is: a message that crosses browser ↔ bridge ↔ agent is defined in core, and
6
+ * a predicate is now one. `FlowStep.expect` is a `Predicate`, which means a saved flow file carries
7
+ * one, which means core has to be able to parse what it reads off disk.
8
+ *
9
+ * It was in `@reticlehq/engine` and it was already half here: `PredicateKind` has always lived in
10
+ * `verdict/consequence.ts`, so the engine's schema imported its own vocabulary back from its parent.
11
+ * This finishes that migration rather than starting one.
12
+ *
13
+ * WHAT DID NOT COME WITH IT, and the line is deliberate. Evaluation stays in the engine:
14
+ * `satisfiesProperty`, the residual-query checks, the grammar and nested-key introspection. Core is
15
+ * the contract, not the reasoning. A reader looking for "what may I write" is in the right file; a
16
+ * reader looking for "what does it decide" is one package out.
17
+ */
18
+ import { z } from 'zod';
19
+ import { type ElementQuery } from '../wire/types.js';
20
+ import { ElementState } from '../wire/constants/constants.js';
21
+ import { CompareAs, type CompareSource } from './compare-source.js';
22
+ import { PredicateKind } from './consequence.js';
23
+ import { type PropertyAssertion } from './property-assertion.js';
24
+ export type Predicate = {
25
+ kind: typeof PredicateKind.ELEMENT;
26
+ query: ElementQuery;
27
+ state?: ElementState;
28
+ absent?: boolean;
29
+ } | {
30
+ kind: typeof PredicateKind.TEXT;
31
+ contains?: string;
32
+ visible?: boolean;
33
+ absent?: boolean;
34
+ /**
35
+ * Restrict the match to a subtree, as a CSS selector or a ref — the same field, and the same
36
+ * meaning, as `scope` on an element query.
37
+ *
38
+ * Without it the match is page-wide, and a word that appears both in a background tab label
39
+ * and in the dialog that just opened satisfies the predicate BEFORE the action runs, so
40
+ * `act_and_wait` reports `already_true` for an action that did exactly the right thing.
41
+ */
42
+ scope?: string;
43
+ /** Match the scope root itself and check its combined subtree text. Requires `scope`. */
44
+ self?: boolean;
45
+ /**
46
+ * Assert a PROPERTY of the rendered text rather than its exact bytes.
47
+ *
48
+ * The same reasoning `state` carries, applied where the user actually reads the value: an
49
+ * app whose output IS a model's output is different on every run and correct on every one of
50
+ * them, so `contains` is the one assertion it cannot satisfy twice. Both may be supplied and
51
+ * then both must hold — `satisfies` narrows, it never excuses.
52
+ */
53
+ satisfies?: PropertyAssertion;
54
+ } | {
55
+ kind: typeof PredicateKind.NET;
56
+ method?: string;
57
+ urlContains?: string;
58
+ status?: number;
59
+ /** Did the call succeed? The honest field for IPC, which has no status code. */
60
+ ok?: boolean;
61
+ since?: number;
62
+ count?: number;
63
+ /** A substring the RESPONSE body must contain — what the server answered, not what was sent. */
64
+ bodyContains?: string;
65
+ /** JSON field match over the RESPONSE body: this FIELD holds this value (#987). A key may be a dotted path. */
66
+ bodyMatches?: Record<string, unknown>;
67
+ /** A substring the REQUEST body must contain — what the UI sent, not what came back. */
68
+ requestBodyContains?: string;
69
+ /** JSON field match over the REQUEST body, in the style of `signal.dataMatches`. */
70
+ requestBodyMatches?: Record<string, unknown>;
71
+ } | {
72
+ kind: typeof PredicateKind.ROUTE;
73
+ pathname?: string;
74
+ contains?: string;
75
+ since?: number;
76
+ } | {
77
+ kind: typeof PredicateKind.CONSOLE;
78
+ level?: string;
79
+ /**
80
+ * A substring the captured message must contain. With `absent: true` this flips the meaning
81
+ * from "no console entries at all" to "THIS message did not appear" — the assertion people
82
+ * actually write regression checks for (deprecation warnings, no-op handler notices).
83
+ */
84
+ contains?: string;
85
+ absent?: boolean;
86
+ since?: number;
87
+ } | {
88
+ kind: typeof PredicateKind.ANIMATION;
89
+ name?: string;
90
+ target?: string;
91
+ completed?: boolean;
92
+ since?: number;
93
+ } | {
94
+ kind: typeof PredicateKind.SIGNAL;
95
+ name?: string;
96
+ dataMatches?: Record<string, unknown>;
97
+ /**
98
+ * Exact number of matching signals in the window — the same cardinality assertion `net`
99
+ * carries, on the channel the app itself speaks. Omit for presence (≥1).
100
+ */
101
+ count?: number;
102
+ since?: number;
103
+ } | {
104
+ kind: typeof PredicateKind.STATE;
105
+ store?: string;
106
+ path: string;
107
+ equals?: unknown;
108
+ satisfies?: PropertyAssertion;
109
+ } | {
110
+ kind: typeof PredicateKind.SETTLED;
111
+ quietMs?: number;
112
+ } | {
113
+ kind: typeof PredicateKind.COMPARE;
114
+ left: CompareSource;
115
+ right: CompareSource;
116
+ /** `value` (default): strict equality. `number`: one number read from each side. */
117
+ as?: CompareAs;
118
+ /** How far apart two numbers may be and still agree. Only with `as: "number"`. */
119
+ tolerance?: number;
120
+ } | {
121
+ kind: typeof PredicateKind.ALL_OF;
122
+ predicates: Predicate[];
123
+ } | {
124
+ kind: typeof PredicateKind.ANY_OF;
125
+ predicates: Predicate[];
126
+ } | {
127
+ kind: typeof PredicateKind.NOT;
128
+ predicate: Predicate;
129
+ };
130
+ export declare const PredicateSchema: z.ZodType<Predicate>;
131
+ /**
132
+ * The fields one predicate kind accepts, as the schema itself declares them.
133
+ *
134
+ * Exported because the ENGINE's introspection needs it and the union it reads is built here. A
135
+ * second copy of the union next door is how a rejection message comes to name a stale field set,
136
+ * which is worse than naming none: the agent trusts it and retries into the same wall.
137
+ */
138
+ export declare function predicateShapeFor(kind: string): z.ZodRawShape | null;
@@ -0,0 +1,430 @@
1
+ /**
2
+ * The predicate: what a caller can declare, as a shape that crosses the wire.
3
+ *
4
+ * This is the CONTRACT half of the predicate language, and it is here for the reason everything
5
+ * else in this package is: a message that crosses browser ↔ bridge ↔ agent is defined in core, and
6
+ * a predicate is now one. `FlowStep.expect` is a `Predicate`, which means a saved flow file carries
7
+ * one, which means core has to be able to parse what it reads off disk.
8
+ *
9
+ * It was in `@reticlehq/engine` and it was already half here: `PredicateKind` has always lived in
10
+ * `verdict/consequence.ts`, so the engine's schema imported its own vocabulary back from its parent.
11
+ * This finishes that migration rather than starting one.
12
+ *
13
+ * WHAT DID NOT COME WITH IT, and the line is deliberate. Evaluation stays in the engine:
14
+ * `satisfiesProperty`, the residual-query checks, the grammar and nested-key introspection. Core is
15
+ * the contract, not the reasoning. A reader looking for "what may I write" is in the right file; a
16
+ * reader looking for "what does it decide" is one package out.
17
+ */
18
+ import { z } from 'zod';
19
+ import { ElementQuerySchema } from '../wire/types.js';
20
+ import { ElementState } from '../wire/constants/constants.js';
21
+ import { CompareAs, CompareSourceSchema, sameCompareSource, } from './compare-source.js';
22
+ import { PredicateKind } from './consequence.js';
23
+ import { propertyAssertionSchema } from './property-assertion.js';
24
+ /**
25
+ * Spellings an agent plausibly reaches for, mapped to the real field.
26
+ *
27
+ * `route` spells its field `pathname` while `state`, in the same union, spells its `path`. Every one
28
+ * of these was silently DROPPED before, and because these kinds have all-optional fields, dropping
29
+ * the only key supplied left a predicate that asserts nothing and passes on anything.
30
+ */
31
+ const PREDICATE_ALIASES = {
32
+ // `text`/`value`/`query` on a `text` predicate: the kind is called "text", so `text:` is the first
33
+ // thing anyone writes for it, `value` follows from the element query's own `value` field, and
34
+ // `query` from `element`'s nested locator, the spelling agents reach for after `reticle_query`.
35
+ // All were hard rejections, and a rejected predicate produces NO verdict at all — the drive ends
36
+ // with nothing rather than with a failure, which is the worst outcome of the three.
37
+ [PredicateKind.TEXT]: { text: 'contains', value: 'contains', query: 'contains' },
38
+ // `urlContains`/`url` reported from the field: an agent that had just written
39
+ // `net { urlContains }` applied the same word to `route`, which spells it `contains`, and got
40
+ // `unrecognized_keys` with no list of what would have worked. The parallel it assumed is a fair
41
+ // one — route's `contains` matches the WHOLE route (path + query + fragment), so "the URL
42
+ // contains this" is precisely what it does — and asserting a redirect after login is the single
43
+ // most common thing an agent reaches for here.
44
+ [PredicateKind.ROUTE]: { path: 'pathname', urlContains: 'contains', url: 'contains' },
45
+ [PredicateKind.NET]: { url: 'urlContains', responseBodyMatches: 'bodyMatches' },
46
+ // `textContains` on a `console` predicate: the reporter who hit the missing matcher reached for
47
+ // it first, by analogy with `net { urlContains }` — and that parallel is exactly right, since
48
+ // both mean "this entry must contain this substring". Accepted as an alias for `contains`.
49
+ [PredicateKind.CONSOLE]: { textContains: 'contains' },
50
+ [PredicateKind.SIGNAL]: { data: 'dataMatches' },
51
+ // `of` on a composite: it reads naturally, several assertion libraries spell it that way, and it has
52
+ // no other meaning here. Observed twice in one drive on a real app, and each rejection cost a round
53
+ // trip AND produced no verdict — a composite is what an agent reaches for precisely when it has two
54
+ // things to prove at once, so failing it is expensive at the worst moment.
55
+ [PredicateKind.ALL_OF]: { of: 'predicates' },
56
+ [PredicateKind.ANY_OF]: { of: 'predicates' },
57
+ // `of` on `not` for the same reason it is accepted on the composites above — an agent that learned
58
+ // the spelling one line earlier applies it to the third composite, and `not` was the one that
59
+ // rejected it. The refusal did name `predicate`, but naming a field still costs the round trip
60
+ // that produced no verdict, and the guess is unambiguous: `not` has exactly one child.
61
+ [PredicateKind.NOT]: { of: 'predicate' },
62
+ };
63
+ /**
64
+ * The word half the assertion world spells `kind`.
65
+ *
66
+ * A discriminated union rejects `{ type: "text", ... }` with "Invalid discriminator value" on a field
67
+ * the caller never wrote, so the reply reads as being about `kind` — which is absent — and never
68
+ * says the word `type`. Observed on a live drive as the first rung of a ladder: one field name
69
+ * learned per rejected call, each costing a verdict. No predicate kind declares a `type` field, so
70
+ * lifting it is unambiguous, and an explicit `kind` still wins.
71
+ */
72
+ const KIND_SPELLING = 'type';
73
+ /**
74
+ * Element-query fields an agent writes FLAT on an `element` predicate instead of nested under
75
+ * `query`. `reticle_query` takes exactly these at the top level, so an agent that has just located
76
+ * something writes the same words again when it asserts on it — and got `query: Required` plus an
77
+ * `unknown field` list for its trouble. Lifting them is unambiguous: they have no other meaning on
78
+ * this kind.
79
+ */
80
+ const ELEMENT_QUERY_FIELDS = [
81
+ 'by',
82
+ 'value',
83
+ 'role',
84
+ 'name',
85
+ 'text',
86
+ 'label',
87
+ 'placeholder',
88
+ 'testid',
89
+ 'alt',
90
+ 'component',
91
+ ];
92
+ /** `type` read as the discriminator when — and only when — `kind` is absent. */
93
+ function renameKindSpelling(obj) {
94
+ if (obj['kind'] !== undefined || 'string' !== typeof obj[KIND_SPELLING])
95
+ return obj;
96
+ const out = { ...obj, kind: obj[KIND_SPELLING] };
97
+ delete out[KIND_SPELLING];
98
+ return out;
99
+ }
100
+ /** Rename known aliases before parse; an explicit canonical key always wins. */
101
+ function applyPredicateAliases(input) {
102
+ if (typeof input !== 'object' || null === input || Array.isArray(input))
103
+ return input;
104
+ const given = input;
105
+ const obj = renameKindSpelling(given);
106
+ const kind = 'string' === typeof obj['kind'] ? obj['kind'] : '';
107
+ const aliases = PREDICATE_ALIASES[kind];
108
+ let out = obj;
109
+ if (aliases !== undefined) {
110
+ out = { ...obj };
111
+ for (const [from, to] of Object.entries(aliases)) {
112
+ if (out[from] === undefined)
113
+ continue;
114
+ if (out[to] === undefined)
115
+ out[to] = out[from];
116
+ delete out[from];
117
+ }
118
+ }
119
+ return PredicateKind.ELEMENT === kind ? liftElementQuery(out) : out;
120
+ }
121
+ /**
122
+ * Fold flat query fields into `query`. An explicit `query` wins outright — a caller that supplied
123
+ * both told us which one it meant, and merging the two would invent a locator neither side wrote.
124
+ */
125
+ function liftElementQuery(obj) {
126
+ const loose = ELEMENT_QUERY_FIELDS.filter((field) => obj[field] !== undefined);
127
+ if (0 === loose.length)
128
+ return obj;
129
+ const out = { ...obj };
130
+ const query = {};
131
+ for (const field of loose) {
132
+ query[field] = out[field];
133
+ delete out[field];
134
+ }
135
+ if (out['query'] === undefined)
136
+ out['query'] = query;
137
+ return out;
138
+ }
139
+ /**
140
+ * Strict on every branch. A key that is nobody's spelling is now a schema error naming it, instead of
141
+ * a stripped field and a green — see predicate-strict.test.ts for the MCP session that found this.
142
+ *
143
+ * Built on demand rather than at module scope: the `allOf`/`anyOf`/`not` branches reference
144
+ * `PredicateSchema` itself, which does not exist yet while this module is initialising. Calling it
145
+ * after init is what makes the union introspectable — see `predicateFieldsFor`.
146
+ */
147
+ function predicateUnion() {
148
+ return z.discriminatedUnion('kind', [
149
+ z
150
+ .object({
151
+ kind: z.literal(PredicateKind.ELEMENT),
152
+ query: ElementQuerySchema,
153
+ state: z.nativeEnum(ElementState).optional(),
154
+ absent: z.boolean().optional(),
155
+ })
156
+ .strict(),
157
+ z
158
+ .object({
159
+ kind: z.literal(PredicateKind.TEXT),
160
+ /**
161
+ * Optional ONLY because `satisfies` can carry the claim instead — see the refinement below,
162
+ * which refuses a text predicate that names neither. A `text` predicate with nothing to
163
+ * assert resolves to "some element, some text" and passes on every page that has one.
164
+ */
165
+ contains: z.string().optional(),
166
+ visible: z.boolean().optional(),
167
+ absent: z.boolean().optional(),
168
+ scope: z.string().optional(),
169
+ self: z.boolean().optional(),
170
+ satisfies: propertyAssertionSchema.optional(),
171
+ })
172
+ .strict(),
173
+ z
174
+ .object({
175
+ kind: z.literal(PredicateKind.NET),
176
+ method: z.string().optional(),
177
+ urlContains: z.string().optional(),
178
+ status: z.number().optional(),
179
+ ok: z.boolean().optional(),
180
+ since: z.number().optional(),
181
+ count: z.number().int().nonnegative().optional(),
182
+ /**
183
+ * A substring the call's RESPONSE body must contain - what the server answered.
184
+ *
185
+ * The only channel that can catch a UI echoing its own input instead of the server's answer.
186
+ * Reported from a real payments UI: a refund posted `{"amount":"1187.01"}`, the server read it
187
+ * as paise and answered 200 with `{"refunded":11.87}`, and the page displayed the number the
188
+ * user had typed. Request fired, exactly once, status 200, console clean, page settled — every
189
+ * assertable channel green on a hundred-fold wrong refund, so the verdict was `yes`.
190
+ *
191
+ * A substring rather than a JSON path, deliberately: `"refunded":11.87` is the whole assertion
192
+ * for the money case, it needs no schema for the body, and it works the same on JSON, form
193
+ * encoding and plain text. A path-and-equals form can be added later if a real case needs one;
194
+ * this is the shape that turns "a blob I read" into a verdict.
195
+ *
196
+ * Requires body capture (`reticle({ captureNetworkBodies: true })`), and says so when the body
197
+ * was never recorded rather than reporting an ordinary mismatch.
198
+ */
199
+ bodyContains: z.string().min(1).optional(),
200
+ /**
201
+ * JSON field match over the RESPONSE body, keyed like `signal.dataMatches` and sharing its
202
+ * `matchValue` operators (`*`, `$gte`, `$contains`, …) — the field-level half of
203
+ * `bodyContains` (#987).
204
+ *
205
+ * `bodyContains` is a substring test, and the comment above says why that shape was chosen.
206
+ * It leaves one assertion unsayable: "this FIELD holds this value". Reported from the field
207
+ * as the only false green in that export — `bodyContains: "completed"` returned
208
+ * `verified: "yes"` for a job whose status was `queued`, because the body carried
209
+ * `"completedAt": null` and the needle matched the KEY. An enum state in a JSON response is
210
+ * the natural reach for a substring and the one thing a substring cannot decide:
211
+ * `completed`/`completedAt`, `success`/`successRate`, `sent`/`unsent`.
212
+ *
213
+ * `{ bodyMatches: { status: "completed" } }` cannot be satisfied by a key name, by a longer
214
+ * sibling value, or by key order, whitespace and serialisation — all of which a substring
215
+ * answers to. Use `bodyContains` for a non-JSON body, or when the substring IS the claim.
216
+ *
217
+ * A field whose captured value was REDACTED cannot be matched, and the verdict says so
218
+ * instead of reporting a mismatch: a redacted field is unknown, not different.
219
+ */
220
+ bodyMatches: z.record(z.string(), z.unknown()).optional(),
221
+ /**
222
+ * A substring the REQUEST body must contain — the other half of `bodyContains`.
223
+ *
224
+ * `bodyContains` deliberately searches only the response, and the comment above says why:
225
+ * searching the request too would let it pass on the very defect it exists to catch. That
226
+ * reasoning is sound and it leaves a real gap. For a filter, a search or a form, the thing
227
+ * under test IS the outgoing payload: "applying this filter actually sends it" had no
228
+ * verdict at all, only `reticle_network { bodies: true }` and a human reading `requestBody`
229
+ * by eye (#798).
230
+ *
231
+ * A separate field rather than a mode on `bodyContains`, so neither assertion can ever be
232
+ * satisfied by the wrong half of the exchange.
233
+ *
234
+ * Requires body capture, and says so when the request body was never recorded rather than
235
+ * reporting an ordinary mismatch.
236
+ */
237
+ requestBodyContains: z.string().min(1).optional(),
238
+ /**
239
+ * JSON field match over the REQUEST body, keyed like `signal.dataMatches` and sharing its
240
+ * `matchValue` operators (`*`, `$gte`, `$contains`, …).
241
+ *
242
+ * `{ requestBodyMatches: { filter: "manual_review" } }` is the one-call verdict for "the UI
243
+ * put the selected value into the payload", and it does not care about key order,
244
+ * whitespace or how the client serialised the object — all of which a substring does.
245
+ *
246
+ * A field whose captured value was REDACTED cannot be matched, and the verdict says so
247
+ * instead of reporting a mismatch: a redacted field is unknown, not different.
248
+ */
249
+ requestBodyMatches: z.record(z.string(), z.unknown()).optional(),
250
+ })
251
+ .strict(),
252
+ z
253
+ .object({
254
+ kind: z.literal(PredicateKind.ROUTE),
255
+ pathname: z.string().optional(),
256
+ contains: z.string().optional(),
257
+ since: z.number().optional(),
258
+ })
259
+ .strict(),
260
+ z
261
+ .object({
262
+ kind: z.literal(PredicateKind.CONSOLE),
263
+ level: z.string().optional(),
264
+ contains: z.string().min(1).optional(),
265
+ absent: z.boolean().optional(),
266
+ since: z.number().optional(),
267
+ })
268
+ .strict(),
269
+ z
270
+ .object({
271
+ kind: z.literal(PredicateKind.ANIMATION),
272
+ name: z.string().optional(),
273
+ target: z.string().optional(),
274
+ completed: z.boolean().optional(),
275
+ since: z.number().optional(),
276
+ })
277
+ .strict(),
278
+ z
279
+ .object({
280
+ kind: z.literal(PredicateKind.SIGNAL),
281
+ name: z.string().optional(),
282
+ dataMatches: z.record(z.unknown()).optional(),
283
+ /**
284
+ * Exact number of matching signals since the action — presence becomes cardinality.
285
+ *
286
+ * The double-fire is the defect no state-only oracle can see: a handler wired twice fires
287
+ * the signal twice, the store ends up in the right shape either way, and a presence check
288
+ * is green on both. The wrong-name variant is the same blind spot from the other side — the
289
+ * intended signal fires once while a mistyped sibling fires alongside it, and only a count
290
+ * scoped to the matched name tells the two apart. Omit = presence (≥1); `0` asserts the
291
+ * signal never fired, which is a claim in its own right and NOT the same as omitting it.
292
+ */
293
+ count: z.number().int().nonnegative().optional(),
294
+ since: z.number().optional(),
295
+ })
296
+ .strict(),
297
+ z
298
+ .object({
299
+ kind: z.literal(PredicateKind.STATE),
300
+ store: z.string().optional(),
301
+ path: z.string(),
302
+ equals: z.unknown().optional(),
303
+ /*
304
+ * Assert a PROPERTY instead of exact bytes, for output that is right differently every run.
305
+ * `equals` cannot express a generated summary, a classification or a computed total; this
306
+ * can, and stays decidable here with no model and no network. Supplying both is allowed and
307
+ * both must hold.
308
+ */
309
+ satisfies: propertyAssertionSchema.optional(),
310
+ })
311
+ .strict(),
312
+ z
313
+ .object({
314
+ kind: z.literal(PredicateKind.SETTLED),
315
+ quietMs: z.number().positive().optional(),
316
+ })
317
+ .strict(),
318
+ z
319
+ .object({
320
+ kind: z.literal(PredicateKind.COMPARE),
321
+ left: CompareSourceSchema,
322
+ right: CompareSourceSchema,
323
+ as: z.enum([CompareAs.VALUE, CompareAs.NUMBER]).optional(),
324
+ tolerance: z.number().finite().nonnegative().optional(),
325
+ })
326
+ .strict(),
327
+ /*
328
+ * `.min(1)` on both combinators, because an EMPTY one is a false green and not an edge case.
329
+ *
330
+ * `allOf` over no members is vacuous truth — every member holds because there are none — so it
331
+ * evaluated `pass: true` and reported `verified: "yes"` for a drive that asserted nothing.
332
+ * Nobody writes that by hand; an agent that builds `predicates` by mapping over a list of
333
+ * channels to check emits it the moment the list comes back empty.
334
+ *
335
+ * `anyOf` over no members is the mirror and is merely a false RED, which is honest-ish and far
336
+ * cheaper. It is refused here anyway: one rule is easier to hold than two, and an empty `anyOf`
337
+ * is a mistake in either direction.
338
+ */
339
+ z
340
+ .object({
341
+ kind: z.literal(PredicateKind.ALL_OF),
342
+ predicates: z.array(PredicateSchema).min(1),
343
+ })
344
+ .strict(),
345
+ z
346
+ .object({
347
+ kind: z.literal(PredicateKind.ANY_OF),
348
+ predicates: z.array(PredicateSchema).min(1),
349
+ })
350
+ .strict(),
351
+ z.object({ kind: z.literal(PredicateKind.NOT), predicate: PredicateSchema }).strict(),
352
+ ]);
353
+ }
354
+ /*
355
+ * Cross-field rules, applied to every predicate INCLUDING the ones nested in a composite.
356
+ *
357
+ * They live on the union rather than on the member because `z.discriminatedUnion` takes plain
358
+ * objects only — wrapping one member in a refinement makes the whole union refuse to build, and
359
+ * `shapeForKind` walks those same options to derive the accepted-field list in a rejection message.
360
+ */
361
+ function checkPredicateShape(predicate, ctx) {
362
+ // Structural and narrowed HERE, not in the signature: the refinement runs on the union zod
363
+ // inferred, whose optional fields are spelled `| undefined`, and naming any concrete type in the
364
+ // parameter makes the overload unresolvable. Only the four fields this reads are looked at.
365
+ if ('object' !== typeof predicate || null === predicate)
366
+ return;
367
+ const p = predicate;
368
+ if (PredicateKind.COMPARE === p.kind) {
369
+ checkCompareShape(predicate, ctx);
370
+ return;
371
+ }
372
+ if (PredicateKind.TEXT !== p.kind)
373
+ return;
374
+ if (undefined === p.contains && undefined === p.satisfies) {
375
+ ctx.addIssue({
376
+ code: z.ZodIssueCode.custom,
377
+ message: 'a text predicate must say WHAT about the text: `contains` for a substring, `satisfies` ' +
378
+ 'for a property of it. With neither it matches any element with any text and cannot fail',
379
+ });
380
+ }
381
+ if (undefined !== p.satisfies && undefined === p.contains && undefined === p.scope) {
382
+ ctx.addIssue({
383
+ code: z.ZodIssueCode.custom,
384
+ message: '`satisfies` needs a subject: add `scope` (the element whose text is tested, with ' +
385
+ '`self: true` to read the scope root itself) or a `contains` that selects one. Without ' +
386
+ 'either, the locator is every element on the page and the property would run against ' +
387
+ 'whichever one happened to match first',
388
+ });
389
+ }
390
+ }
391
+ /**
392
+ * The two ways a `compare` can be written so that it cannot fail, refused before it can report `yes`.
393
+ *
394
+ * A side compared with itself agrees with itself on every page, broken or not. And `tolerance` means
395
+ * nothing to a strict equality, so accepting it there would let a caller believe a band was applied.
396
+ */
397
+ function checkCompareShape(p, ctx) {
398
+ if (sameCompareSource(p.left, p.right)) {
399
+ ctx.addIssue({
400
+ code: z.ZodIssueCode.custom,
401
+ message: '`left` and `right` read the same value, so this comparison agrees with itself on every ' +
402
+ 'page and cannot fail. Compare two different readings: what the page shows against what ' +
403
+ 'the server answered, or what was sent against what came back',
404
+ });
405
+ }
406
+ if (p.tolerance !== undefined && CompareAs.NUMBER !== p.as) {
407
+ ctx.addIssue({
408
+ code: z.ZodIssueCode.custom,
409
+ message: '`tolerance` applies to a numeric comparison only: add `as: "number"`',
410
+ });
411
+ }
412
+ }
413
+ export const PredicateSchema = z.lazy(() => z.preprocess(applyPredicateAliases, predicateUnion()).superRefine(checkPredicateShape));
414
+ /**
415
+ * The fields one predicate kind accepts, as the schema itself declares them.
416
+ *
417
+ * Exported because the ENGINE's introspection needs it and the union it reads is built here. A
418
+ * second copy of the union next door is how a rejection message comes to name a stale field set,
419
+ * which is worse than naming none: the agent trusts it and retries into the same wall.
420
+ */
421
+ export function predicateShapeFor(kind) {
422
+ for (const option of predicateUnion().options) {
423
+ const shape = option.shape;
424
+ const literal = shape?.['kind'];
425
+ const value = literal?._def?.value;
426
+ if (value === kind)
427
+ return shape;
428
+ }
429
+ return null;
430
+ }