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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
"""Etsy offline clone - persistent SQLite layer (stage: backend, R3).

Owns the schema_migrations ledger, WAL configuration, the frozen seed
corpus, and the server-side price computation.

Data directory contract: CLAWBENCH_DATA_DIR (default: <site>/data, always
outside the candidate root clone/). The canonical database file is
websitebench-etsy.sqlite3.

Fidelity-first, decoupled from tasks: the schema and seed model generic
source-site behavior (sellers/shops, listings, variation axes + per-option
price data, per-combination prices and availability, per-listing
personalization rules, buyer accounts, session-scoped carts, account-owned
favorites). No benchmark task constant is validated for or branched on
anywhere; benchmark personalization values are ordinary inputs.

Duplicate-add policy (documented, applied generically): adding an identical
(listing, full variation tuple, personalization) line to the same cart
MERGES by summing quantities, capped by the per-listing maximum. This
mirrors the source site's cart merge behavior for identical configurations.
"""

from __future__ import annotations

import json
import hashlib
import os
import re
import sqlite3
import uuid
from decimal import Decimal
from pathlib import Path

PACKAGE_ROOT = Path(__file__).resolve().parent
CLONE_ROOT = PACKAGE_ROOT.parent
SITE_ROOT = CLONE_ROOT.parent
EMBEDDED = SITE_ROOT / "source-current" / "2026-07-25" / "embedded-browser"
ASSET_WEB_ROOT = "/static/assets/source-current/2026-07-25"

DB_FILENAME = "websitebench-etsy.sqlite3"
LEGACY_DB_FILENAME = "etsy.sqlite3"
FROZEN_CLOCK = "2026-07-25T12:00:00-04:00"
CURRENT_LISTING_VERSION = "2026-07-25"
SCHEMA_HEAD = "0007"

PRICE_RE = re.compile(r"\$([0-9][0-9,]*\.[0-9]{2})")
CURATION_BADGE_MARKERS = ("candidate", "task 5", "semantic match", "family")
PLACEHOLDER_OPTION = "Select an option"

_PAGE_FILES = {
    "search-personalized-wallet": "search-personalized-wallet.json",
    "search-dog-collar": "search-dog-collar.json",
    "search-blue-vase": "search-blue-vase.json",
    "search-bookshelf": "search-bookshelf.json",
}

# The four captured search queries; results are served from DB rows.
SEARCH_QUERY_SEED = {
    "personalized leather wallet": "search-personalized-wallet",
    "personalized leather bifold wallet initials": "search-personalized-wallet",
    "custom dog collar": "search-dog-collar",
    "leather dog collar custom name embroidery medium sized dog": "search-dog-collar",
    "blue ceramic vase": "search-blue-vase",
    "handmade blue ceramic flower vase": "search-blue-vase",
    "wooden bookshelf": "search-bookshelf",
    "mid century modern wooden bookshelf": "search-bookshelf",
}

_WALLET_ID = "870439619"
_COLLAR_ID = "839355276"
_VASE_ID = "4526658048"
_BOOKSHELF_ID = "1801448610"

# Fixture-authored seller identities: the 2026-07-25 capture surfaced only a
# "Made by seller" badge, never a shop name, so these synthetic shop records
# are fixture-authored, not Etsy source facts.
SELLERS = [
    ("fixture-seller-wallet", "Fixture Leather Studio (synthetic)"),
    ("fixture-seller-collar", "Fixture Collar Works (synthetic)"),
    ("fixture-seller-vase", "Fixture Ceramics Shed (synthetic)"),
    ("fixture-seller-bookshelf", "Fixture Woodshop (synthetic)"),
    ("fixture-seller-corpus", "Fixture Marketplace Sellers (synthetic)"),
]

# Synthetic local buyer accounts; never production credentials.
ACCOUNTS = [
    ("alex", "alex-green-fixture", "Alex Green (synthetic)"),
    ("jordan", "jordan-lee-fixture", "Jordan Lee (synthetic)"),
]

# Fixture-authored collar size axis (the collar size axis was never directly
# captured; the option list is a generic small/medium/large ladder).
COLLAR_SIZE_OPTIONS = [PLACEHOLDER_OPTION, "Small", "Medium", "Large"]


def data_dir() -> Path:
    raw = os.environ.get("WEBSITEBENCH_DATA_DIR", "").strip()
    return Path(raw) if raw else SITE_ROOT / "data"


def db_path() -> Path:
    return data_dir() / DB_FILENAME


def connect(path: Path | str | None = None) -> sqlite3.Connection:
    selected = Path(path) if path is not None else db_path()
    selected.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(selected))
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA foreign_keys=ON")
    conn.execute("PRAGMA busy_timeout=5000")
    return conn


