@reticlehq/core 3.7.0 → 3.8.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 (108) hide show
  1. package/dist/activation-entry.d.ts +9 -0
  2. package/dist/activation-entry.js +9 -0
  3. package/dist/artifacts/drive-script.d.ts +64 -64
  4. package/dist/artifacts/flow-constants.d.ts +15 -0
  5. package/dist/artifacts/flow-constants.js +15 -0
  6. package/dist/artifacts/flow-expect-flat.d.ts +8 -8
  7. package/dist/artifacts/flow-results.d.ts +11 -0
  8. package/dist/artifacts/flow-types.d.ts +164 -118
  9. package/dist/artifacts/flow-types.js +12 -0
  10. package/dist/artifacts/harness-credits.d.ts +6 -3
  11. package/dist/artifacts/harness-credits.js +9 -6
  12. package/dist/artifacts/harness-map.d.ts +6 -6
  13. package/dist/artifacts/impact.d.ts +77 -80
  14. package/dist/artifacts/impact.js +34 -17
  15. package/dist/artifacts/journal.d.ts +25 -6
  16. package/dist/artifacts/journal.js +13 -0
  17. package/dist/artifacts/prompt-context.d.ts +12 -0
  18. package/dist/artifacts/prompt-context.js +14 -3
  19. package/dist/graph/app-graph.d.ts +137 -0
  20. package/dist/graph/app-graph.js +498 -0
  21. package/dist/hooks/hook-events.d.ts +22 -22
  22. package/dist/hud-entry.js +1 -1
  23. package/dist/identity/checkout.d.ts +41 -0
  24. package/dist/identity/checkout.js +118 -0
  25. package/dist/identity/state-dir.d.ts +23 -0
  26. package/dist/identity/state-dir.js +43 -0
  27. package/dist/index.d.ts +10 -0
  28. package/dist/index.js +10 -0
  29. package/dist/onboarding.d.ts +22 -1
  30. package/dist/onboarding.js +19 -0
  31. package/dist/registry/dev-server-registry.d.ts +2 -2
  32. package/dist/schema/event-message.json +3 -1
  33. package/dist/schema/event-payloads.json +116 -1
  34. package/dist/schema/event-type.json +3 -1
  35. package/dist/schema/hello-message.json +21 -0
  36. package/dist/schema/reticle-event.json +3 -1
  37. package/dist/schema/reticle-message.json +24 -1
  38. package/dist/telemetry-bug.d.ts +6 -6
  39. package/dist/telemetry-entry.d.ts +1 -1
  40. package/dist/telemetry-entry.js +1 -1
  41. package/dist/telemetry-feedback.d.ts +14 -0
  42. package/dist/telemetry-feedback.js +19 -0
  43. package/dist/telemetry-refusal.d.ts +2 -2
  44. package/dist/telemetry-session.d.ts +23 -8
  45. package/dist/telemetry-session.js +15 -4
  46. package/dist/telemetry-signals.d.ts +227 -9
  47. package/dist/telemetry-signals.js +88 -1
  48. package/dist/telemetry.d.ts +379 -72
  49. package/dist/telemetry.js +71 -5
  50. package/dist/verdict/check-sentence.d.ts +34 -0
  51. package/dist/verdict/check-sentence.js +228 -0
  52. package/dist/verdict/consequence.d.ts +15 -0
  53. package/dist/verdict/consequence.js +11 -0
  54. package/dist/verdict/findings.d.ts +10 -0
  55. package/dist/verdict/findings.js +13 -0
  56. package/dist/verdict/instrumentation-coverage.d.ts +3 -34
  57. package/dist/verdict/instrumentation-coverage.js +14 -58
  58. package/dist/verdict/instrumentation-gap.d.ts +79 -0
  59. package/dist/verdict/instrumentation-gap.js +64 -0
  60. package/dist/verdict/predicate-tree.d.ts +2 -0
  61. package/dist/verdict/predicate-tree.js +16 -0
  62. package/dist/verdict/predicate.d.ts +2 -1
  63. package/dist/verdict/predicate.js +103 -12
  64. package/dist/verdict/property-assertion.d.ts +2 -2
  65. package/dist/verdict/run-report.d.ts +166 -0
  66. package/dist/verdict/run-report.js +53 -0
  67. package/dist/verdict/security.d.ts +36 -2
  68. package/dist/verdict/security.js +94 -14
  69. package/dist/verdict/verification-run.d.ts +95 -38
  70. package/dist/verdict/verification-run.js +33 -2
  71. package/dist/verdict/verify-progress.d.ts +6 -6
  72. package/dist/wire/constants/constants.d.ts +56 -141
  73. package/dist/wire/constants/constants.js +64 -144
  74. package/dist/wire/constants/discovery.d.ts +4 -4
  75. package/dist/wire/constants/discovery.js +4 -4
  76. package/dist/wire/constants/event-types.d.ts +35 -1
  77. package/dist/wire/constants/event-types.js +33 -1
  78. package/dist/wire/constants/hud-controls.js +0 -2
  79. package/dist/wire/constants/hud-use.d.ts +4 -0
  80. package/dist/wire/constants/hud-use.js +4 -0
  81. package/dist/wire/constants/mcp-wire.d.ts +16 -0
  82. package/dist/wire/constants/mcp-wire.js +16 -0
  83. package/dist/wire/constants/response-body-reason.d.ts +19 -0
  84. package/dist/wire/constants/response-body-reason.js +18 -0
  85. package/dist/wire/constants/reticle-env.d.ts +138 -0
  86. package/dist/wire/constants/reticle-env.js +138 -0
  87. package/dist/wire/constants/session-constants.d.ts +11 -0
  88. package/dist/wire/constants/session-constants.js +11 -0
  89. package/dist/wire/event-payloads.d.ts +150 -36
  90. package/dist/wire/event-payloads.js +83 -16
  91. package/dist/wire/messages.d.ts +102 -36
  92. package/dist/wire/messages.js +16 -0
  93. package/dist/wire/narrow.d.ts +6 -0
  94. package/dist/wire/narrow.js +26 -0
  95. package/dist/wire/next-step.d.ts +90 -0
  96. package/dist/wire/next-step.js +37 -0
  97. package/dist/wire/platform-link.d.ts +7 -0
  98. package/dist/wire/platform-link.js +12 -6
  99. package/dist/wire/production/activation-ticket.d.ts +64 -0
  100. package/dist/wire/production/activation-ticket.js +148 -0
  101. package/dist/wire/production/hello-mode.d.ts +35 -0
  102. package/dist/wire/production/hello-mode.js +32 -0
  103. package/dist/wire/production/production-policy.d.ts +138 -0
  104. package/dist/wire/production/production-policy.js +133 -0
  105. package/dist/wire/tool-names.d.ts +2 -0
  106. package/dist/wire/tool-names.js +2 -0
  107. package/dist/wire/types.d.ts +73 -48
  108. package/package.json +5 -1
