@rudra-js/core 0.9.0 → 0.10.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 (63) hide show
  1. package/README.md +425 -375
  2. package/dist/claim-screening.d.ts.map +1 -1
  3. package/dist/claim-screening.js +3 -9
  4. package/dist/claim-screening.js.map +1 -1
  5. package/dist/component-generator.d.ts +1 -1
  6. package/dist/component-generator.d.ts.map +1 -1
  7. package/dist/component-generator.js +28 -61
  8. package/dist/component-generator.js.map +1 -1
  9. package/dist/component-spec.d.ts +100 -11
  10. package/dist/component-spec.d.ts.map +1 -1
  11. package/dist/component-spec.js +3 -6
  12. package/dist/component-spec.js.map +1 -1
  13. package/dist/fallback-component.d.ts.map +1 -1
  14. package/dist/fallback-component.js +3 -3
  15. package/dist/fallback-component.js.map +1 -1
  16. package/dist/fit-to-shopper.d.ts +4 -1
  17. package/dist/fit-to-shopper.d.ts.map +1 -1
  18. package/dist/fit-to-shopper.js +8 -0
  19. package/dist/fit-to-shopper.js.map +1 -1
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/model-prompt.d.ts.map +1 -1
  25. package/dist/model-prompt.js +16 -3
  26. package/dist/model-prompt.js.map +1 -1
  27. package/dist/product-display.d.ts +6 -0
  28. package/dist/product-display.d.ts.map +1 -0
  29. package/dist/product-display.js +32 -0
  30. package/dist/product-display.js.map +1 -0
  31. package/dist/reconciliation.d.ts +2 -4
  32. package/dist/reconciliation.d.ts.map +1 -1
  33. package/dist/reconciliation.js +15 -21
  34. package/dist/reconciliation.js.map +1 -1
  35. package/dist/schemas.d.ts +1 -0
  36. package/dist/schemas.d.ts.map +1 -1
  37. package/dist/schemas.js +1 -0
  38. package/dist/schemas.js.map +1 -1
  39. package/dist/signal-digest.d.ts.map +1 -1
  40. package/dist/signal-digest.js +2 -10
  41. package/dist/signal-digest.js.map +1 -1
  42. package/dist/spec-cache.d.ts +86 -7
  43. package/dist/spec-cache.d.ts.map +1 -1
  44. package/dist/spec-cache.js +14 -32
  45. package/dist/spec-cache.js.map +1 -1
  46. package/dist/tracking-input.d.ts.map +1 -1
  47. package/dist/tracking-input.js +8 -2
  48. package/dist/tracking-input.js.map +1 -1
  49. package/package.json +5 -4
  50. package/schemas/package.json +4 -0
  51. package/src/claim-screening.ts +3 -9
  52. package/src/component-generator.ts +33 -82
  53. package/src/component-spec.ts +5 -18
  54. package/src/fallback-component.ts +4 -3
  55. package/src/fit-to-shopper.ts +16 -1
  56. package/src/index.ts +1 -2
  57. package/src/model-prompt.ts +24 -3
  58. package/src/product-display.ts +43 -0
  59. package/src/reconciliation.ts +16 -23
  60. package/src/schemas.ts +6 -0
  61. package/src/signal-digest.ts +2 -8
  62. package/src/spec-cache.ts +17 -41
  63. package/src/tracking-input.ts +11 -2
package/README.md CHANGED
@@ -1,26 +1,27 @@
1
1
  # @rudra-js/core
2
2
 
