AgPerry commited on
Commit
7199290
·
verified ·
1 Parent(s): 0429fbb

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/petfinder/solution/site/README.md +3 -0
  2. tasks/petfinder/solution/site/implementation/backend/runtime.json +126 -0
  3. tasks/petfinder/solution/site/implementation/clone/__init__.py +0 -0
  4. tasks/petfinder/solution/site/implementation/clone/app.py +0 -0
  5. tasks/petfinder/solution/site/implementation/clone/backend/__init__.py +6 -0
  6. tasks/petfinder/solution/site/implementation/clone/backend/db.py +2200 -0
  7. tasks/petfinder/solution/site/implementation/clone/backend/migrations.py +362 -0
  8. tasks/petfinder/solution/site/implementation/clone/backend/policies.py +48 -0
  9. tasks/petfinder/solution/site/implementation/clone/backend/repositories.py +67 -0
  10. tasks/petfinder/solution/site/implementation/clone/backend/services.py +374 -0
  11. tasks/petfinder/solution/site/implementation/clone/backend/site_backend_integration.py +125 -0
  12. tasks/petfinder/solution/site/implementation/clone/backend/support_payments.py +503 -0
  13. tasks/petfinder/solution/site/implementation/clone/data/frozen-public-content-index.json +0 -0
  14. tasks/petfinder/solution/site/implementation/clone/data/frozen-public-media-index.json +0 -0
  15. tasks/petfinder/solution/site/implementation/clone/data/frozen-public-route-index.json +0 -0
  16. tasks/petfinder/solution/site/implementation/clone/harbor_entry.py +59 -0
  17. tasks/petfinder/solution/site/implementation/clone/static/app.js +370 -0
  18. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/0116b8e561d20edaee354ad0f5054fc3211237a0ab6947f52ca309fe434edbcf.webp +3 -0
  19. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01622c41cd71d3b31760c8f9f7aa45f7f64f5b64e8db17bba331b98ed4ada5d9.webp +3 -0
  20. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01688863ce4141423f972b065522476cad194770282ee47e0c68eb1f4c72570c.webp +3 -0
  21. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01afe71b59907bdf1f8bcf29506f16ad41ddd89e33304e0e0ac17b814fe27a48.webp +3 -0
  22. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01d0579f1f823192f1fad382398b73c8745e92306a897bee89a330a5bc9b5be5.webp +3 -0
  23. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01ee75e0035da5a527e3d25641994c9a1f02b2187f60b895427070cf0f797528.webp +3 -0
  24. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/0551528a7e7cdd20764b5c70a65ccd71601c981644426fdd7c7405e0e786e36e.webp +3 -0
  25. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/057cb188076616bbf52a2bdad3e39854176ffb68c3e02615b66f73db8f462fd5.webp +3 -0
  26. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/0584eb516c4e8dc4bc7f84368ea509704f2a8dbd41c1d70b10d52ea5c1aadb26.jpg +3 -0
  27. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/059ef98a3e106f6b8010956d1f293a6bcdf1630694bfcb3e1e4cf00275761b06.webp +3 -0
  28. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/05a0be34910b9dc1bd1e5e0f6fd819ce0234dc78c8707911def7fdf10a12f830.webp +3 -0
  29. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/06096be7d33c2196b6c73363f0fd7d68efb47bd31b679323ea22b2f385e9c89d.webp +3 -0
  30. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/060bb7f199faaf938baa691bef4a2045ddf980867480fca36b9bf3bde27809da.webp +3 -0
  31. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/062b51f1cbd945e5b001ecc70ff71136e10c24496d428f63b7ba1b8336610ca8.webp +3 -0
  32. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/065f632215925d10c28e0e04d38bcfbc7efb14554b94061574dcce2718d6a93a.webp +3 -0
  33. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e405dcf476d69ed5b530da11192bd36d26804417a85381001b67131b78e92ef.webp +3 -0
  34. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e41e2e86895a3c76e2df25ed2a8f6992804f826684db43fe835dff9aa6030ca.webp +3 -0
  35. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e7b5d501da606e2aa533216fcce1f3fd92fcc936f0268a36d73cf2c1e8b6454.webp +3 -0
  36. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e7ccdc8e29cc1bd5872ec107f14b43f498f31a2f1328f3ef87860cece61c384.webp +3 -0
  37. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e84042c6f9c936419cd3eb15b6434dc4d9bcd949fdc99a29ac1336c63aa931d.webp +3 -0
  38. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0ec22cb9496501ba1770c6aff4089b64c46a7cb66748443161ca437896be5dda.webp +3 -0
  39. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f34077d79acde3ffb91325acf5e6a001be9459806dfb656494037e4fc90cd38.webp +3 -0
  40. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f6a8a3756773ac8ca250916e7bb0d783e0fb592a62463a52af1f066eecbf5f7.webp +3 -0
  41. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f7a7fbe58afd74f43421b536eb0247116a9dfb04fbfca5c490633338defaaca.webp +3 -0
  42. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fc4b497202c05dc7c07321ba731b9842eadf4eae697b243e67183bf671c621f.webp +3 -0
  43. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fdd859840add212345a340d960846e587fa4cd4eacd0be59e6564f401b17e20.webp +3 -0
  44. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fdf1e3e2be6c9065a895164d37ee93c8a00cdc6a10c0a653ee699f6654e6230.webp +3 -0
  45. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/13/13d8f89047bdeb9209be37e51f2d55fd2dbe2c8f8d3f3ccc84f87f4d043c2a68.webp +3 -0
  46. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/13/13f80b43c80d556b249ddb21482fe783a1e4490350698761e325a9d0134c6b4f.webp +3 -0
  47. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14517f64e26786607993dd204a06e925161edca4784f86510b1d0dc174d89a92.jpg +3 -0
  48. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/148e8d18ea5609bf650a8606d21a685021dac51e4fe5ada4fb6c17ace7078cb0.webp +3 -0
  49. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14aaef5a280cdab1624bb233c03fbff3ec60a8904f025cacaf61e8f6335e0d24.webp +3 -0
  50. tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14c1a735a2700bb8e54b4c06ddeee396e7041c4f744c281782c7ede1f3acdfbc.webp +3 -0
