# Wise Business OS — Architecture Validation Report

**Version:** 1.0-draft  
**Date:** 2026-07-16  
**Status:** Review required; no application implementation authorized

## Executive conclusion

The proposed direction is well matched to Wise Business OS if responsibilities are made explicit. Cloudflare Workers plus a TypeScript/React framework are suitable for the application edge and delivery layer; Supabase PostgreSQL is a strong choice for canonical transactional data; R2 fits files; Queues fit asynchronous work. Durable Objects should be introduced only for a demonstrated coordination problem.

The architecture is **conditionally recommended**, not yet ratified. Ratification requires the amendments and ADRs listed in this report—especially authentication/session enforcement, database access patterns, transactional outbox, environment strategy, data retention, backup recovery, and the exact boundary between the Next.js application and domain APIs.

## 1. Required amendments to the Product Foundation

### Platform Philosophy

Wise Business OS should make running a business feel calmer, not busier.

- Reduce clicks whenever practical.
- Prefer guidance over configuration.
- Show only what the current user needs.
- Automate repetitive work.
- Make complex operations feel simple without hiding consequences.
- Earn trust through transparency, previews, history, and recovery.
- Favor consistency over novelty.
- Default to secure choices.
- AI assists people; it does not silently take control.

### Product Success Metrics

Set initial service-level objectives during v0.1 after representative prototypes establish baselines.

| Area | Measure |
|---|---|
| UX | Median clicks/time to create customer, create pipeline, find customer, create task, book appointment, and provision workspace |
| Performance | p75/p95 initial render, navigation response, command-search response, API latency, background-job delay, automation step latency, AI first response and completion |
| Reliability | API success rate, queue retry/DLQ rate, job completion, webhook processing, deployment success, backup and restore verification |
| Security | Cross-tenant test pass rate, sensitive-action MFA coverage, unresolved critical findings, audit completeness |
| Quality | Escaped defect rate, accessibility conformance, flaky-test rate, rollback frequency |
| Product | Activation, time-to-first-value, weekly active workspaces, task completion, automation success, user-reported effort |

Metrics must include definitions, owners, collection method, target, alert threshold and privacy classification. Vanity metrics do not qualify.

### Not Yet

Until the CRM/Business OS foundation is exceptional, exclude full website/funnel builders, memberships/courses, affiliate systems, complex commerce, phone-system replacement, broad social publishing, WordPress hosting, communities, white-label native apps and a large add-on marketplace.

## 2. Technology fit

### Next.js on Cloudflare Workers — recommended with guardrails

Cloudflare currently supports major Next.js features through the OpenNext adapter, including App Router, route handlers, server components, SSR, ISR, server actions and streaming. Node.js middleware remains unsupported, and experimental framework features remain higher risk. Production behavior must be tested against the Workers runtime, not only the Next.js development server. [Cloudflare Next.js guide](https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/)

Use Next.js for routes, rendering, interaction, the browser-facing backend-for-frontend (BFF), and composition of domain capabilities. Do not place irreversible business rules exclusively in React components, server actions or page handlers. Domain commands and authorization must be callable and testable independently.

### Supabase PostgreSQL — recommended as canonical system of record