def combo_key(variations: dict[str, str]) -> str:
    """Canonical opaque key for a full variation tuple."""
    return json.dumps(
        {key: variations[key] for key in sorted(variations)},
        separators=(",", ":"),
        ensure_ascii=False,
    )


# --- migrations (legacy 0001-0004 preserved verbatim, head 0005) --------------


_SQL_0001_CORE_CATALOG = """
CREATE TABLE sellers (
  seller_id TEXT PRIMARY KEY,
  shop_name TEXT NOT NULL,
  provenance TEXT NOT NULL DEFAULT 'fixture-authored'
);
CREATE TABLE listings (
  listing_id TEXT PRIMARY KEY,
  seller_id TEXT NOT NULL REFERENCES sellers(seller_id),
  family TEXT NOT NULL,
  task TEXT,
  title TEXT NOT NULL,
  slug TEXT NOT NULL,
  price_now TEXT NOT NULL,
  price_original TEXT,
  base_price_cents INTEGER,
  image TEXT NOT NULL,
  badges_json TEXT NOT NULL DEFAULT '[]',
  cart_enabled INTEGER NOT NULL DEFAULT 0,
  favorites_focused INTEGER NOT NULL DEFAULT 0,
  version TEXT NOT NULL,
  stock_state TEXT NOT NULL DEFAULT 'in-stock'
);
CREATE TABLE listing_options (
  listing_id TEXT NOT NULL REFERENCES listings(listing_id),
  axis TEXT NOT NULL,
  position INTEGER NOT NULL,
  value TEXT NOT NULL,
  low_cents INTEGER,
  high_cents INTEGER,
  price_tier TEXT,
  selectable INTEGER NOT NULL DEFAULT 1,
  PRIMARY KEY (listing_id, axis, value)
);
CREATE TABLE search_pages (
  page_id TEXT PRIMARY KEY,
  title TEXT NOT NULL,
  cards_count INTEGER NOT NULL
);
CREATE TABLE search_cards (
  page_id TEXT NOT NULL REFERENCES search_pages(page_id),
  position INTEGER NOT NULL,
  listing_id TEXT NOT NULL,
  title TEXT NOT NULL,
  price_usd TEXT NOT NULL,
  slug TEXT NOT NULL,
  image TEXT NOT NULL,
  badges_json TEXT NOT NULL DEFAULT '[]',
  PRIMARY KEY (page_id, listing_id)
);
CREATE TABLE accounts (
  account_id TEXT PRIMARY KEY,
  owner_handle TEXT NOT NULL UNIQUE,
  display_name TEXT NOT NULL
);
"""

_SQL_0002_SESSIONS_AND_CART = """
CREATE TABLE sessions (
  session_id TEXT PRIMARY KEY,
  account_id TEXT REFERENCES accounts(account_id),
  created_at TEXT NOT NULL
);
CREATE TABLE cart_lines (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  owner_key TEXT NOT NULL,
  listing_id TEXT NOT NULL REFERENCES listings(listing_id),
  listing_version TEXT NOT NULL,
  engraving TEXT NOT NULL DEFAULT '',
  color TEXT NOT NULL DEFAULT '',
  size TEXT NOT NULL DEFAULT '',
  personalization TEXT NOT NULL DEFAULT '',
  quantity INTEGER NOT NULL,
  unit_price_cents INTEGER NOT NULL,
  created_at TEXT NOT NULL,
  UNIQUE (owner_key, listing_id, engraving, color, size, personalization, quantity)
);
"""

_SQL_0003_FAVORITES = """
CREATE TABLE favorites (
  account_id TEXT NOT NULL REFERENCES accounts(account_id),
  listing_id TEXT NOT NULL,
  created_at TEXT NOT NULL,
  PRIMARY KEY (account_id, listing_id)
);
"""


def _migrate_0004_opaque_line_tokens(conn: sqlite3.Connection) -> None:
    """Cart line ids become opaque server tokens (legacy rows backfilled)."""
    conn.execute("ALTER TABLE cart_lines ADD COLUMN line_token TEXT")
    rows = conn.execute(
        "SELECT id FROM cart_lines WHERE line_token IS NULL"
    ).fetchall()
    for row in rows:
        conn.execute(
            "UPDATE cart_lines SET line_token = ? WHERE id = ?",
            (uuid.uuid4().hex, row["id"]),
        )
    conn.execute(
        "CREATE UNIQUE INDEX IF NOT EXISTS idx_cart_lines_token "
        "ON cart_lines(line_token)"
    )