tasks/petfinder/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/petfinder/solution/site/implementation/backend/runtime.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": {
3
+ "data_dir": "runtime-data",
4
+ "engine": "sqlite",
5
+ "filename": "petfinder.sqlite3",
6
+ "legacy_unbound_migration": false,
7
+ "migration_hook": "backend.db:apply_site_backend_migrations",
8
+ "seed_hook": "backend.db:seed_site_backend",
9
+ "volume_identity": "websitebench-petfinder-data"
10
+ },
11
+ "deployment": {
12
+ "profiles": {
13
+ "cloudflare-review": {
14
+ "mail_adapter": "redis-resend",
15
+ "payment_adapter": "local-sandbox",
16
+ "persistence": "ephemeral-reset"
17
+ },
18
+ "docker-volume": {
19
+ "mail_adapter": "effects-gateway",
20
+ "payment_adapter": "stripe-test",
21
+ "persistence": "persistent-volume"
22
+ },
23
+ "offline-harbor": {
24
+ "mail_adapter": "local-outbox",
25
+ "payment_adapter": "local-sandbox",
26
+ "persistence": "persistent"
27
+ }
28
+ }
29
+ },
30
+ "mail": {
31
+ "enabled": true,
32
+ "purposes": {
33
+ "password-reset": {
34
+ "body": "Your password reset code is ${code}.",
35
+ "expiry": "This code expires in ${minutes} minutes.",
36
+ "footer": "Ignore this message if you did not contact petfinder offline clone.",
37
+ "lead": "A password reset was requested for petfinder offline clone.",
38
+ "required_variables": [
39
+ "code",
40
+ "minutes"
41
+ ],
42
+ "secret_variables": [
43
+ "code"
44
+ ],
45
+ "subject": "Reset your petfinder offline clone password",
46
+ "template_id": "petfinder.password-reset.v1"
47
+ },
48
+ "registration": {
49
+ "body": "Your verification code is ${code}.",
50
+ "expiry": "This code expires in ${minutes} minutes.",
51
+ "footer": "This code is only for petfinder offline clone.",
52
+ "lead": "Finish creating your petfinder offline clone account.",
53
+ "required_variables": [
54
+ "code",
55
+ "minutes"
56
+ ],
57
+ "secret_variables": [
58
+ "code"
59
+ ],
60
+ "subject": "Verify your petfinder offline clone account",
61
+ "template_id": "petfinder.registration.v1"
62
+ },
63
+ "support-receipt": {
64
+ "body": "Receipt ${receipt_id} records a test-only support payment of ${total}.",
65
+ "expiry": "No real donation, payment, or tax-deductible contribution occurred.",
66
+ "footer": "This simulated receipt does not benefit Petfinder or any shelter or rescue.",
67
+ "lead": "Your Petfinder offline clone support payment was recorded in sandbox mode.",
68
+ "required_variables": [
69
+ "receipt_id",
70
+ "total"
71
+ ],
72
+ "secret_variables": [],
73
+ "subject": "Petfinder offline clone support receipt ${receipt_id}",
74
+ "template_id": "petfinder.support-receipt.v1"
75
+ }
76
+ },
77
+ "sender": {
78
+ "address_env": "RESEND_FROM_EMAIL",
79
+ "display_name": "petfinder offline clone"
80
+ }
81
+ },
82
+ "payments": {
83
+ "currency": "USD",
84
+ "default_adapter": "local-sandbox",
85
+ "enabled": true,
86
+ "local_sandbox": {
87
+ "scenarios": [
88
+ {
89
+ "display_label": "Simulated approval",
90
+ "id": "sandbox-approved",
91
+ "outcome": "approved"
92
+ },
93
+ {
94
+ "display_label": "Simulated decline",
95
+ "id": "sandbox-declined",
96
+ "outcome": "declined"
97
+ },
98
+ {
99
+ "display_label": "Simulated retry",
100
+ "id": "sandbox-retry",
101
+ "outcome": "retryable"
102
+ }
103
+ ]
104
+ },
105
+ "stripe_test": {
106
+ "max_line_items": 1,
107
+ "public_origin": "https://petfinder.website-bench.com",
108
+ "return_path": "/support/stripe-return",
109
+ "secret_key_env": "PETFINDER_STRIPE_TEST_SECRET_KEY",
110
+ "webhook_path": "/api/stripe/webhook",
111
+ "webhook_secret_env": "PETFINDER_STRIPE_TEST_WEBHOOK_SECRET"
112
+ }
113
+ },
114
+ "schema_version": "websitebench.site-backend-runtime.v1",
115
+ "session": {
116
+ "host_only": true,
117
+ "http_only": true,
118
+ "same_site": "Lax",
119
+ "secure": true
120
+ },
121
+ "site": {
122
+ "id": "petfinder",
123
+ "label": "petfinder offline clone",
124
+ "public_origin": "https://petfinder.website-bench.com"
125
+ }
126
+ }
tasks/petfinder/solution/site/implementation/clone/__init__.py ADDED
File without changes
tasks/petfinder/solution/site/implementation/clone/app.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/petfinder/solution/site/implementation/clone/backend/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Persistent backend package for the Petfinder offline clone (R3 stage).
2
+
3
+ SQLite (WAL) persistence with an explicit, ordered migration history and a
4
+ deterministic benchmark-owned seed. The database lives under
5
+ the generated WebsiteBench runtime contract (always outside clone/).
6
+ """
tasks/petfinder/solution/site/implementation/clone/backend/db.py ADDED
@@ -0,0 +1,2200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite persistence for the Petfinder offline clone (R3 persistent backend).
2
+
3
+ Contract:
4
+ - sqlite3 in WAL mode; the database file is selected exclusively by the
5
+ WebsiteBench site-backend runtime contract and always lives outside clone/.
6
+ - An ordered, copy-only migration history recorded in ``schema_migrations``.
7
+ - A deterministic benchmark-owned seed: the 24 frozen animals from the
8
+ 2026-07-25 capture (12 dogs @10001, 12 cats @90210, exact frozen order),
9
+ one intentionally stale animal, five shelters, and the two synthetic
10
+ fixture accounts (alex-green, jordan-reyes).
11
+ - The server owns animal, shelter, account, favorite, adopter profile, and
12
+ inquiry records. Nothing here contacts production Petfinder.
13
+
14
+ Every function resolves the database selected by the active site-backend
15
+ runtime, including its validated deployment override, at call time.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import re
25
+ import secrets
26
+ import sqlite3
27
+ import importlib.util
28
+ import sys
29
+ from datetime import datetime, timedelta
30
+ from pathlib import Path
31
+ from typing import Any, Callable, Iterable
32
+
33
+ _MIGRATIONS_NAME = "petfinder_domain_migrations"
34
+ if _MIGRATIONS_NAME in sys.modules:
35
+ domain_migrations = sys.modules[_MIGRATIONS_NAME]
36
+ else:
37
+ _migrations_spec = importlib.util.spec_from_file_location(
38
+ _MIGRATIONS_NAME, Path(__file__).with_name("migrations.py")
39
+ )
40
+ assert _migrations_spec is not None and _migrations_spec.loader is not None
41
+ domain_migrations = importlib.util.module_from_spec(_migrations_spec)
42
+ sys.modules[_MIGRATIONS_NAME] = domain_migrations
43
+ _migrations_spec.loader.exec_module(domain_migrations)
44
+
45
+
46
+ def _load_backend_module(name: str, filename: str):
47
+ if name in sys.modules:
48
+ return sys.modules[name]
49
+ spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))
50
+ assert spec is not None and spec.loader is not None
51
+ module = importlib.util.module_from_spec(spec)
52
+ sys.modules[name] = module
53
+ spec.loader.exec_module(module)
54
+ return module
55
+
56
+
57
+ domain_policies = _load_backend_module("petfinder_domain_policies", "policies.py")
58
+ domain_repositories = _load_backend_module("petfinder_domain_repositories", "repositories.py")
59
+ domain_services = _load_backend_module("petfinder_domain_services", "services.py")
60
+
61
+ SITE_DIR = Path(__file__).resolve().parents[2]
62
+ DEFAULT_DATA_DIR = SITE_DIR / "runtime-data"
63
+ DATABASE_FILENAME = "petfinder.sqlite3"
64
+ _RUNTIME_DATABASE_PATH: Path | None = None
65
+
66
+ FROZEN_CLOCK = "2026-07-25T12:00:00-04:00"
67
+ ASSET_BASE = "/static/assets/source-current/2026-07-25"
68
+
69
+ _FROZEN_DT = datetime.fromisoformat(FROZEN_CLOCK)
70
+
71
+ # Generic Petfinder search behavior: non-transportable pets appear within
72
+ # this radius of the searched ZIP (mirrors the UI's "Distance: 100 miles").
73
+ SEARCH_RADIUS_MILES = 100.0
74
+
75
+
76
+ class StaleVersionError(RuntimeError):
77
+ """A client attempted to mutate an obsolete business version."""
78
+
79
+
80
+ class IdempotencyConflict(RuntimeError):
81
+ """An idempotency key was reused with a different canonical payload."""
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Frozen seed fixtures (benchmark-owned; mirrors the 2026-07-25 capture).
85
+ # All benchmark constants below are ordinary seed rows -- backend logic
86
+ # never branches on any of these values.
87
+ # ---------------------------------------------------------------------------
88
+
89
+ SHELTERS: list[dict[str, Any]] = [
90
+ # zip_code locates the shelter; transport_radius_miles is how far the
91
+ # shelter transports its out-of-town-listed pets (0 = local-only).
92
+ {"id": "mutts-galore", "name": "Mutts Galore",
93
+ "zip_code": "08701", "transport_radius_miles": 250},
94
+ {"id": "texoma-dog-ranch", "name": "Texoma Dog Ranch",
95
+ "zip_code": "75020", "transport_radius_miles": 1600},
96
+ {"id": "border-paws-rgv", "name": "Border Paws of the RGV",
97
+ "zip_code": "10001", "transport_radius_miles": 0},
98
+ {"id": "bobbies-street-cats", "name": "Bobbie's Street Cats",
99
+ "zip_code": "90211", "transport_radius_miles": 0},
100
+ {"id": "amanda-foundation", "name": "Amanda Foundation",
101
+ "zip_code": "90212", "transport_radius_miles": 0},
102
+ ]
103
+ SHELTER_ID_BY_NAME = {row["name"]: row["id"] for row in SHELTERS}
104
+
105
+ # ZIP centroid seed rows (ordinary geographic reference data). Unknown
106
+ # ZIPs degrade generically: exact row -> shared ZIP3 prefix row -> USPS
107
+ # national-area (first digit) centroid.
108
+ ZIP_LOCATIONS: list[dict[str, Any]] = [
109
+ {"zip_code": "10001", "city": "New York", "state_abbr": "NY",
110
+ "latitude": 40.7484, "longitude": -73.9967},
111
+ {"zip_code": "90210", "city": "Beverly Hills", "state_abbr": "CA",
112
+ "latitude": 34.0901, "longitude": -118.4065},
113
+ {"zip_code": "90211", "city": "Beverly Hills", "state_abbr": "CA",
114
+ "latitude": 34.0650, "longitude": -118.3835},
115
+ {"zip_code": "90212", "city": "Beverly Hills", "state_abbr": "CA",
116
+ "latitude": 34.0620, "longitude": -118.4009},
117
+ {"zip_code": "08701", "city": "Lakewood", "state_abbr": "NJ",
118
+ "latitude": 40.0763, "longitude": -74.2031},
119
+ {"zip_code": "75020", "city": "Denison", "state_abbr": "TX",
120
+ "latitude": 33.7557, "longitude": -96.5570},
121
+ {"zip_code": "78501", "city": "McAllen", "state_abbr": "TX",
122
+ "latitude": 26.2159, "longitude": -98.2372},
123
+ {"zip_code": "60601", "city": "Chicago", "state_abbr": "IL",
124
+ "latitude": 41.8858, "longitude": -87.6229},
125
+ ]
126
+
127
+ # Coarse USPS national-area centroids (generic postal geography, one row
128
+ # per leading ZIP digit) used as the last geocoding fallback.
129
+ ZIP1_REGION_CENTROIDS: dict[str, tuple[float, float]] = {
130
+ "0": (42.9, -71.5), "1": (41.5, -74.5), "2": (37.5, -78.0),
131
+ "3": (33.0, -84.0), "4": (40.0, -84.5), "5": (45.0, -93.5),
132
+ "6": (39.0, -92.5), "7": (32.5, -97.0), "8": (39.5, -106.0),
133
+ "9": (37.0, -120.0),
134
+ }
135
+
136
+ # Representative state slug per USPS national area (URL fallback only).
137
+ ZIP1_STATE_SEGMENTS: dict[str, str] = {
138
+ "0": "ma", "1": "ny", "2": "va", "3": "ga", "4": "oh",
139
+ "5": "mn", "6": "mo", "7": "tx", "8": "co", "9": "ca",
140
+ }
141
+
142
+ # Point-in-time result-count facts observed in the 2026-07-25 capture.
143
+ # Searches without a captured fact honestly render only the local count.
144
+ SEARCH_COUNT_FACTS: list[dict[str, str]] = [
145
+ {"species": "dog", "zip_code": "10001",
146
+ "result_count_fact": "24,677", "observed_on": "2026-07-25"},
147
+ {"species": "cat", "zip_code": "90210",
148
+ "result_count_fact": "10,561", "observed_on": "2026-07-25"},
149
+ ]
150
+
151
+ ACCOUNTS: list[dict[str, str]] = [
152
+ {
153
+ "id": "alex-green",
154
+ "name": "Alex Green",
155
+ "email": "alex.green@example.test",
156
+ "initials": "AG",
157
+ },
158
+ {
159
+ "id": "jordan-reyes",
160
+ "name": "Jordan Reyes",
161
+ "email": "jordan.reyes@example.test",
162
+ "initials": "JR",
163
+ },
164
+ ]
165
+
166
+
167
+ def _slug(name: str) -> str:
168
+ return re.sub(r"[^a-z0-9]+", "-", name.casefold()).strip("-")
169
+
170
+
171
+ def _dog(
172
+ number: int,
173
+ name: str,
174
+ breed: str,
175
+ age: str,
176
+ sex: str,
177
+ shelter: str,
178
+ photo: str,
179
+ *,
180
+ good_with: str = "",
181
+ house_trained: str = "No",
182
+ out_of_town: bool = True,
183
+ adoptable: bool = True,
184
+ position: int | None = None,
185
+ size: str | None = None,
186
+ color: str | None = None,
187
+ coat: str | None = None,
188
+ ) -> dict[str, Any]:
189
+ resolved_position = number if position is None else position
190
+ sizes = ("Medium", "Large", "Small")
191
+ colors = ("Black", "Brown", "White")
192
+ coats = ("Short", "Medium", "Long")
193
+ return {
194
+ "id": f"771{number:05d}",
195
+ "slug": _slug(name),
196
+ "species": "dog",
197
+ "name": name,
198
+ "breed": breed,
199
+ "age": age,
200
+ "sex": sex,
201
+ "shelter": shelter,
202
+ "distance": "0 miles away",
203
+ "photo": f"{ASSET_BASE}/dogs-10001/{photo}",
204
+ "good_with": good_with,
205
+ "house_trained": house_trained,
206
+ "out_of_town": out_of_town,
207
+ "adoptable": adoptable,
208
+ "position": resolved_position,
209
+ "size": size or sizes[(resolved_position - 1) % len(sizes)],
210
+ "color": color or colors[(resolved_position - 1) % len(colors)],
211
+ "coat": coat or coats[(resolved_position - 1) % len(coats)],
212
+ # Freshness seed: newer listings were captured earlier in the frozen
213
+ # result page, so listed_at recedes one day per capture position.
214
+ "listed_at": (_FROZEN_DT - timedelta(days=resolved_position)).isoformat(),
215
+ }
216
+
217
+
218
+ def _cat(
219
+ number: int,
220
+ name: str,
221
+ breed: str,
222
+ age: str,
223
+ sex: str,
224
+ shelter: str,
225
+ photo: str,
226
+ *,
227
+ good_with: str = "",
228
+ house_trained: str = "Yes",
229
+ size: str | None = None,
230
+ color: str | None = None,
231
+ coat: str | None = None,
232
+ ) -> dict[str, Any]:
233
+ sizes = ("Small", "Medium", "Large")
234
+ colors = ("Black", "White", "Gray")
235
+ coats = ("Short", "Medium", "Long")
236
+ return {
237
+ "id": f"779{number:05d}",
238
+ "slug": _slug(name),
239
+ "species": "cat",
240
+ "name": name,
241
+ "breed": breed,
242
+ "age": age,
243
+ "sex": sex,
244
+ "shelter": shelter,
245
+ "distance": "2 miles away",
246
+ "photo": f"{ASSET_BASE}/cats-90210/{photo}",
247
+ "good_with": good_with,
248
+ "house_trained": house_trained,
249
+ "out_of_town": False,
250
+ "adoptable": True,
251
+ "position": number,
252
+ "size": size or sizes[(number - 1) % len(sizes)],
253
+ "color": color or colors[(number - 1) % len(colors)],
254
+ "coat": coat or coats[(number - 1) % len(coats)],
255
+ "listed_at": (_FROZEN_DT - timedelta(days=number)).isoformat(),
256
+ }
257
+
258
+
259
+ # Deterministic frozen card order mirroring the 2026-07-25 capture.
260
+ SEED_DOGS: list[dict[str, Any]] = [
261
+ _dog(1, "Nala", "Border Collie", "Puppy", "Female", "Mutts Galore",
262
+ "dog-card-01-nala.jpeg", good_with="Dogs, Children Under 8"),
263
+ _dog(2, "CM", "Labrador Retriever", "Puppy", "Male", "Mutts Galore",
264
+ "dog-card-02-cm.jpeg", good_with="Dogs, Children Under 8"),
265
+ _dog(3, "Laura", "American Staffordshire Terrier", "Adult", "Female",
266
+ "Texoma Dog Ranch", "dog-card-03-laura.jpeg", house_trained="Yes"),
267
+ _dog(4, "Dotty", "Black Labrador Retriever & Pit Bull Terrier", "Adult",
268
+ "Female", "Texoma Dog Ranch", "dog-card-04-dotty.jpeg",
269
+ house_trained="Yes"),
270
+ _dog(5, "Mamie", "Shepherd & Husky", "Adult", "Female",
271
+ "Texoma Dog Ranch", "dog-card-05-mamie.jpeg", house_trained="Yes"),
272
+ _dog(6, "Yazmin", "Australian Cattle Dog / Blue Heeler", "Young",
273
+ "Female", "Border Paws of the RGV", "dog-card-06-yazmin.jpeg",
274
+ good_with="Dogs, Children Under 8", house_trained="Yes",
275
+ out_of_town=False),
276
+ _dog(7, "Brownie", "Beagle", "Adult", "Male", "Texoma Dog Ranch",
277
+ "dog-card-07-brownie.jpeg", good_with="Dogs"),
278
+ _dog(8, "Katrina", "Staffordshire Bull Terrier", "Young", "Female",
279
+ "Texoma Dog Ranch", "dog-card-08-katrina.jpeg"),
280
+ _dog(9, "Roger", "Pit Bull Terrier", "Adult", "Male", "Texoma Dog Ranch",
281
+ "dog-card-09-roger.jpeg", good_with="Dogs", house_trained="Yes"),
282
+ _dog(10, "Ruger", "Boxer & Pit Bull Terrier", "Adult", "Female",
283
+ "Mutts Galore", "dog-card-10-ruger.jpg",
284
+ good_with="Dogs, Children Over 8, Children Under 8",
285
+ house_trained="Yes"),
286
+ _dog(11, "Cookie", "Labrador Retriever", "Young", "Female",
287
+ "Texoma Dog Ranch", "dog-card-11-cookie.jpeg",
288
+ good_with="Dogs, Other Animals"),
289
+ _dog(12, "Merlin", "Mixed Breed", "Young", "Male", "Texoma Dog Ranch",
290
+ "dog-card-12-merlin.jpeg",
291
+ good_with="Dogs, Children Over 8, Children Under 8",
292
+ house_trained="Yes"),
293
+ ]
294
+
295
+ SEED_CATS: list[dict[str, Any]] = [
296
+ _cat(1, "Jay", "Domestic Medium Hair", "Kitten", "Male",
297
+ "Bobbie's Street Cats", "cat-card-01-jay.jpg"),
298
+ _cat(2, "Oreo", "Domestic Short Hair", "Kitten", "Male",
299
+ "Bobbie's Street Cats", "cat-card-02-oreo.jpg"),
300
+ _cat(3, "Kiwi", "Domestic Medium Hair", "Kitten", "Female",
301
+ "Bobbie's Street Cats", "cat-card-03-kiwi.jpg"),
302
+ _cat(4, "Arwen", "Domestic Short Hair", "Young", "Female",
303
+ "Amanda Foundation", "cat-card-04-arwen.jpg",
304
+ good_with="Cats, Children Over 8, Children Under 8"),
305
+ _cat(5, "Gingerbread", "Domestic Short Hair & Tabby", "Young", "Male",
306
+ "Amanda Foundation", "cat-card-05-gingerbread.jpg",
307
+ good_with="Cats, Children Under 8"),
308
+ _cat(6, "Plum Blossom", "Russian Blue", "Young", "Female",
309
+ "Amanda Foundation", "cat-card-06-plum-blossom.jpg",
310
+ good_with="Cats", house_trained="No"),
311
+ _cat(7, "Orchid", "Russian Blue", "Kitten", "Female",
312
+ "Amanda Foundation", "cat-card-07-orchid.jpg",
313
+ good_with="Dogs, Cats, Children Under 8"),
314
+ _cat(8, "Leopard", "Tuxedo", "Kitten", "Male", "Amanda Foundation",
315
+ "cat-card-08-leopard.jpg", good_with="Cats, Children Under 8"),
316
+ _cat(9, "Lion", "Russian Blue", "Kitten", "Male", "Amanda Foundation",
317
+ "cat-card-09-lion.jpg", good_with="Dogs, Cats, Children Under 8"),
318
+ _cat(10, "Harmony", "Russian Blue", "Young", "Female",
319
+ "Amanda Foundation", "cat-card-10-harmony.jpg", good_with="Cats"),
320
+ _cat(11, "Taco", "Domestic Short Hair", "Kitten", "Male",
321
+ "Amanda Foundation", "cat-card-11-taco.jpg",
322
+ good_with="Dogs, Cats, Children Under 8"),
323
+ _cat(12, "Fluttershy", "Domestic Short Hair & Tabby", "Kitten", "Female",
324
+ "Amanda Foundation", "cat-card-12-fluttershy.jpg",
325
+ good_with="Cats, Children Under 8"),
326
+ ]
327
+
328
+ # One intentionally stale seed animal: still routable, never favoritable.
329
+ SEED_STALE: dict[str, Any] = _dog(
330
+ 99, "Shadow", "German Shepherd Dog", "Adult", "Male", "Mutts Galore",
331
+ "dog-card-12-merlin.jpeg", house_trained="Yes", adoptable=False,
332
+ position=99,
333
+ )
334
+
335
+ SEED_ANIMALS: list[dict[str, Any]] = [*SEED_DOGS, *SEED_CATS, SEED_STALE]
336
+
337
+ FIRST_DOG_ID = SEED_DOGS[0]["id"] # 77100001 (Nala)
338
+ FIRST_CAT_ID = SEED_CATS[0]["id"] # 77900001 (Jay)
339
+ STALE_ANIMAL_ID = SEED_STALE["id"] # 77100099 (Shadow)
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Connection management
344
+ # ---------------------------------------------------------------------------
345
+
346
+ def configure_runtime_database_path(path: Path | str) -> Path:
347
+ """Bind business persistence to the generated runtime's database path."""
348
+
349
+ candidate = Path(path).resolve()
350
+ if candidate.name != DATABASE_FILENAME:
351
+ raise ValueError("runtime database filename does not match Petfinder contract")
352
+ clone_root = SITE_DIR / "clone"
353
+ if candidate.parent == clone_root or clone_root in candidate.parents:
354
+ raise ValueError("runtime database must never live inside clone/")
355
+ global _RUNTIME_DATABASE_PATH
356
+ _RUNTIME_DATABASE_PATH = candidate
357
+ return candidate
358
+
359
+
360
+ def _deployment_database_path() -> Path | None:
361
+ configured = os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE", "").strip()
362
+ if not configured:
363
+ return None
364
+ return configure_runtime_database_path(configured)
365
+
366
+
367
+ def data_dir() -> Path:
368
+ configured = _deployment_database_path()
369
+ if configured is not None:
370
+ return configured.parent
371
+ if _RUNTIME_DATABASE_PATH is not None:
372
+ return _RUNTIME_DATABASE_PATH.parent
373
+ return DEFAULT_DATA_DIR
374
+
375
+
376
+ def database_path() -> Path:
377
+ configured = _deployment_database_path()
378
+ if configured is not None:
379
+ return configured
380
+ if _RUNTIME_DATABASE_PATH is not None:
381
+ return _RUNTIME_DATABASE_PATH
382
+ return data_dir() / DATABASE_FILENAME
383
+
384
+
385
+ def connect(path: Path | None = None) -> sqlite3.Connection:
386
+ target = path or database_path()
387
+ target.parent.mkdir(parents=True, exist_ok=True)
388
+ connection = sqlite3.connect(target)
389
+ connection.row_factory = sqlite3.Row
390
+ connection.execute("PRAGMA journal_mode=WAL")
391
+ connection.execute("PRAGMA synchronous=NORMAL")
392
+ connection.execute("PRAGMA foreign_keys=ON")
393
+ connection.execute("PRAGMA busy_timeout=5000")
394
+ return connection
395
+
396
+
397
+ # ---------------------------------------------------------------------------
398
+ # Migration history (ordered, copy-only, recorded in schema_migrations)
399
+ # ---------------------------------------------------------------------------
400
+
401
+ def _migration_0001_initial(connection: sqlite3.Connection) -> None:
402
+ domain_migrations.execute_sql_script(
403
+ connection,
404
+ """
405
+ CREATE TABLE shelters (
406
+ id TEXT PRIMARY KEY,
407
+ name TEXT NOT NULL UNIQUE
408
+ );
409
+ CREATE TABLE accounts (
410
+ id TEXT PRIMARY KEY,
411
+ name TEXT NOT NULL,
412
+ email TEXT NOT NULL,
413
+ initials TEXT NOT NULL
414
+ );
415
+ CREATE TABLE animals (
416
+ id TEXT PRIMARY KEY,
417
+ slug TEXT NOT NULL,
418
+ species TEXT NOT NULL CHECK (species IN ('dog', 'cat')),
419
+ name TEXT NOT NULL,
420
+ breed TEXT NOT NULL,
421
+ age TEXT NOT NULL,
422
+ sex TEXT NOT NULL,
423
+ shelter_id TEXT NOT NULL REFERENCES shelters(id),
424
+ distance TEXT NOT NULL,
425
+ photo TEXT NOT NULL,
426
+ good_with TEXT NOT NULL DEFAULT '',
427
+ house_trained TEXT NOT NULL,
428
+ out_of_town INTEGER NOT NULL DEFAULT 0,
429
+ adoptable INTEGER NOT NULL DEFAULT 1,
430
+ position INTEGER NOT NULL
431
+ );
432
+ CREATE TABLE favorites (
433
+ account_id TEXT NOT NULL REFERENCES accounts(id),
434
+ animal_id TEXT NOT NULL REFERENCES animals(id),
435
+ created_at TEXT NOT NULL,
436
+ PRIMARY KEY (account_id, animal_id)
437
+ );
438
+ CREATE TABLE adopter_profiles (
439
+ account_id TEXT PRIMARY KEY REFERENCES accounts(id),
440
+ full_name TEXT NOT NULL,
441
+ email TEXT NOT NULL,
442
+ phone TEXT NOT NULL,
443
+ zip_code TEXT NOT NULL,
444
+ housing TEXT NOT NULL,
445
+ animal_id TEXT NOT NULL REFERENCES animals(id),
446
+ inquiry_id TEXT NOT NULL,
447
+ created_at TEXT NOT NULL
448
+ );
449
+ CREATE TABLE inquiries (
450
+ id TEXT PRIMARY KEY,
451
+ account_id TEXT NOT NULL REFERENCES accounts(id),
452
+ animal_id TEXT NOT NULL REFERENCES animals(id),
453
+ created_at TEXT NOT NULL
454
+ );
455
+ """
456
+ )
457
+
458
+
459
+ def _migration_0002_inquiry_status_and_indexes(
460
+ connection: sqlite3.Connection,
461
+ ) -> None:
462
+ # Copy-only: existing rows are preserved; the new column defaults to the
463
+ # only truthful state a local fixture inquiry can have ('draft').
464
+ domain_migrations.execute_sql_script(
465
+ connection,
466
+ """
467
+ ALTER TABLE inquiries
468
+ ADD COLUMN status TEXT NOT NULL DEFAULT 'draft';
469
+ CREATE INDEX IF NOT EXISTS idx_favorites_account
470
+ ON favorites(account_id);
471
+ CREATE INDEX IF NOT EXISTS idx_animals_species_position
472
+ ON animals(species, position);
473
+ """
474
+ )
475
+
476
+
477
+ def _migration_0003_geo_sessions_and_freshness(
478
+ connection: sqlite3.Connection,
479
+ ) -> None:
480
+ # Copy-only, additive change: geographic reference tables, persisted
481
+ # server-side sessions, listing freshness, and dated search-count facts.
482
+ domain_migrations.execute_sql_script(
483
+ connection,
484
+ """
485
+ ALTER TABLE shelters
486
+ ADD COLUMN zip_code TEXT NOT NULL DEFAULT '';
487
+ ALTER TABLE shelters
488
+ ADD COLUMN transport_radius_miles REAL NOT NULL DEFAULT 0;
489
+ ALTER TABLE animals
490
+ ADD COLUMN listed_at TEXT NOT NULL DEFAULT '';
491
+ CREATE TABLE zip_locations (
492
+ zip_code TEXT PRIMARY KEY,
493
+ city TEXT NOT NULL,
494
+ state_abbr TEXT NOT NULL,
495
+ latitude REAL NOT NULL,
496
+ longitude REAL NOT NULL
497
+ );
498
+ CREATE TABLE search_count_facts (
499
+ species TEXT NOT NULL,
500
+ zip_code TEXT NOT NULL,
501
+ result_count_fact TEXT NOT NULL,
502
+ observed_on TEXT NOT NULL,
503
+ PRIMARY KEY (species, zip_code)
504
+ );
505
+ CREATE TABLE sessions (
506
+ token TEXT PRIMARY KEY,
507
+ account_id TEXT NOT NULL REFERENCES accounts(id),
508
+ created_at TEXT NOT NULL
509
+ );
510
+ CREATE INDEX IF NOT EXISTS idx_sessions_account
511
+ ON sessions(account_id);
512
+ CREATE INDEX IF NOT EXISTS idx_animals_species_listed
513
+ ON animals(species, listed_at);
514
+ """
515
+ )
516
+
517
+
518
+ def _migration_0004_authoritative_business_commands(
519
+ connection: sqlite3.Connection,
520
+ ) -> None:
521
+ """Add versioned/idempotent business write boundaries.
522
+
523
+ The legacy state tables remain the canonical read model so the frozen
524
+ frontend identity does not change. These tables own command identity,
525
+ optimistic versions, and the local-auth subject binding.
526
+ """
527
+ domain_migrations.execute_sql_script(
528
+ connection,
529
+ """
530
+ CREATE TABLE business_subjects (
531
+ subject_id TEXT PRIMARY KEY,
532
+ account_id TEXT NOT NULL UNIQUE REFERENCES accounts(id)
533
+ ON DELETE CASCADE,
534
+ created_at TEXT NOT NULL
535
+ );
536
+ CREATE TABLE business_favorites_version_journal (
537
+ account_id TEXT PRIMARY KEY REFERENCES accounts(id)
538
+ ON DELETE CASCADE,
539
+ version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0)
540
+ );
541
+ CREATE TABLE business_favorites_command (
542
+ account_id TEXT NOT NULL REFERENCES accounts(id)
543
+ ON DELETE CASCADE,
544
+ idempotency_key TEXT NOT NULL,
545
+ payload_sha256 TEXT NOT NULL,
546
+ expected_version INTEGER NOT NULL,
547
+ result_json TEXT NOT NULL,
548
+ created_at TEXT NOT NULL,
549
+ PRIMARY KEY (account_id, idempotency_key)
550
+ );
551
+ CREATE TABLE business_adopter_profile_inquiry_version_journal (
552
+ account_id TEXT PRIMARY KEY REFERENCES accounts(id)
553
+ ON DELETE CASCADE,
554
+ version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0)
555
+ );
556
+ CREATE TABLE business_adopter_profile_inquiry_command (
557
+ account_id TEXT NOT NULL REFERENCES accounts(id)
558
+ ON DELETE CASCADE,
559
+ idempotency_key TEXT NOT NULL,
560
+ payload_sha256 TEXT NOT NULL,
561
+ expected_version INTEGER NOT NULL,
562
+ result_json TEXT NOT NULL,
563
+ created_at TEXT NOT NULL,
564
+ PRIMARY KEY (account_id, idempotency_key)
565
+ );
566
+ CREATE TABLE business_animal_discovery_search_command (
567
+ command_id TEXT PRIMARY KEY,
568
+ session_scope TEXT NOT NULL,
569
+ payload_sha256 TEXT NOT NULL,
570
+ result_count INTEGER NOT NULL CHECK (result_count >= 0),
571
+ created_at TEXT NOT NULL
572
+ );
573
+ CREATE INDEX business_search_session_idx
574
+ ON business_animal_discovery_search_command(session_scope);
575
+ """
576
+ )
577
+
578
+
579
+ def _migration_0008_inquiry_recipient_binding(
580
+ connection: sqlite3.Connection,
581
+ ) -> None:
582
+ """Persist the explicit local listing-owner/recipient boundary."""
583
+
584
+ domain_migrations.execute_sql_script(
585
+ connection,
586
+ """
587
+ ALTER TABLE inquiries ADD COLUMN listing_owner_id TEXT NOT NULL
588
+ DEFAULT 'listing-owner.local.unknown';
589
+ ALTER TABLE inquiries ADD COLUMN listing_owner_version INTEGER NOT NULL
590
+ DEFAULT 1 CHECK (listing_owner_version = 1);
591
+ ALTER TABLE inquiries ADD COLUMN intended_recipient_id TEXT NOT NULL
592
+ DEFAULT 'recipient.unavailable.unknown';
593
+ UPDATE inquiries SET
594
+ listing_owner_id = CASE
595
+ WHEN animal_id LIKE '771%' THEN 'listing-owner.local.dog-10001'
596
+ WHEN animal_id LIKE '779%' THEN 'listing-owner.local.cat-90210'
597
+ ELSE 'listing-owner.local.unknown' END,
598
+ intended_recipient_id = CASE
599
+ WHEN animal_id LIKE '771%' THEN 'recipient.unavailable.dog-10001'
600
+ WHEN animal_id LIKE '779%' THEN 'recipient.unavailable.cat-90210'
601
+ ELSE 'recipient.unavailable.unknown' END;
602
+ """
603
+ )
604
+
605
+
606
+ MIGRATIONS: list[tuple[str, Callable[[sqlite3.Connection], None]]] = [
607
+ ("0001_initial", _migration_0001_initial),
608
+ ("0002_inquiry_status_and_indexes", _migration_0002_inquiry_status_and_indexes),
609
+ ("0003_geo_sessions_and_freshness", _migration_0003_geo_sessions_and_freshness),
610
+ (
611
+ "0004_authoritative_business_commands",
612
+ _migration_0004_authoritative_business_commands,
613
+ ),
614
+ ("0005_identity_organization_animal_search", domain_migrations.identity_organization_animal_search),
615
+ ("0006_personalization_content", domain_migrations.personalization_content),
616
+ ("0007_adoption_communication_review", domain_migrations.adoption_communication_review),
617
+ ("0008_inquiry_recipient_binding", _migration_0008_inquiry_recipient_binding),
618
+ ("0009_support_payment_overlay", domain_migrations.support_payment_overlay),
619
+ ]
620
+ HEAD_MIGRATION_ID = MIGRATIONS[-1][0]
621
+
622
+
623
+ def _ensure_migrations_table(connection: sqlite3.Connection) -> None:
624
+ connection.execute(
625
+ """
626
+ CREATE TABLE IF NOT EXISTS schema_migrations (
627
+ id TEXT PRIMARY KEY,
628
+ applied_at TEXT NOT NULL
629
+ )
630
+ """
631
+ )
632
+
633
+
634
+ def applied_migrations(connection: sqlite3.Connection) -> list[str]:
635
+ _ensure_migrations_table(connection)
636
+ rows = connection.execute(
637
+ "SELECT id FROM schema_migrations ORDER BY rowid"
638
+ ).fetchall()
639
+ return [row["id"] for row in rows]
640
+
641
+
642
+ def apply_migrations(
643
+ connection: sqlite3.Connection, *, upto: str | None = None
644
+ ) -> list[str]:
645
+ """Apply pending migrations in order; return the ids applied this call.
646
+
647
+ ``upto`` lets tests build a legacy database frozen at an older migration.
648
+ """
649
+ snapshot = sqlite3.connect(":memory:")
650
+ connection.backup(snapshot)
651
+ try:
652
+ _ensure_migrations_table(connection)
653
+ already = set(applied_migrations(connection))
654
+ applied: list[str] = []
655
+ for migration_id, apply in MIGRATIONS:
656
+ if migration_id not in already:
657
+ apply(connection)
658
+ connection.execute(
659
+ "INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)",
660
+ (migration_id, FROZEN_CLOCK),
661
+ )
662
+ applied.append(migration_id)
663
+ if upto is not None and migration_id == upto:
664
+ break
665
+ migration_count = int(
666
+ connection.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0]
667
+ )
668
+ connection.execute(f"PRAGMA user_version = {migration_count}")
669
+ connection.commit()
670
+ return applied
671
+ except BaseException:
672
+ connection.rollback()
673
+ snapshot.backup(connection)
674
+ connection.commit()
675
+ raise
676
+ finally:
677
+ snapshot.close()
678
+
679
+
680
+ def apply_site_backend_migrations(connection: sqlite3.Connection) -> None:
681
+ """Run the Petfinder business schema hook inside the runtime transaction."""
682
+
683
+ if not connection.in_transaction:
684
+ raise RuntimeError("site-backend migration hook requires an active transaction")
685
+ _ensure_migrations_table(connection)
686
+ already = set(applied_migrations(connection))
687
+ for migration_id, apply in MIGRATIONS:
688
+ if migration_id in already:
689
+ continue
690
+ apply(connection)
691
+ connection.execute(
692
+ "INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)",
693
+ (migration_id, FROZEN_CLOCK),
694
+ )
695
+ migration_count = int(
696
+ connection.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0]
697
+ )
698
+ connection.execute(f"PRAGMA user_version = {migration_count}")
699
+
700
+
701
+ # ---------------------------------------------------------------------------
702
+ # Seed + reset
703
+ # ---------------------------------------------------------------------------
704
+
705
+ def _seed_reference_rows(connection: sqlite3.Connection) -> None:
706
+ """Upsert the frozen shelters, accounts, animals, ZIP centroids, and
707
+ dated search-count facts (both directions: rows added out-of-band are
708
+ removed; rows deleted or mutated out-of-band are restored)."""
709
+ seed_shelter_ids = [row["id"] for row in SHELTERS]
710
+ verifier_mode = os.environ.get("WEBSITEBENCH_VERIFIER_MODE") == "1"
711
+ fixture_accounts = ACCOUNTS if verifier_mode else []
712
+ seed_animal_ids = [row["id"] for row in SEED_ANIMALS]
713
+
714
+ for shelter in SHELTERS:
715
+ connection.execute(
716
+ "INSERT INTO shelters (id, name, zip_code, transport_radius_miles)"
717
+ " VALUES (:id, :name, :zip_code, :transport_radius_miles)"
718
+ " ON CONFLICT(id) DO UPDATE SET name = excluded.name,"
719
+ " zip_code = excluded.zip_code,"
720
+ " transport_radius_miles = excluded.transport_radius_miles",
721
+ shelter,
722
+ )
723
+ for account in fixture_accounts:
724
+ connection.execute(
725
+ "INSERT INTO accounts (id, name, email, initials) "
726
+ "VALUES (:id, :name, :email, :initials) "
727
+ "ON CONFLICT(id) DO UPDATE SET name = excluded.name, "
728
+ "email = excluded.email, initials = excluded.initials",
729
+ account,
730
+ )
731
+ for animal in SEED_ANIMALS:
732
+ record = {
733
+ **animal,
734
+ "shelter_id": SHELTER_ID_BY_NAME[animal["shelter"]],
735
+ "out_of_town": int(animal["out_of_town"]),
736
+ "adoptable": int(animal["adoptable"]),
737
+ }
738
+ connection.execute(
739
+ """
740
+ INSERT INTO animals (
741
+ id, slug, species, name, breed, age, sex, shelter_id,
742
+ distance, photo, good_with, house_trained, out_of_town,
743
+ adoptable, position, listed_at
744
+ ) VALUES (
745
+ :id, :slug, :species, :name, :breed, :age, :sex, :shelter_id,
746
+ :distance, :photo, :good_with, :house_trained, :out_of_town,
747
+ :adoptable, :position, :listed_at
748
+ )
749
+ ON CONFLICT(id) DO UPDATE SET
750
+ slug = excluded.slug, species = excluded.species,
751
+ name = excluded.name, breed = excluded.breed,
752
+ age = excluded.age, sex = excluded.sex,
753
+ shelter_id = excluded.shelter_id,
754
+ distance = excluded.distance, photo = excluded.photo,
755
+ good_with = excluded.good_with,
756
+ house_trained = excluded.house_trained,
757
+ out_of_town = excluded.out_of_town,
758
+ adoptable = excluded.adoptable, position = excluded.position,
759
+ listed_at = excluded.listed_at
760
+ """,
761
+ record,
762
+ )
763
+ for location in ZIP_LOCATIONS:
764
+ connection.execute(
765
+ "INSERT INTO zip_locations"
766
+ " (zip_code, city, state_abbr, latitude, longitude)"
767
+ " VALUES (:zip_code, :city, :state_abbr, :latitude, :longitude)"
768
+ " ON CONFLICT(zip_code) DO UPDATE SET city = excluded.city,"
769
+ " state_abbr = excluded.state_abbr,"
770
+ " latitude = excluded.latitude, longitude = excluded.longitude",
771
+ location,
772
+ )
773
+ for fact in SEARCH_COUNT_FACTS:
774
+ connection.execute(
775
+ "INSERT INTO search_count_facts"
776
+ " (species, zip_code, result_count_fact, observed_on)"
777
+ " VALUES (:species, :zip_code, :result_count_fact, :observed_on)"
778
+ " ON CONFLICT(species, zip_code) DO UPDATE SET"
779
+ " result_count_fact = excluded.result_count_fact,"
780
+ " observed_on = excluded.observed_on",
781
+ fact,
782
+ )
783
+ seed_zip_codes = [row["zip_code"] for row in ZIP_LOCATIONS]
784
+ placeholders = ",".join("?" for _ in seed_zip_codes)
785
+ connection.execute(
786
+ f"DELETE FROM zip_locations WHERE zip_code NOT IN ({placeholders})",
787
+ seed_zip_codes,
788
+ )
789
+ fact_keys = {(row["species"], row["zip_code"]) for row in SEARCH_COUNT_FACTS}
790
+ for row in connection.execute(
791
+ "SELECT species, zip_code FROM search_count_facts"
792
+ ).fetchall():
793
+ if (row["species"], row["zip_code"]) not in fact_keys:
794
+ connection.execute(
795
+ "DELETE FROM search_count_facts"
796
+ " WHERE species = ? AND zip_code = ?",
797
+ (row["species"], row["zip_code"]),
798
+ )
799
+
800
+ def _prune(table: str, keep: Iterable[str]) -> None:
801
+ keep_list = list(keep)
802
+ placeholders = ",".join("?" for _ in keep_list)
803
+ connection.execute(
804
+ f"DELETE FROM {table} WHERE id NOT IN ({placeholders})",
805
+ keep_list,
806
+ )
807
+
808
+ # Dependent rows referencing non-seed reference rows must go first.
809
+ for table, column, keep in (
810
+ ("favorites", "animal_id", seed_animal_ids),
811
+ ("adopter_profiles", "animal_id", seed_animal_ids),
812
+ ("inquiries", "animal_id", seed_animal_ids),
813
+ ):
814
+ placeholders = ",".join("?" for _ in keep)
815
+ connection.execute(
816
+ f"DELETE FROM {table} WHERE {column} NOT IN ({placeholders})",
817
+ list(keep),
818
+ )
819
+ _prune("animals", seed_animal_ids)
820
+ _prune("shelters", seed_shelter_ids)
821
+ _seed_domain_rows(connection, fixture_accounts=fixture_accounts)
822
+
823
+
824
+ def _fixture_auth_account_id(subject_id: str) -> str:
825
+ digest = hashlib.sha256(subject_id.encode("utf-8")).hexdigest()
826
+ return f"account_{digest[:24]}"
827
+
828
+
829
+ def _seed_domain_rows(
830
+ connection: sqlite3.Connection, *, fixture_accounts: list[dict[str, str]]
831
+ ) -> None:
832
+ """Maintain deterministic projections for the normalized domain model."""
833
+ # Compatibility for databases that reached 0006 before the command journal
834
+ # was added to that still-draft migration batch.
835
+ connection.execute(
836
+ "CREATE TABLE IF NOT EXISTS domain_idempotency_commands("
837
+ "user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,"
838
+ "command_kind TEXT NOT NULL,idempotency_key TEXT NOT NULL,"
839
+ "payload_sha256 TEXT NOT NULL,result_json TEXT NOT NULL,created_at TEXT NOT NULL,"
840
+ "PRIMARY KEY(user_id,command_kind,idempotency_key))"
841
+ )
842
+ for account in fixture_accounts:
843
+ connection.execute(
844
+ "INSERT INTO users(id,account_id,display_name,email,created_at)"
845
+ " VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET"
846
+ " account_id=excluded.account_id,display_name=excluded.display_name,"
847
+ " email=excluded.email",
848
+ (
849
+ account["id"], _fixture_auth_account_id(account["id"]),
850
+ account["name"], account["email"], FROZEN_CLOCK,
851
+ ),
852
+ )
853
+ connection.execute(
854
+ "INSERT OR IGNORE INTO favorite_collections"
855
+ "(id,user_id,name,is_default,created_at) VALUES(?,?,?,?,?)",
856
+ (f"default-{account['id']}", account["id"], "My favorites", 1, FROZEN_CLOCK),
857
+ )
858
+ for shelter in SHELTERS:
859
+ location = next(
860
+ (row for row in ZIP_LOCATIONS if row["zip_code"] == shelter["zip_code"]),
861
+ None,
862
+ )
863
+ connection.execute(
864
+ "INSERT INTO organizations(id,name,description,mission,city,state_abbr,"
865
+ "zip_code,verified,response_rate,response_time_hours) VALUES(?,?,?,?,?,?,?,?,?,?)"
866
+ " ON CONFLICT(id) DO UPDATE SET name=excluded.name,zip_code=excluded.zip_code",
867
+ (
868
+ shelter["id"], shelter["name"],
869
+ "A benchmark-owned local shelter profile.",
870
+ "Help pets find safe local homes.",
871
+ location["city"] if location else None,
872
+ location["state_abbr"] if location else None,
873
+ shelter["zip_code"], 1, 85, 24,
874
+ ),
875
+ )
876
+ for location in ZIP_LOCATIONS:
877
+ connection.execute(
878
+ "INSERT INTO locations(zip_code,city,state_abbr,latitude,longitude)"
879
+ " VALUES(:zip_code,:city,:state_abbr,:latitude,:longitude)"
880
+ " ON CONFLICT(zip_code) DO UPDATE SET city=excluded.city,"
881
+ " state_abbr=excluded.state_abbr,latitude=excluded.latitude,"
882
+ " longitude=excluded.longitude",
883
+ location,
884
+ )
885
+ for animal in SEED_ANIMALS:
886
+ organization_id = SHELTER_ID_BY_NAME[animal["shelter"]]
887
+ available = bool(animal["adoptable"])
888
+ good_with = str(animal["good_with"])
889
+ connection.execute(
890
+ "UPDATE animals SET organization_id=? WHERE id=?",
891
+ (organization_id, animal["id"]),
892
+ )
893
+ connection.execute(
894
+ "INSERT INTO animal_profiles(animal_id,primary_breed,age,gender,size,color,coat,"
895
+ "house_trained,good_with_children,good_with_dogs,good_with_cats,description)"
896
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(animal_id) DO UPDATE SET"
897
+ " primary_breed=excluded.primary_breed,age=excluded.age,gender=excluded.gender,"
898
+ "size=excluded.size,color=excluded.color,coat=excluded.coat,"
899
+ "house_trained=excluded.house_trained,"
900
+ "good_with_children=excluded.good_with_children,"
901
+ "good_with_dogs=excluded.good_with_dogs,"
902
+ "good_with_cats=excluded.good_with_cats,description=excluded.description",
903
+ (
904
+ animal["id"], animal["breed"], animal["age"], animal["sex"],
905
+ animal["size"], animal["color"], animal["coat"],
906
+ 1 if animal["house_trained"] == "Yes" else 0,
907
+ 1 if "Children" in good_with else 0,
908
+ 1 if "Dogs" in good_with else 0,
909
+ 1 if "Cats" in good_with else 0,
910
+ f"Meet {animal['name']}, a companion looking for a loving home.",
911
+ ),
912
+ )
913
+ connection.execute(
914
+ "INSERT OR IGNORE INTO animal_status(animal_id,status,version,updated_at)"
915
+ " VALUES(?,?,0,?)",
916
+ (animal["id"], "AVAILABLE" if available else "REMOVED", FROZEN_CLOCK),
917
+ )
918
+ shelter = next(row for row in SHELTERS if row["id"] == organization_id)
919
+ connection.execute(
920
+ "INSERT INTO pet_search_documents(animal_id,keywords,species,breed,"
921
+ "location_zip,traits,availability,indexed_at) VALUES(?,?,?,?,?,?,?,?)"
922
+ " ON CONFLICT(animal_id) DO UPDATE SET keywords=excluded.keywords,"
923
+ " species=excluded.species,breed=excluded.breed,location_zip=excluded.location_zip,"
924
+ " traits=excluded.traits,availability=excluded.availability,indexed_at=excluded.indexed_at",
925
+ (
926
+ animal["id"], f"{animal['name']} {animal['breed']} {good_with}",
927
+ animal["species"], animal["breed"], shelter["zip_code"], good_with,
928
+ "AVAILABLE" if available else "REMOVED", FROZEN_CLOCK,
929
+ ),
930
+ )
931
+ connection.execute(
932
+ "INSERT OR IGNORE INTO article_categories(id,slug,name) VALUES('adoption','adoption','Adoption')"
933
+ )
934
+ connection.execute(
935
+ "INSERT OR IGNORE INTO articles(id,category_id,slug,title,summary,body,species,status,published_at)"
936
+ " VALUES('article-welcome','adoption','preparing-to-adopt','Preparing to adopt',"
937
+ "'A practical checklist for a thoughtful adoption.',"
938
+ "'Plan time, supplies, veterinary care, and a calm transition before bringing a pet home.',"
939
+ "NULL,'published',?)",
940
+ (FROZEN_CLOCK,),
941
+ )
942
+ for slug, title in (
943
+ ("all-about-pets", "All About Pets"),
944
+ ("new-adopter-checklist", "Checklist for New Adopters"),
945
+ ("dog-human-years", "How Old Is a Dog in Human Years?"),
946
+ ("adoption-faqs", "Pet Adoption FAQs"),
947
+ ("dog-adoption", "Dog Adoption Articles"),
948
+ ("cat-adoption", "Cat Adoption Articles"),
949
+ ):
950
+ connection.execute(
951
+ "INSERT OR IGNORE INTO pet_guides(id,slug,title,summary,body,status,published_at)"
952
+ " VALUES(?,?,?,?,?,'published',?)",
953
+ (f"guide-{slug}", slug, title, f"Practical guidance: {title}.",
954
+ f"This guide provides a practical overview of {title.casefold()}.", FROZEN_CLOCK),
955
+ )
956
+
957
+
958
+ def seed_site_backend(connection: sqlite3.Connection) -> None:
959
+ """Seed only deterministic reference facts for a new runtime database."""
960
+
961
+ if not connection.in_transaction:
962
+ raise RuntimeError("site-backend seed hook requires an active transaction")
963
+ _seed_reference_rows(connection)
964
+
965
+
966
+ def ensure_ready() -> None:
967
+ """Migrate to head and guarantee the frozen seed exists (idempotent).
968
+
969
+ Reference rows (shelters, animals, accounts, ZIP centroids, dated
970
+ facts) are server-owned frozen data, so they are re-asserted on every
971
+ boot; user-owned rows (favorites, profiles, inquiries, sessions) are
972
+ never touched here.
973
+ """
974
+ with connect() as connection:
975
+ apply_migrations(connection)
976
+ _seed_reference_rows(connection)
977
+ connection.commit()
978
+
979
+
980
+ def reset_site_state(connection: sqlite3.Connection) -> dict[str, Any]:
981
+ """Clear Petfinder-owned mutable state inside a caller transaction.
982
+
983
+ The generated auth runtime calls this during its site-isolated reset, so
984
+ Petfinder business rows, generic runtime rows, and local-auth rows either
985
+ reset together or none of them do. Migration history is intentionally
986
+ retained.
987
+ """
988
+ if not connection.in_transaction:
989
+ raise RuntimeError("Petfinder reset requires a caller-owned transaction")
990
+ for table in (
991
+ "support_receipts", "support_checkouts",
992
+ "organization_reviews", "notifications", "messages", "conversations",
993
+ "application_events", "application_answers", "adoption_applications",
994
+ "recommendation_cache", "user_activity", "user_preferences",
995
+ "domain_idempotency_commands",
996
+ "recently_viewed_pets", "search_alerts", "saved_searches",
997
+ "favorite_collection_items", "favorite_collections",
998
+ "organization_staff", "users",
999
+ ):
1000
+ connection.execute(f"DELETE FROM {table}")
1001
+ connection.execute("DELETE FROM business_favorites_command")
1002
+ connection.execute("DELETE FROM business_adopter_profile_inquiry_command")
1003
+ connection.execute("DELETE FROM business_animal_discovery_search_command")
1004
+ connection.execute("DELETE FROM business_favorites_version_journal")
1005
+ connection.execute(
1006
+ "DELETE FROM business_adopter_profile_inquiry_version_journal"
1007
+ )
1008
+ connection.execute("DELETE FROM business_subjects")
1009
+ connection.execute("DELETE FROM favorites")
1010
+ connection.execute("DELETE FROM adopter_profiles")
1011
+ connection.execute("DELETE FROM inquiries")
1012
+ connection.execute("DELETE FROM sessions")
1013
+ connection.execute("DELETE FROM accounts")
1014
+ _seed_reference_rows(connection)
1015
+ return {
1016
+ "animals": connection.execute(
1017
+ "SELECT COUNT(*) AS n FROM animals"
1018
+ ).fetchone()["n"],
1019
+ "shelters": connection.execute(
1020
+ "SELECT COUNT(*) AS n FROM shelters"
1021
+ ).fetchone()["n"],
1022
+ "accounts": connection.execute(
1023
+ "SELECT COUNT(*) AS n FROM accounts"
1024
+ ).fetchone()["n"],
1025
+ "zip_locations": connection.execute(
1026
+ "SELECT COUNT(*) AS n FROM zip_locations"
1027
+ ).fetchone()["n"],
1028
+ "favorites": 0,
1029
+ "adopter_profiles": 0,
1030
+ "inquiries": 0,
1031
+ "sessions": 0,
1032
+ "business_commands": 0,
1033
+ }
1034
+
1035
+
1036
+ def reset_to_seed() -> dict[str, Any]:
1037
+ """Restore the exact frozen seed and clear Petfinder-owned state.
1038
+
1039
+ This standalone helper is used by local tests. Runtime requests use
1040
+ :func:`reset_site_state` through ``LocalAuthStore.reset_site_state`` so
1041
+ the whole site reset is atomic.
1042
+ """
1043
+ with connect() as connection:
1044
+ apply_migrations(connection)
1045
+ connection.execute("BEGIN IMMEDIATE")
1046
+ try:
1047
+ counts = reset_site_state(connection)
1048
+ except BaseException:
1049
+ connection.rollback()
1050
+ raise
1051
+ connection.commit()
1052
+ return counts
1053
+
1054
+
1055
+ def db_info() -> dict[str, Any]:
1056
+ with connect() as connection:
1057
+ journal_mode = connection.execute("PRAGMA journal_mode").fetchone()[0]
1058
+ applied = applied_migrations(connection)
1059
+ return {
1060
+ "engine": "sqlite3",
1061
+ "path": str(database_path()),
1062
+ "journal_mode": journal_mode,
1063
+ "schema_migrations": applied,
1064
+ "head_migration": HEAD_MIGRATION_ID,
1065
+ "at_head": bool(applied and applied[-1] == HEAD_MIGRATION_ID),
1066
+ }
1067
+
1068
+
1069
+ def domain_service():
1070
+ return domain_services.DomainService(connect, FROZEN_CLOCK)
1071
+
1072
+
1073
+ def user_for_subject(subject_id: str) -> dict[str, Any] | None:
1074
+ with connect() as connection:
1075
+ row = connection.execute("SELECT * FROM users WHERE id=?", (subject_id,)).fetchone()
1076
+ return dict(row) if row else None
1077
+
1078
+
1079
+ def saved_searches(user_id: str) -> list[dict[str, Any]]:
1080
+ with connect() as connection:
1081
+ return domain_repositories.PersonalizationRepository(connection).saved_searches(user_id)
1082
+
1083
+
1084
+ def preferences(user_id: str) -> dict[str, Any] | None:
1085
+ with connect() as connection:
1086
+ return domain_repositories.PersonalizationRepository(connection).preferences(user_id)
1087
+
1088
+
1089
+ def applications_for_user(user_id: str) -> list[dict[str, Any]]:
1090
+ with connect() as connection:
1091
+ return domain_repositories.ApplicationRepository(connection).list_for_user(user_id)
1092
+
1093
+
1094
+ def notifications_for_user(user_id: str) -> list[dict[str, Any]]:
1095
+ with connect() as connection:
1096
+ rows = connection.execute(
1097
+ "SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC,id",
1098
+ (user_id,),
1099
+ ).fetchall()
1100
+ return [dict(row) for row in rows]
1101
+
1102
+
1103
+ def recently_viewed(user_id: str) -> list[dict[str, Any]]:
1104
+ with connect() as connection:
1105
+ rows = connection.execute(
1106
+ _ANIMAL_SELECT + " JOIN recently_viewed_pets rv ON rv.animal_id=animals.id"
1107
+ " WHERE rv.user_id=? ORDER BY rv.viewed_at DESC,animals.id",
1108
+ (user_id,),
1109
+ ).fetchall()
1110
+ return [_animal_dict(row) for row in rows]
1111
+
1112
+
1113
+ def record_view(user_id: str, animal_id: str) -> None:
1114
+ with connect() as connection:
1115
+ connection.execute(
1116
+ "INSERT INTO recently_viewed_pets(user_id,animal_id,viewed_at) VALUES(?,?,?)"
1117
+ " ON CONFLICT(user_id,animal_id) DO UPDATE SET viewed_at=excluded.viewed_at",
1118
+ (user_id, animal_id, FROZEN_CLOCK),
1119
+ )
1120
+ connection.execute(
1121
+ "INSERT INTO user_activity(user_id,kind,subject_id,created_at) VALUES(?,?,?,?)",
1122
+ (user_id, "animal-viewed", animal_id, FROZEN_CLOCK),
1123
+ )
1124
+ connection.execute("DELETE FROM recommendation_cache WHERE user_id=?", (user_id,))
1125
+
1126
+
1127
+ # ---------------------------------------------------------------------------
1128
+ # Read models
1129
+ # ---------------------------------------------------------------------------
1130
+
1131
+ _ANIMAL_SELECT = """
1132
+ SELECT animals.*, shelters.name AS shelter_name,
1133
+ animal_status.status AS domain_status,
1134
+ animal_status.version AS status_version,
1135
+ animal_profiles.primary_breed, animal_profiles.secondary_breed,
1136
+ animal_profiles.mixed, animal_profiles.size, animal_profiles.color,
1137
+ animal_profiles.coat, animal_profiles.health,
1138
+ animal_profiles.good_with_children, animal_profiles.good_with_dogs,
1139
+ animal_profiles.good_with_cats, animal_profiles.personality,
1140
+ animal_profiles.description
1141
+ FROM animals JOIN shelters ON shelters.id = animals.shelter_id
1142
+ JOIN animal_status ON animal_status.animal_id = animals.id
1143
+ JOIN animal_profiles ON animal_profiles.animal_id = animals.id
1144
+ """
1145
+
1146
+
1147
+ def _animal_dict(row: sqlite3.Row) -> dict[str, Any]:
1148
+ return {
1149
+ "id": row["id"],
1150
+ "slug": row["slug"],
1151
+ "species": row["species"],
1152
+ "name": row["name"],
1153
+ "breed": row["breed"],
1154
+ "age": row["age"],
1155
+ "sex": row["sex"],
1156
+ "shelter": row["shelter_name"],
1157
+ "distance": row["distance"],
1158
+ "photo": row["photo"],
1159
+ "good_with": row["good_with"],
1160
+ "house_trained": row["house_trained"],
1161
+ "out_of_town": bool(row["out_of_town"]),
1162
+ "adoptable": row["domain_status"] == "AVAILABLE",
1163
+ "status": row["domain_status"],
1164
+ "status_version": int(row["status_version"]),
1165
+ "organization_id": row["organization_id"],
1166
+ "listed_at": row["listed_at"],
1167
+ "size": row["size"],
1168
+ "color": row["color"],
1169
+ "coat": row["coat"],
1170
+ "good_with_children": bool(row["good_with_children"]),
1171
+ "good_with_dogs": bool(row["good_with_dogs"]),
1172
+ "good_with_cats": bool(row["good_with_cats"]),
1173
+ "description": row["description"],
1174
+ }
1175
+
1176
+
1177
+ def list_animals(species: str) -> list[dict[str, Any]]:
1178
+ """Adoptable seed animals for one species in the exact frozen order."""
1179
+ with connect() as connection:
1180
+ rows = connection.execute(
1181
+ _ANIMAL_SELECT
1182
+ + " WHERE animals.species = ? AND animals.position < 99"
1183
+ " ORDER BY animals.position ASC",
1184
+ (species,),
1185
+ ).fetchall()
1186
+ return [_animal_dict(row) for row in rows]
1187
+
1188
+
1189
+ def get_animal(animal_id: str) -> dict[str, Any] | None:
1190
+ with connect() as connection:
1191
+ row = connection.execute(
1192
+ _ANIMAL_SELECT + " WHERE animals.id = ?", (animal_id,)
1193
+ ).fetchone()
1194
+ return _animal_dict(row) if row else None
1195
+
1196
+
1197
+ def get_account(account_id: str) -> dict[str, str] | None:
1198
+ with connect() as connection:
1199
+ row = connection.execute(
1200
+ "SELECT id, name, email, initials FROM accounts WHERE id = ?",
1201
+ (account_id,),
1202
+ ).fetchone()
1203
+ return dict(row) if row else None
1204
+
1205
+
1206
+ def create_account_subject(
1207
+ connection: sqlite3.Connection, registration: dict[str, Any]
1208
+ ) -> str:
1209
+ """Atomically bind a verified local-auth registration to Petfinder state."""
1210
+ account_token = str(registration["account_id"]).rsplit("_", 1)[-1][:20]
1211
+ subject_id = f"petfinder-user-{account_token}"
1212
+ display_name = " ".join(str(registration["display_name"]).split())
1213
+ initials = "".join(part[0] for part in display_name.split()[:2]).upper() or "PF"
1214
+ connection.execute(
1215
+ "INSERT INTO accounts(id,name,email,initials) VALUES (?,?,?,?)",
1216
+ (
1217
+ subject_id,
1218
+ display_name,
1219
+ str(registration["email"]),
1220
+ initials,
1221
+ ),
1222
+ )
1223
+ connection.execute(
1224
+ "INSERT INTO business_subjects(subject_id,account_id,created_at)"
1225
+ " VALUES (?,?,?)",
1226
+ (subject_id, subject_id, FROZEN_CLOCK),
1227
+ )
1228
+ connection.execute(
1229
+ "INSERT INTO users(id,account_id,display_name,email,created_at)"
1230
+ " VALUES(?,?,?,?,?)",
1231
+ (
1232
+ subject_id,
1233
+ str(registration["account_id"]),
1234
+ display_name,
1235
+ str(registration["email"]),
1236
+ FROZEN_CLOCK,
1237
+ ),
1238
+ )
1239
+ connection.execute(
1240
+ "INSERT INTO favorite_collections(id,user_id,name,is_default,created_at)"
1241
+ " VALUES(?,?,?,?,?)",
1242
+ (f"default-{subject_id}", subject_id, "My favorites", 1, FROZEN_CLOCK),
1243
+ )
1244
+ return subject_id
1245
+
1246
+
1247
+ def list_accounts() -> list[dict[str, str]]:
1248
+ with connect() as connection:
1249
+ rows = connection.execute(
1250
+ "SELECT id, name, email, initials FROM accounts ORDER BY id"
1251
+ ).fetchall()
1252
+ return [dict(row) for row in rows]
1253
+
1254
+
1255
+ # ---------------------------------------------------------------------------
1256
+ # Persisted server-side sessions (login state survives process restart)
1257
+ # ---------------------------------------------------------------------------
1258
+
1259
+ def create_session(account_id: str, *, token: str | None = None) -> str:
1260
+ """Persist a site session, optionally sharing an auth-store token.
1261
+
1262
+ The verifier-only login seam authenticates through ``LocalAuthStore`` and
1263
+ mirrors that opaque token into the compatibility session table. Normal
1264
+ callers still receive a freshly generated token.
1265
+ """
1266
+ token = token or secrets.token_urlsafe(32)
1267
+ with connect() as connection:
1268
+ connection.execute(
1269
+ "INSERT INTO sessions (token, account_id, created_at)"
1270
+ " VALUES (?, ?, ?)",
1271
+ (token, account_id, FROZEN_CLOCK),
1272
+ )
1273
+ connection.commit()
1274
+ return token
1275
+
1276
+
1277
+ def session_account_id(token: str | None) -> str | None:
1278
+ if not token:
1279
+ return None
1280
+ with connect() as connection:
1281
+ row = connection.execute(
1282
+ "SELECT account_id FROM sessions WHERE token = ?", (token,)
1283
+ ).fetchone()
1284
+ return row["account_id"] if row else None
1285
+
1286
+
1287
+ def delete_session(token: str | None) -> None:
1288
+ if not token:
1289
+ return
1290
+ with connect() as connection:
1291
+ connection.execute("DELETE FROM sessions WHERE token = ?", (token,))
1292
+ connection.commit()
1293
+
1294
+
1295
+ def session_count() -> int:
1296
+ with connect() as connection:
1297
+ row = connection.execute("SELECT COUNT(*) AS n FROM sessions").fetchone()
1298
+ return int(row["n"])
1299
+
1300
+
1301
+ # ---------------------------------------------------------------------------
1302
+ # Generic ZIP geography + deterministic search ranking
1303
+ # ---------------------------------------------------------------------------
1304
+
1305
+ def is_valid_zip(zip_code: str) -> bool:
1306
+ return bool(re.fullmatch(r"\d{5}", zip_code or ""))
1307
+
1308
+
1309
+ def resolve_location(value: str) -> str | None:
1310
+ """Resolve a ZIP or seeded city/state label without benchmark branches."""
1311
+ normalized = " ".join((value or "").strip().split())
1312
+ zip_match = re.search(r"\b(\d{5})\b", normalized)
1313
+ if zip_match:
1314
+ return zip_match.group(1)
1315
+ if not normalized:
1316
+ return None
1317
+ city = normalized.split(",", 1)[0].strip()
1318
+ state = normalized.split(",", 1)[1].strip().split()[0] if "," in normalized else ""
1319
+ with connect() as connection:
1320
+ row = connection.execute(
1321
+ "SELECT zip_code FROM locations WHERE lower(city)=lower(?) "
1322
+ "AND (?='' OR lower(state_abbr)=lower(?)) ORDER BY zip_code LIMIT 1",
1323
+ (city, state, state),
1324
+ ).fetchone()
1325
+ return str(row["zip_code"]) if row else None
1326
+
1327
+
1328
+ def haversine_miles(
1329
+ lat1: float, lon1: float, lat2: float, lon2: float
1330
+ ) -> float:
1331
+ radius_miles = 3958.8
1332
+ p1, p2 = math.radians(lat1), math.radians(lat2)
1333
+ dp = math.radians(lat2 - lat1)
1334
+ dl = math.radians(lon2 - lon1)
1335
+ a = (
1336
+ math.sin(dp / 2) ** 2
1337
+ + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
1338
+ )
1339
+ return 2 * radius_miles * math.asin(math.sqrt(a))
1340
+
1341
+
1342
+ def locate_zip(zip_code: str) -> dict[str, Any] | None:
1343
+ """Resolve ANY valid 5-digit ZIP to a centroid.
1344
+
1345
+ Generic degradation: exact seed row -> mean of rows sharing the ZIP3
1346
+ prefix -> USPS national-area (leading digit) centroid. Never a
1347
+ special-cased literal comparison against a benchmark constant.
1348
+ """
1349
+ if not is_valid_zip(zip_code):
1350
+ return None
1351
+ with connect() as connection:
1352
+ row = connection.execute(
1353
+ "SELECT * FROM zip_locations WHERE zip_code = ?", (zip_code,)
1354
+ ).fetchone()
1355
+ if row:
1356
+ return {
1357
+ "zip_code": zip_code,
1358
+ "city": row["city"],
1359
+ "state_abbr": row["state_abbr"],
1360
+ "latitude": row["latitude"],
1361
+ "longitude": row["longitude"],
1362
+ "resolution": "exact",
1363
+ }
1364
+ siblings = connection.execute(
1365
+ "SELECT * FROM zip_locations WHERE substr(zip_code, 1, 3) = ?",
1366
+ (zip_code[:3],),
1367
+ ).fetchall()
1368
+ if siblings:
1369
+ return {
1370
+ "zip_code": zip_code,
1371
+ "city": None,
1372
+ "state_abbr": siblings[0]["state_abbr"],
1373
+ "latitude": sum(r["latitude"] for r in siblings) / len(siblings),
1374
+ "longitude": sum(r["longitude"] for r in siblings) / len(siblings),
1375
+ "resolution": "zip3",
1376
+ }
1377
+ latitude, longitude = ZIP1_REGION_CENTROIDS[zip_code[0]]
1378
+ return {
1379
+ "zip_code": zip_code,
1380
+ "city": None,
1381
+ "state_abbr": None,
1382
+ "latitude": latitude,
1383
+ "longitude": longitude,
1384
+ "resolution": "zip1",
1385
+ }
1386
+
1387
+
1388
+ def _distance_label(miles: float) -> str:
1389
+ rounded = int(round(miles))
1390
+ return "1 mile away" if rounded == 1 else f"{rounded} miles away"
1391
+
1392
+
1393
+ def search_animals(species: str, zip_code: str) -> list[dict[str, Any]]:
1394
+ """Deterministic, generic species+ZIP search over the seed rows.
1395
+
1396
+ Eligibility (generic source-site rules, no benchmark constants):
1397
+ - local listings (out_of_town = 0) match when their shelter lies within
1398
+ SEARCH_RADIUS_MILES of the searched ZIP centroid;
1399
+ - transportable listings (out_of_town = 1) match when the searched ZIP
1400
+ lies within the shelter's transport radius (they are delivered to the
1401
+ adopter, so their effective distance is 0).
1402
+
1403
+ Ranking key: (distance bucket of 10 miles ASC, listed_at freshness
1404
+ DESC, animal id ASC as the stable tiebreak).
1405
+ """
1406
+ origin = locate_zip(zip_code)
1407
+ if origin is None:
1408
+ return []
1409
+ with connect() as connection:
1410
+ rows = connection.execute(
1411
+ """
1412
+ SELECT animals.*, shelters.name AS shelter_name,
1413
+ animal_status.status AS domain_status,
1414
+ animal_status.version AS status_version,
1415
+ animal_profiles.primary_breed, animal_profiles.secondary_breed,
1416
+ animal_profiles.mixed, animal_profiles.size, animal_profiles.color,
1417
+ animal_profiles.coat, animal_profiles.health,
1418
+ animal_profiles.good_with_children, animal_profiles.good_with_dogs,
1419
+ animal_profiles.good_with_cats, animal_profiles.personality,
1420
+ animal_profiles.description,
1421
+ shelters.zip_code AS shelter_zip,
1422
+ shelters.transport_radius_miles AS transport_radius
1423
+ FROM animals JOIN shelters ON shelters.id = animals.shelter_id
1424
+ JOIN animal_status ON animal_status.animal_id = animals.id
1425
+ JOIN animal_profiles ON animal_profiles.animal_id = animals.id
1426
+ WHERE animals.species = ? AND animal_status.status = 'AVAILABLE'
1427
+ """,
1428
+ (species,),
1429
+ ).fetchall()
1430
+ results: list[tuple[tuple[int, float, str], dict[str, Any]]] = []
1431
+ for row in rows:
1432
+ shelter_origin = locate_zip(row["shelter_zip"])
1433
+ if shelter_origin is None:
1434
+ continue
1435
+ miles = haversine_miles(
1436
+ origin["latitude"], origin["longitude"],
1437
+ shelter_origin["latitude"], shelter_origin["longitude"],
1438
+ )
1439
+ if row["out_of_town"]:
1440
+ if miles > float(row["transport_radius"]):
1441
+ continue
1442
+ effective_miles = 0.0
1443
+ else:
1444
+ if miles > SEARCH_RADIUS_MILES:
1445
+ continue
1446
+ effective_miles = miles
1447
+ animal = _animal_dict(row)
1448
+ animal["distance"] = _distance_label(effective_miles)
1449
+ bucket = int(effective_miles // 10)
1450
+ freshness = -datetime.fromisoformat(row["listed_at"]).timestamp()
1451
+ results.append(((bucket, freshness, row["id"]), animal))
1452
+ results.sort(key=lambda item: item[0])
1453
+ return [animal for _, animal in results]
1454
+
1455
+
1456
+ def search_animals_filtered(
1457
+ species: str,
1458
+ zip_code: str,
1459
+ *,
1460
+ breed: str = "",
1461
+ age: str = "",
1462
+ gender: str = "",
1463
+ size: str = "",
1464
+ color: str = "",
1465
+ coat_length: str = "",
1466
+ care_behavior: str = "",
1467
+ days_on_petfinder: int | None = None,
1468
+ organization: str = "",
1469
+ pet_name: str = "",
1470
+ good_with_children: bool = False,
1471
+ good_with_dogs: bool = False,
1472
+ good_with_cats: bool = False,
1473
+ radius: int = 100,
1474
+ sort: str = "distance",
1475
+ include_out_of_town: bool = True,
1476
+ ) -> list[dict[str, Any]]:
1477
+ allowed_care = {
1478
+ "",
1479
+ "house-trained",
1480
+ "good-with-children",
1481
+ "good-with-dogs",
1482
+ "good-with-cats",
1483
+ }
1484
+ if (
1485
+ radius < 1
1486
+ or radius > 500
1487
+ or sort not in {"distance", "recently_added", "recommended"}
1488
+ or care_behavior not in allowed_care
1489
+ or (
1490
+ days_on_petfinder is not None
1491
+ and (days_on_petfinder < 1 or days_on_petfinder > 365)
1492
+ )
1493
+ ):
1494
+ raise ValueError("invalid radius or sort")
1495
+ animals = search_animals(species, zip_code)
1496
+
1497
+ def matches_care(animal: dict[str, Any]) -> bool:
1498
+ return {
1499
+ "": True,
1500
+ "house-trained": animal["house_trained"] == "Yes",
1501
+ "good-with-children": bool(animal["good_with_children"]),
1502
+ "good-with-dogs": bool(animal["good_with_dogs"]),
1503
+ "good-with-cats": bool(animal["good_with_cats"]),
1504
+ }[care_behavior]
1505
+
1506
+ def matches(animal: dict[str, Any]) -> bool:
1507
+ distance_match = re.search(r"\d+", str(animal["distance"]))
1508
+ miles = int(distance_match.group()) if distance_match else 0
1509
+ listed_at = datetime.fromisoformat(str(animal["listed_at"]))
1510
+ listing_age_days = max(0, (_FROZEN_DT - listed_at).days)
1511
+ return (
1512
+ miles <= radius
1513
+ and (include_out_of_town or not bool(animal["out_of_town"]))
1514
+ and (not breed or breed.casefold() in str(animal["breed"]).casefold())
1515
+ and (not age or age.casefold() == str(animal["age"]).casefold())
1516
+ and (not gender or gender.casefold() == str(animal["sex"]).casefold())
1517
+ and (not size or size.casefold() == str(animal.get("size") or "").casefold())
1518
+ and (not color or color.casefold() in str(animal.get("color") or "").casefold())
1519
+ and (
1520
+ not coat_length
1521
+ or coat_length.casefold()
1522
+ == str(animal.get("coat") or "").casefold()
1523
+ )
1524
+ and matches_care(animal)
1525
+ and (
1526
+ days_on_petfinder is None
1527
+ or listing_age_days <= days_on_petfinder
1528
+ )
1529
+ and (
1530
+ not organization
1531
+ or organization.casefold()
1532
+ in {
1533
+ str(animal.get("organization_id") or "").casefold(),
1534
+ str(animal.get("shelter") or "").casefold(),
1535
+ }
1536
+ )
1537
+ and (
1538
+ not pet_name
1539
+ or pet_name.casefold() in str(animal["name"]).casefold()
1540
+ )
1541
+ and (not good_with_children or animal["good_with_children"])
1542
+ and (not good_with_dogs or animal["good_with_dogs"])
1543
+ and (not good_with_cats or animal["good_with_cats"])
1544
+ )
1545
+ filtered = [animal for animal in animals if matches(animal)]
1546
+ if sort == "recently_added":
1547
+ with connect() as connection:
1548
+ listed = {row["id"]: row["listed_at"] for row in connection.execute(
1549
+ "SELECT id,listed_at FROM animals"
1550
+ ).fetchall()}
1551
+ filtered.sort(
1552
+ key=lambda item: (
1553
+ -datetime.fromisoformat(listed[item["id"]]).timestamp(),
1554
+ item["id"],
1555
+ )
1556
+ )
1557
+ elif sort == "recommended":
1558
+ with connect() as connection:
1559
+ listed = {row["id"]: row["listed_at"] for row in connection.execute(
1560
+ "SELECT id,listed_at FROM animals"
1561
+ ).fetchall()}
1562
+ filtered.sort(key=lambda item: (
1563
+ -int(item["good_with_children"]) - int(item["good_with_dogs"]) - int(item["good_with_cats"]),
1564
+ -datetime.fromisoformat(listed[item["id"]]).timestamp(),
1565
+ item["id"],
1566
+ ))
1567
+ return filtered
1568
+
1569
+
1570
+ def list_organizations(query: str = "") -> list[dict[str, Any]]:
1571
+ with connect() as connection:
1572
+ rows = connection.execute(
1573
+ "SELECT o.*,COUNT(s.animal_id) AS available_animals FROM organizations o "
1574
+ "LEFT JOIN animals a ON a.organization_id=o.id "
1575
+ "LEFT JOIN animal_status s ON s.animal_id=a.id AND s.status='AVAILABLE' "
1576
+ "WHERE (?='' OR lower(o.name) LIKE '%'||lower(?)||'%') "
1577
+ "GROUP BY o.id ORDER BY o.verified DESC,o.name,o.id",
1578
+ (query, query),
1579
+ ).fetchall()
1580
+ return [dict(row) for row in rows]
1581
+
1582
+
1583
+ def get_organization(organization_id: str) -> dict[str, Any] | None:
1584
+ with connect() as connection:
1585
+ row = connection.execute("SELECT * FROM organizations WHERE id=?", (organization_id,)).fetchone()
1586
+ return dict(row) if row else None
1587
+
1588
+
1589
+ def organization_animals(organization_id: str) -> list[dict[str, Any]]:
1590
+ with connect() as connection:
1591
+ rows = connection.execute(
1592
+ _ANIMAL_SELECT + " WHERE animals.organization_id=? AND animal_status.status='AVAILABLE'"
1593
+ " ORDER BY animals.listed_at DESC,animals.id",
1594
+ (organization_id,),
1595
+ ).fetchall()
1596
+ return [_animal_dict(row) for row in rows]
1597
+
1598
+
1599
+ def get_guide(slug: str) -> dict[str, Any] | None:
1600
+ with connect() as connection:
1601
+ row = connection.execute(
1602
+ "SELECT * FROM pet_guides WHERE slug=? AND status='published'", (slug,)
1603
+ ).fetchone()
1604
+ return dict(row) if row else None
1605
+
1606
+
1607
+ def list_articles() -> list[dict[str, Any]]:
1608
+ with connect() as connection:
1609
+ rows = connection.execute(
1610
+ "SELECT a.*,c.name AS category_name FROM articles a LEFT JOIN article_categories c "
1611
+ "ON c.id=a.category_id WHERE a.status='published' ORDER BY a.published_at DESC,a.id"
1612
+ ).fetchall()
1613
+ return [dict(row) for row in rows]
1614
+
1615
+
1616
+ def get_article(slug: str) -> dict[str, Any] | None:
1617
+ with connect() as connection:
1618
+ row = connection.execute(
1619
+ "SELECT a.*,c.name AS category_name FROM articles a LEFT JOIN article_categories c "
1620
+ "ON c.id=a.category_id WHERE a.slug=? AND a.status='published'", (slug,)
1621
+ ).fetchone()
1622
+ return dict(row) if row else None
1623
+
1624
+
1625
+ def recommendations(user_id: str, limit: int = 8) -> list[dict[str, Any]]:
1626
+ prefs = preferences(user_id) or {}
1627
+ species = prefs.get("species") or "dog"
1628
+ zip_code = prefs.get("location_zip") or "10001"
1629
+ radius = int(prefs.get("radius_miles") or 100)
1630
+ try:
1631
+ candidates = search_animals_filtered(species, zip_code, radius=radius, sort="distance")
1632
+ except ValueError:
1633
+ candidates = []
1634
+ preferred_breeds = str(prefs.get("breeds") or "").casefold()
1635
+ preferred_sizes = str(prefs.get("sizes") or "").casefold()
1636
+ with connect() as connection:
1637
+ recent = {
1638
+ str(row["subject_id"]) for row in connection.execute(
1639
+ "SELECT subject_id FROM user_activity WHERE user_id=? "
1640
+ "AND kind IN('animal-viewed','favorite-added') ORDER BY id DESC LIMIT 50",
1641
+ (user_id,),
1642
+ ).fetchall()
1643
+ }
1644
+ scored: list[tuple[float, str, dict[str, Any], list[str]]] = []
1645
+ for animal in candidates:
1646
+ match = re.search(r"\d+", str(animal["distance"]))
1647
+ miles = int(match.group()) if match else 0
1648
+ score = 30.0 + max(0.0, 20.0 - miles / max(1, radius) * 20.0)
1649
+ reasons = ["preferred species", "within preferred distance"]
1650
+ if preferred_breeds and str(animal["breed"]).casefold() in preferred_breeds:
1651
+ score += 25.0
1652
+ reasons.append("preferred breed")
1653
+ if preferred_sizes and str(animal.get("size") or "").casefold() in preferred_sizes:
1654
+ score += 15.0
1655
+ reasons.append("preferred size")
1656
+ if animal["id"] in recent:
1657
+ score += 10.0
1658
+ reasons.append("recent activity")
1659
+ scored.append((-score, animal["id"], animal, reasons))
1660
+ scored.sort(key=lambda item: (item[0], item[1]))
1661
+ connection.execute("DELETE FROM recommendation_cache WHERE user_id=?", (user_id,))
1662
+ for negative, _, animal, reasons in scored:
1663
+ connection.execute(
1664
+ "INSERT INTO recommendation_cache(user_id,animal_id,score,reasons_json,generated_at)"
1665
+ " VALUES(?,?,?,?,?)",
1666
+ (user_id, animal["id"], -negative, json.dumps(reasons), FROZEN_CLOCK),
1667
+ )
1668
+ result: list[dict[str, Any]] = []
1669
+ for negative, _, animal, reasons in scored[:limit]:
1670
+ result.append({**animal, "recommendation_score": -negative, "recommendation_reasons": reasons})
1671
+ return result
1672
+
1673
+
1674
+ def conversations_for_user(user_id: str) -> list[dict[str, Any]]:
1675
+ with connect() as connection:
1676
+ return domain_repositories.MessagingRepository(connection).conversations(user_id)
1677
+
1678
+
1679
+ def search_count_fact(species: str, zip_code: str) -> dict[str, str] | None:
1680
+ """Point-in-time observed result-count fact for this exact query, if
1681
+ one was captured; searches without a captured fact return None and the
1682
+ UI renders only the honest local count."""
1683
+ with connect() as connection:
1684
+ row = connection.execute(
1685
+ "SELECT result_count_fact, observed_on FROM search_count_facts"
1686
+ " WHERE species = ? AND zip_code = ?",
1687
+ (species, zip_code),
1688
+ ).fetchone()
1689
+ return dict(row) if row else None
1690
+
1691
+
1692
+ def search_location_label(zip_code: str) -> str:
1693
+ origin = locate_zip(zip_code)
1694
+ if origin and origin.get("city"):
1695
+ return f"{origin['city']}, {origin['state_abbr']} {zip_code}"
1696
+ return f"ZIP {zip_code} area"
1697
+
1698
+
1699
+ def search_area_label(zip_code: str) -> str:
1700
+ """City/state heading label ('New York, NY'); honest ZIP-area fallback
1701
+ for ZIPs whose city name is not in the seed geography."""
1702
+ origin = locate_zip(zip_code)
1703
+ if origin and origin.get("city"):
1704
+ return f"{origin['city']}, {origin['state_abbr']}"
1705
+ return f"ZIP {zip_code} area"
1706
+
1707
+
1708
+ def search_state_segment(zip_code: str) -> str:
1709
+ origin = locate_zip(zip_code)
1710
+ if origin and origin.get("state_abbr"):
1711
+ return str(origin["state_abbr"]).casefold()
1712
+ return ZIP1_STATE_SEGMENTS[zip_code[0]]
1713
+
1714
+
1715
+ # ---------------------------------------------------------------------------
1716
+ # Favorites (server-owned; idempotent per (account, animal))
1717
+ # ---------------------------------------------------------------------------
1718
+
1719
+ def add_favorite(account_id: str, animal_id: str) -> bool:
1720
+ """Idempotent add; returns True when a new row was created."""
1721
+ with connect() as connection:
1722
+ cursor = connection.execute(
1723
+ "INSERT OR IGNORE INTO favorites (account_id, animal_id, created_at) "
1724
+ "VALUES (?, ?, ?)",
1725
+ (account_id, animal_id, FROZEN_CLOCK),
1726
+ )
1727
+ if cursor.rowcount > 0:
1728
+ _sync_default_collection(connection, account_id, animal_id, add=True)
1729
+ connection.commit()
1730
+ return cursor.rowcount > 0
1731
+
1732
+
1733
+ def remove_favorite(account_id: str, animal_id: str) -> bool:
1734
+ """Idempotent remove (row deletion); returns True when a row was deleted."""
1735
+ with connect() as connection:
1736
+ cursor = connection.execute(
1737
+ "DELETE FROM favorites WHERE account_id = ? AND animal_id = ?",
1738
+ (account_id, animal_id),
1739
+ )
1740
+ if cursor.rowcount > 0:
1741
+ _sync_default_collection(connection, account_id, animal_id, add=False)
1742
+ connection.commit()
1743
+ return cursor.rowcount > 0
1744
+
1745
+
1746
+ def is_favorited(account_id: str, animal_id: str) -> bool:
1747
+ with connect() as connection:
1748
+ row = connection.execute(
1749
+ "SELECT 1 FROM favorites WHERE account_id = ? AND animal_id = ?",
1750
+ (account_id, animal_id),
1751
+ ).fetchone()
1752
+ return row is not None
1753
+
1754
+
1755
+ def favorite_ids(account_id: str) -> list[str]:
1756
+ with connect() as connection:
1757
+ rows = connection.execute(
1758
+ "SELECT animal_id FROM favorites WHERE account_id = ? ORDER BY rowid",
1759
+ (account_id,),
1760
+ ).fetchall()
1761
+ return [row["animal_id"] for row in rows]
1762
+
1763
+
1764
+ def favorite_count(account_id: str) -> int:
1765
+ with connect() as connection:
1766
+ row = connection.execute(
1767
+ "SELECT COUNT(*) AS n FROM favorites WHERE account_id = ?",
1768
+ (account_id,),
1769
+ ).fetchone()
1770
+ return int(row["n"])
1771
+
1772
+
1773
+ def favorite_animals(account_id: str) -> list[dict[str, Any]]:
1774
+ with connect() as connection:
1775
+ rows = connection.execute(
1776
+ _ANIMAL_SELECT
1777
+ + " JOIN favorites ON favorites.animal_id = animals.id"
1778
+ " WHERE favorites.account_id = ? ORDER BY favorites.rowid",
1779
+ (account_id,),
1780
+ ).fetchall()
1781
+ return [_animal_dict(row) for row in rows]
1782
+
1783
+
1784
+ def _canonical_payload(payload: dict[str, Any]) -> tuple[str, str]:
1785
+ rendered = json.dumps(
1786
+ payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
1787
+ )
1788
+ return rendered, hashlib.sha256(rendered.encode("utf-8")).hexdigest()
1789
+
1790
+
1791
+ def _sync_default_collection(
1792
+ connection: sqlite3.Connection, account_id: str, animal_id: str, *, add: bool
1793
+ ) -> None:
1794
+ collection = connection.execute(
1795
+ "SELECT id FROM favorite_collections WHERE user_id=? AND is_default=1",
1796
+ (account_id,),
1797
+ ).fetchone()
1798
+ if collection is None:
1799
+ return
1800
+ if add:
1801
+ connection.execute(
1802
+ "INSERT OR IGNORE INTO favorite_collection_items(collection_id,animal_id,created_at)"
1803
+ " VALUES(?,?,?)",
1804
+ (collection["id"], animal_id, FROZEN_CLOCK),
1805
+ )
1806
+ else:
1807
+ connection.execute(
1808
+ "DELETE FROM favorite_collection_items WHERE collection_id=? AND animal_id=?",
1809
+ (collection["id"], animal_id),
1810
+ )
1811
+ connection.execute(
1812
+ "INSERT INTO user_activity(user_id,kind,subject_id,created_at) VALUES(?,?,?,?)",
1813
+ (account_id, "favorite-added" if add else "favorite-removed", animal_id, FROZEN_CLOCK),
1814
+ )
1815
+ connection.execute("DELETE FROM recommendation_cache WHERE user_id=?", (account_id,))
1816
+
1817
+
1818
+ def favorite_state(account_id: str) -> dict[str, Any]:
1819
+ with connect() as connection:
1820
+ version_row = connection.execute(
1821
+ "SELECT version FROM business_favorites_version_journal"
1822
+ " WHERE account_id=?",
1823
+ (account_id,),
1824
+ ).fetchone()
1825
+ ids = [
1826
+ str(row["animal_id"])
1827
+ for row in connection.execute(
1828
+ "SELECT animal_id FROM favorites WHERE account_id=?"
1829
+ " ORDER BY rowid",
1830
+ (account_id,),
1831
+ )
1832
+ ]
1833
+ return {
1834
+ "version": int(version_row["version"]) if version_row else 0,
1835
+ "animal_ids": ids,
1836
+ }
1837
+
1838
+
1839
+ def mutate_favorite(
1840
+ account_id: str,
1841
+ animal_id: str,
1842
+ *,
1843
+ action: str,
1844
+ expected_version: int,
1845
+ idempotency_key: str,
1846
+ ) -> dict[str, Any]:
1847
+ """Apply one owner-scoped favorite command with replay and OCC safety."""
1848
+ if action not in {"add", "remove"}:
1849
+ raise ValueError("favorite action must be add or remove")
1850
+ if not 8 <= len(idempotency_key) <= 160:
1851
+ raise ValueError("idempotency key must contain 8 to 160 characters")
1852
+ payload = {
1853
+ "action": action,
1854
+ "animal_id": animal_id,
1855
+ "expected_version": expected_version,
1856
+ }
1857
+ _, payload_sha256 = _canonical_payload(payload)
1858
+ with connect() as connection:
1859
+ connection.execute("BEGIN IMMEDIATE")
1860
+ try:
1861
+ account = connection.execute(
1862
+ "SELECT 1 FROM accounts WHERE id=?", (account_id,)
1863
+ ).fetchone()
1864
+ if account is None:
1865
+ raise PermissionError("account does not exist")
1866
+ animal = connection.execute(
1867
+ "SELECT status FROM animal_status WHERE animal_id=?", (animal_id,)
1868
+ ).fetchone()
1869
+ if animal is None:
1870
+ raise LookupError("animal does not exist")
1871
+ if animal["status"] != "AVAILABLE":
1872
+ raise StaleVersionError("animal is no longer adoptable")
1873
+ prior = connection.execute(
1874
+ "SELECT payload_sha256,result_json"
1875
+ " FROM business_favorites_command"
1876
+ " WHERE account_id=? AND idempotency_key=?",
1877
+ (account_id, idempotency_key),
1878
+ ).fetchone()
1879
+ if prior is not None:
1880
+ if prior["payload_sha256"] != payload_sha256:
1881
+ raise IdempotencyConflict(
1882
+ "idempotency key belongs to another payload"
1883
+ )
1884
+ result = json.loads(str(prior["result_json"]))
1885
+ connection.commit()
1886
+ return result
1887
+ version_row = connection.execute(
1888
+ "SELECT version FROM business_favorites_version_journal"
1889
+ " WHERE account_id=?",
1890
+ (account_id,),
1891
+ ).fetchone()
1892
+ current_version = int(version_row["version"]) if version_row else 0
1893
+ if int(expected_version) != current_version:
1894
+ raise StaleVersionError(
1895
+ f"favorite version is {current_version}, not {expected_version}"
1896
+ )
1897
+ present = connection.execute(
1898
+ "SELECT 1 FROM favorites WHERE account_id=? AND animal_id=?",
1899
+ (account_id, animal_id),
1900
+ ).fetchone() is not None
1901
+ changed = (action == "add" and not present) or (
1902
+ action == "remove" and present
1903
+ )
1904
+ if action == "add":
1905
+ connection.execute(
1906
+ "INSERT OR IGNORE INTO favorites"
1907
+ "(account_id,animal_id,created_at) VALUES (?,?,?)",
1908
+ (account_id, animal_id, FROZEN_CLOCK),
1909
+ )
1910
+ else:
1911
+ connection.execute(
1912
+ "DELETE FROM favorites WHERE account_id=? AND animal_id=?",
1913
+ (account_id, animal_id),
1914
+ )
1915
+ if changed:
1916
+ _sync_default_collection(
1917
+ connection, account_id, animal_id, add=(action == "add")
1918
+ )
1919
+ new_version = current_version + (1 if changed else 0)
1920
+ connection.execute(
1921
+ "INSERT INTO business_favorites_version_journal"
1922
+ "(account_id,version) VALUES (?,?)"
1923
+ " ON CONFLICT(account_id) DO UPDATE SET version=excluded.version",
1924
+ (account_id, new_version),
1925
+ )
1926
+ result = {
1927
+ "account_id": account_id,
1928
+ "animal_id": animal_id,
1929
+ "action": action,
1930
+ "changed": changed,
1931
+ "version": new_version,
1932
+ }
1933
+ connection.execute(
1934
+ "INSERT INTO business_favorites_command"
1935
+ "(account_id,idempotency_key,payload_sha256,expected_version,"
1936
+ "result_json,created_at) VALUES (?,?,?,?,?,?)",
1937
+ (
1938
+ account_id,
1939
+ idempotency_key,
1940
+ payload_sha256,
1941
+ expected_version,
1942
+ json.dumps(result, sort_keys=True, separators=(",", ":")),
1943
+ FROZEN_CLOCK,
1944
+ ),
1945
+ )
1946
+ connection.commit()
1947
+ return result
1948
+ except BaseException:
1949
+ connection.rollback()
1950
+ raise
1951
+
1952
+
1953
+ # ---------------------------------------------------------------------------
1954
+ # Adopter profiles + inquiries (one profile per account scope)
1955
+ # ---------------------------------------------------------------------------
1956
+
1957
+ def inquiry_binding(animal_id: str) -> dict[str, Any]:
1958
+ if animal_id.startswith("771"):
1959
+ fixture = "dog-10001"
1960
+ elif animal_id.startswith("779"):
1961
+ fixture = "cat-90210"
1962
+ else:
1963
+ fixture = "unknown"
1964
+ return {
1965
+ "listing_owner_id": f"listing-owner.local.{fixture}",
1966
+ "listing_owner_version": 1,
1967
+ "intended_recipient_id": f"recipient.unavailable.{fixture}",
1968
+ }
1969
+
1970
+
1971
+ def get_profile(account_id: str) -> dict[str, Any] | None:
1972
+ with connect() as connection:
1973
+ row = connection.execute(
1974
+ "SELECT * FROM adopter_profiles WHERE account_id = ?",
1975
+ (account_id,),
1976
+ ).fetchone()
1977
+ return dict(row) if row else None
1978
+
1979
+
1980
+ def create_profile_and_inquiry(
1981
+ account_id: str, animal_id: str, fields: dict[str, str]
1982
+ ) -> dict[str, Any] | None:
1983
+ """Create the adopter profile and its bound inquiry draft atomically.
1984
+
1985
+ Returns None when a profile already exists for the account scope
1986
+ (duplicate submissions never create a second profile or draft).
1987
+ """
1988
+ inquiry_id = f"pf-inquiry-{account_id}-{animal_id}"
1989
+ binding = inquiry_binding(animal_id)
1990
+ with connect() as connection:
1991
+ existing = connection.execute(
1992
+ "SELECT 1 FROM adopter_profiles WHERE account_id = ?",
1993
+ (account_id,),
1994
+ ).fetchone()
1995
+ if existing is not None:
1996
+ return None
1997
+ connection.execute(
1998
+ "INSERT INTO adopter_profiles (account_id, full_name, email, phone,"
1999
+ " zip_code, housing, animal_id, inquiry_id, created_at)"
2000
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
2001
+ (
2002
+ account_id,
2003
+ fields["full_name"],
2004
+ fields["email"],
2005
+ fields["phone"],
2006
+ fields["zip_code"],
2007
+ fields["housing"],
2008
+ animal_id,
2009
+ inquiry_id,
2010
+ FROZEN_CLOCK,
2011
+ ),
2012
+ )
2013
+ connection.execute(
2014
+ "INSERT INTO inquiries(id,account_id,animal_id,created_at,status,"
2015
+ "listing_owner_id,listing_owner_version,intended_recipient_id)"
2016
+ " VALUES (?, ?, ?, ?, 'draft', ?, ?, ?)",
2017
+ (
2018
+ inquiry_id,
2019
+ account_id,
2020
+ animal_id,
2021
+ FROZEN_CLOCK,
2022
+ binding["listing_owner_id"],
2023
+ binding["listing_owner_version"],
2024
+ binding["intended_recipient_id"],
2025
+ ),
2026
+ )
2027
+ connection.commit()
2028
+ return {"inquiry_id": inquiry_id, **binding}
2029
+
2030
+
2031
+ def profile_inquiry_state(account_id: str) -> dict[str, Any]:
2032
+ with connect() as connection:
2033
+ profile = connection.execute(
2034
+ "SELECT * FROM adopter_profiles WHERE account_id=?", (account_id,)
2035
+ ).fetchone()
2036
+ version_row = connection.execute(
2037
+ "SELECT version"
2038
+ " FROM business_adopter_profile_inquiry_version_journal"
2039
+ " WHERE account_id=?",
2040
+ (account_id,),
2041
+ ).fetchone()
2042
+ return {
2043
+ "version": int(version_row["version"]) if version_row else 0,
2044
+ "profile": dict(profile) if profile else None,
2045
+ }
2046
+
2047
+
2048
+ def create_profile_and_inquiry_authoritative(
2049
+ account_id: str,
2050
+ animal_id: str,
2051
+ fields: dict[str, str],
2052
+ *,
2053
+ expected_version: int,
2054
+ idempotency_key: str,
2055
+ ) -> dict[str, Any]:
2056
+ """Create one local inquiry draft atomically with owner/version authority."""
2057
+ if not 8 <= len(idempotency_key) <= 160:
2058
+ raise ValueError("idempotency key must contain 8 to 160 characters")
2059
+ canonical_fields = {
2060
+ key: " ".join(str(fields[key]).split())
2061
+ for key in ("full_name", "email", "phone", "zip_code", "housing")
2062
+ }
2063
+ payload = {
2064
+ "animal_id": animal_id,
2065
+ "expected_version": int(expected_version),
2066
+ "fields": canonical_fields,
2067
+ }
2068
+ _, payload_sha256 = _canonical_payload(payload)
2069
+ inquiry_id = f"pf-inquiry-{account_id}-{animal_id}"
2070
+ binding = inquiry_binding(animal_id)
2071
+ with connect() as connection:
2072
+ connection.execute("BEGIN IMMEDIATE")
2073
+ try:
2074
+ if connection.execute(
2075
+ "SELECT 1 FROM accounts WHERE id=?", (account_id,)
2076
+ ).fetchone() is None:
2077
+ raise PermissionError("account does not exist")
2078
+ animal = connection.execute(
2079
+ "SELECT adoptable FROM animals WHERE id=?", (animal_id,)
2080
+ ).fetchone()
2081
+ if animal is None:
2082
+ raise LookupError("animal does not exist")
2083
+ if not bool(animal["adoptable"]):
2084
+ raise StaleVersionError("animal is no longer adoptable")
2085
+ prior = connection.execute(
2086
+ "SELECT payload_sha256,result_json"
2087
+ " FROM business_adopter_profile_inquiry_command"
2088
+ " WHERE account_id=? AND idempotency_key=?",
2089
+ (account_id, idempotency_key),
2090
+ ).fetchone()
2091
+ if prior is not None:
2092
+ if prior["payload_sha256"] != payload_sha256:
2093
+ raise IdempotencyConflict(
2094
+ "idempotency key belongs to another payload"
2095
+ )
2096
+ result = json.loads(str(prior["result_json"]))
2097
+ connection.commit()
2098
+ return result
2099
+ version_row = connection.execute(
2100
+ "SELECT version"
2101
+ " FROM business_adopter_profile_inquiry_version_journal"
2102
+ " WHERE account_id=?",
2103
+ (account_id,),
2104
+ ).fetchone()
2105
+ current_version = int(version_row["version"]) if version_row else 0
2106
+ if int(expected_version) != current_version:
2107
+ raise StaleVersionError(
2108
+ f"profile version is {current_version}, not {expected_version}"
2109
+ )
2110
+ if connection.execute(
2111
+ "SELECT 1 FROM adopter_profiles WHERE account_id=?",
2112
+ (account_id,),
2113
+ ).fetchone() is not None:
2114
+ raise StaleVersionError("adopter profile already exists")
2115
+ connection.execute(
2116
+ "INSERT INTO adopter_profiles(account_id,full_name,email,phone,"
2117
+ "zip_code,housing,animal_id,inquiry_id,created_at)"
2118
+ " VALUES (?,?,?,?,?,?,?,?,?)",
2119
+ (
2120
+ account_id,
2121
+ canonical_fields["full_name"],
2122
+ canonical_fields["email"],
2123
+ canonical_fields["phone"],
2124
+ canonical_fields["zip_code"],
2125
+ canonical_fields["housing"],
2126
+ animal_id,
2127
+ inquiry_id,
2128
+ FROZEN_CLOCK,
2129
+ ),
2130
+ )
2131
+ connection.execute(
2132
+ "INSERT INTO inquiries(id,account_id,animal_id,created_at,status,"
2133
+ "listing_owner_id,listing_owner_version,intended_recipient_id)"
2134
+ " VALUES (?,?,?,?, 'draft',?,?,?)",
2135
+ (
2136
+ inquiry_id,
2137
+ account_id,
2138
+ animal_id,
2139
+ FROZEN_CLOCK,
2140
+ binding["listing_owner_id"],
2141
+ binding["listing_owner_version"],
2142
+ binding["intended_recipient_id"],
2143
+ ),
2144
+ )
2145
+ new_version = current_version + 1
2146
+ connection.execute(
2147
+ "INSERT INTO business_adopter_profile_inquiry_version_journal"
2148
+ "(account_id,version) VALUES (?,?)",
2149
+ (account_id, new_version),
2150
+ )
2151
+ result = {
2152
+ "account_id": account_id,
2153
+ "animal_id": animal_id,
2154
+ "inquiry_id": inquiry_id,
2155
+ "status": "draft",
2156
+ "version": new_version,
2157
+ **binding,
2158
+ "production_remote_request_count": 0,
2159
+ "production_remote_effect_count": 0,
2160
+ }
2161
+ connection.execute(
2162
+ "INSERT INTO business_adopter_profile_inquiry_command"
2163
+ "(account_id,idempotency_key,payload_sha256,expected_version,"
2164
+ "result_json,created_at) VALUES (?,?,?,?,?,?)",
2165
+ (
2166
+ account_id,
2167
+ idempotency_key,
2168
+ payload_sha256,
2169
+ expected_version,
2170
+ json.dumps(result, sort_keys=True, separators=(",", ":")),
2171
+ FROZEN_CLOCK,
2172
+ ),
2173
+ )
2174
+ connection.commit()
2175
+ return result
2176
+ except BaseException:
2177
+ connection.rollback()
2178
+ raise
2179
+
2180
+
2181
+ def get_inquiry(inquiry_id: str) -> dict[str, Any] | None:
2182
+ with connect() as connection:
2183
+ row = connection.execute(
2184
+ "SELECT * FROM inquiries WHERE id = ?", (inquiry_id,)
2185
+ ).fetchone()
2186
+ return dict(row) if row else None
2187
+
2188
+
2189
+ def inquiry_count() -> int:
2190
+ with connect() as connection:
2191
+ row = connection.execute("SELECT COUNT(*) AS n FROM inquiries").fetchone()
2192
+ return int(row["n"])
2193
+
2194
+
2195
+ def profile_count() -> int:
2196
+ with connect() as connection:
2197
+ row = connection.execute(
2198
+ "SELECT COUNT(*) AS n FROM adopter_profiles"
2199
+ ).fetchone()
2200
+ return int(row["n"])
tasks/petfinder/solution/site/implementation/clone/backend/migrations.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Forward-only Petfinder domain migrations.
2
+
3
+ These migrations are additive so an R3 database can be upgraded in place. The
4
+ legacy tables remain compatibility projections; domain code treats the tables
5
+ below as authoritative for identity, availability, workflow, and ownership.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sqlite3
11
+
12
+
13
+ def execute_sql_script(connection: sqlite3.Connection, script: str) -> None:
14
+ """Execute a migration script without ``executescript`` implicit commits.
15
+
16
+ WebsiteBench invokes site migration hooks inside its own transaction. The
17
+ standard sqlite ``executescript`` helper commits any active transaction,
18
+ so migration statements are applied one complete statement at a time.
19
+ """
20
+
21
+ pending = ""
22
+ for line in script.splitlines(keepends=True):
23
+ pending += line
24
+ if sqlite3.complete_statement(pending):
25
+ statement = pending.strip()
26
+ if statement:
27
+ connection.execute(statement)
28
+ pending = ""
29
+ if pending.strip():
30
+ raise ValueError("migration SQL ended with an incomplete statement")
31
+
32
+
33
+ def identity_organization_animal_search(connection: sqlite3.Connection) -> None:
34
+ execute_sql_script(
35
+ connection,
36
+ """
37
+ ALTER TABLE animals ADD COLUMN organization_id TEXT;
38
+ CREATE TABLE users (
39
+ id TEXT PRIMARY KEY,
40
+ account_id TEXT NOT NULL UNIQUE,
41
+ display_name TEXT NOT NULL,
42
+ email TEXT NOT NULL,
43
+ created_at TEXT NOT NULL,
44
+ version INTEGER NOT NULL DEFAULT 0 CHECK(version >= 0)
45
+ );
46
+ CREATE TABLE organizations (
47
+ id TEXT PRIMARY KEY,
48
+ name TEXT NOT NULL UNIQUE,
49
+ logo TEXT,
50
+ description TEXT NOT NULL DEFAULT '',
51
+ mission TEXT NOT NULL DEFAULT '',
52
+ website TEXT,
53
+ phone TEXT,
54
+ email TEXT,
55
+ address_line1 TEXT,
56
+ city TEXT,
57
+ state_abbr TEXT,
58
+ zip_code TEXT,
59
+ verified INTEGER NOT NULL DEFAULT 0 CHECK(verified IN (0,1)),
60
+ response_rate INTEGER CHECK(response_rate BETWEEN 0 AND 100),
61
+ response_time_hours INTEGER CHECK(response_time_hours >= 0),
62
+ version INTEGER NOT NULL DEFAULT 0 CHECK(version >= 0)
63
+ );
64
+ CREATE TABLE organization_staff (
65
+ organization_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
66
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
67
+ role TEXT NOT NULL CHECK(role IN ('OWNER','ADMIN','STAFF')),
68
+ created_at TEXT NOT NULL,
69
+ PRIMARY KEY(organization_id, user_id)
70
+ );
71
+ CREATE TABLE animal_profiles (
72
+ animal_id TEXT PRIMARY KEY REFERENCES animals(id) ON DELETE CASCADE,
73
+ primary_breed TEXT NOT NULL,
74
+ secondary_breed TEXT,
75
+ mixed INTEGER NOT NULL DEFAULT 0 CHECK(mixed IN (0,1)),
76
+ age TEXT NOT NULL,
77
+ gender TEXT NOT NULL,
78
+ size TEXT,
79
+ color TEXT,
80
+ coat TEXT,
81
+ health TEXT NOT NULL DEFAULT '',
82
+ house_trained INTEGER,
83
+ good_with_children INTEGER,
84
+ good_with_dogs INTEGER,
85
+ good_with_cats INTEGER,
86
+ personality TEXT NOT NULL DEFAULT '',
87
+ description TEXT NOT NULL DEFAULT ''
88
+ );
89
+ CREATE TABLE animal_status (
90
+ animal_id TEXT PRIMARY KEY REFERENCES animals(id) ON DELETE CASCADE,
91
+ status TEXT NOT NULL CHECK(status IN ('AVAILABLE','INTERESTED','PENDING','ADOPTED','FOUND','REMOVED')),
92
+ version INTEGER NOT NULL DEFAULT 0 CHECK(version >= 0),
93
+ updated_at TEXT NOT NULL
94
+ );
95
+ CREATE TABLE animal_status_events (
96
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
97
+ animal_id TEXT NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
98
+ old_status TEXT CHECK(old_status IS NULL OR old_status IN ('AVAILABLE','INTERESTED','PENDING','ADOPTED','FOUND','REMOVED')),
99
+ new_status TEXT NOT NULL CHECK(new_status IN ('AVAILABLE','INTERESTED','PENDING','ADOPTED','FOUND','REMOVED')),
100
+ actor_user_id TEXT REFERENCES users(id),
101
+ created_at TEXT NOT NULL,
102
+ reason TEXT NOT NULL DEFAULT '',
103
+ idempotency_key TEXT NOT NULL,
104
+ UNIQUE(animal_id, idempotency_key)
105
+ );
106
+ CREATE TABLE locations (
107
+ zip_code TEXT PRIMARY KEY,
108
+ city TEXT NOT NULL,
109
+ state_abbr TEXT NOT NULL,
110
+ latitude REAL NOT NULL,
111
+ longitude REAL NOT NULL
112
+ );
113
+ CREATE TABLE pet_search_documents (
114
+ animal_id TEXT PRIMARY KEY REFERENCES animals(id) ON DELETE CASCADE,
115
+ keywords TEXT NOT NULL,
116
+ species TEXT NOT NULL,
117
+ breed TEXT NOT NULL,
118
+ location_zip TEXT NOT NULL REFERENCES locations(zip_code),
119
+ traits TEXT NOT NULL DEFAULT '',
120
+ availability TEXT NOT NULL,
121
+ indexed_at TEXT NOT NULL
122
+ );
123
+ CREATE INDEX idx_pet_search_facets ON pet_search_documents(species, breed, availability);
124
+ CREATE INDEX idx_animal_status_value ON animal_status(status, animal_id);
125
+ """
126
+ )
127
+
128
+
129
+ def personalization_content(connection: sqlite3.Connection) -> None:
130
+ execute_sql_script(
131
+ connection,
132
+ """
133
+ ALTER TABLE favorites ADD COLUMN source TEXT NOT NULL DEFAULT 'profile';
134
+ ALTER TABLE favorites ADD COLUMN last_viewed TEXT;
135
+ CREATE TABLE favorite_collections (
136
+ id TEXT PRIMARY KEY,
137
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
138
+ name TEXT NOT NULL,
139
+ is_default INTEGER NOT NULL DEFAULT 0 CHECK(is_default IN (0,1)),
140
+ created_at TEXT NOT NULL,
141
+ version INTEGER NOT NULL DEFAULT 0,
142
+ UNIQUE(user_id, name)
143
+ );
144
+ CREATE UNIQUE INDEX idx_favorite_default ON favorite_collections(user_id) WHERE is_default=1;
145
+ CREATE TABLE favorite_collection_items (
146
+ collection_id TEXT NOT NULL REFERENCES favorite_collections(id) ON DELETE CASCADE,
147
+ animal_id TEXT NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
148
+ created_at TEXT NOT NULL,
149
+ PRIMARY KEY(collection_id, animal_id)
150
+ );
151
+ CREATE TABLE saved_searches (
152
+ id TEXT PRIMARY KEY,
153
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
154
+ name TEXT NOT NULL,
155
+ query_json TEXT NOT NULL,
156
+ created_at TEXT NOT NULL,
157
+ updated_at TEXT NOT NULL,
158
+ version INTEGER NOT NULL DEFAULT 0,
159
+ UNIQUE(user_id, name)
160
+ );
161
+ CREATE TABLE search_alerts (
162
+ id TEXT PRIMARY KEY,
163
+ saved_search_id TEXT NOT NULL UNIQUE REFERENCES saved_searches(id) ON DELETE CASCADE,
164
+ enabled INTEGER NOT NULL DEFAULT 1 CHECK(enabled IN (0,1)),
165
+ last_evaluated_at TEXT
166
+ );
167
+ CREATE TABLE recently_viewed_pets (
168
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
169
+ animal_id TEXT NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
170
+ viewed_at TEXT NOT NULL,
171
+ PRIMARY KEY(user_id, animal_id)
172
+ );
173
+ CREATE TABLE user_preferences (
174
+ user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
175
+ species TEXT,
176
+ breeds TEXT NOT NULL DEFAULT '',
177
+ sizes TEXT NOT NULL DEFAULT '',
178
+ location_zip TEXT,
179
+ radius_miles INTEGER NOT NULL DEFAULT 100 CHECK(radius_miles BETWEEN 1 AND 500),
180
+ email_alerts INTEGER NOT NULL DEFAULT 0 CHECK(email_alerts IN (0,1)),
181
+ version INTEGER NOT NULL DEFAULT 0,
182
+ updated_at TEXT NOT NULL
183
+ );
184
+ CREATE TABLE user_activity (
185
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
186
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
187
+ kind TEXT NOT NULL,
188
+ subject_id TEXT NOT NULL,
189
+ metadata_json TEXT NOT NULL DEFAULT '{}',
190
+ created_at TEXT NOT NULL
191
+ );
192
+ CREATE TABLE recommendation_cache (
193
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
194
+ animal_id TEXT NOT NULL REFERENCES animals(id) ON DELETE CASCADE,
195
+ score REAL NOT NULL,
196
+ reasons_json TEXT NOT NULL,
197
+ generated_at TEXT NOT NULL,
198
+ PRIMARY KEY(user_id, animal_id)
199
+ );
200
+ CREATE TABLE domain_idempotency_commands (
201
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
202
+ command_kind TEXT NOT NULL,
203
+ idempotency_key TEXT NOT NULL,
204
+ payload_sha256 TEXT NOT NULL,
205
+ result_json TEXT NOT NULL,
206
+ created_at TEXT NOT NULL,
207
+ PRIMARY KEY(user_id, command_kind, idempotency_key)
208
+ );
209
+ CREATE TABLE article_categories (
210
+ id TEXT PRIMARY KEY,
211
+ slug TEXT NOT NULL UNIQUE,
212
+ name TEXT NOT NULL
213
+ );
214
+ CREATE TABLE articles (
215
+ id TEXT PRIMARY KEY,
216
+ category_id TEXT REFERENCES article_categories(id),
217
+ slug TEXT NOT NULL UNIQUE,
218
+ title TEXT NOT NULL,
219
+ summary TEXT NOT NULL,
220
+ body TEXT NOT NULL,
221
+ species TEXT,
222
+ status TEXT NOT NULL CHECK(status IN ('draft','published')),
223
+ published_at TEXT
224
+ );
225
+ CREATE TABLE pet_guides (
226
+ id TEXT PRIMARY KEY,
227
+ slug TEXT NOT NULL UNIQUE,
228
+ title TEXT NOT NULL,
229
+ summary TEXT NOT NULL,
230
+ body TEXT NOT NULL,
231
+ species TEXT,
232
+ status TEXT NOT NULL CHECK(status IN ('draft','published')),
233
+ published_at TEXT
234
+ );
235
+ """
236
+ )
237
+
238
+
239
+ def adoption_communication_review(connection: sqlite3.Connection) -> None:
240
+ execute_sql_script(
241
+ connection,
242
+ """
243
+ CREATE TABLE adoption_applications (
244
+ id TEXT PRIMARY KEY,
245
+ user_id TEXT NOT NULL REFERENCES users(id),
246
+ animal_id TEXT NOT NULL REFERENCES animals(id),
247
+ organization_id TEXT NOT NULL REFERENCES organizations(id),
248
+ inquiry_id TEXT REFERENCES inquiries(id),
249
+ status TEXT NOT NULL CHECK(status IN ('DRAFT','SUBMITTED','UNDER_REVIEW','INTERVIEW','APPROVED','REJECTED','WITHDRAWN','ADOPTED')),
250
+ version INTEGER NOT NULL DEFAULT 0,
251
+ created_at TEXT NOT NULL,
252
+ updated_at TEXT NOT NULL,
253
+ submitted_at TEXT,
254
+ UNIQUE(user_id, animal_id)
255
+ );
256
+ CREATE TABLE application_answers (
257
+ application_id TEXT NOT NULL REFERENCES adoption_applications(id) ON DELETE CASCADE,
258
+ question_key TEXT NOT NULL,
259
+ answer TEXT NOT NULL,
260
+ updated_at TEXT NOT NULL,
261
+ PRIMARY KEY(application_id, question_key)
262
+ );
263
+ CREATE TABLE application_events (
264
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
265
+ application_id TEXT NOT NULL REFERENCES adoption_applications(id) ON DELETE CASCADE,
266
+ old_status TEXT,
267
+ new_status TEXT NOT NULL,
268
+ actor_user_id TEXT NOT NULL REFERENCES users(id),
269
+ note TEXT NOT NULL DEFAULT '',
270
+ created_at TEXT NOT NULL,
271
+ idempotency_key TEXT NOT NULL,
272
+ UNIQUE(application_id, idempotency_key)
273
+ );
274
+ CREATE TABLE conversations (
275
+ id TEXT PRIMARY KEY,
276
+ animal_id TEXT NOT NULL REFERENCES animals(id),
277
+ organization_id TEXT NOT NULL REFERENCES organizations(id),
278
+ adopter_user_id TEXT NOT NULL REFERENCES users(id),
279
+ inquiry_id TEXT REFERENCES inquiries(id),
280
+ application_id TEXT REFERENCES adoption_applications(id),
281
+ created_at TEXT NOT NULL,
282
+ UNIQUE(animal_id, adopter_user_id)
283
+ );
284
+ CREATE TABLE messages (
285
+ id TEXT PRIMARY KEY,
286
+ conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
287
+ sender_user_id TEXT NOT NULL REFERENCES users(id),
288
+ content TEXT NOT NULL CHECK(length(content) BETWEEN 1 AND 5000),
289
+ created_at TEXT NOT NULL,
290
+ read_at TEXT,
291
+ idempotency_key TEXT NOT NULL,
292
+ UNIQUE(conversation_id, idempotency_key)
293
+ );
294
+ CREATE TABLE notifications (
295
+ id TEXT PRIMARY KEY,
296
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
297
+ type TEXT NOT NULL CHECK(type IN ('favorite_update','application_update','new_match','message_received')),
298
+ subject_id TEXT NOT NULL,
299
+ body TEXT NOT NULL,
300
+ created_at TEXT NOT NULL,
301
+ read_at TEXT,
302
+ dedupe_key TEXT NOT NULL,
303
+ UNIQUE(user_id, dedupe_key)
304
+ );
305
+ CREATE TABLE organization_reviews (
306
+ id TEXT PRIMARY KEY,
307
+ organization_id TEXT NOT NULL REFERENCES organizations(id),
308
+ user_id TEXT NOT NULL REFERENCES users(id),
309
+ application_id TEXT NOT NULL UNIQUE REFERENCES adoption_applications(id),
310
+ rating INTEGER NOT NULL CHECK(rating BETWEEN 1 AND 5),
311
+ adoption_experience TEXT NOT NULL,
312
+ created_at TEXT NOT NULL,
313
+ version INTEGER NOT NULL DEFAULT 0,
314
+ UNIQUE(organization_id, user_id)
315
+ );
316
+ CREATE INDEX idx_applications_user ON adoption_applications(user_id, updated_at DESC);
317
+ CREATE INDEX idx_applications_org ON adoption_applications(organization_id, status, updated_at DESC);
318
+ CREATE INDEX idx_messages_conversation ON messages(conversation_id, created_at, id);
319
+ CREATE INDEX idx_notifications_user ON notifications(user_id, read_at, created_at DESC);
320
+ """
321
+ )
322
+
323
+
324
+ def support_payment_overlay(connection: sqlite3.Connection) -> None:
325
+ """Add the site-owned snapshot consumed by the shared payment ledger."""
326
+
327
+ execute_sql_script(
328
+ connection,
329
+ """
330
+ CREATE TABLE support_checkouts (
331
+ checkout_id TEXT PRIMARY KEY,
332
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
333
+ tier_id TEXT NOT NULL,
334
+ amount_minor INTEGER NOT NULL CHECK(amount_minor > 0),
335
+ currency TEXT NOT NULL CHECK(currency = 'USD'),
336
+ fingerprint TEXT NOT NULL CHECK(length(fingerprint) = 64),
337
+ flow_id TEXT NOT NULL UNIQUE,
338
+ adapter TEXT NOT NULL CHECK(adapter IN ('local-sandbox','stripe-test')),
339
+ provider_session_id TEXT UNIQUE,
340
+ status TEXT NOT NULL CHECK(status IN ('PENDING','DECLINED','COMPLETED','CANCELLED')),
341
+ idempotency_key TEXT NOT NULL,
342
+ version INTEGER NOT NULL DEFAULT 0 CHECK(version >= 0),
343
+ created_at TEXT NOT NULL,
344
+ updated_at TEXT NOT NULL,
345
+ UNIQUE(account_id, idempotency_key)
346
+ );
347
+ CREATE TABLE support_receipts (
348
+ receipt_id TEXT PRIMARY KEY,
349
+ checkout_id TEXT NOT NULL UNIQUE REFERENCES support_checkouts(checkout_id) ON DELETE CASCADE,
350
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
351
+ amount_minor INTEGER NOT NULL CHECK(amount_minor > 0),
352
+ currency TEXT NOT NULL CHECK(currency = 'USD'),
353
+ payment_attempt_id TEXT NOT NULL UNIQUE,
354
+ receipt_mail_id TEXT,
355
+ created_at TEXT NOT NULL
356
+ );
357
+ CREATE INDEX idx_support_checkouts_owner
358
+ ON support_checkouts(account_id, created_at DESC, checkout_id);
359
+ CREATE INDEX idx_support_receipts_owner
360
+ ON support_receipts(account_id, created_at DESC, receipt_id);
361
+ """,
362
+ )
tasks/petfinder/solution/site/implementation/clone/backend/policies.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server-side authorization policies for Petfinder domain objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+
7
+
8
+ class AuthorizationDenied(PermissionError):
9
+ pass
10
+
11
+
12
+ def require_owner(actor_user_id: str, owner_user_id: str) -> None:
13
+ if not actor_user_id or actor_user_id != owner_user_id:
14
+ raise AuthorizationDenied("the authenticated user does not own this resource")
15
+
16
+
17
+ def require_organization_staff(
18
+ connection: sqlite3.Connection,
19
+ actor_user_id: str,
20
+ organization_id: str,
21
+ *,
22
+ roles: tuple[str, ...] = ("OWNER", "ADMIN", "STAFF"),
23
+ ) -> str:
24
+ row = connection.execute(
25
+ "SELECT role FROM organization_staff WHERE user_id=? AND organization_id=?",
26
+ (actor_user_id, organization_id),
27
+ ).fetchone()
28
+ if row is None or row["role"] not in roles:
29
+ raise AuthorizationDenied("organization staff permission is required")
30
+ return str(row["role"])
31
+
32
+
33
+ def can_view_conversation(
34
+ connection: sqlite3.Connection, actor_user_id: str, conversation_id: str
35
+ ) -> bool:
36
+ row = connection.execute(
37
+ "SELECT adopter_user_id,organization_id FROM conversations WHERE id=?",
38
+ (conversation_id,),
39
+ ).fetchone()
40
+ if row is None:
41
+ return False
42
+ if row["adopter_user_id"] == actor_user_id:
43
+ return True
44
+ staff = connection.execute(
45
+ "SELECT 1 FROM organization_staff WHERE user_id=? AND organization_id=?",
46
+ (actor_user_id, row["organization_id"]),
47
+ ).fetchone()
48
+ return staff is not None
tasks/petfinder/solution/site/implementation/clone/backend/repositories.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small SQLite repositories; domain transitions live in services.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ from typing import Any
8
+
9
+
10
+ class ApplicationRepository:
11
+ def __init__(self, connection: sqlite3.Connection):
12
+ self.connection = connection
13
+
14
+ def get(self, application_id: str) -> dict[str, Any] | None:
15
+ row = self.connection.execute(
16
+ "SELECT * FROM adoption_applications WHERE id=?", (application_id,)
17
+ ).fetchone()
18
+ return dict(row) if row else None
19
+
20
+ def list_for_user(self, user_id: str) -> list[dict[str, Any]]:
21
+ rows = self.connection.execute(
22
+ "SELECT a.*,animals.name AS animal_name,organizations.name AS organization_name "
23
+ "FROM adoption_applications a JOIN animals ON animals.id=a.animal_id "
24
+ "JOIN organizations ON organizations.id=a.organization_id "
25
+ "WHERE a.user_id=? ORDER BY a.updated_at DESC,a.id",
26
+ (user_id,),
27
+ ).fetchall()
28
+ return [dict(row) for row in rows]
29
+
30
+
31
+ class PersonalizationRepository:
32
+ def __init__(self, connection: sqlite3.Connection):
33
+ self.connection = connection
34
+
35
+ def saved_searches(self, user_id: str) -> list[dict[str, Any]]:
36
+ rows = self.connection.execute(
37
+ "SELECT * FROM saved_searches WHERE user_id=? ORDER BY updated_at DESC,id",
38
+ (user_id,),
39
+ ).fetchall()
40
+ result = []
41
+ for row in rows:
42
+ item = dict(row)
43
+ item["query"] = json.loads(item.pop("query_json"))
44
+ result.append(item)
45
+ return result
46
+
47
+ def preferences(self, user_id: str) -> dict[str, Any] | None:
48
+ row = self.connection.execute(
49
+ "SELECT * FROM user_preferences WHERE user_id=?", (user_id,)
50
+ ).fetchone()
51
+ return dict(row) if row else None
52
+
53
+
54
+ class MessagingRepository:
55
+ def __init__(self, connection: sqlite3.Connection):
56
+ self.connection = connection
57
+
58
+ def conversations(self, user_id: str) -> list[dict[str, Any]]:
59
+ rows = self.connection.execute(
60
+ "SELECT DISTINCT c.*,animals.name AS animal_name,organizations.name AS organization_name "
61
+ "FROM conversations c JOIN animals ON animals.id=c.animal_id "
62
+ "JOIN organizations ON organizations.id=c.organization_id "
63
+ "LEFT JOIN organization_staff s ON s.organization_id=c.organization_id "
64
+ "WHERE c.adopter_user_id=? OR s.user_id=? ORDER BY c.created_at DESC,c.id",
65
+ (user_id, user_id),
66
+ ).fetchall()
67
+ return [dict(row) for row in rows]
tasks/petfinder/solution/site/implementation/clone/backend/services.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transactional Petfinder domain services.
2
+
3
+ All identities are server-resolved user ids. Callers cannot provide an owner
4
+ or organization scope that bypasses the policy checks in this module.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import sqlite3
12
+ from typing import Any, Callable
13
+
14
+ from petfinder_domain_policies import AuthorizationDenied, can_view_conversation, require_organization_staff, require_owner
15
+
16
+
17
+ class DomainConflict(RuntimeError):
18
+ pass
19
+
20
+
21
+ class DomainValidation(ValueError):
22
+ pass
23
+
24
+
25
+ APPLICATION_TRANSITIONS = {
26
+ "DRAFT": {"SUBMITTED"},
27
+ "SUBMITTED": {"UNDER_REVIEW", "WITHDRAWN"},
28
+ "UNDER_REVIEW": {"INTERVIEW", "APPROVED", "REJECTED", "WITHDRAWN"},
29
+ "INTERVIEW": {"APPROVED", "REJECTED", "WITHDRAWN"},
30
+ "APPROVED": {"ADOPTED", "WITHDRAWN"},
31
+ "REJECTED": set(),
32
+ "WITHDRAWN": set(),
33
+ "ADOPTED": set(),
34
+ }
35
+ ADOPTER_TRANSITIONS = {("DRAFT", "SUBMITTED"), ("SUBMITTED", "WITHDRAWN"),
36
+ ("UNDER_REVIEW", "WITHDRAWN"), ("INTERVIEW", "WITHDRAWN"),
37
+ ("APPROVED", "WITHDRAWN")}
38
+ ANIMAL_TRANSITIONS = {
39
+ "AVAILABLE": {"INTERESTED", "PENDING", "ADOPTED", "FOUND", "REMOVED"},
40
+ "INTERESTED": {"AVAILABLE", "PENDING", "ADOPTED", "REMOVED"},
41
+ "PENDING": {"AVAILABLE", "ADOPTED", "REMOVED"},
42
+ "FOUND": {"AVAILABLE", "REMOVED"},
43
+ "ADOPTED": set(),
44
+ "REMOVED": set(),
45
+ }
46
+
47
+
48
+ def _stable_id(prefix: str, *parts: str) -> str:
49
+ value = ":".join(parts)
50
+ return f"{prefix}-{hashlib.sha256(value.encode()).hexdigest()[:24]}"
51
+
52
+
53
+ class DomainService:
54
+ def __init__(self, connect: Callable[[], sqlite3.Connection], clock: str):
55
+ self.connect = connect
56
+ self.clock = clock
57
+
58
+ def save_search(
59
+ self, actor: str, name: str, query: dict[str, Any], *, expected_version: int,
60
+ idempotency_key: str,
61
+ ) -> dict[str, Any]:
62
+ normalized_name = " ".join(name.split())
63
+ if not normalized_name or len(normalized_name) > 120 or not idempotency_key:
64
+ raise DomainValidation("name and idempotency key are required")
65
+ canonical = json.dumps(query, sort_keys=True, separators=(",", ":"))
66
+ command_payload = json.dumps(
67
+ {"name": normalized_name, "query": query, "expected_version": expected_version},
68
+ sort_keys=True, separators=(",", ":"),
69
+ )
70
+ payload_sha = hashlib.sha256(command_payload.encode()).hexdigest()
71
+ search_id = _stable_id("search", actor, idempotency_key)
72
+ with self.connect() as connection:
73
+ connection.execute("BEGIN IMMEDIATE")
74
+ command = connection.execute(
75
+ "SELECT payload_sha256,result_json FROM domain_idempotency_commands "
76
+ "WHERE user_id=? AND command_kind='saved-search' AND idempotency_key=?",
77
+ (actor, idempotency_key),
78
+ ).fetchone()
79
+ if command:
80
+ if command["payload_sha256"] != payload_sha:
81
+ raise DomainConflict("idempotency key was reused with another saved search")
82
+ return json.loads(command["result_json"])
83
+ existing = connection.execute(
84
+ "SELECT * FROM saved_searches WHERE user_id=? AND name=?", (actor, normalized_name)
85
+ ).fetchone()
86
+ if existing and int(existing["version"]) != expected_version:
87
+ raise DomainConflict("saved search version is stale")
88
+ if existing:
89
+ connection.execute(
90
+ "UPDATE saved_searches SET query_json=?,updated_at=?,version=version+1 WHERE id=?",
91
+ (canonical, self.clock, existing["id"]),
92
+ )
93
+ search_id = str(existing["id"])
94
+ else:
95
+ if expected_version != 0:
96
+ raise DomainConflict("saved search version is stale")
97
+ connection.execute(
98
+ "INSERT INTO saved_searches(id,user_id,name,query_json,created_at,updated_at)"
99
+ " VALUES(?,?,?,?,?,?)",
100
+ (search_id, actor, normalized_name, canonical, self.clock, self.clock),
101
+ )
102
+ connection.execute(
103
+ "INSERT INTO search_alerts(id,saved_search_id) VALUES(?,?)",
104
+ (_stable_id("alert", search_id), search_id),
105
+ )
106
+ result = dict(connection.execute("SELECT * FROM saved_searches WHERE id=?", (search_id,)).fetchone())
107
+ connection.execute(
108
+ "INSERT INTO domain_idempotency_commands(user_id,command_kind,idempotency_key,payload_sha256,result_json,created_at)"
109
+ " VALUES(?,'saved-search',?,?,?,?)",
110
+ (actor, idempotency_key, payload_sha, json.dumps(result, sort_keys=True), self.clock),
111
+ )
112
+ connection.execute("DELETE FROM recommendation_cache WHERE user_id=?", (actor,))
113
+ return result
114
+
115
+ def update_preferences(
116
+ self, actor: str, values: dict[str, Any], *, expected_version: int,
117
+ idempotency_key: str,
118
+ ) -> dict[str, Any]:
119
+ radius = int(values.get("radius_miles", 100))
120
+ if not 1 <= radius <= 500:
121
+ raise DomainValidation("radius must be between 1 and 500 miles")
122
+ if not idempotency_key:
123
+ raise DomainValidation("idempotency key is required")
124
+ canonical_values = {
125
+ key: values.get(key) for key in
126
+ ("species", "breeds", "sizes", "location_zip", "email_alerts")
127
+ }
128
+ canonical_values["radius_miles"] = radius
129
+ canonical_values["expected_version"] = expected_version
130
+ payload_sha = hashlib.sha256(
131
+ json.dumps(canonical_values, sort_keys=True, separators=(",", ":")).encode()
132
+ ).hexdigest()
133
+ with self.connect() as connection:
134
+ connection.execute("BEGIN IMMEDIATE")
135
+ command = connection.execute(
136
+ "SELECT payload_sha256,result_json FROM domain_idempotency_commands "
137
+ "WHERE user_id=? AND command_kind='preferences' AND idempotency_key=?",
138
+ (actor, idempotency_key),
139
+ ).fetchone()
140
+ if command:
141
+ if command["payload_sha256"] != payload_sha:
142
+ raise DomainConflict("idempotency key was reused with other preferences")
143
+ return json.loads(command["result_json"])
144
+ row = connection.execute("SELECT version FROM user_preferences WHERE user_id=?", (actor,)).fetchone()
145
+ current = int(row["version"]) if row else 0
146
+ if current != expected_version:
147
+ raise DomainConflict("preferences version is stale")
148
+ connection.execute(
149
+ "INSERT INTO user_preferences(user_id,species,breeds,sizes,location_zip,radius_miles,email_alerts,version,updated_at)"
150
+ " VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET species=excluded.species,"
151
+ "breeds=excluded.breeds,sizes=excluded.sizes,location_zip=excluded.location_zip,"
152
+ "radius_miles=excluded.radius_miles,email_alerts=excluded.email_alerts,"
153
+ "version=user_preferences.version+1,updated_at=excluded.updated_at",
154
+ (actor, values.get("species") or None, values.get("breeds", ""), values.get("sizes", ""),
155
+ values.get("location_zip") or None, radius, int(bool(values.get("email_alerts"))),
156
+ 0, self.clock),
157
+ )
158
+ result = dict(connection.execute("SELECT * FROM user_preferences WHERE user_id=?", (actor,)).fetchone())
159
+ connection.execute(
160
+ "INSERT INTO domain_idempotency_commands(user_id,command_kind,idempotency_key,payload_sha256,result_json,created_at)"
161
+ " VALUES(?,'preferences',?,?,?,?)",
162
+ (actor, idempotency_key, payload_sha, json.dumps(result, sort_keys=True), self.clock),
163
+ )
164
+ connection.execute("DELETE FROM recommendation_cache WHERE user_id=?", (actor,))
165
+ return result
166
+
167
+ def create_application(self, actor: str, animal_id: str, inquiry_id: str | None = None) -> dict[str, Any]:
168
+ with self.connect() as connection:
169
+ connection.execute("BEGIN IMMEDIATE")
170
+ animal = connection.execute(
171
+ "SELECT a.organization_id,s.status FROM animals a JOIN animal_status s ON s.animal_id=a.id WHERE a.id=?",
172
+ (animal_id,),
173
+ ).fetchone()
174
+ if animal is None:
175
+ raise LookupError("animal not found")
176
+ if animal["status"] != "AVAILABLE":
177
+ raise DomainConflict("animal is no longer available")
178
+ application_id = _stable_id("application", actor, animal_id)
179
+ connection.execute(
180
+ "INSERT OR IGNORE INTO adoption_applications(id,user_id,animal_id,organization_id,inquiry_id,status,created_at,updated_at)"
181
+ " VALUES(?,?,?,?,?,'DRAFT',?,?)",
182
+ (application_id, actor, animal_id, animal["organization_id"], inquiry_id, self.clock, self.clock),
183
+ )
184
+ return dict(connection.execute("SELECT * FROM adoption_applications WHERE id=?", (application_id,)).fetchone())
185
+
186
+ def transition_application(
187
+ self, actor: str, application_id: str, new_status: str, *, expected_version: int,
188
+ idempotency_key: str, note: str = "",
189
+ ) -> dict[str, Any]:
190
+ if not idempotency_key:
191
+ raise DomainValidation("idempotency key is required")
192
+ with self.connect() as connection:
193
+ connection.execute("BEGIN IMMEDIATE")
194
+ row = connection.execute("SELECT * FROM adoption_applications WHERE id=?", (application_id,)).fetchone()
195
+ if row is None:
196
+ raise LookupError("application not found")
197
+ old = str(row["status"])
198
+ duplicate = connection.execute(
199
+ "SELECT new_status FROM application_events WHERE application_id=? AND idempotency_key=?",
200
+ (application_id, idempotency_key),
201
+ ).fetchone()
202
+ if duplicate:
203
+ if duplicate["new_status"] != new_status:
204
+ raise DomainConflict("idempotency key was reused for another transition")
205
+ return dict(row)
206
+ if int(row["version"]) != expected_version:
207
+ raise DomainConflict("application version is stale")
208
+ if new_status not in APPLICATION_TRANSITIONS.get(old, set()):
209
+ raise DomainConflict(f"illegal application transition {old} -> {new_status}")
210
+ if (old, new_status) in ADOPTER_TRANSITIONS:
211
+ require_owner(actor, str(row["user_id"]))
212
+ else:
213
+ require_organization_staff(connection, actor, str(row["organization_id"]))
214
+ if new_status == "ADOPTED":
215
+ animal_state = connection.execute(
216
+ "SELECT status,version FROM animal_status WHERE animal_id=?", (row["animal_id"],)
217
+ ).fetchone()
218
+ if animal_state is None or "ADOPTED" not in ANIMAL_TRANSITIONS.get(str(animal_state["status"]), set()):
219
+ raise DomainConflict("animal cannot transition to ADOPTED from its current status")
220
+ connection.execute(
221
+ "UPDATE animal_status SET status='ADOPTED',version=version+1,updated_at=? WHERE animal_id=?",
222
+ (self.clock, row["animal_id"]),
223
+ )
224
+ connection.execute(
225
+ "UPDATE pet_search_documents SET availability='ADOPTED',indexed_at=? WHERE animal_id=?",
226
+ (self.clock, row["animal_id"]),
227
+ )
228
+ connection.execute("DELETE FROM recommendation_cache WHERE animal_id=?", (row["animal_id"],))
229
+ connection.execute(
230
+ "INSERT INTO animal_status_events(animal_id,old_status,new_status,actor_user_id,created_at,reason,idempotency_key)"
231
+ " VALUES(?,?,'ADOPTED',?,?,?,?)",
232
+ (row["animal_id"], animal_state["status"], actor, self.clock,
233
+ f"Completed application {application_id}", f"application:{idempotency_key}"),
234
+ )
235
+ connection.execute(
236
+ "UPDATE adoption_applications SET status=?,version=version+1,updated_at=?,"
237
+ "submitted_at=CASE WHEN ?='SUBMITTED' THEN ? ELSE submitted_at END WHERE id=?",
238
+ (new_status, self.clock, new_status, self.clock, application_id),
239
+ )
240
+ connection.execute(
241
+ "INSERT INTO application_events(application_id,old_status,new_status,actor_user_id,note,created_at,idempotency_key)"
242
+ " VALUES(?,?,?,?,?,?,?)",
243
+ (application_id, old, new_status, actor, note, self.clock, idempotency_key),
244
+ )
245
+ if new_status == "SUBMITTED":
246
+ conversation_id = _stable_id("conversation", str(row["user_id"]), str(row["animal_id"]))
247
+ connection.execute(
248
+ "INSERT OR IGNORE INTO conversations(id,animal_id,organization_id,adopter_user_id,inquiry_id,application_id,created_at)"
249
+ " VALUES(?,?,?,?,?,?,?)",
250
+ (conversation_id, row["animal_id"], row["organization_id"], row["user_id"],
251
+ row["inquiry_id"], application_id, self.clock),
252
+ )
253
+ connection.execute(
254
+ "INSERT OR IGNORE INTO notifications(id,user_id,type,subject_id,body,created_at,dedupe_key)"
255
+ " VALUES(?,?,'application_update',?,?,?,?)",
256
+ (_stable_id("notification", application_id, idempotency_key), row["user_id"], application_id,
257
+ f"Application status changed to {new_status}.", self.clock,
258
+ f"application:{application_id}:{idempotency_key}"),
259
+ )
260
+ return dict(connection.execute("SELECT * FROM adoption_applications WHERE id=?", (application_id,)).fetchone())
261
+
262
+ def transition_animal(
263
+ self, actor: str, animal_id: str, new_status: str, *, expected_version: int,
264
+ idempotency_key: str, reason: str = "",
265
+ ) -> dict[str, Any]:
266
+ with self.connect() as connection:
267
+ connection.execute("BEGIN IMMEDIATE")
268
+ row = connection.execute(
269
+ "SELECT s.*,a.organization_id FROM animal_status s JOIN animals a ON a.id=s.animal_id WHERE s.animal_id=?",
270
+ (animal_id,),
271
+ ).fetchone()
272
+ if row is None:
273
+ raise LookupError("animal not found")
274
+ require_organization_staff(connection, actor, str(row["organization_id"]))
275
+ duplicate = connection.execute(
276
+ "SELECT new_status FROM animal_status_events WHERE animal_id=? AND idempotency_key=?",
277
+ (animal_id, idempotency_key),
278
+ ).fetchone()
279
+ if duplicate:
280
+ if duplicate["new_status"] != new_status:
281
+ raise DomainConflict("idempotency key was reused for another status")
282
+ return dict(row)
283
+ old = str(row["status"])
284
+ if int(row["version"]) != expected_version:
285
+ raise DomainConflict("animal status version is stale")
286
+ if new_status not in ANIMAL_TRANSITIONS.get(old, set()):
287
+ raise DomainConflict(f"illegal animal transition {old} -> {new_status}")
288
+ connection.execute(
289
+ "UPDATE animal_status SET status=?,version=version+1,updated_at=? WHERE animal_id=?",
290
+ (new_status, self.clock, animal_id),
291
+ )
292
+ connection.execute(
293
+ "UPDATE pet_search_documents SET availability=?,indexed_at=? WHERE animal_id=?",
294
+ (new_status, self.clock, animal_id),
295
+ )
296
+ connection.execute("DELETE FROM recommendation_cache WHERE animal_id=?", (animal_id,))
297
+ connection.execute(
298
+ "INSERT INTO animal_status_events(animal_id,old_status,new_status,actor_user_id,created_at,reason,idempotency_key)"
299
+ " VALUES(?,?,?,?,?,?,?)",
300
+ (animal_id, old, new_status, actor, self.clock, reason, idempotency_key),
301
+ )
302
+ return dict(connection.execute("SELECT * FROM animal_status WHERE animal_id=?", (animal_id,)).fetchone())
303
+
304
+ def send_message(
305
+ self, actor: str, conversation_id: str, content: str, *, idempotency_key: str
306
+ ) -> dict[str, Any]:
307
+ normalized = content.strip()
308
+ if not 1 <= len(normalized) <= 5000 or not idempotency_key:
309
+ raise DomainValidation("message content and idempotency key are required")
310
+ with self.connect() as connection:
311
+ connection.execute("BEGIN IMMEDIATE")
312
+ conversation = connection.execute(
313
+ "SELECT * FROM conversations WHERE id=?", (conversation_id,)
314
+ ).fetchone()
315
+ if conversation is None:
316
+ raise LookupError("conversation not found")
317
+ if not can_view_conversation(connection, actor, conversation_id):
318
+ raise AuthorizationDenied("conversation is outside the authenticated scope")
319
+ message_id = _stable_id("message", conversation_id, idempotency_key)
320
+ existing = connection.execute(
321
+ "SELECT * FROM messages WHERE conversation_id=? AND idempotency_key=?",
322
+ (conversation_id, idempotency_key),
323
+ ).fetchone()
324
+ if existing:
325
+ if existing["content"] != normalized or existing["sender_user_id"] != actor:
326
+ raise DomainConflict("idempotency key was reused for another message")
327
+ return dict(existing)
328
+ connection.execute(
329
+ "INSERT INTO messages(id,conversation_id,sender_user_id,content,created_at,idempotency_key)"
330
+ " VALUES(?,?,?,?,?,?)",
331
+ (message_id, conversation_id, actor, normalized, self.clock, idempotency_key),
332
+ )
333
+ recipient = str(conversation["adopter_user_id"])
334
+ if recipient == actor:
335
+ staff = connection.execute(
336
+ "SELECT user_id FROM organization_staff WHERE organization_id=? ORDER BY role,user_id LIMIT 1",
337
+ (conversation["organization_id"],),
338
+ ).fetchone()
339
+ recipient = str(staff["user_id"]) if staff else ""
340
+ if recipient:
341
+ connection.execute(
342
+ "INSERT OR IGNORE INTO notifications(id,user_id,type,subject_id,body,created_at,dedupe_key)"
343
+ " VALUES(?,?,'message_received',?,?,?,?)",
344
+ (_stable_id("notification", message_id), recipient, conversation_id,
345
+ "You have a new local message.", self.clock, f"message:{message_id}"),
346
+ )
347
+ return dict(connection.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone())
348
+
349
+ def create_review(
350
+ self, actor: str, application_id: str, rating: int, experience: str,
351
+ *, organization_id: str | None = None,
352
+ ) -> dict[str, Any]:
353
+ if not 1 <= int(rating) <= 5 or not experience.strip():
354
+ raise DomainValidation("a rating from 1 to 5 and adoption experience are required")
355
+ with self.connect() as connection:
356
+ connection.execute("BEGIN IMMEDIATE")
357
+ application = connection.execute(
358
+ "SELECT * FROM adoption_applications WHERE id=?", (application_id,)
359
+ ).fetchone()
360
+ if application is None:
361
+ raise LookupError("application not found")
362
+ require_owner(actor, str(application["user_id"]))
363
+ if organization_id is not None and application["organization_id"] != organization_id:
364
+ raise LookupError("application not found")
365
+ if application["status"] != "ADOPTED":
366
+ raise DomainConflict("only a completed local adoption can be reviewed")
367
+ review_id = _stable_id("review", actor, str(application["organization_id"]))
368
+ connection.execute(
369
+ "INSERT INTO organization_reviews(id,organization_id,user_id,application_id,rating,adoption_experience,created_at)"
370
+ " VALUES(?,?,?,?,?,?,?)",
371
+ (review_id, application["organization_id"], actor, application_id,
372
+ int(rating), experience.strip(), self.clock),
373
+ )
374
+ return dict(connection.execute("SELECT * FROM organization_reviews WHERE id=?", (review_id,)).fetchone())
tasks/petfinder/solution/site/implementation/clone/backend/site_backend_integration.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generated, site-bound backend integration seam."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import json
7
+ import os
8
+ import secrets
9
+ import sqlite3
10
+ from pathlib import Path
11
+ from typing import Any, Callable
12
+
13
+ from websitebench.local_clone_auth import (
14
+ MAIL_LOCAL_ONLY,
15
+ MAIL_SMTP_PENDING,
16
+ LocalAuthStore,
17
+ )
18
+ from websitebench.site_backend import SiteBackend, load_runtime
19
+
20
+
21
+ DEFAULT_RUNTIME_PATH = (
22
+ Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
23
+ )
24
+ _AUTH_MAIL_WORKER_TOKEN = secrets.token_urlsafe(32)
25
+
26
+
27
+ def _deployment_profile(runtime: Any) -> dict[str, Any] | None:
28
+ profile_name = os.environ.get("WEBSITEBENCH_BACKEND_PROFILE", "").strip()
29
+ if not profile_name:
30
+ return None
31
+ profile = runtime.deployment["profiles"].get(profile_name)
32
+ if profile is None:
33
+ raise RuntimeError("backend profile is not declared by the runtime contract")
34
+ return profile
35
+
36
+
37
+ def auth_mail_worker_token() -> str:
38
+ """Return process-local worker authority; never persist or expose it."""
39
+
40
+ return _AUTH_MAIL_WORKER_TOKEN
41
+
42
+
43
+ def auth_mail_delivery_enabled(backend: SiteBackend) -> bool:
44
+ profile = _deployment_profile(backend.config)
45
+ return bool(
46
+ os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip()
47
+ or (
48
+ profile
49
+ and profile["mail_adapter"] in {"redis-resend", "effects-gateway"}
50
+ )
51
+ )
52
+
53
+
54
+ def _declared_hook(
55
+ declaration: str | None,
56
+ ) -> Callable[[sqlite3.Connection], None] | None:
57
+ if declaration is None:
58
+ return None
59
+ module_name, function_name = declaration.split(":", 1)
60
+ module = importlib.import_module(module_name)
61
+ hook: Any = getattr(module, function_name, None)
62
+ if not callable(hook):
63
+ raise RuntimeError(f"declared backend hook is not callable: {declaration}")
64
+ actual = f"{hook.__module__}:{hook.__name__}"
65
+ if actual != declaration:
66
+ raise RuntimeError(
67
+ f"declared backend hook resolved as {actual!r}, expected {declaration!r}"
68
+ )
69
+ return hook
70
+
71
+
72
+ def open_site_services() -> tuple[SiteBackend, LocalAuthStore]:
73
+ """Open one bound database; never omit the site id for permanent auth."""
74
+
75
+ runtime_path = Path(
76
+ os.environ.get(
77
+ "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
78
+ str(DEFAULT_RUNTIME_PATH),
79
+ )
80
+ ).resolve()
81
+ runtime = load_runtime(runtime_path)
82
+ migration_hook = _declared_hook(runtime.migration_hook)
83
+ seed_hook = _declared_hook(runtime.seed_hook)
84
+ deployed_database = os.environ.get(
85
+ "WEBSITEBENCH_SITE_BACKEND_DATABASE",
86
+ )
87
+ if deployed_database is None:
88
+ backend = SiteBackend.open(
89
+ runtime_path,
90
+ migration_hook=migration_hook,
91
+ seed_hook=seed_hook,
92
+ )
93
+ else:
94
+ database_path = Path(deployed_database).resolve()
95
+ if database_path.name != runtime.database_filename:
96
+ raise RuntimeError(
97
+ "deployed database filename does not match runtime contract"
98
+ )
99
+ backend = SiteBackend.open(
100
+ json.loads(runtime_path.read_text(encoding="utf-8")),
101
+ data_root=database_path.parent,
102
+ migration_hook=migration_hook,
103
+ seed_hook=seed_hook,
104
+ )
105
+ if backend.lifecycle.database_path != database_path:
106
+ raise RuntimeError(
107
+ "deployed database path does not match backend preflight"
108
+ )
109
+ backend.lifecycle.initialize()
110
+ profile = _deployment_profile(runtime)
111
+ remote_mail = bool(
112
+ os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip()
113
+ or (
114
+ profile
115
+ and profile["mail_adapter"] in {"redis-resend", "effects-gateway"}
116
+ )
117
+ )
118
+ auth = LocalAuthStore(
119
+ backend.lifecycle.database_path,
120
+ site_id=backend.config.site_id,
121
+ mail_mode=MAIL_SMTP_PENDING if remote_mail else MAIL_LOCAL_ONLY,
122
+ mail_worker_token=_AUTH_MAIL_WORKER_TOKEN if remote_mail else None,
123
+ )
124
+ auth.ensure_schema()
125
+ return backend, auth
tasks/petfinder/solution/site/implementation/clone/backend/support_payments.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Petfinder support-checkout overlay on the shared WebsiteBench ledger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import secrets
10
+ import sqlite3
11
+ from collections.abc import Mapping
12
+ from datetime import UTC, datetime
13
+ from typing import Any
14
+
15
+ from websitebench.site_backend import (
16
+ PaymentConflict,
17
+ PaymentError,
18
+ PaymentRejected,
19
+ SiteBackend,
20
+ )
21
+
22
+
23
+ SITE_ID = "petfinder"
24
+ CURRENCY = "USD"
25
+ SUPPORT_TIERS: tuple[dict[str, Any], ...] = (
26
+ {
27
+ "id": "support-5",
28
+ "amount_minor": 500,
29
+ "label": "$5 test support",
30
+ "description": "Exercise a small sandbox contribution.",
31
+ },
32
+ {
33
+ "id": "support-10",
34
+ "amount_minor": 1000,
35
+ "label": "$10 test support",
36
+ "description": "Exercise the standard sandbox contribution.",
37
+ },
38
+ {
39
+ "id": "support-25",
40
+ "amount_minor": 2500,
41
+ "label": "$25 test support",
42
+ "description": "Exercise a larger sandbox contribution.",
43
+ },
44
+ )
45
+ _TIERS = {str(item["id"]): item for item in SUPPORT_TIERS}
46
+ _IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{8,200}$")
47
+ _STRIPE_SESSION_RE = re.compile(r"^cs_test_[A-Za-z0-9_]{8,240}$")
48
+
49
+
50
+ class SupportPaymentError(RuntimeError):
51
+ """The support checkout is absent, stale, foreign, or invalid."""
52
+
53
+
54
+ def _now() -> str:
55
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
56
+
57
+
58
+ def _require_transaction(connection: sqlite3.Connection) -> None:
59
+ if not isinstance(connection, sqlite3.Connection) or not connection.in_transaction:
60
+ raise SupportPaymentError("support payment requires an active transaction")
61
+
62
+
63
+ def public_support_tiers() -> tuple[dict[str, Any], ...]:
64
+ return tuple(dict(item) for item in SUPPORT_TIERS)
65
+
66
+
67
+ def payment_adapter(
68
+ backend: SiteBackend,
69
+ environment: Mapping[str, str] | None = None,
70
+ ) -> str:
71
+ """Select only the adapter frozen by the active deployment profile."""
72
+
73
+ source = os.environ if environment is None else environment
74
+ profile_name = str(source.get("WEBSITEBENCH_BACKEND_PROFILE", "")).strip()
75
+ supplied = str(source.get("WEBSITEBENCH_PAYMENT_ADAPTER", "")).strip()
76
+ if profile_name:
77
+ profile = backend.config.deployment["profiles"].get(profile_name)
78
+ if profile is None:
79
+ raise SupportPaymentError("backend profile is not declared")
80
+ selected = str(profile["payment_adapter"])
81
+ else:
82
+ selected = str(backend.config.payments["default_adapter"])
83
+ if supplied and supplied != selected:
84
+ raise SupportPaymentError(
85
+ "payment adapter does not match the frozen deployment profile"
86
+ )
87
+ if selected == "stripe-test" and backend.config.payments["stripe_test"] is None:
88
+ raise SupportPaymentError("stripe-test is not configured")
89
+ if selected not in {"local-sandbox", "stripe-test"}:
90
+ raise SupportPaymentError("payment adapter is unsupported")
91
+ return selected
92
+
93
+
94
+ def local_scenarios(backend: SiteBackend) -> tuple[dict[str, str], ...]:
95
+ return tuple(
96
+ {
97
+ "id": str(item["id"]),
98
+ "label": str(item["display_label"]),
99
+ "outcome": str(item["outcome"]),
100
+ }
101
+ for item in backend.config.payments["local_sandbox"]["scenarios"]
102
+ )
103
+
104
+
105
+ def _fingerprint(
106
+ *, checkout_id: str, account_id: str, tier_id: str, amount_minor: int
107
+ ) -> str:
108
+ payload = {
109
+ "site_id": SITE_ID,
110
+ "checkout_id": checkout_id,
111
+ "account_id": account_id,
112
+ "tier_id": tier_id,
113
+ "amount_minor": amount_minor,
114
+ "currency": CURRENCY,
115
+ "effect": "test-only-support-receipt",
116
+ }
117
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
118
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
119
+
120
+
121
+ def _public_checkout(row: sqlite3.Row) -> dict[str, Any]:
122
+ return {
123
+ "checkout_id": str(row["checkout_id"]),
124
+ "account_id": str(row["account_id"]),
125
+ "tier_id": str(row["tier_id"]),
126
+ "amount_minor": int(row["amount_minor"]),
127
+ "currency": str(row["currency"]),
128
+ "fingerprint": str(row["fingerprint"]),
129
+ "flow_id": str(row["flow_id"]),
130
+ "adapter": str(row["adapter"]),
131
+ "provider_session_id": row["provider_session_id"],
132
+ "status": str(row["status"]),
133
+ "version": int(row["version"]),
134
+ "total": f"${int(row['amount_minor']) / 100:.2f} {row['currency']}",
135
+ }
136
+
137
+
138
+ def create_checkout(
139
+ connection: sqlite3.Connection,
140
+ backend: SiteBackend,
141
+ *,
142
+ account_id: str,
143
+ tier_id: str,
144
+ idempotency_key: str,
145
+ ) -> tuple[dict[str, Any], bool]:
146
+ """Create a domain checkout and shared payment flow atomically."""
147
+
148
+ _require_transaction(connection)
149
+ tier = _TIERS.get(tier_id)
150
+ if tier is None or _IDEMPOTENCY_RE.fullmatch(idempotency_key) is None:
151
+ raise SupportPaymentError("support tier or idempotency key is invalid")
152
+ if connection.execute(
153
+ "SELECT 1 FROM accounts WHERE id=?", (account_id,)
154
+ ).fetchone() is None:
155
+ raise SupportPaymentError("account is unavailable")
156
+ existing = connection.execute(
157
+ "SELECT * FROM support_checkouts WHERE account_id=? AND idempotency_key=?",
158
+ (account_id, idempotency_key),
159
+ ).fetchone()
160
+ if existing is not None:
161
+ if str(existing["tier_id"]) != tier_id:
162
+ raise SupportPaymentError("checkout idempotency key conflicts")
163
+ return _public_checkout(existing), False
164
+ checkout_id = f"support-{secrets.token_urlsafe(18)}"
165
+ amount_minor = int(tier["amount_minor"])
166
+ fingerprint = _fingerprint(
167
+ checkout_id=checkout_id,
168
+ account_id=account_id,
169
+ tier_id=tier_id,
170
+ amount_minor=amount_minor,
171
+ )
172
+ adapter = payment_adapter(backend)
173
+ try:
174
+ flow = backend.payments.create_intent(
175
+ owner=account_id,
176
+ amount_minor=amount_minor,
177
+ currency=CURRENCY,
178
+ fingerprint=fingerprint,
179
+ idempotency_key=f"petfinder-support-flow:{checkout_id}",
180
+ adapter=adapter,
181
+ connection=connection,
182
+ )
183
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
184
+ raise SupportPaymentError("support payment flow was rejected") from exc
185
+ now = _now()
186
+ connection.execute(
187
+ "INSERT INTO support_checkouts("
188
+ "checkout_id,account_id,tier_id,amount_minor,currency,fingerprint,"
189
+ "flow_id,adapter,status,idempotency_key,version,created_at,updated_at"
190
+ ") VALUES(?,?,?,?,?,?,?,?, 'PENDING', ?,0,?,?)",
191
+ (
192
+ checkout_id,
193
+ account_id,
194
+ tier_id,
195
+ amount_minor,
196
+ CURRENCY,
197
+ fingerprint,
198
+ flow["flow_id"],
199
+ adapter,
200
+ idempotency_key,
201
+ now,
202
+ now,
203
+ ),
204
+ )
205
+ row = connection.execute(
206
+ "SELECT * FROM support_checkouts WHERE checkout_id=?", (checkout_id,)
207
+ ).fetchone()
208
+ return _public_checkout(row), True
209
+
210
+
211
+ def checkout_for_owner(
212
+ connection: sqlite3.Connection, account_id: str, checkout_id: str
213
+ ) -> dict[str, Any] | None:
214
+ row = connection.execute(
215
+ "SELECT * FROM support_checkouts WHERE checkout_id=? AND account_id=?",
216
+ (checkout_id, account_id),
217
+ ).fetchone()
218
+ return _public_checkout(row) if row is not None else None
219
+
220
+
221
+ def receipt_for_owner(
222
+ connection: sqlite3.Connection, account_id: str, receipt_id: str
223
+ ) -> dict[str, Any] | None:
224
+ row = connection.execute(
225
+ "SELECT support_receipts.*,support_checkouts.adapter "
226
+ "FROM support_receipts JOIN support_checkouts USING(checkout_id) "
227
+ "WHERE receipt_id=? AND support_receipts.account_id=?",
228
+ (receipt_id, account_id),
229
+ ).fetchone()
230
+ if row is None:
231
+ return None
232
+ return {
233
+ "receipt_id": str(row["receipt_id"]),
234
+ "checkout_id": str(row["checkout_id"]),
235
+ "account_id": str(row["account_id"]),
236
+ "amount_minor": int(row["amount_minor"]),
237
+ "currency": str(row["currency"]),
238
+ "adapter": str(row["adapter"]),
239
+ "receipt_mail_id": row["receipt_mail_id"],
240
+ "created_at": str(row["created_at"]),
241
+ "total": f"${int(row['amount_minor']) / 100:.2f} {row['currency']}",
242
+ }
243
+
244
+
245
+ def stripe_preparation(
246
+ connection: sqlite3.Connection, account_id: str, checkout_id: str
247
+ ) -> dict[str, Any]:
248
+ checkout = checkout_for_owner(connection, account_id, checkout_id)
249
+ if checkout is None or checkout["adapter"] != "stripe-test":
250
+ raise SupportPaymentError("stripe checkout is unavailable")
251
+ flow = connection.execute(
252
+ "SELECT * FROM websitebench_payment_flows WHERE flow_id=? AND site_id=?",
253
+ (checkout["flow_id"], SITE_ID),
254
+ ).fetchone()
255
+ account = connection.execute(
256
+ "SELECT email FROM accounts WHERE id=?", (account_id,)
257
+ ).fetchone()
258
+ if flow is None or account is None:
259
+ raise SupportPaymentError("stripe checkout facts are unavailable")
260
+ return {
261
+ "checkout": checkout,
262
+ "flow": {
263
+ "flow_id": str(flow["flow_id"]),
264
+ "site_id": str(flow["site_id"]),
265
+ "owner": str(flow["owner"]),
266
+ "amount_minor": int(flow["amount_minor"]),
267
+ "currency": str(flow["currency"]),
268
+ "fingerprint": str(flow["fingerprint"]),
269
+ "adapter": str(flow["adapter"]),
270
+ "is_simulation": bool(flow["is_simulation"]),
271
+ },
272
+ "customer_email": str(account["email"]),
273
+ }
274
+
275
+
276
+ def record_provider_session(
277
+ connection: sqlite3.Connection,
278
+ *,
279
+ account_id: str,
280
+ checkout_id: str,
281
+ provider_session_id: str,
282
+ ) -> None:
283
+ _require_transaction(connection)
284
+ if _STRIPE_SESSION_RE.fullmatch(provider_session_id) is None:
285
+ raise SupportPaymentError("Stripe test Session is invalid")
286
+ changed = connection.execute(
287
+ "UPDATE support_checkouts SET provider_session_id=?,updated_at=? "
288
+ "WHERE checkout_id=? AND account_id=? AND adapter='stripe-test' "
289
+ "AND status IN ('PENDING','DECLINED') "
290
+ "AND (provider_session_id IS NULL OR provider_session_id=?)",
291
+ (
292
+ provider_session_id,
293
+ _now(),
294
+ checkout_id,
295
+ account_id,
296
+ provider_session_id,
297
+ ),
298
+ ).rowcount
299
+ if changed != 1:
300
+ raise SupportPaymentError("Stripe test Session conflicts with checkout")
301
+
302
+
303
+ def _finalize(
304
+ connection: sqlite3.Connection,
305
+ backend: SiteBackend,
306
+ *,
307
+ checkout: dict[str, Any],
308
+ ) -> dict[str, Any]:
309
+ existing = connection.execute(
310
+ "SELECT receipt_id FROM support_receipts WHERE checkout_id=?",
311
+ (checkout["checkout_id"],),
312
+ ).fetchone()
313
+ if existing is not None:
314
+ receipt = receipt_for_owner(
315
+ connection, checkout["account_id"], str(existing["receipt_id"])
316
+ )
317
+ return {"result": "approved", "replayed": True, "receipt": receipt}
318
+ approval = backend.payments.consume_approval(
319
+ connection,
320
+ flow_id=checkout["flow_id"],
321
+ owner=checkout["account_id"],
322
+ amount_minor=checkout["amount_minor"],
323
+ currency=checkout["currency"],
324
+ fingerprint=checkout["fingerprint"],
325
+ )
326
+ receipt_id = f"receipt-{secrets.token_urlsafe(14)}"
327
+ account = connection.execute(
328
+ "SELECT email FROM accounts WHERE id=?", (checkout["account_id"],)
329
+ ).fetchone()
330
+ if account is None:
331
+ raise SupportPaymentError("receipt account is unavailable")
332
+ mail = backend.mail.enqueue(
333
+ "support-receipt",
334
+ str(account["email"]),
335
+ {
336
+ "receipt_id": receipt_id,
337
+ "total": checkout["total"],
338
+ },
339
+ idempotency_key=f"petfinder-support-receipt:{receipt_id}",
340
+ simulation=checkout["adapter"] == "local-sandbox",
341
+ connection=connection,
342
+ )
343
+ now = _now()
344
+ connection.execute(
345
+ "INSERT INTO support_receipts("
346
+ "receipt_id,checkout_id,account_id,amount_minor,currency,"
347
+ "payment_attempt_id,receipt_mail_id,created_at) VALUES(?,?,?,?,?,?,?,?)",
348
+ (
349
+ receipt_id,
350
+ checkout["checkout_id"],
351
+ checkout["account_id"],
352
+ checkout["amount_minor"],
353
+ checkout["currency"],
354
+ approval["attempt_id"],
355
+ mail["mail_id"],
356
+ now,
357
+ ),
358
+ )
359
+ connection.execute(
360
+ "UPDATE support_checkouts SET status='COMPLETED',version=version+1,"
361
+ "updated_at=? WHERE checkout_id=? AND status<>'COMPLETED'",
362
+ (now, checkout["checkout_id"]),
363
+ )
364
+ receipt = receipt_for_owner(connection, checkout["account_id"], receipt_id)
365
+ return {"result": "approved", "replayed": False, "receipt": receipt}
366
+
367
+
368
+ def process_local_payment(
369
+ connection: sqlite3.Connection,
370
+ backend: SiteBackend,
371
+ *,
372
+ account_id: str,
373
+ checkout_id: str,
374
+ scenario_id: str,
375
+ idempotency_key: str,
376
+ ) -> dict[str, Any]:
377
+ _require_transaction(connection)
378
+ checkout = checkout_for_owner(connection, account_id, checkout_id)
379
+ if (
380
+ checkout is None
381
+ or checkout["adapter"] != "local-sandbox"
382
+ or checkout["status"] == "CANCELLED"
383
+ or _IDEMPOTENCY_RE.fullmatch(idempotency_key) is None
384
+ ):
385
+ raise SupportPaymentError("local support checkout is unavailable")
386
+ if checkout["status"] == "COMPLETED":
387
+ return _finalize(connection, backend, checkout=checkout)
388
+ try:
389
+ attempt = backend.payments.attempt(
390
+ flow_id=checkout["flow_id"],
391
+ owner=account_id,
392
+ amount_minor=checkout["amount_minor"],
393
+ currency=checkout["currency"],
394
+ fingerprint=checkout["fingerprint"],
395
+ scenario_id=scenario_id,
396
+ idempotency_key=idempotency_key,
397
+ connection=connection,
398
+ )
399
+ if attempt["status"] == "APPROVED":
400
+ return _finalize(connection, backend, checkout=checkout)
401
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
402
+ raise SupportPaymentError("local sandbox payment was rejected") from exc
403
+ status = "DECLINED" if attempt["status"] == "DECLINED" else "PENDING"
404
+ connection.execute(
405
+ "UPDATE support_checkouts SET status=?,version=version+1,updated_at=? "
406
+ "WHERE checkout_id=?",
407
+ (status, _now(), checkout_id),
408
+ )
409
+ return {"result": str(attempt["status"]).casefold(), "replayed": False}
410
+
411
+
412
+ def _provider_flow_id(provider_snapshot: Mapping[str, Any]) -> str:
413
+ metadata = provider_snapshot.get("metadata")
414
+ flow_id = metadata.get("flow_id") if isinstance(metadata, Mapping) else None
415
+ if not isinstance(flow_id, str) or not flow_id.startswith("payflow_"):
416
+ raise SupportPaymentError("Stripe test Session metadata is invalid")
417
+ return flow_id
418
+
419
+
420
+ def process_verified_stripe_payment(
421
+ connection: sqlite3.Connection,
422
+ backend: SiteBackend,
423
+ *,
424
+ provider_session_id: str,
425
+ provider_snapshot: Mapping[str, Any],
426
+ expected_account_id: str | None = None,
427
+ ) -> dict[str, Any]:
428
+ """Verify and consume Stripe approval with the receipt transaction."""
429
+
430
+ _require_transaction(connection)
431
+ flow_id = _provider_flow_id(provider_snapshot)
432
+ row = connection.execute(
433
+ "SELECT * FROM support_checkouts WHERE flow_id=?", (flow_id,)
434
+ ).fetchone()
435
+ if row is None:
436
+ raise SupportPaymentError("Stripe support checkout is unavailable")
437
+ checkout = _public_checkout(row)
438
+ if (
439
+ checkout["adapter"] != "stripe-test"
440
+ or (expected_account_id is not None and checkout["account_id"] != expected_account_id)
441
+ or _STRIPE_SESSION_RE.fullmatch(provider_session_id) is None
442
+ ):
443
+ raise SupportPaymentError("Stripe support checkout is foreign or invalid")
444
+ if checkout["status"] == "COMPLETED":
445
+ receipt = connection.execute(
446
+ "SELECT receipt_id FROM support_receipts WHERE checkout_id=?",
447
+ (checkout["checkout_id"],),
448
+ ).fetchone()
449
+ metadata = provider_snapshot.get("metadata")
450
+ if (
451
+ receipt is None
452
+ or provider_snapshot.get("id") != provider_session_id
453
+ or provider_snapshot.get("livemode") is not False
454
+ or not isinstance(metadata, Mapping)
455
+ or metadata.get("site_id") != SITE_ID
456
+ or metadata.get("owner") != checkout["account_id"]
457
+ or str(metadata.get("amount_minor")) != str(checkout["amount_minor"])
458
+ or metadata.get("fingerprint") != checkout["fingerprint"]
459
+ ):
460
+ raise SupportPaymentError("Stripe replay facts do not match")
461
+ return _finalize(connection, backend, checkout=checkout)
462
+ try:
463
+ backend.payments.attempt_verified_stripe(
464
+ flow_id=flow_id,
465
+ owner=checkout["account_id"],
466
+ amount_minor=checkout["amount_minor"],
467
+ currency=checkout["currency"],
468
+ fingerprint=checkout["fingerprint"],
469
+ provider_session_id=provider_session_id,
470
+ idempotency_key=f"petfinder-stripe:{flow_id}:{provider_session_id}",
471
+ provider_verifier=lambda _session_id: provider_snapshot,
472
+ connection=connection,
473
+ )
474
+ connection.execute(
475
+ "UPDATE support_checkouts SET provider_session_id=?,updated_at=? "
476
+ "WHERE checkout_id=? AND (provider_session_id IS NULL OR provider_session_id=?)",
477
+ (
478
+ provider_session_id,
479
+ _now(),
480
+ checkout["checkout_id"],
481
+ provider_session_id,
482
+ ),
483
+ )
484
+ return _finalize(connection, backend, checkout=checkout)
485
+ except (PaymentConflict, PaymentError, PaymentRejected) as exc:
486
+ raise SupportPaymentError("Stripe test payment was rejected") from exc
487
+
488
+
489
+ __all__ = [
490
+ "CURRENCY",
491
+ "SUPPORT_TIERS",
492
+ "SupportPaymentError",
493
+ "checkout_for_owner",
494
+ "create_checkout",
495
+ "local_scenarios",
496
+ "payment_adapter",
497
+ "process_local_payment",
498
+ "process_verified_stripe_payment",
499
+ "public_support_tiers",
500
+ "receipt_for_owner",
501
+ "record_provider_session",
502
+ "stripe_preparation",
503
+ ]
tasks/petfinder/solution/site/implementation/clone/data/frozen-public-content-index.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/petfinder/solution/site/implementation/clone/data/frozen-public-media-index.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/petfinder/solution/site/implementation/clone/data/frozen-public-route-index.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/petfinder/solution/site/implementation/clone/harbor_entry.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebsiteBench Harbor foreground entrypoint for the frozen clone."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import uvicorn
10
+
11
+
12
+ ROOT = Path(__file__).resolve().parent
13
+ SITE_ROOT = ROOT.parent
14
+ RUNTIME = json.loads((SITE_ROOT / "backend" / "runtime.json").read_text(encoding="utf-8"))
15
+ SITE_ID = str(RUNTIME["site"]["id"])
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["WEBSITEBENCH_DATA_DIR"] = str(DATA_DIR)
22
+ os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(SITE_ROOT / "backend" / "runtime.json")
23
+ os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(DATA_DIR / RUNTIME["database"]["filename"])
24
+ if os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip():
25
+ os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor"
26
+ os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = "local-sandbox"
27
+
28
+ from app import app as clone_app # noqa: E402
29
+
30
+ HEALTH_BODY = b'{"status":"ok"}'
31
+ # /healthz is the contract (ADR-0010); the private path stays mounted
32
+ # so bundles frozen before the migration keep answering.
33
+ HEALTH_PATHS = ("/healthz", "/__websitebench/health")
34
+
35
+
36
+ async def application(scope, receive, send):
37
+ if scope.get("type") == "http" and scope.get("path") in HEALTH_PATHS:
38
+ await send({
39
+ "type": "http.response.start",
40
+ "status": 200,
41
+ "headers": [
42
+ (b"content-type", b"application/json"),
43
+ (b"content-length", str(len(HEALTH_BODY)).encode("ascii")),
44
+ (b"cache-control", b"no-store"),
45
+ ],
46
+ })
47
+ await send({"type": "http.response.body", "body": HEALTH_BODY})
48
+ return
49
+ await clone_app(scope, receive, send)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ uvicorn.run(
54
+ application,
55
+ host=os.environ["HOST"],
56
+ port=int(os.environ["PORT"]),
57
+ access_log=False,
58
+ timeout_graceful_shutdown=2,
59
+ )
tasks/petfinder/solution/site/implementation/clone/static/app.js ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Petfinder offline fixture - authored behavior.
2
+ Same-origin only; no remote requests, telemetry, live chat, or analytics. */
3
+
4
+ (function () {
5
+ "use strict";
6
+
7
+ function ready(fn) {
8
+ if (document.readyState !== "loading") { fn(); return; }
9
+ document.addEventListener("DOMContentLoaded", fn);
10
+ }
11
+
12
+ function focusables(root) {
13
+ return root.querySelectorAll(
14
+ 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), ' +
15
+ 'select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
16
+ );
17
+ }
18
+
19
+ function trapTab(event, root) {
20
+ if (event.key !== "Tab") { return; }
21
+ var nodes = focusables(root);
22
+ if (!nodes.length) { event.preventDefault(); root.focus(); return; }
23
+ var first = nodes[0];
24
+ var last = nodes[nodes.length - 1];
25
+ if (event.shiftKey && document.activeElement === first) {
26
+ event.preventDefault(); last.focus();
27
+ } else if (!event.shiftKey && document.activeElement === last) {
28
+ event.preventDefault(); first.focus();
29
+ }
30
+ }
31
+
32
+ function isPlainClick(event) {
33
+ return !event.metaKey && !event.ctrlKey && !event.shiftKey &&
34
+ !event.altKey && (!event.button || event.button === 0);
35
+ }
36
+
37
+ ready(function () {
38
+ var accountTrigger = document.querySelector(".account-menu-trigger");
39
+ var accountDrawer = document.getElementById("account-drawer");
40
+ var accountBackdrop = document.querySelector(".account-drawer-backdrop");
41
+ if (accountTrigger && accountDrawer && accountBackdrop) {
42
+ var accountClose = accountDrawer.querySelector(".account-drawer-close");
43
+ var openAccountDrawer = function () {
44
+ accountDrawer.hidden = false;
45
+ accountDrawer.setAttribute("aria-hidden", "false");
46
+ accountBackdrop.hidden = false;
47
+ accountTrigger.setAttribute("aria-expanded", "true");
48
+ document.body.classList.add("account-drawer-open");
49
+ (accountClose || accountDrawer).focus();
50
+ };
51
+ var closeAccountDrawer = function () {
52
+ accountDrawer.hidden = true;
53
+ accountDrawer.setAttribute("aria-hidden", "true");
54
+ accountBackdrop.hidden = true;
55
+ accountTrigger.setAttribute("aria-expanded", "false");
56
+ document.body.classList.remove("account-drawer-open");
57
+ accountTrigger.focus();
58
+ };
59
+ accountTrigger.addEventListener("click", openAccountDrawer);
60
+ accountDrawer.querySelectorAll("[data-account-drawer-close]").forEach(function (node) {
61
+ node.addEventListener("click", closeAccountDrawer);
62
+ });
63
+ accountBackdrop.addEventListener("click", closeAccountDrawer);
64
+ accountDrawer.addEventListener("keydown", function (event) { trapTab(event, accountDrawer); });
65
+ document.addEventListener("keydown", function (event) {
66
+ if (event.key === "Escape" && !accountDrawer.hidden) { closeAccountDrawer(); }
67
+ });
68
+ }
69
+
70
+ // The sign-in trigger is a real link. A plain click opens the captured
71
+ // dialog; modifier clicks and no-script browsing still use the page URL.
72
+ var signinTrigger = document.querySelector("[data-signin-dialog-trigger]");
73
+ var signinDialog = document.getElementById("signin-dialog");
74
+ var signinBackdrop = document.querySelector(".signin-dialog-backdrop");
75
+ if (signinTrigger && signinDialog && signinBackdrop) {
76
+ var signinClose = signinDialog.querySelector(".signin-dialog-close");
77
+ var openSignin = function () {
78
+ signinDialog.hidden = false;
79
+ signinBackdrop.hidden = false;
80
+ signinDialog.setAttribute("aria-hidden", "false");
81
+ signinTrigger.setAttribute("aria-expanded", "true");
82
+ document.body.classList.add("signin-dialog-open");
83
+ (signinClose || signinDialog).focus();
84
+ };
85
+ var closeSignin = function () {
86
+ signinDialog.hidden = true;
87
+ signinBackdrop.hidden = true;
88
+ signinDialog.setAttribute("aria-hidden", "true");
89
+ signinTrigger.setAttribute("aria-expanded", "false");
90
+ document.body.classList.remove("signin-dialog-open");
91
+ signinTrigger.focus();
92
+ };
93
+ signinTrigger.addEventListener("click", function (event) {
94
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { return; }
95
+ if (!isPlainClick(event)) { return; }
96
+ event.preventDefault(); openSignin();
97
+ });
98
+ signinDialog.querySelectorAll("[data-signin-dialog-close]").forEach(function (node) {
99
+ node.addEventListener("click", closeSignin);
100
+ });
101
+ signinBackdrop.addEventListener("click", closeSignin);
102
+ signinDialog.addEventListener("keydown", function (event) {
103
+ if (event.key !== "Tab") { return; }
104
+ trapTab(event, signinDialog);
105
+ });
106
+ document.addEventListener("keydown", function (event) {
107
+ if (event.key === "Escape" && !signinDialog.hidden) { closeSignin(); }
108
+ });
109
+ }
110
+
111
+ // Keep the feedback trigger separate from the sign-in dialog lifecycle.
112
+ var trigger = document.querySelector(".overlay-trigger");
113
+
114
+ var mobileTrigger = document.querySelector(".mobile-menu-trigger");
115
+ var mobileMenu = document.getElementById("mobile-menu");
116
+ var mobileBackdrop = document.querySelector(".mobile-menu-backdrop");
117
+ if (mobileTrigger && mobileMenu && mobileBackdrop) {
118
+ var mobileClose = mobileMenu.querySelector("[data-mobile-menu-close]");
119
+ var openMobileMenu = function () {
120
+ mobileMenu.hidden = false; mobileBackdrop.hidden = false;
121
+ mobileMenu.setAttribute("aria-hidden", "false");
122
+ mobileTrigger.setAttribute("aria-expanded", "true");
123
+ document.body.classList.add("mobile-menu-open");
124
+ (mobileClose || mobileMenu).focus();
125
+ };
126
+ var closeMobileMenu = function () {
127
+ mobileMenu.hidden = true; mobileBackdrop.hidden = true;
128
+ mobileMenu.setAttribute("aria-hidden", "true");
129
+ mobileTrigger.setAttribute("aria-expanded", "false");
130
+ document.body.classList.remove("mobile-menu-open");
131
+ mobileTrigger.focus();
132
+ };
133
+ mobileTrigger.addEventListener("click", openMobileMenu);
134
+ document.querySelectorAll("[data-mobile-menu-close]").forEach(function (node) {
135
+ node.addEventListener("click", closeMobileMenu);
136
+ });
137
+ mobileMenu.addEventListener("keydown", function (event) { trapTab(event, mobileMenu); });
138
+ document.addEventListener("keydown", function (event) {
139
+ if (event.key === "Escape" && !mobileMenu.hidden) { closeMobileMenu(); }
140
+ });
141
+ }
142
+
143
+ var footerGroups = document.querySelectorAll(".footer-group");
144
+ if (footerGroups.length) {
145
+ var compactFooter = window.matchMedia("(max-width: 760px)");
146
+ var syncFooterGroups = function () {
147
+ footerGroups.forEach(function (group) {
148
+ if (compactFooter.matches) {
149
+ group.removeAttribute("open");
150
+ } else {
151
+ group.setAttribute("open", "");
152
+ }
153
+ });
154
+ };
155
+ syncFooterGroups();
156
+ if (compactFooter.addEventListener) {
157
+ compactFooter.addEventListener("change", syncFooterGroups);
158
+ }
159
+ }
160
+
161
+ var homeSearchTrigger = document.querySelector("[data-home-search-trigger]");
162
+ var homeSearchLauncher = document.querySelector("[data-home-search-launcher]");
163
+ var homeSearchOverlay = document.getElementById("home-search-overlay");
164
+ if (homeSearchTrigger && homeSearchLauncher && homeSearchOverlay) {
165
+ var homeSearchOverlayInput = homeSearchOverlay.querySelector("[data-home-search-overlay-input]");
166
+ var homeSearchClose = homeSearchOverlay.querySelector("[data-home-search-close]");
167
+ var openHomeSearch = function () {
168
+ homeSearchOverlay.hidden = false;
169
+ homeSearchTrigger.setAttribute("aria-expanded", "true");
170
+ document.body.classList.add("home-search-open");
171
+ if (homeSearchOverlayInput) {
172
+ homeSearchOverlayInput.value = homeSearchTrigger.value;
173
+ homeSearchOverlayInput.focus();
174
+ }
175
+ };
176
+ var closeHomeSearch = function () {
177
+ if (homeSearchOverlayInput) { homeSearchTrigger.value = homeSearchOverlayInput.value; }
178
+ homeSearchOverlay.hidden = true;
179
+ homeSearchTrigger.setAttribute("aria-expanded", "false");
180
+ document.body.classList.remove("home-search-open");
181
+ homeSearchTrigger.focus();
182
+ };
183
+ homeSearchTrigger.addEventListener("click", openHomeSearch);
184
+ homeSearchTrigger.addEventListener("focus", openHomeSearch);
185
+ homeSearchLauncher.addEventListener("submit", function (event) {
186
+ if (homeSearchOverlay.hidden) { event.preventDefault(); openHomeSearch(); }
187
+ });
188
+ if (homeSearchClose) { homeSearchClose.addEventListener("click", closeHomeSearch); }
189
+ homeSearchOverlay.addEventListener("keydown", function (event) {
190
+ if (event.key === "Escape") { event.preventDefault(); closeHomeSearch(); return; }
191
+ trapTab(event, homeSearchOverlay);
192
+ });
193
+ }
194
+
195
+ // Every search control remains a normal GET field. This enhancement only
196
+ // applies immediately and announces progress; the Apply button remains.
197
+ var filterForm = document.querySelector("[data-search-filters]");
198
+ if (filterForm) {
199
+ var filterStatus = filterForm.querySelector("[data-filter-status]");
200
+ filterForm.addEventListener("change", function (event) {
201
+ var field = event.target;
202
+ if (!field || !field.name) { return; }
203
+ if (filterStatus) { filterStatus.textContent = "Updating results…"; }
204
+ filterForm.submit();
205
+ });
206
+ }
207
+
208
+ var filterDrawer = document.getElementById("search-filters");
209
+ var filterDrawerTrigger = document.querySelector(".filter-drawer-trigger");
210
+ var filterBackdrop = document.querySelector(".search-filter-backdrop");
211
+ if (filterDrawer && filterDrawerTrigger && filterBackdrop) {
212
+ var mobileFilters = window.matchMedia("(max-width: 760px)");
213
+ var syncFilterSemantics = function () {
214
+ if (mobileFilters.matches) {
215
+ filterDrawer.setAttribute("role", "dialog");
216
+ filterDrawer.setAttribute("aria-modal", "true");
217
+ filterDrawer.setAttribute(
218
+ "aria-hidden",
219
+ filterDrawer.classList.contains("is-open") ? "false" : "true"
220
+ );
221
+ } else {
222
+ filterDrawer.removeAttribute("role");
223
+ filterDrawer.removeAttribute("aria-modal");
224
+ filterDrawer.removeAttribute("aria-hidden");
225
+ }
226
+ };
227
+ var openFilters = function () {
228
+ filterDrawer.classList.add("is-open");
229
+ filterDrawer.setAttribute("aria-hidden", "false");
230
+ filterBackdrop.hidden = false;
231
+ filterDrawerTrigger.setAttribute("aria-expanded", "true");
232
+ document.body.classList.add("search-filter-open");
233
+ filterDrawer.focus();
234
+ };
235
+ var closeFilters = function () {
236
+ filterDrawer.classList.remove("is-open");
237
+ filterDrawer.setAttribute("aria-hidden", "true");
238
+ filterBackdrop.hidden = true;
239
+ filterDrawerTrigger.setAttribute("aria-expanded", "false");
240
+ document.body.classList.remove("search-filter-open");
241
+ filterDrawerTrigger.focus();
242
+ };
243
+ filterDrawerTrigger.setAttribute("aria-expanded", filterDrawer.classList.contains("is-open") ? "true" : "false");
244
+ syncFilterSemantics();
245
+ if (mobileFilters.addEventListener) {
246
+ mobileFilters.addEventListener("change", syncFilterSemantics);
247
+ }
248
+ filterDrawerTrigger.addEventListener("click", function (event) {
249
+ if (!mobileFilters.matches || !isPlainClick(event)) { return; }
250
+ event.preventDefault(); openFilters();
251
+ });
252
+ document.querySelectorAll("[data-filter-drawer-close]").forEach(function (node) {
253
+ node.addEventListener("click", function (event) {
254
+ if (!mobileFilters.matches || !isPlainClick(event)) { return; }
255
+ event.preventDefault(); closeFilters();
256
+ });
257
+ });
258
+ filterDrawer.addEventListener("keydown", function (event) { trapTab(event, filterDrawer); });
259
+ document.addEventListener("keydown", function (event) {
260
+ if (event.key === "Escape" && filterDrawer.classList.contains("is-open") && mobileFilters.matches) { closeFilters(); }
261
+ });
262
+ if (filterDrawer.classList.contains("is-open") && mobileFilters.matches) {
263
+ filterBackdrop.hidden = false;
264
+ document.body.classList.add("search-filter-open");
265
+ filterDrawer.focus();
266
+ }
267
+ }
268
+
269
+ var preferModal = document.querySelector("[data-prefer-local-modal]");
270
+ var preferBackdrop = document.querySelector(".prefer-local-backdrop");
271
+ if (preferModal && preferBackdrop) {
272
+ var preferReturn = document.querySelector("[data-prefer-local-trigger]") ||
273
+ document.querySelector(".filter-drawer-trigger");
274
+ preferModal.setAttribute("tabindex", "-1");
275
+ preferModal.setAttribute("aria-hidden", "false");
276
+ var closePreferModal = function () {
277
+ preferModal.hidden = true; preferBackdrop.hidden = true;
278
+ preferModal.setAttribute("aria-hidden", "true");
279
+ if (preferReturn) { preferReturn.setAttribute("aria-expanded", "false"); }
280
+ if (preferReturn) { preferReturn.focus(); }
281
+ };
282
+ preferModal.querySelectorAll("[data-prefer-local-close]").forEach(function (node) {
283
+ node.addEventListener("click", function (event) {
284
+ if (node.tagName === "A" && !isPlainClick(event)) { return; }
285
+ event.preventDefault(); closePreferModal();
286
+ });
287
+ });
288
+ preferBackdrop.addEventListener("click", closePreferModal);
289
+ preferModal.addEventListener("keydown", function (event) { trapTab(event, preferModal); });
290
+ document.addEventListener("keydown", function (event) {
291
+ if (event.key === "Escape" && !preferModal.hidden) {
292
+ closePreferModal();
293
+ }
294
+ });
295
+ preferModal.focus();
296
+ }
297
+
298
+ document.querySelectorAll("[data-cookie-close]").forEach(function (button) {
299
+ button.addEventListener("click", function () {
300
+ var notice = button.closest(".source-cookie-notice");
301
+ if (notice) { notice.hidden = true; }
302
+ });
303
+ });
304
+
305
+ var promo = document.querySelector(".purina-promo");
306
+ if (promo) {
307
+ promo.querySelectorAll(".promo-close, .promo-reminder").forEach(function (node) {
308
+ node.addEventListener("click", function (event) {
309
+ if (node.tagName === "A") { event.preventDefault(); }
310
+ promo.hidden = true;
311
+ });
312
+ });
313
+ }
314
+
315
+ var overlayTrigger = trigger;
316
+ var overlay = document.getElementById("fixture-overlay");
317
+ if (overlayTrigger && overlay) {
318
+ var overlayClose = overlay.querySelector(".overlay-close");
319
+ var openOverlay = function () {
320
+ overlay.hidden = false;
321
+ overlay.setAttribute("aria-hidden", "false");
322
+ overlayTrigger.setAttribute("aria-expanded", "true");
323
+ (overlayClose || overlay).focus();
324
+ };
325
+ var closeOverlay = function () {
326
+ overlay.hidden = true;
327
+ overlay.setAttribute("aria-hidden", "true");
328
+ overlayTrigger.setAttribute("aria-expanded", "false");
329
+ overlayTrigger.focus();
330
+ };
331
+ overlayTrigger.addEventListener("click", openOverlay);
332
+ if (overlayClose) { overlayClose.addEventListener("click", closeOverlay); }
333
+ overlay.addEventListener("keydown", function (event) { trapTab(event, overlay); });
334
+ document.addEventListener("keydown", function (event) {
335
+ if (event.key === "Escape" && !overlay.hidden) { closeOverlay(); }
336
+ });
337
+ }
338
+
339
+ document.querySelectorAll(".heart-button, .card-heart, .remove-favorite").forEach(function (heart) {
340
+ heart.addEventListener("click", function () {
341
+ heart.setAttribute("data-submitting", "true");
342
+ });
343
+ });
344
+
345
+ var gallery = document.querySelector("[data-profile-gallery]");
346
+ if (gallery) {
347
+ var galleryMain = gallery.querySelector("[data-gallery-main]");
348
+ var galleryThumbs = Array.prototype.slice.call(gallery.querySelectorAll("[data-gallery-thumb]"));
349
+ var galleryIndex = 0;
350
+ var selectGalleryPhoto = function (index) {
351
+ if (!galleryThumbs.length || !galleryMain) { return; }
352
+ galleryIndex = (index + galleryThumbs.length) % galleryThumbs.length;
353
+ galleryThumbs.forEach(function (thumb, thumbIndex) {
354
+ var active = thumbIndex === galleryIndex;
355
+ thumb.classList.toggle("is-active", active);
356
+ thumb.setAttribute("aria-pressed", active ? "true" : "false");
357
+ });
358
+ galleryMain.style.objectPosition = galleryThumbs[galleryIndex].getAttribute("data-object-position") || "center";
359
+ galleryThumbs[galleryIndex].scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" });
360
+ };
361
+ galleryThumbs.forEach(function (thumb, index) {
362
+ thumb.addEventListener("click", function () { selectGalleryPhoto(index); });
363
+ });
364
+ var galleryPrevious = gallery.querySelector("[data-gallery-previous]");
365
+ var galleryNext = gallery.querySelector("[data-gallery-next]");
366
+ if (galleryPrevious) { galleryPrevious.addEventListener("click", function () { selectGalleryPhoto(galleryIndex - 1); }); }
367
+ if (galleryNext) { galleryNext.addEventListener("click", function () { selectGalleryPhoto(galleryIndex + 1); }); }
368
+ }
369
+ });
370
+ })();
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/0116b8e561d20edaee354ad0f5054fc3211237a0ab6947f52ca309fe434edbcf.webp ADDED

