Skip to content

Latest commit

 

History

History
282 lines (222 loc) · 9.37 KB

File metadata and controls

282 lines (222 loc) · 9.37 KB

CredoCommerce — Application Flow

Version: 1.0


Overview

This document describes every significant user journey and system flow in CredoCommerce — from autonomous agent cycles to customer checkout to supplier verification. Flows are described narratively and with step-by-step sequences to guide implementation and QA.


Flow 1: Autonomous Product Discovery Loop

This flow runs continuously in the background, independent of any user action.

[Scheduler] fires every 15 min
     ↓
[Scout Agent] queries x402 API
     ↓
  For each product:
    Calculate margin score
    Fetch trend score
    margin >= 35% AND trend >= 7.0?
     ├── YES → INSERT into products (status: "draft")
     │         → Supabase Realtime fires event
     │         → [Merchandiser Agent] receives event
     │         → LLM generates title, description, price
     │         → UPDATE products (status: "published")
     │         → Product appears live on storefront
     └── NO  → Discard, log rejection reason

Expected Duration: Under 5 minutes from x402 API call to product live on storefront.

Visibility: Every step is written to agent_logs. Admin can watch in real time on /admin/scout and the main /admin bento grid.


Flow 2: Consumer Shopping Journey

2.1 Product Discovery

Consumer lands on / (Storefront)
  → Fetches published products from Supabase via TanStack Query
  → Infinite scroll / category filter renders products
  → Consumer browses /categories/[niche]
  → Clicks product → product detail page (SSG with ISR, revalidates every 60s)

2.2 Checkout

Consumer clicks "Buy Now" / "Add to Cart"
  → Cart state managed in Zustand (client-side)
  → Consumer enters email + shipping details
  → "Place Order" clicked
  → POST /api/orders
      → Creates row in orders table:
          { status: "pending", supplier_did: <from product>, customer_email: ... }
      → Returns order_id to consumer
  → Consumer sees "Order Confirmed" page with order_id and /track link
  → Supabase Realtime fires → [Logistics Agent] picks up new order

2.3 Order Tracking

Consumer visits /track?order_id=xxx
  → GET /api/orders/:id (requires customer_email match)
  → Fetches order status from DB
  → Status is one of:
      "pending"      → "We've received your order"
      "vc_requested" → "Verifying supplier credentials"
      "vc_verified"  → "Supplier verified ✓ — preparing shipment"
      "shipped"      → "Your order is on the way" + VC proof badge
      "vc_failed"    → "Verification issue — our team is reviewing"
  → If status = "shipped":
      → Display "Verified Provenance" badge
      → Link to full VC proof document (JSON-LD)

Flow 3: Zero-Trust Fulfillment Loop (Logistics Agent)

This is the most security-critical flow in the system.

Trigger: New order with status "pending" detected via Supabase Realtime

Step 1: DID Resolution
  → Logistics Agent reads supplier_did from order
  → Calls Universal Resolver → fetches DID Document
  → Extracts DIDComm service endpoint from DID Document

Step 2: VC Request
  → Agent constructs a Verifiable Presentation Request (VPR)
  → Sends VPR to supplier's DIDComm endpoint
  → Updates order status → "vc_requested"
  → Starts 30-second timeout timer