def _migrate_0005_generic_variation_model(conn: sqlite3.Connection) -> None:
    """Head migration: generic variation axes, per-combination prices and
    availability, per-listing personalization rules, per-listing quantity
    max, DB-driven search queries, and a generic cart line shape
    (variations_json instead of hardwired engraving/color/size columns).
    """
    conn.executescript(
        """
        DROP TABLE IF EXISTS listing_options;
        CREATE TABLE listing_axes (
          listing_id TEXT NOT NULL REFERENCES listings(listing_id),
          position INTEGER NOT NULL,
          axis_label TEXT NOT NULL,
          PRIMARY KEY (listing_id, axis_label)
        );
        CREATE TABLE listing_options (
          listing_id TEXT NOT NULL REFERENCES listings(listing_id),
          axis_label TEXT NOT NULL,
          position INTEGER NOT NULL,
          value TEXT NOT NULL,
          delta_cents INTEGER NOT NULL DEFAULT 0,
          selectable INTEGER NOT NULL DEFAULT 1,
          PRIMARY KEY (listing_id, axis_label, value)
        );
        CREATE TABLE listing_combo_prices (
          listing_id TEXT NOT NULL REFERENCES listings(listing_id),
          combo_key TEXT NOT NULL,
          unit_price_cents INTEGER NOT NULL,
          PRIMARY KEY (listing_id, combo_key)
        );
        CREATE TABLE listing_unavailable_combos (
          listing_id TEXT NOT NULL REFERENCES listings(listing_id),
          combo_key TEXT NOT NULL,
          reason TEXT NOT NULL DEFAULT 'unavailable',
          PRIMARY KEY (listing_id, combo_key)
        );
        CREATE TABLE listing_personalization (
          listing_id TEXT PRIMARY KEY REFERENCES listings(listing_id),
          enabled INTEGER NOT NULL DEFAULT 0,
          required INTEGER NOT NULL DEFAULT 0,
          char_limit INTEGER NOT NULL DEFAULT 256,
          prompt TEXT NOT NULL DEFAULT 'Add your personalization'
        );
        CREATE TABLE search_queries (
          query_norm TEXT PRIMARY KEY,
          page_id TEXT NOT NULL REFERENCES search_pages(page_id)
        );
        ALTER TABLE listings ADD COLUMN max_quantity INTEGER NOT NULL DEFAULT 10;
        CREATE TABLE cart_lines_v2 (
          line_token TEXT PRIMARY KEY,
          owner_key TEXT NOT NULL,
          listing_id TEXT NOT NULL REFERENCES listings(listing_id),
          listing_version TEXT NOT NULL,
          variations_json TEXT NOT NULL DEFAULT '{}',
          personalization TEXT NOT NULL DEFAULT '',
          quantity INTEGER NOT NULL,
          unit_price_cents INTEGER NOT NULL,
          created_at TEXT NOT NULL,
          updated_at TEXT NOT NULL,
          UNIQUE (owner_key, listing_id, variations_json, personalization)
        );
        """
    )
    legacy = conn.execute(
        "SELECT line_token, owner_key, listing_id, listing_version, engraving,"
        " color, size, personalization, quantity, unit_price_cents, created_at"
        " FROM cart_lines"
    ).fetchall()
    for row in legacy:
        variations: dict[str, str] = {}
        if row["engraving"]:
            variations["Engraving Options"] = row["engraving"]
        if row["color"]:
            variations["Colors"] = row["color"]
        if row["size"]:
            variations["Size"] = row["size"]
        conn.execute(
            "INSERT OR IGNORE INTO cart_lines_v2 (line_token, owner_key,"
            " listing_id, listing_version, variations_json, personalization,"
            " quantity, unit_price_cents, created_at, updated_at)"
            " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (
                row["line_token"] or uuid.uuid4().hex,
                row["owner_key"],
                row["listing_id"],
                row["listing_version"],
                combo_key(variations),
                row["personalization"],
                row["quantity"],
                row["unit_price_cents"],
                row["created_at"],
                row["created_at"],
            ),
        )
    conn.executescript(
        """
        DROP TABLE cart_lines;
        ALTER TABLE cart_lines_v2 RENAME TO cart_lines;
        """
    )


def _migrate_0006_command_authority(conn: sqlite3.Connection) -> None:
    """Add durable command replay and optimistic-version authority.

    The public forms never get to choose a price, owner, aggregate, or final
    version.  They may only present an idempotency key and an expected version;
    this journal lets the server atomically replay an exact retry, reject
    changed-payload key reuse, and serialize concurrent winners.
    """
    conn.executescript(
        """
        ALTER TABLE cart_lines ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
        ALTER TABLE favorites ADD COLUMN version INTEGER NOT NULL DEFAULT 1;
        CREATE TABLE business_commands (
          command_id TEXT PRIMARY KEY,
          capability TEXT NOT NULL,
          owner_scope TEXT NOT NULL,
          idempotency_key TEXT NOT NULL,
          payload_sha256 TEXT NOT NULL,
          result_json TEXT NOT NULL,
          created_at TEXT NOT NULL,
          UNIQUE (capability, owner_scope, idempotency_key)
        );
        CREATE TABLE entity_versions (
          capability TEXT NOT NULL,
          entity_key TEXT NOT NULL,
          version INTEGER NOT NULL,
          command_id TEXT NOT NULL REFERENCES business_commands(command_id),
          updated_at TEXT NOT NULL,
          PRIMARY KEY (capability, entity_key)
        );
        """
    )


