From 6847bb956cbcf179ad493beec4a7113b63dd915f Mon Sep 17 00:00:00 2001 From: shaurya2k06 Date: Mon, 3 Aug 2026 02:28:29 +0530 Subject: [PATCH] Added Readme Signed-off-by: shaurya2k06 --- README.md | 265 ++++++++++++++++++++++++++++++++++++++++++++++-------- plan.md | 218 -------------------------------------------- 2 files changed, 230 insertions(+), 253 deletions(-) delete mode 100644 plan.md diff --git a/README.md b/README.md index 30735e6..91a907e 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,235 @@ # Cascade -sadsd -Cascade is an iMessage-native governed commerce kernel: message → purchase contract → verified -offer → Prava passkey → checkout → receipt. The TypeScript/PostgreSQL kernel is exposed through an -authenticated Fastify MCP v2 Streamable HTTP adapter and companion web surfaces. + +**From a message to a governed purchase, with the smallest safe agent topology.** + +Cascade is a governed commerce kernel for agentic buying. A natural-language request becomes an immutable purchase contract; Cascade verifies one offer against approved sources, obtains bounded passkey authority through [Prava](https://prava.space), completes checkout on a tested merchant path, and returns an auditable receipt to the originating conversation or client. + +Models propose. Deterministic code owns money and state. No search agent holds a wallet. No AI advances a financial state alone. + +The same kernel is reachable through the web companion, authenticated MCP tools, and optional messaging adapters. The distinguishing system is not retrieval — it is the purchase contract, evidence-backed offer normalization, capability narrowing, passkey-bound authority, exact checkout reconciliation, revocation, and audit trail. + +Full product and architecture specification: [`context.md`](context.md) + +--- + +## Install Cascade MCP + +Cascade exposes governed commerce as **MCP v2 Streamable HTTP**. External agents create missions, inspect offers, request spend, and read audit events **without** receiving Prava secrets, merchant credentials, or payment instruments. + +| | | +| --- | --- | +| **Endpoint** | `https://cascade-3mec.onrender.com/mcp` | +| **Local** | `http://127.0.0.1:3001/mcp` (when the API is running) | +| **Auth** | `Authorization: Bearer ` | + +The server stores **SHA-256 hashes only** (`MCP_AUTH_TOKENS_JSON`). Each token’s `audience` must exactly match `MCP_AUDIENCE` (e.g. `https://cascade-3mec.onrender.com/mcp`). Generate a hash without putting the raw token in config: + +```bash +export CASCADE_RAW_TOKEN='replace-with-a-long-random-token' +node -e "console.log(require('node:crypto').createHash('sha256').update(process.env.CASCADE_RAW_TOKEN).digest('hex'))" +unset CASCADE_RAW_TOKEN +``` + +Local Compose uses bearer `cascade-local-dev-token` (localhost only). Confirm health before connecting clients: `GET /health/mcp`. + +### Cursor + +`~/.cursor/mcp.json` (or Cursor MCP settings): + +```json +{ + "mcpServers": { + "cascade": { + "url": "https://cascade-3mec.onrender.com/mcp", + "headers": { + "Authorization": "Bearer " + } + } + } +} +``` + +For local development, point `url` at `http://127.0.0.1:3001/mcp` and use your local bearer. Reload MCP after saving. + +### Claude / ChatGPT + +Point a custom connector at `https:///mcp` with: + +```text +Authorization: Bearer +``` + +### Tool surface + +| Tool | Purpose | +| --- | --- | +| `mission.create` | Create a mission and immutable purchase contract v1 | +| `mission.get` | Read an authorized mission and financial state | +| `mission.get_diagnostics` | Redacted search status / diagnostics | +| `mission.get_offers` | Eligible offers before select / BUY | +| `mission.cancel` | Cancel; release reservations; revoke capabilities | +| `offers.submit` | Validate, normalize, and rank candidate offers | +| `offers.select` | Select one eligible offer bound to the active contract | +| `capability.issue` | Issue a revocable, contract-bound capability | +| `spend.request` | Reserve the selected offer (amounts re-derived server-side) | +| `payment.create_session` | Create a Prava sandbox payment session + checkout URL | +| `spend.get_status` | Reservation / payment / order state | +| `ledger.get_events` | Immutable audit sequence | +| `capture.create_marketplace_mission` | Sandbox marketplace capture → mission (no payment) | + +`spend.request` deliberately does not accept amount, currency, merchant, or product identity from the caller — those fields are rebound from the stored offer and active contract. + +### Programmatic client + +```bash +export CASCADE_MCP_ENDPOINT=https://cascade-3mec.onrender.com/mcp +export CASCADE_MCP_TOKEN= + +pnpm --filter @cascade/mcp-demo workflow:test -- \ + "Find red running shoes size 9 under INR 14000" +``` + +`@cascade/mcp-demo` wraps `@modelcontextprotocol/client` (Streamable HTTP) with typed helpers for the tools above. + +--- + +## The problem + +Online commerce is easy to browse and hard to decide. Buyers translate vague intent into search queries, compare incomplete totals, judge seller trust, re-enter constraints across sites, coordinate money with other people, and still leave the conversation to complete checkout — often without knowing what an AI assistant is actually allowed to spend. + +Shopping agents optimize retrieval. Payment products optimize transfer. Group planners optimize discussion. Cascade connects all three with explicit authority boundaries: + +1. **Intent becomes a contract.** +2. **Research becomes evidence-backed offers.** +3. **Authority becomes a bounded, revocable capability.** +4. **The purchase becomes a deterministic state machine.** +5. **The receipt returns to where the intent originated.** + +--- + +## Core principles + +### Smallest safe topology + +Cascade does not run a fixed multi-agent swarm. A deterministic router selects one of four execution modes: + +| Mode | When | +| --- | --- | +| **Solo** | Clear, low-risk, one-person purchase | +| **Guarded Cell** | Independent evidence or failure isolation improves the answer | +| **Shared Coordinator** | Open collaboration with shared context | +| **Federated Group** | Private budgets, vetoes, or external personal agents | + +A component is a separate agent only when it has a different owner, private context, independent authority, a trust boundary, fault containment needs, or speaks through MCP. “Price agent” and “review agent” are usually functions — not principals. + +### Deterministic systems own money and state + +Topology routing, contract versioning, policy, reservations, idempotency, Prava gateway, checkout state machine, revocation, and the audit log are **services**, never models. Models may extract intent, search, summarize evidence, or propose a ranking. Typed code validates every financial transition. + +### Honest commerce claims + +- Final price is confirmed at checkout, not inferred from search. +- Live price and availability come from the merchant path — not from knowledge grounding. +- A Prava payment session grants bounded purchase authority; it is **not** an order. +- “Works at any merchant” is forbidden; only tested adapters and verified Prava/UCP paths. +- Authorization is never silently overspent when a quote drifts. + +--- + +## Product modes + +| Mode | Behavior | +| --- | --- | +| **Buy Now** | One ask → verified recommendation (+ alternatives) → BUY → bounded Prava session → checkout → receipt | +| **Group Decision** | Private constraint capsules; coordinator sees only the minimum envelope for a feasible proposal | +| **Watch & Buy** | Arm a quote watch; notify or require a fresh passkey when conditions hold — never unbounded automation | +| **Cascade MCP** | External agents request governed commerce without holding credentials, policy engines, or checkout state | + +Signature path: + +> Find these red ASICS Gel-Kayano in size 9 under ₹14,000. Prefer delivery before Friday. + +Cascade returns one best valid offer, explains why it won, discloses material trade-offs, and presents BUY. Passkey approval scopes merchant and amount. Checkout runs through a tested path; the receipt and audit trail close the mission. + +--- + +## Architecture + +```text +Web companion · MCP clients · messaging adapters + │ + ▼ + ┌─────────────────────┐ + │ Cascade kernel │ + │ contracts · policy │ + │ ledger · topology │ + │ LangGraph orches. │ + └─────────┬───────────┘ + │ + ┌─────────────┼─────────────┐ + ▼ ▼ ▼ + Merchants Senso Prava + (quotes) (evidence) (passkey auth) +``` + +One TypeScript monorepo: Fastify API + worker, PostgreSQL ledger, LangGraph for durable orchestration, companion web for approval/audit/demo. Channels are adapters around the same domain services — MCP is the platform boundary, not a slide-only integration. + +| Layer | Stack | +| --- | --- | +| Surfaces | Web companion, Cascade MCP (Streamable HTTP), optional Linq messaging | +| Kernel | TypeScript, Fastify, LangGraph, Postgres | +| Commerce | Merchant adapters, Senso grounding, Prava REST / Prava MCP shopping | + +### Repository + +```text +apps/server API, Cascade MCP, worker +apps/web Landing, chat, demo, payment return +apps/mcp-demo External MCP client + workflow runners +packages/ + contracts Shared schemas and MCP tool catalog + domain Deterministic purchase / ledger kernel + agents Orchestration and intent extraction + db Migrations and Postgres access + integrations/ prava · senso · merchants · linq +``` + +--- + +## Outbound Prava MCP (shopping) + +Cascade’s **outbound** client to Prava shopping MCP is separate from the Cascade MCP server agents connect to. REST `sk_test_*` keys do not authorize Prava MCP. ```bash -corepack enable -pnpm install --frozen-lockfile -pnpm format:check -pnpm lint -pnpm typecheck -pnpm test -pnpm test:integration -pnpm build +pnpm --filter @cascade/prava mcp:login # one-time OAuth; paste PRAVA_MCP_* into env +pnpm --filter @cascade/prava mcp:refresh # access tokens expire ~10 minutes ``` -For the quickest local start, `docker compose up --build` runs PostgreSQL, migrations, and the API. -See [`build.md`](build.md) for environment variables, native commands, container operation, and -Render deploy notes. - -### What is implemented - -- **Kernel + MCP** — mission, offers, capability, spend, ledger tools with audience/scope enforcement -- **Discovery** — durable jobs, Senso evidence filtering, merchant adapters, Prava MCP shopping quotes, - OpenAI intent extraction, LangGraph workflow -- **Payments** — Prava REST sandbox sessions and Prava MCP payment sessions; `shop_checkout` stays - sandbox-gated until an approved Prava sandbox MCP hostname exists -- **Linq + web** — webhook ingress/outbox, companion mission/audit/payment-return pages, landing -- **Groups + watch** — private capsules, federated/shared coordinators, watch scheduling (mandate - auto-charge remains fail-closed) - -Public MCP (whendeployed): `https://cascade-3mec.onrender.com/mcp`. - -See [`plan.md`](plan.md) for ownership and Phase 7 launch gates. See -[`docs/LAUNCH_CHECKLIST.md`](docs/LAUNCH_CHECKLIST.md) for operator steps only you can do -(secrets, OAuth, Linq, live rehearsals). -sdaasda -a -sda \ No newline at end of file +Quote path: `shop_search → shop_product → shop_quote`. Keep `PRAVA_MCP_CHECKOUT_ENABLED=false` until an approved sandbox MCP hostname exists; hosted production MCP hosts are rejected for checkout. + +--- + +## Non-negotiables + +- SHA-256 of MCP bearer tokens only — never raw tokens in config or git. +- Provider secrets never appear in browser `VITE_*` vars or MCP responses. +- Authorization ≠ order; checkout and receipt are separate states. +- “Verified by Senso” means grounded in approved ingested sources — not a live-price oracle. +- Mandate auto-charge remains fail-closed until a tested provider contract exists. + +--- + +## Further reading + +| Document | Contents | +| --- | --- | +| [`context.md`](context.md) | Full product, architecture, contracts, demo scripts, judge Q&A | +| [`build.md`](build.md) | Environment variables, local/deploy runbooks, provider harnesses | +| [`docs/LAUNCH_CHECKLIST.md`](docs/LAUNCH_CHECKLIST.md) | Operator secrets, OAuth, live rehearsals | +| [`plan.md`](plan.md) | Ownership and phase gates | + +--- + +## License + +Private repository. All rights reserved unless otherwise noted. diff --git a/plan.md b/plan.md deleted file mode 100644 index ce3daeb..0000000 --- a/plan.md +++ /dev/null @@ -1,218 +0,0 @@ -# Cascade implementation plan - -`context.md` remains authoritative. This file only sequences the work after the -completed Phase 1 kernel and assigns every future task to one owner. - -## Ownership rule for future Codex sessions - -- The user is **Shantanav**. -- When Shantanav asks to implement a future phase, implement only the tasks marked **Shantanav**. -- Do not implement, edit, or silently absorb tasks marked **Shaurya** unless Shantanav explicitly - reassigns them. -- Shantanav-owned code may depend on a narrow typed interface or deterministic fake for a - Shaurya-owned component. Creating that boundary is allowed; implementing the real component is not. -- A phase is globally complete only after both owners' acceptance criteria pass. A Shantanav-only - session should report its side complete and list the remaining Shaurya handoff. -- Preserve the Phase 1 kernel invariants and keep all adapters thin around `CascadeKernel`. - -## Default file ownership - -| Owner | Areas | -|---|---| -| **Shantanav** | `apps/server`, shared contracts, domain/kernel changes, PostgreSQL, MCP transport, API security, jobs/outbox, Prava/payment/checkout, reconciliation, deployment, CI, backend integration tests | -| **Shaurya** | `apps/web`, model/LangGraph workflows, Senso, merchant discovery adapters, Linq conversation behavior, group-agent UX, product copy, evaluation datasets, demo experience | - -Component tests follow component ownership. Cross-owner changes require an explicit handoff or -reassignment before editing. - -## Phase 2 — Expose the kernel through MCP v2 and Fastify - -Goal: make the Phase 1 kernel callable through a secure server boundary using deterministic fakes. - -### Shantanav - -- Replace the native health skeleton with pinned Fastify and MCP v2 Streamable HTTP packages. -- Add runtime environment validation, database lifecycle, readiness, structured errors, and trace IDs. -- Derive authenticated principals from transport credentials; enforce audience, scope, mission access, - origin allowlisting, request limits, and rate limits. -- Expose coarse tools for mission create/get/cancel, offer submission/selection, capability issuance, - spend request/status, and audit events. -- Keep amount, currency, merchant, and product identity absent from the public spend input. -- Add REST read/status endpoints only where the future web adapter needs them; no duplicate business - rules outside `CascadeKernel`. -- Add MCP/Fastify contract tests against PostgreSQL and the existing deterministic fakes. - -### Shaurya - -- Build a minimal external MCP demo client and sanitized request/response fixtures. -- Define the initial mission/audit presentation payload needed by the later companion web app. -- Validate tool descriptions and error wording from an external-agent user's perspective. - -### Exit gate - -- An authenticated external client can run mission → offer → selection → reservation → cancellation - through MCP without provider credentials or raw financial primitives. -- Duplicate MCP commands remain idempotent and all Phase 1 tests stay green. - -## Phase 3 — Evidence, merchant offers, and orchestration - -Goal: replace offer fixtures with evidence-backed discovery while keeping ranking and money -deterministic. - -### Shantanav - -- Add durable PostgreSQL jobs and transactional outbox processing without Redis. -- Add persistence for adapter health, knowledge-source metadata, workflow attempts, and redacted trace - references where the master context requires it. -- Implement the server-side merchant capability registry and enforce supported-host/amount modes at - recommendation and spend boundaries. -- Provide typed interfaces and deterministic fakes for Senso, merchant quote providers, and workflow - execution. -- Add retry/idempotency policy and backend tests for job duplication, stale contract revisions, and - quote expiry during asynchronous work. - -### Shaurya - -- Implement the real Senso source registry, curated ingestion, search, citation filtering, and - freshness behavior. -- Implement tested merchant discovery/quote adapters; label unsupported merchants as handoff-only. -- Add structured intent extraction, search planning, evidence summaries, and the single LangGraph.js - orchestration framework. -- Implement Solo and Guarded Cell offer workflows using zero-spend scouts and the existing - deterministic eligibility/ranker. -- Create model/offer fixtures and evaluation cases for ambiguity, prompt injection, identity, policy, - and evidence quality. - -### Exit gate - -- A typed intent produces a live quoted, evidence-backed recommendation whose winner is still chosen - only by the Phase 1 ranker. -- Senso is never used as live price or inventory truth, and model output cannot mutate financial state. - -## Phase 4 — Prava authorization and tested checkout - -Goal: extend reservation into bounded authorization, checkout, receipt, and safe reconciliation. - -### Shantanav - -- Implement the Prava server gateway with pinned request/response schemas and redacted fixtures. -- Persist payment attempts before provider calls; serialize session creation and handle unknown - creation outcomes without blind retries. -- Implement server-side approval-result reconciliation and keep credentials out of storage, logs, - jobs, MCP, and model contexts. -- Implement the checkout saga, fresh quote validation, price-drift reapproval, execution claims, - payment/order transitions, receipt persistence, and provider outcome reporting. -- Implement unknown-order reconciliation, bounded retry/escalation, cancellation/revocation, and - transactional receipt outbox behavior. -- Add sandbox contract tests plus duplicate, timeout-after-submit, currency/merchant/product drift, - over-cap, decline, expiry, and unknown-order tests. - -### Shaurya - -- Build the approval return/status and receipt views in the companion web app. -- Add clear user-visible wording for reserved, awaiting approval, approved, ordering, confirmed, - failed, and unknown states. -- Maintain sanitized Prava sandbox/demo fixtures and verify that sandbox versus live status is visibly - disclosed. - -### Exit gate - -- One supported sandbox or live merchant path completes reservation → passkey authorization → checkout - → order receipt with no duplicate checkout. -- Authorization is never represented as an order, and unknown checkout is never automatically retried. - -## Phase 5 — Linq/iMessage and companion web adapter - -Goal: make iMessage the thin primary client of the completed commerce path. - -### Shantanav - -- Add raw-body Fastify webhook handling, Linq signature/timestamp verification, event inbox - deduplication, quick acknowledgement, and durable processing jobs. -- Add authenticated companion-web APIs, short-lived sessions, authorization checks, and redacted - mission/audit responses. -- Operate the outgoing message outbox with stable idempotency keys and lifecycle status tracking. -- Add backend contract tests for forged, duplicate, stale, reordered, and replayed events. -- Deploy the server/database worker topology with readiness checks and secret-safe configuration. - -### Shaurya - -- Implement the Linq SDK boundary, event normalization, direct/group routing, wake phrase, control - commands, onboarding, progress updates, recommendation, approval, failure, and receipt messages. -- Implement inbound-first link policy and text/media fallback without requiring a Messages extension. -- Build the mobile-first mission, audit, payment-return, join, privacy, terms, and demo web pages. -- Add conversation fixtures and end-to-end UX tests for message → recommendation → BUY → receipt. - -### Exit gate - -- The tested commerce journey begins and ends in a real Linq-backed conversation. -- Web and Linq remain adapters; neither contains independent financial rules. - -## Phase 6 — Private groups and Watch and Buy - -Goal: add independent principals and bounded scheduled execution only after the direct path is stable. - -### Shantanav - -- Implement participant-scoped encrypted capsule storage, key context binding, retention, and access - controls. -- Implement group membership authorization, immutable consensus-policy binding, vote persistence, and - audit events. -- Implement watch scheduling, one-lock-per-mission evaluation, mandate capability policy, execution - counters, pause/cancel/revoke, and fresh-quote enforcement. -- Keep mandate charging feature-gated until its exact Prava environment is contract-tested; otherwise - require a fresh passkey session. -- Add privacy/access-control, duplicate schedule, stale contract, mandate cap, and cancellation tests. - -### Shaurya - -- Implement private JOIN-by-DM onboarding, participant capsules, disclosure-safe envelopes, private - proposal evaluation, vetoes, and consensus workflows. -- Implement open-group Shared Coordinator behavior without unnecessary participant agents. -- Implement Watch and Buy conversation/web controls and explicit notify-versus-auto-buy behavior. -- Run the shared-agent versus federated privacy/latency/cost evaluation required by the master context. - -### Exit gate - -- Public collaborative groups route to Shared Coordinator; independent private principals route to - Federated Group. -- Private facts do not leave capsules beyond the approved envelope, and watch execution cannot exceed - its contract or mandate. - -## Phase 7 — Production hardening and launch - -Goal: verify the supported slice, deploy it, and make claims match evidence. - -### Shantanav - -- Add CI gates for frozen install, formatting, lint, strict typecheck, unit tests, PostgreSQL - integration tests, builds, migration review, and secret scanning. -- Complete threat-model review, dependency audit, authorization review, load/concurrency testing, - backup/restore rehearsal, reconciliation alerts, and operational runbooks. -- Deploy API and worker processes plus managed PostgreSQL; verify health, migrations, observability, - retention, and rollback. -- Run controlled end-to-end payment and failure rehearsals and retain trace/order evidence for every - live claim. - -### Shaurya - -- Complete the fixed intent/model evaluation set, multi-agent ablation, usability testing, demo - runbook, backup recording, judge dashboard, and product disclosure copy. -- Seed and verify the supported product category, merchants, Senso sources, Linq account, and demo - conversations. -- Prepare onboarding and pilot-user measurement for the first supported cohort. - -### Exit gate - -- The supported direct path and one failure path pass repeated rehearsals in the labeled environment. -- No claim implies universal merchants, atomic multi-payer checkout, live travel booking, or unbounded - autonomy. - -## Deferred until explicitly promoted - -- Native Messages extension. -- Atomic multi-payer checkout. -- Travel booking. -- Universal browser automation or “works at any merchant.” -- Additional orchestration frameworks. -- Blockchain, Redis, Kafka, Kubernetes, or separate Python services.