Step 3: VC Receipt and Verification
  → Supplier's wallet (or automated system) responds with Verifiable Presentation (VP)
  → Agent passes VP to DIDKit for cryptographic verification:
      ✓ Signature valid (matches supplier's public key in DID Document)
      ✓ Claims present: supplierLicense, productAuthenticity, shippingCapacity
      ✓ Credential not expired
      ✓ Credential not revoked (checks revocation registry)

Step 4a: PASS Path
  → Updates order → status: "vc_verified"
  → Calls escrow_release() → on-chain payment to supplier wallet
  → Supplier ships order
  → Updates order → status: "shipped"
  → Logs full VC metadata to agent_logs

Step 4b: FAIL Path
  → Updates order → status: "vc_failed"
  → Creates escalation record
  → Sends alert to admin dashboard (Supabase Realtime → UI toast)
  → Order enters manual review queue

Step 4c: TIMEOUT Path (no VP within 30s)
  → Updates order → status: "vc_timeout"
  → Admin alerted
  → Retries VC request after 5 minutes (max 3 retries)

Flow 4: Customer Support Interaction

Consumer opens Support Chat widget on storefront

Consumer types query (e.g., "Where is my order #12345?")

[Support Agent]:
  Step 1: Intent Classification
    → LLM classifies intent: "order_status_query"

  Step 2: Tool Dispatch
    → Calls order_lookup(order_id="12345", customer_email=session_email)
    → Supabase returns order row

  Step 3: Response Generation
    → LLM receives: order data + system prompt
    → Generates grounded, natural language response
    → Includes VC verification status if relevant

  Step 4: Delivery
    → Response streamed to consumer UI

Low confidence after 3 turns:
  → Agent calls escalate_to_human(order_id, reason)
  → Consumer shown "Connecting you with our team..." message
  → Escalation record created in DB

Flow 5: Supplier Onboarding

Supplier visits /onboard

Step 1: Registration
  → Supplier fills in: company name, email, product categories, wallet address
  → Clicks "Generate My DID"

Step 2: DID Generation
  → POST /api/suppliers/onboard
  → Backend uses DIDKit to generate a new did:key or did:web
  → DID Document created and stored
  → Supplier receives: DID string + private key (shown ONCE, must save)

Step 3: VC Issuance
  → CredoCommerce acts as VC Issuer
  → Issues a "SupplierCredential" VC signed with platform's DID
  → Claims: supplierLicense (mock/manual for v1), productCategories, walletAddress
  → VC delivered to supplier as JSON-LD download + optional DIDComm push

Step 4: Confirmation
  → Supplier DID and VC stored in supplier_profiles table
  → Supplier shown: "You're ready to receive orders from CredoCommerce"
  → Appearance in /admin/wallet Identity Ledger

Flow 6: Admin "God Mode" Dashboard

Admin logs in → /admin (protected route, NextAuth session)

Bento Grid loads:
  ├── Agent Status Panel
  │     → Live status (idle/running/error) for all 4 agents
  │     → Last run timestamp
  ├── Recent Agent Logs
  │     → Supabase Realtime subscription → live scroll of agent_logs
  ├── Products KPI
  │     → Total published / total drafted / published today
  ├── Orders KPI
  │     → Pending / vc_verified / shipped / failed
  ├── Revenue Estimate
  │     → Sum of (selling_price × shipped orders)
  └── Live Market Pulse (x402)
        → Top trending categories right now

Admin navigates to /admin/scout:
  → Chart: margin vs. trend score scatter plot (all scouted products today)
  → Table: x402 API raw results with filter/sort
  → Manual trigger: "Run Scout Now" button → POST /api/agents/scout/trigger

Admin navigates to /admin/wallet:
  → Identity & Escrow Ledger table:
      [Order ID | Supplier DID | VC Status | Payment Released | Timestamp]
  → Click any row → full VC payload viewer (JSON-LD)
  → Revoked credentials highlighted in red

Admin navigates to /admin/agents/[name]:
  → Agent Sandbox: custom prompt input, override parameters
  → "Run" button → executes agent with custom config
  → Live output stream in terminal-style panel

State Diagrams

Order Status States

           ┌─────────────┐
           │   pending   │  ← order created by consumer
           └──────┬──────┘
                  │ Logistics Agent picks up
                  ▼
        ┌──────────────────┐
        │  vc_requested    │  ← VPR sent to supplier DIDComm
        └────────┬─────────┘
                 │
        ┌────────┴────────────────┐
        ▼                         ▼
┌─────────────────┐      ┌──────────────────┐
│  vc_verified    │      │    vc_failed      │
│  (payment sent) │      │  (manual review)  │
└────────┬────────┘      └──────────────────┘
         │
         ▼
    ┌─────────┐
    │ shipped │  ← final consumer-visible state
    └─────────┘

Product Status States

[x402 API] → draft → published → (archived)
                           ↑
                   Merchandiser Agent

API Endpoint Summary

Method Path Description
GET /api/products Paginated published products
GET /api/products/:id Single product detail
POST /api/orders Create new order
GET /api/orders/:id Order status (requires email match)
POST /api/support/chat Support Agent message
POST /api/suppliers/onboard Supplier DID registration
POST /api/agents/:name/trigger Manually trigger agent (admin only)
GET /api/admin/logs Paginated agent logs (admin only)
GET /api/admin/ledger VC identity ledger (admin only)