Git LFS Details

  • SHA256: 0116b8e561d20edaee354ad0f5054fc3211237a0ab6947f52ca309fe434edbcf
  • Pointer size: 130 Bytes
  • Size of remote file: 81.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01622c41cd71d3b31760c8f9f7aa45f7f64f5b64e8db17bba331b98ed4ada5d9.webp ADDED

Git LFS Details

  • SHA256: 01622c41cd71d3b31760c8f9f7aa45f7f64f5b64e8db17bba331b98ed4ada5d9
  • Pointer size: 130 Bytes
  • Size of remote file: 34.8 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01688863ce4141423f972b065522476cad194770282ee47e0c68eb1f4c72570c.webp ADDED

Git LFS Details

  • SHA256: 01688863ce4141423f972b065522476cad194770282ee47e0c68eb1f4c72570c
  • Pointer size: 131 Bytes
  • Size of remote file: 107 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01afe71b59907bdf1f8bcf29506f16ad41ddd89e33304e0e0ac17b814fe27a48.webp ADDED

Git LFS Details

  • SHA256: 01afe71b59907bdf1f8bcf29506f16ad41ddd89e33304e0e0ac17b814fe27a48
  • Pointer size: 131 Bytes
  • Size of remote file: 140 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01d0579f1f823192f1fad382398b73c8745e92306a897bee89a330a5bc9b5be5.webp ADDED