3
- This package is part of [rudra-js](https://rudrajs.com).
4
-
5
- rudra-js is an open-source TypeScript library (MIT) you install from npm. A
6
- language model designs one product-recommendation block for a page in your shop,
7
- rudra-js checks it against your catalog, and React renders it.
8
-
9
- It is not a hosted platform, a visual or low-code app builder, or a workspace
10
- you sign up for.
3
+ This package is part of [rudra-js](https://rudrajs.com), an open-source
4
+ TypeScript library (MIT) you install from npm. With rudra-js, a language model
5
+ designs one product-recommendation block for a page in your shop: the model
6
+ picks the layout and writes the words. After rudra-js checks the model's reply
7
+ against your products, React renders the block with your own titles and prices.
8
+ To be clear, rudra-js is not a hosted platform, a visual or low-code app
9
+ builder, or a workspace you sign up for.
11
10
 
12
11
  You give this package one page view:
13
12
 
14
- - the shopper and what they've been doing
13
+ - who the shopper is and what they've been doing
15
14
  - the page they're on
16
- - the products you're willing to show
15
+ - the products you're happy to show
17
16
 
18
- It gives back a spec: data that describes the recommendations on that page. Your
19
- model writes it, or core builds it without one. Either way, it's checked against
20
- those products. There's no React in this package. `@rudra-js/react` turns the
21
- spec into markup.
17
+ You get back a spec. It's just data describing the block. Your model can write
18
+ the spec, or core can build one without a model. This also happens if the model
19
+ fails. Either way, core checks the spec against those products.
22
20
 
23
- The guides and the API reference are at [rudrajs.com](https://rudrajs.com).
21
+ There's no React here: `@rudra-js/react` turns the spec into markup.
22
+
23
+ For more, see the guides and API reference on
24
+ [rudrajs.com](https://rudrajs.com).
24
25
 
25
26
  ## Install
26
27
 
@@ -28,75 +29,90 @@ The guides and the API reference are at [rudrajs.com](https://rudrajs.com).
28
29
  npm install @rudra-js/core@latest @rudra-js/attested@latest
29
30
  ```
30
31
 
31
- Run the same command in a new app, in an app that already uses rudra-js, and to
32
- upgrade.
32
+ You can run this command in a new app or in an app that already uses rudra-js.
33
+ It's also how to upgrade.
33
34
 
34
- If your app also has `@rudra-js/react` or `@rudra-js/anthropic`, add them to the
35
- command with `@latest`. Each one's peer range on core covers only its own minor
36
- release. Leave one behind and npm only warns, but the next `npm install` or
37
- `npm ci` fails with `ERESOLVE`.
35
+ If your app also has `@rudra-js/react` or `@rudra-js/anthropic`, you need to add
36
+ them to the command with `@latest`. For each of these packages, the peer range
37
+ on core covers only its own minor release. If you leave one behind, npm will
38
+ just warn you, but the next `npm install` or `npm ci` will fail with `ERESOLVE`.
38
39
 
39
- If your app has `@rudra-js/a2ui`, use the install line in that package's README
40
- instead. It also names the two A2UI packages.
40
+ If your app has `@rudra-js/a2ui`, you need to use the install line in the README
41
+ of that package instead. That line also names the two A2UI packages.
41
42
 
42
- Keep `@latest` on every name. For a bare name, npm stays inside the range your
43
- `package.json` already has, so an app on an older core never leaves the minor
44
- release it's on.
43
+ Be sure to keep `@latest` on all the names. For a bare name, npm will stay
44
+ inside the range your `package.json` already has. An app on an older core will
45
+ then never leave the minor release it's on.
45
46
 
46
- `zod` is a dependency, so you don't need to install it yourself. The public API
47
- of this package _is_ zod schemas. An app on any zod 4 shares one copy of zod
48
- with it.
47
+ You don't need to install `zod` yourself, because it's a dependency of this
48
+ package. The public API of this package _is_ zod schemas. If your zod 4 fits
49
+ this package's `zod` range, your app will share a single copy of zod with this
50
+ package. If your app's zod is below that range, it will get a second copy.
49
51
 
50
- An app on zod 3 gets its own copy next to ours, and the two don't mix. Build on
51
- the exported schemas with their own methods (`productSchema.array()`), not with
52
- your zod's (`z.array(productSchema)`). Read `error.issues` instead of checking
52
+ Apps on zod 3 will get their own copy next to ours, but the two copies don't
53
+ mix. Build on the exported schemas with their own methods
54
+ (`productSchema.array()`) instead of the methods of your zod
55
+ (`z.array(productSchema)`). Read `error.issues` instead of checking
53
56
  `instanceof ZodError`.
54
57
 
55
58
  `@rudra-js/anthropic` uses its own zod to write the tool schema sent to the
56
- model, so the schema's wording shifts a little between zod releases. Before zod
57
- 4.5, a nullable field is written as `anyOf` instead of a type array. Both mean
58
- the same thing.
59
-
60
- `@rudra-js/attested` is a peer dependency. None of its types appear in this
61
- package's public API, and you never have to import it. It's a peer so your app
62
- has exactly one copy of its phrase list. If your app pins its own version, npm
63
- stops with an `ERESOLVE` you can see and fix. If you pin nothing, npm installs
64
- one copy at the top of the tree. One tag publishes every `@rudra-js` package to
65
- npm at the same version, so these ranges always move together.
59
+ model. Because of this, the wording of the schema will shift a little between
60
+ zod releases. Before zod 4.5, a nullable field will be written as `anyOf`
61
+ instead of a type array, but both of these mean the same thing.
62
+
63
+ `@rudra-js/attested` is a peer dependency to make sure your app has exactly one
64
+ copy of its phrase list. None of its types appear in the public API of this
65
+ package and you never have to import it. If your app pins its own version, npm
66
+ will stop with an `ERESOLVE` you can see and fix. If you pin nothing, npm will
67
+ install a single copy at the top of the tree. All `@rudra-js` packages are
68
+ published to npm by a single tag at the same version. That's why these ranges
69
+ will always move together.
70
+
71
+ In browser code, import values from `@rudra-js/core/schemas` instead of
72
+ `@rudra-js/core`. It has `productSchema`, `bundleSchema`, `renderContextSchema`,
73
+ `FIELD_LIMITS`, `parseComponentSpec`, and the defaults a block uses for product
74
+ links, prices and stock. The main entry loads `node:crypto` to hash cache keys,
75
+ so keep it on the server. Types are the exception:
76
+ `import type { Product } from '@rudra-js/core'` is removed at build time, so
77
+ it's fine in browser code. Keep the `type` before the braces. With
78
+ `verbatimModuleSyntax`, `import { type Product }` stays in the build as an
79
+ import of the main entry.
66
80
 
67
81
  ## Running without a model
68
82
 
69
- `createComponentGenerator` takes a `provider`. Leave it out, or pass `null`, and
70
- nothing calls a model and nothing gets billed:
83
+ `createComponentGenerator` takes a `provider`. If you leave this out or pass
84
+ `null`, no model will be called and nothing will be billed:
71
85
 
72
86
  ```ts
73
87
  const generator = createComponentGenerator({ provider: null });
74
88
  const spec = await generator.generate(input);
75
89
  ```
76
90
 
77
- This is a supported setting. The benchmark compares the models against it. It's
78
- the right setting until you've picked a provider. `generate` returns a promise
79
- either way, so your code keeps its shape when you add one.
91
+ This is a supported setting. It's what the benchmark compares the models
92
+ against. It's also the right setting to use until you've picked a provider.
93
+ `generate` returns a promise either way, to let your code keep its shape when
94
+ you add one.
80
95
 
81
- Without a model, core builds the spec itself. The rest of this README calls that
82
- spec the fallback. It has exactly one **grid** block, with a headline from a
83
- fixed set of four. It has no blocks at all when there's nothing left to show.
84
- That happens when no candidate is in stock, and also when every candidate is
85
- ruled out for this shopper.
96
+ Without a model, core will build the spec itself. In the rest of this README
97
+ that spec is called the fallback. It has exactly one **grid** block with a
98
+ headline from a fixed set of four. If there's nothing left to show, it will have
99
+ no blocks at all. This will happen if no candidate is in stock, and also if all
100
+ of the candidates are ruled out for this shopper.
86
101
 
87
- The other block kinds (hero, carousel, banner, copy, bundle) only ever come from
88
- a model. So if you're wiring up bundles and none of them appear, that's why. It
89
- isn't your catalog.
102
+ All the other block kinds (hero, carousel, banner, copy, bundle) only ever come
103
+ from a model. If you're wiring up bundles and none of them appear, this is why.
104
+ It isn't your catalog.
90
105
 
91
- To render a spec you wrote yourself, still without a model, pass
92
- `createFixedSpecProvider(spec)` as the provider. It answers every request with
93
- that spec. Your spec goes through the same checks as a model's, so it needs a
94
- headline that passes the [claim check](#what-the-host-must-supply) and at least
95
- one product on show. Otherwise you get the fallback.
106
+ To render a spec you wrote yourself, still without a model, you can pass
107
+ `createFixedSpecProvider(spec)` as the provider. This will answer all requests
108
+ with that spec. Your spec will also go through the checks for a model's spec.
109
+ This means it will need a headline that passes the
110
+ [claim check](#what-the-host-must-supply) and also at least one product on show.
111
+ Otherwise you will get the fallback.
96
112
 
97
113
  ## Options
98
114
 
99
- Everything `createComponentGenerator` takes, and what you get if you leave it
115
+ All the options of `createComponentGenerator` and what you get if you leave them
100
116
  out.
101
117
 
102
118
  | Option | What it does | Default |
@@ -112,8 +128,8 @@ out.
112
128
  ## `tracking-input`
113
129
 
114
130
  This is the boundary between your app and rudra-js. You own your tracking
115
- pipeline and pass one JSON object per render. rudra-js collects nothing and
116
- stores nothing. It doesn't aggregate anything either.
131
+ pipeline and you just pass in a single JSON object per render. rudra-js collects
132
+ nothing and stores nothing. It doesn't aggregate anything either.
117
133
 
118
134
  ```ts
119
135
  import { parseTrackingInput } from '@rudra-js/core';
@@ -137,33 +153,34 @@ const input = parseTrackingInput({
137
153
  });
138
154
  ```
139
155
 
140
- `parseTrackingInput` throws a `ZodError`. If you'd rather not catch,
141
- `safeParseTrackingInput` returns a `TrackingInputResult` instead. Then you can
142
- read `result.error.issues` without importing zod yourself.
156
+ `parseTrackingInput` throws a `ZodError`. If you'd rather not catch it, you can
157
+ use `safeParseTrackingInput` to get a `TrackingInputResult` instead. You will
158
+ then be able to read `result.error.issues` without importing zod yourself.
143
159
 
144
160
  ### Cold start is not an error
145
161
 
146
- A payload with no `signals` block is a first-time visitor. Every signal list
147
- defaults to `[]`, so you don't need a special case for it.
162
+ Any payload with no `signals` block is a first-time visitor. All of the signal
163
+ lists will default to `[]`. You don't need a special case for it.
148
164
 
149
165
  ### What the host must supply
150
166
 
151
- Send `user.id`, `context.surface` and at least one entry in `candidates`. SKUs
152
- must be unique.
167
+ You need to send `user.id`, `context.surface` and at least one entry in
168
+ `candidates`. All SKUs must be unique.
153
169
 
154
- `candidates` sets which products can reach the page. Core looks up every SKU the
155
- model writes in that list. A SKU that isn't on it is dropped before anything
156
- renders.
170
+ `candidates` sets which products can reach the page. Core looks up all the SKUs
171
+ the model writes in that list. Any SKU that isn't in the list will be dropped
172
+ before anything renders.
157
173
 
158
- `bundles` is optional. These are the sets you sell together. Each one has your
159
- own price for the set and the currency that price is in. It can also have your
160
- own name for the set, its `label`. Every product in a set has to be a candidate
161
- as well. Bundle ids must be unique, and one set must not name the same product
174
+ `bundles` is optional. These are the sets you sell together. Each of these has
175
+ your own price for the set and the currency of that price. It can also have your
176
+ own name for the set in its `label`. All the products in a set have to be
177
+ candidates as well. Bundle ids have to be unique and a set can't name a product
162
178
  twice.
163
179
 
164
- A set is placed whole, so one check works differently. A set may hold something
165
- the shopper already bought or has in the basket. A grid or a carousel would drop
166
- that product. The whole set is still blocked when any member is:
180
+ Because a set is placed whole, one of the checks works differently. A set may
181
+ hold something the shopper has already bought or has in the basket, even though
182
+ a grid or a carousel would drop that product. But the whole set will be blocked
183
+ if any member is:
167
184
 
168
185
  - disliked by the shopper
169
186
  - out of stock
@@ -171,23 +188,24 @@ that product. The whole set is still blocked when any member is:
171
188
  - the product being looked at right now
172
189
 
173
190
  That last rule has a cost. A "frequently bought together, including this item"
174
- set names the product whose page it sits on, so it's refused on exactly the page
175
- you wrote it for. Leave that item out and sell its companions as the set. That
176
- rejection goes away, and the other checks still apply.
191
+ set will name the product of the page it sits on. It's then refused on exactly
192
+ the page you wrote it for. To get around this, you can leave that item out and
193
+ sell its companions as the set. That rejection will go away, but the other
194
+ checks will still apply.
177
195
 
178
- When a bundle block is the only block the model asked for, refusing the set
179
- leaves nothing to render. Then the fallback takes over.
196
+ If a bundle block is the only block the model asked for, refusing the set will
197
+ leave nothing to render. Then the fallback will take over.
180
198
 
181
- The model _never_ picks a set and is never told a price. All it does is ask for
182
- a bundle block and write the words around it. Core picks which set when the page
183
- is served. It bases the choice on what the shopper has in their basket, has
184
- looked at, or is browsing right now.
199
+ The model _never_ picks a set and is never told a price. All it can do is ask
200
+ for a bundle block and write the words around it. Core picks which set to use as
201
+ the page is served, based on the shopper's basket, the products they've looked
202
+ at or what they're browsing right now.
185
203
 
186
- The prompt tells the model to write about the offer, not the products in it. It
187
- also tells the model never to say the set saves money, or by how much. Your
188
- `label`, when you pass one, renders ahead of the model's words.
204
+ The prompt tells the model to write about the offer and not the products in it.
205
+ It also tells the model never to say the set saves money, or by how much. If you
206
+ pass a `label`, this will render ahead of the model's words.
189
207
 
190
- Core reads every word the model writes for claims:
208
+ Core reads all of the words the model writes, to look for claims:
191
209
 
192
210
  - the headline and the subheadline
193
211
  - a hero
@@ -197,69 +215,74 @@ Core reads every word the model writes for claims:
197
215
  - the reason under a product
198
216
  - the words around the set
199
217
 
200
- Text you supplied is never read this way. A product title, a category and a
201
- bundle `label` are your words.
218
+ Text you supplied is never read this way. All of these are your words: a product
219
+ title, a category and a bundle `label`.
202
220
 
203
- Core drops text that makes a claim it can't check. This README calls that the
204
- claim check. It runs in three passes:
221
+ Core drops any text that makes a claim it can't check. This README calls that
222
+ the claim check. There are three passes to it:
205
223
 
206
- 1. The first looks for money, a customer score, a delivery date and a count of
207
- what's left.
208
- 2. The second asks whether every numeral in the sentence is one you supplied.
209
- 3. The third is `@rudra-js/attested`'s phrase list. It catches claims with no
210
- number in them to check, like "top pick" and "customer favourite".
224
+ 1. In the first pass, core looks for money, a customer score, a delivery date
225
+ and a count of what's left.
226
+ 2. In the second pass, core asks whether all the numerals in the sentence are
227
+ ones you supplied.
228
+ 3. In the third pass, core uses the phrase list of `@rudra-js/attested`. This
229
+ catches claims with no number in them to check, like "top pick" and
230
+ "customer favourite".
211
231
 
212
- For example, the second pass keeps "a comfort rating of -5C" only when a `5`
213
- turns up in a `tag` or a `category` name you sent. The pass compares the number,
214
- not the string, so a tag reading `5-pocket` keeps it as surely as one reading
215
- `-5C comfort`.
232
+ For example, the second pass will keep "a comfort rating of -5C" only if a `5`
233
+ turns up in a `tag` or a `category` name you sent. This pass compares the number
234
+ and not the string. A tag reading `5-pocket` will keep it just as surely as a
235
+ tag reading `-5C comfort`.
216
236
 
217
- Tags and category names count because they're the strings core hands the model
218
- and lets it repeat. The model is also shown each product's `title` and `rating`.
219
- Neither one backs a number, because the prompt tells it never to restate either.
220
- Put your product's figures in `tags` and the model can quote them. Leave them
221
- out, and any figure the model writes about them is made up, so it's dropped.
237
+ Tags and category names count because these are the strings core hands to the
238
+ model and lets it repeat. The model is also shown the `title` and `rating` of
239
+ each product, but neither of these can back a number, because the prompt tells
240
+ the model never to restate either. If you put your product's figures in `tags`,
241
+ these can be quoted by the model. If you leave these out, any figure the model
242
+ writes about them is made up and will be dropped.
222
243
 
223
244
  Which strings count, exactly:
224
245
 
225
- - Only candidates the model was shown. A product that's out of stock, or past
226
- the 60 core sends, is one the model never saw. Its tags back nothing.
227
- - Not the `currentCategory` on the request. It's a string from this request, not
228
- a row of your catalog, and plenty of sites pass a URL segment straight into
229
- it.
230
- - A `reason` or a `badge` sits under a named product, so it's read against that
231
- product's own tags and category. Every other field is read against all the
232
- candidates' tags and categories, pooled.
233
-
234
- Two things to know about the second pass. Pooled means pooled: one product's
235
- `40 litre` tag backs "take 40 off" written in a headline about another. And
236
- nothing in the pass knows which quantity a tag was about, so a tag holding a
237
- weight backs a price with the same digits in it. The pass proves the digits came
238
- from you. It doesn't prove the sentence is true.
239
-
240
- The first and third passes are word lists. A word list can miss a claim, so it
241
- isn't a guarantee the way checking a price against your catalog is. The second
242
- pass proves something narrower than it sounds: every digit was one of yours. A
243
- number written as a word isn't a number to it, so it can't see "four and a half
244
- stars" as a rating. A ½, or the K in "10K", is a numeral it can't read. It drops
245
- those instead of letting them through.
246
-
247
- The model isn't told any of this. The prompt bans prices, ratings, discounts,
248
- delivery dates and stock levels. It says nothing about digits. So the model
249
- can't tell `3-season`, a tag you sent and fine to use, from `2 litres`, which
250
- isn't. However much good text the check drops on your catalog, nothing in the
251
- prompt brings that down.
252
-
253
- Some fields can't be null, like a headline or a banner's text. When the check
254
- drops text from one of those, it empties the field instead. The block then
255
- drops, as any block with no text does. An empty page headline makes the whole
256
- generation unusable.
257
-
258
- That's the costly case. Say the model writes "Our 3 favourites for wet weather"
259
- and no candidate carries a 3. The headline empties, so the generation is
260
- unusable and the fallback renders. You paid for a model call and threw it away.
261
- In cohort mode the spec is cached before it's checked, so every cache hit runs
262
- the same check and gets the same fallback until the entry expires.
246
+ - Only candidates the model was shown. Any product that's out of stock or past
247
+ the 60 core sends is a product the model never saw. Its tags back nothing.
248
+ - Not the `currentCategory` on the request. That's a string from this request
249
+ and not a row of your catalog. There are also plenty of sites that pass a URL
250
+ segment straight into it.
251
+ - A `reason` or a `badge` will sit under a named product. It's read against the
252
+ tags and category of that product. All other fields are read against the tags
253
+ and categories of all the candidates, pooled.
254
+
255
+ There are two things to know about the second pass. Pooled means pooled: a
256
+ `40 litre` tag on a product will back "take 40 off" in a headline about another
257
+ product. And nothing in this pass can know which quantity a tag was about.
258
+ That's why a tag holding a weight will back a price that has those digits in it.
259
+ This pass will prove the digits came from you, but it won't prove the sentence
260
+ is true.
261
+
262
+ In the first and third passes, core uses word lists. Word lists can miss a
263
+ claim. They aren't a guarantee in the way that checking a price against your
264
+ catalog is. For the second pass, the proof is narrower than it sounds: all of
265
+ the digits were yours. To this pass, a number written as a word isn't a number.
266
+ It can't see "four and a half stars" as a rating. It also can't read some
267
+ numerals, like a ½ or the K in "10K". Those will be dropped, not let through.
268
+
269
+ None of this is told to the model. In the prompt there's a ban on prices,
270
+ ratings, discounts, delivery dates and stock levels, but nothing about digits.
271
+ The model has no way to tell `3-season` (a tag you sent and fine to use) from
272
+ `2 litres` (which isn't). However much good text the check drops on your
273
+ catalog, nothing in the prompt can bring that down.
274
+
275
+ Some fields can't be null, like a headline or the text of a banner. If the check
276
+ drops text from one of these, it will empty the field instead. Banner and copy
277
+ blocks will then be dropped. For a hero, this will only happen if it has no
278
+ product either. An empty page headline makes the whole generation unusable.
279
+
280
+ That's the costly case. For example, the model might write
281
+ "Our 3 favourites for wet weather" when no candidate carries a 3. This headline
282
+ will be emptied. That makes the generation unusable and the fallback will
283
+ render. You will have paid for a model call just to throw it away. In cohort
284
+ mode the spec is cached before it's checked. This means all cache hits will
285
+ repeat the check and get the same fallback until the entry expires.
263
286
 
264
287
  ### Defaults
265
288
 
@@ -278,14 +301,14 @@ the same check and gets the same fallback until the entry expires.
278
301
  | `mostViewed[].views` | `1` |
279
302
  | `lastPurchased[].quantity` | `1` |
280
303
 
281
- `context.locale` has to be one language tag, such as `en-US`. Not a list, and
282
- not an `Accept-Language` header.
304
+ `context.locale` has to be a single language tag, such as `en-US`. It can't be a
305
+ list or an `Accept-Language` header.
283
306
 
284
307
  ### Cohorts
285
308
 
286
- By default, shoppers who look alike share one generated spec. Each shopper's own
287
- products are filled in per request. A group of look-alike shoppers is a cohort.
288
- A cohort is set by:
309
+ By default, shoppers who look alike will share a single generated spec and the
310
+ products for each shopper are filled in per request. A group of look-alike
311
+ shoppers is called a cohort. It's set by:
289
312
 
290
313
  - the shopper's segment
291
314
  - the surface and the slot
@@ -295,53 +318,58 @@ A cohort is set by:
295
318
  - the category being browsed
296
319
  - the category they lean towards
297
320
 
298
- Only two of these come from the shopper's own data: whether they have any
299
- history, and the category they lean towards. Who they are, what they searched
300
- for and the products they liked or viewed stay out. That's what lets many page
301
- views reuse one model call.
302
-
303
- The candidate list is part of the cohort too, because the model is shown those
304
- products and writes about them. In most shops candidates come from the page, so
305
- everyone looking at it shares them. If you pick candidates per shopper, you'll
306
- get smaller cohorts, because each prompt really is personal.
307
-
308
- The cache key for a cohort holds the _set_ of candidate SKUs. It ignores the
309
- order you sent them in, which ones were in stock, and where the 60-product cut
310
- fell. So two requests with the same SKUs in a different order share one spec,
311
- and both get the one generated first. If your ranking is personal and you order
312
- your candidates per shopper, the products the copy talks about won't be the ones
313
- you put at the top.
314
-
315
- Prices, titles and stock are always read from your catalog at render time, so a
316
- stale one never shows. A product that sold out is dropped as the page is served.
317
- Any sentence the model wrote about it stays.
321
+ Only two of these come from the shopper's data: whether they have any history
322
+ and the category they lean towards. Who they are, their searches and the
323
+ products they liked or viewed are all left out. This lets many page views reuse
324
+ a single model call.
325
+
326
+ Candidate lists are also part of the cohort, because the model is shown those
327
+ products and writes about them. In most shops the candidates come from the page
328
+ and will be shared by all the people looking at it. If you pick candidates per
329
+ shopper, you'll get smaller cohorts, because each prompt really is personal.
330
+
331
+ The cache key is a hash of the exact prompt the model is sent. So it sees the
332
+ candidates the way the model does: the first 60 in stock, in the order you sent
333
+ them, each with its title, category, rating and tags. Two requests with the same
334
+ products in a different order get a spec each. A product that sells out or comes
335
+ back moves the key too, so the next request asks the model again. If your
336
+ ranking is personal and you order your candidates per shopper, each order makes
337
+ a cohort of its own. Send them in the same order to everyone who should share a
338
+ spec.
339
+
340
+ Prices, titles and stock will always be read from your catalog at render time.
341
+ This is to make sure a stale value never shows in those fields. A price or an
342
+ image never reaches the model, so changing one keeps the spec you have.
318
343
 
319
344
  #### Who can create a cohort
320
345
 
321
- Every cohort field above is one you supply, and each distinct value makes a
322
- cohort of its own. That's a fresh model call, and a slot in the cache. If a
323
- visitor can choose one of these values, a visitor can choose how many calls you
324
- pay for. These are the three that go wrong:
346
+ You supply all of the cohort fields above and each distinct value will make a
347
+ cohort of its own. This will cost you a fresh model call and also a slot in the
348
+ cache. If a visitor can choose any of these values, they can choose how many
349
+ calls you pay for. These are the three that go wrong:
325
350
 
326
351
  - a `locale` copied straight out of `Accept-Language`
327
352
  - a `currentCategory` read off a URL slug
328
353
  - a `segment` built from a query parameter
329
354
 
330
- The built-in cache holds 10,000 entries, so once it's full, made-up values push
331
- out the cohorts your real shoppers were being served from.
355
+ There's room for 10,000 entries in the built-in cache. Once it's full, made-up
356
+ values will push out the cohorts your real shoppers were being served from.
332
357
 
333
- Draw those fields from sets you control:
358
+ You need to draw those fields from sets you control:
334
359
 
335
360
  - your own locale list
336
361
  - your own category ids
337
362
  - your own segment labels
338
363
 
339
- Nothing leaks either way, because a cohort prompt carries no shopper text at
340
- all. The cost is the bill, plus a model round trip on a page that was being
341
- served from cache.
364
+ A cohort prompt leaves out the shopper's searches and signal lists, but those
365
+ three fields go in as written. If a visitor can set one, what they send reaches
366
+ your provider. The other cost will be the bill, plus a model round trip on a
367
+ page that was being served from cache.
342
368
 
343
- Pass `generation: 'per-shopper'` to generate for each shopper instead. The model
344
- then picks the products too, and every shopper costs their own call.
369
+ To generate for each shopper instead, you can pass `generation: 'per-shopper'`.
370
+ The model will then pick the products too. Most shoppers will cost a call of
371
+ their own. Two share an entry only when their prompts match exactly, as two
372
+ first-time visitors on the same page can.
345
373
 
346
374
  ```ts
347
375
  createComponentGenerator({ provider, generation: 'per-shopper' });
@@ -349,9 +377,9 @@ createComponentGenerator({ provider, generation: 'per-shopper' });
349
377
 
350
378
  #### What you put in `segment`
351
379
 
352
- `segment` goes to the model exactly as you wrote it, in both modes. The schema
353
- takes any string up to 128 characters. Stick to plain merchandising labels like
354
- `lapsed`, `high-value`, `trial` or `wholesale`. Keep out anything that says
380
+ In both modes, `segment` goes to the model exactly as you wrote it. The schema
381
+ takes any string of up to 128 characters. Stick to plain merchandising labels
382
+ like `lapsed`, `high-value`, `trial` or `wholesale`. Keep out anything that says
355
383
  something protected about a person:
356
384
 
357
385
  - health
@@ -363,14 +391,15 @@ something protected about a person:
363
391
  - union membership
364
392
  - biometric or genetic data
365
393
 
366
- The same goes for `recentSearches`, `context.searchQuery` and `interaction.type`
367
- in per-shopper mode. Those three are shopper text, and they're sent as written.
368
- What a shopper types belongs to them. The label you give them is your choice.
394
+ This also applies to `recentSearches`, `context.searchQuery` and
395
+ `interaction.type` in per-shopper mode. These three are shopper text and will be
396
+ sent as written. Anything a shopper types belongs to them, but the label you
397
+ give them is your choice.
369
398
 
370
399
  ### Limits
371
400
 
372
- Every free-text field and every array has a cap, because your strings end up
373
- inside a model prompt and you pay for a model per token. The caps live in
401
+ All free-text fields and all arrays have a cap, because your strings end up
402
+ inside a model prompt and you pay for a model per token. These caps are in
374
403
  `FIELD_LIMITS`, which is exported. Validate against the same numbers instead of
375
404
  finding them out from a rejection.
376
405
 
@@ -390,28 +419,36 @@ finding them out from a rejection.
390
419
  | `maxItems` | 12 | `context.maxItems`, which also needs at least 1 |
391
420
  | `reason` | 120 | `candidates[].reason`, your own phrase for a product |
392
421
 
393
- Each cap bounds one field on its own. Together they aren't a budget for the
394
- whole prompt. Fitting a payload into a context window is the digest's job. The
395
- digest is core's short summary of the shopper and the page, which goes into the
396
- prompt. It trims instead of throwing.
422
+ A product's `sku` and each of `bundles[].skus` must also be well-formed Unicode.
423
+ Half of a UTF-16 surrogate pair on its own is refused, because the default
424
+ product link runs the SKU through `encodeURIComponent`, and that throws on one.
425
+
426
+ Each cap bounds a single field on its own. Together they aren't a budget for the
427
+ whole prompt. Core doesn't count tokens either. The digest, the short summary of
428
+ the shopper and the page, trims signals instead of throwing. The prompt will
429
+ also be limited to 60 in-stock candidates. With long titles and tag lists, those
430
+ 60 products can still be too much for a small model.
397
431
 
398
432
  ### Unknown fields are rejected
399
433
 
400
- Every fixed-shape object is a `strictObject`. Misspell `recentSearches` and you
401
- get an error, instead of a shopper who quietly looks like a first-time visitor.
402
- `interaction.meta` is the one open shape. It takes any key, except the keys that
403
- would change a prototype instead of the object.
434
+ Any fixed-shape object is a `strictObject`. If you misspell `recentSearches`,
435
+ you'll get an error instead of a shopper who looks like a first-time visitor
436
+ with no sign of why. `interaction.meta` is the only open shape. It takes any
437
+ key, except the keys that would change a prototype instead of the object.
404
438
 
405
439
  ## Bringing your own ranking
406
440
 
407
- By default core orders the products for you. It scores each candidate against
408
- the shopper's signals. You might already have a recommender you trust:
441
+ By default core orders the products for you in cohort mode and in the fallback,
442
+ by scoring each candidate against the shopper's signals. You might already have
443
+ a recommender you trust:
409
444
 
410
445
  - bought-together data
411
- - an engine trained on your own orders
446
+ - an engine trained on your orders
412
447
  - a merchandiser's hand-picked row
413
448
 
414
- Pass `rank: 'given'` and the order you sent is the order that renders.
449
+ If you pass `rank: 'given'`, the order you sent will be kept for grids and
450
+ carousels in cohort mode and in the fallback. The hero's product will still be
451
+ picked by the model. In per-shopper mode the model will pick the order too.
415
452
 
416
453
  ```ts
417
454
  const generator = createComponentGenerator({ provider, rank: 'given' });
@@ -424,30 +461,30 @@ shouldn't be shown:
424
461
  - already bought
425
462
  - in the basket
426
463
  - disliked
427
- - the product they're looking at right now
464
+ - being looked at right now
428
465
 
429
- Core reads these from the payload you sent, not from the shorter history the
430
- model was shown. So a shopper with a long order history is covered too. Every
431
- product still carries a basis, a code like `most_viewed` that says why it's
432
- shown, and core checks it against the shopper's real signals. Everything the
433
- model writes still goes through the claim check.
466
+ These checks use the payload you sent and not a trimmed copy of it. This means
467
+ a shopper with a long order history is covered too. Each product will still have
468
+ a basis: this is a code like `most_viewed` to say why
469
+ it's shown. Core checks this basis against the shopper's real signals. All of
470
+ the model's text will still be read by the claim check.
434
471
 
435
- There are six bases, and two of them prove less than their names suggest:
472
+ There are six bases, but two of them prove less than their names suggest:
436
473
 
437
474
  - `most_viewed` is checked against the SKUs they viewed.
438
475
  - `similar_to_current` is checked against the category being browsed.
439
- - `liked_category` is checked against the categories they bought, liked, carted
440
- or viewed in. Standing on a category page isn't one of those.
476
+ - `liked_category` is checked against the categories of products they've bought,
477
+ liked, carted or viewed. Just standing on a category page doesn't count.
441
478
  - `popular` claims nothing.
442
479
  - `complements_cart` checks only that the basket isn't empty.
443
480
  - `complements_purchase` checks only that the order history isn't empty.
444
481
 
445
- The two `complements_` bases are the weak ones, because nothing here can know
446
- that one product goes with another. A basis that fails takes the sentence and
447
- the badge stating it with it.
482
+ Of these, the two `complements_` bases are the weak ones, because nothing here
483
+ can know that a product goes with another. If a basis fails, the sentence and
484
+ the badge stating it are dropped too.
448
485
 
449
- Each candidate can carry its own `reason`, the phrase shown under the product.
450
- Use it when your ranking knows something the signals don't:
486
+ Candidates can also carry a `reason` (the phrase shown under the product). You
487
+ can use this if your ranking knows something the signals don't:
451
488
 
452
489
  ```ts
453
490
  candidates: [
@@ -461,69 +498,74 @@ candidates: [
461
498
  ];
462
499
  ```
463
500
 
464
- A reason you supply is your own words, like the title, so it renders as written
465
- and skips the claim check. That only applies where this request actually used
466
- it, which is the default `cohort` mode. In `per-shopper` mode the model writes
467
- the reasons itself. Every one of them goes through the claim check, even one
468
- that reads the same as yours.
501
+ Any reason you supply is in your own words, like the title. It renders as
502
+ written and skips the claim check. But that only applies where this request
503
+ actually used it (the default `cohort` mode). In `per-shopper` mode the model
504
+ writes the reasons itself. All of these will be read by the claim check, even if
505
+ a reason reads the same as yours.
469
506
 
470
- Without a reason of your own, core states the basis for you from the shopper's
471
- signals, like "More in Backpacks" or "Goes with what is in your cart". Those are
472
- core's words, not the model's, so in `cohort` mode they skip the claim check
473
- too.
507
+ You don't have to supply a reason: core will state the basis for you from the
508
+ shopper's signals, like "More in Backpacks" or "Goes with what is in your cart".
509
+ These are core's words and not the model's. In `cohort` mode they also skip the
510
+ claim check.
474
511
 
475
512
  ## What the model sees
476
513
 
477
- The two generation modes send different things. Cohort is the default.
514
+ There are two generation modes and they send different things. Cohort is the
515
+ default.
478
516
 
479
517
  ### Cohort mode
480
518
 
481
519
  - the surface and the slot
482
520
  - the locale
483
- - the segment, when you set one
521
+ - the segment, if set
484
522
  - the category being browsed (`context.currentCategory`)
485
- - the name of the category the shopper leans towards most, without its score
486
- - whether this shopper has no history at all, meaning no likes, dislikes,
487
- purchases, basket items or views. Searches and other interactions don't count
488
- - how many products the spec may place (`context.maxItems`)
489
- - the candidate list: one line per product, with its SKU, title, category,
490
- rating and tags
523
+ - the name of the category the shopper leans towards most, but not its score
524
+ - whether this shopper has no history at all (no likes, dislikes, purchases,
525
+ basket items or views). Searches and other interactions don't count
526
+ - how many products the spec can place (`context.maxItems`)
527
+ - the candidate list: a line per product with its SKU, title, category, rating
528
+ and tags
491
529
 
492
530
  ### Per-shopper mode
493
531
 
494
- Everything above, and:
532
+ All of the above and also:
495
533
 
496
534
  - the SKU being looked at right now
497
535
  - the current search
498
536
  - whether this is a returning shopper
499
537
  - liked SKUs, and disliked SKUs
500
- - purchased SKUs, and what is in the basket
501
- - the most-viewed SKUs, each with its view count
538
+ - purchased SKUs and what is in the basket
539
+ - most-viewed SKUs, each with its view count
502
540
  - recent searches
503
541
  - up to six categories they lean towards, strongest first
504
- - the other kinds of interaction, each with a count
542
+ - other kinds of interaction, each with a count
505
543
 
506
544
  ### Left out of both
507
545
 
508
546
  - `user.id`
509
- - every timestamp (`at`). Core uses them to sort signals, then drops them
547
+ - all timestamps (`at`). Core uses these to sort signals and then they're
548
+ dropped
510
549
  - dwell time (`dwellMs`). It's added up in the digest and left out of the prompt
511
550
  - every price, and every currency
512
551
  - `imageUrl`
513
552
  - `interaction.value` and `interaction.meta`. The model is told which kinds of
514
- interaction happened and how often, and no more
553
+ interaction happened and how often, but no more
515
554
 
516
- The candidate list is trimmed before it's sent. Out-of-stock products are
517
- dropped, and at most 60 products go, in the order you supplied them.
555
+ The candidate list will be trimmed before it's sent. Out-of-stock products will
556
+ be dropped and no more than 60 products will go, in the order you supplied.
518
557
 
519
- `spec-cache.test.ts` walks every field of the digest. It checks that each one is
520
- either in the cache key or removed from the cohort prompt. A field the key
521
- leaves out that still changes the prompt fails that test. A new field added to
522
- the digest fails it too, until someone says which side the field is on.
558
+ The cache key hashes the prompt itself, so nothing the model is shown can be
559
+ left out of it. `spec-cache.test.ts` walks all the fields of the digest, to
560
+ check that each one either reaches the cohort prompt or is removed from it. A
561
+ new field added to the digest fails the typecheck there until someone gives it
562
+ a test value, and the walk then fails if the field reaches the cohort prompt
563
+ without being listed as part of the cohort.
523
564
 
524
565
  ## What the model decides, by mode
525
566
 
526
- What the model wrote, and what core replaces before the page is served.
567
+ Here you can see what the model wrote and what will be replaced by core before
568
+ the page is served.
527
569
 
528
570
  | Decision | Cohort, the default | Per-shopper |
529
571
  | ---------------------------------- | --------------------------------------- | -------------------------------------- |
@@ -535,21 +577,21 @@ What the model wrote, and what core replaces before the page is served.
535
577
  | The reason and basis per product | Filled in per request, not by the model | The model, checked against the signals |
536
578
  | Which bundle, of the ones you pass | Chosen per request, not by the model | Chosen per request, not by the model |
537
579
 
538
- In cohort mode the grid and carousel items are filled in per request, best pick
539
- first, so a spec written for one shopper still fits the next.
580
+ In cohort mode the grid and carousel items are filled in per request (best pick
581
+ first). That way, a spec written for one shopper will also fit the next.
540
582
 
541
- The hero is the exception. It keeps the product the model named, because its
542
- headline and body were written about that product. When that product can't be
543
- placed, core drops the link and keeps the words. It can't be placed when:
583
+ But the hero is the exception. It keeps the product the model named, because its
584
+ headline and body were written about that product. If this product can't be
585
+ placed, core will drop the link and keep the words. It can't be placed if:
544
586
 
545
587
  - this shopper can't see it: it's out of stock, not a candidate, disliked,
546
- already bought, in the basket, or the one being looked at
588
+ already bought, in the basket or being looked at
547
589
  - an earlier block already placed it
548
- - the item budget ran out before the hero was reached
590
+ - the item budget had run out by the time the hero was reached
549
591
 
550
592
  ## Any provider
551
593
 
552
- A provider is three things:
594
+ There are three things to a provider:
553
595
 
554
596
  ```ts
555
597
  export interface ComponentProvider {
@@ -561,36 +603,36 @@ export interface ComponentProvider {
561
603
  }
562
604
  ```
563
605
 
564
- `createComponentGenerator({ provider })` takes any object of that shape. That
565
- can be a hosted API, a model you run yourself, a deployment inside your own
566
- tenancy, or a recorded fixture. `@rudra-js/core` depends on no vendor SDK.
567
- `@rudra-js/anthropic` is one adapter, and you don't need it.
606
+ `createComponentGenerator({ provider })` takes any object of that shape. This
607
+ might be a hosted API, a model you run yourself, a deployment inside your
608
+ tenancy or a recorded fixture. `@rudra-js/core` depends on no vendor SDK.
609
+ `@rudra-js/anthropic` is just one adapter and you don't have to use it.
568
610
 
569
- An adapter takes its API key as an option, so you choose where the key comes
570
- from. `ANTHROPIC_API_KEY` is just the name the example shop uses. No package
571
- here reads the environment.
611
+ An adapter takes its API key as an option. You can then choose where the key
612
+ comes from. `ANTHROPIC_API_KEY` is just the name the demo uses. No
613
+ package here reads the environment.
572
614
 
573
615
  ## The cache
574
616
 
575
617
  By default `cache` is an in-process store. `createMemorySpecCache()` keeps an
576
- entry for `ttlMs`, which defaults to 60,000 milliseconds, so one minute. It
577
- holds up to `maxEntries`, which defaults to 10,000. Once it's full, the entry
578
- read longest ago is the first to go.
618
+ entry for `ttlMs`. This defaults to 60,000 milliseconds (one minute). This store
619
+ will hold up to `maxEntries`, which defaults to 10,000. Once it's full, the
620
+ entry read longest ago will be the first to go.
579
621
 
580
622
  An entry holds the generated spec, as the model returned it before any checks.
581
- It also holds `generatedAt`, the epoch milliseconds when the model produced it.
582
- It holds no payload and no prompt.
623
+ It also holds `generatedAt` (the epoch milliseconds of when the model produced
624
+ the spec). It doesn't hold a payload or a prompt.
583
625
 
584
- In cohort mode an entry holds no shopper id, and everyone in the cohort shares
585
- it. The exception is an entry whose segment or candidates were picked for one
586
- shopper. In per-shopper mode the model wrote the entry from that shopper's
587
- signals. So its text can repeat them, a search term for instance, and the entry
588
- is personal data until it's gone.
626
+ In cohort mode an entry holds no shopper id and it's shared by all the shoppers
627
+ in the cohort. But there's an exception if the segment or candidates were picked
628
+ or ordered for one shopper. In per-shopper mode the model wrote the entry from
629
+ the signals of that shopper. Its text can then repeat them (a search term, for
630
+ instance) and the entry will be personal data until it's gone.
589
631
 
590
- Expiry is checked when an entry is read, so an expired entry stays in memory
591
- until it's read again or pushed out by a newer one.
632
+ Expiry is checked when an entry is read. An expired entry will stay in memory
633
+ until it's read again or pushed out by a newer entry.
592
634
 
593
- The cache interface is two methods, and an optional third:
635
+ The cache interface is two methods and an optional third:
594
636
 
595
637
  ```ts
596
638
  export interface SpecCache {
@@ -600,111 +642,118 @@ export interface SpecCache {
600
642
  }
601
643
  ```
602
644
 
603
- Pass your own store, whether that's Redis, Memcached or whatever you already
604
- run, and it keeps entries on its own terms. What that store holds, and for how
605
- long, is yours to declare to your users. This package doesn't set it. Pass
606
- `createNullSpecCache()` to store nothing at all.
645
+ You can also pass a store of your own (Redis, Memcached or whatever you already
646
+ run) and it will keep entries on its own terms. It's up to you to declare to
647
+ your users what that store holds and for how long. That's not set by this
648
+ package. To store nothing at all, you can pass `createNullSpecCache()`.
607
649
 
608
650
  ### When a generation is wrong
609
651
 
610
- - Pass `provider: null` and nothing new is generated, so every page renders the
611
- fallback.
612
- - Shorten `ttlMs` and a bad entry ends sooner.
613
- - If your store has `delete`, drop one entry by the `key` on its
614
- `GenerationEvent`. The next request generates again.
652
+ - If you pass `provider: null`, nothing new will be generated and all pages will
653
+ render the fallback.
654
+ - If you shorten `ttlMs`, a bad entry will end sooner.
655
+ - If your store has `delete`, you can drop an entry by the `key` on its
656
+ `GenerationEvent`. The next request will then generate again.
615
657
 
616
- Per-shopper entries only end when they expire, because nothing maps a shopper to
617
- their keys.
658
+ Core can't drop all the entries of a shopper for you, because nothing maps a
659
+ shopper to their keys. Per-shopper entries will end when they expire or when
660
+ newer entries push them out. You can also delete an entry by a `key` you kept.
618
661
 
619
662
  ## Watching it in production
620
663
 
621
- The generator never fails a render, so a provider that's been down for a week
622
- only shows up as plainer pages. Watch `onEvent` to find out. Every call to
623
- `generate` that gets past input validation reports exactly one
624
- `GenerationEvent`. A payload that fails `parseTrackingInput` throws instead, and
625
- reports nothing.
664
+ The generator never fails a render. If a provider has been down for a week, this
665
+ will only show up as plainer pages. To find out, you need to watch `onEvent`.
666
+ Each call to `generate` that gets past input validation reports exactly one
667
+ `GenerationEvent`. If a payload fails `parseTrackingInput`, it will throw
668
+ instead and report nothing.
626
669
 
627
- Keep these numbers:
670
+ These are the numbers to keep:
628
671
 
629
- - **Fallback share.** The share of events with `source: 'fallback'`. Alert when
630
- it climbs. `degradedReason` tells you which way the call failed. When the
631
- reason is `'provider-error'` or `'timeout'`, `error` carries what was thrown.
672
+ - **Fallback share.** This is the share of events with `source: 'fallback'`. Be
673
+ sure to alert if it climbs. `degradedReason` will tell you which way the call
674
+ failed. If the reason is `'provider-error'` or `'timeout'`, `error` has the
675
+ value that was thrown.
632
676
  - **Cache hit rate.** `cache: 'hit'` over the events that have a `cache` field.
633
- A store that's down shows as `cache: 'error'`, and a slow one as
634
- `cache: 'timeout'`. So a broken store shows up here, not only as a rising
635
- bill.
636
- - **Spend.** Sum `usage` over the events where `calledModel` is true. Requests
637
- that joined a generation already in flight carry the same `usage`, so summing
638
- over every event counts one call many times. Some calls the model answered are
639
- turned down by the adapter: a `max_tokens` stop, a refusal, no tool call, or a
640
- reply that doesn't fit the schema. Those were billed too. They arrive as a
641
- `'provider-error'` with no `usage`, so this sum is lower than your bill.
677
+ A store that's down will show as `cache: 'error'` and a slow store as
678
+ `cache: 'timeout'`. A broken store will then show up here and not just as a
679
+ rising bill.
680
+ - **Spend.** This is the sum of `usage` over the events where `calledModel` is
681
+ true. Any requests that joined a generation already in flight will carry the
682
+ `usage` of that generation too. If you sum over all the events, this will
683
+ count a call many times. Some of the calls the model answered are turned down
684
+ by the adapter: a `max_tokens` stop, a refusal, no tool call or a reply that
685
+ doesn't fit the schema. These were billed too, but they arrive as a
686
+ `'provider-error'` with no `usage`. That's why your bill will be more than
687
+ this sum.
642
688
 
643
689
  ## Running it in a regulated shop
644
690
 
645
- This isn't legal advice, and which rules apply depends on where you sell. It
646
- describes what the package does, so you can answer what a privacy or
647
- consumer-law review will ask.
648
-
649
- **What leaves your server.** Nothing, unless you pass a `provider`, or a `cache`
650
- whose store lives somewhere else. With a provider, cohort mode sends the page
651
- and locale, the category, the segment you set, the shopper's strongest category,
652
- whether they have any history, and the candidate products. That has no shopper
653
- id, but it can still be personal data. The strongest category and the history
654
- flag come from that shopper's data. The segment goes exactly as you wrote it.
655
- The candidate list is about them too if you pick or order it per shopper.
656
- Per-shopper mode adds the shopper's own signals. Both lists are under
691
+ This isn't legal advice. Which rules apply will depend on where you sell. To
692
+ help you answer the questions in a privacy or consumer-law review, this section
693
+ describes what the package does.
694
+
695
+ **What leaves your server.** Nothing, unless you pass a `provider` or a `cache`
696
+ that has its store somewhere else. With a provider, cohort mode will send the
697
+ page and locale, the category, the segment you set, the shopper's strongest
698
+ category, whether they have any history and the candidate products. That has no
699
+ shopper id, but it can still be personal data. Both the strongest category and
700
+ the history flag are taken from the shopper's data. Any segment will go to the
701
+ provider exactly as you wrote it. If you pick or order the candidate list per
702
+ shopper, this list is also about the shopper. Per-shopper mode will also send
703
+ the shopper's signals. You can see these lists under
657
704
  [What the model sees](#what-the-model-sees). `user.id` is never sent in either
658
- mode. The provider should be your processor, under a contract that says so. For
659
- Anthropic, see the `@rudra-js/anthropic` README.
705
+ mode. The provider should be your processor, under a contract that says this.
706
+ For Anthropic, see the `@rudra-js/anthropic` README.
660
707
 
661
708
  **A shopper who objects to profiling.** Leave `signals` and `user.segment` out
662
- of their payload. In per-shopper mode, leave out `context.searchQuery` and
663
- `user.isReturning` too. They get what a first-time visitor gets, built from the
664
- page and the catalog, not from them. With those left out,
665
- `generateDeterministic(input)` gives the same kind of spec without calling the
666
- model or the cache. Called with signals, it still personalises.
667
-
668
- **Deleting a shopper's data.** The package keeps nothing about a shopper except
669
- the cache. In cohort mode an entry holds no shopper id and everyone in the
670
- cohort shares it, so usually there's no one shopper's entry to delete. The
671
- exception is a cohort entry whose segment or candidate list was picked for one
672
- shopper. Like every per-shopper entry, it's about that shopper. Nothing maps a
673
- shopper to their entries, so keep `ttlMs` short or pass `createNullSpecCache()`.
674
- `onEvent` sends no shopper id. But in per-shopper mode its `key` is derived from
675
- one, and `violations` can name SKUs from a shopper's basket or purchases. So
676
- treat logs of it as personal data.
677
-
678
- **Caching pages.** A personalised page says things like "Goes with your cart"
679
- and "You looked at this recently" in its HTML. Serve those pages with
680
- `Cache-Control: private` or `no-store`, so a shared cache never hands one
681
- shopper's page to another.
682
-
683
- **Telling shoppers a model wrote the copy.** The wrapper's `data-rudra-source`
684
- says `llm` or `cache` when a model wrote the copy, and `fallback` when it
685
- didn't. That makes it a machine-readable marker you can build on, for example
686
- to show a note. Whether you must label AI-written copy, and how, depends on
709
+ of their payload. In per-shopper mode, you also need to leave out
710
+ `context.searchQuery` and `user.isReturning`. They will be treated like a
711
+ first-time visitor, with a spec built just from the page and the catalog. With
712
+ those left out, `generateDeterministic(input)` can be used to get the same kind
713
+ of spec without calling the model or the cache. But if you call it with signals,
714
+ it will personalise.
715
+
716
+ **Deleting a shopper's data.** This package keeps nothing about a shopper except
717
+ the cache. In cohort mode an entry holds no shopper id and it's shared by all
718
+ the shoppers in the cohort. There's usually no single shopper's entry to delete.
719
+ But there's an exception if a cohort entry has a segment or candidate list
720
+ picked or ordered for one shopper. Like all per-shopper entries, it's about that
721
+ shopper. Nothing maps a shopper to their entries. That's why you need to keep
722
+ `ttlMs` short or pass `createNullSpecCache()`. `onEvent` sends no shopper id.
723
+ But in per-shopper mode its `key` is derived from the shopper's history.
724
+ `violations` can also name SKUs from a shopper's basket or purchases. Treat logs
725
+ of `onEvent` as personal data.
726
+
727
+ **Caching pages.** In its HTML, a personalised page will say things like
728
+ "Goes with your cart" and "You looked at this recently". Serve those pages with
729
+ `Cache-Control: private` or `no-store`, to be sure a shared cache never hands
730
+ one shopper's page to another.
731
+
732
+ **Telling shoppers a model wrote the copy.** In the wrapper, `data-rudra-source`
733
+ says `llm` or `cache` if a model wrote the copy but `fallback` if it didn't.
734
+ This makes it a machine-readable marker you can build on, for example to show a
735
+ note. Whether you must label AI-written copy and how you do it will depend on
687
736
  where you sell. In the EU, Article 50 of the AI Act is the rule to ask about.
688
737
 
689
- **Claims.** The copy on your page is your own advertising, whoever wrote it. The
738
+ **Claims.** All the copy on your page is your advertising, whoever wrote it. The
690
739
  claim check catches prices, discounts, stock, ratings, delivery, urgency and
691
- generic environmental claims. But it's a list, and rewordings get through.
692
- SECURITY.md explains why, and the tests list the known ones. Anything it misses
693
- is still yours to stand behind.
740
+ generic environmental claims. But it's just a list and rewordings get through.
741
+ You can read why in SECURITY.md and see the known ones in the tests. Any claim
742
+ it misses is still yours to stand behind.
694
743
 
695
744
  **Children.** In the UK, the ICO's Children's Code covers any shop that
696
- under-18s are more likely than not to use, not only one aimed at them. Its
697
- standard 12 asks for profiling to be off by default unless you can show a
745
+ under-18s are more likely than not to use, not only a shop aimed at under-18s.
746
+ Its standard 12 asks for profiling to be off by default unless you can show a
698
747
  compelling reason, judged by the child's best interests. It also asks for
699
748
  safeguards when profiling is on. For a shop like that, don't use per-shopper
700
- mode. For a shopper under 18, leave `signals` and `user.segment` out of their
701
- payload unless they've switched personalisation on, as for a shopper who objects
702
- to profiling. If you can't tell a shopper's age with confidence that fits the
703
- risk, treat every shopper as under 18. Cohort mode alone doesn't turn profiling
704
- off. The default `rank: 'signals'` still orders products by the shopper's
705
- signals in cohort mode and in the fallback, even with no provider. And cohort
706
- mode still sends their strongest category, whether they have any history, and
707
- any segment to the model.
749
+ mode. For a shopper under 18, be sure to leave `signals` and `user.segment` out
750
+ of their payload unless they've switched personalisation on, as for a shopper
751
+ who objects to profiling. If you can't tell a shopper's age with confidence that
752
+ fits the risk, treat all shoppers as under 18. Just using cohort mode doesn't
753
+ turn profiling off. By default `rank: 'signals'` will still order products by
754
+ the shopper's signals in cohort mode and in the fallback, even with no provider.
755
+ Cohort mode will also still send their strongest category, whether they have any
756
+ history and any segment to the model.
708
757
 
709
758
  **Marketplaces.** If other sellers list products on your site, EU platform rules
710
759
  (Article 27 of the Digital Services Act) ask you to set out in your terms:
@@ -717,26 +766,27 @@ This doesn't apply if you're a micro or small business. If shoppers can pick
717
766
  between options, such as switching personalisation off, the control has to sit
718
767
  where the products are shown.
719
768
 
720
- Which parameters apply depends on your mode and your `rank` setting:
769
+ Which parameters apply will depend on your mode and your `rank` setting:
721
770
 
722
- - `rank` sets the order in cohort mode and in the fallback. With `rank: 'given'`
723
- that's the order you sent, so describe your own ranking.
771
+ - In cohort mode and in the fallback, `rank` sets the order. With
772
+ `rank: 'given'` that's the order you sent. This means you will have to
773
+ describe your own ranking.
724
774
  - With `rank: 'signals'` the order comes from the shopper's category interest
725
775
  (the category they're browsing counts too), how often they've viewed a
726
- product, its rating, and tags it shares with products they've engaged with.
727
- Category weighs most.
776
+ product, its rating and any tags it shares with products they've engaged with.
777
+ Of these, category weighs most.
728
778
  - In per-shopper mode the model picks which candidates to show and in what
729
779
  order, from what's under [What the model sees](#what-the-model-sees).
730
- - In cohort mode the model picks the hero's product, from the cohort list in
731
- that section.
732
- - In every mode, anything out of stock, disliked or being looked at right now is
733
- left out. So is anything bought or in the basket, except as part of a bundle.
734
- - A bundle is picked by what's in the basket, then what they viewed, then the
735
- category being browsed.
736
-
737
- **Accessibility.** Every card is one link with a readable name, and headings
738
- only render when they have text. Contrast, focus styles and layout come from
739
- your stylesheet, so those are yours to check.
780
+ - In cohort mode the model picks the hero's product from the cohort list there.
781
+ - In all modes, anything out of stock, disliked or being looked at right now
782
+ will be left out. This is also true of anything bought or in the basket,
783
+ except as part of a bundle.
784
+ - A bundle will be picked by what's in the basket, then what they viewed, then
785
+ the category being browsed.
786
+
787
+ **Accessibility.** Each of the cards is a single link with a readable name.
788
+ Headings will only render if they have text. You will have to check contrast,
789
+ focus styles and layout yourself, because these come from your stylesheet.
740
790
 
741
791
  ## Licence
742
792