portage-cli 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +98 -1
  3. data/README.md +88 -18
  4. data/lib/portage/cli/adapter_session.rb +34 -0
  5. data/lib/portage/cli/browser_import/importer.rb +1 -1
  6. data/lib/portage/cli/browser_import/plist_xml.rb +5 -12
  7. data/lib/portage/cli/browser_import/sqlite.rb +19 -25
  8. data/lib/portage/cli/browser_profile/cdp.rb +0 -9
  9. data/lib/portage/cli/buy.rb +217 -39
  10. data/lib/portage/cli/compare.rb +4 -3
  11. data/lib/portage/cli/confidence_check.rb +27 -7
  12. data/lib/portage/cli/confidence_state.rb +109 -0
  13. data/lib/portage/cli/find.rb +66 -9
  14. data/lib/portage/cli/generate/agent_profile.rb +1 -1
  15. data/lib/portage/cli/handoff_agents.rb +7 -21
  16. data/lib/portage/cli/handoff_reconciler.rb +2 -22
  17. data/lib/portage/cli/homepage_fetch.rb +5 -3
  18. data/lib/portage/cli/index/builder.rb +2 -11
  19. data/lib/portage/cli/index/known_cache.rb +9 -2
  20. data/lib/portage/cli/index/sources/stores_file.rb +2 -11
  21. data/lib/portage/cli/index/sources/wikidata.rb +2 -11
  22. data/lib/portage/cli/install_doctor.rb +2 -1
  23. data/lib/portage/cli/notifier.rb +16 -12
  24. data/lib/portage/cli/offer_sources.rb +3 -14
  25. data/lib/portage/cli/payment_methods.rb +7 -30
  26. data/lib/portage/cli/reconcile_notifier.rb +2 -5
  27. data/lib/portage/cli/setup_wizard/steps/env_keys_step.rb +40 -0
  28. data/lib/portage/cli/setup_wizard/steps/retailer_keys.rb +11 -23
  29. data/lib/portage/cli/setup_wizard/steps/search_keys.rb +10 -22
  30. data/lib/portage/cli/setup_wizard/steps/shipping.rb +5 -19
  31. data/lib/portage/cli/version.rb +1 -1
  32. data/lib/portage/cli.rb +25 -173
  33. metadata +5 -3
  34. data/lib/portage/cli/known_stores_url.rb +0 -15
@@ -9,6 +9,7 @@ require_relative "payment_methods"
9
9
  require_relative "setting"
10
10
  require_relative "decisions"
11
11
  require_relative "confidence_check"
12
+ require_relative "confidence_state"
12
13
  require_relative "checkout_handoff"
13
14
  require_relative "money"
14
15
  require_relative "notifier"
@@ -122,14 +123,18 @@ module Portage
122
123
  # hand off the real checkout first checks its total against this
123
124
  # (with `quote_currency:`) and reports `quote_changed` instead if it
124
125
  # is higher, in another currency, or missing. See #finish_checkout.
125
- # rubocop:disable Metrics/ParameterLists, Metrics/MethodLength -- all keywords; one per flag, plus
126
+ # @param quote_store [String, nil] the approved quote's store, and
127
+ # @param quote_title [String, nil] its title — set by `buy --quote`
128
+ # alongside quote_total:. Only the confidence check reads them: they
129
+ # go into its `approved_quote` (see #confidence_quote).
130
+ # rubocop:disable Metrics/ParameterLists, Metrics/MethodLength, Metrics/AbcSize -- all keywords; one per flag, plus
126
131
  # injectable collaborators, each assigned to its own ivar
127
132
  def initialize(url:, query:, qty: 1, payment_token: nil, yes: false, dry_run: false, product_id: nil,
128
133
  auto_open: nil, notify_webhook: nil, handoff_target: nil, confidence_check: nil,
129
134
  transaction_log: nil, max_price: nil, webmcp_bridge: nil, webmcp_mappings: nil,
130
135
  webmcp_mapping_confirm: nil, autofill: nil, webmcp_autofill_confirm: nil, json: false,
131
- quote_total: nil, quote_currency: nil)
132
- # rubocop:enable Metrics/ParameterLists, Metrics/MethodLength
136
+ quote_total: nil, quote_currency: nil, quote_store: nil, quote_title: nil)
137
+ # rubocop:enable Metrics/ParameterLists, Metrics/MethodLength, Metrics/AbcSize
133
138
  raw = url.to_s.strip
