Architecture
The parts of Mend and where each runs, every PayPal call and who makes it, and three diagrams, of the whole system, of one campaign end to end and of the code modules.
Mend finds a small shop's regular customers who have gone quiet, using the shop's own order records, and sends each a thank-you cashback into their PayPal, after the owner approves. Only customers who joined the shop's thank-you list with Log in with PayPal can be paid. A random holdout group in every campaign gets nothing, so the lift is measured.
Codes such as C15 or C28 name the security rules in the threat model, where each one is written out with the code that enforces it.
Everything runs against the PayPal sandbox.
Parts
| Part | Where it runs | Job |
|---|---|---|
Web app (packages/web) | Render web service, mend-web | Pages, API routes, the webhook receiver, Join with PayPal, Claude. Never sends money. |
Engine (packages/engine) | Render private service, mend-engine | Scores customers, drafts campaigns, sends and cancels payouts. The only code that moves money (C1). |
| Database | Render Postgres 18, mend-db | Orders, members and consent, scores, campaigns, payouts, the audit log. |
Scheduled jobs (mend_engine.jobs) | Render cron job every 5 minutes, mend-jobs | Keeps payout status current and tidies stored PayPal data. |
| Operator scripts | A developer's machine | Deploy, seed the demo shop, run the proofs, run the local stack. |
| PayPal sandbox | PayPal | Payouts, Orders v2, balances, webhooks, Log in with PayPal, the hosted MCP server. |
| Read-only PayPal app | PayPal sandbox, same business account | A second app without Payouts, used only for the agent's four reads. |
| Claude Haiku 5.5 | Anthropic API | Reads the owner's goal, writes the notes, answers questions. Never picks an amount or a recipient (C4, C5, C11). |
| The dashboard's agents | The visitor's browser, on AG Studio | Answer questions about the dashboard and arrange that visitor's widgets. |
The dashboard's agents reach Claude through POST /api/studio/turn, one Claude call a round on counts of its own, and their tools cannot reach money (C20, C31).
Web app
- Next.js on Render (mend-web, Starter): the landing page at
/, the demo console at/demo, these docs at/docs, and API routes for sessions, campaigns and the agent. - Receives PayPal webhooks and checks each delivery's signature itself against PayPal's certificate chain. It never calls PayPal's verify API (C9). After storing a verified event it asks the engine to run process_events at once, without waiting for the answer.
- Calls the engine over Render's private network.
- Runs Join with PayPal (Log in with PayPal, sandbox): the confirmation page, the sign-in redirect and the callback.
- Reads PayPal orders, disputes and products for the agent through four read-only tools on PayPal's hosted MCP server, with identity fields stripped before Claude sees anything. These reads use the read-only app.
- If PayPal's MCP server fails with a setup error, cannot be reached or breaks the protocol, and at least 5 of the call's 15 seconds are left, the same four reads go straight to PayPal's REST API under the same rules. Each answer says which way it came.
Engine
- A Python task server on a Render private service (mend-engine, Starter), reachable only at
http://mend-engine:10000on Render's private network, behind a shared token (MEND_ENGINE_TOKEN). - Imports the shop's own order records and scores customers with BG/NBD.
- Builds campaign drafts in code: who is eligible, the random holdout, the amounts.
- Reads the shop's PayPal balance before every send and sends nothing below the floor (C20).
- Sends approved batches through Payouts, cancels unclaimed rewards on request, reconciles and refreshes payout status, and records purchases and attribution.
Database
- Render Postgres (mend-db, basic 256 MB, Postgres 18, virginia).
- Holds the shop's order records, members and consent, customer scores, campaigns and their snapshots, payout items, attribution, sessions, and an append-only audit log (C23).
Scheduled jobs
- A Render cron job (mend-jobs, Starter) every 5 minutes. It runs in Python straight against the database, never calls mend-engine and holds no engine token. Locally,
npm run dev:consoleruns the same command every 30 seconds. - purge runs first and deletes stored PayPal payloads at 47 hours, so none outlives 48 (C27).
- process_events re-reads each stored webhook's resource from PayPal and acts only on PayPal's answer (C10).
- reconcile settles campaigns whose batch outcome is unknown, without ever making a second batch (C3).
- refresh_items re-reads every unsettled payout item from PayPal after 15 minutes, so a lost webhook cannot leave the ledger stale.
- cancel_demo_unclaimed sends demo rewards still unclaimed after 10 minutes back to the shop.
Operator scripts
scripts/deploy/render.mjsbuilds and checks the Render setup and runs the live prove-it command.mend_engine.seed_demoimports the real dataset as the demo shop's order records.mend_engine.prove_*reproduce the published benchmark and run the backtest.packages/web/scriptshold the local stack (npm run dev:console).
PayPal and Claude
- PayPal sandbox: OAuth, Payouts, Orders v2, Reporting balances, Webhooks, Log in with PayPal, the hosted MCP server, and read-only Disputes and Catalog Products calls for the REST fallback. Only one proof script calls Transaction Search.
- The read-only app is a second sandbox app on the same business account, created without the Payouts permission. Its keys (
PAYPAL_READ_CLIENT_ID,PAYPAL_READ_CLIENT_SECRET) live on mend-web only. PayPal answers 403 when its token asks for a payout batch, so a leaked read token cannot pay anyone. When the pair is not set, the reads use the main app's keys. - Claude Haiku 5.5 reads the owner's goal into structured campaign settings, writes one note per customer, and answers the owner's questions through read-only tools.
Where each PayPal call lives:
| PayPal call | Caller | How |
|---|---|---|
POST /v1/oauth2/token | web, engine, jobs | REST, token cached until expires_in |
Transaction Search GET /v1/reporting/transactions | M1 proof script only (mend_engine.prove_m1) | Server SDK (Python). Used only by the M1 proof script today; no live task calls it. |
Payouts create POST /v1/payments/payouts | engine (submit), jobs (reconcile resend with the same sender_batch_id, C3) | REST |
| Payouts show batch and show item | engine (process_events), jobs (refresh_items, reconcile) | REST |
Payouts cancel unclaimed POST /v1/payments/payouts-item/{id}/cancel | engine (cancel_unclaimed task), jobs (cancel_demo_unclaimed) | REST, sent once and never retried in the same call |
Reporting balances GET /v1/reporting/balances | engine and jobs, before every send and resend | REST; nothing is sent when the batch, its fees and the floor (MEND_BALANCE_FLOOR_MINOR, USD 250 by default) do not fit, and a failed read counts as too low |
| Orders v2 create with PayPal's sandbox test card, and read | engine (simulate task), jobs (refresh_items), web agent (get_order fallback) | REST; the order is captured at once with no buyer login |
| Webhooks create, list, update event types | deploy script (render.mjs) | REST |
Webhook signing certificate https://api.sandbox.paypal.com/v1/notifications/certs/CERT-<id> | web | Downloaded only at that exact address, chained to a root Node ships, cached until it expires; the signature is checked in the app |
Log in with PayPal (/connect, /v1/oauth2/token, userinfo schema=paypalv1.1, then schema=openid only on a 404) | web | REST; scopes openid, email, paypalattributes |
PayPal's hosted MCP server, four read-only tools (get_order, list_disputes, get_dispute, show_product_details) | web agent, through mend-web's own server, with the read-only app's token | Mend's MCP client (paypal-mcp.ts) at mcp.sandbox.paypal.com; any other tool name is refused before a token is fetched, and each answer is rebuilt from listed fields with identity stripped before Claude sees it |
Direct REST fallback for the same four reads (GET /v2/checkout/orders/{id}, /v1/customer/disputes, /v1/customer/disputes/{id}, /v1/catalogs/products/{id}) | web agent (paypal-read.ts) | Only when the MCP server fails with a setup error, cannot be reached or breaks the protocol, with at least 5 seconds left; same inputs, host check, headers, 1 MB cap and rebuilt views; each answer is marked via paypal_mcp or via paypal_rest |
1. System overview
2. Main sequence: one campaign, end to end
3. Module dependencies
How the web calls the engine
Each task is one POST /tasks/<name> with the body {"args": [...]} and the x-mend-engine-token header, sent to MEND_ENGINE_URL (http://mend-engine:10000). The web refuses to send anything unless that address is plain http to a one-label host (a Render private network name: no dots, not an IP address, not localhost) with no path, query or userinfo, and the token is at least 32 printable characters. Redirects are refused, so the token cannot be carried to another host. The call runs in the background with a 120-second limit; the route answers with a run id, the run's state lives in an in-process run store (the latest 500 runs, none kept across a restart), and GET /api/runs/<id> polls it, answering only the session that started the run. A session has at most 2 engine calls in flight. An answer over 1 MB or of the wrong shape counts as a failed run (C12). The engine compares the token in constant time before it reads the path or body, runs at most 16 tasks at once (the five heavy reads share 6 of those slots), and answers 503 after 60 seconds without a free slot. mend-jobs does not use this path: it runs its five jobs in its own process. No service holds a Render API key.
The local stack
npm run dev:console in packages/web runs the whole product on one machine with real data and real sandbox payouts:
- A local Postgres (pgserver, from the engine's dev and test extras), with the demo shop in its own schema,
console_dev. The first run applies the schema and runsmend_engine.seed_demo, which downloads UCI Online Retail II, imports it and measures the model (131 seconds on 28 Oct). Later runs reuse it in a few seconds. - The engine's dev bridge on
127.0.0.1in place of mend-engine, behind a token made new for each run. python -m mend_engine.jobs allevery 30 seconds in place of mend-jobs. No PayPal webhook can reach the machine, so these runs read PayPal instead; locally they re-read a new batch's items after 45 seconds rather than 15 minutes (MEND_DEV_REFRESH_AFTER_SECONDS, honoured only in local development, never set on Render).next devon127.0.0.1, port 3001 unless--portsays otherwise, with the console at/demo.
It reads the repo's .env, prints no setting's value, and stops everything on Ctrl+C.
Open items
- Real return purchases are not attributed yet. The demo shop has no live storefront, so every return in the demo is a simulated sandbox purchase, labelled as simulated and kept out of the verdict. A production shop would match its own order record to the member first (
campaigns/attribution.py). - Rate counts live in one process's memory. Render runs one mend-web instance today; the counts would multiply if it scaled out (threat model, 26 Oct round 2).
- No live task uses Transaction Search. In an early sandbox test it still showed no rows 27 minutes after a payout, so it needs checking again before any task relies on it.
Every route the browser calls is on the API page.