@@ -117,24 +117,15 @@ export function coverageOf(input) {
117
117
  }
118
118
  return { seen, missing, notSeenYet, total: RULES.length, covered: seen.length };
119
119
  }
120
- /**
121
- * The gaps that would close these capabilities: the ones verdicts recorded (they name the control
122
- * and file), else the capability's own fix, so a capability never checked is still named. Pure.
123
- */
124
- export function gapsToClose(gaps, capabilities) {
125
- return RULES.filter((rule) => capabilities.includes(rule.capability)).flatMap((rule) => {
126
- const recorded = gaps.filter((gap) => rule.gaps.some((kind) => kind === gap.kind));
127
- return 0 < recorded.length
128
- ? recorded
129
- : [{ kind: rule.capability, missing: rule.capability, fix: rule.fix }];
130
- });
131
- }
132
120
  /** The first line of every coverage prompt. */
133
- export const AGENT_PROMPT_LEAD = "Read https://reticle.sh/SKILL.md, then improve Reticle's coverage in this repo:";
121
+ export const AGENT_PROMPT_LEAD = "Read https://docs.reticle.sh/skill.md, then improve Reticle's coverage in this repo:";
134
122
  /** The last line: what the agent hands back. */
135
123
  export const AGENT_PROMPT_TAIL = 'Report the coverage line it prints.';