def _migrate_0007_purchase_closure(conn: sqlite3.Connection) -> None:
    """Add owner-bound checkout and immutable order snapshots.

    The shared WebsiteBench runtime owns payment flows, attempts, and events.
    These site-local tables own only Etsy checkout/address/cart snapshots and
    the order committed when a matching shared approval is consumed.
    """
    conn.executescript(
        """
        CREATE TABLE checkouts (
          checkout_id TEXT PRIMARY KEY,
          account_id TEXT NOT NULL REFERENCES accounts(account_id),
          status TEXT NOT NULL CHECK (
            status IN ('pending-payment','payment-declined','payment-retry','completed','stale')
          ),
          currency TEXT NOT NULL CHECK (currency = 'USD'),
          item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0),
          shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0),
          tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
          total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
          cart_fingerprint TEXT NOT NULL,
          address_json TEXT NOT NULL,
          payment_flow_id TEXT,
          version INTEGER NOT NULL DEFAULT 1,
          created_at TEXT NOT NULL,
          updated_at TEXT NOT NULL,
          UNIQUE (account_id, cart_fingerprint)
        );
        CREATE TABLE checkout_lines (
          checkout_id TEXT NOT NULL REFERENCES checkouts(checkout_id) ON DELETE RESTRICT,
          position INTEGER NOT NULL,
          cart_line_token TEXT NOT NULL,
          listing_id TEXT NOT NULL,
          listing_version TEXT NOT NULL,
          title TEXT NOT NULL,
          slug TEXT NOT NULL,
          image TEXT NOT NULL,
          variations_json TEXT NOT NULL,
          personalization TEXT NOT NULL,
          quantity INTEGER NOT NULL CHECK (quantity > 0),
          unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
          subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
          PRIMARY KEY (checkout_id, position),
          UNIQUE (checkout_id, cart_line_token)
        );
        CREATE TABLE orders (
          order_id TEXT PRIMARY KEY,
          account_id TEXT NOT NULL REFERENCES accounts(account_id),
          checkout_id TEXT NOT NULL UNIQUE REFERENCES checkouts(checkout_id),
          payment_flow_id TEXT NOT NULL UNIQUE,
          status TEXT NOT NULL CHECK (status = 'paid'),
          currency TEXT NOT NULL CHECK (currency = 'USD'),
          item_total_cents INTEGER NOT NULL CHECK (item_total_cents >= 0),
          shipping_cents INTEGER NOT NULL CHECK (shipping_cents >= 0),
          tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
          total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
          address_json TEXT NOT NULL,
          placed_at TEXT NOT NULL
        );
        CREATE TABLE order_lines (
          order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT,
          position INTEGER NOT NULL,
          listing_id TEXT NOT NULL,
          listing_version TEXT NOT NULL,
          title TEXT NOT NULL,
          slug TEXT NOT NULL,
          image TEXT NOT NULL,
          variations_json TEXT NOT NULL,
          personalization TEXT NOT NULL,
          quantity INTEGER NOT NULL CHECK (quantity > 0),
          unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0),
          subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
          PRIMARY KEY (order_id, position)
        );
        CREATE TABLE order_events (
          event_id TEXT PRIMARY KEY,
          order_id TEXT NOT NULL REFERENCES orders(order_id) ON DELETE RESTRICT,
          event_type TEXT NOT NULL CHECK (event_type = 'order-created'),
          snapshot_json TEXT NOT NULL,
          created_at TEXT NOT NULL
        );
        CREATE INDEX checkouts_owner_status_idx
          ON checkouts(account_id, status, created_at);
        CREATE INDEX orders_owner_placed_idx
          ON orders(account_id, placed_at, order_id);
        CREATE TRIGGER order_events_no_update
        BEFORE UPDATE ON order_events
        BEGIN
          SELECT RAISE(ABORT, 'order events are immutable');
        END;
        CREATE TRIGGER order_events_no_delete
        BEFORE DELETE ON order_events
        BEGIN
          SELECT RAISE(ABORT, 'order events are immutable');
        END;
        UPDATE listings SET cart_enabled = 1 WHERE stock_state = 'in-stock';
        """
    )