Git LFS Details

  • SHA256: 01d0579f1f823192f1fad382398b73c8745e92306a897bee89a330a5bc9b5be5
  • Pointer size: 130 Bytes
  • Size of remote file: 29.9 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/01/01ee75e0035da5a527e3d25641994c9a1f02b2187f60b895427070cf0f797528.webp ADDED

Git LFS Details

  • SHA256: 01ee75e0035da5a527e3d25641994c9a1f02b2187f60b895427070cf0f797528
  • Pointer size: 130 Bytes
  • Size of remote file: 73.6 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/0551528a7e7cdd20764b5c70a65ccd71601c981644426fdd7c7405e0e786e36e.webp ADDED

Git LFS Details

  • SHA256: 0551528a7e7cdd20764b5c70a65ccd71601c981644426fdd7c7405e0e786e36e
  • Pointer size: 130 Bytes
  • Size of remote file: 48.2 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/057cb188076616bbf52a2bdad3e39854176ffb68c3e02615b66f73db8f462fd5.webp ADDED

Git LFS Details

  • SHA256: 057cb188076616bbf52a2bdad3e39854176ffb68c3e02615b66f73db8f462fd5
  • Pointer size: 130 Bytes
  • Size of remote file: 82 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/0584eb516c4e8dc4bc7f84368ea509704f2a8dbd41c1d70b10d52ea5c1aadb26.jpg ADDED