134
139
  @uri = URI.parse(raw =~ %r{\Ahttps?://}i ? raw : "https://#{raw}")
135
140
  @query = query
@@ -151,6 +156,8 @@ module Portage
151
156
  @json = json
152
157
  @quote_total = quote_total
153
158
  @quote_currency = quote_currency
159
+ @quote_store = quote_store
160
+ @quote_title = quote_title
154
161
  @webmcp_bridge = webmcp_bridge
155
162
  @decisions = {}
156
163
  end
@@ -510,7 +517,9 @@ module Portage
510
517
  # call it against. Builds a cart, reads it back through the (already
511
518
  # cart/checkout-capable, per the gate in #webmcp_flow) session so
512
519
  # #reconcile_checkout has a `get_cart`-shaped document to check against
513
- # (there's no checkout document either), then calls the preset's
520
+ # (there's no checkout document either), stops there if the quote cap,
521
+ # the mismatch check or the opt-in confidence check holds it
522
+ # (#webmcp_cart_held_report), and only then calls the preset's
514
523
  # `handoff_checkout` tool directly on the bridge — after the cart
515
524
  # read-back, not before, so any post-mutation "page not ready" gap
516
525
  # (see Transport's own retry) has already been waited out by then.
@@ -536,24 +545,84 @@ module Portage
536
545
  end
537
546
  return webmcp_handoff_dry_run_report(products, product, preset) if @dry_run
538
547
 
539
- created = session.create_cart(line_items: [{ product_id: line_item_id_of(product), quantity: @qty }],
540
- context: buyer_context, meta: agent_meta)
541
- cart = session.get_cart(cart_id: created["id"], meta: agent_meta)
542
- warnings = reconcile_checkout(product, cart)
548
+ @product = product
549
+ cart = webmcp_build_cart(session, product)
550
+ held = webmcp_cart_held_report(products, product, cart)
551
+ return held if held
543
552
 
544
553
  result = @webmcp_bridge.execute_tool(preset.handoff_checkout, {})
545
554
  autofill = attempt_webmcp_autofill(preset)
546
- webmcp_handoff_report("webmcp", products, cart.merge("continue_url" => url_from_handoff(result)), warnings,
555
+ webmcp_handoff_report("webmcp", products, cart.merge("continue_url" => url_from_handoff(result)), [],
547
556
  autofill: autofill)
548
557
  end
549
558
 
559
+ # The same gates #finish_checkout runs before anything leaves this
560
+ # process, in the same order, all before the hand-off tool sends the
561
+ # tab to checkout and before anything is autofilled: the quote cap,
562
+ # then the deterministic mismatch stop, then (only when a decision
563
+ # backend is enabled) the confidence check. The confidence check only
564
+ # sees a cart the first two let through, so it can hold this hand-off
565
+ # but never let through one they stop.
566
+ # @return [Hash, nil] the report for the first gate that held, or nil.
567
+ def webmcp_cart_held_report(products, product, cart)
568
+ warnings = reconcile_checkout(product, cart)
569
+ return quote_changed_report("webmcp", products, cart, warnings) if quote_exceeded?(cart)
570
+ return webmcp_cart_mismatch_report(products, cart, warnings) if warnings.any?
571
+
572
+ webmcp_low_confidence_report(products, cart)
573
+ end
574
+
575
+ # A hold here points at the store's cart page, like the mismatch stop:
576
+ # checkout was never opened, so there's nothing at a checkout URL yet.
577
+ def webmcp_low_confidence_report(products, cart)
578
+ verdict = decide_confidence(cart, [])
579
+ return nil if verdict.nil? || verdict[:proceed]
580
+
581
+ handoff_report("webmcp", products, cart.merge("continue_url" => webmcp_cart_page_url), [],
582
+ outcome: "low_confidence",
583
+ message: "#{low_confidence_message(verdict)} Checkout wasn't opened, and nothing was " \
584
+ "autofilled.")
585
+ end
586
+
587
+ # Adds the line to the store's cart, then reads the cart back.
588
+ def webmcp_build_cart(session, product)
589
+ created = session.create_cart(line_items: [{ product_id: line_item_id_of(product), quantity: @qty }],
590
+ context: buyer_context, meta: agent_meta)
591
+ session.get_cart(cart_id: created["id"], meta: agent_meta)
592
+ end
593
+
594
+ # Same fail-closed rule as #full_buy (see #decide_escalation): a cart
595
+ # that doesn't match the request stops here, before the hand-off tool
596
+ # sends the tab to checkout and before anything is autofilled. This
597
+ # flow used to only add the mismatch to `warnings` and carry on to
598
+ # checkout. The cart already exists on the store, so the report points
599
+ # at the store's cart page for the person to inspect, not at checkout.
600
+ # Every preset with a `handoff_checkout` tool today is Shopify's, where
601
+ # that page is /cart. A cart has no checkout status, so the verdict is
602
+ # the mismatch alone: `decisions.escalation.reason` is "mismatch", as
603
+ # on #full_buy's own stop.
604
+ def webmcp_cart_mismatch_report(products, cart, warnings)
605
+ @decisions[:escalation] = Decisions.escalation(checkout_status: nil, warnings: warnings)
606
+ handoff_report("webmcp", products, cart.merge("continue_url" => webmcp_cart_page_url), warnings,
607
+ outcome: "checkout_mismatch",
608
+ message: "Stopped before checkout — the store's cart didn't match the request: " \
609
+ "#{warnings.join(' ')} Nothing was bought, and checkout wasn't opened.")
610
+ end
611
+
612
+ def webmcp_cart_page_url
613
+ URI.join(@uri, "/cart").to_s
614
+ end
615
+
550
616
  # Unlike #full_buy's dry run (which still creates a UCP checkout, since
551
617
  # that's a document the store drops on its own), a dry run here stops
552
618
  # before `create_cart`: every step after it changes something outside
553
619
  # this process — a real cart on the store, the bridge's own tab
554
620
  # navigated to checkout, and (with autofill on) typing into that page.
555
621
  # None of that is safe to do on a preview run, so this only reports
556
- # what the run would have done. No checkout_id either, so History
622
+ # what the run would have done. That also means there's no cart to
623
+ # reconcile, so unlike #dry_run_report this can never carry
624
+ # `checkout_mismatch: true`; the real run checks the cart and stops
625
+ # there instead. No checkout_id either, so History
557
626
  # records it as a search, not a purchase.
558
627
  def webmcp_handoff_dry_run_report(products, product, preset)
559
628
  build_report(
@@ -764,6 +833,7 @@ module Portage
764
833
  message: no_match_message)
765
834
  end
766
835
 
836
+ @product = product
767
837
  checkout = session.create_checkout(line_items: [{ product_id: line_item_id_of(product), quantity: @qty }],
768
838
  fulfillment: requested_fulfillment(fulfillment_adapter),
769
839
  context: buyer_context, meta: agent_meta)
@@ -779,34 +849,78 @@ module Portage
779
849
  # (if surprising) checkout response, not a transport error. Buying
780
850
  # blind against a mismatch this method could have caught defeats the
781
851
  # point of an agent shopping on the buyer's behalf, so this always
782
- # checks and surfaces what it finds; PORTAGE_ABORT_ON_CHECKOUT_MISMATCH
783
- # additionally refuses to proceed rather than merely warning.
852
+ # checks, and any warning it returns stops a real purchase before
853
+ # payment (see #decide_escalation). The quoted total and currency are
854
+ # #quote_exceeded?'s job, not this method's.
855
+ #
856
+ # This is the authoritative check, and it always runs first: the
857
+ # opt-in model check (#decide_confidence) only ever sees a checkout
858
+ # that already passed it, and can hold that checkout but never
859
+ # overrule a warning from here.
784
860
  def reconcile_checkout(product, checkout)
785
861
  item_id = line_item_id_of(product)
786
- line = Array(checkout["line_items"]).find { |li| li.dig("item", "id") == item_id }
862
+ lines = Array(checkout["line_items"])
863
+ line = lines.find { |li| li.dig("item", "id") == item_id }
787
864
  return ["Store dropped the requested item (#{item_id}) from checkout."] unless line
788
865
 
789
866
  warnings = []
790
867
  if line["quantity"] != @qty
791
868
  warnings << "Store checked out quantity #{line['quantity']}, not the requested #{@qty}."
792
869
  end
870
+ warnings + price_mismatches(product, item_id, line, checkout["currency"]) +
871
+ unrequested_lines(lines.reject { |li| li.equal?(line) })
872
+ end
873
+
874
+ # Only one line is ever requested, so any other line is something the
875
+ # person never asked for: an upsell, a "shipping protection" add-on,
876
+ # or (on a WebMCP cart) whatever was already sitting in the store's
877
+ # cart. One that costs nothing is let through, so a store's free gift
878
+ # or $0 sample doesn't stop the purchase; one whose cost can't be read
879
+ # is treated as costing something, so it stops.
880
+ def unrequested_lines(extras)
881
+ extras.reject { |li| line_cost(li)&.zero? }.map do |li|
882
+ label = [li.dig("item", "id"), li.dig("item", "title")].compact.join(" ")
883
+ "Store added #{label.empty? ? 'a line' : label} to checkout, which wasn't requested."
884
+ end
885
+ end
886
+
887
+ # The line's own total, else its unit price times its quantity; nil
888
+ # when the line carries neither.
889
+ def line_cost(line)
890
+ total = Portage::Ucp::Support::Totals.amount(line["totals"])
891
+ return total if total.is_a?(Numeric)
892
+
893
+ price = line.dig("item", "price")
894
+ quantity = line["quantity"] || 1
895
+ price * quantity if price.is_a?(Numeric) && quantity.is_a?(Numeric)
896
+ end
897
+
898
+ # A unit price is only comparable in the catalog's own currency, so a
899
+ # checkout in another one is reported as that, not as a price change.
900
+ def price_mismatches(product, item_id, line, currency)
901
+ catalog_currency = expected_unit_currency(product, item_id)
902
+ if catalog_currency && currency && catalog_currency != currency
903
+ return ["Store checked out in #{currency}, not the catalog's #{catalog_currency}."]
904
+ end
793
905
 
794
906
  expected = expected_unit_price(product, item_id)
795
907
  actual = line.dig("item", "price")
796
- if expected && actual && expected != actual
797
- warnings << "Store priced the item at #{actual} #{checkout['currency']} minor units per unit, " \
798
- "not the catalog's #{expected}."
799
- end
800
- warnings
908
+ return [] unless expected && actual && expected != actual
909
+
910
+ ["Store priced the item at #{actual} #{currency} minor units per unit, not the catalog's #{expected}."]
801
911
  end
802
912
 
803
913
  def expected_unit_price(product, item_id)
804
- variant = Array(product["variants"]).find { |v| v["id"] == item_id }
805
- variant&.dig("price", "amount") || product.dig("price_range", "min", "amount")
914
+ expected_price_of(product, item_id)&.dig("amount")
806
915
  end
807
916
 
808
- def abort_on_mismatch?
809
- Setting.flag?(env: "PORTAGE_ABORT_ON_CHECKOUT_MISMATCH")
917
+ def expected_unit_currency(product, item_id)
918
+ expected_price_of(product, item_id)&.dig("currency")
919
+ end
920
+
921
+ def expected_price_of(product, item_id)
922
+ variant = Array(product["variants"]).find { |v| v["id"] == item_id }
923
+ variant&.dig("price") || product.dig("price_range", "min")
810
924
  end
811
925
 
812
926
  # Submits PORTAGE_SHIP_* (see Portage::Cli::ShippingProfile) as the
@@ -963,22 +1077,38 @@ module Portage
963
1077
  escalation = decide_escalation(checkout, warnings)
964
1078
  return escalated_report(source, products, checkout, warnings, escalation) if escalation[:escalate]
965
1079
  return dry_run_report(source, products, checkout, warnings) if @dry_run
966
- return webmcp_handoff_report(source, products, checkout, warnings) if force_handoff
1080
+ return webmcp_handoff_checkout_report(source, products, checkout, warnings) if force_handoff
967
1081
  return confirmation_needed_report(source, products, checkout, warnings) unless confirmed?
968
1082
 
969
1083
  complete(session, source, products, checkout, warnings)
970
1084
  end
971
1085
 
1086
+ # The non-preset WebMCP hand-off (`express_stop` through #full_buy). Same
1087
+ # last gate as #webmcp_handoff_checkout_flow's: with a decision backend
1088
+ # enabled, the confidence check runs before anything is handed off, on a
1089
+ # checkout the quote cap and the mismatch stop already let through. A
1090
+ # hold reports `low_confidence` pointing at the store's cart page, as the
1091
+ # preset flow's does, so nothing is sent to a `profile` target's checkout.
1092
+ # No backend named: straight to the hand-off, as before.
1093
+ def webmcp_handoff_checkout_report(source, products, checkout, warnings)
1094
+ webmcp_low_confidence_report(products, checkout) ||
1095
+ webmcp_handoff_report(source, products, checkout, warnings)
1096
+ end
1097
+
972
1098
  # First in #finish_checkout, ahead of the escalation gates: a
973
1099
  # `quote_changed` refusal never hands off, since that would spend the
974
1100
  # quote and open a checkout the person never approved. #complete is
975
1101
  # the only place this file charges, and it is reached only through
976
1102
  # #finish_checkout.
1103
+ #
1104
+ # A quote with no total (its dry run had none to show, as a WebMCP
1105
+ # preset dry run never does) caps nothing, so it refuses too, rather
1106
+ # than buying at whatever the store now asks.
977
1107
  def quote_exceeded?(checkout)
978
- return false unless @quote_total
1108
+ return false unless quote_run?
979
1109
 
980
1110
  total = checkout_total(checkout)
981
- total.nil? || total > @quote_total || checkout["currency"] != @quote_currency
1111
+ @quote_total.nil? || total.nil? || total > @quote_total || checkout["currency"] != @quote_currency
982
1112
  end
983
1113
 
984
1114
  def quote_changed_report(source, products, checkout, warnings)
@@ -990,6 +1120,11 @@ module Portage
990
1120
  end
991
1121
 
992
1122
  def quote_changed_message(total, currency)
1123
+ if @quote_total.nil?
1124
+ return "The quote has no total to hold this checkout (now #{quoted_amount(total, currency)}) to — " \
1125
+ "nothing was bought. Dry-run again for a priced quote."
1126
+ end
1127
+
993
1128
  "The price changed since the quote (was #{quoted_amount(@quote_total, @quote_currency)}, " \
994
1129
  "now #{quoted_amount(total, currency)}) — nothing was bought."
995
1130
  end
@@ -998,15 +1133,18 @@ module Portage
998
1133
 
999
1134
  # Hand off vs. keep going is Decisions.escalation's call
1000
1135
  # (docs/plans/system-one-decision-layer.md § Responsibilities 2): a
1001
- # literal `requires_escalation` status always escalates. A mismatch
1002
- # from #reconcile_checkout escalates only under
1003
- # PORTAGE_ABORT_ON_CHECKOUT_MISMATCH. By default the warnings are
1004
- # surfaced on the report, and the purchase is not stopped for them.
1136
+ # literal `requires_escalation` status always escalates, and so does
1137
+ # any mismatch from #reconcile_checkout, with no setting to turn that
1138
+ # off. This used to only warn unless PORTAGE_ABORT_ON_CHECKOUT_MISMATCH
1139
+ # was set, so by default a checkout that didn't match what the person
1140
+ # approved was still paid for and reported `purchased`. That variable
1141
+ # is now ignored. A --dry-run never pays, so there the mismatch stays
1142
+ # in `warnings` and #dry_run_report flags it instead, since an agent
1143
+ # needs the priced checkout to tell the person what went wrong.
1005
1144
  # The verdict lands on the report's `decisions:`, and the report's
1006
1145
  # `outcome:` names which gate (if any) stopped the purchase.
1007
1146
  def decide_escalation(checkout, warnings)
1008
- verdict = Decisions.escalation(checkout_status: checkout["status"],
1009
- warnings: abort_on_mismatch? ? warnings : [])
1147
+ verdict = Decisions.escalation(checkout_status: checkout["status"], warnings: @dry_run ? [] : warnings)
1010
1148
  @decisions[:escalation] = verdict
1011
1149
  verdict
1012
1150
  end
@@ -1129,17 +1267,48 @@ module Portage
1129
1267
  Portage::Ucp::Support::Totals.amount(checkout["totals"])
1130
1268
  end
1131
1269
 
1132
- # Never includes the payment token: the state goes to a model backend,
1133
- # which may be a hosted API (Jev).
1270
+ # Runs only on a checkout that already passed #reconcile_checkout, the
1271
+ # quote cap and the spend policy, so it can hold a purchase but never
1272
+ # let through one those would stop. The state is ConfidenceState's
1273
+ # allowlisted summary — never the payment token, the address or the
1274
+ # buyer's contact details — because it goes to a model backend that
1275
+ # may be a hosted third-party API (Jev).
1134
1276
  def decide_confidence(checkout, warnings)
1135
- verdict = confidence_check.call(
1136
- query: @query, merchant: @uri.host, quantity: @qty, warnings: warnings,
1137
- checkout: checkout.slice("id", "status", "currency", "line_items", "totals")
1138
- )
1277
+ return nil unless confidence_check.enabled?
1278
+
1279
+ verdict = confidence_check.call(confidence_state(checkout, warnings))
1139
1280
  @decisions[:confidence] = verdict if verdict
1140
1281
  verdict
1141
1282
  end
1142
1283
 
1284
+ def confidence_state(checkout, warnings)
1285
+ item_id = @product && line_item_id_of(@product)
1286
+ ConfidenceState.build(
1287
+ request: { query: @query, merchant: @uri.host, quantity: @qty, item_id: item_id,
1288
+ item_title: picked_title(item_id) },
1289
+ checkout: checkout, warnings: warnings, quote: confidence_quote
1290
+ )
1291
+ end
1292
+
1293
+ # The picked product's title from the store's own search, plus its
1294
+ # variant's when the checked-out variant has one ("Tee — Large").
1295
+ def picked_title(item_id)
1296
+ return nil unless @product
1297
+
1298
+ [@product["title"], variant_matching(@product, item_id)&.dig("title")].compact.uniq.join(" — ")
1299
+ end
1300
+
1301
+ # What `buy --quote` pinned, as the person approved it. nil on a run
1302
+ # with no quote.
1303
+ def confidence_quote
1304
+ return nil unless quote_run?
1305
+
1306
+ { store: @quote_store, product_id: @product_id, title: @quote_title, quantity: @qty,
1307
+ total: @quote_total, currency: @quote_currency }
1308
+ end
1309
+
1310
+ def quote_run? = !(@quote_store || @quote_total || @quote_currency).nil?
1311
+
1143
1312
  def confidence_check
1144
1313
  @confidence_check ||= ConfidenceCheck.new
1145
1314
  end
@@ -1410,9 +1579,18 @@ module Portage
1410
1579
  @yes
1411
1580
  end
1412
1581
 
1582
+ # `warnings` here are #reconcile_checkout's mismatches, which a real
1583
+ # run of the same checkout stops on — so the report says so up front,
1584
+ # before anyone approves a quote for it.
1413
1585
  def dry_run_report(source, products, checkout, warnings = [])
1414
- checkout_report(source, products, checkout, outcome: "dry_run", warnings: warnings,
1415
- message: "Dry run — checkout created but not completed.")
1586
+ message = "Dry run — checkout created but not completed."
1587
+ extra = {}
1588
+ if warnings.any?
1589
+ message += " It doesn't match the request (#{warnings.join(' ')}), so a real purchase would stop " \
1590
+ "with checkout_mismatch."
1591
+ extra[:checkout_mismatch] = true
1592
+ end
1593
+ checkout_report(source, products, checkout, outcome: "dry_run", warnings: warnings, message: message, **extra)
1416
1594
  end
1417
1595
 
1418
1596
  def confirmation_needed_report(source, products, checkout, warnings = [])
@@ -57,12 +57,13 @@ module Portage
57
57
  return report(message: "#{uri.host} is hand-off only — #{HandoffOnly::LEGAL_NOTICE}") \
58
58
  if @handoff_only.host?(uri.host)
59
59
 
60
- session = discover(origin_of(uri))
61
- return report(message: "#{origin_of(uri)} doesn't speak UCP.") unless session
60
+ origin = OfferSources.origin_of(uri.to_s)
61
+ session = discover(origin)
62
+ return report(message: "#{origin} doesn't speak UCP.") unless session
62
63
 
63
64
  wrapped = session.get_product(product_id: @origin_product_id)
64
65
  product = wrapped.is_a?(Hash) ? wrapped["product"] : nil
65
- return report(message: "Product #{@origin_product_id.inspect} not found at #{origin_of(uri)}.") unless product
66
+ return report(message: "Product #{@origin_product_id.inspect} not found at #{origin}.") unless product
66
67
 
67
68
  { host: uri.host, title: field(product, "title"), product: product }
68
69
  end
@@ -8,7 +8,9 @@ module Portage
8
8
  # § Responsibilities 3) as `portage buy` uses it: one yes/no question put
9
9
  # to a Decision::ModelBackends backend right before an unattended
10
10
  # (`--yes`) completion — "is this checkout what the shopper asked for,
11
- # and safe to complete without a person looking at it?"
11
+ # and safe to complete without a person looking at it?" Also asked
12
+ # before the WebMCP preset flow sends the browser to the store's
13
+ # checkout and autofills it (Buy#webmcp_cart_held_report).
12
14
  #
13
15
  # Default off. Nothing asks a model anything unless a backend is named,
14
16
  # via `--decision-backend NAME` or PORTAGE_DECISION_BACKEND (`jev` or
@@ -22,6 +24,16 @@ module Portage
22
24
  # purchase and hands the checkout to the shopper. It never
23
25
  # auto-approves anything `--yes` wouldn't already have allowed.
24
26
  #
27
+ # Additive only. Buy runs it after #reconcile_checkout's deterministic
28
+ # mismatch check, the quote cap and the spend policy, and only on a
29
+ # checkout all three let through, so a "yes" here can never let
30
+ # through a purchase one of those would stop. A "no" can only hold it.
31
+ #
32
+ # What it sends is ConfidenceState's allowlisted summary, never the
33
+ # raw checkout: no payment token, no address, no buyer contact
34
+ # details. #call JSON-encodes whatever state it is given, so a caller
35
+ # outside Buy has to build its state the same way.
36
+ #
25
37
  # Fails closed. An unknown backend name, a backend that isn't configured
26
38
  # (no JEV_API_KEY, no Laya bridge), or a backend call that fails all hold
27
39
  # the purchase, the same as a low score does. So does naming a backend
@@ -35,11 +47,18 @@ module Portage
35
47
  QUESTION = "safe_to_complete".freeze
36
48
  # Phrased so "yes" means "proceed": a noul answer's value is the
37
49
  # probability of yes, and that is what ConfidenceGate thresholds.
38
- INSTRUCTIONS = "The state is a checkout an agent built on a shopper's behalf: the shopper's search " \
39
- "query, the merchant, the requested quantity, the checkout's line items and totals, and " \
40
- "any warnings about where the checkout differs from the request. Answer yes only if the " \
41
- "checkout clearly matches what the shopper asked for and is safe to complete without a " \
42
- "person reviewing it first.".freeze
50
+ INSTRUCTIONS = "The state is a summary of a checkout an agent built on a shopper's behalf. `request` " \
51
+ "is what the shopper asked for: the search query, the store, the quantity, and the item " \
52
+ "picked from the store's search results. `approved_quote`, when present, is the exact " \
53
+ "purchase the shopper approved beforehand: store, product, title, quantity, total and " \
54
+ "currency. `checkout` is what the store is about to charge for: its line items (`requested` " \
55
+ "marks the line that was asked for), totals including any shipping, tax and fees, " \
56
+ "discounts and the selected shipping option. `warnings` lists differences an automatic " \
57
+ "check already found. Answer yes only if the checkout clearly matches the request and, " \
58
+ "when there is one, the approved quote: the same product (not a different model, size, " \
59
+ "bundle or subscription), the same quantity, no extra items, and a total with no " \
60
+ "surprising shipping, fees or other charges. Answer no if anything is unclear, missing " \
61
+ "or doesn't fit, or if the checkout would need a person to review it before paying.".freeze
43
62
 
44
63
  # @param backend [String, nil] a ModelBackends::REGISTRY key; nil
45
64
  # defers to PORTAGE_DECISION_BACKEND.
@@ -64,7 +83,8 @@ module Portage
64
83
 
65
84
  def enabled? = !@backend_name.nil?
66
85
 
67
- # @param state [Hash] JSON-serializable. Never pass it a payment token.
86
+ # @param state [Hash] JSON-serializable — ConfidenceState.build's
87
+ # output. Never a payment token, address or contact detail.
68
88
  # @return [Hash, nil] nil when disabled. Otherwise `proceed:`,
69
89
  # `reason:`, `confidence:`, `threshold:`, `backend:` and `error:`.
70
90
  # `reason` is nil when it proceeds, else why it held:
@@ -0,0 +1,109 @@
1
+ require "portage/ucp"
2
+
3
+ module Portage
4
+ module Cli
5
+ # The state ConfidenceCheck sends to its model backend, which may be a
6
+ # hosted third-party API (Jev, run by TypeSafe). Built from an allowlist:
7
+ # every field below is copied by name, and nothing else in the checkout
8
+ # hash is ever read. A store can put a buyer block, a shipping address,
9
+ # payment handlers or anything else on its checkout, and none of it
10
+ # reaches the backend, because this never copies a sub-hash wholesale.
11
+ #
12
+ # Never sent: the payment token (or any token reference), the shipping
13
+ # address and destinations, the buyer's name, phone or email, links and
14
+ # continue URLs, ids of the checkout itself, image URLs, discount codes,
15
+ # and anything read from the environment.
16
+ #
17
+ # Sent:
18
+ # - `request`: the search query, the store's host, the requested
19
+ # quantity, and the item id and title that were picked from the
20
+ # store's own search results.
21
+ # - `approved_quote` (only on `buy --quote`): the store, product id,
22
+ # title, quantity, total and currency the person approved.
23
+ # - `checkout`: its status and currency; each line's item id, title,
24
+ # unit price, quantity, line totals and whether it is the requested
25
+ # line; the checkout's totals (subtotal, shipping, tax, fees, total:
26
+ # whatever types the store sends); applied discounts' titles and
27
+ # amounts; and the title and price of each selected shipping option.
28
+ # - `warnings`: the deterministic check's warnings, if any.
29
+ #
30
+ # Strings are cut to MAX_STRING characters and anything that isn't a
31
+ # string, number, boolean or nil is dropped, so a store can't smuggle a
32
+ # nested object (or a very long prompt) in through a title.
33
+ module ConfidenceState
34
+ MAX_STRING = 200
35
+
36
+ module_function
37
+
38
+ # @param request [Hash] `query:`, `merchant:`, `quantity:`,
39
+ # `item_id:`, `item_title:`.
40
+ # @param checkout [Hash] a checkout or cart wire hash, string-keyed.
41
+ # @param warnings [Array<String>]
42
+ # @param quote [Hash, nil] `store:`, `product_id:`, `title:`,
43
+ # `quantity:`, `total:`, `currency:` — nil when the run has no
44
+ # approved quote.
45
+ # @return [Hash] JSON-serializable, string-keyed.
46
+ def build(request:, checkout:, warnings:, quote: nil)
47
+ state = { "request" => pick(request, %i[query merchant quantity item_id item_title]) }
48
+ state["approved_quote"] = pick(quote, %i[store product_id title quantity total currency]) if quote
49
+ state["checkout"] = checkout_summary(checkout, request[:item_id])
50
+ state["warnings"] = Array(warnings).map { |warning| scalar(warning.to_s) }
51
+ state
52
+ end
53
+
54
+ def checkout_summary(checkout, requested_id)
55
+ { "status" => scalar(checkout["status"]), "currency" => scalar(checkout["currency"]),
56
+ "line_items" => Array(checkout["line_items"]).map { |line| line_summary(line, requested_id) },
57
+ "totals" => totals_summary(checkout["totals"]),
58
+ "discounts" => discounts_summary(checkout["discounts"]),
59
+ "shipping" => shipping_summary(checkout["fulfillment"]) }
60
+ end
61
+
62
+ def line_summary(line, requested_id)
63
+ line = {} unless line.is_a?(Hash)
64
+ item = line["item"].is_a?(Hash) ? line["item"] : {}
65
+ { "item_id" => scalar(item["id"]), "title" => scalar(item["title"]), "unit_price" => scalar(item["price"]),
66
+ "quantity" => scalar(line["quantity"]), "totals" => totals_summary(line["totals"]),
67
+ "requested" => !requested_id.nil? && item["id"] == requested_id }
68
+ end
69
+
70
+ def totals_summary(totals)
71
+ hashes(totals).map { |total| { "type" => scalar(total["type"]), "amount" => scalar(total["amount"]) } }
72
+ end
73
+
74
+ def discounts_summary(discounts)
75
+ applied = discounts.is_a?(Hash) ? discounts["applied"] : nil
76
+ hashes(applied).map do |discount|
77
+ { "title" => scalar(discount["title"]), "amount" => scalar(discount["amount"]) }
78
+ end
79
+ end
80
+
81
+ # Only the options the checkout has selected — the price the person
82
+ # pays for shipping — never the destinations they're priced for.
83
+ def shipping_summary(fulfillment)
84
+ methods = fulfillment.is_a?(Hash) ? fulfillment["methods"] : nil
85
+ hashes(methods).flat_map { |method| hashes(method["groups"]) }.filter_map do |group|
86
+ option = hashes(group["options"]).find { |o| o["id"] == group["selected_option_id"] }
87
+ next unless option
88
+
89
+ { "title" => scalar(option["title"]),
90
+ "amount" => scalar(Portage::Ucp::Support::Totals.amount(hashes(option["totals"]))) }
91
+ end
92
+ end
93
+
94
+ def pick(hash, keys)
95
+ keys.to_h { |key| [key.to_s, scalar(hash[key])] }
96
+ end
97
+
98
+ def hashes(value) = Array(value).grep(Hash)
99
+
100
+ def scalar(value)
101
+ case value
102
+ when String then value[0, MAX_STRING]
103
+ when Integer, true, false, nil then value
104
+ when Float then value.finite? ? value : nil
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end