MIGRATIONS: list[tuple[str, str, object]] = [
    ("0001", "core-catalog", _SQL_0001_CORE_CATALOG),
    ("0002", "sessions-and-cart", _SQL_0002_SESSIONS_AND_CART),
    ("0003", "favorites", _SQL_0003_FAVORITES),
    ("0004", "opaque-cart-line-tokens", _migrate_0004_opaque_line_tokens),
    ("0005", "generic-variation-model", _migrate_0005_generic_variation_model),
    ("0006", "command-authority-and-versions", _migrate_0006_command_authority),
    ("0007", "purchase-closure", _migrate_0007_purchase_closure),
]


def migrate(conn: sqlite3.Connection, target: str | None = None) -> list[str]:
    """Apply pending migrations up to target (default: head). Idempotent."""
    conn.execute(
        "CREATE TABLE IF NOT EXISTS schema_migrations ("
        "  version TEXT PRIMARY KEY,"
        "  name TEXT NOT NULL,"
        "  applied_at TEXT NOT NULL"
        ")"
    )
    applied = {
        row["version"]
        for row in conn.execute("SELECT version FROM schema_migrations")
    }
    newly_applied: list[str] = []
    for version, name, action in MIGRATIONS:
        if target is not None and version > target:
            break
        if version in applied:
            continue
        if callable(action):
            action(conn)
        else:
            conn.executescript(str(action))
        conn.execute(
            "INSERT INTO schema_migrations (version, name, applied_at) "
            "VALUES (?, ?, ?)",
            (version, name, FROZEN_CLOCK),
        )
        newly_applied.append(version)
    migration_count = int(
        conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0]
    )
    conn.execute(f"PRAGMA user_version = {migration_count}")
    conn.commit()
    return newly_applied


def applied_migrations(conn: sqlite3.Connection) -> list[str]:
    return [
        row["version"]
        for row in conn.execute(
            "SELECT version FROM schema_migrations ORDER BY version"
        )
    ]


# --- frozen seed corpus --------------------------------------------------------


def _load_capture(name: str) -> dict:
    return json.loads((EMBEDDED / name).read_text(encoding="utf-8"))


def _slug_from_href(href: str) -> str:
    return href.rstrip("/").rsplit("/", 1)[-1]


def _public_badges(badges: list[str]) -> list[str]:
    return [
        badge
        for badge in badges
        if not any(marker in badge.casefold() for marker in CURATION_BADGE_MARKERS)
    ]


def _cents(text: str) -> int:
    return int(Decimal(text.replace(",", "")) * 100)


def _parse_range_cents(label: str) -> tuple[int, int] | None:
    prices = PRICE_RE.findall(label)
    if not prices:
        return None
    return _cents(prices[0]), _cents(prices[-1])


def _seed_search_corpus(conn: sqlite3.Connection) -> dict[str, dict]:
    card_index: dict[str, dict] = {}
    for page_id, file_name in _PAGE_FILES.items():
        capture = _load_capture(file_name)
        conn.execute(
            "INSERT OR IGNORE INTO search_pages (page_id, title, cards_count) "
            "VALUES (?, ?, ?)",
            (page_id, capture["title"], capture["cards_count"]),
        )
        for position, raw in enumerate(capture["cards"]):
            listing_id = raw["listing_id"]
            if page_id == "search-personalized-wallet" and listing_id == _WALLET_ID:
                image = (
                    f"{ASSET_WEB_ROOT}/{page_id}/"
                    f"listing-{listing_id}-wallet-hero.jpg"
                )
            else:
                image = f"{ASSET_WEB_ROOT}/{page_id}/listing-{listing_id}-card.jpg"
            card = {
                "listing_id": listing_id,
                "title": raw["title"],
                "price_usd": raw["price_usd"],
                "slug": _slug_from_href(raw["href"]),
                "image": image,
                "badges": _public_badges(raw.get("badges", [])),
            }
            card_index.setdefault(listing_id, card)
            conn.execute(
                "INSERT OR IGNORE INTO search_cards "
                "(page_id, position, listing_id, title, price_usd, slug, "
                " image, badges_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    page_id,
                    position,
                    listing_id,
                    card["title"],
                    card["price_usd"],
                    card["slug"],
                    card["image"],
                    json.dumps(card["badges"]),
                ),
            )
    for query_norm, page_id in SEARCH_QUERY_SEED.items():
        conn.execute(
            "INSERT OR IGNORE INTO search_queries (query_norm, page_id) "
            "VALUES (?, ?)",
            (query_norm, page_id),
        )
    return card_index