Git LFS Details

  • SHA256: 0584eb516c4e8dc4bc7f84368ea509704f2a8dbd41c1d70b10d52ea5c1aadb26
  • Pointer size: 130 Bytes
  • Size of remote file: 54.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/059ef98a3e106f6b8010956d1f293a6bcdf1630694bfcb3e1e4cf00275761b06.webp ADDED

Git LFS Details

  • SHA256: 059ef98a3e106f6b8010956d1f293a6bcdf1630694bfcb3e1e4cf00275761b06
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/05/05a0be34910b9dc1bd1e5e0f6fd819ce0234dc78c8707911def7fdf10a12f830.webp ADDED

Git LFS Details

  • SHA256: 05a0be34910b9dc1bd1e5e0f6fd819ce0234dc78c8707911def7fdf10a12f830
  • Pointer size: 130 Bytes
  • Size of remote file: 66.6 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/06096be7d33c2196b6c73363f0fd7d68efb47bd31b679323ea22b2f385e9c89d.webp ADDED

Git LFS Details

  • SHA256: 06096be7d33c2196b6c73363f0fd7d68efb47bd31b679323ea22b2f385e9c89d
  • Pointer size: 130 Bytes
  • Size of remote file: 38.1 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/060bb7f199faaf938baa691bef4a2045ddf980867480fca36b9bf3bde27809da.webp ADDED