136
- /** The placeholder the person replaces with the journey their change touched. */
137
- const JOURNEY_PLACEHOLDER = '<one journey you changed>';
124
+ /**
125
+ * The placeholder the agent replaces with the end state of the journey its change touched. It names
126
+ * a JSON predicate, because `--expect` parses JSON and refuses prose.
127
+ */
128
+ const JOURNEY_PLACEHOLDER = '<JSON predicate for the end state of one journey you changed>';
138
129
  /**
139
130
  * The copy-paste prompt for a coding agent: only the gaps verdicts recorded, each with its fix and
140
131
  * what it is missing (and the control or file, when the gap names one), then the verify that proves
@@ -153,7 +144,7 @@ export function agentPromptFor(input) {
153
144
  AGENT_PROMPT_LEAD,
154
145
  `App: ${input.appName} at ${input.url}`,
155
146
  ...new Set(items),
156
- `Then run: reticle verify ${input.url} --expect "${JOURNEY_PLACEHOLDER}"`,
147
+ `Then run: npx @reticlehq/server verify ${input.url} --expect '${JOURNEY_PLACEHOLDER}'`,
157
148
  AGENT_PROMPT_TAIL,
158
149
  ].join('\n');
159
150
  }
@@ -162,30 +153,20 @@ function fixForKind(kind) {
162
153
  const known = Object.values(InstrumentationGapKind).find((k) => k === kind);
163
154
  return known === undefined ? kind : fixForGap(known);
164
155
  }
165
- // ── The Harness coverage gate ─────────────────────────────────────────────────────────────────
156
+ // ── The setup score ───────────────────────────────────────────────────────────────────────────
166
157
  /*
167
- * When the Reticle Harness may drive an app: only once Reticle can see enough of it.
168
- *
169
- * A Harness drive decides on the platform and spends credits; on an app Reticle half sees, it pays
170
- * for verdicts that can only infer from the DOM. So the Harness unlocks at a coverage score, and the
171
- * coding agent (which can use every other tool at any coverage) is how an app gets there.
172
- *
173
- * THE RULE, one definition; the platform mirrors it exactly:
158
+ * How much of an app Reticle sees, as one number. It is information, never a gate: the Harness and
159
+ * every tool run at any score. Doctor and the HUD show it so a person knows what more wiring adds.
174
160
  *
175
161
  * capabilities the eight `CoverageCapability` entries, as `coverageOf` reads them
176
162
  * applicable capabilities minus those that do not apply to this app (excluded from both sides;
177
163
  * the daemon reports them as `notApplicable` on each local-apps app)
178
164
  * seen applicable capabilities `coverageOf` lists as seen; "not seen yet" is NOT seen
179
165
  * score seen ÷ applicable, 0 when nothing applies
180
- * percent floor(score × 100), so a shown percent is below 80 exactly when the gate is shut
181
- * unlocked score ≥ HARNESS_UNLOCK_COVERAGE (0.8)
182
- *
183
- * The gate is the Harness's alone. Pure: coverage in, a decision and its sentence out.
166
+ * percent floor(score × 100)
184
167
  */
185
168
  /** The capabilities an app reports as not applying to it, on the wire. Closed: core's eight only. */
186
169
  export const NotApplicableSchema = z.array(z.nativeEnum(CoverageCapability)).max(8);
187
- /** The score at which the Harness unlocks. */
188
- export const HARNESS_UNLOCK_COVERAGE = 0.8;
189
170
  /** Floating-point slack, so 0.29 × 100 floors to 29 and not 28. */
190
171
  const PERCENT_EPSILON = 1e-9;
191
172
  /** Seen ÷ applicable over the eight capabilities. See the header for the exact rule. */
@@ -195,32 +176,7 @@ export function coverageScore(coverage, notApplicable = []) {
195
176
  return 0;
196
177
  return applicable.filter((c) => coverage.seen.includes(c)).length / applicable.length;
197
178
  }