def _seed_wallet(conn: sqlite3.Connection) -> None:
    """Seed the wallet listing exactly from the 2026-07-25 embedded-browser
    structural capture: variation axes, per-option price ranges, and the
    derived per-combination price grid.

    Grid derivation (data-driven, no option-name special-cases): every
    engraving option label carries a captured ($low - $high) range; a color
    whose own captured range starts at the listing base price resolves each
    engraving to its low bound, any other color to its high bound. This
    reproduces every captured range endpoint exactly.
    """
    capture = _load_capture("listing-personalized-wallet.json")
    price_now = capture["buy_box"]["price_now"]
    base_cents = _cents(PRICE_RE.findall(price_now)[0])
    quantity_options = []
    axes: list[tuple[str, list[str]]] = []
    for variation in capture["variations"]:
        if variation["label"] == "Quantity":
            quantity_options = list(variation["options"])
        else:
            axes.append((variation["label"], list(variation["options"])))
    max_quantity = max(int(value) for value in quantity_options) if quantity_options else 10

    conn.execute(
        "INSERT OR IGNORE INTO listings "
        "(listing_id, seller_id, family, task, title, slug, price_now, "
        " price_original, base_price_cents, image, badges_json, cart_enabled, "
        " favorites_focused, version, stock_state, max_quantity) "
        "VALUES (?, ?, 'wallet', '530', ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, "
        " 'in-stock', ?)",
        (
            _WALLET_ID,
            "fixture-seller-wallet",
            capture["h1"],
            _slug_from_href(capture["final_url"]),
            price_now,
            capture["buy_box"]["price_original"],
            base_cents,
            f"{ASSET_WEB_ROOT}/search-personalized-wallet/"
            f"listing-{_WALLET_ID}-wallet-hero.jpg",
            json.dumps(list(capture["buy_box"]["badges"])),
            CURRENT_LISTING_VERSION,
            max_quantity,
        ),
    )
    for axis_position, (label, options) in enumerate(axes):
        conn.execute(
            "INSERT OR IGNORE INTO listing_axes (listing_id, position, "
            "axis_label) VALUES (?, ?, ?)",
            (_WALLET_ID, axis_position, label),
        )
        for position, option in enumerate(options):
            conn.execute(
                "INSERT OR IGNORE INTO listing_options "
                "(listing_id, axis_label, position, value, delta_cents, "
                " selectable) VALUES (?, ?, ?, ?, 0, ?)",
                (
                    _WALLET_ID,
                    label,
                    position,
                    option,
                    0 if option == PLACEHOLDER_OPTION else 1,
                ),
            )

    # Per-combination price grid from the captured per-option ranges.
    axis_map = dict(axes)
    engraving_axis = "Engraving Options"
    color_axis = "Colors"
    engraving_ranges = {
        option: _parse_range_cents(option)
        for option in axis_map[engraving_axis]
        if option != PLACEHOLDER_OPTION
    }
    for color in axis_map[color_axis]:
        if color == PLACEHOLDER_OPTION:
            continue
        color_range = _parse_range_cents(color)
        resolves_low = color_range is not None and color_range[0] == base_cents
        for engraving, engraving_range in engraving_ranges.items():
            if engraving_range is None:
                continue
            unit = engraving_range[0] if resolves_low else engraving_range[1]
            conn.execute(
                "INSERT OR IGNORE INTO listing_combo_prices "
                "(listing_id, combo_key, unit_price_cents) VALUES (?, ?, ?)",
                (
                    _WALLET_ID,
                    combo_key({engraving_axis: engraving, color_axis: color}),
                    unit,
                ),
            )

    # Personalization: the capture shows a '+ Add personalization'
    # affordance separate from the variations (optional on the source
    # listing). Any text within the limit is accepted verbatim.
    conn.execute(
        "INSERT OR IGNORE INTO listing_personalization "
        "(listing_id, enabled, required, char_limit, prompt) "
        "VALUES (?, 1, 0, 256, 'Add personalization (engraving text)')",
        (_WALLET_ID,),
    )


def _seed_simple_listing(
    conn: sqlite3.Connection,
    card: dict,
    *,
    seller_id: str,
    family: str,
    task: str | None,
    cart_enabled: int = 1,
    favorites_focused: int = 0,
    max_quantity: int = 10,
) -> None:
    conn.execute(
        "INSERT OR IGNORE INTO listings "
        "(listing_id, seller_id, family, task, title, slug, price_now, "
        " price_original, base_price_cents, image, badges_json, cart_enabled, "
        " favorites_focused, version, stock_state, max_quantity) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 'in-stock', ?)",
        (
            card["listing_id"],
            seller_id,
            family,
            task,
            card["title"],
            card["slug"],
            f"${card['price_usd']}",
            _cents(card["price_usd"]),
            card["image"],
            json.dumps(card["badges"]),
            cart_enabled,
            favorites_focused,
            CURRENT_LISTING_VERSION,
            max_quantity,
        ),
    )


