AgPerry commited on
Commit
d939dd0
·
verified ·
1 Parent(s): 3c88293

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/amazon/solution/site/README.md +3 -0
  2. tasks/amazon/solution/site/implementation/clone/auth_views.py +364 -0
  3. tasks/amazon/solution/site/implementation/clone/browse_breadth.py +405 -0
  4. tasks/amazon/solution/site/implementation/clone/deals_catalog.py +656 -0
  5. tasks/amazon/solution/site/implementation/clone/external_verification.py +71 -0
  6. tasks/amazon/solution/site/implementation/clone/harbor_entry.py +174 -0
  7. tasks/amazon/solution/site/implementation/clone/home_category_catalog.py +169 -0
  8. tasks/amazon/solution/site/implementation/clone/mail_transport.py +356 -0
  9. tasks/amazon/solution/site/implementation/clone/payment_methods.py +104 -0
  10. tasks/amazon/solution/site/implementation/clone/product_options.py +704 -0
  11. tasks/amazon/solution/site/implementation/clone/render.py +0 -0
  12. tasks/amazon/solution/site/implementation/clone/review_catalog.py +524 -0
  13. tasks/amazon/solution/site/implementation/clone/review_store.py +746 -0
  14. tasks/amazon/solution/site/implementation/clone/schema.sql +680 -0
  15. tasks/amazon/solution/site/implementation/clone/search_commerce.py +319 -0
  16. tasks/amazon/solution/site/implementation/clone/search_suggestions.py +220 -0
  17. tasks/amazon/solution/site/implementation/clone/server.py +0 -0
  18. tasks/amazon/solution/site/implementation/clone/specialty_views.py +313 -0
  19. tasks/amazon/solution/site/implementation/clone/store.py +0 -0
  20. tasks/amazon/solution/site/implementation/clone/wishlist_store.py +698 -0
  21. tasks/amazon/solution/site/implementation/clone/wishlist_views.py +496 -0
  22. tasks/amazon/solution/site/implementation/compile.sh +50 -0
  23. tasks/amazon/solution/site/implementation/run.sh +11 -0
  24. tasks/amazon/solution/site/implementation/vendor.requirements.in +17 -0
  25. tasks/amazon/solution/site/implementation/vendor.requirements.lock +341 -0
  26. tasks/amazon/tests/fixtures/cicd/amazon-business-laws.json +163 -0
  27. tasks/amazon/tests/fixtures/cicd/obligations.json +173 -0
  28. tasks/amazon/tests/fixtures/cicd/run-amazon-business.sh +4 -0
  29. tasks/amazon/tests/fixtures/cicd/run-check.sh +11 -0
  30. tasks/amazon/tests/fixtures/site/README.md +3 -0
  31. tasks/amazon/tests/oracle-runtime/clone/fixtures/source-snapshots/2026-07-31/pdp-unified--1365x900.png +3 -0
  32. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-bold.woff2 +0 -0
  33. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-italic.woff2 +0 -0
  34. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-medium.woff2 +0 -0
  35. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-regular.woff2 +0 -0
  36. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite-retail-1x.png +3 -0
  37. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite-retail-2x.png +3 -0
  38. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite.png +3 -0
  39. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/007d6dcf1fdb975a.jpg +3 -0
  40. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/014f2bdb67865e0e.jpg +3 -0
  41. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0570588e61329a69.jpg +3 -0
  42. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/067d7ad08025ea90.jpg +3 -0
  43. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0ad083d2d44c138c.jpg +3 -0
  44. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0b93049189c1d89f.jpg +3 -0
  45. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/1044f0abd1b0a9a4.jpg +3 -0
  46. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/10f449c8f68d4ff3.jpg +3 -0
  47. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/118dad6228a13f3b.jpg +3 -0
  48. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/12237c942f7639ab.jpg +3 -0
  49. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/13b4e86ff2941173.jpg +3 -0
  50. tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/13e358fe611b2960.jpg +3 -0
tasks/amazon/solution/site/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Private oracle implementation
2
+
3
+ The implementation is a deterministic projection of the current material clone and is copied only into the privileged oracle solution.
tasks/amazon/solution/site/implementation/clone/auth_views.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from html import escape
4
+ from typing import Mapping, Sequence
5
+ from urllib.parse import unquote, urlencode, urlsplit
6
+
7
+
8
+ AUTH_STYLESHEET = "/static/auth.css?v=20260806-06"
9
+
10
+
11
+ def _first(query: Mapping[str, Sequence[str]], name: str) -> str:
12
+ values = query.get(name, ())
13
+ return values[0] if values else ""
14
+
15
+
16
+ def safe_return_target(query: Mapping[str, Sequence[str]]) -> str | None:
17
+ """Return a same-origin path, never an absolute or scheme-relative URL."""
18
+ candidate = _first(query, "openid.return_to").strip()
19
+ if not candidate or any(ord(character) < 32 for character in candidate):
20
+ return None
21
+ parsed = urlsplit(candidate)
22
+ if parsed.scheme or parsed.netloc:
23
+ return None
24
+ if not parsed.path.startswith("/") or parsed.path.startswith("//") or "\\" in parsed.path:
25
+ return None
26
+ decoded_path = parsed.path
27
+ for _ in range(2):
28
+ decoded_path = unquote(decoded_path)
29
+ if (
30
+ decoded_path.startswith("//")
31
+ or "\\" in decoded_path
32
+ or any(ord(character) < 32 for character in decoded_path)
33
+ ):
34
+ return None
35
+ return candidate
36
+
37
+
38
+ def _logo() -> str:
39
+ return '<a class="auth-logo" href="/" aria-label="Amazon"></a>'
40
+
41
+
42
+ def _hidden_return_target(query: Mapping[str, Sequence[str]]) -> str:
43
+ target = safe_return_target(query)
44
+ if target is None:
45
+ return ""
46
+ return (
47
+ '<input type="hidden" name="openid.return_to" value="'
48
+ f'{escape(target, quote=True)}">'
49
+ )
50
+
51
+
52
+ def _return_target_suffix(query: Mapping[str, Sequence[str]]) -> str:
53
+ target = safe_return_target(query)
54
+ return "?" + urlencode({"openid.return_to": target}) if target else ""
55
+
56
+
57
+ def _error_notice(message: str | None) -> str:
58
+ if not message:
59
+ return ""
60
+ return f'<div class="auth-error" role="alert">{escape(message)}</div>'
61
+
62
+
63
+ def _document(
64
+ title: str,
65
+ content: str,
66
+ *,
67
+ body_class: str,
68
+ scripts: Sequence[str] = (),
69
+ ) -> str:
70
+ script_markup = "".join(
71
+ f'<script src="{escape(source, quote=True)}" defer></script>'
72
+ for source in scripts
73
+ )
74
+ return f"""<!doctype html>
75
+ <html lang="en-us">
76
+ <head>
77
+ <meta charset="utf-8">
78
+ <meta name="viewport" content="width=device-width, initial-scale=1">
79
+ <title>{escape(title)}</title>
80
+ <link rel="stylesheet" href="{AUTH_STYLESHEET}">
81
+ {script_markup}
82
+ </head>
83
+ <body class="auth-page {escape(body_class, quote=True)}">
84
+ <header class="auth-header">{_logo()}</header>
85
+ <main class="auth-main">
86
+ {content}
87
+ </main>
88
+ <footer class="auth-footer">
89
+ <nav aria-label="Amazon account policies">
90
+ <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a>
91
+ <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>
92
+ <a href="/gp/help/customer/display.html?nodeId=508510">Help</a>
93
+ </nav>
94
+ <p>© 1996–2026, Amazon.com, Inc. or its affiliates</p>
95
+ </footer>
96
+ </body>
97
+ </html>"""
98
+
99
+
100
+ def signin_page(query: Mapping[str, Sequence[str]], error: str | None = None) -> str:
101
+ if _first(query, "stage").lower() == "password":
102
+ content = f"""
103
+ <section class="auth-card" aria-labelledby="auth-heading">
104
+ <h1 id="auth-heading">Sign in</h1>
105
+ <p class="auth-identity">Amazon account</p>
106
+ {_error_notice(error)}
107
+ <form method="post" action="/ap/signin">
108
+ {_hidden_return_target(query)}
109
+ <label for="ap-password">Password</label>
110
+ <a class="auth-inline-link" href="/ap/forgotpassword">Forgot password?</a>
111
+ <input id="ap-password" name="password" type="password" autocomplete="current-password" required autofocus>
112
+ <button class="auth-primary" type="submit">Sign in</button>
113
+ </form>
114
+ <label class="auth-checkbox"><input name="rememberMe" type="checkbox"> Keep me signed in</label>
115
+ <details class="auth-details"><summary>Details</summary><p>Use this option only on your personal device.</p></details>
116
+ </section>
117
+ """
118
+ return _document("Amazon Sign-In", content, body_class="auth-signin auth-password-stage")
119
+
120
+ content = f"""
121
+ <section class="auth-card" aria-labelledby="auth-heading">
122
+ <h1 id="auth-heading">Sign in or create account</h1>
123
+ {_error_notice(error)}
124
+ <form method="post" action="/ap/signin">
125
+ {_hidden_return_target(query)}
126
+ <label for="ap-email">Enter mobile number or email</label>
127
+ <input id="ap-email" name="email" type="text" autocomplete="username" inputmode="email" required autofocus>
128
+ <button class="auth-primary" type="submit">Continue</button>
129
+ </form>
130
+ <p class="auth-legal">By continuing, you agree to Amazon's <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a> and <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>.</p>
131
+ <details class="auth-details"><summary>Need help?</summary><a href="/ap/forgotpassword">Forgot your password?</a><a href="/ap/register{escape(_return_target_suffix(query), quote=True)}">Create your Amazon account</a></details>
132
+ <div class="auth-business"><strong>Buying for work?</strong> <a href="/gp/navigation/amazon-business">Create a free business account</a></div>
133
+ </section>
134
+ """
135
+ return _document("Amazon Sign-In", content, body_class="auth-signin auth-identifier-stage")
136
+
137
+
138
+ def register_page(
139
+ query: Mapping[str, Sequence[str]],
140
+ error: str | None = None,
141
+ *,
142
+ external_verification: bool = False,
143
+ ) -> str:
144
+ suggested_email = _first(query, "email").strip()
145
+ verification_controls = ""
146
+ form_attributes = ""
147
+ submit_attributes = ""
148
+ scripts: tuple[str, ...] = ()
149
+ if external_verification:
150
+ form_attributes = ' data-external-registration="true"'
151
+ submit_attributes = ' disabled data-auth-create-account'
152
+ scripts = ("/static/auth-verification.js",)
153
+ verification_controls = """
154
+ <button class="auth-secondary auth-send-code" type="button" data-auth-send-code>Send Verification Code</button>
155
+ <section class="auth-code-panel" data-auth-code-panel hidden aria-labelledby="auth-code-heading">
156
+ <h2 id="auth-code-heading">Verify email address</h2>
157
+ <label for="ap-register-code">Verification code</label>
158
+ <input id="ap-register-code" type="text"
159
+ autocomplete="one-time-code" inputmode="numeric"
160
+ pattern="[0-9]{6}" maxlength="6" data-auth-code>
161
+ <button class="auth-secondary" type="button" data-auth-verify-code>Verify code</button>
162
+ </section>
163
+ <p class="auth-api-status" data-auth-verification-status role="status" aria-live="polite"></p>
164
+ """
165
+ content = f"""
166
+ <section class="auth-card" aria-labelledby="auth-heading">
167
+ <h1 id="auth-heading">Create account</h1>
168
+ {_error_notice(error)}
169
+ <form method="post" action="/ap/register"{form_attributes}>
170
+ {_hidden_return_target(query)}
171
+ <label for="ap-customer-name">Your name</label>
172
+ <input id="ap-customer-name" name="customerName" type="text" autocomplete="name" placeholder="First and last name" required autofocus>
173
+ <label for="ap-register-email">Mobile number or email</label>
174
+ <input id="ap-register-email" name="email" type="email" autocomplete="email" inputmode="email" value="{escape(suggested_email, quote=True)}" required data-auth-email>
175
+ {verification_controls}
176
+ <label for="ap-register-password">Password</label>
177
+ <input id="ap-register-password" name="password" type="password" autocomplete="new-password" minlength="6" placeholder="At least 6 characters" required aria-describedby="password-hint" data-auth-password>
178
+ <p id="password-hint" class="auth-hint"><span aria-hidden="true">i</span> Passwords must be at least 6 characters.</p>
179
+ <label for="ap-password-check">Re-enter password</label>
180
+ <input id="ap-password-check" name="passwordCheck" type="password" autocomplete="new-password" minlength="6" required data-auth-password-check>
181
+ <button class="auth-primary" type="submit"{submit_attributes}>Continue</button>
182
+ </form>
183
+ <p class="auth-legal">By creating an account, you agree to Amazon's <a href="/gp/help/customer/display.html?nodeId=508088">Conditions of Use</a> and <a href="/gp/help/customer/display.html?nodeId=468496">Privacy Notice</a>.</p>
184
+ <hr>
185
+ <p class="auth-existing">Already have an account? <a href="/ap/signin{escape(_return_target_suffix(query), quote=True)}">Sign in <span aria-hidden="true">›</span></a></p>
186
+ </section>
187
+ """
188
+ return _document(
189
+ "Amazon Registration",
190
+ content,
191
+ body_class="auth-register",
192
+ scripts=scripts,
193
+ )
194
+
195
+
196
+ def forgot_password_page(
197
+ query: Mapping[str, Sequence[str]], error: str | None = None
198
+ ) -> str:
199
+ if _first(query, "stage").lower() == "reset-password":
200
+ content = f"""
201
+ <section class="auth-card" aria-labelledby="auth-heading">
202
+ <h1 id="auth-heading">Create new password</h1>
203
+ <p>We'll ask for this password whenever you sign in.</p>
204
+ {_error_notice(error)}
205
+ <form method="post" action="/ap/forgotpassword">
206
+ <label for="ap-new-password">New password</label>
207
+ <input id="ap-new-password" name="password" type="password" autocomplete="new-password" minlength="6" required autofocus>
208
+ <label for="ap-new-password-check">Re-enter password</label>
209
+ <input id="ap-new-password-check" name="passwordCheck" type="password" autocomplete="new-password" minlength="6" required>
210
+ <button class="auth-primary" type="submit">Save changes and sign in</button>
211
+ </form>
212
+ </section>
213
+ """
214
+ return _document("Create New Password", content, body_class="auth-forgot auth-reset-stage")
215
+
216
+ content = f"""
217
+ <section class="auth-card" aria-labelledby="auth-heading">
218
+ <h1 id="auth-heading">Password assistance</h1>
219
+ <p>Enter the email address or mobile phone number associated with your Amazon account.</p>
220
+ {_error_notice(error)}
221
+ <form method="post" action="/ap/forgotpassword">
222
+ {_hidden_return_target(query)}
223
+ <label for="ap-forgot-email">Email or mobile phone number</label>
224
+ <input id="ap-forgot-email" name="email" type="text" autocomplete="username" inputmode="email" required autofocus>
225
+ <button class="auth-primary" type="submit">Continue</button>
226
+ </form>
227
+ </section>
228
+ <section class="auth-support-copy">
229
+ <h2>Has your email or mobile number changed?</h2>
230
+ <p>If you no longer use the email address associated with your Amazon account, you may contact Customer Service for help restoring access to your account.</p>
231
+ </section>
232
+ """
233
+ return _document("Amazon Password Assistance", content, body_class="auth-forgot auth-email-stage")
234
+
235
+
236
+ def _mail_delivery_status_markup(
237
+ purpose: str,
238
+ mail_delivery: Mapping[str, object] | None,
239
+ mail_delivery_mode: str,
240
+ local_inbox_url: str | None = None,
241
+ ) -> str:
242
+ status = str((mail_delivery or {}).get("status") or "")
243
+ if status not in {
244
+ "QUEUED",
245
+ "LOCAL_ONLY",
246
+ "SMTP_PENDING",
247
+ "SMTP_SENT",
248
+ "SMTP_FAILED",
249
+ }:
250
+ status = "SMTP_PENDING" if mail_delivery_mode == "SMTP" else "LOCAL_ONLY"
251
+
252
+ descriptions = {
253
+ "QUEUED": (
254
+ "If an account matches that address, its verification message is "
255
+ "being handled. Refreshing does not reveal whether an account exists."
256
+ ),
257
+ "LOCAL_ONLY": (
258
+ "This message is stored only in the protected local outbox; "
259
+ "no external email was sent."
260
+ ),
261
+ "SMTP_PENDING": (
262
+ "The configured SMTP service is processing this message. "
263
+ "Refresh to check the latest delivery result."
264
+ ),
265
+ "SMTP_SENT": "The configured SMTP service accepted this message.",
266
+ "SMTP_FAILED": (
267
+ "The SMTP attempt failed. No address or provider error is exposed here."
268
+ ),
269
+ }
270
+ action_suffix = "?" + urlencode({"purpose": purpose})
271
+ actions: list[str] = []
272
+ if status in {"QUEUED", "SMTP_PENDING"}:
273
+ actions.append(
274
+ f'<a class="auth-status-link" href="/ap/cvf/verify{escape(action_suffix, quote=True)}">Refresh delivery status</a>'
275
+ )
276
+ if status == "SMTP_FAILED" and bool((mail_delivery or {}).get("can_retry")):
277
+ actions.append(
278
+ '<form class="auth-retry-form" method="post" '
279
+ f'action="/ap/cvf/verify{escape(action_suffix, quote=True)}">'
280
+ '<button class="auth-link-button" type="submit" name="action" '
281
+ 'value="retry-delivery">Retry email delivery</button></form>'
282
+ )
283
+ if local_inbox_url and status in {"SMTP_PENDING", "SMTP_SENT", "SMTP_FAILED"}:
284
+ actions.append(
285
+ f'<a class="auth-status-link" href="{escape(local_inbox_url, quote=True)}">'
286
+ "Open local SMTP inbox</a>"
287
+ )
288
+ action_markup = (
289
+ f'<div class="auth-delivery-actions">{"".join(actions)}</div>'
290
+ if actions
291
+ else ""
292
+ )
293
+ return (
294
+ f'<section class="auth-delivery-status auth-delivery-{status.casefold()}" '
295
+ 'aria-live="polite"><h2>Email delivery</h2>'
296
+ f'<p><strong>{status}</strong><span>{escape(descriptions[status])}</span></p>'
297
+ f'{action_markup}</section>'
298
+ )
299
+
300
+
301
+ def verification_page(
302
+ query: Mapping[str, Sequence[str]],
303
+ *,
304
+ masked_destination: str | None = None,
305
+ error: str | None = None,
306
+ mail_delivery_mode: str = "LOCAL_ONLY",
307
+ mail_delivery: Mapping[str, object] | None = None,
308
+ local_inbox_url: str | None = None,
309
+ ) -> str:
310
+ purpose = _first(query, "purpose").lower()
311
+ if purpose == "registration" and masked_destination:
312
+ lead = (
313
+ f"A verification code was queued for {masked_destination}. "
314
+ "Enter it below when it arrives."
315
+ )
316
+ elif purpose == "registration":
317
+ lead = "Start account creation again to request a new email verification code."
318
+ elif purpose == "password-reset":
319
+ lead = (
320
+ "If an account matches that address, a verification code was queued. "
321
+ "Enter it below if it arrives."
322
+ )
323
+ else:
324
+ lead = "Enter the one-time password that was queued for you."
325
+ action_suffix = (
326
+ "?" + urlencode({"purpose": purpose})
327
+ if purpose in {"registration", "password-reset"}
328
+ else ""
329
+ )
330
+ delivery_status = _mail_delivery_status_markup(
331
+ purpose,
332
+ mail_delivery,
333
+ mail_delivery_mode,
334
+ local_inbox_url,
335
+ )
336
+ content = f"""
337
+ <section class="auth-card" aria-labelledby="auth-heading">
338
+ <h1 id="auth-heading">Verify email address</h1>
339
+ <p>{escape(lead)}</p>
340
+ {_error_notice(error)}
341
+ <form method="post" action="/ap/cvf/verify{escape(action_suffix, quote=True)}">
342
+ <label for="ap-code">Enter verification code</label>
343
+ <input id="ap-code" name="code" type="text" autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]{{6}}" maxlength="6" required autofocus>
344
+ <button class="auth-primary" type="submit">Verify</button>
345
+ </form>
346
+ <form class="auth-resend-form" method="post" action="/ap/cvf/verify{escape(action_suffix, quote=True)}">
347
+ <button class="auth-link-button" type="submit" name="action" value="resend">Resend code</button>
348
+ </form>
349
+ {delivery_status}
350
+ </section>
351
+ """
352
+ return _document("Amazon Verification", content, body_class="auth-verification")
353
+
354
+
355
+ def page_for(path: str, query: Mapping[str, Sequence[str]]) -> str:
356
+ if path == "/ap/signin":
357
+ return signin_page(query)
358
+ if path == "/ap/register":
359
+ return register_page(query)
360
+ if path == "/ap/forgotpassword":
361
+ return forgot_password_page(query)
362
+ if path == "/ap/cvf/verify":
363
+ return verification_page(query)
364
+ raise ValueError(f"unsupported auth path: {path}")
tasks/amazon/solution/site/implementation/clone/browse_breadth.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Iterable, Mapping, Sequence
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from home_catalog import load_home_product_catalog
9
+ from search_catalog import search_home_catalog
10
+ from search_commerce import load_search_commerce_cards
11
+
12
+
13
+ EXPECTED_HOME_RAILS: tuple[tuple[str, str, int], ...] = (
14
+ ("related-items", "Related to items you've viewed", 25),
15
+ ("best-sellers-home-kitchen", "Best Sellers in Home & Kitchen", 19),
16
+ ("top-sellers-toys", "Top Sellers in Toys for you", 26),
17
+ (
18
+ "best-sellers-computers-accessories",
19
+ "Best Sellers in Computers & Accessories",
20
+ 17,
21
+ ),
22
+ ("best-sellers-books", "Best Sellers in Books", 26),
23
+ ("top-picks-singapore", "Top picks for Singapore", 28),
24
+ (
25
+ "best-sellers-beauty-personal-care",
26
+ "Best Sellers in Beauty & Personal Care",
27
+ 16,
28
+ ),
29
+ )
30
+
31
+ HOME_BROWSE_FIELDS = frozenset(
32
+ {
33
+ "asin",
34
+ "title",
35
+ "image_path",
36
+ "canonical_path",
37
+ "title_status",
38
+ "evidence_tier",
39
+ "evidence_class",
40
+ "placements",
41
+ }
42
+ )
43
+
44
+ OFFER_DISPLAY_FIELDS = frozenset(
45
+ {
46
+ "asin",
47
+ "slug",
48
+ "canonical_path",
49
+ "title",
50
+ "brand",
51
+ "capacity",
52
+ "color",
53
+ "price_minor",
54
+ "list_price_minor",
55
+ "currency",
56
+ "rating",
57
+ "reviews",
58
+ "image_path",
59
+ "badge",
60
+ "evidence_class",
61
+ "source",
62
+ }
63
+ )
64
+
65
+ DEPARTMENT_SLUGS_FIELD = "department_slugs"
66
+ INSTANT_POT_ASIN = "B00FLYWNYQ"
67
+ EXTERNAL_SSD_RANKING_ID = "external-ssd"
68
+ EXTERNAL_SSD_RANKING_TITLE = "Best Sellers in External Solid State Drives"
69
+ DEAL_MEMBERSHIP_FIELDS = frozenset(
70
+ {
71
+ "captured_discount_percent",
72
+ "deal_label",
73
+ "deals_evidence_key",
74
+ "discount_percent",
75
+ "limited_time_deal",
76
+ "themes",
77
+ }
78
+ )
79
+
80
+
81
+ class BrowseBreadthError(ValueError):
82
+ pass
83
+
84
+
85
+ def _read_object(path: Path) -> dict[str, Any]:
86
+ try:
87
+ value = json.loads(path.read_text(encoding="utf-8"))
88
+ except (OSError, json.JSONDecodeError) as exc:
89
+ raise BrowseBreadthError(f"invalid breadth fixture {path.name}: {exc}") from exc
90
+ if not isinstance(value, dict):
91
+ raise BrowseBreadthError(f"breadth fixture {path.name} must be an object")
92
+ return value
93
+
94
+
95
+ def _home_browse_product(product: Mapping[str, Any]) -> dict[str, Any]:
96
+ """Return the sparse, source-backed fields safe for browse-only cards."""
97
+
98
+ projected = {
99
+ field: product[field]
100
+ for field in HOME_BROWSE_FIELDS
101
+ if field in product
102
+ }
103
+ placements = projected.get("placements")
104
+ if isinstance(placements, list):
105
+ projected["placements"] = [dict(placement) for placement in placements]
106
+ return projected
107
+
108
+
109
+ def build_home_rail_sections(
110
+ catalog: Mapping[str, Mapping[str, Any]],
111
+ ) -> tuple[dict[str, Any], ...]:
112
+ """Group the 157 homepage products by their seven original source rails."""
113
+
114
+ expected = {key: (title, count) for key, title, count in EXPECTED_HOME_RAILS}
115
+ grouped: dict[str, list[tuple[int, dict[str, Any]]]] = {
116
+ key: [] for key, _, _ in EXPECTED_HOME_RAILS
117
+ }
118
+ seen_asins: set[str] = set()
119
+
120
+ for product in catalog.values():
121
+ asin = product.get("asin")
122
+ placements = product.get("placements")
123
+ if not isinstance(asin, str) or not isinstance(placements, list):
124
+ raise BrowseBreadthError("home products require an ASIN and placements")
125
+ if asin in seen_asins:
126
+ raise BrowseBreadthError(f"duplicate home product {asin}")
127
+ if len(placements) != 1 or not isinstance(placements[0], Mapping):
128
+ raise BrowseBreadthError(
129
+ f"home product {asin} must have exactly one original rail placement"
130
+ )
131
+ placement = placements[0]
132
+ key = placement.get("railKey")
133
+ title = placement.get("railTitle")
134
+ ordinal = placement.get("ordinal")
135
+ if key not in grouped or not isinstance(ordinal, int):
136
+ raise BrowseBreadthError(f"home product {asin} has an unknown placement")
137
+ if title != expected[key][0]:
138
+ raise BrowseBreadthError(f"home rail {key} has an unexpected title")
139
+ seen_asins.add(asin)
140
+ grouped[key].append((ordinal, _home_browse_product(product)))
141
+
142
+ sections: list[dict[str, Any]] = []
143
+ for key, title, expected_count in EXPECTED_HOME_RAILS:
144
+ products = tuple(product for _, product in sorted(grouped[key], key=lambda row: row[0]))
145
+ if len(products) != expected_count:
146
+ raise BrowseBreadthError(
147
+ f"home rail {key} expected {expected_count} products, found {len(products)}"
148
+ )
149
+ sections.append(
150
+ {
151
+ "key": key,
152
+ "title": title,
153
+ "count": len(products),
154
+ "products": products,
155
+ }
156
+ )
157
+
158
+ if len(seen_asins) != 157:
159
+ raise BrowseBreadthError(
160
+ f"home browse breadth expected 157 unique ASINs, found {len(seen_asins)}"
161
+ )
162
+ return tuple(sections)
163
+
164
+
165
+ def _asins(products_or_asins: Iterable[Mapping[str, Any] | str]) -> set[str]:
166
+ values: set[str] = set()
167
+ for product in products_or_asins:
168
+ asin = product if isinstance(product, str) else product.get("asin")
169
+ if not isinstance(asin, str) or not asin:
170
+ raise BrowseBreadthError("offer exclusions require valid ASINs")
171
+ values.add(asin)
172
+ return values
173
+
174
+
175
+ def build_portable_ssd_supplement(
176
+ catalog: Mapping[str, Mapping[str, Any]],
177
+ frozen_products_or_asins: Iterable[Mapping[str, Any] | str],
178
+ ) -> tuple[dict[str, Any], ...]:
179
+ """Return browse-only homepage matches not already in the frozen nine."""
180
+
181
+ frozen_asins = _asins(frozen_products_or_asins)
182
+ supplement = tuple(
183
+ _home_browse_product(product)
184
+ for product in search_home_catalog("portable ssd", catalog)
185
+ if product.get("asin") not in frozen_asins
186
+ )
187
+ supplement_asins = [product.get("asin") for product in supplement]
188
+ if len(supplement_asins) != len(set(supplement_asins)):
189
+ raise BrowseBreadthError("portable SSD supplement contains duplicate ASINs")
190
+ return supplement
191
+
192
+
193
+ def _offer_display_product(product: Mapping[str, Any], source: str) -> dict[str, Any]:
194
+ asin = product.get("asin")
195
+ price_minor = product.get("price_minor")
196
+ currency = product.get("currency")
197
+ if not isinstance(asin, str) or not asin:
198
+ raise BrowseBreadthError("verified offers require an ASIN")
199
+ if isinstance(price_minor, bool) or not isinstance(price_minor, int) or price_minor < 0:
200
+ raise BrowseBreadthError(f"verified offer {asin} has an invalid price")
201
+ if currency != "USD":
202
+ raise BrowseBreadthError(f"verified offer {asin} is outside the USD baseline")
203
+
204
+ normalized = dict(product)
205
+ canonical_path = normalized.get("canonical_path") or normalized.get("canonicalPath")
206
+ if canonical_path is None:
207
+ slug = normalized.get("slug")
208
+ canonical_path = f"/{slug}/dp/{asin}" if isinstance(slug, str) and slug else f"/dp/{asin}"
209
+ normalized["canonical_path"] = canonical_path
210
+ normalized["source"] = source
211
+ return {
212
+ field: normalized[field]
213
+ for field in OFFER_DISPLAY_FIELDS
214
+ if field in normalized
215
+ }
216
+
217
+
218
+ def combine_verified_offer_display(
219
+ frozen_products: Sequence[Mapping[str, Any]],
220
+ direct_products: Sequence[Mapping[str, Any]],
221
+ ) -> tuple[dict[str, Any], ...]:
222
+ """Combine verified offers while letting newer direct evidence win by ASIN.
223
+
224
+ The function never derives or adjusts a price. It only projects values from
225
+ the two evidence inputs, preserving frozen order and appending new direct
226
+ offers in their source order.
227
+ """
228
+
229
+ offers: dict[str, dict[str, Any]] = {}
230
+ for product in frozen_products:
231
+ projected = _offer_display_product(product, "task-fixture")
232
+ asin = str(projected["asin"])
233
+ if asin in offers:
234
+ raise BrowseBreadthError(f"duplicate frozen offer {asin}")
235
+ offers[asin] = projected
236
+ for product in direct_products:
237
+ projected = _offer_display_product(product, "direct-pdp")
238
+ offers[str(projected["asin"])] = projected
239
+ return tuple(offers.values())
240
+
241
+
242
+ def build_department_commerce_supplements(
243
+ catalog: Mapping[str, Mapping[str, Any]],
244
+ frozen_fixture: Mapping[str, Any],
245
+ direct_fixture: Mapping[str, Any],
246
+ verified_offers: Sequence[Mapping[str, Any]],
247
+ ) -> tuple[dict[str, Any], ...]:
248
+ """Expose already-verified offers under their directly evidenced taxonomy.
249
+
250
+ This is deliberately a search/category view rather than a catalog merge:
251
+ the 157 captured homepage cards retain their original rail membership, and
252
+ Deals continues to use its own explicit membership fixture. Existing rich
253
+ direct-PDP records win over sparse homepage duplicates; otherwise the exact
254
+ projected verified offer is used without deriving any commerce fact.
255
+ """
256
+
257
+ ranking = frozen_fixture.get("ranking")
258
+ frozen_products = frozen_fixture.get("products")
259
+ direct_products = direct_fixture.get("products")
260
+ if (
261
+ frozen_fixture.get("schema") != "amazon-clone.fixture.v1"
262
+ or not isinstance(ranking, Mapping)
263
+ or ranking.get("list_id") != EXTERNAL_SSD_RANKING_ID
264
+ or ranking.get("title") != EXTERNAL_SSD_RANKING_TITLE
265
+ or not isinstance(frozen_products, list)
266
+ or len(frozen_products) != 9
267
+ ):
268
+ raise BrowseBreadthError("external SSD taxonomy evidence is invalid")
269
+ if (
270
+ direct_fixture.get("schema") != "amazon-clone.home-pdp-evidence.v1"
271
+ or not isinstance(direct_products, list)
272
+ ):
273
+ raise BrowseBreadthError("direct PDP taxonomy evidence is invalid")
274
+
275
+ direct_by_asin = {
276
+ str(product.get("asin") or ""): product
277
+ for product in direct_products
278
+ if isinstance(product, Mapping)
279
+ }
280
+ instant_pot = direct_by_asin.get(INSTANT_POT_ASIN)
281
+ instant_detail = instant_pot.get("pdp") if isinstance(instant_pot, Mapping) else None
282
+ breadcrumb = (
283
+ instant_detail.get("breadcrumb")
284
+ if isinstance(instant_detail, Mapping)
285
+ else None
286
+ )
287
+ if (
288
+ not isinstance(instant_detail, Mapping)
289
+ or instant_detail.get("page_category") != "Home & Kitchen"
290
+ or not isinstance(breadcrumb, list)
291
+ or not breadcrumb
292
+ or breadcrumb[0] != "Home & Kitchen"
293
+ ):
294
+ raise BrowseBreadthError("Instant Pot lacks direct Home & Kitchen taxonomy")
295
+
296
+ offer_by_asin: dict[str, Mapping[str, Any]] = {}
297
+ for offer in verified_offers:
298
+ asin = offer.get("asin")
299
+ if not isinstance(asin, str) or not asin or asin in offer_by_asin:
300
+ raise BrowseBreadthError("department commerce offers require unique ASINs")
301
+ offer_by_asin[asin] = offer
302
+
303
+ frozen_asins: list[str] = []
304
+ for product in frozen_products:
305
+ asin = product.get("asin") if isinstance(product, Mapping) else None
306
+ if not isinstance(asin, str) or not asin or asin in frozen_asins:
307
+ raise BrowseBreadthError("external SSD fixture requires nine unique ASINs")
308
+ frozen_asins.append(asin)
309
+
310
+ assignments = (
311
+ (INSTANT_POT_ASIN, "home-kitchen"),
312
+ *((asin, "computers") for asin in frozen_asins),
313
+ )
314
+ supplements: list[dict[str, Any]] = []
315
+ for asin, department_slug in assignments:
316
+ offer = offer_by_asin.get(asin)
317
+ if offer is None:
318
+ raise BrowseBreadthError(f"department commerce offer is missing: {asin}")
319
+ catalog_product = catalog.get(asin)
320
+ if (
321
+ isinstance(catalog_product, Mapping)
322
+ and catalog_product.get("evidence_tier") == "pdp-direct"
323
+ ):
324
+ product = dict(catalog_product)
325
+ else:
326
+ product = dict(offer)
327
+
328
+ if (
329
+ product.get("price_minor") != offer.get("price_minor")
330
+ or product.get("currency") != "USD"
331
+ or product.get("currency") != offer.get("currency")
332
+ or product.get("image_path") != offer.get("image_path")
333
+ or not isinstance(product.get("image_path"), str)
334
+ or not str(product["image_path"]).startswith("/static/")
335
+ ):
336
+ raise BrowseBreadthError(
337
+ f"department commerce offer changed verified facts: {asin}"
338
+ )
339
+ if set(product).intersection(DEAL_MEMBERSHIP_FIELDS):
340
+ raise BrowseBreadthError(
341
+ f"department commerce offer contains Deals membership: {asin}"
342
+ )
343
+ product[DEPARTMENT_SLUGS_FIELD] = (department_slug,)
344
+ supplements.append(product)
345
+
346
+ supplement_asins = [str(product["asin"]) for product in supplements]
347
+ if len(supplements) != 10 or len(supplement_asins) != len(set(supplement_asins)):
348
+ raise BrowseBreadthError("department commerce supplement must contain 10 offers")
349
+ return tuple(supplements)
350
+
351
+
352
+ def load_browse_breadth(fixture_root: Path) -> dict[str, Any]:
353
+ """Load all browse-breadth views from the immutable local evidence set."""
354
+
355
+ root = fixture_root.resolve()
356
+ frozen = _read_object(root / "task-frozen-900136-v1.json")
357
+ direct = _read_object(root / "home-pdp-evidence.json")
358
+ region = frozen.get("region")
359
+ market = direct.get("marketContext")
360
+ if not isinstance(region, Mapping) or (
361
+ region.get("delivery_country"), region.get("currency")
362
+ ) != ("Singapore", "USD"):
363
+ raise BrowseBreadthError("frozen offers are outside the Singapore/USD baseline")
364
+ if not isinstance(market, Mapping) or (
365
+ market.get("deliveryCountry"), market.get("currency")
366
+ ) != ("Singapore", "USD"):
367
+ raise BrowseBreadthError("direct offers are outside the Singapore/USD baseline")
368
+ frozen_products = frozen.get("products")
369
+ direct_products = direct.get("products")
370
+ if not isinstance(frozen_products, list) or not isinstance(direct_products, list):
371
+ raise BrowseBreadthError("offer fixtures require product arrays")
372
+
373
+ catalog = load_home_product_catalog(root)
374
+ rail_sections = build_home_rail_sections(catalog)
375
+ supplement = build_portable_ssd_supplement(catalog, frozen_products)
376
+ offers = combine_verified_offer_display(frozen_products, direct_products)
377
+ department_supplements = build_department_commerce_supplements(
378
+ catalog,
379
+ frozen,
380
+ direct,
381
+ offers,
382
+ )
383
+ search_commerce_cards = load_search_commerce_cards(root)
384
+ if len(supplement) != 27:
385
+ raise BrowseBreadthError(
386
+ f"portable SSD supplement expected 27 products, found {len(supplement)}"
387
+ )
388
+ expected_offer_count = len(
389
+ {
390
+ str(product.get("asin") or "")
391
+ for product in (*frozen_products, *direct_products)
392
+ }
393
+ )
394
+ if len(offers) != expected_offer_count:
395
+ raise BrowseBreadthError(
396
+ "verified offer union expected "
397
+ f"{expected_offer_count} products, found {len(offers)}"
398
+ )
399
+ return {
400
+ "rail_sections": rail_sections,
401
+ "portable_ssd_supplement": supplement,
402
+ "verified_offers": offers,
403
+ "department_commerce_supplements": department_supplements,
404
+ "search_commerce_cards": search_commerce_cards,
405
+ }
tasks/amazon/solution/site/implementation/clone/deals_catalog.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import hashlib
5
+ import re
6
+ from collections import Counter
7
+ from collections.abc import Mapping, Sequence
8
+ from decimal import Decimal, InvalidOperation
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlsplit
12
+
13
+
14
+ DEALS_EVIDENCE_FIXTURE = "deals-evidence.json"
15
+ DEALS_DEFAULT_CARDS_FIXTURE = "deals-current-2026-07-22.json"
16
+ DEALS_THEME_CHIPS: tuple[tuple[str, str], ...] = (
17
+ ("lightning-deals", "Lightning deals"),
18
+ ("customers-most-loved", "Customers' Most-Loved"),
19
+ ("outlet", "Outlet"),
20
+ ("lowest-price-365", "Lowest Price in 365 Days"),
21
+ ("premium-brands", "Premium Brands"),
22
+ ("summer-favorites", "Summer Favorites"),
23
+ ("beauty", "Beauty"),
24
+ ("fashion", "Fashion"),
25
+ ("home", "Home"),
26
+ ("toys", "Toys & Games"),
27
+ ("electronics", "Electronics"),
28
+ ("devices", "Devices"),
29
+ ("kitchen", "Kitchen"),
30
+ ("everyday-essentials", "Everyday Essentials"),
31
+ ("amazon-brands", "Amazon Brands"),
32
+ ("computers", "Computers & Accessories"),
33
+ ("pet-supplies", "Pet Supplies"),
34
+ ("furniture", "Furniture"),
35
+ ("tvs-accessories", "TVs & Accessories"),
36
+ ("home-diy-appliances", "Home DIY & Appliances"),
37
+ ("sports-outdoors", "Sports & Outdoors"),
38
+ ("grocery", "Grocery"),
39
+ ("health-household", "Health & Household"),
40
+ ("cell-phones-accessories", "Cell Phones & Accessories"),
41
+ ("small-business", "Small Business"),
42
+ ("video-games", "Video Games"),
43
+ ("lawn-garden", "Lawn & Garden"),
44
+ ("automotive", "Automotive"),
45
+ ("camera-photo", "Camera & Photo"),
46
+ ("books", "Books"),
47
+ ("jewelry", "Jewelry"),
48
+ ("baby", "Baby"),
49
+ ("office-supplies", "Office Supplies"),
50
+ ("musical-instruments", "Musical Instruments"),
51
+ ("refurbished", "Refurbished Products"),
52
+ ("coupons", "Coupons"),
53
+ )
54
+ DEALS_THEME_LABELS = dict(DEALS_THEME_CHIPS)
55
+ DEALS_SOURCE_PRICE_LIMIT_MINOR = 15_800
56
+ DEALS_DISCOUNT_LIMIT = 75
57
+ _MONEY_INPUT = re.compile(r"(?:0|[1-9][0-9]{0,2})(?:\.[0-9]{1,2})?")
58
+ _DISCOUNT_INPUT = re.compile(r"(?:0|[1-9][0-9]?)")
59
+
60
+ # Only a subset of the horizontally scrollable theme navigation had direct
61
+ # product membership in the retained snapshot. A selected empty theme is
62
+ # therefore projected deterministically from the existing deal pool and kept
63
+ # explicitly simulated in the internal view model. This makes every captured
64
+ # navigation control a real destination without presenting the projection as
65
+ # source-verified membership.
66
+ DEALS_THEME_KEYWORDS: dict[str, tuple[str, ...]] = {
67
+ "customers-most-loved": ("mighty patch", "instant pot", "sandisk", "samsung", "pillow"),
68
+ "outlet": ("old model", "basics", "refurbished"),
69
+ "lowest-price-365": ("screen protector", "figure", "picture frame", "book"),
70
+ "premium-brands": ("samsung", "sandisk", "instant pot", "levoit", "dreo"),
71
+ "summer-favorites": ("fan", "linen", "sheet", "beet root", "backpack"),
72
+ "fashion": ("shirt", "backpack", "fashion"),
73
+ "devices": ("ssd", "screen protector", "usb"),
74
+ "everyday-essentials": ("toilet paper", "paper towel", "air filter", "sheet", "pillow"),
75
+ "pet-supplies": ("okapi", "figure", "binder"),
76
+ "furniture": ("pillow", "sheet", "picture frame"),
77
+ "tvs-accessories": ("screen protector", "usb", "ssd"),
78
+ "home-diy-appliances": ("air filter", "fan", "instant pot"),
79
+ "sports-outdoors": ("backpack", "beet root", "fan"),
80
+ "grocery": ("beet root", "paper towel", "toilet paper"),
81
+ "health-household": ("pain relief", "mighty patch", "beet root", "toilet paper"),
82
+ "cell-phones-accessories": ("screen protector", "portable ssd", "usb"),
83
+ "small-business": ("ssd", "paper", "binder", "backpack"),
84
+ "video-games": ("ssd", "trading card", "binder"),
85
+ "lawn-garden": ("fan", "okapi", "air filter"),
86
+ "automotive": ("air filter", "portable ssd", "fan"),
87
+ "camera-photo": ("picture frame", "ssd", "screen protector"),
88
+ "jewelry": ("fashion", "shirt", "picture frame"),
89
+ "baby": ("toilet paper", "sheet", "pillow"),
90
+ "office-supplies": ("paper", "binder", "backpack", "ssd"),
91
+ "musical-instruments": ("fan", "ssd", "binder"),
92
+ "refurbished": ("old model", "portable ssd"),
93
+ "coupons": ("amazon basics", "limited time deal"),
94
+ }
95
+
96
+
97
+ class DealsCatalogError(ValueError):
98
+ pass
99
+
100
+
101
+ def _department_slug(label: str) -> str:
102
+ slug = re.sub(r"[^a-z0-9]+", "-", label.casefold()).strip("-")
103
+ if not slug:
104
+ raise DealsCatalogError("deal department must have a usable label")
105
+ return slug
106
+
107
+
108
+ def _read_fixture(path: Path) -> dict[str, Any]:
109
+ try:
110
+ payload = json.loads(path.read_text(encoding="utf-8"))
111
+ except (OSError, json.JSONDecodeError) as exc:
112
+ raise DealsCatalogError(f"invalid Deals fixture: {path.name}") from exc
113
+ if not isinstance(payload, dict):
114
+ raise DealsCatalogError("Deals fixture must be an object")
115
+ return payload
116
+
117
+
118
+ def load_deals_default_card_offers(
119
+ fixture_root: Path,
120
+ ) -> tuple[dict[str, Any], ...]:
121
+ """Validate and project the ten current source Deal cards as base offers."""
122
+
123
+ fixture_root = fixture_root.resolve()
124
+ path = (fixture_root / DEALS_DEFAULT_CARDS_FIXTURE).resolve()
125
+ if fixture_root not in path.parents:
126
+ raise DealsCatalogError("Deals card fixture escapes fixture root")
127
+ payload = _read_fixture(path)
128
+ if payload.get("schema") != "amazon-clone.deals-default-card-offers.v1":
129
+ raise DealsCatalogError("unsupported Deals card fixture schema")
130
+ scope = payload.get("scope")
131
+ products = payload.get("products")
132
+ if (
133
+ not isinstance(scope, dict)
134
+ or scope.get("observed_card_count") != 10
135
+ or scope.get("rating_or_reviews_captured") is not False
136
+ or scope.get("delivery_or_inventory_captured") is not False
137
+ or scope.get("option_matrix_captured") is not False
138
+ or not isinstance(products, list)
139
+ or len(products) != 10
140
+ ):
141
+ raise DealsCatalogError("Deals card evidence boundary is invalid")
142
+
143
+ clone_root = fixture_root.parent
144
+ normalized: list[dict[str, Any]] = []
145
+ seen: set[str] = set()
146
+ for expected_order, raw in enumerate(products, 1):
147
+ if not isinstance(raw, dict):
148
+ raise DealsCatalogError("Deals card must be an object")
149
+ asin = raw.get("asin")
150
+ title = raw.get("title")
151
+ brand = raw.get("brand")
152
+ source_url = raw.get("source_product_url")
153
+ image_path = raw.get("image_path")
154
+ image_sha = raw.get("image_sha256")
155
+ price = raw.get("price_minor")
156
+ reference = raw.get("reference_price_minor")
157
+ discount = raw.get("discount_percent")
158
+ if (
159
+ not isinstance(asin, str)
160
+ or re.fullmatch(r"[A-Z0-9]{10}", asin) is None
161
+ or asin in seen
162
+ or raw.get("display_order") != expected_order
163
+ or not isinstance(title, str)
164
+ or not title.strip()
165
+ or (brand is not None and (not isinstance(brand, str) or not brand.strip()))
166
+ or not isinstance(source_url, str)
167
+ or not isinstance(image_path, str)
168
+ or not image_path.startswith("/static/")
169
+ or raw.get("image_media_type") != "image/avif"
170
+ or not isinstance(image_sha, str)
171
+ or re.fullmatch(r"[0-9a-f]{64}", image_sha) is None
172
+ or isinstance(price, bool)
173
+ or not isinstance(price, int)
174
+ or price < 0
175
+ or isinstance(reference, bool)
176
+ or not isinstance(reference, int)
177
+ or reference <= price
178
+ or isinstance(discount, bool)
179
+ or not isinstance(discount, int)
180
+ or not 1 <= discount <= DEALS_DISCOUNT_LIMIT
181
+ or raw.get("deal_label") != "Limited time deal"
182
+ or raw.get("reference_price_label") not in {"Typical", "List"}
183
+ or raw.get("currency") != "USD"
184
+ or "rating" in raw
185
+ or "reviews" in raw
186
+ or "delivery" in raw
187
+ or "options" in raw
188
+ ):
189
+ raise DealsCatalogError(f"Deals source card is invalid: {asin!r}")
190
+ parsed = urlsplit(source_url)
191
+ if (
192
+ parsed.scheme != "https"
193
+ or parsed.hostname not in {"www.amazon.com", "amazon.com"}
194
+ or not parsed.path.endswith(f"/dp/{asin}")
195
+ or parsed.query
196
+ or parsed.fragment
197
+ ):
198
+ raise DealsCatalogError(f"Deals product URL is invalid: {asin}")
199
+ local_asset = (clone_root / image_path.removeprefix("/")).resolve()
200
+ static_root = (clone_root / "static").resolve()
201
+ if (
202
+ static_root not in local_asset.parents
203
+ or not local_asset.is_file()
204
+ or hashlib.sha256(local_asset.read_bytes()).hexdigest() != image_sha
205
+ ):
206
+ raise DealsCatalogError(f"Deals image integrity failed: {asin}")
207
+ computed_discount = round((reference - price) * 100 / reference)
208
+ if computed_discount != discount:
209
+ raise DealsCatalogError(f"Deals discount arithmetic changed: {asin}")
210
+ seen.add(asin)
211
+ normalized.append(
212
+ {
213
+ "asin": asin,
214
+ "slug": parsed.path.split("/")[1],
215
+ "canonical_path": parsed.path,
216
+ "title": title,
217
+ "brand": brand or "",
218
+ "capacity": "",
219
+ "color": "",
220
+ "price_minor": price,
221
+ "list_price_minor": reference,
222
+ "reference_price_label": str(raw["reference_price_label"]),
223
+ "captured_discount_percent": discount,
224
+ "currency": "USD",
225
+ "rating": "",
226
+ "reviews": 0,
227
+ "image_path": image_path,
228
+ "badge": "",
229
+ "evidence_class": "direct-deals-card",
230
+ "source": "direct-deals",
231
+ "deal_label": "Limited time deal",
232
+ "image_alt": str(raw.get("image_alt") or title),
233
+ }
234
+ )
235
+ return tuple(normalized)
236
+
237
+
238
+ def load_deals_catalog(
239
+ fixture_root: Path,
240
+ verified_offers: Sequence[Mapping[str, Any]],
241
+ ) -> tuple[dict[str, Any], ...]:
242
+ """Join explicit Deals membership to strict commerce offers.
243
+
244
+ ``verified_offers`` is an availability pool, not a Deals membership list.
245
+ Only ASINs named by the Deals evidence fixture may enter this catalog, so a
246
+ future ordinary commerce offer does not need unrelated Deals metadata.
247
+ """
248
+
249
+ fixture_root = fixture_root.resolve()
250
+ metadata_path = (fixture_root / DEALS_EVIDENCE_FIXTURE).resolve()
251
+ if fixture_root not in metadata_path.parents:
252
+ raise DealsCatalogError("Deals fixture escapes fixture root")
253
+ payload = _read_fixture(metadata_path)
254
+ if payload.get("schema") != "amazon-clone.deals-evidence.v1":
255
+ raise DealsCatalogError("unsupported Deals fixture schema")
256
+ raw_products = payload.get("products")
257
+ if not isinstance(raw_products, list) or not raw_products:
258
+ raise DealsCatalogError("Deals fixture has no products")
259
+
260
+ metadata_by_asin: dict[str, dict[str, Any]] = {}
261
+ orders: list[int] = []
262
+ for raw in raw_products:
263
+ if not isinstance(raw, dict):
264
+ raise DealsCatalogError("Deals product metadata must be an object")
265
+ asin = raw.get("asin")
266
+ order = raw.get("displayOrder")
267
+ department = raw.get("department")
268
+ themes = raw.get("themes")
269
+ limited_time = raw.get("limitedTimeDeal")
270
+ evidence_key = raw.get("evidenceKey")
271
+ if (
272
+ not isinstance(asin, str)
273
+ or not asin
274
+ or asin in metadata_by_asin
275
+ or isinstance(order, bool)
276
+ or not isinstance(order, int)
277
+ or order <= 0
278
+ or (
279
+ department is not None
280
+ and (not isinstance(department, str) or not department.strip())
281
+ )
282
+ or not isinstance(themes, list)
283
+ or not all(
284
+ isinstance(theme, str) and theme in DEALS_THEME_LABELS
285
+ for theme in themes
286
+ )
287
+ or len(themes) != len(set(themes))
288
+ or not isinstance(limited_time, bool)
289
+ or not isinstance(evidence_key, str)
290
+ or not evidence_key.strip()
291
+ ):
292
+ raise DealsCatalogError(f"Deals metadata is invalid: {asin!r}")
293
+ metadata_by_asin[asin] = raw
294
+ orders.append(order)
295
+
296
+ if sorted(orders) != list(range(1, len(orders) + 1)):
297
+ raise DealsCatalogError("Deals display order must be contiguous")
298
+
299
+ eligible_asins = frozenset(metadata_by_asin)
300
+ current_card_offers = load_deals_default_card_offers(fixture_root)
301
+ current_card_asins = {str(product["asin"]) for product in current_card_offers}
302
+ missing_current_metadata = sorted(current_card_asins - eligible_asins)
303
+ if missing_current_metadata:
304
+ raise DealsCatalogError(
305
+ "current Deals cards require display metadata: "
306
+ + ", ".join(missing_current_metadata)
307
+ )
308
+
309
+ offer_by_asin: dict[str, dict[str, Any]] = {}
310
+ all_offers: tuple[Mapping[str, Any], ...] = (
311
+ *verified_offers,
312
+ *current_card_offers,
313
+ )
314
+ for raw_offer in all_offers:
315
+ offer = dict(raw_offer)
316
+ asin = offer.get("asin")
317
+ if not isinstance(asin, str) or not asin:
318
+ raise DealsCatalogError("strict commerce offers require ASINs")
319
+ if asin not in eligible_asins:
320
+ continue
321
+ if asin in offer_by_asin:
322
+ raise DealsCatalogError("strict Deals offers require unique ASINs")
323
+ price_minor = offer.get("price_minor")
324
+ if (
325
+ isinstance(price_minor, bool)
326
+ or not isinstance(price_minor, int)
327
+ or price_minor < 0
328
+ or offer.get("currency") != "USD"
329
+ ):
330
+ raise DealsCatalogError(f"strict Deals offer is invalid: {asin}")
331
+ offer_by_asin[asin] = offer
332
+
333
+ missing_offers = sorted(eligible_asins - offer_by_asin.keys())
334
+ if missing_offers:
335
+ raise DealsCatalogError(
336
+ "Deals metadata references unavailable offers: "
337
+ f"offers_missing={missing_offers}"
338
+ )
339
+
340
+ captured_deal_evidence: dict[str, tuple[bool, int | None]] = {}
341
+ for fixture_name in (
342
+ "task-frozen-900136-v1.json",
343
+ "home-pdp-evidence.json",
344
+ ):
345
+ fixture = _read_fixture(fixture_root / fixture_name)
346
+ source_products = fixture.get("products")
347
+ if not isinstance(source_products, list):
348
+ raise DealsCatalogError(f"{fixture_name} has no products")
349
+ for product in source_products:
350
+ if not isinstance(product, dict) or not isinstance(
351
+ product.get("asin"), str
352
+ ):
353
+ continue
354
+ detail = product.get("pdp")
355
+ deal_badge = (
356
+ detail.get("deal_badge") if isinstance(detail, dict) else None
357
+ )
358
+ discount = (
359
+ detail.get("discount_percent")
360
+ if isinstance(detail, dict)
361
+ else None
362
+ )
363
+ captured_deal_evidence[str(product["asin"])] = (
364
+ deal_badge == "Limited time deal",
365
+ discount if isinstance(discount, int) else None,
366
+ )
367
+ for product in current_card_offers:
368
+ captured_deal_evidence[str(product["asin"])] = (
369
+ product.get("deal_label") == "Limited time deal",
370
+ int(product["captured_discount_percent"]),
371
+ )
372
+
373
+ catalog: list[dict[str, Any]] = []
374
+ for asin, metadata in metadata_by_asin.items():
375
+ offer = dict(offer_by_asin[asin])
376
+ list_price = offer.get("list_price_minor")
377
+ price = int(offer["price_minor"])
378
+ arithmetic_discount: int | None = None
379
+ if isinstance(list_price, int) and not isinstance(list_price, bool):
380
+ if list_price > price:
381
+ arithmetic_discount = round(
382
+ (list_price - price) * 100 / list_price
383
+ )
384
+ else:
385
+ offer["list_price_minor"] = None
386
+ expected_limited, captured_discount = captured_deal_evidence.get(
387
+ asin, (False, None)
388
+ )
389
+ if bool(metadata["limitedTimeDeal"]) != expected_limited:
390
+ raise DealsCatalogError(
391
+ f"limited-time label does not match direct evidence: {asin}"
392
+ )
393
+ if captured_discount is not None and (
394
+ arithmetic_discount is None
395
+ or arithmetic_discount != captured_discount
396
+ ):
397
+ raise DealsCatalogError(
398
+ f"captured discount does not match source evidence: {asin}"
399
+ )
400
+ rating_value: float | None = None
401
+ try:
402
+ if str(offer.get("rating") or "").strip():
403
+ rating_value = float(str(offer["rating"]))
404
+ except ValueError:
405
+ rating_value = None
406
+ offer.update(
407
+ {
408
+ "display_order": int(metadata["displayOrder"]),
409
+ "department": (
410
+ str(metadata["department"])
411
+ if metadata["department"] is not None
412
+ else ""
413
+ ),
414
+ "department_slug": (
415
+ _department_slug(str(metadata["department"]))
416
+ if metadata["department"] is not None
417
+ else ""
418
+ ),
419
+ "themes": tuple(str(theme) for theme in metadata["themes"]),
420
+ "limited_time_deal": expected_limited,
421
+ "discount_percent": captured_discount,
422
+ "rating_value": rating_value,
423
+ "deals_evidence_key": str(metadata["evidenceKey"]),
424
+ }
425
+ )
426
+ catalog.append(offer)
427
+ return tuple(sorted(catalog, key=lambda product: product["display_order"]))
428
+
429
+
430
+ def _first(query: Mapping[str, Sequence[str]], key: str) -> str:
431
+ values = query.get(key, ())
432
+ return values[0].strip() if len(values) == 1 else ""
433
+
434
+
435
+ def _money_filter(
436
+ query: Mapping[str, Sequence[str]], key: str, limit_minor: int
437
+ ) -> tuple[int | None, str]:
438
+ raw = _first(query, key)
439
+ if not raw or _MONEY_INPUT.fullmatch(raw) is None:
440
+ return None, ""
441
+ try:
442
+ value = Decimal(raw)
443
+ except InvalidOperation:
444
+ return None, ""
445
+ minor = int(value * 100)
446
+ if minor < 0 or minor > limit_minor:
447
+ return None, ""
448
+ canonical = f"{minor / 100:.2f}".rstrip("0").rstrip(".")
449
+ return minor, canonical
450
+
451
+
452
+ def _discount_filter(
453
+ query: Mapping[str, Sequence[str]], key: str
454
+ ) -> tuple[int | None, str]:
455
+ raw = _first(query, key)
456
+ if not raw or _DISCOUNT_INPUT.fullmatch(raw) is None:
457
+ return None, ""
458
+ value = int(raw)
459
+ if value < 0 or value > DEALS_DISCOUNT_LIMIT:
460
+ return None, ""
461
+ return value, str(value)
462
+
463
+
464
+ def build_deals_view(
465
+ catalog: Sequence[Mapping[str, Any]],
466
+ query: Mapping[str, Sequence[str]],
467
+ ) -> dict[str, Any]:
468
+ """Apply copyable GET filters to the evidence-backed Deals catalog."""
469
+
470
+ products = [dict(product) for product in catalog]
471
+ departments = {
472
+ str(product["department_slug"]): str(product["department"])
473
+ for product in products
474
+ if str(product.get("department_slug") or "")
475
+ }
476
+ brands = {
477
+ str(product.get("brand") or "")
478
+ for product in products
479
+ if str(product.get("brand") or "").strip()
480
+ }
481
+ theme = _first(query, "theme")
482
+ if theme not in DEALS_THEME_LABELS:
483
+ theme = ""
484
+ department = _first(query, "department")
485
+ if department not in departments:
486
+ department = ""
487
+ selected_brands: list[str] = []
488
+ for brand in query.get("brand", ()):
489
+ candidate = brand.strip()
490
+ if candidate in brands and candidate not in selected_brands:
491
+ selected_brands.append(candidate)
492
+ rating = _first(query, "rating")
493
+ if rating != "4-up":
494
+ rating = ""
495
+ price_limit_minor = max(
496
+ DEALS_SOURCE_PRICE_LIMIT_MINOR,
497
+ max((int(product["price_minor"]) for product in products), default=0),
498
+ )
499
+ min_price, min_price_text = _money_filter(
500
+ query, "minPrice", price_limit_minor
501
+ )
502
+ max_price, max_price_text = _money_filter(
503
+ query, "maxPrice", price_limit_minor
504
+ )
505
+ min_discount, min_discount_text = _discount_filter(query, "minDiscount")
506
+ max_discount, max_discount_text = _discount_filter(query, "maxDiscount")
507
+ deal_type = _first(query, "dealType")
508
+ if deal_type != "limited-time":
509
+ deal_type = ""
510
+ range_error = ""
511
+ if min_price is not None and max_price is not None and min_price > max_price:
512
+ range_error = "Minimum price cannot exceed maximum price."
513
+ elif (
514
+ min_discount is not None
515
+ and max_discount is not None
516
+ and min_discount > max_discount
517
+ ):
518
+ range_error = "Minimum discount cannot exceed maximum discount."
519
+
520
+ direct_theme_products = [
521
+ product
522
+ for product in products
523
+ if theme and theme in product.get("themes", ())
524
+ ]
525
+ theme_projection = bool(theme and not direct_theme_products)
526
+ projected_asins: set[str] = set()
527
+ if theme_projection:
528
+ if theme == "lightning-deals":
529
+ projected_asins = {
530
+ str(product["asin"])
531
+ for product in products
532
+ if product.get("limited_time_deal")
533
+ }
534
+ else:
535
+ keywords = DEALS_THEME_KEYWORDS.get(theme, ())
536
+ projected_asins = {
537
+ str(product["asin"])
538
+ for product in products
539
+ if any(
540
+ keyword in " ".join(
541
+ (
542
+ str(product.get("title") or ""),
543
+ str(product.get("brand") or ""),
544
+ str(product.get("department") or ""),
545
+ )
546
+ ).casefold()
547
+ for keyword in keywords
548
+ )
549
+ }
550
+ if not projected_asins:
551
+ # A stable final fallback keeps a navigation destination useful
552
+ # even when the bounded deal pool has no semantic match.
553
+ digest = hashlib.sha256(theme.encode("utf-8")).digest()
554
+ start = int.from_bytes(digest[:2], "big") % len(products)
555
+ projected_asins = {
556
+ str(products[(start + offset) % len(products)]["asin"])
557
+ for offset in range(min(4, len(products)))
558
+ }
559
+
560
+ filtered: list[dict[str, Any]] = []
561
+ if not range_error:
562
+ for product in products:
563
+ discount = product.get("discount_percent")
564
+ discount_value = int(discount) if isinstance(discount, int) else None
565
+ if theme:
566
+ has_direct_membership = theme in product.get("themes", ())
567
+ if not has_direct_membership and str(product["asin"]) not in projected_asins:
568
+ continue
569
+ if department and product.get("department_slug") != department:
570
+ continue
571
+ if selected_brands and product.get("brand") not in selected_brands:
572
+ continue
573
+ if rating and (
574
+ product.get("rating_value") is None
575
+ or float(product["rating_value"]) < 4.0
576
+ ):
577
+ continue
578
+ price = int(product["price_minor"])
579
+ if min_price is not None and price < min_price:
580
+ continue
581
+ if max_price is not None and price > max_price:
582
+ continue
583
+ if min_discount is not None or max_discount is not None:
584
+ if discount_value is None:
585
+ continue
586
+ if min_discount is not None and discount_value < min_discount:
587
+ continue
588
+ if max_discount is not None and discount_value > max_discount:
589
+ continue
590
+ if deal_type == "limited-time" and not product.get(
591
+ "limited_time_deal"
592
+ ):
593
+ continue
594
+ result = dict(product)
595
+ if theme_projection:
596
+ result["theme_membership_provenance"] = "simulated-projection"
597
+ result["projected_theme"] = theme
598
+ filtered.append(result)
599
+
600
+ department_counts = Counter(
601
+ str(product["department_slug"]) for product in products
602
+ )
603
+ brand_counts = Counter(str(product.get("brand") or "") for product in products)
604
+ filters = {
605
+ "theme": theme,
606
+ "department": department,
607
+ "brands": tuple(selected_brands),
608
+ "rating": rating,
609
+ "min_price_minor": min_price,
610
+ "max_price_minor": max_price,
611
+ "min_price_text": min_price_text,
612
+ "max_price_text": max_price_text,
613
+ "min_discount": min_discount,
614
+ "max_discount": max_discount,
615
+ "min_discount_text": min_discount_text,
616
+ "max_discount_text": max_discount_text,
617
+ "deal_type": deal_type,
618
+ "range_error": range_error,
619
+ "price_limit_minor": price_limit_minor,
620
+ "price_limit_text": f"{price_limit_minor / 100:.2f}".rstrip("0").rstrip("."),
621
+ }
622
+ active_count = sum(
623
+ (
624
+ bool(theme),
625
+ bool(department),
626
+ len(selected_brands),
627
+ bool(rating),
628
+ min_price is not None,
629
+ max_price is not None,
630
+ min_discount is not None,
631
+ max_discount is not None,
632
+ bool(deal_type),
633
+ )
634
+ )
635
+ return {
636
+ "products": filtered,
637
+ "all_count": len(products),
638
+ "result_count": len(filtered),
639
+ "filters": filters,
640
+ "active_filter_count": active_count,
641
+ "theme_chips": DEALS_THEME_CHIPS,
642
+ "theme_label": DEALS_THEME_LABELS.get(theme, "All deals"),
643
+ "theme_projection": theme_projection,
644
+ "departments": tuple(
645
+ {
646
+ "slug": slug,
647
+ "label": label,
648
+ "count": department_counts[slug],
649
+ }
650
+ for slug, label in departments.items()
651
+ ),
652
+ "brands": tuple(
653
+ {"label": brand, "count": brand_counts[brand]}
654
+ for brand in sorted(brands, key=str.casefold)
655
+ ),
656
+ }
tasks/amazon/solution/site/implementation/clone/external_verification.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Amazon adapter for the canonical WebsiteBench verification library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+
10
+ for ancestor in Path(__file__).resolve().parents:
11
+ repository_src = ancestor / "src"
12
+ if (repository_src / "websitebench" / "public_clone_auth").is_dir():
13
+ if str(repository_src) not in sys.path:
14
+ sys.path.insert(0, str(repository_src))
15
+ break
16
+
17
+ from websitebench.public_clone_auth import ( # noqa: E402
18
+ ExternalRegistrationVerification,
19
+ PublicCloneIdentity,
20
+ RedisRestClient,
21
+ ResendEmailClient,
22
+ VerificationConfigurationError,
23
+ VerificationIssue,
24
+ VerificationLocked,
25
+ VerificationRateLimited,
26
+ VerificationUnavailable,
27
+ ensure_sqlite_email_verified,
28
+ load_public_clone_registration_verification,
29
+ registration_frontend_script,
30
+ )
31
+
32
+
33
+ _LEGACY_ALIASES = {
34
+ "AMAZON_EXTERNAL_VERIFICATION_MODE": "PUBLIC_CLONE_AUTH_MODE",
35
+ "AMAZON_REDIS_REST_URL": "PUBLIC_CLONE_AUTH_REDIS_REST_URL",
36
+ "AMAZON_REDIS_REST_TOKEN": "PUBLIC_CLONE_AUTH_REDIS_REST_TOKEN",
37
+ "AMAZON_RESEND_API_URL": "PUBLIC_CLONE_AUTH_RESEND_API_URL",
38
+ "AMAZON_RESEND_API_KEY": "PUBLIC_CLONE_AUTH_RESEND_API_KEY",
39
+ "AMAZON_RESEND_FROM_EMAIL": "PUBLIC_CLONE_AUTH_RESEND_FROM_EMAIL",
40
+ }
41
+
42
+
43
+ def load_external_registration_verification(
44
+ source: dict[str, str] | None = None,
45
+ ) -> ExternalRegistrationVerification | None:
46
+ """Load Amazon's public profile through the shared implementation."""
47
+
48
+ original = os.environ if source is None else source
49
+ values = dict(original)
50
+ for legacy_name, common_name in _LEGACY_ALIASES.items():
51
+ if common_name not in values and legacy_name in values:
52
+ values[common_name] = values[legacy_name]
53
+ values.setdefault("PUBLIC_CLONE_AUTH_SITE_ID", "amazon")
54
+ values.setdefault("PUBLIC_CLONE_AUTH_SITE_LABEL", "Amazon Clone")
55
+ return load_public_clone_registration_verification(values)
56
+
57
+
58
+ __all__ = [
59
+ "ExternalRegistrationVerification",
60
+ "PublicCloneIdentity",
61
+ "RedisRestClient",
62
+ "ResendEmailClient",
63
+ "VerificationConfigurationError",
64
+ "VerificationIssue",
65
+ "VerificationLocked",
66
+ "VerificationRateLimited",
67
+ "VerificationUnavailable",
68
+ "ensure_sqlite_email_verified",
69
+ "load_external_registration_verification",
70
+ "registration_frontend_script",
71
+ ]
tasks/amazon/solution/site/implementation/clone/harbor_entry.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebsiteBench Harbor foreground entrypoint for the Amazon clone."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from pathlib import Path
12
+
13
+
14
+ ROOT = Path(__file__).resolve().parent
15
+ SITE_ROOT = ROOT.parent
16
+ DATA_DIR = Path(os.environ["DATA_DIR"])
17
+ if not DATA_DIR.is_absolute():
18
+ raise RuntimeError("DATA_DIR must be absolute")
19
+ DATA_DIR = DATA_DIR.resolve()
20
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
21
+ os.environ["AMAZON_HOST"] = os.environ["HOST"]
22
+ os.environ["AMAZON_DB_PATH"] = str(DATA_DIR / "amazon.sqlite3")
23
+ os.environ["WEBSITEBENCH_DATA_DIR"] = str(DATA_DIR)
24
+ os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(DATA_DIR / "amazon.sqlite3")
25
+ os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(SITE_ROOT / "backend" / "runtime.json")
26
+ if os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip():
27
+ os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor"
28
+ os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = "local-sandbox"
29
+ os.environ["AMAZON_PAYMENT_MODE"] = "local-sandbox"
30
+
31
+
32
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
33
+ def redirect_request(self, request, fp, code, msg, headers, newurl):
34
+ del request, fp, code, msg, headers, newurl
35
+ return None
36
+
37
+
38
+ def _configure_harbor_mailbox() -> None:
39
+ bootstrap_url = os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip()
40
+ bootstrap_token = os.environ.get(
41
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN", ""
42
+ ).strip()
43
+ if not bootstrap_url and not bootstrap_token:
44
+ return
45
+ parsed = urllib.parse.urlsplit(bootstrap_url)
46
+ if (
47
+ parsed.scheme != "http"
48
+ or parsed.hostname not in {
49
+ "127.0.0.1",
50
+ "::1",
51
+ "localhost",
52
+ "mailbox-internal",
53
+ }
54
+ or parsed.username is not None
55
+ or parsed.password is not None
56
+ or len(bootstrap_token) < 32
57
+ ):
58
+ raise RuntimeError("Harbor mailbox bootstrap configuration is invalid")
59
+ request = urllib.request.Request(
60
+ bootstrap_url,
61
+ headers={
62
+ "Accept": "application/json",
63
+ "Authorization": f"Bearer {bootstrap_token}",
64
+ },
65
+ method="GET",
66
+ )
67
+ try:
68
+ with urllib.request.build_opener(_NoRedirect).open(request, timeout=10) as response:
69
+ raw = response.read(64 * 1024 + 1)
70
+ except (OSError, urllib.error.URLError) as exc:
71
+ raise RuntimeError("Harbor mailbox bootstrap is unavailable") from exc
72
+ if len(raw) > 64 * 1024:
73
+ raise RuntimeError("Harbor mailbox bootstrap response is too large")
74
+ try:
75
+ identity = json.loads(raw.decode("utf-8"))
76
+ namespace = str(identity["namespace"])
77
+ capability = str(identity["capability"])
78
+ smtp_host = str(identity["smtp_host"])
79
+ smtp_port = int(identity["smtp_port"])
80
+ except (KeyError, TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc:
81
+ raise RuntimeError("Harbor mailbox bootstrap response is invalid") from exc
82
+ if (
83
+ re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", namespace) is None
84
+ or len(namespace) > 128
85
+ or len(capability) < 32
86
+ or smtp_host not in {"127.0.0.1", "::1", "localhost", "mailbox-internal"}
87
+ or not 1 <= smtp_port <= 65535
88
+ ):
89
+ raise RuntimeError("Harbor mailbox identity is invalid")
90
+ os.environ.update(
91
+ {
92
+ "AMAZON_CLONE_REQUIRE_SMTP": "1",
93
+ "AMAZON_CLONE_SMTP_HOST": smtp_host,
94
+ "AMAZON_CLONE_SMTP_PORT": str(smtp_port),
95
+ "AMAZON_CLONE_SMTP_TLS": "none",
96
+ # The trial mailbox account only accepts envelopes from the
97
+ # sender the harness offers; a site-branded literal is rejected
98
+ # with "mail sender is not allowed" and no code ever lands.
99
+ "AMAZON_CLONE_SMTP_FROM": (
100
+ os.environ.get("WEBSITEBENCH_SMTP_FROM", "").strip()
101
+ or os.environ.get("WEBSITEBENCH_MAIL_FROM", "").strip()
102
+ or "Amazon WebsiteBench <no-reply@amazon.websitebench.local>"
103
+ ),
104
+ "AMAZON_CLONE_MAILBOX_NAMESPACE": namespace,
105
+ "AMAZON_CLONE_MAILBOX_CAPABILITY": capability,
106
+ }
107
+ )
108
+
109
+
110
+ _configure_harbor_mailbox()
111
+
112
+ import server # noqa: E402
113
+
114
+
115
+ _original_get = server.PublicHandler.do_GET
116
+ _original_head = server.PublicHandler.do_HEAD
117
+
118
+
119
+ # /healthz is the contract (ADR-0010); the private path stays mounted so
120
+ # bundles frozen before the migration keep answering.
121
+ HEALTH_PATHS = ("/healthz", "/__websitebench/health")
122
+
123
+
124
+ def _health(handler, *, head: bool) -> bool:
125
+ if urllib.parse.urlsplit(handler.path).path not in HEALTH_PATHS:
126
+ return False
127
+ body = b'{"status":"ok"}'
128
+ handler.send_response(200)
129
+ handler.send_header("Content-Type", "application/json")
130
+ handler.send_header("Content-Length", str(len(body)))
131
+ handler.send_header("Cache-Control", "no-store")
132
+ handler.end_headers()
133
+ if not head:
134
+ handler.wfile.write(body)
135
+ return True
136
+
137
+
138
+ def do_get(handler):
139
+ if not _health(handler, head=False):
140
+ _original_get(handler)
141
+
142
+
143
+ def do_head(handler):
144
+ if not _health(handler, head=True):
145
+ _original_head(handler)
146
+
147
+
148
+ class _DisabledAdminServer:
149
+ def serve_forever(self):
150
+ return None
151
+
152
+ def shutdown(self):
153
+ return None
154
+
155
+ def server_close(self):
156
+ return None
157
+
158
+
159
+ _real_server = server.ReusableThreadingHTTPServer
160
+
161
+
162
+ def _server_factory(address, handler):
163
+ if handler is server.AdminHandler:
164
+ return _DisabledAdminServer()
165
+ return _real_server(address, handler)
166
+
167
+
168
+ server.PublicHandler.do_GET = do_get
169
+ server.PublicHandler.do_HEAD = do_head
170
+ server.ReusableThreadingHTTPServer = _server_factory
171
+
172
+
173
+ if __name__ == "__main__":
174
+ raise SystemExit(server.main())
tasks/amazon/solution/site/implementation/clone/home_category_catalog.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ HOME_CATEGORY_FIXTURE = "home-category-products-current-2026-07-25.json"
11
+ HOME_CATEGORY_SCHEMA = "amazon-home-category-products-fixture.v1"
12
+ HOME_CATEGORY_EVIDENCE_CLASS = "direct-home-category-search-card"
13
+ ASIN_RE = re.compile(r"^[A-Z0-9]{10}$")
14
+ RUNTIME_IMAGE_PREFIX = (
15
+ "/static/assets/source-current/2026-07-25/home-category-products/"
16
+ )
17
+
18
+
19
+ def load_home_category_fixture(fixture_root: Path) -> dict[str, Any]:
20
+ fixture_root = fixture_root.resolve()
21
+ path = (fixture_root / HOME_CATEGORY_FIXTURE).resolve()
22
+ if fixture_root not in path.parents or not path.is_file():
23
+ raise ValueError("home-category product fixture does not exist")
24
+ payload = json.loads(path.read_text(encoding="utf-8"))
25
+ if (
26
+ not isinstance(payload, dict)
27
+ or payload.get("schema") != HOME_CATEGORY_SCHEMA
28
+ or payload.get("evidence_class") != HOME_CATEGORY_EVIDENCE_CLASS
29
+ or payload.get("marketplace") != "amazon.com"
30
+ or payload.get("unique_product_count") != 272
31
+ ):
32
+ raise ValueError("invalid home-category product fixture header")
33
+ raw_groups = payload.get("groups")
34
+ if not isinstance(raw_groups, list) or len(raw_groups) != 17:
35
+ raise ValueError("home-category product fixture requires 17 groups")
36
+
37
+ seen_groups: set[str] = set()
38
+ seen_asins: set[str] = set()
39
+ normalized_groups: list[dict[str, Any]] = []
40
+ for raw_group in raw_groups:
41
+ if not isinstance(raw_group, Mapping):
42
+ raise ValueError("home-category group must be an object")
43
+ key = raw_group.get("key")
44
+ title = raw_group.get("title")
45
+ raw_tiles = raw_group.get("tiles")
46
+ if (
47
+ not isinstance(key, str)
48
+ or not key
49
+ or key in seen_groups
50
+ or not isinstance(title, str)
51
+ or not title
52
+ or not isinstance(raw_tiles, list)
53
+ or len(raw_tiles) != 4
54
+ ):
55
+ raise ValueError("invalid home-category group")
56
+ seen_groups.add(key)
57
+ normalized_tiles: list[dict[str, Any]] = []
58
+ for expected_index, raw_tile in enumerate(raw_tiles, start=1):
59
+ if not isinstance(raw_tile, Mapping):
60
+ raise ValueError(f"home-category tile must be an object: {key}")
61
+ label = raw_tile.get("label")
62
+ query = raw_tile.get("query")
63
+ source_search_url = raw_tile.get("source_search_url")
64
+ raw_products = raw_tile.get("products")
65
+ if (
66
+ raw_tile.get("index") != expected_index
67
+ or not isinstance(label, str)
68
+ or not label
69
+ or not isinstance(query, str)
70
+ or not query
71
+ or not isinstance(source_search_url, str)
72
+ or not source_search_url.startswith(
73
+ ("https://www.amazon.com/", "https://us.amazon.com/")
74
+ )
75
+ or not isinstance(raw_products, list)
76
+ or len(raw_products) != 4
77
+ ):
78
+ raise ValueError(f"invalid home-category tile: {key}/{expected_index}")
79
+ products: list[dict[str, Any]] = []
80
+ for raw_product in raw_products:
81
+ if not isinstance(raw_product, Mapping):
82
+ raise ValueError(
83
+ f"home-category product must be an object: {key}/{expected_index}"
84
+ )
85
+ product = dict(raw_product)
86
+ asin = product.get("asin")
87
+ if (
88
+ not isinstance(asin, str)
89
+ or not ASIN_RE.fullmatch(asin)
90
+ or asin in seen_asins
91
+ or not isinstance(product.get("title"), str)
92
+ or not product["title"]
93
+ or not isinstance(product.get("slug"), str)
94
+ or not product["slug"]
95
+ or product.get("canonical_path")
96
+ != f"/{product['slug']}/dp/{asin}"
97
+ or not isinstance(product.get("price_minor"), int)
98
+ or product["price_minor"] <= 0
99
+ or product.get("currency") != "USD"
100
+ or not isinstance(product.get("image_path"), str)
101
+ or not product["image_path"].startswith(RUNTIME_IMAGE_PREFIX)
102
+ or product.get("evidence_class")
103
+ != HOME_CATEGORY_EVIDENCE_CLASS
104
+ or product.get("category_key") != key
105
+ or product.get("category_index") != expected_index
106
+ or product.get("category_label") != label
107
+ or product.get("category_query") != query
108
+ or product.get("source_search_url") != source_search_url
109
+ ):
110
+ raise ValueError(
111
+ f"invalid or duplicate home-category product: {asin!r}"
112
+ )
113
+ seen_asins.add(asin)
114
+ products.append(product)
115
+ normalized_tiles.append(
116
+ {
117
+ "index": expected_index,
118
+ "label": label,
119
+ "query": query,
120
+ "source_search_url": source_search_url,
121
+ "products": products,
122
+ }
123
+ )
124
+ normalized_groups.append(
125
+ {"key": key, "title": title, "tiles": normalized_tiles}
126
+ )
127
+ if len(seen_asins) != 272:
128
+ raise ValueError(
129
+ f"home-category fixture expected 272 ASINs, found {len(seen_asins)}"
130
+ )
131
+ return {
132
+ **payload,
133
+ "groups": normalized_groups,
134
+ }
135
+
136
+
137
+ def load_home_category_groups(fixture_root: Path) -> dict[str, dict[str, Any]]:
138
+ payload = load_home_category_fixture(fixture_root)
139
+ return {str(group["key"]): group for group in payload["groups"]}
140
+
141
+
142
+ def load_home_category_offers(fixture_root: Path) -> tuple[dict[str, Any], ...]:
143
+ groups = load_home_category_groups(fixture_root)
144
+ return tuple(
145
+ dict(product)
146
+ for group in groups.values()
147
+ for tile in group["tiles"]
148
+ for product in tile["products"]
149
+ )
150
+
151
+
152
+ def home_category_products(
153
+ fixture_root: Path,
154
+ collection_key: str,
155
+ tile_index: int | None,
156
+ ) -> list[dict[str, Any]]:
157
+ group = load_home_category_groups(fixture_root).get(collection_key)
158
+ if group is None:
159
+ return []
160
+ tiles = (
161
+ [group["tiles"][tile_index - 1]]
162
+ if tile_index is not None and tile_index in range(1, 5)
163
+ else group["tiles"]
164
+ )
165
+ return [
166
+ dict(product)
167
+ for tile in tiles
168
+ for product in tile["products"]
169
+ ]
tasks/amazon/solution/site/implementation/clone/mail_transport.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable outbound SMTP transport for the local Amazon clone.
2
+
3
+ No network delivery is configured by default. Supplying SMTP environment
4
+ variables switches registration, password-recovery, and order-confirmation
5
+ outboxes from ``LOCAL_ONLY`` to an asynchronous SMTP delivery attempt.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+ import os
12
+ import re
13
+ import smtplib
14
+ import ssl
15
+ from dataclasses import dataclass
16
+ from email.message import EmailMessage
17
+ from email.utils import getaddresses, parseaddr
18
+ from typing import Mapping
19
+ from urllib.parse import urlsplit
20
+
21
+
22
+ class SMTPConfigurationError(ValueError):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True, repr=False)
27
+ class SMTPConfig:
28
+ host: str
29
+ port: int
30
+ security: str
31
+ sender: str
32
+ username: str | None = None
33
+ password: str | None = None
34
+ timeout_seconds: float = 10.0
35
+ mailbox_namespace: str | None = None
36
+ mailbox_capability: str | None = None
37
+
38
+ def __repr__(self) -> str:
39
+ return (
40
+ "SMTPConfig("
41
+ f"host={self.host!r}, port={self.port!r}, security={self.security!r}, "
42
+ f"sender={self.sender!r}, username={'<configured>' if self.username else None}, "
43
+ "password=<redacted>, "
44
+ f"timeout_seconds={self.timeout_seconds!r}, "
45
+ f"mailbox_namespace={self.mailbox_namespace!r}, "
46
+ "mailbox_capability=<redacted>)"
47
+ )
48
+
49
+
50
+ _SMTP_ENV_KEYS = (
51
+ "AMAZON_CLONE_SMTP_HOST",
52
+ "AMAZON_CLONE_SMTP_PORT",
53
+ "AMAZON_CLONE_SMTP_TLS",
54
+ "AMAZON_CLONE_SMTP_USERNAME",
55
+ "AMAZON_CLONE_SMTP_PASSWORD",
56
+ "AMAZON_CLONE_SMTP_FROM",
57
+ "AMAZON_CLONE_SMTP_TIMEOUT_SECONDS",
58
+ "AMAZON_CLONE_MAILBOX_NAMESPACE",
59
+ "AMAZON_CLONE_MAILBOX_CAPABILITY",
60
+ )
61
+ _REQUIRE_SMTP_ENV_KEY = "AMAZON_CLONE_REQUIRE_SMTP"
62
+
63
+
64
+ def _clean_header(value: str, field: str, *, max_bytes: int = 512) -> str:
65
+ cleaned = value.strip()
66
+ if (
67
+ not cleaned
68
+ or len(cleaned.encode("utf-8")) > max_bytes
69
+ or any(ord(character) < 32 or ord(character) == 127 for character in cleaned)
70
+ ):
71
+ raise SMTPConfigurationError(f"{field} must be a non-empty single-line value")
72
+ return cleaned
73
+
74
+
75
+ def _clean_body(value: str) -> str:
76
+ if not isinstance(value, str) or len(value.encode("utf-8")) > 64 * 1024:
77
+ raise SMTPConfigurationError("message body must not exceed 64 KiB")
78
+ if any(
79
+ (ord(character) < 32 or ord(character) == 127)
80
+ and character not in {"\t", "\n", "\r"}
81
+ for character in value
82
+ ):
83
+ raise SMTPConfigurationError("message body contains a forbidden control character")
84
+ return value
85
+
86
+
87
+ def _mailbox(value: str, field: str, *, allow_display_name: bool) -> str:
88
+ cleaned = _clean_header(value, field)
89
+ parsed_addresses = getaddresses([cleaned])
90
+ if len(parsed_addresses) != 1:
91
+ raise SMTPConfigurationError(f"{field} must contain one valid email address")
92
+ display_name, address = parseaddr(cleaned)
93
+ if (
94
+ parsed_addresses[0] != (display_name, address)
95
+ or not address
96
+ or address.count("@") != 1
97
+ or any(character.isspace() for character in address)
98
+ ):
99
+ raise SMTPConfigurationError(f"{field} must contain one valid email address")
100
+ if not allow_display_name and (display_name or address != cleaned):
101
+ raise SMTPConfigurationError(f"{field} must be a bare email address")
102
+ return cleaned
103
+
104
+
105
+ def load_smtp_config(
106
+ environ: Mapping[str, str] | None = None,
107
+ ) -> SMTPConfig | None:
108
+ """Load strict SMTP configuration, or return ``None`` for LOCAL_ONLY mode."""
109
+
110
+ source = os.environ if environ is None else environ
111
+ require_value = source.get(_REQUIRE_SMTP_ENV_KEY, "0").strip().lower()
112
+ require_aliases = {
113
+ "": False,
114
+ "0": False,
115
+ "false": False,
116
+ "no": False,
117
+ "1": True,
118
+ "true": True,
119
+ "yes": True,
120
+ }
121
+ if require_value not in require_aliases:
122
+ raise SMTPConfigurationError(
123
+ "AMAZON_CLONE_REQUIRE_SMTP must be 1 or 0"
124
+ )
125
+ require_smtp = require_aliases[require_value]
126
+ host_value = source.get("AMAZON_CLONE_SMTP_HOST", "").strip()
127
+ any_smtp_value = any(source.get(key, "").strip() for key in _SMTP_ENV_KEYS)
128
+ if not host_value:
129
+ if require_smtp:
130
+ raise SMTPConfigurationError(
131
+ "AMAZON_CLONE_REQUIRE_SMTP=1 requires a complete SMTP configuration"
132
+ )
133
+ if any_smtp_value:
134
+ raise SMTPConfigurationError(
135
+ "AMAZON_CLONE_SMTP_HOST is required when any SMTP setting is present"
136
+ )
137
+ return None
138
+
139
+ host = _clean_header(host_value, "SMTP host")
140
+ tls_value = source.get("AMAZON_CLONE_SMTP_TLS", "starttls").strip().lower()
141
+ security_aliases = {
142
+ "1": "starttls",
143
+ "true": "starttls",
144
+ "yes": "starttls",
145
+ "starttls": "starttls",
146
+ "ssl": "ssl",
147
+ "implicit": "ssl",
148
+ "0": "plain",
149
+ "false": "plain",
150
+ "no": "plain",
151
+ "none": "plain",
152
+ "plain": "plain",
153
+ }
154
+ security = security_aliases.get(tls_value)
155
+ if security is None:
156
+ raise SMTPConfigurationError(
157
+ "AMAZON_CLONE_SMTP_TLS must be starttls, ssl, or none"
158
+ )
159
+
160
+ default_port = 465 if security == "ssl" else 587
161
+ try:
162
+ port = int(source.get("AMAZON_CLONE_SMTP_PORT", str(default_port)))
163
+ except ValueError as exc:
164
+ raise SMTPConfigurationError("SMTP port must be an integer") from exc
165
+ if not 1 <= port <= 65535:
166
+ raise SMTPConfigurationError("SMTP port must be between 1 and 65535")
167
+
168
+ username = source.get("AMAZON_CLONE_SMTP_USERNAME", "").strip() or None
169
+ password = source.get("AMAZON_CLONE_SMTP_PASSWORD", "") or None
170
+ if (username is None) != (password is None):
171
+ raise SMTPConfigurationError(
172
+ "SMTP username and password must be configured together"
173
+ )
174
+ if username is not None:
175
+ username = _clean_header(username, "SMTP username")
176
+ if security == "plain":
177
+ try:
178
+ parsed_host = ipaddress.ip_address(host.strip("[]"))
179
+ host_is_loopback = parsed_host.is_loopback
180
+ except ValueError:
181
+ host_is_loopback = host.casefold() in {
182
+ "localhost",
183
+ "mailbox-internal",
184
+ }
185
+ if not host_is_loopback:
186
+ raise SMTPConfigurationError(
187
+ "unencrypted SMTP is permitted only for a loopback mail server"
188
+ )
189
+ if username is not None:
190
+ raise SMTPConfigurationError(
191
+ "unencrypted SMTP cannot be configured with authentication"
192
+ )
193
+
194
+ sender = _mailbox(
195
+ source.get("AMAZON_CLONE_SMTP_FROM", ""),
196
+ "AMAZON_CLONE_SMTP_FROM",
197
+ allow_display_name=True,
198
+ )
199
+ try:
200
+ timeout_seconds = float(
201
+ source.get("AMAZON_CLONE_SMTP_TIMEOUT_SECONDS", "10")
202
+ )
203
+ except ValueError as exc:
204
+ raise SMTPConfigurationError("SMTP timeout must be numeric") from exc
205
+ if not 1 <= timeout_seconds <= 60:
206
+ raise SMTPConfigurationError("SMTP timeout must be between 1 and 60 seconds")
207
+
208
+ mailbox_namespace = source.get("AMAZON_CLONE_MAILBOX_NAMESPACE", "").strip() or None
209
+ mailbox_capability = source.get("AMAZON_CLONE_MAILBOX_CAPABILITY", "") or None
210
+ if (mailbox_namespace is None) != (mailbox_capability is None):
211
+ raise SMTPConfigurationError(
212
+ "mailbox namespace and capability must be configured together"
213
+ )
214
+ if mailbox_namespace is not None and (
215
+ len(mailbox_namespace) > 128
216
+ or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", mailbox_namespace) is None
217
+ ):
218
+ raise SMTPConfigurationError("mailbox namespace is malformed")
219
+ if mailbox_capability is not None and len(mailbox_capability) < 32:
220
+ raise SMTPConfigurationError("mailbox capability is malformed")
221
+
222
+ return SMTPConfig(
223
+ host=host,
224
+ port=port,
225
+ security=security,
226
+ sender=sender,
227
+ username=username,
228
+ password=password,
229
+ timeout_seconds=timeout_seconds,
230
+ mailbox_namespace=mailbox_namespace,
231
+ mailbox_capability=mailbox_capability,
232
+ )
233
+
234
+
235
+ def smtp_public_summary(config: SMTPConfig | None) -> dict[str, object]:
236
+ if config is None:
237
+ return {"mode": "LOCAL_ONLY"}
238
+ return {
239
+ "mode": "SMTP",
240
+ "host": config.host,
241
+ "port": config.port,
242
+ "security": config.security,
243
+ "authentication": bool(config.username),
244
+ "sender": config.sender,
245
+ }
246
+
247
+
248
+ def load_local_inbox_url(
249
+ config: SMTPConfig | None,
250
+ environ: Mapping[str, str] | None = None,
251
+ ) -> str | None:
252
+ """Return a validated loopback inbox URL for the local capture profile."""
253
+
254
+ source = os.environ if environ is None else environ
255
+ raw = source.get("AMAZON_CLONE_LOCAL_INBOX_URL", "").strip()
256
+ if not raw:
257
+ return None
258
+ if config is None:
259
+ raise SMTPConfigurationError(
260
+ "AMAZON_CLONE_LOCAL_INBOX_URL requires SMTP configuration"
261
+ )
262
+ try:
263
+ config_host = ipaddress.ip_address(config.host.strip("[]"))
264
+ except ValueError as exc:
265
+ raise SMTPConfigurationError(
266
+ "AMAZON_CLONE_LOCAL_INBOX_URL is allowed only with loopback SMTP"
267
+ ) from exc
268
+ if not config_host.is_loopback:
269
+ raise SMTPConfigurationError(
270
+ "AMAZON_CLONE_LOCAL_INBOX_URL is allowed only with loopback SMTP"
271
+ )
272
+ parsed = urlsplit(raw)
273
+ try:
274
+ port = parsed.port
275
+ except ValueError as exc:
276
+ raise SMTPConfigurationError("local inbox URL has an invalid port") from exc
277
+ if (
278
+ parsed.scheme != "http"
279
+ or parsed.hostname not in {"127.0.0.1", "::1"}
280
+ or port is None
281
+ or parsed.username is not None
282
+ or parsed.password is not None
283
+ or parsed.path not in {"", "/"}
284
+ or parsed.query
285
+ or parsed.fragment
286
+ ):
287
+ raise SMTPConfigurationError(
288
+ "AMAZON_CLONE_LOCAL_INBOX_URL must be a loopback HTTP origin"
289
+ )
290
+ host = f"[{parsed.hostname}]" if parsed.hostname == "::1" else parsed.hostname
291
+ return f"http://{host}:{port}/"
292
+
293
+
294
+ def send_smtp_message(
295
+ config: SMTPConfig,
296
+ *,
297
+ recipient: str,
298
+ subject: str,
299
+ body: str,
300
+ ) -> None:
301
+ """Send one plain-text message without logging credentials or message content."""
302
+
303
+ safe_recipient = _mailbox(recipient, "recipient", allow_display_name=False)
304
+ safe_subject = _clean_header(subject, "subject")
305
+ safe_body = _clean_body(body)
306
+ message = EmailMessage()
307
+ message["From"] = config.sender
308
+ message["To"] = safe_recipient
309
+ message["Subject"] = safe_subject
310
+ if config.mailbox_namespace is not None:
311
+ assert config.mailbox_capability is not None
312
+ message["X-WebsiteBench-Namespace"] = config.mailbox_namespace
313
+ message["X-WebsiteBench-Capability"] = config.mailbox_capability
314
+ message.set_content(safe_body)
315
+
316
+ context = ssl.create_default_context()
317
+ if config.security == "ssl":
318
+ client: smtplib.SMTP = smtplib.SMTP_SSL(
319
+ config.host,
320
+ config.port,
321
+ timeout=config.timeout_seconds,
322
+ context=context,
323
+ )
324
+ else:
325
+ client = smtplib.SMTP(
326
+ config.host, config.port, timeout=config.timeout_seconds
327
+ )
328
+ with client:
329
+ client.ehlo()
330
+ if config.security == "starttls":
331
+ client.starttls(context=context)
332
+ client.ehlo()
333
+ if config.username is not None:
334
+ assert config.password is not None
335
+ client.login(config.username, config.password)
336
+ client.send_message(message)
337
+
338
+
339
+ def smtp_error_summary(error: BaseException) -> str:
340
+ """Return an admin-safe failure category without exception text or secrets."""
341
+
342
+ name = type(error).__name__
343
+ if isinstance(error, smtplib.SMTPResponseException):
344
+ return f"{name}:smtp-{int(error.smtp_code)}"
345
+ return name[:96] or "SMTPDeliveryError"
346
+
347
+
348
+ __all__ = [
349
+ "SMTPConfig",
350
+ "SMTPConfigurationError",
351
+ "load_local_inbox_url",
352
+ "load_smtp_config",
353
+ "send_smtp_message",
354
+ "smtp_error_summary",
355
+ "smtp_public_summary",
356
+ ]
tasks/amazon/solution/site/implementation/clone/payment_methods.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Safe, deterministic payment tools for the local checkout simulation.
2
+
3
+ These identifiers are scenarios, not payment credentials. The public checkout
4
+ must never accept a PAN, expiry date, CVV, bank routing number, or similar
5
+ secret. Keeping the outcome table server-owned makes decline and retry
6
+ behaviour reproducible without pretending that a real processor is involved.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+
14
+ PAYMENT_APPROVED = "APPROVED"
15
+ PAYMENT_DECLINED = "DECLINED"
16
+
17
+ LEGACY_TEST_CARD = "test-card"
18
+ SANDBOX_CARD_APPROVED = "sandbox-card-approved"
19
+ SANDBOX_CARD_DECLINED = "sandbox-card-declined"
20
+ SANDBOX_BANK_APPROVED = "sandbox-bank-approved"
21
+ DEFAULT_PAYMENT_METHOD = SANDBOX_CARD_APPROVED
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class SandboxPaymentMethod:
26
+ identifier: str
27
+ label: str
28
+ description: str
29
+ outcome: str
30
+ decline_code: str | None = None
31
+
32
+
33
+ PAYMENT_METHODS: tuple[SandboxPaymentMethod, ...] = (
34
+ SandboxPaymentMethod(
35
+ identifier=SANDBOX_CARD_APPROVED,
36
+ label="Sandbox card · ending in 4242",
37
+ description="Simulated card authorization succeeds",
38
+ outcome=PAYMENT_APPROVED,
39
+ ),
40
+ SandboxPaymentMethod(
41
+ identifier=SANDBOX_CARD_DECLINED,
42
+ label="Sandbox card · ending in 0002",
43
+ description="Simulated issuer decline for testing retry",
44
+ outcome=PAYMENT_DECLINED,
45
+ decline_code="sandbox-card-declined",
46
+ ),
47
+ SandboxPaymentMethod(
48
+ identifier=SANDBOX_BANK_APPROVED,
49
+ label="Sandbox bank account",
50
+ description="Simulated bank authorization succeeds",
51
+ outcome=PAYMENT_APPROVED,
52
+ ),
53
+ )
54
+
55
+ _BY_IDENTIFIER = {method.identifier: method for method in PAYMENT_METHODS}
56
+
57
+
58
+ def payment_method(identifier: str) -> SandboxPaymentMethod:
59
+ """Return a supported public sandbox method or reject the identifier."""
60
+
61
+ if not isinstance(identifier, str):
62
+ raise ValueError("unsupported sandbox payment method")
63
+ try:
64
+ return _BY_IDENTIFIER[identifier]
65
+ except KeyError as exc:
66
+ raise ValueError("unsupported sandbox payment method") from exc
67
+
68
+
69
+ def payment_method_label(identifier: str) -> str:
70
+ """Return a safe display label, including legacy persisted test attempts."""
71
+
72
+ if identifier == LEGACY_TEST_CARD:
73
+ return "Legacy sandbox test card"
74
+ return payment_method(identifier).label
75
+
76
+
77
+ def public_payment_methods() -> tuple[dict[str, str], ...]:
78
+ """Return the non-secret method metadata needed by the checkout renderer."""
79
+
80
+ return tuple(
81
+ {
82
+ "identifier": method.identifier,
83
+ "label": method.label,
84
+ "description": method.description,
85
+ "outcome": method.outcome,
86
+ }
87
+ for method in PAYMENT_METHODS
88
+ )
89
+
90
+
91
+ __all__ = [
92
+ "DEFAULT_PAYMENT_METHOD",
93
+ "LEGACY_TEST_CARD",
94
+ "PAYMENT_APPROVED",
95
+ "PAYMENT_DECLINED",
96
+ "PAYMENT_METHODS",
97
+ "SANDBOX_BANK_APPROVED",
98
+ "SANDBOX_CARD_APPROVED",
99
+ "SANDBOX_CARD_DECLINED",
100
+ "SandboxPaymentMethod",
101
+ "payment_method",
102
+ "payment_method_label",
103
+ "public_payment_methods",
104
+ ]
tasks/amazon/solution/site/implementation/clone/product_options.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Any, Mapping
7
+
8
+ from deals_catalog import (
9
+ DEALS_DEFAULT_CARDS_FIXTURE,
10
+ load_deals_default_card_offers,
11
+ )
12
+ from home_catalog import load_home_product_catalog
13
+ from home_category_catalog import (
14
+ HOME_CATEGORY_FIXTURE,
15
+ load_home_category_offers,
16
+ )
17
+ from home_commerce import HOME_COMMERCE_FIXTURE, load_home_commerce_offers
18
+ from search_commerce import (
19
+ SEARCH_COMMERCE_EVIDENCE_CLASS,
20
+ SEARCH_COMMERCE_FIXTURE,
21
+ load_search_commerce_cards,
22
+ )
23
+
24
+
25
+ TARGET_ASIN = "B0874XN4D8"
26
+ T9_ASIN = "B0CHFSWM2P"
27
+ SHEETS_ASIN = "B01M16WBW1"
28
+ OKAPI_ASIN = "B0BG6B2D4D"
29
+ SANDISK_ASIN = "B08HN37XC1"
30
+ BOOK_ASIN = "168281808X"
31
+ BEAUTY_ASIN = "B074PVTPBW"
32
+ AILUN_ASIN = "B0BJPXXM7D"
33
+ VAULT_X_ASIN = "B071V91LGC"
34
+ UPSIMPLES_ASIN = "B0BQR2BQYZ"
35
+ INSTANT_POT_ASIN = "B00FLYWNYQ"
36
+ JANSPORT_ASIN = "B07K74LDCH"
37
+ AIR_FILTER_ASIN = "B088BZTYFP"
38
+
39
+ AVAILABLE_STATUS = "AVAILABLE"
40
+ UNAVAILABLE_SELECTION_COPY = "This selection is currently unavailable"
41
+
42
+
43
+ def _display_stock_copy(value: str) -> str:
44
+ """Keep internal quote provenance out of customer-facing stock copy."""
45
+
46
+ cleaned = " ".join(str(value).split())
47
+ normalized = cleaned.casefold()
48
+ if normalized == "in stock" or (
49
+ normalized.startswith("only ") and "left in stock" in normalized
50
+ ):
51
+ return cleaned
52
+ return "In Stock"
53
+
54
+ # The retained T7 source render displays this exact Blue/1 TB price and uses
55
+ # gallery image 09 for the Blue swatch. No child-variant ASIN was captured, so
56
+ # the transaction target below deliberately keeps variant_asin unset instead
57
+ # of inventing one.
58
+ T7_BLUE_PRICE_MINOR = 26_789
59
+ T7_BLUE_IMAGE_PATH = (
60
+ "/static/assets/source-current/2026-07-21/pdp-t7/gallery-09.jpg"
61
+ )
62
+
63
+ # The T7 task fixture intentionally freezes only the transaction identity. Its
64
+ # option labels are nevertheless visible in the retained source render (and in
65
+ # the current T7 PDP implementation), so keep them here instead of inventing
66
+ # variant prices or treating the labels as new commerce offers.
67
+ T7_SOURCE_OPTIONS: tuple[dict[str, Any], ...] = (
68
+ {
69
+ "label": "Color",
70
+ "default": "Titan Gray",
71
+ "options": ("Titan Gray", "Blue"),
72
+ },
73
+ {
74
+ "label": "Memory Storage Capacity",
75
+ "default": "1 TB",
76
+ "options": ("1 TB", "2 TB", "2.1 TB", "4.0 TB"),
77
+ },
78
+ )
79
+
80
+
81
+ def _option_names(raw_options: Any) -> tuple[str, ...]:
82
+ if not isinstance(raw_options, list):
83
+ return ()
84
+ names: list[str] = []
85
+ for raw_option in raw_options:
86
+ if isinstance(raw_option, Mapping):
87
+ raw_name = raw_option.get("name")
88
+ else:
89
+ raw_name = raw_option
90
+ if not isinstance(raw_name, str) or not raw_name:
91
+ continue
92
+ if raw_name not in names:
93
+ names.append(raw_name)
94
+ return tuple(names)
95
+
96
+
97
+ def option_groups_from_detail(
98
+ detail: Mapping[str, Any], product: Mapping[str, Any] | None = None
99
+ ) -> tuple[dict[str, Any], ...]:
100
+ """Normalize only option labels and values that exist in captured PDP data."""
101
+
102
+ choice_groups = detail.get("choice_groups")
103
+ if isinstance(choice_groups, list) and choice_groups:
104
+ groups: list[dict[str, Any]] = []
105
+ for raw_group in choice_groups:
106
+ if not isinstance(raw_group, Mapping):
107
+ continue
108
+ label = raw_group.get("label")
109
+ default = raw_group.get("value")
110
+ options = _option_names(raw_group.get("options"))
111
+ if not isinstance(label, str) or not label or not isinstance(default, str) or not default:
112
+ continue
113
+ if default not in options:
114
+ options = (default, *options)
115
+ groups.append({"label": label, "default": default, "options": options})
116
+ return tuple(groups)
117
+
118
+ groups = []
119
+ primary_label = detail.get("primary_option_label", "Digital Storage Capacity")
120
+ primary_default = detail.get("primary_option_value") or (product or {}).get("capacity")
121
+ primary_options = _option_names(
122
+ detail.get("primary_options", detail.get("capacity_options"))
123
+ )
124
+ if isinstance(primary_label, str) and primary_label and isinstance(primary_default, str) and primary_default:
125
+ if primary_default not in primary_options:
126
+ primary_options = (primary_default, *primary_options)
127
+ groups.append(
128
+ {
129
+ "label": primary_label,
130
+ "default": primary_default,
131
+ "options": primary_options,
132
+ }
133
+ )
134
+
135
+ secondary_label = detail.get("secondary_option_label", "Color")
136
+ secondary_default = detail.get("secondary_option_value") or (product or {}).get("color")
137
+ secondary_options = _option_names(detail.get("color_options"))
138
+ if isinstance(secondary_label, str) and secondary_label and isinstance(secondary_default, str) and secondary_default:
139
+ if secondary_default not in secondary_options:
140
+ secondary_options = (secondary_default, *secondary_options)
141
+ groups.append(
142
+ {
143
+ "label": secondary_label,
144
+ "default": secondary_default,
145
+ "options": secondary_options,
146
+ }
147
+ )
148
+ return tuple(groups)
149
+
150
+
151
+ def load_source_option_specs(fixture_root: Path) -> dict[str, tuple[dict[str, Any], ...]]:
152
+ """Build the option allow-list from the two retained PDP evidence fixtures."""
153
+
154
+ specs: dict[str, tuple[dict[str, Any], ...]] = {TARGET_ASIN: T7_SOURCE_OPTIONS}
155
+ fixture_names = ("task-frozen-900136-v1.json", "home-pdp-evidence.json")
156
+ for fixture_name in fixture_names:
157
+ candidate = (fixture_root / fixture_name).resolve()
158
+ if fixture_root.resolve() not in candidate.parents or not candidate.is_file():
159
+ raise ValueError(f"PDP option evidence fixture is unavailable: {fixture_name}")
160
+ payload = json.loads(candidate.read_text(encoding="utf-8"))
161
+ products = payload.get("products")
162
+ if not isinstance(products, list):
163
+ raise ValueError(f"PDP option evidence fixture has no product list: {fixture_name}")
164
+ for product in products:
165
+ if not isinstance(product, Mapping):
166
+ continue
167
+ asin = product.get("asin")
168
+ detail = product.get("pdp")
169
+ if not isinstance(asin, str) or not isinstance(detail, Mapping):
170
+ continue
171
+ groups = option_groups_from_detail(detail, product)
172
+ if groups:
173
+ specs[asin] = groups
174
+ return specs
175
+
176
+
177
+ def default_selection(
178
+ spec: tuple[dict[str, Any], ...] | None,
179
+ ) -> dict[str, str]:
180
+ return {
181
+ str(group["label"]): str(group["default"])
182
+ for group in spec or ()
183
+ }
184
+
185
+
186
+ def validate_selection(
187
+ spec: tuple[dict[str, Any], ...] | None,
188
+ selection: Mapping[str, Any] | None,
189
+ ) -> dict[str, str]:
190
+ """Return a canonical selection, rejecting every non-observed label/value."""
191
+
192
+ defaults = default_selection(spec)
193
+ if selection is None or not selection:
194
+ return defaults
195
+ if not isinstance(selection, Mapping) or set(selection) != set(defaults):
196
+ raise ValueError("product option selection is incomplete or unsupported")
197
+ normalized: dict[str, str] = {}
198
+ for group in spec or ():
199
+ label = str(group["label"])
200
+ value = selection.get(label)
201
+ if not isinstance(value, str) or value not in group["options"]:
202
+ raise ValueError(f"unsupported observed option value for {label}")
203
+ normalized[label] = value
204
+ return normalized
205
+
206
+
207
+ def normalize_complete_selection(
208
+ spec: tuple[dict[str, Any], ...] | None,
209
+ selection: Mapping[str, Any] | None,
210
+ ) -> dict[str, str]:
211
+ """Return a canonical complete selection without trusting extra fields.
212
+
213
+ ``None`` means the server-selected defaults. This keeps add-to-cart entry
214
+ points that do not render option fields deterministic. An explicitly
215
+ supplied mapping, however, must contain every captured label exactly once;
216
+ an empty or partial client mapping cannot silently become a default choice.
217
+ Valid values are normalized in source group order.
218
+ """
219
+
220
+ defaults = default_selection(spec)
221
+ if selection is None:
222
+ return defaults
223
+ if not isinstance(selection, Mapping):
224
+ raise ValueError("product option selection must be a mapping")
225
+ if set(selection) != set(defaults):
226
+ raise ValueError("product option selection is incomplete or unsupported")
227
+
228
+ normalized: dict[str, str] = {}
229
+ for group in spec or ():
230
+ label = str(group["label"])
231
+ value = selection.get(label)
232
+ if not isinstance(value, str) or value not in group["options"]:
233
+ raise ValueError(f"unsupported observed option value for {label}")
234
+ normalized[label] = value
235
+ return normalized
236
+
237
+
238
+ def canonical_selection_key(selection: Mapping[str, str]) -> str:
239
+ """Serialize a server-normalized selection into a stable line identity."""
240
+
241
+ if not isinstance(selection, Mapping) or any(
242
+ not isinstance(label, str) or not isinstance(value, str)
243
+ for label, value in selection.items()
244
+ ):
245
+ raise ValueError("canonical selection keys require string labels and values")
246
+ return json.dumps(
247
+ dict(selection),
248
+ ensure_ascii=True,
249
+ sort_keys=True,
250
+ separators=(",", ":"),
251
+ )
252
+
253
+
254
+ def _fixture_products(fixture_root: Path, fixture_name: str) -> list[dict[str, Any]]:
255
+ candidate = (fixture_root / fixture_name).resolve()
256
+ if fixture_root.resolve() not in candidate.parents or not candidate.is_file():
257
+ raise ValueError(f"PDP transaction evidence fixture is unavailable: {fixture_name}")
258
+ payload = json.loads(candidate.read_text(encoding="utf-8"))
259
+ products = payload.get("products")
260
+ if not isinstance(products, list):
261
+ raise ValueError(
262
+ f"PDP transaction evidence fixture has no product list: {fixture_name}"
263
+ )
264
+ return [dict(product) for product in products if isinstance(product, Mapping)]
265
+
266
+
267
+ def _base_quote_rule(
268
+ selection: Mapping[str, str],
269
+ *,
270
+ offer_asin: str,
271
+ currency: str,
272
+ display_availability: str,
273
+ evidence_key: str,
274
+ ) -> dict[str, Any]:
275
+ return {
276
+ "selected_options": dict(selection),
277
+ "price_minor": None,
278
+ "currency": currency,
279
+ "image_path": None,
280
+ "availability": AVAILABLE_STATUS,
281
+ "display_availability": _display_stock_copy(display_availability),
282
+ "target_kind": "base-offer",
283
+ "variant_asin": offer_asin,
284
+ "evidence_key": evidence_key,
285
+ }
286
+
287
+
288
+ def _captured_selection_quote_rule(
289
+ selection: Mapping[str, str],
290
+ *,
291
+ price_minor: int,
292
+ image_path: str,
293
+ display_availability: str,
294
+ evidence_key: str,
295
+ ) -> dict[str, Any]:
296
+ if isinstance(price_minor, bool) or not isinstance(price_minor, int) or price_minor < 0:
297
+ raise ValueError("captured option quote price must be a non-negative integer")
298
+ if not isinstance(image_path, str) or not image_path.startswith("/static/"):
299
+ raise ValueError("captured option quote image must be a local static asset")
300
+ return {
301
+ "selected_options": dict(selection),
302
+ "price_minor": price_minor,
303
+ "currency": "USD",
304
+ "image_path": image_path,
305
+ "availability": AVAILABLE_STATUS,
306
+ "display_availability": _display_stock_copy(display_availability),
307
+ "target_kind": "captured-selection",
308
+ "variant_asin": None,
309
+ "evidence_key": evidence_key,
310
+ }
311
+
312
+
313
+ def _usd_offer_copy_to_minor(value: Any) -> int:
314
+ if not isinstance(value, str):
315
+ raise ValueError("captured option quote is missing its USD price")
316
+ match = re.fullmatch(r"\$(\d+)\.(\d{2})", value)
317
+ if match is None:
318
+ raise ValueError("captured option quote has a malformed USD price")
319
+ return int(match.group(1)) * 100 + int(match.group(2))
320
+
321
+
322
+ def load_source_transaction_quote_specs(
323
+ fixture_root: Path,
324
+ ) -> dict[str, tuple[dict[str, Any], ...]]:
325
+ """Build the complete-selection transaction allow-list from source evidence.
326
+
327
+ Axis values remain available to the PDP renderer through
328
+ :func:`load_source_option_specs`, but this catalog contains only complete
329
+ combinations with enough evidence to create a server-side price quote.
330
+ Consequently, a captured label/value combination is not automatically a
331
+ purchasable Cartesian product.
332
+ """
333
+
334
+ fixture_root = fixture_root.resolve()
335
+ option_specs = load_source_option_specs(fixture_root)
336
+ fixture_names = ("task-frozen-900136-v1.json", "home-pdp-evidence.json")
337
+ products_by_asin: dict[str, dict[str, Any]] = {}
338
+ source_by_asin: dict[str, str] = {}
339
+ for fixture_name in fixture_names:
340
+ for product in _fixture_products(fixture_root, fixture_name):
341
+ asin = product.get("asin")
342
+ if not isinstance(asin, str) or not asin:
343
+ continue
344
+ products_by_asin[asin] = product
345
+ source_by_asin[asin] = fixture_name
346
+ for product in load_deals_default_card_offers(fixture_root):
347
+ asin = str(product["asin"])
348
+ if asin in products_by_asin:
349
+ raise ValueError(f"duplicate Deals transaction offer: {asin}")
350
+ products_by_asin[asin] = dict(product)
351
+ source_by_asin[asin] = DEALS_DEFAULT_CARDS_FIXTURE
352
+ for product in load_search_commerce_cards(fixture_root):
353
+ asin = str(product["asin"])
354
+ if asin in products_by_asin:
355
+ raise ValueError(f"duplicate search-card transaction offer: {asin}")
356
+ products_by_asin[asin] = dict(product)
357
+ source_by_asin[asin] = SEARCH_COMMERCE_FIXTURE
358
+ home_catalog = load_home_product_catalog(fixture_root)
359
+ for product in load_home_commerce_offers(fixture_root, home_catalog):
360
+ asin = str(product["asin"])
361
+ # A direct PDP, Deals, or search-card capture is richer evidence than
362
+ # the dated homepage offer snapshot. Keep that richer quote and add
363
+ # only the homepage offers that would otherwise have no transaction
364
+ # identity.
365
+ if asin in products_by_asin:
366
+ continue
367
+ products_by_asin[asin] = dict(product)
368
+ source_by_asin[asin] = HOME_COMMERCE_FIXTURE
369
+ for product in load_home_category_offers(fixture_root):
370
+ asin = str(product["asin"])
371
+ # Richer task, PDP, Deals, search, and homepage captures keep
372
+ # precedence on the five category-card overlaps. The category route
373
+ # still displays them using the authoritative stored quote.
374
+ if asin in products_by_asin:
375
+ continue
376
+ products_by_asin[asin] = dict(product)
377
+ source_by_asin[asin] = HOME_CATEGORY_FIXTURE
378
+
379
+ rules: dict[str, list[dict[str, Any]]] = {}
380
+
381
+ # Every verified source offer with no captured option axes has one complete
382
+ # selection: the empty selection. Its transaction price and image still
383
+ # come from the caller's server-owned base offer, never from the client.
384
+ for asin, product in products_by_asin.items():
385
+ if option_specs.get(asin):
386
+ continue
387
+ currency = product.get("currency")
388
+ if not isinstance(currency, str) or not currency:
389
+ raise ValueError(f"base transaction evidence has no currency: {asin}")
390
+ detail = product.get("pdp")
391
+ captured_availability = (
392
+ detail.get("availability") if isinstance(detail, Mapping) else None
393
+ )
394
+ display_availability = (
395
+ captured_availability
396
+ if isinstance(captured_availability, str) and captured_availability
397
+ else (
398
+ "In Stock"
399
+ if product.get("evidence_class") == SEARCH_COMMERCE_EVIDENCE_CLASS
400
+ else "In Stock"
401
+ )
402
+ )
403
+ rules[asin] = [
404
+ _base_quote_rule(
405
+ {},
406
+ offer_asin=asin,
407
+ currency=currency,
408
+ display_availability=display_availability,
409
+ evidence_key=str(
410
+ product.get("card_evidence_key")
411
+ or f"{source_by_asin[asin]}:{asin}:base-offer"
412
+ ),
413
+ )
414
+ ]
415
+
416
+ # New direct PDP captures can carry a declarative list of complete option
417
+ # quotes. Keeping those quotes beside the captured choices prevents this
418
+ # module from accumulating product-specific price tables and, more
419
+ # importantly, makes the evidence boundary explicit: an option may be
420
+ # browseable without becoming purchasable until a complete source quote is
421
+ # present here.
422
+ for asin, product in products_by_asin.items():
423
+ detail = product.get("pdp")
424
+ raw_quotes = detail.get("transaction_quotes") if isinstance(detail, Mapping) else None
425
+ if raw_quotes is None:
426
+ continue
427
+ if not isinstance(raw_quotes, list) or not raw_quotes:
428
+ raise ValueError(f"captured transaction quotes must be a non-empty list: {asin}")
429
+ spec = option_specs.get(asin)
430
+ if not spec:
431
+ raise ValueError(f"captured transaction quotes require option evidence: {asin}")
432
+ if product.get("currency") != "USD":
433
+ raise ValueError(f"captured transaction quotes require a USD product: {asin}")
434
+ default_image = product.get("image_path")
435
+ if not isinstance(default_image, str) or not default_image.startswith("/static/"):
436
+ raise ValueError(f"captured transaction quotes require a local image: {asin}")
437
+ captured_rules: list[dict[str, Any]] = []
438
+ seen_selections: set[str] = set()
439
+ for index, raw_quote in enumerate(raw_quotes):
440
+ if not isinstance(raw_quote, Mapping):
441
+ raise ValueError(f"captured transaction quote must be an object: {asin}[{index}]")
442
+ selection = normalize_complete_selection(spec, raw_quote.get("selected_options"))
443
+ selection_key = canonical_selection_key(selection)
444
+ if selection_key in seen_selections:
445
+ raise ValueError(f"duplicate captured transaction quote: {asin}[{index}]")
446
+ seen_selections.add(selection_key)
447
+ evidence_key = raw_quote.get("evidence_key")
448
+ if not isinstance(evidence_key, str) or not evidence_key.strip():
449
+ raise ValueError(f"captured transaction quote requires evidence: {asin}[{index}]")
450
+ display_availability = raw_quote.get("display_availability")
451
+ if not isinstance(display_availability, str) or not display_availability.strip():
452
+ display_availability = detail.get("availability")
453
+ if not isinstance(display_availability, str) or not display_availability.strip():
454
+ raise ValueError(f"captured transaction quote requires availability: {asin}[{index}]")
455
+ image_path = raw_quote.get("image_path", default_image)
456
+ captured_rules.append(
457
+ _captured_selection_quote_rule(
458
+ selection,
459
+ price_minor=raw_quote.get("price_minor"),
460
+ image_path=image_path,
461
+ display_availability=display_availability,
462
+ evidence_key=evidence_key,
463
+ )
464
+ )
465
+ rules[asin] = captured_rules
466
+
467
+ required_asins = {
468
+ TARGET_ASIN,
469
+ T9_ASIN,
470
+ SHEETS_ASIN,
471
+ OKAPI_ASIN,
472
+ SANDISK_ASIN,
473
+ BOOK_ASIN,
474
+ BEAUTY_ASIN,
475
+ INSTANT_POT_ASIN,
476
+ JANSPORT_ASIN,
477
+ AIR_FILTER_ASIN,
478
+ }
479
+ missing = required_asins - products_by_asin.keys()
480
+ if missing:
481
+ raise ValueError(
482
+ "required PDP transaction evidence is missing: " + ", ".join(sorted(missing))
483
+ )
484
+
485
+ # T7 has one default base quote plus one explicitly priced Blue/1 TB quote.
486
+ t7_default = default_selection(option_specs[TARGET_ASIN])
487
+ rules[TARGET_ASIN] = [
488
+ _base_quote_rule(
489
+ t7_default,
490
+ offer_asin=TARGET_ASIN,
491
+ currency="USD",
492
+ display_availability="In Stock",
493
+ evidence_key="task-frozen-900136-v1.json:B0874XN4D8:base-offer",
494
+ ),
495
+ _captured_selection_quote_rule(
496
+ {"Color": "Blue", "Memory Storage Capacity": "1 TB"},
497
+ price_minor=T7_BLUE_PRICE_MINOR,
498
+ image_path=T7_BLUE_IMAGE_PATH,
499
+ display_availability="In Stock",
500
+ evidence_key="source-current-2026-07-21:pdp-t7:Blue:1 TB",
501
+ ),
502
+ ]
503
+
504
+ # T9 and the sheet set expose captured axes, but only their current default
505
+ # selections have a complete source price/offer in the retained fixtures.
506
+ for asin in (T9_ASIN, SHEETS_ASIN):
507
+ product = products_by_asin[asin]
508
+ detail = product.get("pdp")
509
+ availability = detail.get("availability") if isinstance(detail, Mapping) else None
510
+ rules[asin] = [
511
+ _base_quote_rule(
512
+ default_selection(option_specs[asin]),
513
+ offer_asin=asin,
514
+ currency=str(product["currency"]),
515
+ display_availability=(
516
+ availability
517
+ if isinstance(availability, str) and availability
518
+ else "In Stock"
519
+ ),
520
+ evidence_key=f"{source_by_asin[asin]}:{asin}:base-offer",
521
+ )
522
+ ]
523
+
524
+ # The Books PDP exposes Kindle as a visible format choice, but the source
525
+ # handoff establishes a physical international offer only for Hardcover.
526
+ # Keep Kindle browseable in the PDP control while intentionally omitting a
527
+ # transaction quote for it; digital delivery must not inherit shipping or
528
+ # delivery semantics from the hardcover offer.
529
+ book = products_by_asin[BOOK_ASIN]
530
+ book_detail = book.get("pdp")
531
+ book_availability = (
532
+ book_detail.get("availability") if isinstance(book_detail, Mapping) else None
533
+ )
534
+ rules[BOOK_ASIN] = [
535
+ _base_quote_rule(
536
+ {"Format": "Hardcover"},
537
+ offer_asin=BOOK_ASIN,
538
+ currency=str(book["currency"]),
539
+ display_availability=(
540
+ book_availability
541
+ if isinstance(book_availability, str) and book_availability
542
+ else "In Stock"
543
+ ),
544
+ evidence_key="home-pdp-evidence.json:168281808X:Hardcover:base-offer",
545
+ )
546
+ ]
547
+
548
+ # Both Beauty size prices were captured as complete source offers. They
549
+ # share the base ASIN because no child ASIN was retained, so selection_key
550
+ # remains the server-owned cart/order identity.
551
+ beauty = products_by_asin[BEAUTY_ASIN]
552
+ beauty_detail = beauty.get("pdp")
553
+ beauty_availability = (
554
+ beauty_detail.get("availability")
555
+ if isinstance(beauty_detail, Mapping)
556
+ else None
557
+ )
558
+ beauty_image = str(beauty["image_path"])
559
+ rules[BEAUTY_ASIN] = [
560
+ _base_quote_rule(
561
+ {"Size": "36 Count (Pack of 1)"},
562
+ offer_asin=BEAUTY_ASIN,
563
+ currency=str(beauty["currency"]),
564
+ display_availability=(
565
+ beauty_availability
566
+ if isinstance(beauty_availability, str) and beauty_availability
567
+ else "In Stock"
568
+ ),
569
+ evidence_key="home-pdp-evidence.json:B074PVTPBW:36 Count (Pack of 1):base-offer",
570
+ ),
571
+ _captured_selection_quote_rule(
572
+ {"Size": "75 Count"},
573
+ price_minor=1_829,
574
+ image_path=beauty_image,
575
+ display_availability=(
576
+ beauty_availability
577
+ if isinstance(beauty_availability, str) and beauty_availability
578
+ else "In Stock"
579
+ ),
580
+ evidence_key="home-pdp-evidence.json:B074PVTPBW:75 Count",
581
+ ),
582
+ ]
583
+
584
+ # The current SanDisk PDP explicitly prices only the three color choices
585
+ # while Style=Old Model and Capacity=2TB are selected. Parse those prices
586
+ # and images from the fixture, and do not infer any other cross-product.
587
+ sandisk = products_by_asin[SANDISK_ASIN]
588
+ detail = sandisk.get("pdp")
589
+ groups = detail.get("choice_groups") if isinstance(detail, Mapping) else None
590
+ if not isinstance(groups, list):
591
+ raise ValueError("SanDisk option quote evidence has no choice groups")
592
+ groups_by_label = {
593
+ group.get("label"): group
594
+ for group in groups
595
+ if isinstance(group, Mapping) and isinstance(group.get("label"), str)
596
+ }
597
+ style_group = groups_by_label.get("Style")
598
+ capacity_group = groups_by_label.get("Capacity")
599
+ color_group = groups_by_label.get("Color")
600
+ if not all(isinstance(group, Mapping) for group in (style_group, capacity_group, color_group)):
601
+ raise ValueError("SanDisk option quote evidence is incomplete")
602
+ if style_group.get("value") != "Old Model" or capacity_group.get("value") != "2TB":
603
+ raise ValueError("SanDisk option quote evidence changed its captured selection")
604
+ raw_colors = color_group.get("options")
605
+ if not isinstance(raw_colors, list):
606
+ raise ValueError("SanDisk option quote evidence has no color prices")
607
+ colors = {
608
+ option.get("name"): option
609
+ for option in raw_colors
610
+ if isinstance(option, Mapping) and isinstance(option.get("name"), str)
611
+ }
612
+ expected_prices = {"Black": 31_699, "Monterey": 32_999, "Sky Blue": 32_999}
613
+ sandisk_rules: list[dict[str, Any]] = []
614
+ for color, expected_price in expected_prices.items():
615
+ option = colors.get(color)
616
+ if not isinstance(option, Mapping):
617
+ raise ValueError(f"SanDisk option quote evidence is missing {color}")
618
+ price_minor = _usd_offer_copy_to_minor(option.get("offer_copy"))
619
+ if price_minor != expected_price:
620
+ raise ValueError(f"SanDisk captured option price changed for {color}")
621
+ image_path = option.get("image")
622
+ sandisk_rules.append(
623
+ _captured_selection_quote_rule(
624
+ {"Style": "Old Model", "Capacity": "2TB", "Color": color},
625
+ price_minor=price_minor,
626
+ image_path=image_path,
627
+ display_availability=(
628
+ "In Stock"
629
+ ),
630
+ evidence_key=f"home-pdp-evidence.json:B08HN37XC1:Old Model:2TB:{color}",
631
+ )
632
+ )
633
+ rules[SANDISK_ASIN] = sandisk_rules
634
+
635
+ return {asin: tuple(entries) for asin, entries in rules.items()}
636
+
637
+
638
+ def resolve_transaction_quote(
639
+ asin: str,
640
+ selection: Mapping[str, Any] | None,
641
+ *,
642
+ option_specs: Mapping[str, tuple[dict[str, Any], ...]],
643
+ quote_specs: Mapping[str, tuple[dict[str, Any], ...]],
644
+ base_offer: Mapping[str, Any],
645
+ ) -> dict[str, Any] | None:
646
+ """Resolve one server-owned quote, or ``None`` for an unquoted combination.
647
+
648
+ The caller must supply the verified base commerce offer retrieved on the
649
+ server. Client price/image/availability fields are never accepted. A
650
+ complete combination may use captured UI values yet still return ``None``
651
+ when the retained evidence does not establish a transaction price.
652
+ """
653
+
654
+ if not isinstance(asin, str) or not asin:
655
+ raise ValueError("transaction quote requires an ASIN")
656
+ if not isinstance(base_offer, Mapping) or base_offer.get("asin") != asin:
657
+ raise ValueError("transaction quote requires the matching server base offer")
658
+ base_price = base_offer.get("price_minor")
659
+ if isinstance(base_price, bool) or not isinstance(base_price, int) or base_price < 0:
660
+ raise ValueError("server base offer has an invalid price")
661
+ base_currency = base_offer.get("currency")
662
+ if not isinstance(base_currency, str) or not base_currency:
663
+ raise ValueError("server base offer has an invalid currency")
664
+ base_image = base_offer.get("image_path")
665
+ if not isinstance(base_image, str) or not base_image.startswith("/static/"):
666
+ raise ValueError("server base offer has an invalid image")
667
+
668
+ normalized = normalize_complete_selection(option_specs.get(asin), selection)
669
+ matching_rule = next(
670
+ (
671
+ rule
672
+ for rule in quote_specs.get(asin, ())
673
+ if rule.get("selected_options") == normalized
674
+ ),
675
+ None,
676
+ )
677
+ if matching_rule is None:
678
+ return None
679
+ if matching_rule.get("currency") != base_currency:
680
+ raise ValueError("captured option quote currency does not match the base offer")
681
+
682
+ captured_price = matching_rule.get("price_minor")
683
+ price_minor = base_price if captured_price is None else captured_price
684
+ captured_image = matching_rule.get("image_path")
685
+ image_path = base_image if captured_image is None else captured_image
686
+ target_kind = str(matching_rule["target_kind"])
687
+ variant_asin = matching_rule.get("variant_asin")
688
+ return {
689
+ "asin": asin,
690
+ "selected_options": normalized,
691
+ "selection_key": canonical_selection_key(normalized),
692
+ "price_minor": price_minor,
693
+ "currency": base_currency,
694
+ "image_path": image_path,
695
+ "availability": str(matching_rule["availability"]),
696
+ "display_availability": str(matching_rule["display_availability"]),
697
+ "transaction_target": {
698
+ "kind": target_kind,
699
+ "offer_asin": asin,
700
+ "variant_asin": variant_asin,
701
+ "selection_key": canonical_selection_key(normalized),
702
+ },
703
+ "evidence_key": str(matching_rule["evidence_key"]),
704
+ }
tasks/amazon/solution/site/implementation/clone/render.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/solution/site/implementation/clone/review_catalog.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from copy import deepcopy
5
+ from functools import lru_cache
6
+ from html import escape
7
+ from pathlib import Path
8
+ from typing import Any, Iterable, Mapping
9
+ from urllib.parse import urlencode
10
+
11
+
12
+ FIXTURE_PATH = Path(__file__).resolve().parent / "fixtures" / "review-evidence.json"
13
+ SOURCE_AGGREGATE_PROVENANCE = "source_snapshot_aggregate"
14
+ LOCAL_REVIEW_PROVENANCE = "local_user_review"
15
+ REVIEW_SORTS = frozenset({"recent", "helpful"})
16
+
17
+
18
+ @lru_cache(maxsize=1)
19
+ def _fixture() -> dict[str, Any]:
20
+ payload = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
21
+ if payload.get("schema") != "amazon-clone.review-evidence.v1":
22
+ raise ValueError("Unsupported review evidence schema")
23
+ products = payload.get("products")
24
+ if not isinstance(products, dict):
25
+ raise ValueError("Review evidence products must be an object")
26
+ return payload
27
+
28
+
29
+ def supported_review_asins() -> tuple[str, ...]:
30
+ """Return ASINs with source-observed review aggregates."""
31
+
32
+ return tuple(_fixture()["products"])
33
+
34
+
35
+ def get_review_evidence(asin: str) -> dict[str, Any] | None:
36
+ """Return a caller-safe copy of an ASIN's immutable source evidence."""
37
+
38
+ product = _fixture()["products"].get(asin.upper())
39
+ return deepcopy(product) if product is not None else None
40
+
41
+
42
+ def _bounded_text(value: object, field: str, *, maximum: int) -> str:
43
+ if not isinstance(value, str):
44
+ raise ValueError(f"{field} must be text")
45
+ result = " ".join(value.split())
46
+ if not result:
47
+ raise ValueError(f"{field} must not be empty")
48
+ if len(result) > maximum:
49
+ raise ValueError(f"{field} is too long")
50
+ return result
51
+
52
+
53
+ def _boolean(review: Mapping[str, Any], field: str, default: bool) -> bool:
54
+ value = review.get(field, default)
55
+ if not isinstance(value, bool):
56
+ raise ValueError(f"{field} must be a boolean")
57
+ return value
58
+
59
+
60
+ def _normalize_local_review(review: Mapping[str, Any]) -> dict[str, Any]:
61
+ if review.get("provenance") != LOCAL_REVIEW_PROVENANCE:
62
+ raise ValueError("Local reviews must carry provenance=local_user_review")
63
+
64
+ rating = review.get("rating")
65
+ if isinstance(rating, bool) or not isinstance(rating, int) or not 1 <= rating <= 5:
66
+ raise ValueError("rating must be an integer from 1 to 5")
67
+ helpful_count = review.get("helpful_count", 0)
68
+ if (
69
+ isinstance(helpful_count, bool)
70
+ or not isinstance(helpful_count, int)
71
+ or helpful_count < 0
72
+ ):
73
+ raise ValueError("helpful_count must be a non-negative integer")
74
+
75
+ created_at = review.get("created_at", "")
76
+ updated_at = review.get("updated_at", created_at)
77
+ if created_at and not isinstance(created_at, str):
78
+ raise ValueError("created_at must be text")
79
+ if updated_at and not isinstance(updated_at, str):
80
+ raise ValueError("updated_at must be text")
81
+ review_id = review.get("id", "")
82
+ if review_id and not isinstance(review_id, (str, int)):
83
+ raise ValueError("id must be text or an integer")
84
+
85
+ verified_purchase = _boolean(review, "verified_purchase", False)
86
+ viewer_found_helpful = _boolean(review, "viewer_found_helpful", False)
87
+ owned_by_viewer = _boolean(review, "owned_by_viewer", False)
88
+ can_mark_helpful = _boolean(review, "can_mark_helpful", not owned_by_viewer)
89
+ if owned_by_viewer and can_mark_helpful:
90
+ raise ValueError("review owners cannot mark their own review helpful")
91
+
92
+ return {
93
+ "id": str(review_id),
94
+ "provenance": LOCAL_REVIEW_PROVENANCE,
95
+ "author_display_name": _bounded_text(
96
+ review.get("author_display_name"), "author_display_name", maximum=128
97
+ ),
98
+ "rating": rating,
99
+ "title": _bounded_text(review.get("title"), "title", maximum=200),
100
+ "body": _bounded_text(review.get("body"), "body", maximum=10000),
101
+ "created_at": created_at.strip(),
102
+ "updated_at": updated_at.strip(),
103
+ "verified_purchase": verified_purchase,
104
+ "helpful_count": helpful_count,
105
+ "viewer_found_helpful": viewer_found_helpful,
106
+ "owned_by_viewer": owned_by_viewer,
107
+ "can_mark_helpful": can_mark_helpful,
108
+ }
109
+
110
+
111
+ def normalize_local_reviews(
112
+ reviews: Iterable[Mapping[str, Any]], *, star: int | None = None
113
+ ) -> list[dict[str, Any]]:
114
+ """Validate local rows without allowing them to masquerade as source reviews."""
115
+
116
+ if star is not None and (isinstance(star, bool) or star not in range(1, 6)):
117
+ raise ValueError("star filter must be 1 through 5")
118
+ normalized = [_normalize_local_review(review) for review in reviews]
119
+ if star is not None:
120
+ normalized = [review for review in normalized if review["rating"] == star]
121
+ return normalized
122
+
123
+
124
+ def build_review_view(
125
+ asin: str,
126
+ local_reviews: Iterable[Mapping[str, Any]] = (),
127
+ *,
128
+ star: int | None = None,
129
+ product_label: str | None = None,
130
+ source_rating_summary: Mapping[str, Any] | None = None,
131
+ ) -> dict[str, Any] | None:
132
+ """Build a UI view while keeping source aggregates and local rows separate."""
133
+
134
+ evidence = get_review_evidence(asin)
135
+ known_product_label = None
136
+ if product_label is not None:
137
+ known_product_label = _bounded_text(
138
+ product_label, "product_label", maximum=1000
139
+ )
140
+ if source_rating_summary is not None and not isinstance(
141
+ source_rating_summary, Mapping
142
+ ):
143
+ raise ValueError("source_rating_summary must be a mapping")
144
+ captured_summary = (
145
+ evidence["rating_summary"]
146
+ if evidence is not None
147
+ else (dict(source_rating_summary) if source_rating_summary is not None else None)
148
+ )
149
+ if evidence is None and known_product_label is None and captured_summary is None:
150
+ return None
151
+ if star is not None and (isinstance(star, bool) or star not in range(1, 6)):
152
+ raise ValueError("star filter must be 1 through 5")
153
+
154
+ all_local = normalize_local_reviews(local_reviews)
155
+ filtered_local = (
156
+ all_local
157
+ if star is None
158
+ else [review for review in all_local if review["rating"] == star]
159
+ )
160
+ rating_total = sum(review["rating"] for review in all_local)
161
+ local_average = round(rating_total / len(all_local), 1) if all_local else None
162
+ local_by_star = {
163
+ value: sum(review["rating"] == value for review in all_local)
164
+ for value in range(5, 0, -1)
165
+ }
166
+
167
+ return {
168
+ "asin": asin.upper(),
169
+ "product_label": (
170
+ evidence["product_label"] if evidence is not None else known_product_label
171
+ ),
172
+ "source_aggregate_available": captured_summary is not None,
173
+ "source_rating_summary": captured_summary,
174
+ "source_histogram": evidence.get("histogram") if evidence is not None else None,
175
+ "source_topics": evidence.get("source_topics", []) if evidence is not None else [],
176
+ "source_topic_provenance": (
177
+ evidence.get("topic_provenance") if evidence is not None else None
178
+ ),
179
+ "source_excerpts": evidence.get("source_excerpts", []) if evidence is not None else [],
180
+ "individual_review_evidence": (
181
+ evidence["individual_review_evidence"]
182
+ if evidence is not None
183
+ else {
184
+ "available": False,
185
+ "missing_fields": [
186
+ "aggregate_rating",
187
+ "aggregate_count",
188
+ "author",
189
+ "title",
190
+ "date",
191
+ "rating",
192
+ "helpful_count",
193
+ ],
194
+ }
195
+ ),
196
+ "local_summary": {
197
+ "rating": local_average,
198
+ "review_count": len(all_local),
199
+ "provenance": LOCAL_REVIEW_PROVENANCE,
200
+ "count_by_star": local_by_star,
201
+ },
202
+ "owned_review": next(
203
+ (review for review in all_local if review["owned_by_viewer"]), None
204
+ ),
205
+ "local_reviews": filtered_local,
206
+ "active_star": star,
207
+ }
208
+
209
+
210
+ def _review_href(
211
+ asin: str,
212
+ *,
213
+ star: int | None,
214
+ sort: str,
215
+ base_path: str,
216
+ ) -> str:
217
+ query: dict[str, str] = {}
218
+ if star is not None:
219
+ query["reviewStar"] = str(star)
220
+ if sort != "recent":
221
+ query["reviewSort"] = sort
222
+ suffix = f"?{urlencode(query)}" if query else ""
223
+ return f"{base_path}{suffix}#customerReviews"
224
+
225
+
226
+ def _write_panel(
227
+ view: Mapping[str, Any], account_name: str | None, form_error: str | None
228
+ ) -> str:
229
+ asin = str(view["asin"])
230
+ error_html = (
231
+ f'<div class="review-form-error" role="alert">{escape(form_error)}</div>'
232
+ if form_error
233
+ else ""
234
+ )
235
+ if account_name is None:
236
+ signin_target = f"/product-reviews/{asin}#reviewComposer"
237
+ return (
238
+ '<section id="reviewComposer" class="review-write-panel review-signin-panel">'
239
+ '<h3>Review this product</h3>'
240
+ '<p>Share your experience with other shoppers.</p>'
241
+ '<a class="review-signin-cta" href="/ap/signin?'
242
+ + escape(urlencode({"openid.return_to": signin_target}), quote=True)
243
+ + '">Sign in to write a review</a></section>'
244
+ )
245
+
246
+ owned = view["owned_review"]
247
+ selected_rating = int(owned["rating"]) if owned else 5
248
+ rating_options = "".join(
249
+ f'<option value="{value}"{" selected" if value == selected_rating else ""}>'
250
+ f"{value} out of 5 stars</option>"
251
+ for value in range(5, 0, -1)
252
+ )
253
+ existing_title = escape(owned["title"] if owned else "", quote=True)
254
+ existing_body = escape(owned["body"] if owned else "")
255
+ return f"""
256
+ <section id="reviewComposer" class="review-write-panel">
257
+ <h3>{'Edit your review' if owned else 'Write a customer review'}</h3>
258
+ <p>Posting as <strong>{escape(account_name)}</strong>.</p>
259
+ {error_html}
260
+ <form class="review-write-form" method="post" action="/product-reviews/{asin}">
261
+ <label>Overall rating<select name="rating" required>{rating_options}</select></label>
262
+ <label>Add a headline<input name="headline" maxlength="200" required value="{existing_title}"></label>
263
+ <label>Add a written review<textarea name="body" maxlength="10000" rows="6" required>{existing_body}</textarea></label>
264
+ <button type="submit">{'Update review' if owned else 'Submit review'}</button>
265
+ </form>
266
+ </section>
267
+ """
268
+
269
+
270
+ def _local_review_card(asin: str, review: Mapping[str, Any]) -> str:
271
+ verified = (
272
+ '<span class="review-verified">Verified Purchase</span>'
273
+ if review["verified_purchase"]
274
+ else ""
275
+ )
276
+ date = (
277
+ f'<time datetime="{escape(review["created_at"], quote=True)}">'
278
+ f'{escape(review["created_at"])}</time>'
279
+ if review["created_at"]
280
+ else ""
281
+ )
282
+ edited = (
283
+ '<span class="review-edited">Edited</span>'
284
+ if review["updated_at"] and review["updated_at"] != review["created_at"]
285
+ else ""
286
+ )
287
+ if review["owned_by_viewer"]:
288
+ helpful_action = (
289
+ '<button class="review-helpful-button" type="button" disabled '
290
+ 'title="You cannot mark your own review as helpful">Your review</button>'
291
+ )
292
+ elif review["can_mark_helpful"]:
293
+ pressed = "true" if review["viewer_found_helpful"] else "false"
294
+ label = "Helpful ✓" if review["viewer_found_helpful"] else "Helpful"
295
+ helpful_action = (
296
+ f'<form class="review-helpful-form" method="post" action="/product-reviews/{asin}/helpful">'
297
+ f'<input type="hidden" name="reviewId" value="{escape(review["id"], quote=True)}">'
298
+ f'<button class="review-helpful-button" type="submit" aria-pressed="{pressed}">{label}</button>'
299
+ "</form>"
300
+ )
301
+ else:
302
+ helpful_action = ""
303
+
304
+ return (
305
+ '<article class="local-review-card" '
306
+ f'data-viewer-found-helpful="{str(review["viewer_found_helpful"]).lower()}" '
307
+ f'data-owned-by-viewer="{str(review["owned_by_viewer"]).lower()}" '
308
+ f'data-can-mark-helpful="{str(review["can_mark_helpful"]).lower()}">'
309
+ f'<div class="review-author">{escape(review["author_display_name"])}</div>'
310
+ f'<div class="review-card-rating" aria-label="{review["rating"]} out of 5 stars">'
311
+ f'{"★" * review["rating"]}{"☆" * (5 - review["rating"])}</div>'
312
+ f'<h4>{escape(review["title"])}</h4>'
313
+ f'<div class="review-card-meta">{verified}{date}{edited}</div>'
314
+ f'<p>{escape(review["body"])}</p>'
315
+ '<div class="review-card-actions">'
316
+ f'<span class="review-helpful">{review["helpful_count"]} people found this helpful</span>'
317
+ f"{helpful_action}</div></article>"
318
+ )
319
+
320
+
321
+ def _source_rating_summary_html(summary: Mapping[str, Any]) -> str:
322
+ """Render a captured aggregate without manufacturing a rating for zero reviews."""
323
+
324
+ rating = summary.get("rating")
325
+ rating_count = summary.get("rating_count")
326
+ rating_count_display = summary.get("rating_count_display")
327
+ if rating_count is None:
328
+ if not isinstance(rating_count_display, str) or not rating_count_display.strip():
329
+ raise ValueError(
330
+ "source rating_count needs an exact integer or captured display copy"
331
+ )
332
+ display_count = rating_count_display.strip()
333
+ elif (
334
+ isinstance(rating_count, bool)
335
+ or not isinstance(rating_count, int)
336
+ or rating_count < 0
337
+ ):
338
+ raise ValueError("source rating_count must be a non-negative integer")
339
+ else:
340
+ display_count = (
341
+ rating_count_display.strip()
342
+ if isinstance(rating_count_display, str) and rating_count_display.strip()
343
+ else f"{rating_count:,}"
344
+ )
345
+
346
+ if rating is None:
347
+ if rating_count != 0:
348
+ raise ValueError("a missing source rating is valid only with zero ratings")
349
+ zero_copy = summary.get("zero_rating_copy")
350
+ if not isinstance(zero_copy, str) or not zero_copy.strip():
351
+ zero_copy = f"There are {rating_count:,} customer reviews"
352
+ return (
353
+ '<div class="review-no-source-rating">'
354
+ f"{escape(zero_copy.strip())}</div>"
355
+ )
356
+
357
+ if (
358
+ isinstance(rating, bool)
359
+ or not isinstance(rating, (int, float))
360
+ or not 1 <= rating <= 5
361
+ ):
362
+ raise ValueError("source rating must be null or a number from 1 to 5")
363
+ count_label = summary.get("count_label")
364
+ if not isinstance(count_label, str) or not count_label.strip():
365
+ raise ValueError("source count_label must be non-empty text")
366
+ display_rating = str(rating)
367
+ return (
368
+ f'<div class="review-average" aria-label="{display_rating} out of 5 stars">'
369
+ '<span aria-hidden="true">★★★★★</span>'
370
+ f"<strong>{display_rating} out of 5</strong></div>"
371
+ f"<div>{escape(display_count)} {escape(count_label.strip())}</div>"
372
+ )
373
+
374
+
375
+ def render_reviews_section(
376
+ asin: str,
377
+ local_reviews: Iterable[Mapping[str, Any]] = (),
378
+ *,
379
+ star: int | None = None,
380
+ sort: str = "recent",
381
+ account_name: str | None = None,
382
+ base_path: str | None = None,
383
+ form_error: str | None = None,
384
+ product_label: str | None = None,
385
+ source_rating_summary: Mapping[str, Any] | None = None,
386
+ ) -> str:
387
+ """Render source aggregates and separately attributed local review rows."""
388
+
389
+ view = build_review_view(
390
+ asin,
391
+ local_reviews,
392
+ star=star,
393
+ product_label=product_label,
394
+ source_rating_summary=source_rating_summary,
395
+ )
396
+ if view is None:
397
+ return ""
398
+ if sort not in REVIEW_SORTS:
399
+ raise ValueError("review sort must be recent or helpful")
400
+ review_base_path = base_path or f"/dp/{view['asin']}"
401
+ if (
402
+ not review_base_path.startswith("/")
403
+ or review_base_path.startswith("//")
404
+ or "\\" in review_base_path
405
+ ):
406
+ raise ValueError("review base path must be a same-origin path")
407
+
408
+ source_aggregate_available = bool(view["source_aggregate_available"])
409
+ summary = view["source_rating_summary"]
410
+ source_summary_html = (
411
+ _source_rating_summary_html(summary)
412
+ if source_aggregate_available and isinstance(summary, Mapping)
413
+ else ""
414
+ )
415
+ histogram = view["source_histogram"]
416
+ histogram_html = ""
417
+ if histogram:
418
+ histogram_rows = []
419
+ for value in range(5, 0, -1):
420
+ percent = histogram["percent_by_star"][str(value)]
421
+ href = _review_href(
422
+ view["asin"],
423
+ star=value,
424
+ sort=sort,
425
+ base_path=review_base_path,
426
+ )
427
+ histogram_rows.append(
428
+ '<a class="review-histogram-row" '
429
+ f'href="{escape(href, quote=True)}" data-review-star-filter="{value}">'
430
+ f"<span>{value} star</span>"
431
+ '<progress class="review-histogram-track" max="100" '
432
+ f'value="{percent}" aria-label="{percent} percent"></progress>'
433
+ f"<span>{percent}%</span></a>"
434
+ )
435
+ histogram_html = (
436
+ '<div class="review-histogram">' + "".join(histogram_rows) + "</div>"
437
+ )
438
+
439
+ topics_html = ""
440
+ if view["source_topics"]:
441
+ topics = "".join(
442
+ '<li><span class="review-topic-label">'
443
+ f'{escape(topic["label"])}</span> '
444
+ f'<span class="review-topic-count">{topic["mentions"]:,}</span></li>'
445
+ for topic in view["source_topics"]
446
+ )
447
+ topics_html = (
448
+ '<div class="review-topics"><h3>Customers say</h3>'
449
+ f'<ul aria-label="Common review topics">{topics}</ul></div>'
450
+ )
451
+
452
+ filters: list[str] = []
453
+ for value, label in ((None, "All stars"), (5, "5 star"), (4, "4 star"), (3, "3 star"), (2, "2 star"), (1, "1 star")):
454
+ href = _review_href(
455
+ view["asin"], star=value, sort=sort, base_path=review_base_path
456
+ )
457
+ active = ' aria-current="page"' if star == value else ""
458
+ data_value = "all" if value is None else str(value)
459
+ filters.append(
460
+ f'<a href="{escape(href, quote=True)}" data-review-star-filter="{data_value}"{active}>{label}</a>'
461
+ )
462
+
463
+ sort_links = []
464
+ for value, label in (("recent", "Most recent"), ("helpful", "Most helpful")):
465
+ href = _review_href(
466
+ view["asin"], star=star, sort=value, base_path=review_base_path
467
+ )
468
+ active = ' aria-current="page"' if sort == value else ""
469
+ sort_links.append(
470
+ f'<a href="{escape(href, quote=True)}" data-review-sort="{value}"{active}>{label}</a>'
471
+ )
472
+
473
+ local_cards = "".join(
474
+ _local_review_card(view["asin"], review)
475
+ for review in view["local_reviews"]
476
+ )
477
+ local_reviews_html = (
478
+ local_cards
479
+ if local_cards
480
+ else '<p class="review-empty">No customer reviews match this filter yet.</p>'
481
+ )
482
+ local_count = view["local_summary"]["review_count"]
483
+ write_panel = _write_panel(view, account_name, form_error)
484
+ rating_summary_html = (
485
+ f"""
486
+ <div class="review-summary-layout">
487
+ <div class="review-source-summary">
488
+ {source_summary_html}
489
+ {histogram_html}
490
+ </div>
491
+ {topics_html}
492
+ </div>
493
+ """
494
+ if source_aggregate_available
495
+ else '<p class="review-empty">There are no customer ratings for this item yet.</p>'
496
+ )
497
+
498
+ return f"""
499
+ <section id="customerReviews" class="customer-reviews" data-asin="{escape(view['asin'], quote=True)}">
500
+ <h2>Customer reviews</h2>
501
+ {rating_summary_html}
502
+ {write_panel}
503
+ <div class="review-local-list">
504
+ <div class="review-local-heading"><div><h3>Customer reviews</h3></div><span>{local_count} reviews</span></div>
505
+ <div class="review-toolbar">
506
+ <nav class="review-filters" aria-label="Filter customer reviews">{''.join(filters)}</nav>
507
+ <nav class="review-sorts" aria-label="Sort customer reviews">{''.join(sort_links)}</nav>
508
+ </div>
509
+ {local_reviews_html}
510
+ </div>
511
+ </section>
512
+ """
513
+
514
+
515
+ __all__ = [
516
+ "FIXTURE_PATH",
517
+ "LOCAL_REVIEW_PROVENANCE",
518
+ "SOURCE_AGGREGATE_PROVENANCE",
519
+ "build_review_view",
520
+ "get_review_evidence",
521
+ "normalize_local_reviews",
522
+ "render_reviews_section",
523
+ "supported_review_asins",
524
+ ]
tasks/amazon/solution/site/implementation/clone/review_store.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable local customer reviews for the Amazon clone.
2
+
3
+ This module is deliberately independent from :mod:`store` so its schema can be
4
+ installed into an existing clone database without rewriting the core schema.
5
+ Call :func:`install_schema` once during database startup, after ``schema.sql``
6
+ has created ``accounts``, ``browser_sessions``, ``catalog_products``,
7
+ ``commerce_offers``, ``orders``, and ``order_items``.
8
+
9
+ Request handlers must pass the server-side session digest, never an account id
10
+ from a form. Review ownership is resolved through ``browser_sessions`` and
11
+ ``verified_purchase`` is derived at read time from placed orders. Consequently
12
+ neither value can be asserted by a client.
13
+
14
+ For a full benchmark reset, call :func:`reset_review_data` before clearing the
15
+ core tables. Deleting ``accounts`` with foreign keys enabled also cascades all
16
+ reviews and votes, but the explicit reset is clearer and remains safe if the
17
+ core reset order changes. Schema installation is idempotent and refuses an
18
+ unknown review-schema version instead of destructively guessing a migration.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ import sqlite3
25
+ from datetime import datetime, timezone
26
+ from typing import Any
27
+
28
+
29
+ LOCAL_REVIEW_PROVENANCE = "local_user_review"
30
+ REVIEW_SCHEMA_VERSION = 1
31
+ MAX_HEADLINE_LENGTH = 200
32
+ MAX_BODY_LENGTH = 10_000
33
+ REVIEW_SORT_RECENT = "recent"
34
+ REVIEW_SORT_HELPFUL = "helpful"
35
+ REVIEW_SORTS = frozenset({REVIEW_SORT_RECENT, REVIEW_SORT_HELPFUL})
36
+ REVIEW_PRODUCT_SCOPES = frozenset(
37
+ {"catalog_product", "commerce_offer", "home_snapshot"}
38
+ )
39
+
40
+ _ASIN_PATTERN = re.compile(r"^[A-Z0-9]{10}$")
41
+
42
+
43
+ class ReviewStoreError(ValueError):
44
+ """Base class for expected review-domain failures."""
45
+
46
+
47
+ class ReviewValidationError(ReviewStoreError):
48
+ """A submitted review field or query option is invalid."""
49
+
50
+
51
+ class ReviewAuthenticationRequired(ReviewStoreError):
52
+ """The browser session exists but is not signed in."""
53
+
54
+
55
+ class ReviewNotFound(ReviewStoreError):
56
+ """A referenced session, product, or review does not exist."""
57
+
58
+
59
+ class ReviewPermissionDenied(ReviewStoreError):
60
+ """The current actor is not allowed to perform the operation."""
61
+
62
+
63
+ class ReviewSchemaError(RuntimeError):
64
+ """The installed review schema is incompatible with this module."""
65
+
66
+
67
+ _BASE_SCHEMA = """
68
+ CREATE TABLE IF NOT EXISTS local_review_schema_meta (
69
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
70
+ schema_version INTEGER NOT NULL CHECK (schema_version > 0)
71
+ );
72
+
73
+ INSERT OR IGNORE INTO local_review_schema_meta(singleton, schema_version)
74
+ VALUES (1, 1);
75
+
76
+ CREATE TABLE IF NOT EXISTS product_reviews (
77
+ review_id INTEGER PRIMARY KEY AUTOINCREMENT,
78
+ account_id INTEGER NOT NULL
79
+ REFERENCES accounts(account_id) ON DELETE CASCADE,
80
+ asin TEXT NOT NULL COLLATE NOCASE,
81
+ rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
82
+ headline TEXT NOT NULL CHECK (
83
+ length(trim(headline)) BETWEEN 1 AND 200
84
+ ),
85
+ body TEXT NOT NULL CHECK (
86
+ length(trim(body)) BETWEEN 1 AND 10000
87
+ ),
88
+ created_at TEXT NOT NULL,
89
+ updated_at TEXT NOT NULL,
90
+ UNIQUE (account_id, asin)
91
+ );
92
+
93
+ -- Browse-only products intentionally stay out of commerce_offers. This
94
+ -- server-owned registry lets those known PDPs accept local reviews without
95
+ -- turning them into purchasable inventory or trusting an ASIN from a form.
96
+ CREATE TABLE IF NOT EXISTS review_product_catalog (
97
+ asin TEXT PRIMARY KEY COLLATE NOCASE CHECK (
98
+ length(asin) = 10 AND asin NOT GLOB '*[^A-Z0-9]*'
99
+ ),
100
+ source_scope TEXT NOT NULL CHECK (
101
+ source_scope IN ('catalog_product', 'commerce_offer', 'home_snapshot')
102
+ )
103
+ );
104
+
105
+ CREATE TABLE IF NOT EXISTS review_helpful_votes (
106
+ vote_id INTEGER PRIMARY KEY AUTOINCREMENT,
107
+ review_id INTEGER NOT NULL
108
+ REFERENCES product_reviews(review_id) ON DELETE CASCADE,
109
+ voter_account_id INTEGER
110
+ REFERENCES accounts(account_id) ON DELETE CASCADE,
111
+ voter_session_digest TEXT
112
+ REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
113
+ created_at TEXT NOT NULL,
114
+ CHECK (
115
+ (voter_account_id IS NOT NULL AND voter_session_digest IS NULL)
116
+ OR
117
+ (voter_account_id IS NULL AND voter_session_digest IS NOT NULL)
118
+ )
119
+ );
120
+ """
121
+
122
+
123
+ _INDEXES_AND_TRIGGERS = """
124
+ CREATE INDEX IF NOT EXISTS product_reviews_asin_recent_idx
125
+ ON product_reviews(asin, created_at DESC, review_id DESC);
126
+ CREATE INDEX IF NOT EXISTS product_reviews_asin_rating_idx
127
+ ON product_reviews(asin, rating, created_at DESC, review_id DESC);
128
+ CREATE INDEX IF NOT EXISTS review_helpful_votes_review_idx
129
+ ON review_helpful_votes(review_id);
130
+
131
+ CREATE UNIQUE INDEX IF NOT EXISTS review_helpful_votes_account_unique_idx
132
+ ON review_helpful_votes(review_id, voter_account_id)
133
+ WHERE voter_account_id IS NOT NULL;
134
+ CREATE UNIQUE INDEX IF NOT EXISTS review_helpful_votes_session_unique_idx
135
+ ON review_helpful_votes(review_id, voter_session_digest)
136
+ WHERE voter_account_id IS NULL;
137
+
138
+ -- Trigger bodies changed when the browse-only review scope was added. Drop
139
+ -- the old v1 definitions so existing databases receive the additive guard.
140
+ DROP TRIGGER IF EXISTS product_reviews_product_guard_insert;
141
+ DROP TRIGGER IF EXISTS product_reviews_product_guard_update;
142
+ DROP TRIGGER IF EXISTS product_reviews_catalog_product_cleanup;
143
+ DROP TRIGGER IF EXISTS product_reviews_commerce_offer_cleanup;
144
+ DROP TRIGGER IF EXISTS product_reviews_scope_cleanup;
145
+
146
+ CREATE TRIGGER product_reviews_product_guard_insert
147
+ BEFORE INSERT ON product_reviews
148
+ WHEN NOT EXISTS (
149
+ SELECT 1 FROM catalog_products WHERE asin = NEW.asin
150
+ )
151
+ AND NOT EXISTS (
152
+ SELECT 1 FROM commerce_offers WHERE asin = NEW.asin
153
+ )
154
+ AND NOT EXISTS (
155
+ SELECT 1 FROM review_product_catalog WHERE asin = NEW.asin
156
+ )
157
+ BEGIN
158
+ SELECT RAISE(ABORT, 'review product does not exist');
159
+ END;
160
+
161
+ CREATE TRIGGER product_reviews_product_guard_update
162
+ BEFORE UPDATE OF asin ON product_reviews
163
+ WHEN NOT EXISTS (
164
+ SELECT 1 FROM catalog_products WHERE asin = NEW.asin
165
+ )
166
+ AND NOT EXISTS (
167
+ SELECT 1 FROM commerce_offers WHERE asin = NEW.asin
168
+ )
169
+ AND NOT EXISTS (
170
+ SELECT 1 FROM review_product_catalog WHERE asin = NEW.asin
171
+ )
172
+ BEGIN
173
+ SELECT RAISE(ABORT, 'review product does not exist');
174
+ END;
175
+
176
+ CREATE TRIGGER IF NOT EXISTS review_helpful_votes_no_self_insert
177
+ BEFORE INSERT ON review_helpful_votes
178
+ WHEN NEW.voter_account_id IS NOT NULL
179
+ AND EXISTS (
180
+ SELECT 1
181
+ FROM product_reviews
182
+ WHERE review_id = NEW.review_id
183
+ AND account_id = NEW.voter_account_id
184
+ )
185
+ BEGIN
186
+ SELECT RAISE(ABORT, 'review authors cannot vote for their own review');
187
+ END;
188
+
189
+ -- Reviews disappear only when an ASIN is absent from every server-owned
190
+ -- product scope. Deleting one overlapping source cannot erase valid rows.
191
+ CREATE TRIGGER product_reviews_catalog_product_cleanup
192
+ AFTER DELETE ON catalog_products
193
+ WHEN NOT EXISTS (
194
+ SELECT 1 FROM commerce_offers WHERE asin = OLD.asin
195
+ )
196
+ AND NOT EXISTS (
197
+ SELECT 1 FROM review_product_catalog WHERE asin = OLD.asin
198
+ )
199
+ BEGIN
200
+ DELETE FROM product_reviews WHERE asin = OLD.asin;
201
+ END;
202
+
203
+ CREATE TRIGGER product_reviews_commerce_offer_cleanup
204
+ AFTER DELETE ON commerce_offers
205
+ WHEN NOT EXISTS (
206
+ SELECT 1 FROM catalog_products WHERE asin = OLD.asin
207
+ )
208
+ AND NOT EXISTS (
209
+ SELECT 1 FROM review_product_catalog WHERE asin = OLD.asin
210
+ )
211
+ BEGIN
212
+ DELETE FROM product_reviews WHERE asin = OLD.asin;
213
+ END;
214
+
215
+ CREATE TRIGGER product_reviews_scope_cleanup
216
+ AFTER DELETE ON review_product_catalog
217
+ WHEN NOT EXISTS (
218
+ SELECT 1 FROM catalog_products WHERE asin = OLD.asin
219
+ )
220
+ AND NOT EXISTS (
221
+ SELECT 1 FROM commerce_offers WHERE asin = OLD.asin
222
+ )
223
+ BEGIN
224
+ DELETE FROM product_reviews WHERE asin = OLD.asin;
225
+ END;
226
+ """
227
+
228
+
229
+ _EXPECTED_COLUMNS = {
230
+ "review_product_catalog": {"asin", "source_scope"},
231
+ "product_reviews": {
232
+ "review_id",
233
+ "account_id",
234
+ "asin",
235
+ "rating",
236
+ "headline",
237
+ "body",
238
+ "created_at",
239
+ "updated_at",
240
+ },
241
+ "review_helpful_votes": {
242
+ "vote_id",
243
+ "review_id",
244
+ "voter_account_id",
245
+ "voter_session_digest",
246
+ "created_at",
247
+ },
248
+ }
249
+
250
+
251
+ def install_schema(conn: sqlite3.Connection) -> None:
252
+ """Install the additive v1 schema and validate an existing installation.
253
+
254
+ Run this outside an active request transaction: ``executescript`` owns the
255
+ DDL transaction boundary in Python's SQLite driver. No core row is changed.
256
+ """
257
+
258
+ conn.execute("PRAGMA foreign_keys = ON")
259
+ conn.executescript(_BASE_SCHEMA)
260
+ version_row = conn.execute(
261
+ "SELECT schema_version FROM local_review_schema_meta WHERE singleton=?",
262
+ (1,),
263
+ ).fetchone()
264
+ if version_row is None or int(version_row[0]) != REVIEW_SCHEMA_VERSION:
265
+ found = None if version_row is None else version_row[0]
266
+ raise ReviewSchemaError(
267
+ f"unsupported local review schema version: {found!r}"
268
+ )
269
+
270
+ for table, expected in _EXPECTED_COLUMNS.items():
271
+ actual = {
272
+ str(row[1]) for row in conn.execute(f"PRAGMA table_info({table})")
273
+ }
274
+ missing = expected - actual
275
+ if missing:
276
+ raise ReviewSchemaError(
277
+ f"{table} is missing required columns: {', '.join(sorted(missing))}"
278
+ )
279
+ conn.executescript(_INDEXES_AND_TRIGGERS)
280
+
281
+
282
+ def reset_review_data(conn: sqlite3.Connection) -> None:
283
+ """Remove mutable review data while preserving the installed schema."""
284
+
285
+ conn.execute("DELETE FROM review_helpful_votes")
286
+ conn.execute("DELETE FROM product_reviews")
287
+ conn.execute("DELETE FROM review_product_catalog")
288
+
289
+
290
+ def _normalize_asin(value: object) -> str:
291
+ if not isinstance(value, str):
292
+ raise ReviewValidationError("asin must be text")
293
+ asin = value.strip().upper()
294
+ if not _ASIN_PATTERN.fullmatch(asin):
295
+ raise ReviewValidationError("asin must contain 10 ASCII letters or digits")
296
+ return asin
297
+
298
+
299
+ def register_review_product(
300
+ conn: sqlite3.Connection, *, asin: str, source_scope: str
301
+ ) -> str:
302
+ """Register one server-known browse/product scope for local reviews.
303
+
304
+ This is a privileged catalog operation, not a request-form operation. It
305
+ deliberately stores no offer, rating, review count, author, or excerpt.
306
+ """
307
+
308
+ normalized_asin = _normalize_asin(asin)
309
+ if source_scope not in REVIEW_PRODUCT_SCOPES:
310
+ raise ReviewValidationError("unsupported review product source scope")
311
+ conn.execute(
312
+ """
313
+ INSERT INTO review_product_catalog(asin,source_scope)
314
+ VALUES (?,?)
315
+ ON CONFLICT(asin) DO UPDATE SET source_scope=excluded.source_scope
316
+ """,
317
+ (normalized_asin, source_scope),
318
+ )
319
+ return normalized_asin
320
+
321
+
322
+ def _normalize_session_digest(value: object) -> str:
323
+ if not isinstance(value, str) or not value.strip():
324
+ raise ReviewValidationError("session_digest must be non-empty text")
325
+ return value.strip()
326
+
327
+
328
+ def _normalize_review_id(value: object) -> int:
329
+ if isinstance(value, bool):
330
+ raise ReviewValidationError("review_id must be a positive integer")
331
+ if isinstance(value, int):
332
+ review_id = value
333
+ elif isinstance(value, str) and value.isascii() and value.isdecimal():
334
+ review_id = int(value)
335
+ else:
336
+ raise ReviewValidationError("review_id must be a positive integer")
337
+ if review_id <= 0:
338
+ raise ReviewValidationError("review_id must be a positive integer")
339
+ return review_id
340
+
341
+
342
+ def _normalize_rating(value: object) -> int:
343
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 5:
344
+ raise ReviewValidationError("rating must be an integer from 1 to 5")
345
+ return value
346
+
347
+
348
+ def _normalize_headline(value: object) -> str:
349
+ if not isinstance(value, str):
350
+ raise ReviewValidationError("headline must be text")
351
+ headline = " ".join(value.split())
352
+ if not headline:
353
+ raise ReviewValidationError("headline must not be empty")
354
+ if len(headline) > MAX_HEADLINE_LENGTH:
355
+ raise ReviewValidationError(
356
+ f"headline must be at most {MAX_HEADLINE_LENGTH} characters"
357
+ )
358
+ return headline
359
+
360
+
361
+ def _normalize_body(value: object) -> str:
362
+ if not isinstance(value, str):
363
+ raise ReviewValidationError("body must be text")
364
+ body = value.replace("\r\n", "\n").replace("\r", "\n").strip()
365
+ if not body:
366
+ raise ReviewValidationError("body must not be empty")
367
+ if len(body) > MAX_BODY_LENGTH:
368
+ raise ReviewValidationError(
369
+ f"body must be at most {MAX_BODY_LENGTH} characters"
370
+ )
371
+ return body
372
+
373
+
374
+ def _timestamp(value: str | None) -> str:
375
+ if value is None:
376
+ return (
377
+ datetime.now(timezone.utc)
378
+ .isoformat(timespec="seconds")
379
+ .replace("+00:00", "Z")
380
+ )
381
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > 64:
382
+ raise ReviewValidationError("at must be a non-empty timestamp string")
383
+ return value.strip()
384
+
385
+
386
+ def _account_for_session(
387
+ conn: sqlite3.Connection,
388
+ session_digest: str,
389
+ *,
390
+ require_authenticated: bool,
391
+ ) -> int | None:
392
+ row = conn.execute(
393
+ "SELECT account_id FROM browser_sessions WHERE session_digest=?",
394
+ (session_digest,),
395
+ ).fetchone()
396
+ if row is None:
397
+ raise ReviewNotFound("browser session does not exist")
398
+ account_id = None if row[0] is None else int(row[0])
399
+ if require_authenticated and account_id is None:
400
+ raise ReviewAuthenticationRequired("sign in before writing a review")
401
+ return account_id
402
+
403
+
404
+ def _product_exists(conn: sqlite3.Connection, asin: str) -> bool:
405
+ row = conn.execute(
406
+ """
407
+ SELECT EXISTS(
408
+ SELECT 1 FROM catalog_products WHERE asin=?
409
+ UNION ALL
410
+ SELECT 1 FROM commerce_offers WHERE asin=?
411
+ UNION ALL
412
+ SELECT 1 FROM review_product_catalog WHERE asin=?
413
+ )
414
+ """,
415
+ (asin, asin, asin),
416
+ ).fetchone()
417
+ return bool(row and row[0])
418
+
419
+
420
+ def _review_query(
421
+ conn: sqlite3.Connection,
422
+ *,
423
+ where_sql: str,
424
+ where_params: tuple[object, ...],
425
+ viewer_session_digest: str | None,
426
+ order_sql: str,
427
+ ) -> list[dict[str, Any]]:
428
+ viewer_account_id: int | None = None
429
+ viewer_guest_session: str | None = None
430
+ if viewer_session_digest is not None:
431
+ normalized_session = _normalize_session_digest(viewer_session_digest)
432
+ viewer_account_id = _account_for_session(
433
+ conn, normalized_session, require_authenticated=False
434
+ )
435
+ if viewer_account_id is None:
436
+ viewer_guest_session = normalized_session
437
+
438
+ cursor = conn.execute(
439
+ f"""
440
+ SELECT
441
+ r.review_id,
442
+ r.account_id AS reviewer_account_id,
443
+ a.display_name AS author_display_name,
444
+ r.rating,
445
+ r.headline,
446
+ r.body,
447
+ r.created_at,
448
+ r.updated_at,
449
+ EXISTS(
450
+ SELECT 1
451
+ FROM orders o
452
+ JOIN order_items oi ON oi.order_id=o.order_id
453
+ LEFT JOIN shipments shipment ON shipment.order_id=o.order_id
454
+ WHERE o.account_id=r.account_id
455
+ AND o.status='PLACED'
456
+ AND COALESCE(shipment.lifecycle_status,'PREPARING')<>'CANCELLED'
457
+ AND oi.asin=r.asin
458
+ ) AS verified_purchase,
459
+ (
460
+ SELECT COUNT(*)
461
+ FROM review_helpful_votes hv
462
+ WHERE hv.review_id=r.review_id
463
+ ) AS helpful_count,
464
+ CASE
465
+ WHEN ? IS NOT NULL THEN EXISTS(
466
+ SELECT 1 FROM review_helpful_votes own_vote
467
+ WHERE own_vote.review_id=r.review_id
468
+ AND own_vote.voter_account_id=?
469
+ )
470
+ WHEN ? IS NOT NULL THEN EXISTS(
471
+ SELECT 1 FROM review_helpful_votes own_vote
472
+ WHERE own_vote.review_id=r.review_id
473
+ AND own_vote.voter_session_digest=?
474
+ )
475
+ ELSE 0
476
+ END AS viewer_found_helpful
477
+ FROM product_reviews r
478
+ JOIN accounts a ON a.account_id=r.account_id
479
+ WHERE {where_sql}
480
+ ORDER BY {order_sql}
481
+ """,
482
+ (
483
+ viewer_account_id,
484
+ viewer_account_id,
485
+ viewer_guest_session,
486
+ viewer_guest_session,
487
+ *where_params,
488
+ ),
489
+ )
490
+ names = [str(description[0]) for description in cursor.description]
491
+ result: list[dict[str, Any]] = []
492
+ for raw_row in cursor.fetchall():
493
+ row = dict(zip(names, raw_row))
494
+ reviewer_account_id = int(row.pop("reviewer_account_id"))
495
+ owned_by_viewer = (
496
+ viewer_account_id is not None
497
+ and reviewer_account_id == viewer_account_id
498
+ )
499
+ result.append(
500
+ {
501
+ "id": str(row["review_id"]),
502
+ "provenance": LOCAL_REVIEW_PROVENANCE,
503
+ "author_display_name": str(row["author_display_name"]),
504
+ "rating": int(row["rating"]),
505
+ "title": str(row["headline"]),
506
+ "body": str(row["body"]),
507
+ "created_at": str(row["created_at"]),
508
+ "updated_at": str(row["updated_at"]),
509
+ "verified_purchase": bool(row["verified_purchase"]),
510
+ "helpful_count": int(row["helpful_count"]),
511
+ "viewer_found_helpful": bool(row["viewer_found_helpful"]),
512
+ "owned_by_viewer": owned_by_viewer,
513
+ "can_mark_helpful": not owned_by_viewer,
514
+ }
515
+ )
516
+ return result
517
+
518
+
519
+ def upsert_review(
520
+ conn: sqlite3.Connection,
521
+ *,
522
+ session_digest: str,
523
+ asin: str,
524
+ rating: int,
525
+ headline: str,
526
+ body: str,
527
+ at: str | None = None,
528
+ ) -> dict[str, Any]:
529
+ """Create or update the signed-in account's one review for an ASIN.
530
+
531
+ ``verified_purchase`` is intentionally absent from this signature. The
532
+ returned value is already shaped for ``review_catalog.normalize_local_reviews``.
533
+ The caller owns commit/rollback.
534
+ """
535
+
536
+ normalized_session = _normalize_session_digest(session_digest)
537
+ normalized_asin = _normalize_asin(asin)
538
+ normalized_rating = _normalize_rating(rating)
539
+ normalized_headline = _normalize_headline(headline)
540
+ normalized_body = _normalize_body(body)
541
+ timestamp = _timestamp(at)
542
+ account_id = _account_for_session(
543
+ conn, normalized_session, require_authenticated=True
544
+ )
545
+ assert account_id is not None
546
+ if not _product_exists(conn, normalized_asin):
547
+ raise ReviewNotFound("product does not exist")
548
+
549
+ conn.execute(
550
+ """
551
+ INSERT INTO product_reviews(
552
+ account_id,asin,rating,headline,body,created_at,updated_at
553
+ ) VALUES (?,?,?,?,?,?,?)
554
+ ON CONFLICT(account_id,asin) DO UPDATE SET
555
+ rating=excluded.rating,
556
+ headline=excluded.headline,
557
+ body=excluded.body,
558
+ updated_at=excluded.updated_at
559
+ """,
560
+ (
561
+ account_id,
562
+ normalized_asin,
563
+ normalized_rating,
564
+ normalized_headline,
565
+ normalized_body,
566
+ timestamp,
567
+ timestamp,
568
+ ),
569
+ )
570
+ rows = _review_query(
571
+ conn,
572
+ where_sql="r.account_id=? AND r.asin=?",
573
+ where_params=(account_id, normalized_asin),
574
+ viewer_session_digest=normalized_session,
575
+ order_sql="r.review_id",
576
+ )
577
+ if len(rows) != 1: # pragma: no cover - defensive database invariant
578
+ raise ReviewSchemaError("review upsert did not produce one row")
579
+ return rows[0]
580
+
581
+
582
+ def get_review(
583
+ conn: sqlite3.Connection,
584
+ review_id: int | str,
585
+ *,
586
+ viewer_session_digest: str | None = None,
587
+ ) -> dict[str, Any] | None:
588
+ """Return one review in review-catalog shape, or ``None`` if absent."""
589
+
590
+ normalized_id = _normalize_review_id(review_id)
591
+ rows = _review_query(
592
+ conn,
593
+ where_sql="r.review_id=?",
594
+ where_params=(normalized_id,),
595
+ viewer_session_digest=viewer_session_digest,
596
+ order_sql="r.review_id",
597
+ )
598
+ return rows[0] if rows else None
599
+
600
+
601
+ def list_reviews(
602
+ conn: sqlite3.Connection,
603
+ asin: str,
604
+ *,
605
+ star: int | None = None,
606
+ sort: str = REVIEW_SORT_RECENT,
607
+ viewer_session_digest: str | None = None,
608
+ ) -> list[dict[str, Any]]:
609
+ """List local reviews, optionally filtering by star and sorting by recency/helpfulness."""
610
+
611
+ normalized_asin = _normalize_asin(asin)
612
+ if star is not None:
613
+ normalized_star = _normalize_rating(star)
614
+ else:
615
+ normalized_star = None
616
+ if sort not in REVIEW_SORTS:
617
+ raise ReviewValidationError("sort must be 'recent' or 'helpful'")
618
+
619
+ where_sql = "r.asin=?"
620
+ params: tuple[object, ...] = (normalized_asin,)
621
+ if normalized_star is not None:
622
+ where_sql += " AND r.rating=?"
623
+ params += (normalized_star,)
624
+ order_sql = (
625
+ "helpful_count DESC, r.created_at DESC, r.review_id DESC"
626
+ if sort == REVIEW_SORT_HELPFUL
627
+ else "r.created_at DESC, r.review_id DESC"
628
+ )
629
+ return _review_query(
630
+ conn,
631
+ where_sql=where_sql,
632
+ where_params=params,
633
+ viewer_session_digest=viewer_session_digest,
634
+ order_sql=order_sql,
635
+ )
636
+
637
+
638
+ def toggle_helpful_vote(
639
+ conn: sqlite3.Connection,
640
+ *,
641
+ session_digest: str,
642
+ review_id: int | str,
643
+ at: str | None = None,
644
+ ) -> dict[str, Any]:
645
+ """Toggle one helpful vote for the authenticated account or guest session.
646
+
647
+ A signed-in account has one durable identity across browser sessions. An
648
+ anonymous visitor is keyed by the server-created browser session. Authors
649
+ can never vote for their own review. The caller owns the outer commit.
650
+ """
651
+
652
+ normalized_session = _normalize_session_digest(session_digest)
653
+ normalized_id = _normalize_review_id(review_id)
654
+ timestamp = _timestamp(at)
655
+ voter_account_id = _account_for_session(
656
+ conn, normalized_session, require_authenticated=False
657
+ )
658
+ review_row = conn.execute(
659
+ "SELECT account_id FROM product_reviews WHERE review_id=?",
660
+ (normalized_id,),
661
+ ).fetchone()
662
+ if review_row is None:
663
+ raise ReviewNotFound("review does not exist")
664
+ reviewer_account_id = int(review_row[0])
665
+ if voter_account_id is not None and voter_account_id == reviewer_account_id:
666
+ raise ReviewPermissionDenied("review authors cannot vote for their own review")
667
+
668
+ conn.execute("SAVEPOINT amazon_review_vote")
669
+ try:
670
+ if voter_account_id is not None:
671
+ cursor = conn.execute(
672
+ """
673
+ DELETE FROM review_helpful_votes
674
+ WHERE review_id=? AND voter_account_id=?
675
+ """,
676
+ (normalized_id, voter_account_id),
677
+ )
678
+ found_helpful = cursor.rowcount == 0
679
+ if found_helpful:
680
+ conn.execute(
681
+ """
682
+ INSERT INTO review_helpful_votes(
683
+ review_id,voter_account_id,voter_session_digest,created_at
684
+ ) VALUES (?,?,NULL,?)
685
+ """,
686
+ (normalized_id, voter_account_id, timestamp),
687
+ )
688
+ else:
689
+ cursor = conn.execute(
690
+ """
691
+ DELETE FROM review_helpful_votes
692
+ WHERE review_id=? AND voter_account_id IS NULL
693
+ AND voter_session_digest=?
694
+ """,
695
+ (normalized_id, normalized_session),
696
+ )
697
+ found_helpful = cursor.rowcount == 0
698
+ if found_helpful:
699
+ conn.execute(
700
+ """
701
+ INSERT INTO review_helpful_votes(
702
+ review_id,voter_account_id,voter_session_digest,created_at
703
+ ) VALUES (?,NULL,?,?)
704
+ """,
705
+ (normalized_id, normalized_session, timestamp),
706
+ )
707
+ count_row = conn.execute(
708
+ "SELECT COUNT(*) FROM review_helpful_votes WHERE review_id=?",
709
+ (normalized_id,),
710
+ ).fetchone()
711
+ helpful_count = int(count_row[0])
712
+ except Exception:
713
+ conn.execute("ROLLBACK TO amazon_review_vote")
714
+ conn.execute("RELEASE amazon_review_vote")
715
+ raise
716
+ else:
717
+ conn.execute("RELEASE amazon_review_vote")
718
+ return {
719
+ "review_id": str(normalized_id),
720
+ "found_helpful": found_helpful,
721
+ "helpful_count": helpful_count,
722
+ }
723
+
724
+
725
+ __all__ = [
726
+ "LOCAL_REVIEW_PROVENANCE",
727
+ "MAX_BODY_LENGTH",
728
+ "MAX_HEADLINE_LENGTH",
729
+ "REVIEW_SCHEMA_VERSION",
730
+ "REVIEW_PRODUCT_SCOPES",
731
+ "REVIEW_SORT_HELPFUL",
732
+ "REVIEW_SORT_RECENT",
733
+ "ReviewAuthenticationRequired",
734
+ "ReviewNotFound",
735
+ "ReviewPermissionDenied",
736
+ "ReviewSchemaError",
737
+ "ReviewStoreError",
738
+ "ReviewValidationError",
739
+ "get_review",
740
+ "install_schema",
741
+ "list_reviews",
742
+ "register_review_product",
743
+ "reset_review_data",
744
+ "toggle_helpful_vote",
745
+ "upsert_review",
746
+ ]
tasks/amazon/solution/site/implementation/clone/schema.sql ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PRAGMA foreign_keys = ON;
2
+ PRAGMA journal_mode = WAL;
3
+ PRAGMA busy_timeout = 5000;
4
+
5
+ CREATE TABLE IF NOT EXISTS meta (
6
+ key TEXT PRIMARY KEY,
7
+ value TEXT NOT NULL
8
+ );
9
+
10
+ CREATE TABLE IF NOT EXISTS catalog_products (
11
+ asin TEXT PRIMARY KEY,
12
+ slug TEXT NOT NULL,
13
+ title TEXT NOT NULL,
14
+ brand TEXT NOT NULL,
15
+ capacity TEXT NOT NULL,
16
+ color TEXT NOT NULL,
17
+ price_minor INTEGER NOT NULL CHECK (price_minor >= 0),
18
+ list_price_minor INTEGER,
19
+ currency TEXT NOT NULL,
20
+ rating TEXT NOT NULL,
21
+ reviews INTEGER NOT NULL CHECK (reviews >= 0),
22
+ image_path TEXT NOT NULL,
23
+ badge TEXT NOT NULL DEFAULT '',
24
+ evidence_class TEXT NOT NULL
25
+ );
26
+
27
+ -- Transaction-ready offers are intentionally separate from the frozen search
28
+ -- catalog. This lets current direct-PDP evidence override an older search
29
+ -- offer without changing the benchmark's nine-result catalog contract.
30
+ CREATE TABLE IF NOT EXISTS commerce_offers (
31
+ asin TEXT PRIMARY KEY,
32
+ slug TEXT NOT NULL,
33
+ canonical_path TEXT NOT NULL,
34
+ title TEXT NOT NULL,
35
+ brand TEXT NOT NULL,
36
+ capacity TEXT NOT NULL,
37
+ color TEXT NOT NULL,
38
+ price_minor INTEGER NOT NULL CHECK (price_minor >= 0),
39
+ list_price_minor INTEGER CHECK (list_price_minor IS NULL OR list_price_minor >= 0),
40
+ currency TEXT NOT NULL,
41
+ rating TEXT NOT NULL,
42
+ reviews INTEGER NOT NULL CHECK (reviews >= 0),
43
+ image_path TEXT NOT NULL,
44
+ badge TEXT NOT NULL DEFAULT '',
45
+ evidence_class TEXT NOT NULL,
46
+ source TEXT NOT NULL CHECK (source IN ('task-fixture', 'direct-pdp'))
47
+ );
48
+
49
+ -- Presentation is intentionally separate from the transaction quote registry.
50
+ -- Every known ASIN gets one complete display payload, while provenance remains
51
+ -- internal and commerce_offers stays authoritative for price and identity.
52
+ CREATE TABLE IF NOT EXISTS product_display_catalog (
53
+ asin TEXT PRIMARY KEY REFERENCES commerce_offers(asin) ON DELETE CASCADE,
54
+ source_index INTEGER NOT NULL UNIQUE CHECK (source_index >= 0),
55
+ provenance TEXT NOT NULL CHECK (provenance IN ('direct','legacy','simulated')),
56
+ payload_json TEXT NOT NULL
57
+ );
58
+
59
+ CREATE TABLE IF NOT EXISTS product_details (
60
+ asin TEXT PRIMARY KEY REFERENCES catalog_products(asin) ON DELETE CASCADE,
61
+ payload_json TEXT NOT NULL
62
+ );
63
+
64
+ CREATE TABLE IF NOT EXISTS accounts (
65
+ account_id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ email_normalized TEXT NOT NULL UNIQUE,
67
+ display_name TEXT NOT NULL,
68
+ password_salt BLOB NOT NULL,
69
+ password_hash BLOB NOT NULL,
70
+ password_scheme TEXT NOT NULL CHECK (password_scheme = 'scrypt-v1'),
71
+ email_verified INTEGER NOT NULL DEFAULT 0 CHECK (email_verified IN (0, 1)),
72
+ created_at TEXT NOT NULL
73
+ );
74
+
75
+ CREATE TABLE IF NOT EXISTS ranking_lists (
76
+ list_id TEXT PRIMARY KEY,
77
+ title TEXT NOT NULL,
78
+ canonical_path TEXT NOT NULL UNIQUE
79
+ );
80
+
81
+ CREATE TABLE IF NOT EXISTS ranking_items (
82
+ list_id TEXT NOT NULL REFERENCES ranking_lists(list_id) ON DELETE CASCADE,
83
+ rank INTEGER NOT NULL CHECK (rank > 0),
84
+ asin TEXT NOT NULL REFERENCES catalog_products(asin),
85
+ PRIMARY KEY (list_id, rank),
86
+ UNIQUE (list_id, asin)
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS browser_sessions (
90
+ session_digest TEXT PRIMARY KEY,
91
+ reset_epoch INTEGER NOT NULL,
92
+ created_at TEXT NOT NULL,
93
+ account_id INTEGER REFERENCES accounts(account_id) ON DELETE SET NULL,
94
+ delivery_country_code TEXT
95
+ );
96
+
97
+ CREATE TABLE IF NOT EXISTS compare_items (
98
+ compare_line_id TEXT PRIMARY KEY NOT NULL,
99
+ session_digest TEXT NOT NULL REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
100
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
101
+ selection_json TEXT NOT NULL DEFAULT '{}',
102
+ selection_key TEXT NOT NULL,
103
+ position INTEGER NOT NULL CHECK (position BETWEEN 1 AND 4),
104
+ created_at TEXT NOT NULL,
105
+ UNIQUE (session_digest, asin, selection_key),
106
+ UNIQUE (session_digest, position)
107
+ );
108
+
109
+ CREATE TABLE IF NOT EXISTS account_compare_items (
110
+ compare_line_id TEXT PRIMARY KEY NOT NULL,
111
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
112
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
113
+ selection_json TEXT NOT NULL DEFAULT '{}',
114
+ selection_key TEXT NOT NULL,
115
+ position INTEGER NOT NULL CHECK (position BETWEEN 1 AND 4),
116
+ created_at TEXT NOT NULL,
117
+ UNIQUE (account_id, asin, selection_key),
118
+ UNIQUE (account_id, position)
119
+ );
120
+
121
+ CREATE TABLE IF NOT EXISTS auth_signin_flows (
122
+ session_digest TEXT PRIMARY KEY REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
123
+ email_normalized TEXT NOT NULL,
124
+ return_to TEXT,
125
+ updated_at TEXT NOT NULL
126
+ );
127
+
128
+ -- Persistent delivery budgets survive replacement of an auth flow. Recipient
129
+ -- keys are SHA-256 digests rather than email addresses.
130
+ CREATE TABLE IF NOT EXISTS auth_mail_rate_limits (
131
+ purpose TEXT NOT NULL CHECK (purpose IN ('registration', 'password-reset')),
132
+ scope_type TEXT NOT NULL CHECK (scope_type IN ('session', 'recipient', 'account')),
133
+ scope_key TEXT NOT NULL,
134
+ window_started_at INTEGER NOT NULL,
135
+ send_count INTEGER NOT NULL CHECK (send_count >= 0),
136
+ last_sent_at INTEGER NOT NULL,
137
+ PRIMARY KEY (purpose, scope_type, scope_key)
138
+ );
139
+
140
+ -- Registration credentials remain pending until the email one-time code is
141
+ -- verified. Password material is already salted/hashed at this stage; the
142
+ -- public storefront never stores a pending plaintext password or OTP.
143
+ CREATE TABLE IF NOT EXISTS auth_registration_flows (
144
+ pending_id TEXT PRIMARY KEY,
145
+ session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
146
+ email_normalized TEXT NOT NULL,
147
+ display_name TEXT NOT NULL,
148
+ password_salt BLOB NOT NULL,
149
+ password_hash BLOB NOT NULL,
150
+ password_scheme TEXT NOT NULL CHECK (password_scheme = 'scrypt-v1'),
151
+ return_to TEXT,
152
+ code_salt BLOB NOT NULL,
153
+ code_hash BLOB NOT NULL,
154
+ expires_at INTEGER NOT NULL,
155
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
156
+ created_at INTEGER NOT NULL,
157
+ updated_at INTEGER NOT NULL
158
+ );
159
+
160
+ -- Verification mail is LOCAL_ONLY unless an operator configures SMTP. The
161
+ -- one-time code is never persisted here: only its salt/hash lives in the flow
162
+ -- table, while the short-lived cleartext is held by the current process long
163
+ -- enough to render the protected local inbox or call the configured provider.
164
+ CREATE TABLE IF NOT EXISTS auth_registration_email_outbox (
165
+ email_id INTEGER PRIMARY KEY AUTOINCREMENT,
166
+ pending_id TEXT NOT NULL UNIQUE REFERENCES auth_registration_flows(pending_id) ON DELETE CASCADE,
167
+ recipient TEXT NOT NULL,
168
+ template TEXT NOT NULL CHECK (template = 'registration-verification'),
169
+ status TEXT NOT NULL CHECK (status IN (
170
+ 'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
171
+ )),
172
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
173
+ delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
174
+ claim_token TEXT,
175
+ last_error TEXT,
176
+ attempted_at INTEGER,
177
+ sent_at INTEGER,
178
+ created_at INTEGER NOT NULL,
179
+ CHECK (
180
+ (status = 'LOCAL_ONLY' AND is_simulation = 1)
181
+ OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
182
+ )
183
+ );
184
+
185
+ -- Password reset state is session-bound. account_id is intentionally nullable
186
+ -- so unknown identifiers follow the same public flow without receiving mail.
187
+ CREATE TABLE IF NOT EXISTS auth_password_reset_flows (
188
+ reset_id TEXT PRIMARY KEY,
189
+ session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
190
+ account_id INTEGER REFERENCES accounts(account_id) ON DELETE CASCADE,
191
+ return_to TEXT,
192
+ code_salt BLOB NOT NULL,
193
+ code_hash BLOB NOT NULL,
194
+ expires_at INTEGER NOT NULL,
195
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
196
+ verified_at INTEGER,
197
+ created_at INTEGER NOT NULL,
198
+ updated_at INTEGER NOT NULL
199
+ );
200
+
201
+ CREATE UNIQUE INDEX IF NOT EXISTS auth_password_reset_account_unique_idx
202
+ ON auth_password_reset_flows(account_id)
203
+ WHERE account_id IS NOT NULL;
204
+
205
+ CREATE TABLE IF NOT EXISTS auth_password_reset_email_outbox (
206
+ email_id INTEGER PRIMARY KEY AUTOINCREMENT,
207
+ reset_id TEXT NOT NULL UNIQUE REFERENCES auth_password_reset_flows(reset_id) ON DELETE CASCADE,
208
+ recipient TEXT NOT NULL,
209
+ template TEXT NOT NULL CHECK (template = 'password-reset-verification'),
210
+ status TEXT NOT NULL CHECK (status IN (
211
+ 'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
212
+ )),
213
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
214
+ delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
215
+ claim_token TEXT,
216
+ last_error TEXT,
217
+ attempted_at INTEGER,
218
+ sent_at INTEGER,
219
+ created_at INTEGER NOT NULL,
220
+ CHECK (
221
+ (status = 'LOCAL_ONLY' AND is_simulation = 1)
222
+ OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
223
+ )
224
+ );
225
+
226
+ CREATE TABLE IF NOT EXISTS carts (
227
+ cart_id INTEGER PRIMARY KEY AUTOINCREMENT,
228
+ session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
229
+ created_at TEXT NOT NULL
230
+ );
231
+
232
+ CREATE TABLE IF NOT EXISTS cart_lines (
233
+ line_id TEXT PRIMARY KEY NOT NULL,
234
+ cart_id INTEGER NOT NULL REFERENCES carts(cart_id) ON DELETE CASCADE,
235
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
236
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
237
+ selection_json TEXT NOT NULL DEFAULT '{}',
238
+ selection_key TEXT NOT NULL,
239
+ line_state TEXT NOT NULL DEFAULT 'ACTIVE'
240
+ CHECK (line_state IN ('ACTIVE', 'SAVED')),
241
+ UNIQUE (cart_id, asin, selection_key)
242
+ );
243
+
244
+ -- Authenticated carts are account-owned so they survive sign-out, session
245
+ -- rotation, and a later sign-in from another browser session. Legacy anonymous
246
+ -- rows remain readable for migration compatibility; public cart mutations are
247
+ -- authenticated and do not create new guest cart lines.
248
+ CREATE TABLE IF NOT EXISTS account_cart_lines (
249
+ line_id TEXT PRIMARY KEY NOT NULL,
250
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
251
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
252
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
253
+ selection_json TEXT NOT NULL DEFAULT '{}',
254
+ selection_key TEXT NOT NULL,
255
+ line_state TEXT NOT NULL DEFAULT 'ACTIVE'
256
+ CHECK (line_state IN ('ACTIVE', 'SAVED')),
257
+ UNIQUE (account_id, asin, selection_key)
258
+ );
259
+
260
+ -- A guest Buy Now intent must survive the sign-in/registration session
261
+ -- rotation without being mixed into the shopper's ordinary cart.
262
+ CREATE TABLE IF NOT EXISTS pending_buy_now (
263
+ session_digest TEXT PRIMARY KEY
264
+ REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
265
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
266
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
267
+ selection_json TEXT NOT NULL DEFAULT '{}',
268
+ created_at TEXT NOT NULL
269
+ );
270
+
271
+ CREATE TABLE IF NOT EXISTS addresses (
272
+ address_id INTEGER PRIMARY KEY AUTOINCREMENT,
273
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
274
+ full_name TEXT NOT NULL,
275
+ address_line1 TEXT NOT NULL,
276
+ address_line2 TEXT NOT NULL DEFAULT '',
277
+ city TEXT NOT NULL,
278
+ state_region TEXT NOT NULL,
279
+ postal_code TEXT NOT NULL,
280
+ country_code TEXT NOT NULL CHECK (
281
+ length(country_code) = 2 AND country_code = upper(country_code)
282
+ ),
283
+ phone TEXT NOT NULL DEFAULT '',
284
+ is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),
285
+ is_archived INTEGER NOT NULL DEFAULT 0 CHECK (is_archived IN (0, 1)),
286
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
287
+ created_at TEXT NOT NULL,
288
+ updated_at TEXT NOT NULL,
289
+ CHECK (is_archived = 0 OR is_default = 0)
290
+ );
291
+
292
+ CREATE TABLE IF NOT EXISTS checkout_sessions (
293
+ checkout_id INTEGER PRIMARY KEY AUTOINCREMENT,
294
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
295
+ idempotency_key TEXT NOT NULL,
296
+ checkout_mode TEXT NOT NULL DEFAULT 'CART'
297
+ CHECK (checkout_mode IN ('CART', 'BUY_NOW')),
298
+ status TEXT NOT NULL CHECK (status IN (
299
+ 'CART_READY', 'ADDRESS_SELECTED', 'DELIVERY_SELECTED',
300
+ 'PAYMENT_SELECTED', 'PAYMENT_PENDING', 'PLACED'
301
+ )),
302
+ address_id INTEGER REFERENCES addresses(address_id),
303
+ delivery_method TEXT CHECK (
304
+ delivery_method IS NULL OR delivery_method IN ('standard', 'expedited')
305
+ ),
306
+ shipping_minor INTEGER CHECK (
307
+ shipping_minor IS NULL OR shipping_minor IN (0, 1299)
308
+ ),
309
+ currency TEXT NOT NULL DEFAULT 'USD',
310
+ created_at TEXT NOT NULL,
311
+ updated_at TEXT NOT NULL,
312
+ placed_at TEXT,
313
+ CHECK (
314
+ (status = 'CART_READY' AND address_id IS NULL
315
+ AND delivery_method IS NULL AND shipping_minor IS NULL
316
+ AND placed_at IS NULL)
317
+ OR
318
+ (status = 'ADDRESS_SELECTED' AND address_id IS NOT NULL
319
+ AND delivery_method IS NULL AND shipping_minor IS NULL
320
+ AND placed_at IS NULL)
321
+ OR
322
+ (status IN ('DELIVERY_SELECTED', 'PAYMENT_SELECTED', 'PAYMENT_PENDING')
323
+ AND address_id IS NOT NULL AND delivery_method IS NOT NULL
324
+ AND shipping_minor IS NOT NULL AND placed_at IS NULL)
325
+ OR
326
+ (status = 'PLACED' AND address_id IS NOT NULL
327
+ AND delivery_method IS NOT NULL AND shipping_minor IS NOT NULL
328
+ AND placed_at IS NOT NULL)
329
+ )
330
+ );
331
+
332
+ CREATE UNIQUE INDEX IF NOT EXISTS checkout_sessions_one_open_account_idx
333
+ ON checkout_sessions(account_id) WHERE status <> 'PLACED';
334
+ CREATE UNIQUE INDEX IF NOT EXISTS checkout_sessions_idempotency_key_idx
335
+ ON checkout_sessions(idempotency_key);
336
+
337
+ -- BUY_NOW checkouts own an isolated line snapshot. CART checkouts continue
338
+ -- to read the account cart so cart edits invalidate stale payment approvals.
339
+ CREATE TABLE IF NOT EXISTS checkout_lines (
340
+ checkout_id INTEGER NOT NULL
341
+ REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
342
+ ordinal INTEGER NOT NULL CHECK (ordinal > 0),
343
+ asin TEXT NOT NULL REFERENCES commerce_offers(asin),
344
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
345
+ selection_json TEXT NOT NULL DEFAULT '{}',
346
+ PRIMARY KEY (checkout_id, ordinal)
347
+ );
348
+
349
+ CREATE TABLE IF NOT EXISTS payment_attempts (
350
+ payment_attempt_id INTEGER PRIMARY KEY AUTOINCREMENT,
351
+ checkout_id INTEGER NOT NULL REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
352
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
353
+ method TEXT NOT NULL CHECK (method IN (
354
+ 'test-card','sandbox-card-approved','sandbox-card-declined',
355
+ 'sandbox-bank-approved','stripe-test'
356
+ )),
357
+ status TEXT NOT NULL CHECK (status IN ('APPROVED', 'DECLINED', 'SUPERSEDED')),
358
+ amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
359
+ currency TEXT NOT NULL,
360
+ cart_fingerprint TEXT NOT NULL,
361
+ site_backend_flow_id TEXT,
362
+ site_backend_attempt_id TEXT,
363
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
364
+ created_at TEXT NOT NULL
365
+ );
366
+
367
+ CREATE UNIQUE INDEX IF NOT EXISTS payment_attempts_one_approved_checkout_idx
368
+ ON payment_attempts(checkout_id) WHERE status = 'APPROVED';
369
+
370
+ -- Stripe is an opt-in external test profile. The browser never supplies
371
+ -- transaction prices or payment credentials; these rows freeze the exact
372
+ -- server quote used to create one hosted Checkout Session.
373
+ CREATE TABLE IF NOT EXISTS stripe_payment_sessions (
374
+ stripe_payment_session_id INTEGER PRIMARY KEY AUTOINCREMENT,
375
+ checkout_id INTEGER NOT NULL UNIQUE
376
+ REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
377
+ account_id INTEGER NOT NULL
378
+ REFERENCES accounts(account_id) ON DELETE CASCADE,
379
+ checkout_token TEXT NOT NULL UNIQUE,
380
+ provider_session_id TEXT UNIQUE,
381
+ provider_idempotency_key TEXT NOT NULL UNIQUE,
382
+ site_backend_flow_id TEXT,
383
+ amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
384
+ currency TEXT NOT NULL,
385
+ cart_fingerprint TEXT NOT NULL,
386
+ snapshot_hash TEXT NOT NULL,
387
+ shipping_address_json TEXT NOT NULL,
388
+ delivery_method TEXT NOT NULL CHECK (
389
+ delivery_method IN ('standard','expedited')
390
+ ),
391
+ shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0,1299)),
392
+ status TEXT NOT NULL CHECK (status IN (
393
+ 'CREATING','OPEN','PAID','CANCELLED','EXPIRED','FAILED','INVALID'
394
+ )),
395
+ provider_payment_status TEXT,
396
+ expires_at INTEGER NOT NULL,
397
+ created_at TEXT NOT NULL,
398
+ updated_at TEXT NOT NULL
399
+ );
400
+
401
+ CREATE INDEX IF NOT EXISTS stripe_payment_sessions_provider_idx
402
+ ON stripe_payment_sessions(provider_session_id);
403
+
404
+ CREATE TABLE IF NOT EXISTS stripe_checkout_lines (
405
+ stripe_payment_session_id INTEGER NOT NULL
406
+ REFERENCES stripe_payment_sessions(stripe_payment_session_id)
407
+ ON DELETE CASCADE,
408
+ ordinal INTEGER NOT NULL CHECK (ordinal > 0),
409
+ asin TEXT NOT NULL,
410
+ title TEXT NOT NULL,
411
+ image_path TEXT NOT NULL,
412
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
413
+ selection_json TEXT NOT NULL DEFAULT '{}',
414
+ unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
415
+ line_total_minor INTEGER NOT NULL CHECK (
416
+ line_total_minor = unit_price_minor * quantity
417
+ ),
418
+ currency TEXT NOT NULL,
419
+ PRIMARY KEY (stripe_payment_session_id, ordinal)
420
+ );
421
+
422
+ CREATE TABLE IF NOT EXISTS stripe_webhook_events (
423
+ event_id TEXT PRIMARY KEY,
424
+ stripe_payment_session_id INTEGER
425
+ REFERENCES stripe_payment_sessions(stripe_payment_session_id)
426
+ ON DELETE SET NULL,
427
+ event_type TEXT NOT NULL,
428
+ provider_created_at INTEGER NOT NULL,
429
+ status TEXT NOT NULL CHECK (status IN (
430
+ 'PROCESSING','PROCESSED','IGNORED','REJECTED'
431
+ )),
432
+ detail TEXT NOT NULL DEFAULT '',
433
+ created_at TEXT NOT NULL,
434
+ processed_at TEXT
435
+ );
436
+
437
+ CREATE TABLE IF NOT EXISTS orders (
438
+ order_id INTEGER PRIMARY KEY AUTOINCREMENT,
439
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
440
+ checkout_id INTEGER NOT NULL UNIQUE REFERENCES checkout_sessions(checkout_id),
441
+ payment_attempt_id INTEGER NOT NULL UNIQUE REFERENCES payment_attempts(payment_attempt_id),
442
+ idempotency_key TEXT NOT NULL,
443
+ status TEXT NOT NULL CHECK (status = 'PLACED'),
444
+ items_subtotal_minor INTEGER NOT NULL CHECK (items_subtotal_minor >= 0),
445
+ shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0, 1299)),
446
+ total_minor INTEGER NOT NULL CHECK (
447
+ total_minor >= 0 AND total_minor = items_subtotal_minor + shipping_minor
448
+ ),
449
+ currency TEXT NOT NULL,
450
+ delivery_method TEXT NOT NULL CHECK (
451
+ delivery_method IN ('standard', 'expedited')
452
+ ),
453
+ shipping_address_json TEXT NOT NULL,
454
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
455
+ created_at TEXT NOT NULL,
456
+ UNIQUE (account_id, idempotency_key)
457
+ );
458
+
459
+ CREATE INDEX IF NOT EXISTS orders_account_created_idx
460
+ ON orders(account_id, order_id DESC);
461
+
462
+ CREATE TABLE IF NOT EXISTS order_items (
463
+ order_item_id INTEGER PRIMARY KEY AUTOINCREMENT,
464
+ order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
465
+ ordinal INTEGER NOT NULL CHECK (ordinal > 0),
466
+ asin TEXT NOT NULL,
467
+ title TEXT NOT NULL,
468
+ image_path TEXT NOT NULL,
469
+ quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
470
+ selection_json TEXT NOT NULL DEFAULT '{}',
471
+ unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
472
+ line_total_minor INTEGER NOT NULL CHECK (
473
+ line_total_minor = unit_price_minor * quantity
474
+ ),
475
+ currency TEXT NOT NULL,
476
+ UNIQUE (order_id, ordinal)
477
+ );
478
+
479
+ CREATE TABLE IF NOT EXISTS shipments (
480
+ shipment_id INTEGER PRIMARY KEY AUTOINCREMENT,
481
+ order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
482
+ status TEXT NOT NULL CHECK (status = 'PREPARING'),
483
+ lifecycle_status TEXT NOT NULL DEFAULT 'PREPARING' CHECK (
484
+ lifecycle_status IN ('PREPARING', 'SHIPPED', 'DELIVERED', 'CANCELLED')
485
+ ),
486
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
487
+ delivery_method TEXT NOT NULL CHECK (
488
+ delivery_method IN ('standard', 'expedited')
489
+ ),
490
+ shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0, 1299)),
491
+ carrier TEXT NOT NULL,
492
+ tracking_code TEXT,
493
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
494
+ created_at TEXT NOT NULL,
495
+ updated_at TEXT NOT NULL,
496
+ shipped_at TEXT,
497
+ delivered_at TEXT,
498
+ cancelled_at TEXT,
499
+ CHECK (
500
+ (lifecycle_status IN ('PREPARING', 'CANCELLED') AND tracking_code IS NULL)
501
+ OR
502
+ (lifecycle_status IN ('SHIPPED', 'DELIVERED') AND tracking_code IS NOT NULL
503
+ AND length(tracking_code) BETWEEN 8 AND 64)
504
+ ),
505
+ CHECK (lifecycle_status<>'SHIPPED' OR shipped_at IS NOT NULL),
506
+ CHECK (lifecycle_status<>'DELIVERED' OR (shipped_at IS NOT NULL AND delivered_at IS NOT NULL)),
507
+ CHECK (lifecycle_status<>'CANCELLED' OR cancelled_at IS NOT NULL)
508
+ );
509
+
510
+ CREATE TABLE IF NOT EXISTS order_events (
511
+ order_event_id INTEGER PRIMARY KEY AUTOINCREMENT,
512
+ order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
513
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
514
+ event_type TEXT NOT NULL CHECK (event_type IN (
515
+ 'ORDER_PLACED', 'ORDER_CANCELLED', 'SHIPMENT_SHIPPED',
516
+ 'SHIPMENT_DELIVERED', 'RETURN_REQUESTED', 'RETURN_RECEIVED',
517
+ 'RETURN_REFUNDED'
518
+ )),
519
+ actor TEXT NOT NULL CHECK (actor IN ('CUSTOMER', 'ADMIN', 'SYSTEM')),
520
+ from_status TEXT,
521
+ to_status TEXT NOT NULL,
522
+ idempotency_key TEXT,
523
+ detail_json TEXT NOT NULL DEFAULT '{}',
524
+ created_at TEXT NOT NULL,
525
+ UNIQUE (order_id, event_type)
526
+ );
527
+
528
+ CREATE INDEX IF NOT EXISTS order_events_order_idx
529
+ ON order_events(order_id, order_event_id);
530
+ CREATE UNIQUE INDEX IF NOT EXISTS order_events_mutation_key_idx
531
+ ON order_events(account_id, event_type, idempotency_key)
532
+ WHERE idempotency_key IS NOT NULL;
533
+
534
+ CREATE TABLE IF NOT EXISTS order_action_keys (
535
+ order_action_key_id INTEGER PRIMARY KEY AUTOINCREMENT,
536
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
537
+ order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
538
+ action_type TEXT NOT NULL CHECK (action_type IN ('CANCEL', 'RETURN_REQUEST')),
539
+ idempotency_key TEXT NOT NULL,
540
+ result_reference INTEGER,
541
+ created_at TEXT NOT NULL,
542
+ UNIQUE (account_id, action_type, idempotency_key),
543
+ UNIQUE (order_id, action_type)
544
+ );
545
+
546
+ CREATE TABLE IF NOT EXISTS return_requests (
547
+ return_request_id INTEGER PRIMARY KEY AUTOINCREMENT,
548
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
549
+ order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
550
+ idempotency_key TEXT NOT NULL,
551
+ reason_code TEXT NOT NULL CHECK (reason_code IN (
552
+ 'DAMAGED', 'DEFECTIVE', 'NOT_AS_DESCRIBED',
553
+ 'WRONG_ITEM', 'NO_LONGER_NEEDED'
554
+ )),
555
+ customer_note TEXT NOT NULL DEFAULT '' CHECK (length(customer_note) <= 500),
556
+ status TEXT NOT NULL CHECK (status IN ('REQUESTED', 'RECEIVED', 'REFUNDED')),
557
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
558
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
559
+ created_at TEXT NOT NULL,
560
+ updated_at TEXT NOT NULL,
561
+ UNIQUE (account_id, idempotency_key)
562
+ );
563
+
564
+ CREATE INDEX IF NOT EXISTS return_requests_account_idx
565
+ ON return_requests(account_id, return_request_id DESC);
566
+
567
+ CREATE TABLE IF NOT EXISTS return_request_items (
568
+ return_request_id INTEGER NOT NULL
569
+ REFERENCES return_requests(return_request_id) ON DELETE CASCADE,
570
+ order_item_id INTEGER NOT NULL REFERENCES order_items(order_item_id),
571
+ quantity INTEGER NOT NULL CHECK (quantity > 0),
572
+ PRIMARY KEY (return_request_id, order_item_id)
573
+ );
574
+
575
+ CREATE TABLE IF NOT EXISTS refunds (
576
+ refund_id INTEGER PRIMARY KEY AUTOINCREMENT,
577
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
578
+ order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
579
+ payment_attempt_id INTEGER NOT NULL REFERENCES payment_attempts(payment_attempt_id),
580
+ return_request_id INTEGER REFERENCES return_requests(return_request_id) ON DELETE CASCADE,
581
+ kind TEXT NOT NULL CHECK (kind IN ('CANCELLATION', 'RETURN')),
582
+ status TEXT NOT NULL CHECK (status = 'COMPLETED'),
583
+ amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
584
+ currency TEXT NOT NULL,
585
+ idempotency_key TEXT NOT NULL,
586
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
587
+ created_at TEXT NOT NULL,
588
+ CHECK (
589
+ (kind='CANCELLATION' AND return_request_id IS NULL)
590
+ OR (kind='RETURN' AND return_request_id IS NOT NULL)
591
+ ),
592
+ UNIQUE (order_id, kind),
593
+ UNIQUE (account_id, idempotency_key)
594
+ );
595
+
596
+ CREATE INDEX IF NOT EXISTS refunds_account_idx
597
+ ON refunds(account_id, refund_id DESC);
598
+
599
+ CREATE TABLE IF NOT EXISTS email_outbox (
600
+ email_id INTEGER PRIMARY KEY AUTOINCREMENT,
601
+ account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
602
+ order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
603
+ recipient TEXT NOT NULL,
604
+ template TEXT NOT NULL CHECK (template = 'order-confirmation'),
605
+ subject TEXT NOT NULL,
606
+ payload_json TEXT NOT NULL,
607
+ site_backend_mail_id TEXT,
608
+ site_backend_claim_token TEXT,
609
+ status TEXT NOT NULL CHECK (status IN (
610
+ 'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
611
+ )),
612
+ is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
613
+ delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
614
+ claim_token TEXT,
615
+ last_error TEXT,
616
+ attempted_at INTEGER,
617
+ sent_at INTEGER,
618
+ created_at TEXT NOT NULL,
619
+ CHECK (
620
+ (status = 'LOCAL_ONLY' AND is_simulation = 1)
621
+ OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
622
+ )
623
+ );
624
+
625
+ CREATE TABLE IF NOT EXISTS navigation_events (
626
+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,
627
+ session_digest TEXT NOT NULL REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
628
+ sequence INTEGER NOT NULL,
629
+ method TEXT NOT NULL,
630
+ route_key TEXT NOT NULL,
631
+ path TEXT NOT NULL,
632
+ referer TEXT NOT NULL,
633
+ status INTEGER NOT NULL,
634
+ asin TEXT,
635
+ rank INTEGER,
636
+ created_at TEXT NOT NULL,
637
+ UNIQUE (session_digest, sequence)
638
+ );
639
+
640
+ CREATE TABLE IF NOT EXISTS task_progress (
641
+ session_digest TEXT PRIMARY KEY REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
642
+ task_id TEXT NOT NULL,
643
+ stage TEXT NOT NULL,
644
+ best_sellers_event_id INTEGER REFERENCES navigation_events(event_id),
645
+ pdp_event_id INTEGER REFERENCES navigation_events(event_id),
646
+ flow_capability_digest TEXT,
647
+ capability_consumed INTEGER NOT NULL DEFAULT 0 CHECK (capability_consumed IN (0, 1)),
648
+ reset_epoch INTEGER NOT NULL,
649
+ updated_at TEXT NOT NULL
650
+ );
651
+
652
+ CREATE TABLE IF NOT EXISTS request_journal (
653
+ request_id INTEGER PRIMARY KEY AUTOINCREMENT,
654
+ session_digest TEXT NOT NULL,
655
+ method TEXT NOT NULL,
656
+ path TEXT NOT NULL,
657
+ media_type TEXT NOT NULL,
658
+ raw_body_sha256 TEXT NOT NULL,
659
+ canonical_form TEXT NOT NULL,
660
+ status INTEGER NOT NULL,
661
+ outcome TEXT NOT NULL,
662
+ contract_id TEXT NOT NULL,
663
+ created_at TEXT NOT NULL
664
+ );
665
+
666
+ CREATE TABLE IF NOT EXISTS task_completions (
667
+ completion_id INTEGER PRIMARY KEY AUTOINCREMENT,
668
+ run_id TEXT NOT NULL,
669
+ session_digest TEXT NOT NULL,
670
+ task_id TEXT NOT NULL,
671
+ terminal_path TEXT NOT NULL,
672
+ request_id INTEGER NOT NULL REFERENCES request_journal(request_id),
673
+ completed_at TEXT NOT NULL,
674
+ UNIQUE (run_id, session_digest, task_id)
675
+ );
676
+
677
+ CREATE INDEX IF NOT EXISTS navigation_events_session_idx
678
+ ON navigation_events(session_digest, sequence);
679
+ CREATE INDEX IF NOT EXISTS request_journal_session_idx
680
+ ON request_journal(session_digest, request_id);
tasks/amazon/solution/site/implementation/clone/search_commerce.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import re
6
+ from collections import Counter
7
+ from collections.abc import Mapping
8
+ from decimal import Decimal, InvalidOperation
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from urllib.parse import urlsplit
12
+
13
+
14
+ SEARCH_COMMERCE_FIXTURE = "search-commerce-current-2026-07-22.json"
15
+ SEARCH_COMMERCE_SCHEMA = "amazon-clone.search-commerce-cards.v1"
16
+ SEARCH_COMMERCE_CAPTURED_AT = "2026-07-22T16:10:00+08:00"
17
+ SEARCH_COMMERCE_QUERY = "best sellers"
18
+ SEARCH_COMMERCE_EVIDENCE_CLASS = "direct-search-card"
19
+ EXPECTED_DEPARTMENT_COUNTS = {
20
+ "books": 6,
21
+ "beauty-personal-care": 6,
22
+ "home-kitchen": 2,
23
+ "toys-games": 1,
24
+ "computers": 5,
25
+ }
26
+ EXPECTED_CAPTURE_POLICY = {
27
+ "offerRule": "A frozen card is transaction-ready only when the same visible result card exposed a non-empty USD price and an Add to cart button.",
28
+ "selectionBoundary": "Each card establishes only its displayed default offer. No unobserved size, color, format, seller, inventory count, delivery date, list price, or variant cross-product is inferred.",
29
+ "pdpBoundary": "These are current public search-card observations, not complete PDP captures. The clone may expose a card-evidence detail shell but must not claim a full source PDP.",
30
+ "reviewBoundary": "ratingDisplay and reviewsDisplay preserve visible aggregate copy. Values abbreviated with K are not converted into exact review counts.",
31
+ "sponsoredBoundary": "Sponsored status is retained as observed; it does not change the price or Add to cart evidence rule.",
32
+ }
33
+ CARD_FIELDS = frozenset(
34
+ {
35
+ "asin",
36
+ "sourceIndex",
37
+ "sourceDepartment",
38
+ "department",
39
+ "sponsored",
40
+ "title",
41
+ "slug",
42
+ "canonicalPath",
43
+ "format",
44
+ "price_minor",
45
+ "ratingDisplay",
46
+ "reviewsDisplay",
47
+ "reviewsExact",
48
+ "sourceImageUrl",
49
+ "image_path",
50
+ "asset",
51
+ }
52
+ )
53
+ ASSET_FIELDS = frozenset({"bytes", "width", "height", "mime", "sha256"})
54
+ ASIN_RE = re.compile(r"[A-Z0-9]{10}\Z")
55
+ SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")
56
+ REVIEW_DISPLAY_RE = re.compile(r"(?:[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)K?\Z")
57
+
58
+
59
+ class SearchCommerceError(ValueError):
60
+ pass
61
+
62
+
63
+ def _jpeg_dimensions(payload: bytes) -> tuple[int, int] | None:
64
+ """Read JPEG SOF dimensions without adding a runtime imaging dependency."""
65
+
66
+ if len(payload) < 4 or payload[:2] != b"\xff\xd8":
67
+ return None
68
+ offset = 2
69
+ sof_markers = {
70
+ 0xC0,
71
+ 0xC1,
72
+ 0xC2,
73
+ 0xC3,
74
+ 0xC5,
75
+ 0xC6,
76
+ 0xC7,
77
+ 0xC9,
78
+ 0xCA,
79
+ 0xCB,
80
+ 0xCD,
81
+ 0xCE,
82
+ 0xCF,
83
+ }
84
+ while offset < len(payload):
85
+ while offset < len(payload) and payload[offset] != 0xFF:
86
+ offset += 1
87
+ while offset < len(payload) and payload[offset] == 0xFF:
88
+ offset += 1
89
+ if offset >= len(payload):
90
+ break
91
+ marker = payload[offset]
92
+ offset += 1
93
+ if marker in {0x01, *range(0xD0, 0xDA)}:
94
+ continue
95
+ if offset + 2 > len(payload):
96
+ return None
97
+ segment_length = int.from_bytes(payload[offset : offset + 2], "big")
98
+ if segment_length < 2 or offset + segment_length > len(payload):
99
+ return None
100
+ if marker in sof_markers:
101
+ if segment_length < 7:
102
+ return None
103
+ height = int.from_bytes(payload[offset + 3 : offset + 5], "big")
104
+ width = int.from_bytes(payload[offset + 5 : offset + 7], "big")
105
+ return width, height
106
+ offset += segment_length
107
+ return None
108
+
109
+
110
+ def _validate_sources(raw: Any) -> None:
111
+ if not isinstance(raw, list) or len(raw) != 2:
112
+ raise SearchCommerceError("search commerce sources must contain two captures")
113
+ expected_departments = ("All Departments", "Computers")
114
+ for source, department in zip(raw, expected_departments, strict=True):
115
+ if (
116
+ not isinstance(source, Mapping)
117
+ or set(source) != {"query", "department", "url"}
118
+ or source.get("query") != SEARCH_COMMERCE_QUERY
119
+ or source.get("department") != department
120
+ ):
121
+ raise SearchCommerceError("search commerce source identity changed")
122
+ parsed = urlsplit(str(source.get("url") or ""))
123
+ if (
124
+ parsed.scheme != "https"
125
+ or parsed.hostname not in {"amazon.com", "www.amazon.com"}
126
+ or parsed.path != "/s"
127
+ ):
128
+ raise SearchCommerceError("search commerce source URL is invalid")
129
+
130
+
131
+ def normalize_search_commerce_cards(
132
+ payload: Mapping[str, Any], fixture_root: Path
133
+ ) -> tuple[dict[str, Any], ...]:
134
+ """Validate the immutable card capture and project only evidenced fields."""
135
+
136
+ fixture_root = fixture_root.resolve()
137
+ if (
138
+ payload.get("schema") != SEARCH_COMMERCE_SCHEMA
139
+ or payload.get("capturedAt") != SEARCH_COMMERCE_CAPTURED_AT
140
+ or payload.get("locale") != "en-US"
141
+ or payload.get("deliveryRegion") != "Singapore"
142
+ or payload.get("currency") != "USD"
143
+ or payload.get("capturePolicy") != EXPECTED_CAPTURE_POLICY
144
+ ):
145
+ raise SearchCommerceError("search commerce capture boundary is invalid")
146
+ _validate_sources(payload.get("sources"))
147
+ raw_products = payload.get("products")
148
+ if not isinstance(raw_products, list) or len(raw_products) != 20:
149
+ raise SearchCommerceError("search commerce capture must contain 20 cards")
150
+
151
+ normalized: list[dict[str, Any]] = []
152
+ seen_asins: set[str] = set()
153
+ seen_source_positions: set[tuple[str, int]] = set()
154
+ static_root = (fixture_root.parent / "static").resolve()
155
+ for raw in raw_products:
156
+ if not isinstance(raw, Mapping) or set(raw) not in {
157
+ CARD_FIELDS,
158
+ CARD_FIELDS - {"format"},
159
+ }:
160
+ raise SearchCommerceError("search commerce card fields changed")
161
+ asin = raw.get("asin")
162
+ source_index = raw.get("sourceIndex")
163
+ source_department = raw.get("sourceDepartment")
164
+ department = raw.get("department")
165
+ title = raw.get("title")
166
+ slug = raw.get("slug")
167
+ canonical_path = raw.get("canonicalPath")
168
+ price_minor = raw.get("price_minor")
169
+ rating_display = raw.get("ratingDisplay")
170
+ reviews_display = raw.get("reviewsDisplay")
171
+ reviews_exact = raw.get("reviewsExact")
172
+ image_path = raw.get("image_path")
173
+ asset = raw.get("asset")
174
+ if (
175
+ not isinstance(asin, str)
176
+ or ASIN_RE.fullmatch(asin) is None
177
+ or asin in seen_asins
178
+ or isinstance(source_index, bool)
179
+ or not isinstance(source_index, int)
180
+ or source_index < 1
181
+ or source_department not in {"All Departments", "Computers"}
182
+ or (source_department, source_index) in seen_source_positions
183
+ or department not in EXPECTED_DEPARTMENT_COUNTS
184
+ or (department == "computers") != (source_department == "Computers")
185
+ or not isinstance(raw.get("sponsored"), bool)
186
+ or not isinstance(title, str)
187
+ or not title.strip()
188
+ or not isinstance(slug, str)
189
+ or not slug
190
+ or "/" in slug
191
+ or canonical_path != f"/{slug}/dp/{asin}"
192
+ or isinstance(price_minor, bool)
193
+ or not isinstance(price_minor, int)
194
+ or price_minor < 0
195
+ ):
196
+ raise SearchCommerceError(f"invalid search commerce identity: {asin!r}")
197
+
198
+ product_format = raw.get("format")
199
+ if (
200
+ (department == "books" and (not isinstance(product_format, str) or not product_format))
201
+ or (department != "books" and product_format is not None)
202
+ ):
203
+ raise SearchCommerceError(f"invalid captured format boundary: {asin}")
204
+ try:
205
+ rating_value = Decimal(str(rating_display))
206
+ except InvalidOperation as exc:
207
+ raise SearchCommerceError(f"invalid captured rating: {asin}") from exc
208
+ if (
209
+ not isinstance(rating_display, str)
210
+ or not rating_value.is_finite()
211
+ or rating_value < 0
212
+ or rating_value > 5
213
+ or not isinstance(reviews_display, str)
214
+ or REVIEW_DISPLAY_RE.fullmatch(reviews_display) is None
215
+ or (
216
+ reviews_display.endswith("K")
217
+ and reviews_exact is not None
218
+ )
219
+ or (
220
+ not reviews_display.endswith("K")
221
+ and (
222
+ isinstance(reviews_exact, bool)
223
+ or not isinstance(reviews_exact, int)
224
+ or reviews_exact <= 0
225
+ or str(reviews_exact) != reviews_display
226
+ )
227
+ )
228
+ ):
229
+ raise SearchCommerceError(f"invalid captured review boundary: {asin}")
230
+
231
+ source_image = urlsplit(str(raw.get("sourceImageUrl") or ""))
232
+ if (
233
+ source_image.scheme != "https"
234
+ or source_image.hostname != "m.media-amazon.com"
235
+ or not isinstance(image_path, str)
236
+ or image_path
237
+ != f"/static/assets/source-current/2026-07-22/search-commerce/{asin}.jpg"
238
+ or not isinstance(asset, Mapping)
239
+ or set(asset) != ASSET_FIELDS
240
+ or asset.get("mime") != "image/jpeg"
241
+ or isinstance(asset.get("bytes"), bool)
242
+ or not isinstance(asset.get("bytes"), int)
243
+ or int(asset["bytes"]) <= 0
244
+ or isinstance(asset.get("width"), bool)
245
+ or not isinstance(asset.get("width"), int)
246
+ or int(asset["width"]) <= 0
247
+ or isinstance(asset.get("height"), bool)
248
+ or not isinstance(asset.get("height"), int)
249
+ or int(asset["height"]) <= 0
250
+ or not isinstance(asset.get("sha256"), str)
251
+ or SHA256_RE.fullmatch(str(asset["sha256"])) is None
252
+ ):
253
+ raise SearchCommerceError(f"invalid captured image metadata: {asin}")
254
+ local_asset = (fixture_root.parent / image_path.removeprefix("/")).resolve()
255
+ if static_root not in local_asset.parents or not local_asset.is_file():
256
+ raise SearchCommerceError(f"search commerce image is unavailable: {asin}")
257
+ image_bytes = local_asset.read_bytes()
258
+ if (
259
+ len(image_bytes) != asset["bytes"]
260
+ or hashlib.sha256(image_bytes).hexdigest() != asset["sha256"]
261
+ or _jpeg_dimensions(image_bytes) != (asset["width"], asset["height"])
262
+ ):
263
+ raise SearchCommerceError(f"search commerce image integrity failed: {asin}")
264
+
265
+ seen_asins.add(asin)
266
+ seen_source_positions.add((str(source_department), int(source_index)))
267
+ normalized.append(
268
+ {
269
+ "asin": asin,
270
+ "slug": slug,
271
+ "canonical_path": canonical_path,
272
+ "title": title,
273
+ "brand": "",
274
+ "capacity": "",
275
+ "color": "",
276
+ "price_minor": price_minor,
277
+ "list_price_minor": None,
278
+ "currency": "USD",
279
+ "rating": rating_display,
280
+ # The legacy offer table needs an integer. Zero deliberately
281
+ # means "not exact"; presentation uses reviews_display below.
282
+ "reviews": reviews_exact if isinstance(reviews_exact, int) else 0,
283
+ "reviews_exact": reviews_exact,
284
+ "reviews_display": reviews_display,
285
+ "image_path": image_path,
286
+ "badge": "",
287
+ "evidence_class": SEARCH_COMMERCE_EVIDENCE_CLASS,
288
+ "department_slugs": (department,),
289
+ "captured_queries": (SEARCH_COMMERCE_QUERY,),
290
+ "source_index": source_index,
291
+ "source_department": source_department,
292
+ "sponsored": bool(raw["sponsored"]),
293
+ "format": product_format,
294
+ "card_evidence_key": (
295
+ f"{SEARCH_COMMERCE_FIXTURE}:{source_department}:"
296
+ f"{source_index}:{asin}"
297
+ ),
298
+ }
299
+ )
300
+
301
+ if dict(
302
+ Counter(product["department_slugs"][0] for product in normalized)
303
+ ) != EXPECTED_DEPARTMENT_COUNTS:
304
+ raise SearchCommerceError("search commerce department counts changed")
305
+ return tuple(normalized)
306
+
307
+
308
+ def load_search_commerce_cards(fixture_root: Path) -> tuple[dict[str, Any], ...]:
309
+ fixture_root = fixture_root.resolve()
310
+ candidate = (fixture_root / SEARCH_COMMERCE_FIXTURE).resolve()
311
+ if fixture_root not in candidate.parents or not candidate.is_file():
312
+ raise SearchCommerceError("search commerce fixture is unavailable")
313
+ try:
314
+ payload = json.loads(candidate.read_text(encoding="utf-8"))
315
+ except (OSError, json.JSONDecodeError) as exc:
316
+ raise SearchCommerceError("search commerce fixture is invalid") from exc
317
+ if not isinstance(payload, Mapping):
318
+ raise SearchCommerceError("search commerce fixture must be an object")
319
+ return normalize_search_commerce_cards(payload, fixture_root)
tasks/amazon/solution/site/implementation/clone/search_suggestions.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import unicodedata
5
+ from dataclasses import dataclass
6
+ from typing import Any, Iterable, Literal, Mapping
7
+ from urllib.parse import parse_qsl
8
+
9
+ from search_catalog import (
10
+ DEFAULT_SEARCH_DEPARTMENT,
11
+ SEARCH_DEPARTMENTS,
12
+ SOURCE_DEPARTMENTS,
13
+ SOURCE_DEPARTMENT_SLUG_BY_RAIL,
14
+ )
15
+
16
+
17
+ INVALID_PERCENT_ESCAPE_RE = re.compile(r"%(?![0-9a-fA-F]{2})")
18
+ TOKEN_RE = re.compile(r"[a-z0-9]+")
19
+ MAX_RAW_QUERY_LENGTH = 1_024
20
+ MAX_QUERY_LENGTH = 120
21
+ MAX_QUERY_FIELDS = 4
22
+ MAX_SUGGESTIONS = 10
23
+ MAX_SUGGESTION_VALUE_LENGTH = 180
24
+
25
+
26
+ class SearchSuggestionValidationError(ValueError):
27
+ """Raised when the public suggestion request is ambiguous or malformed."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class SearchSuggestionRequest:
32
+ query: str
33
+ department: str = DEFAULT_SEARCH_DEPARTMENT
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class SearchSuggestion:
38
+ value: str
39
+ kind: Literal["query", "department", "product"]
40
+ department: str | None = None
41
+
42
+
43
+ # These are shopping phrases already represented by the frozen local catalog,
44
+ # public routes, or directly captured PDP identity. They improve discovery but
45
+ # do not introduce prices, availability, ratings, or other product facts.
46
+ CATALOG_QUERY_TERMS: tuple[tuple[str, str | None], ...] = (
47
+ ("portable ssd", "computers"),
48
+ ("portable ssd 1tb", "computers"),
49
+ ("portable ssd 2tb", "computers"),
50
+ ("samsung portable ssd", "computers"),
51
+ ("sandisk portable ssd", "computers"),
52
+ ("external solid state drive", "computers"),
53
+ ("instant pot", "home-kitchen"),
54
+ ("picture frames", "home-kitchen"),
55
+ ("trading card binder", "toys-games"),
56
+ ("ipad screen protector", "computers"),
57
+ ("acne patches", "beauty-personal-care"),
58
+ ("jansport backpack", None),
59
+ ("air filter", None),
60
+ ("top picks singapore", None),
61
+ )
62
+
63
+
64
+ def _clean_text(value: str, *, label: str, limit: int) -> str:
65
+ if any(unicodedata.category(character) == "Cc" for character in value):
66
+ raise SearchSuggestionValidationError(f"{label} contains control characters")
67
+ cleaned = " ".join(value.strip().split())
68
+ if len(cleaned) > limit:
69
+ raise SearchSuggestionValidationError(f"{label} is too long")
70
+ return cleaned
71
+
72
+
73
+ def parse_suggestion_request(raw_query: str) -> SearchSuggestionRequest:
74
+ if len(raw_query) > MAX_RAW_QUERY_LENGTH:
75
+ raise SearchSuggestionValidationError("suggestion query is too long")
76
+ if INVALID_PERCENT_ESCAPE_RE.search(raw_query):
77
+ raise SearchSuggestionValidationError("suggestion query has invalid encoding")
78
+ try:
79
+ pairs = parse_qsl(
80
+ raw_query,
81
+ keep_blank_values=True,
82
+ encoding="utf-8",
83
+ errors="strict",
84
+ max_num_fields=MAX_QUERY_FIELDS,
85
+ )
86
+ except (UnicodeDecodeError, ValueError) as exc:
87
+ raise SearchSuggestionValidationError("suggestion query is malformed") from exc
88
+
89
+ unknown = {name for name, _ in pairs} - {"q", "i"}
90
+ if unknown:
91
+ raise SearchSuggestionValidationError("suggestion query has unsupported parameters")
92
+ query_values = [value for name, value in pairs if name == "q"]
93
+ department_values = [value for name, value in pairs if name == "i"]
94
+ if len(query_values) != 1 or len(department_values) > 1:
95
+ raise SearchSuggestionValidationError("suggestion query has duplicate parameters")
96
+
97
+ query = _clean_text(query_values[0], label="suggestion query", limit=MAX_QUERY_LENGTH)
98
+ department = (
99
+ _clean_text(
100
+ department_values[0],
101
+ label="suggestion department",
102
+ limit=64,
103
+ )
104
+ if department_values
105
+ else DEFAULT_SEARCH_DEPARTMENT
106
+ )
107
+ if department not in SEARCH_DEPARTMENTS:
108
+ raise SearchSuggestionValidationError("suggestion department is unsupported")
109
+ return SearchSuggestionRequest(query=query, department=department)
110
+
111
+
112
+ def _normalized(value: str) -> str:
113
+ return " ".join(TOKEN_RE.findall(unicodedata.normalize("NFKC", value).casefold()))
114
+
115
+
116
+ def _bounded_title(value: str) -> str:
117
+ cleaned = " ".join(value.split())
118
+ if len(cleaned) <= MAX_SUGGESTION_VALUE_LENGTH:
119
+ return cleaned
120
+ shortened = cleaned[: MAX_SUGGESTION_VALUE_LENGTH + 1].rsplit(" ", 1)[0]
121
+ return shortened.rstrip(" ,.;:-") + "…"
122
+
123
+
124
+ def build_suggestion_corpus(
125
+ catalog: Mapping[str, Mapping[str, Any]],
126
+ ) -> tuple[SearchSuggestion, ...]:
127
+ """Build a deterministic corpus from frozen department and product evidence."""
128
+
129
+ candidates: list[SearchSuggestion] = []
130
+ for department in SOURCE_DEPARTMENTS:
131
+ candidates.append(
132
+ SearchSuggestion(
133
+ value=str(department["query"]),
134
+ kind="department",
135
+ department=str(department["slug"]),
136
+ )
137
+ )
138
+ candidates.extend(
139
+ SearchSuggestion(value=value, kind="query", department=department)
140
+ for value, department in CATALOG_QUERY_TERMS
141
+ )
142
+
143
+ for product in catalog.values():
144
+ title = product.get("title")
145
+ placements = product.get("placements")
146
+ if not isinstance(title, str) or not title.strip():
147
+ continue
148
+ department: str | None = None
149
+ if isinstance(placements, list) and placements and isinstance(placements[0], Mapping):
150
+ rail_key = placements[0].get("railKey")
151
+ if isinstance(rail_key, str):
152
+ department = SOURCE_DEPARTMENT_SLUG_BY_RAIL.get(rail_key)
153
+ candidates.append(
154
+ SearchSuggestion(
155
+ value=_bounded_title(title),
156
+ kind="product",
157
+ department=department,
158
+ )
159
+ )
160
+
161
+ deduplicated: list[SearchSuggestion] = []
162
+ seen: set[str] = set()
163
+ for candidate in candidates:
164
+ key = _normalized(candidate.value)
165
+ if not key or key in seen:
166
+ continue
167
+ seen.add(key)
168
+ deduplicated.append(candidate)
169
+ return tuple(deduplicated)
170
+
171
+
172
+ def _match_rank(query: str, candidate: str) -> int | None:
173
+ if candidate.startswith(query):
174
+ return 0
175
+ query_tokens = query.split()
176
+ candidate_tokens = candidate.split()
177
+ if len(query_tokens) == 1 and any(token.startswith(query) for token in candidate_tokens):
178
+ return 1
179
+ if query_tokens and all(token in candidate_tokens for token in query_tokens):
180
+ return 2
181
+ if query in candidate:
182
+ return 3
183
+ return None
184
+
185
+
186
+ def suggest_search_terms(
187
+ request: SearchSuggestionRequest,
188
+ corpus: Iterable[SearchSuggestion],
189
+ *,
190
+ limit: int = MAX_SUGGESTIONS,
191
+ ) -> tuple[SearchSuggestion, ...]:
192
+ if not isinstance(limit, int) or not 1 <= limit <= MAX_SUGGESTIONS:
193
+ raise SearchSuggestionValidationError("suggestion limit is invalid")
194
+ normalized_query = _normalized(request.query)
195
+ if len(normalized_query) < 2:
196
+ return ()
197
+
198
+ kind_rank = {"query": 0, "department": 1, "product": 2}
199
+ ranked: list[tuple[int, int, int, int, SearchSuggestion]] = []
200
+ for source_index, candidate in enumerate(corpus):
201
+ if (
202
+ request.department != DEFAULT_SEARCH_DEPARTMENT
203
+ and candidate.department != request.department
204
+ ):
205
+ continue
206
+ normalized_candidate = _normalized(candidate.value)
207
+ match_rank = _match_rank(normalized_query, normalized_candidate)
208
+ if match_rank is None:
209
+ continue
210
+ ranked.append(
211
+ (
212
+ match_rank,
213
+ kind_rank[candidate.kind],
214
+ len(normalized_candidate),
215
+ source_index,
216
+ candidate,
217
+ )
218
+ )
219
+ ranked.sort(key=lambda item: item[:4])
220
+ return tuple(item[-1] for item in ranked[:limit])
tasks/amazon/solution/site/implementation/clone/server.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/solution/site/implementation/clone/specialty_views.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rendered local Gift Cards, Sell, Registry, and static Video placeholder pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from html import escape
6
+ from typing import Any, Iterable
7
+ from urllib.parse import urlencode
8
+
9
+ from render import layout, money
10
+ from specialty_store import (
11
+ GIFT_AMOUNTS_MINOR,
12
+ GIFT_CARD_BALANCE_PATH,
13
+ GIFT_CARD_PREVIEW_PATH,
14
+ GIFT_CARD_REDEEM_PATH,
15
+ GIFT_CARDS_PATH,
16
+ GIFT_DESIGNS,
17
+ PRIME_VIDEO_PATH,
18
+ REGISTRY_CREATE_PATH,
19
+ REGISTRY_DETAIL_PATH,
20
+ REGISTRY_PATH,
21
+ REGISTRY_SEARCH_PATH,
22
+ REGISTRY_TYPES,
23
+ SELL_CATEGORIES,
24
+ SELL_CONDITIONS,
25
+ SELL_DRAFT_PATH,
26
+ SELL_PATH,
27
+ )
28
+
29
+
30
+ CUSTOMER_SERVICE_HREF = "/gp/help/customer/display.html?nodeId=508510"
31
+
32
+
33
+ def _simulation_notice(copy: str) -> str:
34
+ return (
35
+ '<aside class="specialty-simulation-notice" role="note">'
36
+ '<strong>Local simulation</strong>'
37
+ f"<span>{escape(copy)}</span></aside>"
38
+ )
39
+
40
+
41
+ def gift_cards_page(cart_count: int, account_name: str | None = None) -> str:
42
+ account_href = (
43
+ "/gp/css/homepage.html"
44
+ if account_name
45
+ else "/ap/signin?openid.return_to=%2Fgift-cards%2Fb%2F"
46
+ )
47
+ account_action = "Go to your account" if account_name else "Sign in"
48
+ design_choices = "".join(
49
+ f'<label class="specialty-design-card specialty-design-{escape(key, quote=True)}">'
50
+ f'<input type="radio" name="design" value="{escape(key, quote=True)}"'
51
+ f'{" checked" if key == "classic" else ""}><span aria-hidden="true"></span>'
52
+ f"<strong>{escape(label)}</strong></label>"
53
+ for key, label in GIFT_DESIGNS.items()
54
+ )
55
+ amount_choices = "".join(
56
+ f'<label><input type="radio" name="amount" value="{amount // 100}"'
57
+ f'{" checked" if amount == 5000 else ""}><span>{money(amount, "USD")}</span></label>'
58
+ for amount in GIFT_AMOUNTS_MINOR
59
+ )
60
+ categories = (
61
+ ("Birthday", "/s?k=birthday+gifts", "Celebrate their day"),
62
+ ("Books", "/s?k=books", "For every kind of reader"),
63
+ ("Home & Kitchen", "/s?k=home+kitchen", "Useful picks for home"),
64
+ ("Toys & Games", "/s?k=toys", "For play and discovery"),
65
+ ("Beauty", "/s?k=beauty+personal+care", "Self-care favorites"),
66
+ ("Deals", "/gp/goldbox/", "Browse current offers"),
67
+ )
68
+ category_cards = "".join(
69
+ f'<a class="specialty-gift-category" href="{href}"><strong>{escape(title)}</strong>'
70
+ f"<span>{escape(copy)}</span><small>Explore ›</small></a>"
71
+ for title, href, copy in categories
72
+ )
73
+ body = f"""
74
+ <main id="main" class="specialty-main specialty-gift-main" data-navigation-page="gift-cards">
75
+ <section class="specialty-gift-hero">
76
+ <div><p>Amazon Gift Cards</p><h1>So many ways to celebrate</h1><span>Choose a card face and amount, then continue to a controlled local preview. No payment information is collected.</span></div>
77
+ <div class="specialty-gift-art specialty-design-classic" aria-hidden="true"><span>amazon</span><strong>Gift Card</strong><i></i></div>
78
+ </section>
79
+ <nav class="specialty-primary-actions" aria-label="Gift Card actions">
80
+ <a href="{GIFT_CARD_REDEEM_PATH}"><span aria-hidden="true">+</span><strong>Redeem</strong><small>Try a fictional local code</small></a>
81
+ <a href="{GIFT_CARD_BALANCE_PATH}"><span aria-hidden="true">$</span><strong>View balance</strong><small>See the simulated $0.00 balance</small></a>
82
+ <a href="#gift-card-builder"><span aria-hidden="true">↻</span><strong>Reload or buy</strong><small>Build a local purchase preview</small></a>
83
+ </nav>
84
+ {_simulation_notice("Gift Card previews do not create value, charge a card, send email, or connect to Amazon Gift Card services.")}
85
+ <section id="gift-card-builder" class="specialty-panel specialty-builder" aria-labelledby="gift-builder-heading">
86
+ <div class="specialty-section-heading"><p>Customers love these gift card styles</p><h2 id="gift-builder-heading">Build a local Gift Card preview</h2></div>
87
+ <form method="post" action="{GIFT_CARD_PREVIEW_PATH}" class="specialty-form">
88
+ <fieldset><legend>1. Choose a card face</legend><div class="specialty-design-grid">{design_choices}</div></fieldset>
89
+ <fieldset><legend>2. Choose an amount</legend><div class="specialty-amount-grid">{amount_choices}</div></fieldset>
90
+ <fieldset><legend>3. Who is it for?</legend><div class="specialty-choice-row"><label><input type="radio" name="recipientKind" value="gift" checked> Someone else</label><label><input type="radio" name="recipientKind" value="self"> Me</label></div></fieldset>
91
+ <button class="button primary" type="submit">Continue to local preview</button>
92
+ </form>
93
+ </section>
94
+ <section class="specialty-rail-section"><div class="specialty-section-heading"><p>Occasion, category, and delivery ideas</p><h2>Shop gifts by department</h2><span>Find a gift from the local catalog.</span></div><div class="specialty-category-grid">{category_cards}</div></section>
95
+ <section class="specialty-faq"><h2>Gift Card FAQ</h2><details><summary>Can I use a real Gift Card here?</summary><p>No. Do not enter a real claim code. This clone stores only an irreversible fingerprint of a fictional test code and never changes a real balance.</p></details><details><summary>Will the purchase preview charge me?</summary><p>No. It does not request card details and cannot complete a financial transaction.</p></details><details><summary>Where can I get account help?</summary><p><a href="{CUSTOMER_SERVICE_HREF}&amp;help_keywords=gift">Search Customer Service</a> or <a href="{account_href}">{account_action}</a>.</p></details></section>
96
+ </main>
97
+ """
98
+ return layout(
99
+ "Amazon.com Gift Cards",
100
+ body,
101
+ cart_count,
102
+ body_class="specialty-page gift-cards-page",
103
+ account_name=account_name,
104
+ )
105
+
106
+
107
+ def gift_card_preview_page(
108
+ preview: dict[str, Any], cart_count: int, account_name: str | None
109
+ ) -> str:
110
+ design = str(preview.get("design", "classic"))
111
+ design_label = GIFT_DESIGNS.get(design, GIFT_DESIGNS["classic"])
112
+ recipient = "For me" if preview.get("recipient_kind") == "self" else "For someone else"
113
+ amount = money(int(preview.get("amount_minor", 0)), "USD")
114
+ body = f"""
115
+ <main id="main" class="specialty-main specialty-result-main">
116
+ <nav class="specialty-breadcrumb"><a href="{GIFT_CARDS_PATH}">Gift Cards</a><span>›</span><strong>Local preview</strong></nav>
117
+ {_simulation_notice("This is a saved preview in this browser session. It is not in the cart and no payment or Gift Card value exists.")}
118
+ <section class="specialty-result-card">
119
+ <div class="specialty-gift-art specialty-design-{escape(design, quote=True)}" aria-label="{escape(design_label, quote=True)}"><span>amazon</span><strong>{amount}</strong><i></i></div>
120
+ <div><p>Local Gift Card preview #{int(preview['preview_id'])}</p><h1>{escape(design_label)}</h1><dl><dt>Amount</dt><dd>{amount}</dd><dt>Recipient</dt><dd>{escape(recipient)}</dd><dt>Status</dt><dd>Preview only — not purchased</dd></dl><div class="specialty-inline-actions"><a class="button primary" href="{GIFT_CARDS_PATH}#gift-card-builder">Change selection</a><a class="button secondary" href="{GIFT_CARD_BALANCE_PATH}">View simulated balance</a></div></div>
121
+ </section>
122
+ </main>
123
+ """
124
+ return layout(
125
+ "Gift Card local preview",
126
+ body,
127
+ cart_count,
128
+ body_class="specialty-page specialty-result-page",
129
+ account_name=account_name,
130
+ )
131
+
132
+
133
+ def gift_card_balance_page(
134
+ balance: dict[str, int],
135
+ cart_count: int,
136
+ account_name: str | None,
137
+ *,
138
+ redemption_result: bool = False,
139
+ ) -> str:
140
+ result = (
141
+ '<div class="specialty-generic-result" role="status"><strong>No balance was applied.</strong><span>This local simulation returns the same result for every well-formed fictional code.</span></div>'
142
+ if redemption_result
143
+ else ""
144
+ )
145
+ body = f"""
146
+ <main id="main" class="specialty-main specialty-balance-main">
147
+ <nav class="specialty-breadcrumb"><a href="{GIFT_CARDS_PATH}">Gift Cards</a><span>›</span><strong>Balance &amp; redemption</strong></nav>
148
+ <section class="specialty-balance-grid">
149
+ <div class="specialty-balance-card"><p>Local simulated balance</p><h1>{money(int(balance.get('balance_minor', 0)), 'USD')}</h1><span>No real Gift Card account is connected.</span><a href="{GIFT_CARDS_PATH}#gift-card-builder">Build a purchase preview</a></div>
150
+ <div class="specialty-panel"><h2>Redeem a fictional test code</h2><p>Do not enter a real Amazon Gift Card claim code. Raw input is never stored; only an irreversible fingerprint is retained.</p>{result}<form class="specialty-form" method="post" action="{GIFT_CARD_REDEEM_PATH}"><label for="claim-code">Fictional claim code</label><input id="claim-code" name="claimCode" autocomplete="off" minlength="8" maxlength="32" pattern="[A-Za-z0-9-]{{8,32}}" required><button class="button primary" type="submit">Try local redemption</button></form><small>Local attempts in this browser session: {int(balance.get('redemption_attempts', 0))}</small></div>
151
+ </section>
152
+ {_simulation_notice("Redemption never contacts Amazon and never applies monetary value. Public responses do not reveal whether any real-looking code exists.")}
153
+ </main>
154
+ """
155
+ return layout(
156
+ "Gift Card balance and redemption",
157
+ body,
158
+ cart_count,
159
+ body_class="specialty-page specialty-balance-page",
160
+ account_name=account_name,
161
+ )
162
+
163
+
164
+ def sell_page(
165
+ drafts: Iterable[dict[str, Any]], cart_count: int, account_name: str | None
166
+ ) -> str:
167
+ category_options = "".join(
168
+ f'<option value="{escape(key, quote=True)}">{escape(label)}</option>'
169
+ for key, label in SELL_CATEGORIES.items()
170
+ )
171
+ condition_options = "".join(
172
+ f'<option value="{escape(key, quote=True)}">{escape(label)}</option>'
173
+ for key, label in SELL_CONDITIONS.items()
174
+ )
175
+ draft_cards = "".join(
176
+ f'<a class="specialty-draft-row" href="{SELL_DRAFT_PATH}?{urlencode({"draftID": int(draft["draft_id"])})}"><span><strong>{escape(str(draft["title"]))}</strong><small>{escape(SELL_CATEGORIES.get(str(draft["category"]), str(draft["category"])))}</small></span><b>{money(int(draft["price_minor"]), "USD")}</b></a>'
177
+ for draft in drafts
178
+ ) or '<p class="specialty-empty">No listing drafts saved in this browser session yet.</p>'
179
+ body = f"""
180
+ <main id="main" class="specialty-main specialty-sell-main" data-navigation-page="sell">
181
+ <section class="specialty-sell-hero"><div><p>Sell on Amazon</p><h1>Create an Amazon selling account</h1><span>This clone cannot create a real seller account. You can save a server-validated listing draft locally to understand the flow.</span><div class="specialty-inline-actions"><a class="button primary" href="#listing-draft">Start a local draft</a><a class="button secondary" href="/ap/register">Create an account</a></div></div><div class="specialty-sell-visual" aria-hidden="true"><span>1</span><span>2</span><span>3</span></div></section>
182
+ {_simulation_notice("Nothing saved here is published, searchable by other shoppers, or sent to Amazon. No seller identity, tax, bank, or payout data is collected.")}
183
+ <section class="specialty-question-grid"><article><span>1</span><h2>What will you sell?</h2><p>Choose a supported local catalog category and write a clear title.</p></article><article><span>2</span><h2>How will you offer it?</h2><p>Set condition, price, and quantity. The server validates every field.</p></article><article><span>3</span><h2>Ready to publish?</h2><p>Review the local result. Publishing and fulfillment stay intentionally unavailable.</p></article></section>
184
+ <section id="listing-draft" class="specialty-panel specialty-sell-form-panel"><div><p>Getting started</p><h2>Save a local listing draft</h2><p>Estimate gross listing value from price × quantity without implying fees, revenue, or real sales.</p></div><form method="post" action="{SELL_DRAFT_PATH}" class="specialty-form specialty-two-column-form"><label>Product title<input name="title" minlength="5" maxlength="100" required></label><label>Category<select name="category" required>{category_options}</select></label><label>Condition<select name="condition" required>{condition_options}</select></label><label>Price in USD<input name="price" inputmode="decimal" placeholder="29.99" pattern="(?:[1-9][0-9]{{0,3}}|5000)(?:\\.[0-9]{{2}})?" required></label><label>Quantity<input name="quantity" type="number" min="1" max="30" value="1" required></label><label class="specialty-field-wide">Description<textarea name="description" maxlength="500" rows="4"></textarea></label><button class="button primary specialty-field-wide" type="submit">Save local draft</button></form></section>
185
+ <section class="specialty-rail-section"><div class="specialty-section-heading"><p>Your browser session</p><h2>Saved listing drafts</h2></div><div class="specialty-draft-list">{draft_cards}</div></section>
186
+ <section class="specialty-benefit-grid"><article><h2>Why model selling?</h2><p>It connects catalog information, inventory choices, validation, and a review step.</p></article><article><h2>Local incentives</h2><p>There are no promotional credits or seller benefits in this clone.</p></article><article><h2>Next step</h2><p>Use the saved result to review data before a hypothetical publish action.</p></article></section>
187
+ </main>
188
+ """
189
+ return layout(
190
+ "Sell on Amazon - local draft",
191
+ body,
192
+ cart_count,
193
+ body_class="specialty-page specialty-sell-page",
194
+ account_name=account_name,
195
+ )
196
+
197
+
198
+ def seller_draft_page(
199
+ draft: dict[str, Any], cart_count: int, account_name: str | None
200
+ ) -> str:
201
+ gross_minor = int(draft["price_minor"]) * int(draft["quantity"])
202
+ body = f"""
203
+ <main id="main" class="specialty-main specialty-result-main"><nav class="specialty-breadcrumb"><a href="{SELL_PATH}">Sell on Amazon</a><span>›</span><strong>Listing draft</strong></nav>{_simulation_notice("This draft belongs only to this browser session and is not a public Amazon listing.")}<section class="specialty-result-card specialty-listing-result"><div class="specialty-listing-placeholder" aria-hidden="true">DRAFT</div><div><p>Local listing draft #{int(draft['draft_id'])}</p><h1>{escape(str(draft['title']))}</h1><dl><dt>Category</dt><dd>{escape(SELL_CATEGORIES.get(str(draft['category']), str(draft['category'])))}</dd><dt>Condition</dt><dd>{escape(SELL_CONDITIONS.get(str(draft['item_condition']), str(draft['item_condition'])))}</dd><dt>Unit price</dt><dd>{money(int(draft['price_minor']), 'USD')}</dd><dt>Quantity</dt><dd>{int(draft['quantity'])}</dd><dt>Gross listing value</dt><dd>{money(gross_minor, 'USD')} before any hypothetical fees</dd><dt>Status</dt><dd>Local draft — not published</dd></dl>{f'<p>{escape(str(draft["description"]))}</p>' if draft.get('description') else ''}<a class="button primary" href="{SELL_PATH}#listing-draft">Create another draft</a></div></section></main>
204
+ """
205
+ return layout(
206
+ "Local seller listing draft",
207
+ body,
208
+ cart_count,
209
+ body_class="specialty-page specialty-result-page",
210
+ account_name=account_name,
211
+ )
212
+
213
+
214
+ def registry_page(
215
+ own_registries: Iterable[dict[str, Any]], cart_count: int, account_name: str | None
216
+ ) -> str:
217
+ type_cards = "".join(
218
+ f'<a class="specialty-registry-type" href="#create-registry"><span aria-hidden="true">{icon}</span><strong>{escape(label)}</strong><small>{escape(copy)}</small></a>'
219
+ for (key, label), icon, copy in zip(
220
+ REGISTRY_TYPES.items(),
221
+ ("💍", "🧸", "🎁"),
222
+ ("Plan shared gift ideas", "Prepare for a new arrival", "Collect ideas for any occasion"),
223
+ )
224
+ )
225
+ type_options = "".join(
226
+ f'<option value="{escape(key, quote=True)}">{escape(label)}</option>'
227
+ for key, label in REGISTRY_TYPES.items()
228
+ )
229
+ own_cards = "".join(
230
+ f'<a class="specialty-draft-row" href="{REGISTRY_DETAIL_PATH}?{urlencode({"registryID": int(item["registry_id"])})}"><span><strong>{escape(str(item["registry_name"]))}</strong><small>{escape(REGISTRY_TYPES.get(str(item["registry_type"]), str(item["registry_type"])))}</small></span><b>Private local draft</b></a>'
231
+ for item in own_registries
232
+ ) or '<p class="specialty-empty">No registry drafts saved in this browser session.</p>'
233
+ body = f"""
234
+ <main id="main" class="specialty-main specialty-registry-main" data-navigation-page="registry">
235
+ <section class="specialty-registry-hero"><div><p>Registry &amp; Gift List</p><h1>Find a registry or create your own</h1><span>Search local demo registries and your own private browser-session drafts.</span></div><form method="get" action="{REGISTRY_SEARCH_PATH}" class="specialty-search-form" role="search"><label for="registry-search">Find a registry</label><div><input id="registry-search" name="query" minlength="2" maxlength="60" placeholder="Name or registry title" required><button class="button primary" type="submit">Search</button></div><a href="#create-registry">Create a registry</a></form></section>
236
+ {_simulation_notice("Registry drafts are private to this browser session. They are not published to Amazon and are never exposed in another visitor's search results.")}
237
+ <section class="specialty-rail-section"><div class="specialty-section-heading"><p>Choose the list that fits</p><h2>Baby Registry, Wedding Registry, and Gift List</h2></div><div class="specialty-registry-types">{type_cards}</div></section>
238
+ <section id="create-registry" class="specialty-panel specialty-registry-form-panel"><div><p>Create and personalize</p><h2>Start a private local registry draft</h2><p>After saving, build the idea list by browsing Books, Home, Toys, Beauty, or Electronics.</p></div><form method="post" action="{REGISTRY_CREATE_PATH}" class="specialty-form specialty-two-column-form"><label>Registry type<select name="registryType" required>{type_options}</select></label><label>Your display name<input name="ownerName" minlength="2" maxlength="80" required></label><label>Registry name<input name="registryName" minlength="3" maxlength="100" required></label><label>Event date (optional)<input name="eventDate" type="date" min="2000-01-01" max="2100-12-31"></label><button class="button primary specialty-field-wide" type="submit">Create private local draft</button></form></section>
239
+ <section class="specialty-rail-section"><div class="specialty-section-heading"><p>Reasons and benefits</p><h2>One place to organize gift ideas</h2></div><div class="specialty-benefit-grid"><article><h3>Personalize</h3><p>Name the event and choose the kind of registry.</p></article><article><h3>Build</h3><p>Use the live catalog links on the saved detail page.</p></article><article><h3>Keep it private</h3><p>Only the creating browser session can open the draft.</p></article></div><div class="specialty-draft-list">{own_cards}</div></section>
240
+ </main>
241
+ """
242
+ return layout(
243
+ "Amazon Registry & Gift List",
244
+ body,
245
+ cart_count,
246
+ body_class="specialty-page specialty-registry-page",
247
+ account_name=account_name,
248
+ )
249
+
250
+
251
+ def registry_search_page(
252
+ query: str,
253
+ results: Iterable[dict[str, Any]],
254
+ cart_count: int,
255
+ account_name: str | None,
256
+ ) -> str:
257
+ cards: list[str] = []
258
+ for item in results:
259
+ label = REGISTRY_TYPES.get(str(item.get("registry_type")), "Gift List")
260
+ if item.get("is_own"):
261
+ href = REGISTRY_DETAIL_PATH + "?" + urlencode(
262
+ {"registryID": int(item["registry_id"])}
263
+ )
264
+ action = f'<a href="{href}">Open your private draft</a>'
265
+ else:
266
+ action = "<span>Local demo result — no personal data</span>"
267
+ cards.append(
268
+ f'<article class="specialty-search-result"><p>{escape(label)}</p><h2>{escape(str(item["registry_name"]))}</h2><small>{escape(str(item["owner_name"]))}</small>{action}</article>'
269
+ )
270
+ result_markup = "".join(cards) or '<p class="specialty-empty">No local demo or private draft matched that search.</p>'
271
+ body = f"""
272
+ <main id="main" class="specialty-main specialty-search-main"><nav class="specialty-breadcrumb"><a href="{REGISTRY_PATH}">Registry</a><span>›</span><strong>Search</strong></nav><section class="specialty-panel"><form method="get" action="{REGISTRY_SEARCH_PATH}" class="specialty-search-form"><label for="registry-search-results">Find a registry</label><div><input id="registry-search-results" name="query" value="{escape(query, quote=True)}" minlength="2" maxlength="60" required><button class="button primary" type="submit">Search</button></div></form><h1>Results for “{escape(query)}”</h1><div class="specialty-search-results">{result_markup}</div></section>{_simulation_notice("Only built-in demo entries and registries owned by this browser session are searchable here.")}</main>
273
+ """
274
+ return layout(
275
+ "Find a local registry",
276
+ body,
277
+ cart_count,
278
+ body_class="specialty-page specialty-registry-page",
279
+ account_name=account_name,
280
+ )
281
+
282
+
283
+ def registry_detail_page(
284
+ item: dict[str, Any], cart_count: int, account_name: str | None
285
+ ) -> str:
286
+ date_copy = escape(str(item.get("event_date") or "No event date selected"))
287
+ body = f"""
288
+ <main id="main" class="specialty-main specialty-result-main"><nav class="specialty-breadcrumb"><a href="{REGISTRY_PATH}">Registry</a><span>›</span><strong>Private draft</strong></nav>{_simulation_notice("This registry exists only in the creating browser session and is not published or shared.")}<section class="specialty-result-card specialty-registry-result"><div class="specialty-registry-emblem" aria-hidden="true">🎁</div><div><p>{escape(REGISTRY_TYPES.get(str(item['registry_type']), 'Gift List'))}</p><h1>{escape(str(item['registry_name']))}</h1><dl><dt>Owner</dt><dd>{escape(str(item['owner_name']))}</dd><dt>Event date</dt><dd>{date_copy}</dd><dt>Status</dt><dd>Private local draft</dd></dl><h2>Start building your list</h2><div class="specialty-inline-actions"><a href="/s?k=books">Books</a><a href="/s?k=home+kitchen">Home</a><a href="/s?k=toys">Toys</a><a href="/s?k=beauty+personal+care">Beauty</a></div></div></section></main>
289
+ """
290
+ return layout(
291
+ "Private local registry draft",
292
+ body,
293
+ cart_count,
294
+ body_class="specialty-page specialty-result-page",
295
+ account_name=account_name,
296
+ )
297
+
298
+
299
+ def prime_video_page(cart_count: int, account_name: str | None) -> str:
300
+ body = f"""
301
+ <main id="main" class="specialty-video-main" data-navigation-page="prime-video">
302
+ <nav class="specialty-video-nav" aria-label="Prime Video local placeholder"><a class="specialty-video-brand" href="{PRIME_VIDEO_PATH}">prime video <small>local</small></a><a aria-current="page" href="{PRIME_VIDEO_PATH}">Home</a></nav>
303
+ <section class="specialty-video-placeholder"><div><p>PRIME VIDEO</p><h1>Video service is outside this shopping clone</h1><span>This reachable placeholder does not model a catalog, subscription, stream, rental, purchase, watchlist, or viewing history.</span><div class="specialty-inline-actions"><a class="button primary" href="/">Continue shopping</a><a class="button secondary" href="/gp/help/customer/display.html?nodeId=508510">Customer Service</a></div></div></section>
304
+ <aside class="specialty-video-notice"><strong>No streaming service connected</strong><span>Nothing on this page represents real Prime Video availability or entitlement.</span></aside>
305
+ </main>
306
+ """
307
+ return layout(
308
+ "Prime Video - local placeholder",
309
+ body,
310
+ cart_count,
311
+ body_class="specialty-video-page",
312
+ account_name=account_name,
313
+ )
tasks/amazon/solution/site/implementation/clone/store.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/solution/site/implementation/clone/wishlist_store.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import sqlite3
6
+ import unicodedata
7
+ from collections.abc import Mapping
8
+ from functools import lru_cache
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from home_catalog import load_home_product_catalog
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from store import Store
17
+
18
+
19
+ DEFAULT_LIST_NAME = "Shopping List"
20
+ MAX_LIST_NAME_LENGTH = 100
21
+ _ASIN_RE = re.compile(r"[A-Z0-9]{10}\Z")
22
+
23
+
24
+ class WishlistError(Exception):
25
+ """Base class for stable Wishlist service failures."""
26
+
27
+
28
+ class WishlistAuthenticationRequired(WishlistError):
29
+ """The browser session is not bound to an account."""
30
+
31
+
32
+ class WishlistNotFound(WishlistError):
33
+ """The requested account-owned list or item does not exist."""
34
+
35
+
36
+ class WishlistValidationError(WishlistError):
37
+ """A caller supplied malformed or unsupported Wishlist input."""
38
+
39
+
40
+ class WishlistConflict(WishlistError):
41
+ """The requested mutation conflicts with an account invariant."""
42
+
43
+
44
+ _WISHLIST_SCHEMA = """
45
+ CREATE TABLE IF NOT EXISTS wishlist_lists (
46
+ list_id INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ account_id INTEGER NOT NULL
48
+ REFERENCES accounts(account_id) ON DELETE CASCADE,
49
+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
50
+ name_key TEXT NOT NULL,
51
+ is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),
52
+ created_at TEXT NOT NULL,
53
+ updated_at TEXT NOT NULL,
54
+ UNIQUE (account_id, name_key)
55
+ );
56
+
57
+ CREATE UNIQUE INDEX IF NOT EXISTS wishlist_one_default_per_account_idx
58
+ ON wishlist_lists(account_id)
59
+ WHERE is_default = 1;
60
+
61
+ CREATE INDEX IF NOT EXISTS wishlist_lists_account_idx
62
+ ON wishlist_lists(account_id, is_default DESC, list_id);
63
+
64
+ CREATE TABLE IF NOT EXISTS wishlist_items (
65
+ item_id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ list_id INTEGER NOT NULL
67
+ REFERENCES wishlist_lists(list_id) ON DELETE CASCADE,
68
+ asin TEXT NOT NULL CHECK (
69
+ length(asin) = 10 AND asin NOT GLOB '*[^A-Z0-9]*'
70
+ ),
71
+ selection_json TEXT NOT NULL,
72
+ created_at TEXT NOT NULL,
73
+ UNIQUE (list_id, asin, selection_json)
74
+ );
75
+
76
+ CREATE INDEX IF NOT EXISTS wishlist_items_list_idx
77
+ ON wishlist_items(list_id, item_id DESC);
78
+ """
79
+
80
+
81
+ def ensure_wishlist_schema(store: Store) -> None:
82
+ """Install the additive Wishlist schema without changing the core schema file."""
83
+
84
+ with store.connect() as connection:
85
+ connection.executescript(_WISHLIST_SCHEMA)
86
+
87
+
88
+ def _canonical_identifier(value: int | str, label: str) -> int:
89
+ if isinstance(value, bool):
90
+ raise WishlistValidationError(f"{label} must be a positive integer")
91
+ if isinstance(value, int):
92
+ result = value
93
+ elif (
94
+ isinstance(value, str)
95
+ and value
96
+ and value.isascii()
97
+ and value.isdecimal()
98
+ and not (len(value) > 1 and value.startswith("0"))
99
+ ):
100
+ result = int(value)
101
+ else:
102
+ raise WishlistValidationError(f"{label} must be a positive integer")
103
+ if result <= 0:
104
+ raise WishlistValidationError(f"{label} must be a positive integer")
105
+ return result
106
+
107
+
108
+ def _canonical_name(value: str) -> tuple[str, str]:
109
+ if not isinstance(value, str):
110
+ raise WishlistValidationError("list name must be text")
111
+ normalized = unicodedata.normalize("NFKC", value)
112
+ name = " ".join(normalized.split())
113
+ if not name or len(name) > MAX_LIST_NAME_LENGTH:
114
+ raise WishlistValidationError(
115
+ f"list name must contain 1 to {MAX_LIST_NAME_LENGTH} characters"
116
+ )
117
+ if any(unicodedata.category(character).startswith("C") for character in name):
118
+ raise WishlistValidationError("list name contains unsupported characters")
119
+ return name, name.casefold()
120
+
121
+
122
+ def _canonical_asin(value: str) -> str:
123
+ if not isinstance(value, str) or _ASIN_RE.fullmatch(value) is None:
124
+ raise WishlistValidationError("ASIN must use the canonical 10-character form")
125
+ return value
126
+
127
+
128
+ def _require_account_id(
129
+ connection: sqlite3.Connection, session_digest: str
130
+ ) -> int:
131
+ row = connection.execute(
132
+ "SELECT account_id FROM browser_sessions WHERE session_digest=?",
133
+ (session_digest,),
134
+ ).fetchone()
135
+ if row is None or row["account_id"] is None:
136
+ raise WishlistAuthenticationRequired("sign in to use Lists")
137
+ return int(row["account_id"])
138
+
139
+
140
+ def _ensure_default_list(
141
+ store: Store, connection: sqlite3.Connection, account_id: int
142
+ ) -> int:
143
+ rows = connection.execute(
144
+ """
145
+ SELECT list_id,is_default
146
+ FROM wishlist_lists
147
+ WHERE account_id=?
148
+ ORDER BY is_default DESC,list_id
149
+ """,
150
+ (account_id,),
151
+ ).fetchall()
152
+ if not rows:
153
+ now = store.now(connection)
154
+ cursor = connection.execute(
155
+ """
156
+ INSERT INTO wishlist_lists(
157
+ account_id,name,name_key,is_default,created_at,updated_at
158
+ ) VALUES (?,?,?,?,?,?)
159
+ """,
160
+ (
161
+ account_id,
162
+ DEFAULT_LIST_NAME,
163
+ DEFAULT_LIST_NAME.casefold(),
164
+ 1,
165
+ now,
166
+ now,
167
+ ),
168
+ )
169
+ return int(cursor.lastrowid)
170
+
171
+ default_rows = [row for row in rows if bool(row["is_default"])]
172
+ if default_rows:
173
+ return int(default_rows[0]["list_id"])
174
+
175
+ default_list_id = int(rows[0]["list_id"])
176
+ connection.execute(
177
+ "UPDATE wishlist_lists SET is_default=1 WHERE list_id=?",
178
+ (default_list_id,),
179
+ )
180
+ return default_list_id
181
+
182
+
183
+ def _prepare_session(store: Store, session_digest: str) -> None:
184
+ if not isinstance(session_digest, str) or not session_digest:
185
+ raise WishlistAuthenticationRequired("sign in to use Lists")
186
+ ensure_wishlist_schema(store)
187
+ store.ensure_session(session_digest)
188
+
189
+
190
+ def _owned_list_row(
191
+ connection: sqlite3.Connection, account_id: int, list_id: int
192
+ ) -> sqlite3.Row:
193
+ row = connection.execute(
194
+ """
195
+ SELECT l.*,
196
+ (SELECT COUNT(*) FROM wishlist_items i WHERE i.list_id=l.list_id)
197
+ AS item_count
198
+ FROM wishlist_lists l
199
+ WHERE l.list_id=? AND l.account_id=?
200
+ """,
201
+ (list_id, account_id),
202
+ ).fetchone()
203
+ if row is None:
204
+ # Missing and foreign-owned identifiers deliberately share one result.
205
+ raise WishlistNotFound("list not found")
206
+ return row
207
+
208
+
209
+ def _list_payload(row: sqlite3.Row) -> dict[str, Any]:
210
+ return {
211
+ "list_id": int(row["list_id"]),
212
+ "name": str(row["name"]),
213
+ "is_default": bool(row["is_default"]),
214
+ "item_count": int(row["item_count"]),
215
+ "created_at": str(row["created_at"]),
216
+ "updated_at": str(row["updated_at"]),
217
+ }
218
+
219
+
220
+ def _decode_selection(raw_value: Any) -> dict[str, str]:
221
+ try:
222
+ payload = json.loads(str(raw_value))
223
+ except (json.JSONDecodeError, TypeError) as exc:
224
+ raise WishlistValidationError("stored Wishlist selection is corrupted") from exc
225
+ if not isinstance(payload, dict) or any(
226
+ not isinstance(label, str) or not isinstance(value, str)
227
+ for label, value in payload.items()
228
+ ):
229
+ raise WishlistValidationError("stored Wishlist selection is corrupted")
230
+ return payload
231
+
232
+
233
+ @lru_cache(maxsize=8)
234
+ def _home_catalog(fixture_root: str) -> dict[str, dict[str, Any]]:
235
+ return load_home_product_catalog(Path(fixture_root))
236
+
237
+
238
+ def _trusted_product(store: Store, asin: str) -> dict[str, Any] | None:
239
+ """Resolve display facts from server-owned fixtures and tables only."""
240
+
241
+ home_product = _home_catalog(str(store.fixture_root)).get(asin)
242
+ if home_product is not None and home_product.get("evidence_tier") == "pdp-direct":
243
+ product = dict(home_product)
244
+ else:
245
+ offer = store.commerce_offer(asin)
246
+ catalog_product = store.product(asin)
247
+ if offer is not None:
248
+ product = dict(offer)
249
+ elif catalog_product is not None:
250
+ product = dict(catalog_product)
251
+ elif home_product is not None:
252
+ product = dict(home_product)
253
+ else:
254
+ return None
255
+
256
+ product["asin"] = asin
257
+ product["canonical_path"] = str(
258
+ product.get("canonical_path") or f"/dp/{asin}"
259
+ )
260
+ product["brand"] = str(product.get("brand") or "")
261
+ return product
262
+
263
+
264
+ def _matching_quote(
265
+ store: Store, asin: str, selected_options: Mapping[str, str]
266
+ ) -> dict[str, Any] | None:
267
+ if store.commerce_offer(asin) is None:
268
+ return None
269
+ for quote in store.product_option_quotes(asin):
270
+ if (
271
+ quote.get("selected_options") == dict(selected_options)
272
+ and quote.get("availability") == "AVAILABLE"
273
+ ):
274
+ return quote
275
+ return None
276
+
277
+
278
+ def _quote_available(
279
+ store: Store, asin: str, selected_options: Mapping[str, str]
280
+ ) -> bool:
281
+ return _matching_quote(store, asin, selected_options) is not None
282
+
283
+
284
+ def _item_payload(store: Store, row: sqlite3.Row) -> dict[str, Any]:
285
+ asin = str(row["asin"])
286
+ selected_options = _decode_selection(row["selection_json"])
287
+ product = _trusted_product(store, asin)
288
+ if product is None:
289
+ raise WishlistValidationError("stored Wishlist product is no longer trusted")
290
+ quote = _matching_quote(store, asin, selected_options)
291
+ available_to_cart = quote is not None
292
+ payload: dict[str, Any] = {
293
+ "item_id": int(row["item_id"]),
294
+ "list_id": int(row["list_id"]),
295
+ "asin": asin,
296
+ "selected_options": selected_options,
297
+ "created_at": str(row["created_at"]),
298
+ "title": str(product["title"]),
299
+ "brand": str(product.get("brand") or ""),
300
+ "canonical_path": str(product["canonical_path"]),
301
+ "image_path": str(
302
+ quote.get("image_path")
303
+ if quote is not None and quote.get("image_path")
304
+ else product["image_path"]
305
+ ),
306
+ # Display prices are joined from the current server-owned offer. They
307
+ # are never accepted from, or persisted on behalf of, the browser.
308
+ "price_minor": int(quote["price_minor"]) if quote is not None else None,
309
+ "currency": str(quote["currency"]) if quote is not None else None,
310
+ "rating": str(product.get("rating") or ""),
311
+ "reviews": int(product.get("reviews") or 0),
312
+ "badge": str(product.get("badge") or ""),
313
+ "available_to_cart": available_to_cart,
314
+ }
315
+ return payload
316
+
317
+
318
+ _ITEM_SELECT = """
319
+ SELECT i.item_id,i.list_id,i.asin,i.selection_json,i.created_at
320
+ FROM wishlist_items i
321
+ """
322
+
323
+
324
+ def _item_row(
325
+ connection: sqlite3.Connection,
326
+ account_id: int,
327
+ list_id: int,
328
+ item_id: int,
329
+ ) -> sqlite3.Row:
330
+ row = connection.execute(
331
+ _ITEM_SELECT
332
+ + """
333
+ JOIN wishlist_lists l ON l.list_id=i.list_id
334
+ WHERE i.item_id=? AND i.list_id=? AND l.account_id=?
335
+ """,
336
+ (item_id, list_id, account_id),
337
+ ).fetchone()
338
+ if row is None:
339
+ # Do not reveal whether either identifier belongs to another account.
340
+ raise WishlistNotFound("item not found")
341
+ return row
342
+
343
+
344
+ def _canonical_selection(
345
+ store: Store, asin: str, selected_options: Mapping[str, Any]
346
+ ) -> dict[str, str]:
347
+ if not isinstance(selected_options, Mapping):
348
+ raise WishlistValidationError("product option selection must be a mapping")
349
+
350
+ if _trusted_product(store, asin) is None:
351
+ raise WishlistNotFound("product not found")
352
+
353
+ specification = store.product_option_spec(asin)
354
+ expected_labels = {str(group["label"]) for group in specification}
355
+ if set(selected_options) != expected_labels:
356
+ raise WishlistValidationError(
357
+ "product option selection is incomplete or unsupported"
358
+ )
359
+
360
+ canonical: dict[str, str] = {}
361
+ for group in specification:
362
+ label = str(group["label"])
363
+ value = selected_options.get(label)
364
+ allowed = tuple(str(option) for option in group["options"])
365
+ if not isinstance(value, str) or value not in allowed:
366
+ raise WishlistValidationError(
367
+ f"unsupported observed option value for {label}"
368
+ )
369
+ canonical[label] = value
370
+
371
+ # Reject option combinations that have no server-owned transaction quote.
372
+ if store.commerce_offer(asin) is not None and not _quote_available(
373
+ store, asin, canonical
374
+ ):
375
+ raise WishlistValidationError("this selection is not available")
376
+ return canonical
377
+
378
+
379
+ def product_selection_for_wishlist(
380
+ store: Store, asin: str, selected_options: Mapping[str, Any]
381
+ ) -> tuple[dict[str, Any], dict[str, str]]:
382
+ """Return one trusted product and its canonical complete option selection.
383
+
384
+ This is the read-only boundary used by the HTTP chooser. It validates the
385
+ same server-owned catalog and option contract as :func:`add_item` without
386
+ mutating a list or accepting browser-supplied display facts.
387
+ """
388
+
389
+ canonical_asin = _canonical_asin(asin)
390
+ canonical_options = _canonical_selection(
391
+ store, canonical_asin, selected_options
392
+ )
393
+ product = _trusted_product(store, canonical_asin)
394
+ if product is None:
395
+ raise WishlistNotFound("product not found")
396
+ quote = _matching_quote(store, canonical_asin, canonical_options)
397
+ if quote is not None and quote.get("image_path"):
398
+ product = {**product, "image_path": str(quote["image_path"])}
399
+ return product, canonical_options
400
+
401
+
402
+ def lists_for_session(store: Store, session_digest: str) -> list[dict[str, Any]]:
403
+ """Return account-owned lists, creating Shopping List on first access."""
404
+
405
+ _prepare_session(store, session_digest)
406
+ with store.connect() as connection:
407
+ connection.execute("BEGIN IMMEDIATE")
408
+ account_id = _require_account_id(connection, session_digest)
409
+ _ensure_default_list(store, connection, account_id)
410
+ rows = connection.execute(
411
+ """
412
+ SELECT l.*,
413
+ (SELECT COUNT(*) FROM wishlist_items i WHERE i.list_id=l.list_id)
414
+ AS item_count
415
+ FROM wishlist_lists l
416
+ WHERE l.account_id=?
417
+ ORDER BY l.is_default DESC,l.list_id
418
+ """,
419
+ (account_id,),
420
+ ).fetchall()
421
+ connection.commit()
422
+ return [_list_payload(row) for row in rows]
423
+
424
+
425
+ def default_list_for_session(store: Store, session_digest: str) -> dict[str, Any]:
426
+ lists = lists_for_session(store, session_digest)
427
+ return next(wishlist for wishlist in lists if wishlist["is_default"])
428
+
429
+
430
+ def list_for_session(
431
+ store: Store, session_digest: str, list_id: int | str
432
+ ) -> dict[str, Any]:
433
+ """Return one owned list with its current server-side product displays."""
434
+
435
+ canonical_list_id = _canonical_identifier(list_id, "list id")
436
+ _prepare_session(store, session_digest)
437
+ with store.connect() as connection:
438
+ connection.execute("BEGIN IMMEDIATE")
439
+ account_id = _require_account_id(connection, session_digest)
440
+ _ensure_default_list(store, connection, account_id)
441
+ list_row = _owned_list_row(connection, account_id, canonical_list_id)
442
+ item_rows = connection.execute(
443
+ _ITEM_SELECT
444
+ + " WHERE i.list_id=? ORDER BY i.item_id DESC",
445
+ (canonical_list_id,),
446
+ ).fetchall()
447
+ connection.commit()
448
+ result = _list_payload(list_row)
449
+ result["items"] = [_item_payload(store, row) for row in item_rows]
450
+ return result
451
+
452
+
453
+ def create_list(
454
+ store: Store, session_digest: str, name: str
455
+ ) -> dict[str, Any]:
456
+ canonical_name, name_key = _canonical_name(name)
457
+ _prepare_session(store, session_digest)
458
+ with store.connect() as connection:
459
+ connection.execute("BEGIN IMMEDIATE")
460
+ account_id = _require_account_id(connection, session_digest)
461
+ _ensure_default_list(store, connection, account_id)
462
+ now = store.now(connection)
463
+ try:
464
+ cursor = connection.execute(
465
+ """
466
+ INSERT INTO wishlist_lists(
467
+ account_id,name,name_key,is_default,created_at,updated_at
468
+ ) VALUES (?,?,?,?,?,?)
469
+ """,
470
+ (account_id, canonical_name, name_key, 0, now, now),
471
+ )
472
+ except sqlite3.IntegrityError as exc:
473
+ raise WishlistConflict("a list with that name already exists") from exc
474
+ row = _owned_list_row(connection, account_id, int(cursor.lastrowid))
475
+ connection.commit()
476
+ return _list_payload(row)
477
+
478
+
479
+ def rename_list(
480
+ store: Store,
481
+ session_digest: str,
482
+ list_id: int | str,
483
+ name: str,
484
+ ) -> dict[str, Any]:
485
+ canonical_list_id = _canonical_identifier(list_id, "list id")
486
+ canonical_name, name_key = _canonical_name(name)
487
+ _prepare_session(store, session_digest)
488
+ with store.connect() as connection:
489
+ connection.execute("BEGIN IMMEDIATE")
490
+ account_id = _require_account_id(connection, session_digest)
491
+ _ensure_default_list(store, connection, account_id)
492
+ _owned_list_row(connection, account_id, canonical_list_id)
493
+ try:
494
+ connection.execute(
495
+ """
496
+ UPDATE wishlist_lists
497
+ SET name=?,name_key=?,updated_at=?
498
+ WHERE list_id=? AND account_id=?
499
+ """,
500
+ (
501
+ canonical_name,
502
+ name_key,
503
+ store.now(connection),
504
+ canonical_list_id,
505
+ account_id,
506
+ ),
507
+ )
508
+ except sqlite3.IntegrityError as exc:
509
+ raise WishlistConflict("a list with that name already exists") from exc
510
+ row = _owned_list_row(connection, account_id, canonical_list_id)
511
+ connection.commit()
512
+ return _list_payload(row)
513
+
514
+
515
+ def delete_list(
516
+ store: Store, session_digest: str, list_id: int | str
517
+ ) -> dict[str, int]:
518
+ """Delete one owned list while preserving exactly one account default."""
519
+
520
+ canonical_list_id = _canonical_identifier(list_id, "list id")
521
+ _prepare_session(store, session_digest)
522
+ with store.connect() as connection:
523
+ connection.execute("BEGIN IMMEDIATE")
524
+ account_id = _require_account_id(connection, session_digest)
525
+ _ensure_default_list(store, connection, account_id)
526
+ row = _owned_list_row(connection, account_id, canonical_list_id)
527
+ count = int(
528
+ connection.execute(
529
+ "SELECT COUNT(*) FROM wishlist_lists WHERE account_id=?",
530
+ (account_id,),
531
+ ).fetchone()[0]
532
+ )
533
+ if count <= 1:
534
+ raise WishlistConflict("an account must keep at least one list")
535
+
536
+ connection.execute(
537
+ "DELETE FROM wishlist_lists WHERE list_id=? AND account_id=?",
538
+ (canonical_list_id, account_id),
539
+ )
540
+ if bool(row["is_default"]):
541
+ replacement = connection.execute(
542
+ """
543
+ SELECT list_id FROM wishlist_lists
544
+ WHERE account_id=? ORDER BY list_id LIMIT 1
545
+ """,
546
+ (account_id,),
547
+ ).fetchone()
548
+ if replacement is None:
549
+ raise WishlistConflict("an account must keep at least one list")
550
+ default_list_id = int(replacement["list_id"])
551
+ connection.execute(
552
+ "UPDATE wishlist_lists SET is_default=1 WHERE list_id=?",
553
+ (default_list_id,),
554
+ )
555
+ else:
556
+ default_row = connection.execute(
557
+ """
558
+ SELECT list_id FROM wishlist_lists
559
+ WHERE account_id=? AND is_default=1
560
+ """,
561
+ (account_id,),
562
+ ).fetchone()
563
+ if default_row is None:
564
+ default_list_id = _ensure_default_list(
565
+ store, connection, account_id
566
+ )
567
+ else:
568
+ default_list_id = int(default_row["list_id"])
569
+ connection.commit()
570
+ return {
571
+ "deleted_list_id": canonical_list_id,
572
+ "default_list_id": default_list_id,
573
+ }
574
+
575
+
576
+ def add_item(
577
+ store: Store,
578
+ session_digest: str,
579
+ list_id: int | str,
580
+ asin: str,
581
+ selected_options: Mapping[str, Any],
582
+ ) -> dict[str, Any]:
583
+ """Idempotently add one fully specified server-verifiable product."""
584
+
585
+ canonical_list_id = _canonical_identifier(list_id, "list id")
586
+ canonical_asin = _canonical_asin(asin)
587
+ _prepare_session(store, session_digest)
588
+
589
+ # Authorize the opaque list id before validating product input so a foreign
590
+ # list id cannot be used as a behavioral oracle.
591
+ with store.connect() as connection:
592
+ account_id = _require_account_id(connection, session_digest)
593
+ _owned_list_row(connection, account_id, canonical_list_id)
594
+
595
+ canonical_options = _canonical_selection(
596
+ store, canonical_asin, selected_options
597
+ )
598
+ selection_json = json.dumps(
599
+ canonical_options,
600
+ ensure_ascii=True,
601
+ sort_keys=True,
602
+ separators=(",", ":"),
603
+ )
604
+
605
+ with store.connect() as connection:
606
+ connection.execute("BEGIN IMMEDIATE")
607
+ account_id = _require_account_id(connection, session_digest)
608
+ _owned_list_row(connection, account_id, canonical_list_id)
609
+ cursor = connection.execute(
610
+ """
611
+ INSERT INTO wishlist_items(list_id,asin,selection_json,created_at)
612
+ VALUES (?,?,?,?)
613
+ ON CONFLICT(list_id,asin,selection_json) DO NOTHING
614
+ """,
615
+ (
616
+ canonical_list_id,
617
+ canonical_asin,
618
+ selection_json,
619
+ store.now(connection),
620
+ ),
621
+ )
622
+ created = cursor.rowcount == 1
623
+ item_row = connection.execute(
624
+ _ITEM_SELECT
625
+ + """
626
+ WHERE i.list_id=? AND i.asin=? AND i.selection_json=?
627
+ """,
628
+ (canonical_list_id, canonical_asin, selection_json),
629
+ ).fetchone()
630
+ if item_row is None:
631
+ raise WishlistConflict("Wishlist item could not be persisted")
632
+ connection.execute(
633
+ "UPDATE wishlist_lists SET updated_at=? WHERE list_id=?",
634
+ (store.now(connection), canonical_list_id),
635
+ )
636
+ connection.commit()
637
+ return {"created": created, "item": _item_payload(store, item_row)}
638
+
639
+
640
+ def remove_item(
641
+ store: Store,
642
+ session_digest: str,
643
+ list_id: int | str,
644
+ item_id: int | str,
645
+ ) -> dict[str, Any]:
646
+ canonical_list_id = _canonical_identifier(list_id, "list id")
647
+ canonical_item_id = _canonical_identifier(item_id, "item id")
648
+ _prepare_session(store, session_digest)
649
+ with store.connect() as connection:
650
+ connection.execute("BEGIN IMMEDIATE")
651
+ account_id = _require_account_id(connection, session_digest)
652
+ row = _item_row(
653
+ connection, account_id, canonical_list_id, canonical_item_id
654
+ )
655
+ connection.execute(
656
+ "DELETE FROM wishlist_items WHERE item_id=? AND list_id=?",
657
+ (canonical_item_id, canonical_list_id),
658
+ )
659
+ connection.execute(
660
+ "UPDATE wishlist_lists SET updated_at=? WHERE list_id=?",
661
+ (store.now(connection), canonical_list_id),
662
+ )
663
+ connection.commit()
664
+ return _item_payload(store, row)
665
+
666
+
667
+ def item_for_move_to_cart(
668
+ store: Store,
669
+ session_digest: str,
670
+ list_id: int | str,
671
+ item_id: int | str,
672
+ ) -> dict[str, Any]:
673
+ """Return only the trusted cart identity; leave deletion to the caller.
674
+
675
+ The route can first add this identity to the account cart and only then call
676
+ :func:`remove_item`, avoiding data loss when cart insertion fails.
677
+ """
678
+
679
+ canonical_list_id = _canonical_identifier(list_id, "list id")
680
+ canonical_item_id = _canonical_identifier(item_id, "item id")
681
+ _prepare_session(store, session_digest)
682
+ with store.connect() as connection:
683
+ account_id = _require_account_id(connection, session_digest)
684
+ row = _item_row(
685
+ connection, account_id, canonical_list_id, canonical_item_id
686
+ )
687
+ selected_options = _decode_selection(row["selection_json"])
688
+ canonical_options = _canonical_selection(
689
+ store, str(row["asin"]), selected_options
690
+ )
691
+ if not _quote_available(store, str(row["asin"]), canonical_options):
692
+ raise WishlistConflict("this product is not available for cart")
693
+ return {
694
+ "list_id": canonical_list_id,
695
+ "item_id": canonical_item_id,
696
+ "asin": str(row["asin"]),
697
+ "selected_options": canonical_options,
698
+ }
tasks/amazon/solution/site/implementation/clone/wishlist_views.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from html import escape
4
+ from typing import Any
5
+ from urllib.parse import urlencode
6
+
7
+ from render import layout, money, selected_options_markup
8
+
9
+
10
+ WISHLIST_INTRO_PATH = "/hz/wishlist/intro"
11
+ WISHLIST_INDEX_PATH = "/hz/wishlist/ls"
12
+ WISHLIST_CREATE_PATH = "/hz/wishlist/create"
13
+ WISHLIST_RENAME_PATH = "/hz/wishlist/rename"
14
+ WISHLIST_DELETE_PATH = "/hz/wishlist/delete"
15
+ WISHLIST_ADD_CHOOSER_PATH = "/hz/wishlist/add"
16
+ WISHLIST_ADD_ITEM_PATH = "/hz/wishlist/add-item"
17
+ WISHLIST_REMOVE_ITEM_PATH = "/hz/wishlist/remove-item"
18
+ WISHLIST_MOVE_TO_CART_PATH = "/hz/wishlist/move-to-cart"
19
+
20
+ WISHLIST_ASSET_ROOT = (
21
+ "/static/assets/source-current/2026-07-22/lists-intro"
22
+ )
23
+ WISHLIST_STYLESHEET = "/static/wishlist.css?v=20260722-1"
24
+
25
+
26
+ def _wishlist_layout(
27
+ title: str,
28
+ body: str,
29
+ cart_count: int,
30
+ *,
31
+ account_name: str | None = None,
32
+ body_class: str = "",
33
+ ) -> str:
34
+ return layout(
35
+ title,
36
+ body,
37
+ cart_count,
38
+ account_name=account_name,
39
+ body_class=f"wishlist-surface {body_class}".strip(),
40
+ extra_head=(
41
+ f'<link rel="stylesheet" href="{WISHLIST_STYLESHEET}">'
42
+ ),
43
+ )
44
+
45
+
46
+ def _signin_href(return_to: str = WISHLIST_INDEX_PATH) -> str:
47
+ query = urlencode({"openid.return_to": return_to})
48
+ return f"/ap/signin?{escape(query, quote=True)}"
49
+
50
+
51
+ def _detail_href(list_id: int | str) -> str:
52
+ query = urlencode({"listID": str(list_id)})
53
+ return f"{WISHLIST_INDEX_PATH}?{escape(query, quote=True)}"
54
+
55
+
56
+ def wishlist_entry_form(
57
+ product: dict[str, Any],
58
+ selected_options: dict[str, str],
59
+ *,
60
+ button_label: str = "Add to List",
61
+ css_class: str = "add-to-list-form",
62
+ ) -> str:
63
+ """Build the PDP/search entry form that opens the authenticated chooser.
64
+
65
+ ``data-product-option-field`` lets the existing PDP option controller keep
66
+ this form's complete selection synchronized with visible variant controls.
67
+ The form deliberately contains no browser-supplied price or offer metadata.
68
+ """
69
+
70
+ asin = escape(str(product["asin"]), quote=True)
71
+ option_fields = "".join(
72
+ f'<input type="hidden" name="option.{escape(label, quote=True)}" value="{escape(value, quote=True)}" data-product-option-field="{escape(label, quote=True)}">'
73
+ for label, value in selected_options.items()
74
+ )
75
+ return f"""
76
+ <form class="{escape(css_class, quote=True)}" method="get" action="{WISHLIST_ADD_CHOOSER_PATH}" data-wishlist-form="open-add-chooser">
77
+ <input type="hidden" name="ASIN" value="{asin}">
78
+ {option_fields}
79
+ <button type="submit">{escape(button_label)}</button>
80
+ </form>
81
+ """
82
+
83
+
84
+ def wishlist_intro_page(cart_count: int) -> str:
85
+ """Render the anonymous Your Lists introduction at desktop and mobile widths."""
86
+
87
+ signin_href = _signin_href()
88
+ desktop_benefits = (
89
+ (
90
+ "save-money.png",
91
+ "Save money",
92
+ "Keep products together and check back when prices change.",
93
+ ),
94
+ (
95
+ "shop-with-friends.png",
96
+ "Shop with friends",
97
+ "Keep gift ideas together for birthdays, holidays, and everyday shopping.",
98
+ ),
99
+ (
100
+ "stay-organized.png",
101
+ "Stay organized",
102
+ "Build as many lists as you need and find every saved item quickly.",
103
+ ),
104
+ )
105
+ desktop_benefit_markup = "".join(
106
+ f"""
107
+ <article class="wishlist-benefit-card">
108
+ <img src="{WISHLIST_ASSET_ROOT}/{image_name}" alt="" loading="lazy">
109
+ <h3>{escape(title)}</h3>
110
+ <p>{escape(copy)}</p>
111
+ </article>
112
+ """
113
+ for image_name, title, copy in desktop_benefits
114
+ )
115
+
116
+ desktop_registries = (
117
+ (
118
+ "baby-registry.jpg",
119
+ "Baby Registry",
120
+ "Get ready for your new arrival with everything in one place.",
121
+ "/gp/browse.html?node=16115931011",
122
+ ),
123
+ (
124
+ "wedding-registry.jpg",
125
+ "Wedding Registry",
126
+ "Create a registry that makes gifting simple for everyone.",
127
+ "/gp/browse.html?node=16115931011",
128
+ ),
129
+ (
130
+ "custom-gift.jpg",
131
+ "Gift List",
132
+ "Save gift ideas for birthdays, holidays, and other celebrations.",
133
+ "/gp/browse.html?node=16115931011",
134
+ ),
135
+ )
136
+ desktop_registry_markup = "".join(
137
+ f"""
138
+ <a class="wishlist-registry-card" href="{escape(href, quote=True)}">
139
+ <img src="{WISHLIST_ASSET_ROOT}/{image_name}" alt="" loading="lazy">
140
+ <span><strong>{escape(title)}</strong>{escape(copy)}</span>
141
+ </a>
142
+ """
143
+ for image_name, title, copy, href in desktop_registries
144
+ )
145
+
146
+ mobile_benefits = (
147
+ ("Save time", "Add products now and come back whenever you're ready."),
148
+ ("Give great gifts", "Keep thoughtful gift ideas together in one place."),
149
+ ("Check price changes", "See the latest offer each time you open your list."),
150
+ ("Check current deals", "Keep your favorite products together for easy deal checking."),
151
+ )
152
+ mobile_benefit_markup = "".join(
153
+ f"""
154
+ <li><span aria-hidden="true">✓</span><div><strong>{escape(title)}</strong><p>{escape(copy)}</p></div></li>
155
+ """
156
+ for title, copy in mobile_benefits
157
+ )
158
+
159
+ body = f"""
160
+ <main id="main" class="wishlist-intro" data-wishlist-page="intro">
161
+ <section class="wishlist-intro-desktop" aria-label="Your Lists">
162
+ <nav class="wishlist-intro-tabs" aria-label="Lists navigation">
163
+ <a class="is-active" href="{WISHLIST_INTRO_PATH}" aria-current="page">Your Lists</a>
164
+ <a href="/hz/wishlist/your-friends">Your Friends</a>
165
+ </nav>
166
+
167
+ <section class="wishlist-intro-hero">
168
+ <img src="{WISHLIST_ASSET_ROOT}/desktop-banner.jpg" alt="" fetchpriority="high">
169
+ <div>
170
+ <h1>Lists &amp; Registries</h1>
171
+ <p>Save products you love, keep ideas organized, and plan gifts for the people who matter.</p>
172
+ </div>
173
+ </section>
174
+
175
+ <section class="wishlist-benefits" aria-labelledby="wishlist-benefits-title">
176
+ <h2 id="wishlist-benefits-title">Why use Lists?</h2>
177
+ <div class="wishlist-benefit-grid">{desktop_benefit_markup}</div>
178
+ <a class="wishlist-primary-button" href="{signin_href}">Sign In</a>
179
+ </section>
180
+
181
+ <section class="wishlist-registries" aria-labelledby="wishlist-registries-title">
182
+ <h2 id="wishlist-registries-title">Gift Registries</h2>
183
+ <div class="wishlist-registry-grid">{desktop_registry_markup}</div>
184
+ </section>
185
+ </section>
186
+
187
+ <section class="wishlist-intro-mobile" aria-label="Your Lists">
188
+ <a class="wishlist-primary-button wishlist-mobile-signin" href="{signin_href}">Sign In</a>
189
+ <p class="wishlist-mobile-signin-note">Sign in to see your Lists and Registries.</p>
190
+
191
+ <section class="wishlist-mobile-list-kind">
192
+ <img src="{WISHLIST_ASSET_ROOT}/mobile-list-icon.png" alt="">
193
+ <div><h1>Shopping List</h1><p>Save everyday items, compare choices, and buy them when you're ready.</p></div>
194
+ </section>
195
+ <section class="wishlist-mobile-list-kind">
196
+ <img src="{WISHLIST_ASSET_ROOT}/mobile-gift-icon.png" alt="">
197
+ <div><h2>Wish List</h2><p>Collect gift ideas for family, friends, and special occasions.</p></div>
198
+ </section>
199
+
200
+ <ul class="wishlist-mobile-benefits" aria-label="List benefits">{mobile_benefit_markup}</ul>
201
+
202
+ <section class="wishlist-mobile-registries" aria-labelledby="wishlist-mobile-registries-title">
203
+ <h2 id="wishlist-mobile-registries-title">Create a Registry</h2>
204
+ <a href="/gp/browse.html?node=16115931011"><img src="{WISHLIST_ASSET_ROOT}/mobile-baby-registry.png" alt="Baby Registry"><span>Baby Registry</span></a>
205
+ <a href="/gp/browse.html?node=16115931011"><img src="{WISHLIST_ASSET_ROOT}/mobile-wedding-registry.png" alt="Wedding Registry"><span>Wedding Registry</span></a>
206
+ </section>
207
+ </section>
208
+ </main>
209
+ """
210
+ return _wishlist_layout(
211
+ "Amazon Lists",
212
+ body,
213
+ cart_count,
214
+ body_class="wishlist-intro-body",
215
+ )
216
+
217
+
218
+ def _list_card(wishlist: dict[str, Any]) -> str:
219
+ list_id = int(wishlist["list_id"])
220
+ name = escape(str(wishlist["name"]))
221
+ item_count = int(wishlist.get("item_count", 0))
222
+ item_copy = "1 item" if item_count == 1 else f"{item_count} items"
223
+ default_badge = (
224
+ '<span class="wishlist-default-badge">Default</span>'
225
+ if bool(wishlist.get("is_default"))
226
+ else ""
227
+ )
228
+ return f"""
229
+ <article class="wishlist-list-card" data-list-id="{list_id}">
230
+ <a href="{_detail_href(list_id)}">
231
+ <span class="wishlist-list-card-icon" aria-hidden="true">☰</span>
232
+ <span class="wishlist-list-card-copy"><strong>{name}</strong><small>{item_copy}</small></span>
233
+ {default_badge}
234
+ <span class="wishlist-list-card-arrow" aria-hidden="true">›</span>
235
+ </a>
236
+ </article>
237
+ """
238
+
239
+
240
+ def wishlist_index_page(
241
+ wishlists: list[dict[str, Any]],
242
+ cart_count: int,
243
+ account_name: str,
244
+ *,
245
+ status: str = "",
246
+ ) -> str:
247
+ """Render the authenticated list index and the create-list affordance."""
248
+
249
+ list_markup = "".join(_list_card(wishlist) for wishlist in wishlists)
250
+ status_markup = (
251
+ f'<div class="wishlist-status" role="status">{escape(status)}</div>'
252
+ if status
253
+ else ""
254
+ )
255
+ body = f"""
256
+ <main id="main" class="wishlist-app" data-wishlist-page="index">
257
+ <header class="wishlist-page-heading">
258
+ <div><p>Your Account › Your Lists</p><h1>Your Lists</h1></div>
259
+ </header>
260
+ {status_markup}
261
+ <div class="wishlist-index-layout">
262
+ <section class="wishlist-list-collection" aria-labelledby="wishlist-owned-title">
263
+ <h2 id="wishlist-owned-title">Your lists</h2>
264
+ <div class="wishlist-list-grid">{list_markup}</div>
265
+ </section>
266
+ <aside class="wishlist-create-card">
267
+ <h2>Create a List</h2>
268
+ <p>Use Lists to save products and keep purchases organized.</p>
269
+ <form method="post" action="{WISHLIST_CREATE_PATH}" data-wishlist-form="create">
270
+ <label for="wishlist-new-name">List name</label>
271
+ <input id="wishlist-new-name" name="listName" maxlength="100" autocomplete="off" required>
272
+ <button class="wishlist-primary-button" type="submit">Create List</button>
273
+ </form>
274
+ </aside>
275
+ </div>
276
+ </main>
277
+ """
278
+ return _wishlist_layout(
279
+ "Your Lists",
280
+ body,
281
+ cart_count,
282
+ account_name=account_name,
283
+ body_class="wishlist-app-body",
284
+ )
285
+
286
+
287
+ def _list_rail(wishlists: list[dict[str, Any]], active_list_id: int) -> str:
288
+ links = "".join(
289
+ f"""
290
+ <a href="{_detail_href(int(wishlist['list_id']))}"{' class="is-active" aria-current="page"' if int(wishlist['list_id']) == active_list_id else ''}>
291
+ <span>{escape(str(wishlist['name']))}</span><small>{int(wishlist.get('item_count', 0))}</small>
292
+ </a>
293
+ """
294
+ for wishlist in wishlists
295
+ )
296
+ return f"""
297
+ <aside class="wishlist-list-rail" aria-label="Your lists">
298
+ <a class="wishlist-back-link" href="{WISHLIST_INDEX_PATH}">‹ All Lists</a>
299
+ <nav>{links}</nav>
300
+ </aside>
301
+ """
302
+
303
+
304
+ def _wishlist_item(item: dict[str, Any], list_id: int) -> str:
305
+ item_id = int(item["item_id"])
306
+ asin = escape(str(item["asin"]), quote=True)
307
+ title = escape(str(item["title"]))
308
+ image_path = escape(str(item["image_path"]), quote=True)
309
+ href = escape(str(item["canonical_path"]), quote=True)
310
+ available_to_cart = bool(item.get("available_to_cart"))
311
+ raw_price = item.get("price_minor")
312
+ currency = str(item.get("currency") or "USD")
313
+ options = selected_options_markup(
314
+ item, css_class="wishlist-item-options"
315
+ )
316
+ if available_to_cart and isinstance(raw_price, int):
317
+ offer_markup = f"<strong>{money(raw_price, currency)}</strong>"
318
+ cart_control = f"""
319
+ <form method="post" action="{WISHLIST_MOVE_TO_CART_PATH}" data-wishlist-form="move-to-cart">
320
+ <input type="hidden" name="listID" value="{list_id}">
321
+ <input type="hidden" name="itemID" value="{item_id}">
322
+ <input type="hidden" name="quantity" value="1">
323
+ <button class="wishlist-primary-button" type="submit">Add to Cart</button>
324
+ </form>
325
+ """
326
+ availability_copy = '<p class="wishlist-item-stock">In Stock</p>'
327
+ else:
328
+ offer_markup = '<strong class="wishlist-item-unavailable">Offer unavailable</strong>'
329
+ cart_control = '<button class="wishlist-secondary-button" type="button" disabled>Unavailable for Cart</button>'
330
+ availability_copy = '<p class="wishlist-item-unavailable-copy">No verified local offer for this product.</p>'
331
+ return f"""
332
+ <article class="wishlist-item" data-item-id="{item_id}" data-asin="{asin}">
333
+ <a class="wishlist-item-image" href="{href}"><img src="{image_path}" alt="{escape(str(item['title']), quote=True)}" loading="lazy"></a>
334
+ <div class="wishlist-item-copy">
335
+ <a class="wishlist-item-title" href="{href}">{title}</a>
336
+ {options}
337
+ {availability_copy}
338
+ <p class="wishlist-item-added">Added to this List</p>
339
+ </div>
340
+ <div class="wishlist-item-purchase">
341
+ {offer_markup}
342
+ {cart_control}
343
+ <form method="post" action="{WISHLIST_REMOVE_ITEM_PATH}" data-wishlist-form="remove-item">
344
+ <input type="hidden" name="listID" value="{list_id}">
345
+ <input type="hidden" name="itemID" value="{item_id}">
346
+ <button class="wishlist-secondary-button" type="submit">Delete</button>
347
+ </form>
348
+ </div>
349
+ </article>
350
+ """
351
+
352
+
353
+ def wishlist_detail_page(
354
+ wishlist: dict[str, Any],
355
+ wishlists: list[dict[str, Any]],
356
+ cart_count: int,
357
+ account_name: str,
358
+ *,
359
+ status: str = "",
360
+ ) -> str:
361
+ """Render one authenticated list with account-owned item controls."""
362
+
363
+ list_id = int(wishlist["list_id"])
364
+ name = escape(str(wishlist["name"]))
365
+ items = wishlist.get("items")
366
+ if not isinstance(items, list):
367
+ items = []
368
+ if items:
369
+ item_markup = "".join(_wishlist_item(item, list_id) for item in items)
370
+ else:
371
+ item_markup = """
372
+ <section class="wishlist-empty" aria-label="Empty list">
373
+ <span aria-hidden="true">♡</span>
374
+ <h2>This List is empty</h2>
375
+ <p>Browse products and choose <strong>Add to List</strong> on a product page.</p>
376
+ <a class="wishlist-primary-button" href="/">Continue shopping</a>
377
+ </section>
378
+ """
379
+ status_markup = (
380
+ f'<div class="wishlist-status" role="status">{escape(status)}</div>'
381
+ if status
382
+ else ""
383
+ )
384
+ default_copy = (
385
+ '<span class="wishlist-default-badge">Default List</span>'
386
+ if bool(wishlist.get("is_default"))
387
+ else ""
388
+ )
389
+ delete_control = (
390
+ ""
391
+ if len(wishlists) <= 1
392
+ else f"""
393
+ <form method="post" action="{WISHLIST_DELETE_PATH}" data-wishlist-form="delete-list">
394
+ <input type="hidden" name="listID" value="{list_id}">
395
+ <button class="wishlist-link-button" type="submit">Delete List</button>
396
+ </form>
397
+ """
398
+ )
399
+ body = f"""
400
+ <main id="main" class="wishlist-app" data-wishlist-page="detail" data-list-id="{list_id}">
401
+ {status_markup}
402
+ <div class="wishlist-detail-layout">
403
+ {_list_rail(wishlists, list_id)}
404
+ <section class="wishlist-detail-content">
405
+ <header class="wishlist-detail-heading">
406
+ <div><h1>{name}</h1>{default_copy}<p>{len(items)} {'item' if len(items) == 1 else 'items'}</p></div>
407
+ <details class="wishlist-manage-menu">
408
+ <summary>More</summary>
409
+ <div>
410
+ <form method="post" action="{WISHLIST_RENAME_PATH}" data-wishlist-form="rename-list">
411
+ <input type="hidden" name="listID" value="{list_id}">
412
+ <label for="wishlist-rename-{list_id}">Rename List</label>
413
+ <input id="wishlist-rename-{list_id}" name="listName" value="{escape(str(wishlist['name']), quote=True)}" maxlength="100" required>
414
+ <button class="wishlist-secondary-button" type="submit">Save</button>
415
+ </form>
416
+ {delete_control}
417
+ </div>
418
+ </details>
419
+ </header>
420
+ <div class="wishlist-items">{item_markup}</div>
421
+ </section>
422
+ </div>
423
+ </main>
424
+ """
425
+ return _wishlist_layout(
426
+ str(wishlist["name"]),
427
+ body,
428
+ cart_count,
429
+ account_name=account_name,
430
+ body_class="wishlist-app-body",
431
+ )
432
+
433
+
434
+ def wishlist_add_chooser_page(
435
+ product: dict[str, Any],
436
+ selected_options: dict[str, str],
437
+ wishlists: list[dict[str, Any]],
438
+ cart_count: int,
439
+ account_name: str,
440
+ ) -> str:
441
+ """Render a signed-in list chooser without embedding a client price."""
442
+
443
+ asin = escape(str(product["asin"]), quote=True)
444
+ title = escape(str(product["title"]))
445
+ image_path = escape(str(product["image_path"]), quote=True)
446
+ default_list = next(
447
+ (wishlist for wishlist in wishlists if wishlist.get("is_default")),
448
+ wishlists[0] if wishlists else None,
449
+ )
450
+ option_fields = "".join(
451
+ f'<input type="hidden" name="option.{escape(label, quote=True)}" value="{escape(value, quote=True)}">'
452
+ for label, value in selected_options.items()
453
+ )
454
+ option_markup = selected_options_markup(
455
+ {"selected_options": selected_options},
456
+ css_class="wishlist-chooser-options",
457
+ )
458
+ list_choices = "".join(
459
+ f"""
460
+ <label class="wishlist-chooser-list">
461
+ <input type="radio" name="listID" value="{int(wishlist['list_id'])}"{' checked' if default_list is not None and int(wishlist['list_id']) == int(default_list['list_id']) else ''} required>
462
+ <span><strong>{escape(str(wishlist['name']))}</strong><small>{int(wishlist.get('item_count', 0))} {'item' if int(wishlist.get('item_count', 0)) == 1 else 'items'}</small></span>
463
+ </label>
464
+ """
465
+ for wishlist in wishlists
466
+ )
467
+ if not list_choices:
468
+ list_choices = '<p class="wishlist-chooser-error">No List is available for this account.</p>'
469
+
470
+ body = f"""
471
+ <main id="main" class="wishlist-chooser-page" data-wishlist-page="add-chooser" data-asin="{asin}">
472
+ <section class="wishlist-chooser-card">
473
+ <header><a href="{WISHLIST_INDEX_PATH}">Your Lists</a><h1>Add to List</h1></header>
474
+ <div class="wishlist-chooser-product">
475
+ <img src="{image_path}" alt="{escape(str(product['title']), quote=True)}">
476
+ <div><strong>{title}</strong>{option_markup}</div>
477
+ </div>
478
+ <form method="post" action="{WISHLIST_ADD_ITEM_PATH}" data-wishlist-form="add-item">
479
+ <input type="hidden" name="ASIN" value="{asin}">
480
+ {option_fields}
481
+ <fieldset><legend>Choose a List</legend>{list_choices}</fieldset>
482
+ <div class="wishlist-chooser-actions">
483
+ <a class="wishlist-secondary-button" href="{escape(str(product.get('canonical_path') or '/'), quote=True)}">Cancel</a>
484
+ <button class="wishlist-primary-button" type="submit"{' disabled' if not wishlists else ''}>Add to List</button>
485
+ </div>
486
+ </form>
487
+ </section>
488
+ </main>
489
+ """
490
+ return _wishlist_layout(
491
+ "Add to List",
492
+ body,
493
+ cart_count,
494
+ account_name=account_name,
495
+ body_class="wishlist-chooser-body",
496
+ )
tasks/amazon/solution/site/implementation/compile.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -Eeuo pipefail
3
+ root="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
4
+ cat > "$root/executable" <<'EOF'
5
+ #!/usr/bin/env python3
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import random
10
+ import runpy
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+
16
+ ROOT = Path(__file__).resolve().parent
17
+ for name in ("HOST", "PORT", "DATA_DIR", "SEED", "TZ"):
18
+ if not os.environ.get(name):
19
+ raise SystemExit(f"{name} is required")
20
+ data_dir = Path(os.environ["DATA_DIR"])
21
+ if not data_dir.is_absolute():
22
+ raise SystemExit("DATA_DIR must be absolute")
23
+ data_dir.mkdir(parents=True, exist_ok=True)
24
+ try:
25
+ random.seed(int(os.environ["SEED"]))
26
+ except ValueError:
27
+ raise SystemExit("SEED must be an integer") from None
28
+ if hasattr(time, "tzset"):
29
+ time.tzset()
30
+ os.environ["WEBSITEBENCH_DATA_DIR"] = str(data_dir)
31
+ os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(
32
+ ROOT / "backend" / "runtime.json"
33
+ )
34
+ os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor"
35
+ os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = "local-sandbox"
36
+ for name in (
37
+ "STRIPE_SECRET_KEY",
38
+ "STRIPE_WEBHOOK_SECRET",
39
+ "STRIPE_TEST_SECRET_KEY",
40
+ "STRIPE_TEST_WEBHOOK_SECRET",
41
+ "PETFINDER_STRIPE_TEST_SECRET_KEY",
42
+ "PETFINDER_STRIPE_TEST_WEBHOOK_SECRET",
43
+ ):
44
+ os.environ.pop(name, None)
45
+ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
46
+ os.environ["PYTHONUNBUFFERED"] = "1"
47
+ os.environ["PYTHONPATH"] = str(ROOT / "vendor")
48
+ os.execvp("python3", ["python3", str(ROOT / "clone" / "harbor_entry.py")])
49
+ EOF
50
+ chmod 755 "$root/executable"
tasks/amazon/solution/site/implementation/run.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ root="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
4
+ cd "$root"
5
+ : "${HOST:=127.0.0.1}"
6
+ : "${PORT:=8080}"
7
+ : "${DATA_DIR:=/tmp/websitebench-reference-data}"
8
+ : "${SEED:=0}"
9
+ : "${TZ:=UTC}"
10
+ export HOST PORT DATA_DIR SEED TZ
11
+ exec ./executable
tasks/amazon/solution/site/implementation/vendor.requirements.in ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated-doc==0.0.4
2
+ annotated-types==0.8.0
3
+ anyio==4.14.2
4
+ click==8.4.2
5
+ fastapi==0.139.2
6
+ h11==0.16.0
7
+ idna==3.18
8
+ jinja2==3.1.6
9
+ markupsafe==3.0.3
10
+ pillow==12.3.0
11
+ pydantic==2.13.4
12
+ pydantic-core==2.46.4
13
+ python-multipart==0.0.32
14
+ starlette==1.3.1
15
+ typing-extensions==4.16.0
16
+ typing-inspection==0.4.2
17
+ uvicorn==0.51.0
tasks/amazon/solution/site/implementation/vendor.requirements.lock ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated-doc==0.0.4 \
2
+ --hash=sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320 \
3
+ --hash=sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4
4
+ annotated-types==0.8.0 \
5
+ --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \
6
+ --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
7
+ anyio==4.14.2 \
8
+ --hash=sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494 \
9
+ --hash=sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f
10
+ click==8.4.2 \
11
+ --hash=sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6 \
12
+ --hash=sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76
13
+ fastapi==0.139.2 \
14
+ --hash=sha256:333145a6891e9b5b3cfceb69baf817e8240cde4d4588ae5a10bf56ffacb6255e \
15
+ --hash=sha256:b9ad015a835173d59865e2f5d8296fbc2b317bf56a2ba1a5bfbdd03de2fd4b1c
16
+ h11==0.16.0 \
17
+ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
18
+ --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
19
+ idna==3.18 \
20
+ --hash=sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2 \
21
+ --hash=sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848
22
+ jinja2==3.1.6 \
23
+ --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \
24
+ --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
25
+ markupsafe==3.0.3 \
26
+ --hash=sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f \
27
+ --hash=sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a \
28
+ --hash=sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf \
29
+ --hash=sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19 \
30
+ --hash=sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf \
31
+ --hash=sha256:0f4b68347f8c5eab4a13419215bdfd7f8c9b19f2b25520968adfad23eb0ce60c \
32
+ --hash=sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175 \
33
+ --hash=sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219 \
34
+ --hash=sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb \
35
+ --hash=sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6 \
36
+ --hash=sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab \
37
+ --hash=sha256:15d939a21d546304880945ca1ecb8a039db6b4dc49b2c5a400387cdae6a62e26 \
38
+ --hash=sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1 \
39
+ --hash=sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce \
40
+ --hash=sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218 \
41
+ --hash=sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634 \
42
+ --hash=sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695 \
43
+ --hash=sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad \
44
+ --hash=sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73 \
45
+ --hash=sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c \
46
+ --hash=sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe \
47
+ --hash=sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa \
48
+ --hash=sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559 \
49
+ --hash=sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa \
50
+ --hash=sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37 \
51
+ --hash=sha256:3537e01efc9d4dccdf77221fb1cb3b8e1a38d5428920e0657ce299b20324d758 \
52
+ --hash=sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f \
53
+ --hash=sha256:38664109c14ffc9e7437e86b4dceb442b0096dfe3541d7864d9cbe1da4cf36c8 \
54
+ --hash=sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d \
55
+ --hash=sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c \
56
+ --hash=sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97 \
57
+ --hash=sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a \
58
+ --hash=sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19 \
59
+ --hash=sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9 \
60
+ --hash=sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9 \
61
+ --hash=sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc \
62
+ --hash=sha256:591ae9f2a647529ca990bc681daebdd52c8791ff06c2bfa05b65163e28102ef2 \
63
+ --hash=sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4 \
64
+ --hash=sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354 \
65
+ --hash=sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50 \
66
+ --hash=sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698 \
67
+ --hash=sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9 \
68
+ --hash=sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b \
69
+ --hash=sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc \
70
+ --hash=sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115 \
71
+ --hash=sha256:7c3fb7d25180895632e5d3148dbdc29ea38ccb7fd210aa27acbd1201a1902c6e \
72
+ --hash=sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485 \
73
+ --hash=sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f \
74
+ --hash=sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12 \
75
+ --hash=sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025 \
76
+ --hash=sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009 \
77
+ --hash=sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d \
78
+ --hash=sha256:949b8d66bc381ee8b007cd945914c721d9aba8e27f71959d750a46f7c282b20b \
79
+ --hash=sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a \
80
+ --hash=sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5 \
81
+ --hash=sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f \
82
+ --hash=sha256:a320721ab5a1aba0a233739394eb907f8c8da5c98c9181d1161e77a0c8e36f2d \
83
+ --hash=sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1 \
84
+ --hash=sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287 \
85
+ --hash=sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6 \
86
+ --hash=sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f \
87
+ --hash=sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581 \
88
+ --hash=sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed \
89
+ --hash=sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b \
90
+ --hash=sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c \
91
+ --hash=sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026 \
92
+ --hash=sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8 \
93
+ --hash=sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676 \
94
+ --hash=sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6 \
95
+ --hash=sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e \
96
+ --hash=sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d \
97
+ --hash=sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d \
98
+ --hash=sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01 \
99
+ --hash=sha256:df2449253ef108a379b8b5d6b43f4b1a8e81a061d6537becd5582fba5f9196d7 \
100
+ --hash=sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419 \
101
+ --hash=sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795 \
102
+ --hash=sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1 \
103
+ --hash=sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5 \
104
+ --hash=sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d \
105
+ --hash=sha256:e8fc20152abba6b83724d7ff268c249fa196d8259ff481f3b1476383f8f24e42 \
106
+ --hash=sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe \
107
+ --hash=sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda \
108
+ --hash=sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e \
109
+ --hash=sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737 \
110
+ --hash=sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523 \
111
+ --hash=sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591 \
112
+ --hash=sha256:f71a396b3bf33ecaa1626c255855702aca4d3d9fea5e051b41ac59a9c1c41edc \
113
+ --hash=sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a \
114
+ --hash=sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50
115
+ pillow==12.3.0 \
116
+ --hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \
117
+ --hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \
118
+ --hash=sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59 \
119
+ --hash=sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45 \
120
+ --hash=sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3 \
121
+ --hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \
122
+ --hash=sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139 \
123
+ --hash=sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b \
124
+ --hash=sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39 \
125
+ --hash=sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e \
126
+ --hash=sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8 \
127
+ --hash=sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1 \
128
+ --hash=sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8 \
129
+ --hash=sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89 \
130
+ --hash=sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5 \
131
+ --hash=sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130 \
132
+ --hash=sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd \
133
+ --hash=sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d \
134
+ --hash=sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b \
135
+ --hash=sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed \
136
+ --hash=sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace \
137
+ --hash=sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb \
138
+ --hash=sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931 \
139
+ --hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \
140
+ --hash=sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6 \
141
+ --hash=sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1 \
142
+ --hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \
143
+ --hash=sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385 \
144
+ --hash=sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e \
145
+ --hash=sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c \
146
+ --hash=sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7 \
147
+ --hash=sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace \
148
+ --hash=sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c \
149
+ --hash=sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f \
150
+ --hash=sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64 \
151
+ --hash=sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f \
152
+ --hash=sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a \
153
+ --hash=sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827 \
154
+ --hash=sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17 \
155
+ --hash=sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4 \
156
+ --hash=sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a \
157
+ --hash=sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701 \
158
+ --hash=sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e \
159
+ --hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \
160
+ --hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \
161
+ --hash=sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468 \
162
+ --hash=sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217 \
163
+ --hash=sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658 \
164
+ --hash=sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418 \
165
+ --hash=sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a \
166
+ --hash=sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c \
167
+ --hash=sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330 \
168
+ --hash=sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402 \
169
+ --hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \
170
+ --hash=sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930 \
171
+ --hash=sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f \
172
+ --hash=sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec \
173
+ --hash=sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a \
174
+ --hash=sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94 \
175
+ --hash=sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468 \
176
+ --hash=sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b \
177
+ --hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \
178
+ --hash=sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8 \
179
+ --hash=sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd \
180
+ --hash=sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7 \
181
+ --hash=sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c \
182
+ --hash=sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777 \
183
+ --hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 \
184
+ --hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \
185
+ --hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \
186
+ --hash=sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f \
187
+ --hash=sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0 \
188
+ --hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \
189
+ --hash=sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71 \
190
+ --hash=sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3 \
191
+ --hash=sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838 \
192
+ --hash=sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf \
193
+ --hash=sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321 \
194
+ --hash=sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26 \
195
+ --hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec \
196
+ --hash=sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9 \
197
+ --hash=sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65 \
198
+ --hash=sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5 \
199
+ --hash=sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e \
200
+ --hash=sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d \
201
+ --hash=sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198 \
202
+ --hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7
203
+ pydantic==2.13.4 \
204
+ --hash=sha256:45a282cde31d808236fd7ea9d919b128653c8b38b393d1c4ab335c62924d9aba \
205
+ --hash=sha256:c40756b57adaa8b1efeeced5c196f3f3b7c435f90e84ea7f443901bec8099ef6
206
+ pydantic-core==2.46.4 \
207
+ --hash=sha256:00c603d540afdd6b80eb39f078f33ebd46211f02f33e34a32d9f053bba711de0 \
208
+ --hash=sha256:0186750b482eefa11d7f435892b09c5c606193ef3375bcf94aa00ae6bfb66262 \
209
+ --hash=sha256:041bde0a48fd37cf71cab1c9d56d3e8625a3793fef1f7dd232b3ff37e978ecda \
210
+ --hash=sha256:0c563b08bca408dc7f65f700633d8442fffb2421fc47b8101377e9fd65051ff0 \
211
+ --hash=sha256:0cbe8b01f948de4286c74cdd6c667aceb38f5c1e26f0693b3983d9d74887c65e \
212
+ --hash=sha256:0ce40cd7b21210e99342afafbd4d0f76d784eb5b1d60f3bdc566be4983c6c73b \
213
+ --hash=sha256:0e96592440881c74a213e5ad528e2b24d3d4f940de2766bed9010ab1d9e51594 \
214
+ --hash=sha256:10e17cbb10a330363733efc4d7c4d0dd827ac0909b8f6a6542298fed1ea62f29 \
215
+ --hash=sha256:133878133d271ade3d41d1bfb2a45ec38dbdbda40bc065921c6b04e4630127e2 \
216
+ --hash=sha256:14d4edf427bdcf950a8a02d7cb44a08614388dd6e1bdcbf4f67504fa7887da9c \
217
+ --hash=sha256:14f4c5d6db102bd796a627bbb3a17b4cf4574b9ae861d8b7c9a9661c6dd3362d \
218
+ --hash=sha256:17299feefe090f2caa5b8e37222bb5f663e4935a8bfa6931d4102e5df1a9f398 \
219
+ --hash=sha256:184c081504d17f1c1066e430e117142b2c77d9448a97f7b65c6ac9fd9aee238d \
220
+ --hash=sha256:18e5ceec2ab67e6d5f1a9085e5a24c9c4e2ac4545730bfe668680bca05e555f3 \
221
+ --hash=sha256:19e51f073cd3df251856a8a4189fbdf1de4012c3ebacfb1884f94f1eb406079f \
222
+ --hash=sha256:1a7dd0b3ee80d90150e3495a3a13ac34dbcbfd4f012996a6a1d8900e91b5c0fb \
223
+ --hash=sha256:1d8ba486450b14f3b1d63bc521d410ec7565e52f887b9fb671791886436a42f7 \
224
+ --hash=sha256:2108ba5c1c1eca18030634489dc544844144ee36357f2f9f780b93e7ddbb44b5 \
225
+ --hash=sha256:228ee9bae8bef5b1e97ec58302f80357c37199e0d0a99174e138d28e6957b9d9 \
226
+ --hash=sha256:23ace664830ee0bfe014a0c7bc248b1f7f25ed7ad103852c317624a1083af462 \
227
+ --hash=sha256:2412e734dcb48da14d4e4006b82b46b74f2518b8a26ee7e58c6844a6cd6d03c4 \
228
+ --hash=sha256:29c61fc04a3d840155ff08e475a04809278972fe6aef51e2720554e96367e34b \
229
+ --hash=sha256:2f84c03c8607173d16b5a854ec68a2f9079ae03237a54fb506d13af47e1d018d \
230
+ --hash=sha256:3009f12e4e90b7f88b4f9adb1b0c4a3d58fe7820f3238c190047209d148026df \
231
+ --hash=sha256:3245406455a5d98187ec35530fd772b1d799b26667980872c8d4614991e2c4a2 \
232
+ --hash=sha256:3447661d99f75a3683a4cf5c87da72f2161964611864dbbeac7fbb118bb4bfc0 \
233
+ --hash=sha256:372429a130e469c9cd698925ce5fc50940b7a1336b0d82038e63d5bbc4edc519 \
234
+ --hash=sha256:395aebd9183f9d112f569aeb5b2214d1a10a33bec8456447f7fbdfa51d38d4cd \
235
+ --hash=sha256:3a233125ac121aa3ffba9a2b59edfc4a985a76092dc8279586ab4b71390875e7 \
236
+ --hash=sha256:3be77f45df024d789a672ae34f8b06fb346c4f9f46ea714956660ea4862e89ac \
237
+ --hash=sha256:3bf92c5d0e00fefaab325a4d27828fe6b6e2a21848686b5b60d2d9eeb09d76c6 \
238
+ --hash=sha256:3ecbc122d18468d06ca279dc26a8c2e2d5acb10943bb35e36ae92096dc3b5565 \
239
+ --hash=sha256:3fb702cd90b0446a3a1c5e470bfa0dd23c0233b676a9099ddcc964fa6ca13898 \
240
+ --hash=sha256:428e04521a40150c85216fc8b85e8d39fece235a9cf5e383761238c7fa9b96fb \
241
+ --hash=sha256:432c179df7874eeb73307aad2df0755e1ae0efa61ff0ea89b93e194411ae3928 \
242
+ --hash=sha256:4a05d69cba51d852c5c3e92758653245a50c0b646ced0cf05bd793ed592839d6 \
243
+ --hash=sha256:4c63ebc82684aa89d9a3bcbd13d515b3be44250dc68dd3bd81526c1cb31286c3 \
244
+ --hash=sha256:4fc73cb559bdb54b1134a706a2802a4cddd27a0633f5abb7e53056268751ac6a \
245
+ --hash=sha256:4fcbe087dbc2068af7eda3aa87634eba216dbda64d1ae73c8684b621d33f6596 \
246
+ --hash=sha256:56cb4851bcaf3d117eddcef4fe66afd750a50274b0da8e22be256d10e5611987 \
247
+ --hash=sha256:5855698a4856556d86e8e6cd8434bc3ac0314ee8e12089ae0e143f64c6256e4e \
248
+ --hash=sha256:5a4330cdbc57162e4b3aa303f588ba752257694c9c9be3e7ebb11b4aca659b5d \
249
+ --hash=sha256:5b712b53160b79a5850310b912a5ef8e57e56947c8ad690c227f5c9d7e561712 \
250
+ --hash=sha256:5d5902252db0d3cedf8d4a1bc68f70eeb430f7e4c7104c8c476753519b423008 \
251
+ --hash=sha256:617d7e2ca7dcb8c5cf6bcb8c59b8832c94b36196bbf1cbd1bfb56ed341905edd \
252
+ --hash=sha256:62f875393d7f270851f20523dd2e29f082bcc82292d66db2b64ea71f64b6e1c1 \
253
+ --hash=sha256:633147d34cf4550417f12e2b1a0383973bdf5cdfde212cb09e9a581cf10820be \
254
+ --hash=sha256:66ce7632c22d837c95301830e111ad0128a32b8207533b60896a96c4915192ea \
255
+ --hash=sha256:6b3ace8194b0e5204818c92802dcdca7fc6d88aabbb799d7c795540d9cd6d292 \
256
+ --hash=sha256:6f2eeda33a839975441c86a4119e1383c50b47faf0cbb5176985565c6bb02c33 \
257
+ --hash=sha256:7027560ee92211647d0d34e3f7cd6f50da56399d26a9c8ad0da286d3869a53f3 \
258
+ --hash=sha256:7283d57845ecf5a163403eb0702dfc220cc4fbdd18919cb5ccea4f95ee1cdab4 \
259
+ --hash=sha256:7a5f930472650a82629163023e630d160863fce524c616f4e5186e5de9d9a49b \
260
+ --hash=sha256:7bfb192b3f4b9e8a89b6277b6ce787564f62cfd272055f6e685726b111dc7826 \
261
+ --hash=sha256:811ff8e9c313ab425368bcbb36e5c4ebd7108c2bbf4e4089cfbb0b01eff63fac \
262
+ --hash=sha256:8233f2947cf85404441fd7e0085f53b10c93e0ee78611099b5c7237e36aacbf7 \
263
+ --hash=sha256:82cf5301172168103724d49a1444d3378cb20cdee30b116a1bd6031236298a5d \
264
+ --hash=sha256:8358a950c8909158e3df31538a7e4edc2d7265a7c54b47f0864d9e5bae9dcebf \
265
+ --hash=sha256:85bb3611ff1802f3ee7fdd7dbff26b56f343fb432d57a4728fdd49b6ef35e2f4 \
266
+ --hash=sha256:86e1a4418c6cd97d60c95c71164158eaf7324fae7b0923264016baa993eba6fc \
267
+ --hash=sha256:8b9bab013d1c7a79d3501ff86d0bc9c31bf587db4551677b96bec07df78c6b15 \
268
+ --hash=sha256:8c5dac79fa1614d1e06ca695109c6105923bd9c7d1d6c918d4e637b7e6b32fd3 \
269
+ --hash=sha256:8d0820e8192167f80d88d64038e609c31452eeca865b4e1d9950a27a4609b00b \
270
+ --hash=sha256:8daafc69c93ee8a0204506a3b6b30f586ef54028f52aeeeb5c4cfc5184fd5914 \
271
+ --hash=sha256:9037063db01f09b09e237c282b6792bd4da634b5402c4e7f0c61effed7701a04 \
272
+ --hash=sha256:905a0ed8ea6f2d61c1738835f99b699348d7857379083e5fc497fa0c967a407c \
273
+ --hash=sha256:90884113d8b48f760e9587002789ddd741e76ab9f89518cd1e43b1f1a52ec44b \
274
+ --hash=sha256:91a06d2e259ecfbd8c901d70c3c507900458498142b3026a296b7de4d1322cc9 \
275
+ --hash=sha256:926c9541b14b12b1681dca8a0b75feb510b06c6341b70a8e500c2fdcff837cce \
276
+ --hash=sha256:9401557acd873c3a7f3eb9383edef8ac4968f9510e340f4808d427e75667e7b4 \
277
+ --hash=sha256:9551187363ffc0de2a00b2e47c25aeaeb1020b69b668762966df15fc5659dd5a \
278
+ --hash=sha256:962ccbab7b642487b1d8b7df90ef677e03134cf1fd8880bf698649b22a69371f \
279
+ --hash=sha256:97e7cf2be5c77b7d1a9713a05605d49460d02c6078d38d8bef3cbe323c548424 \
280
+ --hash=sha256:9aa768456404a8bf48a4406685ac2bec8e72b62c69313734fa3b73cf33b3a894 \
281
+ --hash=sha256:9bc519fbf2b7578398853d815009ae5e4d4603d12f4e3f91da8c06852d3da3e9 \
282
+ --hash=sha256:9d56801be94b86a9da183e5f3766e6310752b99ff647e38b09a9500d88e46e76 \
283
+ --hash=sha256:9f444c499b3eefd3a92e348059471ea0c3a6e303d9c1cec09fa748fd9f895201 \
284
+ --hash=sha256:9fa8ae11da9e2b3126c6426f147e0fba88d96d65921799bb30c6abd1cb2c97fb \
285
+ --hash=sha256:a0f62d0a58f4e7da165457e995725421e0064f2255d8eccebc49f41bbc23b109 \
286
+ --hash=sha256:a396dcc17e5a0b164dbe026896245a4fa9ff402edca1dff0be3d53a517f74de4 \
287
+ --hash=sha256:aaa2a54443eff1950ba5ddc6b6ccda0d9c84a364276a62f969bdf2a390650848 \
288
+ --hash=sha256:ad785e92e6dc634c21555edc8bd6b64957ab844541bcb96a1366c202951ae526 \
289
+ --hash=sha256:af8244b2bef6aaad6d92cda81372de7f8c8d36c9f0c3ea36e827c60e7d9467a0 \
290
+ --hash=sha256:b078afbc25f3a1436c7a1d2cd3e322497ee99615ba97c563566fdf46aff1ee01 \
291
+ --hash=sha256:b2f69dec1725e79a012d920df1707de5caf7ed5e08f3be4435e25803efc47458 \
292
+ --hash=sha256:b8458003118a712e66286df6a707db01c52c0f52f7db8e4a38f0da1d3b94fc4e \
293
+ --hash=sha256:bb63e0198ca18aad131c089b9204c23079c3afa95487e561f4c522d519e55aba \
294
+ --hash=sha256:bfec22eab3c8cc2ceec0248aec886624116dc079afa027ecc8ad4a7e62010f8a \
295
+ --hash=sha256:c1747f85cee84c26985853c6f3d9bd3e75da5212912443fa111c113b9c246f39 \
296
+ --hash=sha256:c1b3f518abeca3aa13c712fd202306e145abf59a18b094a6bafb2d2bbf59192c \
297
+ --hash=sha256:c50f2528cf200c5eed56faf3f4e22fcd5f38c157a8b78576e6ba3168ec35f000 \
298
+ --hash=sha256:c68fcd102d71ea85c5b2dfac3f4f8476eff42a9e078fd5faefff6d145063536b \
299
+ --hash=sha256:c7a7bd4e39e8e4c12c39cd480356842b6a8a06e41b23a55a5e3e191718838ddf \
300
+ --hash=sha256:c94f0688e7b8d0a67abf40e57a7eaaecd17cc9586706a31b76c031f63df052b4 \
301
+ --hash=sha256:cbaf13819775b7f769bf4a1f066cb6df7a28d4480081a589828ef190226881cd \
302
+ --hash=sha256:cd2213145bcc2ba85884d0ac63d222fece9209678f77b9b4d76f054c561adb28 \
303
+ --hash=sha256:ce5c1d2a8b27468f433ca974829c44060b8097eedc39933e3c206a90ee49c4a9 \
304
+ --hash=sha256:d396ec2b979760aaf3218e76c24e65bd0aca24983298653b3a9d7a45f9e47b30 \
305
+ --hash=sha256:d51026d73fcfd93610abc7b27789c26b313920fcfb20e27462d74a7f8b06e983 \
306
+ --hash=sha256:d80ee3d731373b24cebbc10d689ca4ee1875caf0d5703a245db18efd4dd37fc1 \
307
+ --hash=sha256:d995260fdf4e1db774581b4900e0f832abe3c7c84996726bbc161b19c8f29e76 \
308
+ --hash=sha256:da4b951fe36dc7c3a1ccb4e3cd1747c3542b8c9ceede8fc86cae054e764485f5 \
309
+ --hash=sha256:daa27d92c36f24388fe3ad306b174781c747627f134452e4f128ea00ce1fe8c4 \
310
+ --hash=sha256:db06ffe51636ffe9ca531fe9023dd64bdd794be8754cb5df57c5498ae5b518a7 \
311
+ --hash=sha256:e0d65b8c354be7fb5f720c3caa8bc940bc2d20ce749c8e06135f07f8ed95dd7c \
312
+ --hash=sha256:e68b7a074f65a2fd746c52a7ce6142ab7006074ac269ace0c25cd8ba171f8066 \
313
+ --hash=sha256:e739fee756ba1010f8bcccb534252e85a35fe45ae92c295a06059ce58b74ccd3 \
314
+ --hash=sha256:e846ae7835bf0703ae43f534ab79a867146dadd59dc9ca5c8b53d5c8f7c9ef02 \
315
+ --hash=sha256:e9c26f834c65f5752f3f06cb08cb86a913ceb7274d0db6e267808a708b46bc89 \
316
+ --hash=sha256:ea793e075b70290d89d8142074262885d3f7da19634845135751bd6344f73b50 \
317
+ --hash=sha256:f027324c56cd5406ca49c124b0db10e56c69064fec039acc571c29020cc87c76 \
318
+ --hash=sha256:f13a646d65d09fbf1bc6b3a9635d30095c8e7e5cc419ff35ecc563c5fd04cd49 \
319
+ --hash=sha256:f47286a97f0bc9b8859519809077b91b2cefe4ae47fcbf5e466a009c1c5d742b \
320
+ --hash=sha256:f747929cf940cddb5b3668a390056ddd5ba2e5010615ea2dcf4f9c4f3ab8791d \
321
+ --hash=sha256:f99626688942fb746e545232e7726926f3be91b5975f8b55327665fafda991c7 \
322
+ --hash=sha256:f9fa868638bf362d3d138ea55829cefb3d5f4b0d7f142234382a15e2485dbec4 \
323
+ --hash=sha256:fbdb89b3e1c94a30cc5edfce477c6e6a5dc4d8f84665b455c27582f211a1c72c \
324
+ --hash=sha256:fc010ab034c8c7452522748bf937df58020d256ccae0874463d1f4d01758af8e \
325
+ --hash=sha256:fc3e9034a63de20e15e8ade85358bc6efc614008cab72898b4b4952bea0509ff \
326
+ --hash=sha256:fd8b3d9fd264be37976686c7f65cd52a83f5e84f4bfd2adf9c1d469676bbb6ae
327
+ python-multipart==0.0.32 \
328
+ --hash=sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e \
329
+ --hash=sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23
330
+ starlette==1.3.1 \
331
+ --hash=sha256:05d0213193f2fbaae60e2ecb593b4add4262ad4e46536b54abe36f11a71724e0 \
332
+ --hash=sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6
333
+ typing-extensions==4.16.0 \
334
+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
335
+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
336
+ typing-inspection==0.4.2 \
337
+ --hash=sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7 \
338
+ --hash=sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464
339
+ uvicorn==0.51.0 \
340
+ --hash=sha256:5d38af6cd620f2ae3849fb44fd4879e0890aa1febe8d47eb355fb45d93fe6a5b \
341
+ --hash=sha256:f6f4b69b657c312f516dd2d268ab9ae6f254b11e4bac504f37b2ab58b24dd0b0
tasks/amazon/tests/fixtures/cicd/amazon-business-laws.json ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "websitebench.amazon.business-obligations.v1",
3
+ "site_id": "amazon",
4
+ "assertions": [
5
+ "cart-subtotal",
6
+ "cart-add-accumulates",
7
+ "cart-quantity-cap",
8
+ "cart-update-replaces",
9
+ "cart-zero-quantity",
10
+ "cart-over-limit",
11
+ "cart-noninteger-quantity",
12
+ "cart-missing-product",
13
+ "cart-unknown-product",
14
+ "cart-partial-options",
15
+ "cart-invalid-option",
16
+ "cart-delete",
17
+ "cart-save",
18
+ "cart-restore",
19
+ "cart-reactivate-saved",
20
+ "cart-unknown-line",
21
+ "cart-foreign-update",
22
+ "cart-foreign-delete",
23
+ "cart-anonymous-redirect",
24
+ "cart-variant-lines",
25
+ "cart-delete-saved",
26
+ "cart-extra-field",
27
+ "compare-variant-identity",
28
+ "compare-add",
29
+ "compare-duplicate",
30
+ "compare-remove",
31
+ "compare-clear",
32
+ "compare-limit",
33
+ "compare-incompatible",
34
+ "compare-missing-product",
35
+ "compare-unknown-product",
36
+ "compare-partial-options",
37
+ "compare-invalid-option",
38
+ "compare-malformed-remove",
39
+ "compare-unknown-remove",
40
+ "compare-foreign-remove",
41
+ "compare-clear-extra-field",
42
+ "compare-remove-preserves-order",
43
+ "list-normalization",
44
+ "list-unicode-normalization",
45
+ "list-empty",
46
+ "list-long",
47
+ "list-casefold-conflict",
48
+ "list-rename",
49
+ "list-rename-conflict",
50
+ "list-delete",
51
+ "list-last-delete",
52
+ "wishlist-add",
53
+ "wishlist-duplicate",
54
+ "wishlist-remove",
55
+ "wishlist-move",
56
+ "wishlist-move-quantity",
57
+ "wishlist-foreign-read",
58
+ "wishlist-foreign-rename",
59
+ "wishlist-foreign-delete",
60
+ "wishlist-foreign-add",
61
+ "wishlist-foreign-remove",
62
+ "wishlist-unknown-product",
63
+ "wishlist-invalid-selection",
64
+ "auth-wrong-password",
65
+ "auth-invalid-signin-email",
66
+ "auth-password-mismatch",
67
+ "auth-short-password",
68
+ "auth-invalid-registration-email",
69
+ "auth-invalid-code",
70
+ "auth-code-reuse",
71
+ "auth-logout-preserves-cart"
72
+ ],
73
+ "authentication": "Public form registration and real private trial inbox OTP. Browser fetch sends the real Secure cookie on loopback; mutation response event observes original status before the normal redirect. No test session, local outbox or seed account credentials.",
74
+ "source_review": {
75
+ "cart": "clone/server.py:4895-5115; clone/store.py:5398-5578; clone/render.py:3010-3252",
76
+ "compare": "clone/server.py:4798-4894; clone/store.py:4934-5094",
77
+ "wishlist": "clone/wishlist_store.py and clone/wishlist_views.py; clone/server.py:3715-3920",
78
+ "auth": "clone/server.py:3195-3620; public form registration and separate email/password signin stages"
79
+ },
80
+ "groups": {
81
+ "CART": [
82
+ "cart-subtotal",
83
+ "cart-add-accumulates",
84
+ "cart-quantity-cap",
85
+ "cart-update-replaces",
86
+ "cart-zero-quantity",
87
+ "cart-over-limit",
88
+ "cart-noninteger-quantity",
89
+ "cart-missing-product",
90
+ "cart-unknown-product",
91
+ "cart-partial-options",
92
+ "cart-invalid-option",
93
+ "cart-delete",
94
+ "cart-save",
95
+ "cart-restore",
96
+ "cart-reactivate-saved",
97
+ "cart-unknown-line",
98
+ "cart-foreign-update",
99
+ "cart-foreign-delete",
100
+ "cart-anonymous-redirect",
101
+ "cart-variant-lines",
102
+ "cart-delete-saved",
103
+ "cart-extra-field"
104
+ ],
105
+ "COMPARE": [
106
+ "compare-variant-identity",
107
+ "compare-add",
108
+ "compare-duplicate",
109
+ "compare-remove",
110
+ "compare-clear",
111
+ "compare-limit",
112
+ "compare-incompatible",
113
+ "compare-missing-product",
114
+ "compare-unknown-product",
115
+ "compare-partial-options",
116
+ "compare-invalid-option",
117
+ "compare-malformed-remove",
118
+ "compare-unknown-remove",
119
+ "compare-foreign-remove",
120
+ "compare-clear-extra-field",
121
+ "compare-remove-preserves-order"
122
+ ],
123
+ "WISH": [
124
+ "list-normalization",
125
+ "list-unicode-normalization",
126
+ "list-empty",
127
+ "list-long",
128
+ "list-casefold-conflict",
129
+ "list-rename",
130
+ "list-rename-conflict",
131
+ "list-delete",
132
+ "list-last-delete",
133
+ "wishlist-add",
134
+ "wishlist-duplicate",
135
+ "wishlist-remove",
136
+ "wishlist-move",
137
+ "wishlist-move-quantity",
138
+ "wishlist-foreign-read",
139
+ "wishlist-foreign-rename",
140
+ "wishlist-foreign-delete",
141
+ "wishlist-foreign-add",
142
+ "wishlist-foreign-remove",
143
+ "wishlist-unknown-product",
144
+ "wishlist-invalid-selection"
145
+ ],
146
+ "AUTH": [
147
+ "auth-wrong-password",
148
+ "auth-invalid-signin-email",
149
+ "auth-password-mismatch",
150
+ "auth-short-password",
151
+ "auth-invalid-registration-email",
152
+ "auth-invalid-code",
153
+ "auth-code-reuse",
154
+ "auth-logout-preserves-cart"
155
+ ]
156
+ },
157
+ "migration_alias_replacement": {
158
+ "removed": "migration-replay-keeps-normalized-state-idempotent",
159
+ "retained": "migration-restart-preserves-normalized-durable-state",
160
+ "reason": "Both bundled dispatch functions only call _normalized_restart_snapshot with identical CLI context.",
161
+ "replacement": "compare-variant-identity"
162
+ }
163
+ }
tasks/amazon/tests/fixtures/cicd/obligations.json ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "business_probe": {
3
+ "baseline": {
4
+ "method": "GET",
5
+ "path": "/gp/cart/view.html",
6
+ "status": 200
7
+ },
8
+ "mutate": {
9
+ "body": {
10
+ "ASIN": "B000052Y5Q",
11
+ "quantity": "1"
12
+ },
13
+ "headers": {
14
+ "content-type": "application/x-www-form-urlencoded"
15
+ },
16
+ "method": "POST",
17
+ "path": "/gp/cart/add.html",
18
+ "status": 200
19
+ },
20
+ "read": {
21
+ "method": "GET",
22
+ "path": "/gp/cart/view.html",
23
+ "status": 200
24
+ }
25
+ },
26
+ "effect_policy": "payment-sandbox",
27
+ "mail_probe": {
28
+ "body": {
29
+ "email": "shopper@example.test"
30
+ },
31
+ "headers": {
32
+ "content-type": "application/x-www-form-urlencoded"
33
+ },
34
+ "method": "POST",
35
+ "path": "/ap/forgotpassword",
36
+ "status": 200,
37
+ "body_contains": "recovery request accepted",
38
+ "effect_contains": [
39
+ "shopper@example.test",
40
+ "password-recovery"
41
+ ]
42
+ },
43
+ "payment_probe": {
44
+ "body": {
45
+ "idempotencyKey": "checkout-local",
46
+ "paymentMethod": "sandbox-approved"
47
+ },
48
+ "headers": {
49
+ "content-type": "application/x-www-form-urlencoded"
50
+ },
51
+ "method": "POST",
52
+ "path": "/gp/buy/place-order",
53
+ "status": 200
54
+ },
55
+ "required_invariants": [
56
+ "assets.local-only.closed",
57
+ "variants.complete-quote.identity",
58
+ "identity.verification.recovery",
59
+ "cart.mutations.account-gated",
60
+ "checkout.retry.idempotent",
61
+ "orders.lifecycle.monotone",
62
+ "migration.copy-only",
63
+ "evidence.denominators.separate",
64
+ "scope.shopping-mainline.bounded"
65
+ ],
66
+ "required_routes": [
67
+ "/",
68
+ "/healthz",
69
+ "/ap/cvf/verify?purpose=registration",
70
+ "/ap/cvf/verify",
71
+ "/ap/signin",
72
+ "/ap/forgotpassword",
73
+ "/gp/css/homepage.html",
74
+ "/static/app.js",
75
+ "/gp/cart/view.html",
76
+ "/gp/buy/now/continue",
77
+ "/gp/compare",
78
+ "/hz/wishlist/intro",
79
+ "/gp/cart/add.html",
80
+ "/gp/buy/place-order"
81
+ ],
82
+ "route_probes": [
83
+ {
84
+ "body_contains": "Amazon",
85
+ "path": "/",
86
+ "status": 200
87
+ },
88
+ {
89
+ "path": "/healthz",
90
+ "status": 200
91
+ },
92
+ {
93
+ "path": "/ap/cvf/verify?purpose=registration",
94
+ "status": 200
95
+ },
96
+ {
97
+ "path": "/ap/cvf/verify",
98
+ "status": 200
99
+ },
100
+ {
101
+ "path": "/ap/signin",
102
+ "status": 200
103
+ },
104
+ {
105
+ "path": "/ap/forgotpassword",
106
+ "status": 200
107
+ },
108
+ {
109
+ "path": "/gp/css/homepage.html",
110
+ "status": 200
111
+ },
112
+ {
113
+ "path": "/static/app.js",
114
+ "status": 200
115
+ },
116
+ {
117
+ "path": "/gp/cart/view.html",
118
+ "status": 200
119
+ },
120
+ {
121
+ "path": "/gp/buy/now/continue",
122
+ "status": 200
123
+ },
124
+ {
125
+ "path": "/gp/compare",
126
+ "status": 200
127
+ },
128
+ {
129
+ "path": "/hz/wishlist/intro",
130
+ "status": 200
131
+ }
132
+ ],
133
+ "schema": "websitebench.harbor.trusted-obligations",
134
+ "site_id": "amazon",
135
+ "invariant_probes": [
136
+ {
137
+ "invariants": [
138
+ "assets.local-only.closed",
139
+ "variants.complete-quote.identity",
140
+ "identity.verification.recovery",
141
+ "cart.mutations.account-gated",
142
+ "checkout.retry.idempotent"
143
+ ],
144
+ "probe": {
145
+ "path": "/",
146
+ "status": 200,
147
+ "body_contains": "Amazon"
148
+ }
149
+ },
150
+ {
151
+ "invariants": [
152
+ "orders.lifecycle.monotone",
153
+ "migration.copy-only",
154
+ "evidence.denominators.separate",
155
+ "scope.shopping-mainline.bounded"
156
+ ],
157
+ "probe": {
158
+ "path": "/gp/cart/view.html",
159
+ "status": 200,
160
+ "body_contains": "Shopping Cart"
161
+ }
162
+ }
163
+ ],
164
+ "management_probes": [
165
+ {
166
+ "path": "/__bench/reset",
167
+ "method": "POST"
168
+ },
169
+ {
170
+ "path": "/__bench/mail/outbox"
171
+ }
172
+ ]
173
+ }
tasks/amazon/tests/fixtures/cicd/run-amazon-business.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/usr/bin/env sh
2
+ set -eu
3
+ python="$(command -v python3 || command -v python)"
4
+ exec "$python" -m websitebench.harbor.amazon_business "$@"
tasks/amazon/tests/fixtures/cicd/run-check.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ repo_python="$(dirname "$0")/../../../../../../.venv/bin/python"
4
+ if test -x "$repo_python"; then
5
+ python_bin=$repo_python
6
+ elif command -v python >/dev/null 2>&1; then
7
+ python_bin=python
8
+ else
9
+ python_bin=python3
10
+ fi
11
+ exec "$python_bin" -m websitebench.harbor.trusted_check "$@"
tasks/amazon/tests/fixtures/site/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Hidden fixtures
2
+
3
+ Evaluator-only reset states and test data.
tasks/amazon/tests/oracle-runtime/clone/fixtures/source-snapshots/2026-07-31/pdp-unified--1365x900.png ADDED

Git LFS Details

  • SHA256: 4856b4a46e15159502f0602313aa0e7a7e843c350475cee5f7178bed4e1f3624
  • Pointer size: 131 Bytes
  • Size of remote file: 338 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-bold.woff2 ADDED
Binary file (16.5 kB). View file
 
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-italic.woff2 ADDED
Binary file (17.3 kB). View file
 
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-medium.woff2 ADDED
Binary file (21.5 kB). View file
 
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/amazon-ember-regular.woff2 ADDED
Binary file (16.6 kB). View file
 
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite-retail-1x.png ADDED

Git LFS Details

  • SHA256: 10c6b07b1816247131544e21f1dfa161eeb65de4e770314780f97ed953cb6a82
  • Pointer size: 130 Bytes
  • Size of remote file: 24.5 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite-retail-2x.png ADDED

Git LFS Details

  • SHA256: 94b0bd249b1d06afe65a57c8270494a36d7c72e81fd6cc7f614c0bf7dcae5153
  • Pointer size: 130 Bytes
  • Size of remote file: 53.2 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/auth/auth-sprite.png ADDED

Git LFS Details

  • SHA256: 68158eb78e285855e409054a9c23880fbb5a48cbd113e165f9de0c10a472245c
  • Pointer size: 130 Bytes
  • Size of remote file: 28.1 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/007d6dcf1fdb975a.jpg ADDED

Git LFS Details

  • SHA256: 45c2a948fd3feeeeb98f0aeca77a586a3d8e46c791a9f6d7f083dc64bfedee81
  • Pointer size: 129 Bytes
  • Size of remote file: 5.82 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/014f2bdb67865e0e.jpg ADDED

Git LFS Details

  • SHA256: c29529a01e43e2508f42c9ebfb33ecdf2e620bbbc9bd2528c5e1d1178c43e9d3
  • Pointer size: 129 Bytes
  • Size of remote file: 5.4 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0570588e61329a69.jpg ADDED

Git LFS Details

  • SHA256: 2be4cb8bffe83d086c78f6090e063e6d4f28110a5b35d8ba6a307fc3f7b53e9c
  • Pointer size: 129 Bytes
  • Size of remote file: 2.45 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/067d7ad08025ea90.jpg ADDED

Git LFS Details

  • SHA256: ed19010e03da6ae0aa38d1cb66376a4ac1c3a98d386bf6f3fd23f9d6e3efdec3
  • Pointer size: 129 Bytes
  • Size of remote file: 7.9 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0ad083d2d44c138c.jpg ADDED

Git LFS Details

  • SHA256: 71ae8f199282a92f9cec2e056bc47c7b7bc3676edd88436377b3f24640dd9dd0
  • Pointer size: 129 Bytes
  • Size of remote file: 2.27 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/0b93049189c1d89f.jpg ADDED

Git LFS Details

  • SHA256: 65f522360894f442128cb8a2f55cda26732721f9bb6e4889b067e2fcb252ed60
  • Pointer size: 129 Bytes
  • Size of remote file: 9.09 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/1044f0abd1b0a9a4.jpg ADDED

Git LFS Details

  • SHA256: 39a79d6d6b21c97576d21c97e2beeba4d405ecff20e1e74ac09a5a6892b7453e
  • Pointer size: 129 Bytes
  • Size of remote file: 5.2 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/10f449c8f68d4ff3.jpg ADDED

Git LFS Details

  • SHA256: 1979d582117acdf5e67767bc4067cbdf0e98ca3f284f6f19405f271ec6a9b11b
  • Pointer size: 130 Bytes
  • Size of remote file: 10.5 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/118dad6228a13f3b.jpg ADDED

Git LFS Details

  • SHA256: 74df6c40700d3998466380412525b505a2d5fa6468eda280d53610c1f9349200
  • Pointer size: 129 Bytes
  • Size of remote file: 1.69 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/12237c942f7639ab.jpg ADDED

Git LFS Details

  • SHA256: 7976aeef0a1a57be2e95affc4047a25718e82d04a2ba044345014015306bd7e1
  • Pointer size: 129 Bytes
  • Size of remote file: 5.91 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/13b4e86ff2941173.jpg ADDED

Git LFS Details

  • SHA256: c65646e30c956c26059b3c346724cdd18a21c548277eef1a0458c9499cb91227
  • Pointer size: 129 Bytes
  • Size of remote file: 3.92 kB
tasks/amazon/tests/oracle-runtime/clone/static/assets/source-current/2026-07-21/home/13e358fe611b2960.jpg ADDED

Git LFS Details

  • SHA256: 9fda1bd423f49cbd6a29ee8f0a6dc1b50ffdf0ed5ba4e61d7875407cc17bdb5d
  • Pointer size: 129 Bytes
  • Size of remote file: 8.26 kB