Git LFS Details

  • SHA256: 060bb7f199faaf938baa691bef4a2045ddf980867480fca36b9bf3bde27809da
  • Pointer size: 130 Bytes
  • Size of remote file: 39 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/062b51f1cbd945e5b001ecc70ff71136e10c24496d428f63b7ba1b8336610ca8.webp ADDED

Git LFS Details

  • SHA256: 062b51f1cbd945e5b001ecc70ff71136e10c24496d428f63b7ba1b8336610ca8
  • Pointer size: 130 Bytes
  • Size of remote file: 50.6 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/06/065f632215925d10c28e0e04d38bcfbc7efb14554b94061574dcce2718d6a93a.webp ADDED

Git LFS Details

  • SHA256: 065f632215925d10c28e0e04d38bcfbc7efb14554b94061574dcce2718d6a93a
  • Pointer size: 130 Bytes
  • Size of remote file: 23.4 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e405dcf476d69ed5b530da11192bd36d26804417a85381001b67131b78e92ef.webp ADDED

Git LFS Details

  • SHA256: 0e405dcf476d69ed5b530da11192bd36d26804417a85381001b67131b78e92ef
  • Pointer size: 131 Bytes
  • Size of remote file: 123 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e41e2e86895a3c76e2df25ed2a8f6992804f826684db43fe835dff9aa6030ca.webp ADDED