def seed(conn: sqlite3.Connection, *, commit: bool = True) -> None:
    """Insert the frozen corpus. Idempotent (INSERT OR IGNORE keyed rows)."""
    for seller_id, shop_name in SELLERS:
        conn.execute(
            "INSERT OR IGNORE INTO sellers (seller_id, shop_name, provenance) "
            "VALUES (?, ?, 'fixture-authored')",
            (seller_id, shop_name),
        )
    for account_id, owner_handle, display_name in ACCOUNTS:
        conn.execute(
            "INSERT OR IGNORE INTO accounts "
            "(account_id, owner_handle, display_name) VALUES (?, ?, ?)",
            (account_id, owner_handle, display_name),
        )

    card_index = _seed_search_corpus(conn)

    _seed_wallet(conn)

    # Dog collar: fixture-authored Size axis + required name personalization.
    _seed_simple_listing(
        conn,
        card_index[_COLLAR_ID],
        seller_id="fixture-seller-collar",
        family="collar",
        task="531",
        max_quantity=10,
    )
    conn.execute(
        "INSERT OR IGNORE INTO listing_axes (listing_id, position, axis_label) "
        "VALUES (?, 0, 'Size')",
        (_COLLAR_ID,),
    )
    for position, option in enumerate(COLLAR_SIZE_OPTIONS):
        conn.execute(
            "INSERT OR IGNORE INTO listing_options "
            "(listing_id, axis_label, position, value, delta_cents, "
            " selectable) VALUES (?, 'Size', ?, ?, 0, ?)",
            (_COLLAR_ID, position, option, 0 if option == PLACEHOLDER_OPTION else 1),
        )
    conn.execute(
        "INSERT OR IGNORE INTO listing_personalization "
        "(listing_id, enabled, required, char_limit, prompt) "
        "VALUES (?, 1, 1, 20, 'Name embroidery')",
        (_COLLAR_ID,),
    )

    # Favorites-focused fixtures are still purchasable: every in-stock detail
    # page exposes the same cart and Buy it now contract.
    _seed_simple_listing(
        conn,
        card_index[_VASE_ID],
        seller_id="fixture-seller-vase",
        family="vase",
        task="535",
        cart_enabled=1,
        favorites_focused=1,
    )
    _seed_simple_listing(
        conn,
        card_index[_BOOKSHELF_ID],
        seller_id="fixture-seller-bookshelf",
        family="bookshelf",
        task="536",
        cart_enabled=1,
        favorites_focused=1,
    )

    # Every other captured card becomes an ordinary listing row.
    for listing_id, card in card_index.items():
        _seed_simple_listing(
            conn,
            card,
            seller_id="fixture-seller-corpus",
            family="corpus",
            task=None,
            cart_enabled=1,
        )
    if commit:
        conn.commit()


def ensure_ready(path: Path | str | None = None) -> None:
    """Migrate to head and seed the frozen corpus if absent."""
    conn = connect(path)
    try:
        migrate(conn)
        seed(conn)
    finally:
        conn.close()


def drop_order_event_guards(conn: sqlite3.Connection) -> None:
    conn.execute("DROP TRIGGER IF EXISTS order_events_no_update")
    conn.execute("DROP TRIGGER IF EXISTS order_events_no_delete")


def install_order_event_guards(conn: sqlite3.Connection) -> None:
    conn.execute(
        """
        CREATE TRIGGER IF NOT EXISTS order_events_no_update
        BEFORE UPDATE ON order_events
        BEGIN
          SELECT RAISE(ABORT, 'order events are immutable');
        END
        """
    )
    conn.execute(
        """
        CREATE TRIGGER IF NOT EXISTS order_events_no_delete
        BEFORE DELETE ON order_events
        BEGIN
          SELECT RAISE(ABORT, 'order events are immutable');
        END
        """
    )


RESET_TABLE_ORDER = (
    "order_events",
    "order_lines",
    "orders",
    "checkout_lines",
    "checkouts",
    "entity_versions",
    "business_commands",
    "favorites",
    "cart_lines",
    "sessions",
    "listing_unavailable_combos",
    "listing_combo_prices",
    "listing_personalization",
    "listing_options",
    "listing_axes",
    "search_queries",
    "search_cards",
    "search_pages",
    "listings",
    "sellers",
    "accounts",
)


def reset(path: Path | str | None = None) -> dict:
    """Wipe all mutable and catalog state, then reseed the frozen corpus."""
    conn = connect(path)
    try:
        migrate(conn)
        cleared = {}
        drop_order_event_guards(conn)
        try:
            for table in RESET_TABLE_ORDER:
                cleared[table] = conn.execute(f"DELETE FROM {table}").rowcount
        finally:
            install_order_event_guards(conn)
        conn.commit()
        seed(conn)
        return {"cleared": cleared, "reseeded": True}
    finally:
        conn.close()


# --- server-side domain reads/writes used by the app --------------------------


def get_listing(conn: sqlite3.Connection, listing_id: str) -> sqlite3.Row | None:
    return conn.execute(
        "SELECT * FROM listings WHERE listing_id = ?", (listing_id,)
    ).fetchone()