198
- /** The one sentence a locked Harness answers with. */
199
- export const harnessLockedReason = (percent, unseen) => `Harness unlocks at ${String(Math.round(HARNESS_UNLOCK_COVERAGE * 100))}% instrumentation. ` +
200
- `This app is at ${String(percent)}%: missing ${unseen.join(', ')}.`;
201
- /** Whether the Harness may drive an app with this coverage, and the sentence when it may not. */
202
- export function harnessGateOf(coverage, notApplicable = []) {
203
- const score = coverageScore(coverage, notApplicable);
204
- const percent = Math.floor(score * 100 + PERCENT_EPSILON);
205
- const unseen = Object.values(CoverageCapability).filter((c) => !notApplicable.includes(c) && !coverage.seen.includes(c));
206
- const unlocked = HARNESS_UNLOCK_COVERAGE <= score;
207
- return {
208
- score,
209
- percent,
210
- unlocked,
211
- unseen,
212
- ...(unlocked ? {} : { reason: harnessLockedReason(percent, unseen) }),
213
- };
214
- }
215
- /**
216
- * The prompt for the coding agent that closes the gate: each unseen capability with how to close it
217
- * (the control and file when a verdict named one), then the one flow that proves it. Pure.
218
- */
219
- export function harnessUnlockPrompt(input) {
220
- const { unseen } = harnessGateOf(input.coverage, input.notApplicable);
221
- return agentPromptFor({
222
- gaps: gapsToClose(input.gaps, unseen),
223
- appName: input.appName,
224
- url: input.url,
225
- });
179
+ /** floor(coverageScore × 100): the setup score a person reads. */
180
+ export function coveragePercent(coverage, notApplicable = []) {
181
+ return Math.floor(coverageScore(coverage, notApplicable) * 100 + PERCENT_EPSILON);
226
182
  }
@@ -14,6 +14,7 @@
14
14
  * everything uninstrumented on the page. The test is *did this absence change the answer the agent
15
15
  * just got?* — if not, it does not fire.
16
16
  */
17
+ import { z } from 'zod';
17
18
  /**
18
19
  * The kinds of absence that can weaken a verdict. Most name a capability the app did not provide;
19
20
  * `UNDECLARED_CHANGE` names one the agent did not, and is here because it costs a verdict the same.
@@ -147,3 +148,81 @@ export declare function instrumentationGap(kind: InstrumentationGapKind, missing
147
148
  * while one store hit twice stays one.
148
149
  */
149
150
  export declare function dedupeGaps(gaps: readonly InstrumentationGap[]): InstrumentationGap[];
151
+ /**
152
+ * What the ENGINE could not observe in a run, so a host can refuse to call that run clean.
153
+ *
154
+ * Not an instrumentation gap: nothing the app adds closes these, because this engine has no reader
155
+ * for them. Each verdict result (`reticle_act_and_wait`, `reticle_assert`) carries the list under
156
+ * `ENGINE_BLIND_SPOTS_FIELD`, CUMULATIVE for its session: everything seen since the session began,
157
+ * and `[]` when there is nothing. So the LAST verdict result of a run is the run's list. A host that
158
+ * predates the field ignores it; nothing else in the result changes.
159
+ */
160
+ export declare const EngineBlindSpotKind: {
161
+ /**
162
+ * An action ran while a `<canvas>` was visible, and this engine records no canvas digest.
163
+ *
164
+ * The pixels are the output there. A colour picker that no longer reaches the renderer leaves the
165
+ * DOM, the network and the store exactly as they were on the build that works, so "nothing
166
+ * disagreed" is not evidence that the canvas is right.
167
+ */
168
+ readonly PIXELS_UNOBSERVED: "pixels-unobserved";
169
+ /**
170
+ * A claim under test names a number or a total, and no verdict ran a computed comparison
171
+ * (`compare`).
172
+ *
173
+ * "Each hit adds one point" is broken by a handler that adds two. The store, the screen and the
174
+ * wire all agree with each other on that build, so only the arithmetic the claim states can catch
175
+ * it, and nothing checked it.
176
+ */
177
+ readonly CLAIM_ARITHMETIC_UNCHECKED: "claim-arithmetic-unchecked";
178
+ };
179
+ export type EngineBlindSpotKind = (typeof EngineBlindSpotKind)[keyof typeof EngineBlindSpotKind];
180
+ export declare const EngineBlindSpotSchema: z.ZodObject<{
181
+ kind: z.ZodNativeEnum<{
182
+ /**
183
+ * An action ran while a `<canvas>` was visible, and this engine records no canvas digest.
184
+ *
185
+ * The pixels are the output there. A colour picker that no longer reaches the renderer leaves the
186
+ * DOM, the network and the store exactly as they were on the build that works, so "nothing
187
+ * disagreed" is not evidence that the canvas is right.
188
+ */
189
+ readonly PIXELS_UNOBSERVED: "pixels-unobserved";
190
+ /**
191
+ * A claim under test names a number or a total, and no verdict ran a computed comparison
192
+ * (`compare`).
193
+ *
194
+ * "Each hit adds one point" is broken by a handler that adds two. The store, the screen and the
195
+ * wire all agree with each other on that build, so only the arithmetic the claim states can catch
196
+ * it, and nothing checked it.
197
+ */
198
+ readonly CLAIM_ARITHMETIC_UNCHECKED: "claim-arithmetic-unchecked";
199
+ }>;
200
+ /** What could not be seen, in words. */
201
+ detail: z.ZodString;
202
+ }, "strip", z.ZodTypeAny, {
203
+ kind: "pixels-unobserved" | "claim-arithmetic-unchecked";
204
+ detail: string;
205
+ }, {
206
+ kind: "pixels-unobserved" | "claim-arithmetic-unchecked";
207
+ detail: string;
208
+ }>;
209
+ export type EngineBlindSpot = z.infer<typeof EngineBlindSpotSchema>;
210
+ /** The verdict-result field that carries a session's `EngineBlindSpot[]`. */
211
+ export declare const ENGINE_BLIND_SPOTS_FIELD = "engineBlindSpots";
212
+ /** True when a claim states an amount: a digit, a percent sign, or a number word. */
213
+ export declare function namesArithmetic(claim: string): boolean;
214
+ /** What a session's run has shown so far, for `engineBlindSpots`. */
215
+ export interface EngineBlindSpotFacts {
216
+ /** An action in this session ran while a `<canvas>` was visible. */
217
+ canvasSeen: boolean;
218
+ /** A verdict in this session ran a computed comparison. */
219
+ compared: boolean;
220
+ /** The claims under test: inline intents and this run's declared intents. */
221
+ claims: readonly (string | undefined)[];
222
+ }
223
+ /**
224
+ * What this engine could not observe in a session, cumulative. See `EngineBlindSpotKind`.
225
+ *
226
+ * Pixels: this engine records no canvas digest, so a visible canvas is always unobserved.
227
+ */
228
+ export declare function engineBlindSpots(facts: EngineBlindSpotFacts): EngineBlindSpot[];
@@ -14,6 +14,7 @@
14
14
  * everything uninstrumented on the page. The test is *did this absence change the answer the agent
15
15
  * just got?* — if not, it does not fire.
16
16
  */
17
+ import { z } from 'zod';
17
18
  /**
18
19
  * The kinds of absence that can weaken a verdict. Most name a capability the app did not provide;
19
20
  * `UNDECLARED_CHANGE` names one the agent did not, and is here because it costs a verdict the same.
@@ -170,3 +171,66 @@ export function dedupeGaps(gaps) {
170
171
  }
171
172
  return out;
172
173
  }
174
+ /**
175
+ * What the ENGINE could not observe in a run, so a host can refuse to call that run clean.
176
+ *
177
+ * Not an instrumentation gap: nothing the app adds closes these, because this engine has no reader
178
+ * for them. Each verdict result (`reticle_act_and_wait`, `reticle_assert`) carries the list under
179
+ * `ENGINE_BLIND_SPOTS_FIELD`, CUMULATIVE for its session: everything seen since the session began,
180
+ * and `[]` when there is nothing. So the LAST verdict result of a run is the run's list. A host that
181
+ * predates the field ignores it; nothing else in the result changes.
182
+ */
183
+ export const EngineBlindSpotKind = {
184
+ /**
185
+ * An action ran while a `<canvas>` was visible, and this engine records no canvas digest.
186
+ *
187
+ * The pixels are the output there. A colour picker that no longer reaches the renderer leaves the
188
+ * DOM, the network and the store exactly as they were on the build that works, so "nothing
189
+ * disagreed" is not evidence that the canvas is right.
190
+ */
191
+ PIXELS_UNOBSERVED: 'pixels-unobserved',
192
+ /**
193
+ * A claim under test names a number or a total, and no verdict ran a computed comparison
194
+ * (`compare`).
195
+ *
196
+ * "Each hit adds one point" is broken by a handler that adds two. The store, the screen and the
197
+ * wire all agree with each other on that build, so only the arithmetic the claim states can catch
198
+ * it, and nothing checked it.
199
+ */
200
+ CLAIM_ARITHMETIC_UNCHECKED: 'claim-arithmetic-unchecked',
201
+ };
202
+ export const EngineBlindSpotSchema = z.object({
203
+ kind: z.nativeEnum(EngineBlindSpotKind),
204
+ /** What could not be seen, in words. */
205
+ detail: z.string().min(1),
206
+ });
207
+ /** The verdict-result field that carries a session's `EngineBlindSpot[]`. */
208
+ export const ENGINE_BLIND_SPOTS_FIELD = 'engineBlindSpots';
209
+ /** Number words and arithmetic nouns a claim uses to state an amount. Whole words only. */
210
+ const ARITHMETIC_WORDS = /\b(?:one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|hundred|thousand|once|twice|double|triple|half|total|sum|subtotal|count|score|points?|balance|average|percent)\b/i;
211
+ /** True when a claim states an amount: a digit, a percent sign, or a number word. */
212
+ export function namesArithmetic(claim) {
213
+ return /\d|%/.test(claim) || ARITHMETIC_WORDS.test(claim);
214
+ }
215
+ /**
216
+ * What this engine could not observe in a session, cumulative. See `EngineBlindSpotKind`.
217
+ *
218
+ * Pixels: this engine records no canvas digest, so a visible canvas is always unobserved.
219
+ */
220
+ export function engineBlindSpots(facts) {
221
+ const spots = [];
222
+ if (facts.canvasSeen) {
223
+ spots.push({
224
+ kind: EngineBlindSpotKind.PIXELS_UNOBSERVED,
225
+ detail: 'an action ran while a canvas was visible, and no canvas digest was recorded, so what it draws was not compared',
226
+ });
227
+ }
228
+ const numeric = facts.claims.find((claim) => claim !== undefined && namesArithmetic(claim));
229
+ if (numeric !== undefined && !facts.compared) {
230
+ spots.push({
231
+ kind: EngineBlindSpotKind.CLAIM_ARITHMETIC_UNCHECKED,
232
+ detail: `the claim "${numeric}" states an amount, and no verdict ran a computed comparison against it`,
233
+ });
234
+ }
235
+ return spots;
236
+ }
@@ -95,3 +95,5 @@ export declare function sessionRefRefusal(field: string): string;
95
95
  * another session. A ref under a `not` is exactly as meaningless as one at the top.
96
96
  */
97
97
  export declare function sessionBoundField(predicate: Predicate): string | undefined;
98
+ /** True when any clause of this predicate, at any depth, is a computed `compare`. */
99
+ export declare function computesComparison(predicate: Predicate | undefined): boolean;
@@ -205,3 +205,19 @@ export function sessionBoundField(predicate) {
205
205
  return undefined;
206
206
  }
207
207
  }