Git LFS Details

  • SHA256: 0e41e2e86895a3c76e2df25ed2a8f6992804f826684db43fe835dff9aa6030ca
  • Pointer size: 130 Bytes
  • Size of remote file: 76.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e7b5d501da606e2aa533216fcce1f3fd92fcc936f0268a36d73cf2c1e8b6454.webp ADDED

Git LFS Details

  • SHA256: 0e7b5d501da606e2aa533216fcce1f3fd92fcc936f0268a36d73cf2c1e8b6454
  • Pointer size: 131 Bytes
  • Size of remote file: 112 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e7ccdc8e29cc1bd5872ec107f14b43f498f31a2f1328f3ef87860cece61c384.webp ADDED

Git LFS Details

  • SHA256: 0e7ccdc8e29cc1bd5872ec107f14b43f498f31a2f1328f3ef87860cece61c384
  • Pointer size: 131 Bytes
  • Size of remote file: 131 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0e84042c6f9c936419cd3eb15b6434dc4d9bcd949fdc99a29ac1336c63aa931d.webp ADDED

Git LFS Details

  • SHA256: 0e84042c6f9c936419cd3eb15b6434dc4d9bcd949fdc99a29ac1336c63aa931d
  • Pointer size: 130 Bytes
  • Size of remote file: 52 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0e/0ec22cb9496501ba1770c6aff4089b64c46a7cb66748443161ca437896be5dda.webp ADDED