PostgreSQL provides the transaction model, constraints, indexes, migrations, relational integrity and query flexibility required by the initial domains. Supabase documents daily database backups and paid point-in-time recovery, while noting that database backups do not include stored objects. [Supabase database overview](https://supabase.com/docs/guides/database/overview)

Use PostgreSQL for canonical agency, workspace, identity linkage, customer, sales, task, scheduling, automation definition, billing metadata, outbox and audit indexes. Keep high-volume analytical projections and raw operational telemetry separable so they cannot degrade transactional work.

### Supabase Auth — recommended as identity/session authority

Supabase Auth issues and refreshes JWT-based sessions and stores session state. Access tokens are short-lived; stronger revocation can be checked through the session identifier for sensitive actions. [Supabase sessions](https://supabase.com/docs/guides/auth/sessions)

Cloudflare should participate in **session enforcement**, not become a second identity authority:

1. Supabase authenticates users and owns credentials, MFA, refresh and session lifecycle.
2. The application stores tokens using an approved secure browser/session pattern.
3. Cloudflare/Next.js verifies signature, issuer, audience, expiry and required claims on every protected request.
4. Application authorization resolves membership, workspace and capability scope server-side.
5. Sensitive actions additionally verify recent authentication and, where needed, that `session_id` remains active.
6. PostgreSQL RLS provides defense in depth for exposed tables and user-scoped access.

Supabase states RLS must be enabled on exposed-schema tables and describes policies as database-enforced query predicates. [Supabase RLS](https://supabase.com/docs/guides/database/postgres/row-level-security)

Do not rely on JWT role claims alone for fast-changing workspace permissions; membership/capability decisions need a revocation-aware server-side source. Do not expose service-role credentials to browsers.

### R2 — recommended for objects, not business truth

R2 is strongly consistent for object reads, writes, deletes, metadata and listings. [R2 consistency](https://developers.cloudflare.com/r2/reference/consistency/)

Use R2 for attachments, exports, generated documents, media and sanitized backups. PostgreSQL stores ownership, classification, checksum, lifecycle, version and authorization metadata. Object keys include environment and tenant-safe opaque prefixes; authorization never depends only on an unguessable URL. Database backups and object recovery are separate concerns.

### Queues — recommended for asynchronous side effects

Cloudflare Queues provides at-least-once delivery, so duplicate delivery is expected and consumers require idempotency. [Queue delivery guarantees](https://developers.cloudflare.com/queues/reference/delivery-guarantees/) Failed messages should route to configured DLQs; without a DLQ they can be deleted after retry limits. [Dead-letter queues](https://developers.cloudflare.com/queues/configuration/dead-letter-queues/)

Use Queues for provider calls, email/SMS dispatch, webhook fan-out, bulk imports/exports, media processing, search indexing, analytics projections, workflow steps, report generation, AI jobs and noncritical notifications.

### Durable Objects — defer by default

Durable Objects are globally addressable, single-threaded coordination units with private transactional strongly consistent storage. Cloudflare recommends them for stateful coordination, not ordinary stateless request handling. [Durable Object rules](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/)

Justify a Durable Object only when all are true:

- A specific coordination atom exists, such as a collaborative document, live conversation room or serialized shared resource.
- Concurrent actors must observe ordered shared state in near real time.
- PostgreSQL constraints/transactions plus queues cannot meet the correctness/latency requirement cleanly.
- The sharding key, throughput limit, recovery model and source-of-truth relationship are documented.

Do not use one global object, one object for the entire platform, basic CRUD, ordinary caching, standard rate limits, or simple delayed jobs. No Durable Object is required for v0.1 based on current requirements.

## 3. Responsibility matrix

| Component | Primary responsibility | Must not become |
|---|---|---|
| Next.js application | UI, routing, rendering, BFF, command/query composition, session-aware experience | Sole home of business rules |
| Cloudflare Workers | Edge execution, request verification, API boundary, lightweight orchestration, webhooks | Competing identity or transactional database |
| Supabase Auth | Authentication, MFA, token issuance/refresh, session lifecycle | Complete workspace authorization system |
| Supabase PostgreSQL | Canonical transactions, constraints, tenant-owned records, outbox, migration history | File store or unbounded telemetry warehouse |
| PostgreSQL RLS | Defense-in-depth tenant/user data policy | Replacement for application authorization testing |
| R2 | Files, exports, media, generated artifacts | Canonical record ownership or permissions |
| Queues | Reliable asynchronous delivery, buffering, retries and fan-out | Transaction coordinator or exactly-once system |
| Durable Objects | Proven per-atom real-time coordination | Default state layer |

## 4. Command, transaction and event boundaries

### Synchronous actions

Keep synchronous work to authentication/authorization, validation, a small bounded canonical database transaction, and the response needed for the user’s next decision. Examples: create customer, update opportunity stage, create task, reserve appointment slot.

### Queued actions

Queue work that calls external providers, may exceed the interactive latency budget, fans out, retries, processes many records, generates media/reports, invokes long-running AI, sends notifications or updates noncritical projections.

### Transaction rule

One domain command should update its canonical state and insert its domain-event/outbox record in the **same PostgreSQL transaction**. It must not call email, SMS, payment, AI, R2 or other external systems while the database transaction is open.

An outbox relay publishes committed records to Queues. Consumers use `eventId` or a dedicated idempotency key and record processing results. Provider callbacks reconcile final state through new commands/events.

Cross-domain operations are sagas/process managers, not distributed transactions. Compensation and user-visible pending/failure states must be designed.

### API classes

- **Browser BFF:** session-bound, same-origin application calls; not a public integration contract.
- **Internal domain capabilities:** authenticated service/module contracts; AI invokes these, never tables.
- **Webhook ingress:** provider-specific authenticated endpoints with replay protection and deduplication.
- **Public API:** deferred until use cases and support policy exist; versioned, scoped and rate-limited.
- **Administrative API:** separately protected, step-up authenticated and audited.

## 5. Event persistence and immutability

### Long-lived domain history

Retain business-significant domain events according to legal and tenant retention policy: identity/access changes, customer consent, opportunity stage/win/loss, appointment lifecycle, message dispatch/delivery summaries, invoice/payment/refund facts, workflow publication/execution outcomes and template application.

“Forever” should not be promised universally. Retention must reconcile business history, deletion rights, data minimization, industry requirements and contract terms. Preserve event identity and nonpersonal accounting/audit facts where legally required while redacting or crypto-shredding personal payload references where permitted.

### Immutable records

Append rather than overwrite audit events, domain-event envelopes, sent-message records, payment/refund ledger entries, consent history, stage history, workflow versions and template versions. Corrections are new records linked to the original.

Mutable projections include current contact profile, current opportunity stage, task state, current permissions and dashboard aggregates. Their history is reconstructed from explicit history/audit records, not accidental database logs.

System telemetry has shorter tiered retention based on operational need and cost; security logs generally outlive routine performance traces.

## 6. Tenant branding without tenant code

- Store a versioned workspace theme containing approved semantic design-token overrides.
- Restrict values by schema, contrast, file type, size and safe CSS/URL rules.
- Store logos/assets in R2 and reference them through tenant-scoped metadata.
- Resolve custom domains through a controlled domain-mapping table and verified ownership.
- Generate theme variables at the application boundary; components consume semantic tokens only.
- Keep navigation capabilities plan/permission driven, not implemented through tenant forks.
- Never allow arbitrary tenant JavaScript in the main application origin.

## 7. Schema migration strategy

Supabase provides versioned SQL migration workflows. [Supabase database migrations](https://supabase.com/docs/guides/deployment/database-migrations)

Adopt expand–migrate–contract:

1. **Expand:** add compatible tables/columns/indexes/contracts; old code continues working.
2. **Deploy dual-compatible code:** read old/new; write both only when necessary and time-bounded.
3. **Backfill:** queued, resumable, tenant-batched, idempotent and observable.
4. **Verify:** counts, constraints, sampled tenant comparisons and performance.
5. **Switch:** feature flag/read path to the new schema.
6. **Contract:** remove old fields only after rollback windows and compatibility guarantees expire.

Rules:

- Never edit an applied migration; add a new one.
- Production migrations run through CI with a dedicated restricted identity.
- Lock duration and table rewrite risk are reviewed.
- Large indexes use online/concurrent techniques where supported.
- Migrations and application deployment are forward/backward compatible across the rollout window.
- Staging uses production-shaped anonymized data.
- Backups are not a migration plan; restore is rehearsed and timed.
- Tenant-specific schemas are prohibited; all tenants share versioned structures and `workspace_id` scoping.

## 8. Scalability pressure points

1. **Edge-to-database distance:** Workers are global while PostgreSQL is region-based. Measure total query latency; avoid chatty request patterns and uncontrolled server-component queries.
2. **RLS complexity:** policy joins can become expensive and difficult to reason about. Keep membership paths indexed, test query plans, and use security-definer functions only under strict review.
3. **Activity/event growth:** partition or archive high-volume histories; avoid loading full timelines.
4. **Search:** PostgreSQL search may serve v0.1, but a replaceable indexing adapter is needed before large-scale fuzzy/global search.
5. **Analytics:** operational dashboards can use projections; complex cross-tenant analytics should move to an analytical store rather than burden PostgreSQL.
6. **Queue duplicates and poison messages:** require idempotency, per-message acknowledgement, DLQs, replay tooling and alerts.
7. **Automation fan-out:** enforce per-tenant quotas, concurrency controls, execution budgets and cancellation.
8. **AI cost/latency:** route models by task, cache only safe derived results, bound context, meter by workspace and support cancellation.
9. **Noisy tenants:** quotas and work partitioning must protect shared resources.

## 9. Replaceability

Keep framework, auth provider, queue, object store, AI provider, search and observability behind narrow owned adapters. PostgreSQL schemas and domain contracts are the hardest assets to replace and deserve the strongest discipline.

Avoid false portability: do not build lowest-common-denominator abstractions before a second implementation is plausible. Instead, isolate vendor-specific code, keep domain types vendor-neutral, and record exit triggers plus export procedures in ADRs.

## 10. Cloudflare organization strategy

### Naming

Use `wise-bos-{service}-{environment}` for runtime resources, for example `wise-bos-web-staging`, `wise-bos-events-production`, and `wise-bos-files-production`. Documentation projects use `wise-bos-docs-*`. Names must identify product, responsibility and environment.

### Environments

- Development: isolated developer/local resources and synthetic data.
- Preview: ephemeral per-change deployments; no production secrets or customer data.
- Staging: production-shaped, separate databases/buckets/queues/domains and anonymized fixtures.
- Production: restricted access, change approval, immutable deployment history and protected domains.

Never simulate environments only through runtime flags against shared production data.

### Secrets

Cloudflare secrets are encrypted bindings and should be used instead of plaintext variables for sensitive values. [Workers secrets](https://developers.cloudflare.com/workers/configuration/secrets/)

- Separate secrets per environment and least-privilege service identity.
- No secrets in source, build logs, client bundles, telemetry or documentation.
- Maintain owners, purpose, rotation, expiry and incident procedure.
- Prefer short-lived credentials and scoped tokens.

### Deployment and DNS

- One controlled CI path, immutable build artifacts, preview → staging → production promotion, automated tests and documented rollback.
- Custom domains managed through reviewed infrastructure configuration; production DNS changes are logged and protected.
- Compatibility dates and runtime flags are explicit and upgraded deliberately.

### Logging, monitoring and recovery

Cloudflare Workers supports native logs and exporting telemetry through mechanisms including Logpush. [Workers observability](https://developers.cloudflare.com/workers/observability/)

- Structured logs include environment, service, version, tenant-safe identifiers and correlation ID.
- Redaction occurs before emission.
- Alert on availability, latency, queue age/retries/DLQ, webhook failures, auth anomalies, database saturation, AI cost, and deployment health.
- Define database PITR, R2 replication/versioning or backup, configuration export, secret recovery and tested restore runbooks separately.
- Run scheduled restore drills and record recovery-time/recovery-point results.

## 11. Contradictions, ambiguities and missing decisions

1. “Edge-first” can conflict with a single-region transactional database; define it as edge delivery and policy enforcement, not mandatory edge persistence.
2. Supabase Auth versus Cloudflare session responsibility was unspecified; this report proposes identity authority plus edge enforcement.
3. Direct browser-to-Supabase access versus BFF-only access remains undecided. Recommendation: BFF/domain commands for writes; narrowly approved RLS reads only after threat-model review.
4. Domain ownership exists conceptually, but package/deployment/database boundaries are not yet defined.
5. Event retention cannot be “forever” without privacy and deletion policies.
6. Audit log, domain history and operational telemetry need distinct schemas and retention.
7. The AI confirmation model needs a precise action registry and UI contract.
8. Backup language must cover R2 and configuration, not only PostgreSQL.
9. Success metrics need ratified targets after prototype measurement.
10. Cloudflare account ownership, billing roles, break-glass access and CI identities require an operations ADR.

## 12. ADRs required before implementation

- ADR-001: Runtime and deployment topology
- ADR-002: Authentication, tokens, cookies, refresh and session revocation
- ADR-003: Authorization, memberships and PostgreSQL RLS
- ADR-004: Database access pattern and domain transaction boundary
- ADR-005: Transactional outbox, event broker, idempotency and DLQ policy
- ADR-006: R2 object ownership, encryption, retention and recovery
- ADR-007: Environment/resource naming, CI/CD, secrets and DNS
- ADR-008: Observability, audit, data classification and retention
- ADR-009: Schema migration and tenant-safe backfill strategy
- ADR-010: Design tokens, theming and tenant branding
- ADR-011: AI capability registry, confirmation and evaluation framework
- ADR-012: Search and analytics evolution path

## Ratification recommendation

Do not begin feature implementation yet. First:

1. Amend the Product Foundation with Platform Philosophy, Success Metrics and Not Yet.
2. Review and approve this responsibility matrix and transaction model.
3. Decide the direct-Supabase-versus-BFF policy.
4. Write and approve ADR-001 through ADR-009; ADR-010 and ADR-011 must precede design-system and AI implementation respectively.
5. Define initial SLO targets and recovery objectives.
6. Conduct a tenant-isolation threat-model review.
7. Mark the Foundation and this report ratified only after those decisions are recorded.

The architecture is sound enough to continue into detailed decisions. It is not yet specific enough to govern implementation without additional ADRs.