208
+ /** True when any clause of this predicate, at any depth, is a computed `compare`. */
209
+ export function computesComparison(predicate) {
210
+ if (predicate === undefined)
211
+ return false;
212
+ switch (predicate.kind) {
213
+ case PredicateKind.COMPARE:
214
+ return true;
215
+ case PredicateKind.ALL_OF:
216
+ case PredicateKind.ANY_OF:
217
+ return predicate.predicates.some(computesComparison);
218
+ case PredicateKind.NOT:
219
+ return computesComparison(predicate.predicate);
220
+ default:
221
+ return false;
222
+ }
223
+ }
@@ -19,7 +19,7 @@ import { z } from 'zod';
19
19
  import { type ElementQuery } from '../wire/types.js';
20
20
  import { ElementState } from '../wire/constants/constants.js';
21
21
  import { CompareAs, type CompareSource } from './compare-source.js';
22
- import { PredicateKind } from './consequence.js';
22
+ import { PredicateKind, SettledChannel } from './consequence.js';
23
23
  import { type PropertyAssertion } from './property-assertion.js';
24
24
  export type Predicate = {
25
25
  kind: typeof PredicateKind.ELEMENT;
@@ -113,6 +113,7 @@ export type Predicate = {
113
113
  } | {
114
114
  kind: typeof PredicateKind.SETTLED;
115
115
  quietMs?: number;
116
+ channel?: SettledChannel;
116
117
  } | {
117
118
  kind: typeof PredicateKind.COMPARE;
118
119
  left: CompareSource;
@@ -19,7 +19,7 @@ import { z } from 'zod';
19
19
  import { ElementQuerySchema } from '../wire/types.js';
20
20
  import { ElementState } from '../wire/constants/constants.js';
21
21
  import { CompareAs, CompareSourceSchema, sameCompareSource, } from './compare-source.js';
22
- import { PredicateKind } from './consequence.js';
22
+ import { PredicateKind, SettledChannel } from './consequence.js';
23
23
  import { propertyAssertionSchema } from './property-assertion.js';
24
24
  /**
25
25
  * Spellings an agent plausibly reaches for, mapped to the real field.
@@ -65,13 +65,14 @@ const PREDICATE_ALIASES = {
65
65
  // no other meaning here. Observed twice in one drive on a real app, and each rejection cost a round
66
66
  // trip AND produced no verdict — a composite is what an agent reaches for precisely when it has two
67
67
  // things to prove at once, so failing it is expensive at the worst moment.
68
- [PredicateKind.ALL_OF]: { of: 'predicates' },
69
- [PredicateKind.ANY_OF]: { of: 'predicates' },
68
+ // The kind's own name as the key (`{ allOf: [...] }`) is the shorthand `inferKind` reads.
69
+ [PredicateKind.ALL_OF]: { of: 'predicates', allOf: 'predicates' },
70
+ [PredicateKind.ANY_OF]: { of: 'predicates', anyOf: 'predicates' },
70
71
  // `of` on `not` for the same reason it is accepted on the composites above — an agent that learned
71
72
  // the spelling one line earlier applies it to the third composite, and `not` was the one that
72
73
  // rejected it. The refusal did name `predicate`, but naming a field still costs the round trip
73
74
  // that produced no verdict, and the guess is unambiguous: `not` has exactly one child.
74
- [PredicateKind.NOT]: { of: 'predicate' },
75
+ [PredicateKind.NOT]: { of: 'predicate', not: 'predicate' },
75
76
  };
76
77
  /**
77
78
  * The word half the assertion world spells `kind`.
@@ -105,6 +106,86 @@ function renameKindSpelling(obj) {
105
106
  delete out[KIND_SPELLING];
106
107
  return out;
107
108
  }
109
+ /**
110
+ * Keys that are also the name of a kind. `{ text: "Saved" }` and `{ allOf: [...] }` are what agents
111
+ * write when they leave out `kind`. The key names the kind, and the alias table maps it to a field.
112
+ */
113
+ const KIND_NAMED_KEYS = {
114
+ text: PredicateKind.TEXT,
115
+ allOf: PredicateKind.ALL_OF,
116
+ anyOf: PredicateKind.ANY_OF,
117
+ not: PredicateKind.NOT,
118
+ };
119
+ /** Each kind and every key it takes: its fields, its aliases and, for `element`, flat query fields. */
120
+ let keysByKind;
121
+ function keysOfEachKind() {
122
+ if (keysByKind !== undefined) {
123
+ return keysByKind;
124
+ }
125
+ const out = new Map();
126
+ for (const option of predicateUnion().options) {
127
+ const shape = option.shape;
128
+ const kind = shape['kind']._def.value;
129
+ const flat = PredicateKind.ELEMENT === kind ? ELEMENT_QUERY_FIELDS : [];
130
+ out.set(kind, new Set([
131
+ ...Object.keys(shape).filter((key) => 'kind' !== key),
132
+ ...Object.keys(PREDICATE_ALIASES[kind] ?? {}),
133
+ ...flat,
134
+ ]));
135
+ }
136
+ keysByKind = out;
137
+ return out;
138
+ }
139
+ const writtenKeys = (obj) => Object.keys(obj).filter((key) => obj[key] !== undefined);
140
+ /**
141
+ * The kind of a predicate written with no `kind`, when its keys fit exactly one kind.
142
+ *
143
+ * A key that names a kind (`text`, `allOf`, `anyOf`, `not`) selects that kind, if the kind takes
144
+ * every other key too. Otherwise the kind is the only one that takes every key. Keys that fit two
145
+ * kinds (`name` is on `signal` and `animation`) or none give no kind, and the schema refuses them.
146
+ * This only supplies `kind`: the predicate that results is the one the explicit form gives.
147
+ */
148
+ function inferKind(obj) {
149
+ const keys = writtenKeys(obj);
150
+ if (0 === keys.length) {
151
+ return undefined;
152
+ }
153
+ const kinds = keysOfEachKind();
154
+ const takesAll = (kind) => {
155
+ const accepted = kinds.get(kind);
156
+ return accepted !== undefined && keys.every((key) => accepted.has(key));
157
+ };
158
+ const named = keys.flatMap((key) => {
159
+ const kind = KIND_NAMED_KEYS[key];
160
+ return kind === undefined ? [] : [kind];
161
+ });
162
+ if (1 < named.length) {
163
+ return undefined;
164
+ }
165
+ const [byName] = named;
166
+ if (byName !== undefined) {
167
+ return takesAll(byName) ? byName : undefined;
168
+ }
169
+ const fits = [...kinds.keys()].filter(takesAll);
170
+ return 1 === fits.length ? fits[0] : undefined;
171
+ }
172
+ /** The kind inferred for a predicate written with neither `kind` nor `type`, if any. */
173
+ function kindToInfer(given) {
174
+ const renamed = renameKindSpelling(given);
175
+ return renamed['kind'] === undefined ? inferKind(renamed) : undefined;
176
+ }
177
+ /** `type` renamed to `kind`, then the kind inferred from the keys when neither was written. */
178
+ function withKind(given) {
179
+ const renamed = renameKindSpelling(given);
180
+ const kind = kindToInfer(given);
181
+ return kind === undefined ? renamed : { ...renamed, kind };
182
+ }
183
+ /** Why a predicate with no `kind` was refused: the keys it had, and the kinds there are. */
184
+ function noKindRefusal(obj) {
185
+ const keys = writtenKeys(obj).map((key) => `\`${key}\``);
186
+ return (`this predicate has no \`kind\`, and its keys (${keys.length > 0 ? keys.join(', ') : 'none'}) ` +
187
+ `do not fit exactly one kind. Add \`kind\`: one of ${[...keysOfEachKind().keys()].join(', ')}`);
188
+ }
108
189
  /**
109
190
  * Which aliases a predicate as WRITTEN would have renamed, as `kind.from → to` (and `type → kind`).
110
191
  *
@@ -122,7 +203,11 @@ export function predicateAliasesUsed(input, depth = 0) {
122
203
  if (given['kind'] === undefined && 'string' === typeof given[KIND_SPELLING]) {
123
204
  used.push(`${KIND_SPELLING} → kind`);
124
205
  }
125
- const obj = renameKindSpelling(given);
206
+ const inferred = kindToInfer(given);
207
+ if (inferred !== undefined) {
208
+ used.push(`(no kind) → kind: "${inferred}"`);
209
+ }
210
+ const obj = withKind(given);
126
211
  const kind = 'string' === typeof obj['kind'] ? obj['kind'] : '';
127
212
  for (const [from, to] of Object.entries(PREDICATE_ALIASES[kind] ?? {})) {
128
213
  if (obj[from] !== undefined && obj[to] === undefined)
@@ -134,7 +219,7 @@ export function predicateAliasesUsed(input, depth = 0) {
134
219
  used.push(`element.${field} → query.${field}`);
135
220
  }
136
221
  }
137
- for (const field of ['predicates', 'of', 'predicate']) {
222
+ for (const field of ['predicates', 'of', 'predicate', 'allOf', 'anyOf', 'not']) {
138
223
  const child = obj[field];
139
224
  for (const nested of Array.isArray(child) ? child : [child]) {
140
225
  used.push(...predicateAliasesUsed(nested, depth + 1));
@@ -143,11 +228,14 @@ export function predicateAliasesUsed(input, depth = 0) {
143
228
  return used;
144
229
  }
145
230
  /** Rename known aliases before parse; an explicit canonical key always wins. */
146
- function applyPredicateAliases(input) {
231
+ function applyPredicateAliases(input, ctx) {
147
232
  if (typeof input !== 'object' || null === input || Array.isArray(input))
148
233
  return input;
149
234
  const given = input;
150
- const obj = renameKindSpelling(given);
235
+ const obj = withKind(given);
236
+ if (obj['kind'] === undefined) {
237
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: noKindRefusal(obj) });
238
+ }
151
239
  const kind = 'string' === typeof obj['kind'] ? obj['kind'] : '';
152
240
  const aliases = PREDICATE_ALIASES[kind];
153
241
  let out = obj;
@@ -164,10 +252,13 @@ function applyPredicateAliases(input) {
164
252
  return PredicateKind.ELEMENT === kind ? liftElementQuery(out) : out;
165
253
  }
166
254
  /**
167
- * Fold flat query fields into `query`. An explicit `query` wins outright — a caller that supplied
168
- * both told us which one it meant, and merging the two would invent a locator neither side wrote.
255
+ * Fold flat query fields into `query`. With an explicit `query` nothing is folded and nothing is
256
+ * dropped: merging would invent a locator neither side wrote, and dropping a flat `value` checked
257
+ * only that the element exists. The strict schema refuses the flat field instead, by name.
169
258
  */
170
259
  function liftElementQuery(obj) {
260
+ if (obj['query'] !== undefined)
261
+ return obj;
171
262
  const loose = ELEMENT_QUERY_FIELDS.filter((field) => obj[field] !== undefined);
172
263
  if (0 === loose.length)
173
264
  return obj;
@@ -177,8 +268,7 @@ function liftElementQuery(obj) {
177
268
  query[field] = out[field];
178
269
  delete out[field];
179
270
  }
180
- if (out['query'] === undefined)
181
- out['query'] = query;
271
+ out['query'] = query;
182
272
  return out;
183
273
  }
184
274
  /**
@@ -371,6 +461,7 @@ function predicateUnion() {
371
461
  .object({
372
462
  kind: z.literal(PredicateKind.SETTLED),
373
463
  quietMs: z.number().positive().optional(),
464
+ channel: z.enum([SettledChannel.NETWORK, SettledChannel.APP]).optional(),
374
465
  })
375
466
  .strict(),
376
467
  z
@@ -94,11 +94,11 @@ export declare const propertyAssertionSchema: z.ZodDiscriminatedUnion<"property"
94
94
  property: z.ZodLiteral<"matchesPattern">;
95
95
  pattern: z.ZodString;
96
96
  }, "strict", z.ZodTypeAny, {
97
- property: "matchesPattern";
98
97
  pattern: string;
99
- }, {
100
98
  property: "matchesPattern";
99
+ }, {
101
100
  pattern: string;
101
+ property: "matchesPattern";
102
102
  }>, z.ZodObject<{
103
103
  property: z.ZodLiteral<"type">;
104
104
  is: z.ZodEnum<["string", "number", "boolean", "array", "object"]>;