Git LFS Details

  • SHA256: 0ec22cb9496501ba1770c6aff4089b64c46a7cb66748443161ca437896be5dda
  • Pointer size: 130 Bytes
  • Size of remote file: 56 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f34077d79acde3ffb91325acf5e6a001be9459806dfb656494037e4fc90cd38.webp ADDED

Git LFS Details

  • SHA256: 0f34077d79acde3ffb91325acf5e6a001be9459806dfb656494037e4fc90cd38
  • Pointer size: 130 Bytes
  • Size of remote file: 67.9 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f6a8a3756773ac8ca250916e7bb0d783e0fb592a62463a52af1f066eecbf5f7.webp ADDED

Git LFS Details

  • SHA256: 0f6a8a3756773ac8ca250916e7bb0d783e0fb592a62463a52af1f066eecbf5f7
  • Pointer size: 130 Bytes
  • Size of remote file: 36.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0f7a7fbe58afd74f43421b536eb0247116a9dfb04fbfca5c490633338defaaca.webp ADDED

Git LFS Details

  • SHA256: 0f7a7fbe58afd74f43421b536eb0247116a9dfb04fbfca5c490633338defaaca
  • Pointer size: 130 Bytes
  • Size of remote file: 43.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fc4b497202c05dc7c07321ba731b9842eadf4eae697b243e67183bf671c621f.webp ADDED

Git LFS Details

  • SHA256: 0fc4b497202c05dc7c07321ba731b9842eadf4eae697b243e67183bf671c621f
  • Pointer size: 130 Bytes
  • Size of remote file: 56.9 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fdd859840add212345a340d960846e587fa4cd4eacd0be59e6564f401b17e20.webp ADDED

Git LFS Details

  • SHA256: 0fdd859840add212345a340d960846e587fa4cd4eacd0be59e6564f401b17e20
  • Pointer size: 131 Bytes
  • Size of remote file: 122 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/0f/0fdf1e3e2be6c9065a895164d37ee93c8a00cdc6a10c0a653ee699f6654e6230.webp ADDED

Git LFS Details

  • SHA256: 0fdf1e3e2be6c9065a895164d37ee93c8a00cdc6a10c0a653ee699f6654e6230
  • Pointer size: 131 Bytes
  • Size of remote file: 120 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/13/13d8f89047bdeb9209be37e51f2d55fd2dbe2c8f8d3f3ccc84f87f4d043c2a68.webp ADDED

Git LFS Details

  • SHA256: 13d8f89047bdeb9209be37e51f2d55fd2dbe2c8f8d3f3ccc84f87f4d043c2a68
  • Pointer size: 130 Bytes
  • Size of remote file: 68 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/13/13f80b43c80d556b249ddb21482fe783a1e4490350698761e325a9d0134c6b4f.webp ADDED

Git LFS Details

  • SHA256: 13f80b43c80d556b249ddb21482fe783a1e4490350698761e325a9d0134c6b4f
  • Pointer size: 130 Bytes
  • Size of remote file: 12.2 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14517f64e26786607993dd204a06e925161edca4784f86510b1d0dc174d89a92.jpg ADDED

Git LFS Details

  • SHA256: 14517f64e26786607993dd204a06e925161edca4784f86510b1d0dc174d89a92
  • Pointer size: 130 Bytes
  • Size of remote file: 23.1 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/148e8d18ea5609bf650a8606d21a685021dac51e4fe5ada4fb6c17ace7078cb0.webp ADDED

Git LFS Details

  • SHA256: 148e8d18ea5609bf650a8606d21a685021dac51e4fe5ada4fb6c17ace7078cb0
  • Pointer size: 130 Bytes
  • Size of remote file: 32.8 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14aaef5a280cdab1624bb233c03fbff3ec60a8904f025cacaf61e8f6335e0d24.webp ADDED

Git LFS Details

  • SHA256: 14aaef5a280cdab1624bb233c03fbff3ec60a8904f025cacaf61e8f6335e0d24
  • Pointer size: 130 Bytes
  • Size of remote file: 37.5 kB
tasks/petfinder/solution/site/implementation/clone/static/assets/source-current/2026-08-03-public-optimized-v3/objects/14/14c1a735a2700bb8e54b4c06ddeee396e7041c4f744c281782c7ede1f3acdfbc.webp ADDED

Git LFS Details

  • SHA256: 14c1a735a2700bb8e54b4c06ddeee396e7041c4f744c281782c7ede1f3acdfbc
  • Pointer size: 130 Bytes
  • Size of remote file: 54.6 kB