def listing_axes(conn: sqlite3.Connection, listing_id: str) -> list[dict]:
    axes = []
    for axis in conn.execute(
        "SELECT axis_label, position FROM listing_axes WHERE listing_id = ? "
        "ORDER BY position",
        (listing_id,),
    ):
        options = conn.execute(
            "SELECT value, selectable FROM listing_options "
            "WHERE listing_id = ? AND axis_label = ? ORDER BY position",
            (listing_id, axis["axis_label"]),
        ).fetchall()
        axes.append(
            {
                "label": axis["axis_label"],
                "position": axis["position"],
                "field": f"variation{axis['position']}",
                "options": [
                    {"value": row["value"], "selectable": bool(row["selectable"])}
                    for row in options
                ],
            }
        )
    return axes


def personalization_config(
    conn: sqlite3.Connection, listing_id: str
) -> dict:
    row = conn.execute(
        "SELECT enabled, required, char_limit, prompt "
        "FROM listing_personalization WHERE listing_id = ?",
        (listing_id,),
    ).fetchone()
    if row is None:
        return {"enabled": False, "required": False, "char_limit": 0, "prompt": ""}
    return {
        "enabled": bool(row["enabled"]),
        "required": bool(row["required"]),
        "char_limit": row["char_limit"],
        "prompt": row["prompt"],
    }


def combo_unavailable(
    conn: sqlite3.Connection, listing_id: str, variations: dict[str, str]
) -> bool:
    row = conn.execute(
        "SELECT 1 FROM listing_unavailable_combos "
        "WHERE listing_id = ? AND combo_key = ?",
        (listing_id, combo_key(variations)),
    ).fetchone()
    return row is not None


def unit_price_cents(
    conn: sqlite3.Connection, listing_id: str, variations: dict[str, str]
) -> int:
    """Server-authoritative unit price: per-combination grid first, else
    base price plus per-option deltas. Client-posted prices are never read."""
    row = conn.execute(
        "SELECT unit_price_cents FROM listing_combo_prices "
        "WHERE listing_id = ? AND combo_key = ?",
        (listing_id, combo_key(variations)),
    ).fetchone()
    if row is not None:
        return row["unit_price_cents"]
    listing = get_listing(conn, listing_id)
    if listing is None:
        raise ValueError(f"unknown listing {listing_id}")
    total = listing["base_price_cents"] or 0
    for axis_label, value in variations.items():
        option = conn.execute(
            "SELECT delta_cents FROM listing_options "
            "WHERE listing_id = ? AND axis_label = ? AND value = ?",
            (listing_id, axis_label, value),
        ).fetchone()
        if option is not None:
            total += option["delta_cents"]
    return total


def payload_sha256(payload: dict[str, object]) -> str:
    encoded = (
        json.dumps(
            payload,
            ensure_ascii=False,
            separators=(",", ":"),
            sort_keys=True,
        )
        + "\n"
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


def prior_command(
    conn: sqlite3.Connection,
    *,
    capability: str,
    owner_scope: str,
    idempotency_key: str,
) -> sqlite3.Row | None:
    return conn.execute(
        "SELECT command_id, payload_sha256, result_json "
        "FROM business_commands WHERE capability = ? AND owner_scope = ? "
        "AND idempotency_key = ?",
        (capability, owner_scope, idempotency_key),
    ).fetchone()


def entity_version(
    conn: sqlite3.Connection,
    *,
    capability: str,
    entity_key: str,
) -> int:
    row = conn.execute(
        "SELECT version FROM entity_versions "
        "WHERE capability = ? AND entity_key = ?",
        (capability, entity_key),
    ).fetchone()
    return int(row["version"]) if row is not None else 0


def commit_command(
    conn: sqlite3.Connection,
    *,
    capability: str,
    owner_scope: str,
    idempotency_key: str,
    payload_digest: str,
    result: dict[str, object],
    entity_key: str,
    next_version: int,
) -> str:
    command_id = uuid.uuid4().hex
    conn.execute(
        "INSERT INTO business_commands "
        "(command_id, capability, owner_scope, idempotency_key, "
        "payload_sha256, result_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
        (
            command_id,
            capability,
            owner_scope,
            idempotency_key,
            payload_digest,
            json.dumps(result, ensure_ascii=False, separators=(",", ":"), sort_keys=True),
            FROZEN_CLOCK,
        ),
    )
    conn.execute(
        "INSERT INTO entity_versions "
        "(capability, entity_key, version, command_id, updated_at) "
        "VALUES (?, ?, ?, ?, ?) "
        "ON CONFLICT(capability, entity_key) DO UPDATE SET "
        "version = excluded.version, command_id = excluded.command_id, "
        "updated_at = excluded.updated_at",
        (capability, entity_key, next_version, command_id, FROZEN_CLOCK),
    )
    return command_id