Appearance
Touli Platform — Unified Architecture Document
Version: 1.0
Date: June 2025
Status: Architecture baseline for client review and engineering kickoff
Audience: Product stakeholders, client sponsors, engineering leads, compliance reviewers
Document Control
| Field | Value |
|---|---|
| Product | Touli — impact, challenges, and gifting platform |
| Repository | Nx monorepo (Express API, React Native mobile, shared libraries) |
| Target data store | PostgreSQL |
| Related artifacts | docs/architecture/ packet, docs/touli-erd.md, docs/touli-erd-postgres.sql |
This document consolidates the high-level design (HLD), detailed designs (DLDs), architecture decision records (ADRs), data model, API contracts, compliance controls, rollout plan, and gift-economy flows into a single client-shareable reference.
1. Executive Summary
Touli is a mobile-first platform that encourages positive real-world actions (“deeds”) through challenges, verified submissions, a points economy (Touli Points), badges, leaderboards, and a vendor marketplace for anonymous gifting. Users complete challenges, submit evidence, earn points when deeds are verified, and spend points on gifts for others.
The architecture is designed around five non-negotiable principles:
- Rules first, AI second, humans third — automated rules gate every submission before AI or manual review.
- Deterministic points — the points engine never calls AI; rewards are reproducible from configuration snapshots and ledger history.
- Privacy on chain — blockchain stores pseudonymous proofs only; no personally identifiable information (PII) on chain.
- Ledger as source of truth — wallet balances are projections; append-only ledger entries are authoritative.
- Reproducibility — every economically relevant decision can be audited from config + ledger.
The platform uses a hybrid stack: an Express/Nx API with PostgreSQL, background workers for verification, points, and blockchain anchoring, and a React Native (Expo) mobile app. AI vision (e.g., Gemini) assists verification but does not determine point amounts.
Current implementation status: Foundation is in place (monorepo, auth, mobile screen shells, basic user model). Domain modules for challenges, verification pipelines, points ledger, gifting, and blockchain anchoring are specified in this architecture and scheduled for phased delivery.
2. Product Vision and Scope
2.1 What Touli Delivers
| Capability | Description |
|---|---|
| Onboarding & consent | Age-appropriate flows, parental consent, privacy and permissions |
| Challenges | Curated and user-facing challenge catalog with categories and difficulty |
| Deed submission | Photo/video evidence upload with metadata and anti-abuse checks |
| Verification | Rules engine → optional AI vision → manual review when needed |
| Touli Points | Earn on verified deeds; spend in marketplace; full audit trail |
| Badges & leaderboard | Recognition and social proof without exposing sensitive data |
| Gifting | Anonymous or pseudonymous gift purchases using earned points |
| Vendor marketplace | Third-party catalog, fulfillment, and order lifecycle |
| Blockchain proofs | Periodic Merkle-root anchoring of verification outcomes on Polygon |
| Admin & trust ops | Manual review queues, configuration management, compliance tooling |
2.2 Users and Roles
| Role | Primary interactions |
|---|---|
| End user (mobile) | Challenges, submissions, wallet, shop, gifts, profile |
| Parent/guardian | Consent and age-gating where required |
| Vendor | Catalog and fulfillment (future portal) |
| Trust operator | Manual review, escalation, abuse response |
| Platform admin | Configuration, feature flags, observability |
2.3 Out of Scope (This Architecture Cycle)
- Infrastructure-as-code provisioning scripts
- Final vendor onboarding legal agreements
- Production environment cutover runbooks (referenced in rollout section, not executed here)
3. System Context
3.1 Logical Architecture
┌─────────────────┐ ┌─────────────────┐
│ Mobile App │ │ Admin Console │
│ (React Native) │ │ (future) │
└────────┬────────┘ └────────┬────────┘
│ │
└───────────┬───────────┘
▼
┌────────────────┐
│ API Gateway │
│ (Express/Nx) │
└───────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────────┐ ┌──────────┐
│Submission│ │ Read API │ │ Auth │
│ Service │ │ (queries) │ │ Service │
└────┬────┘ └──────┬──────┘ └────┬─────┘
│ │ │
└──────────────┼──────────────┘
▼
┌────────────────┐
│ PostgreSQL │
│ (primary) │
└───────┬────────┘
│
┌───────▼────────┐
│ Event Bus / │
│ Job Queue │
└───────┬────────┘
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────────┐
│Verification│ │ Points │ │ Anchor │
│ Worker │ │ Worker │ │ Worker │
└─────┬──────┘ └────┬────┘ └──────┬───────┘
│ │ │
▼ ▼ ▼
Rules + AI Pure engine Merkle + Polygon3.2 Trust Boundaries
| Zone | Components | Data sensitivity |
|---|---|---|
| User zone | Mobile client | Device-local cache; tokens |
| Application zone | API, workers | Business logic; pseudonymous IDs |
| Data zone | Postgres, object storage | PII, media, ledger |
| External zone | Gemini, Polygon/Alchemy, push/email | Processed under DPAs; no raw PII on chain |
Mobile clients never talk directly to AI or blockchain providers. All external calls are server-side with policy enforcement.
4. Core Domain Flows
4.1 Deed Submission and Verification
States: draft → submitted → rules_passed | rules_failed → ai_review → approved | rejected | manual_review → terminal outcome.
Pipeline:
- User submits deed with media and challenge reference.
- Rules engine (deterministic): file type, size, duplicate hash, rate limits, challenge eligibility.
- If rules fail → reject with reason codes (no AI spend).
- If rules pass → vision adapter scores evidence against challenge criteria (confidence score).
- Routing by confidence:
- High confidence → auto-approve path
- Low confidence → manual review queue
- Medium → policy-defined (may sample for review)
- On approval → emit
deed.verifiedevent for points worker. - Media retention and deletion follow compliance lifecycle (see Section 8).
4.2 Points Attribution
Trigger: deed.verified event (and defined admin adjustments).
Process:
- Load active points config snapshot (versioned; immutable once referenced).
- Compute award from: base points, challenge multiplier, caps, cooldowns, streak bonuses.
- Write append-only ledger entry with idempotency key (
deed_id + config_version). - Project wallet balance asynchronously or synchronously per read consistency policy.
- Emit
points.creditedfor notifications, badges, leaderboard projection.
Invariants: No AI in this path. Same inputs + same snapshot → same points every time.
4.3 Gifting and Marketplace
Earn points → Browse catalog → Select gift → Confirm spend
→ Ledger debit → Order created → Vendor fulfillment → Delivery status- Spending creates a ledger debit linked to order id (idempotent).
- Gifter identity may be hidden from recipient per product rules.
- Refunds and partial fulfillment reverse or adjust via compensating ledger entries.
4.4 Blockchain Anchoring
Purpose: Tamper-evident, public audit of that verified deeds occurred — without exposing who did what.
- Batch approved verification records into Merkle tree.
- Leaf = hash(pseudonymous_user_id, deed_id, outcome, timestamp_bucket, config_hash).
- Submit Merkle root to Polygon via Alchemy adapter.
- Store tx hash, block, batch id for proof retrieval API.
- Reconciliation job verifies on-chain root matches off-chain batch.
5. Data Architecture
5.1 Conceptual Entity Groups
| Domain | Key entities |
|---|---|
| Identity | User, session, consent, permissions |
| Challenges | Category, challenge, user enrollment, progress |
| Submissions | Deed submission, media asset, verification result |
| Points | Config snapshot, ledger entry, wallet projection |
| Recognition | Badge, user badge, leaderboard snapshot |
| Commerce | Vendor, catalog item, order, fulfillment event |
| Gifting | Gift intent, anonymity policy, delivery |
| Chain | Anchor batch, Merkle leaf, chain transaction |
| Operations | Manual review case, audit log, feature flag |
Full entity-relationship detail: see docs/touli-erd.md.
Postgres-ready DDL: see docs/touli-erd-postgres.sql.
5.2 Schema Evolution: Current vs Target
| Area | Implemented today (Sequelize) | Target (Postgres architecture) |
|---|---|---|
| Users | users, user_roles | app_user with UUID, age, consent |
| Auth | auths, refresh_tokens | user_session, OAuth providers |
| Challenges | — | Full challenge domain tables |
| Submissions | — | Deed + verification tables |
| Points | — | Snapshot + append-only ledger |
| Gifting / shop | — | Vendor, order, gift tables |
| Blockchain | — | Batch + leaf + tx tables |
Migration from current auth foundation to target schema is defined in touli-schema-delta-spec.md (additive phases, no big-bang cutover).
5.3 Ledger Design (Critical)
points_ledger_entry
id, user_id, type (credit|debit|adjustment)
amount, balance_after (optional projection field)
reference_type, reference_id
config_snapshot_id (for credits)
idempotency_key UNIQUE
created_at (immutable)Wallet table is a materialized projection rebuildable from ledger. Never update ledger rows in place.
6. API and Event Contracts (Summary)
6.1 Representative REST Endpoints
| Method | Path | Purpose |
|---|---|---|
| POST | /auth/login, /auth/refresh | Session management |
| GET | /challenges | List active challenges |
| POST | /deeds | Create submission |
| POST | /deeds/:id/media | Upload evidence |
| GET | /wallet | Balance and recent ledger |
| GET | /leaderboard | Rankings |
| POST | /orders | Spend points / place gift order |
| GET | /proofs/:batchId | Merkle proof for verification |
Full OpenAPI-style contracts: touli-api-event-contracts.md.
6.2 Domain Events
| Event | Producer | Consumers |
|---|---|---|
deed.submitted | Submission service | Verification worker |
deed.verified | Verification worker | Points worker, notifications |
deed.rejected | Verification worker | Notifications |
points.credited | Points worker | Badges, leaderboard, push |
points.debited | Order service | Fulfillment, notifications |
anchor.batch.sealed | Anchor worker | Audit, admin dashboard |
All events carry correlation id, idempotency key, and schema version.
7. Architecture Decision Records (Summary)
| ADR | Decision | Rationale |
|---|---|---|
| Rules-before-AI | Deterministic gates precede any model call | Cost control, safety, explainability |
| Pure points engine | No ML in points calculation | Auditability, regulatory clarity |
| Append-only ledger | No in-place balance mutation | Financial-grade traceability |
| Pseudonymous anchoring | Hashed identifiers on chain | Privacy compliance |
| Worker-based async | Verification/points/chain off API hot path | Resilience and scale |
| Config snapshots | Versioned point rules at credit time | Reproducible disputes |
| Postgres primary | Relational integrity for ledger | ACID, mature ops |
| Polygon + Alchemy | L2 anchoring with managed RPC | Cost vs. Ethereum L1 |
Full ADR texts: docs/architecture/adr/.
8. Compliance, Privacy, and Safety
8.1 Regulatory Themes
- Age-appropriate design: consent flows, parental gates, minimized data collection for minors.
- GDPR / data subject rights: export, erasure requests with ledger retention exceptions documented.
- Media lifecycle: verification retention window, then secure deletion; thumbnails may outlive originals per policy.
- AI transparency: users informed when AI assists verification; human appeal path for manual review cases.
8.2 Security Controls
| Control | Implementation |
|---|---|
| Authentication | JWT access + rotating refresh tokens, device binding |
| Authorization | Role-based access; admin actions audited |
| Encryption | TLS in transit; encrypted object storage for media |
| Rate limiting | Per-user and per-IP on submission endpoints |
| Abuse detection | Duplicate media hash, velocity limits, device signals |
| Audit logging | Admin and economically sensitive actions immutable log |
Detail: touli-compliance-controls.md.
9. Observability and Operations
| Concern | Approach |
|---|---|
| Metrics | Submission rate, verification latency, review queue depth, points credits/sec |
| SLOs | API p95 < 300ms reads; verification p95 < 5 min (excl. manual) |
| Alerting | Queue backlog, anchor failures, ledger idempotency violations |
| Runbooks | AI provider outage → rules-only degrade; chain outage → batch retry |
10. Phased Delivery Plan
| Phase | Focus | Exit criteria |
|---|---|---|
| A — Points foundation | Ledger, snapshots, idempotency | Calculation contract approved; schema delta signed off |
| B — Verification foundation | Rules engine, state machine, manual review | SLA and reason codes approved |
| C — AI integration | Vision adapter, labeling, fallbacks | Provider contract and outage policy approved |
| D — Blockchain anchoring | Merkle batches, Polygon adapter | Privacy and reconciliation approved |
| E — Operational hardening | SLOs, runbooks, compliance checkpoint | Go/no-go checklist green |
Suggested architecture finalization (2 weeks): Week 1 — HLD alignment, verification + points DLDs, schema review. Week 2 — blockchain + compliance, risk workshop, freeze package.
Detail: touli-rollout-risk-readiness.md.
11. Risk Register (Top Items)
| ID | Risk | Mitigation |
|---|---|---|
| R1 | Points logic drift vs. product docs | Snapshot versioning; single source of truth gate |
| R2 | Duplicate credits on retry | Idempotency keys; unique constraints |
| R3 | Manual review backlog | Capacity planning; degrade routing |
| R4 | AI cost overrun | Rules-first gating; confidence thresholds |
| R5 | PII leakage on chain | Pseudonymization review; pre-publish checklist |
| R6 | Schema migration pain | Additive migrations; dual-write window if needed |
12. Current Implementation Snapshot
12.1 Repository Structure
| Area | Status |
|---|---|
| Nx monorepo | Active — shared libs, server, mobile |
| Mobile app (Expo) | Screen shells: auth, onboarding, challenges, shop, gifts, profile |
| API server | Express with auth routes (login, refresh, user CRUD foundation) |
| Data models | Sequelize: User, UserRole, Auth, RefreshToken |
| Architecture docs | Full packet in docs/architecture/ |
| Target ERD / SQL | docs/touli-erd.md, docs/touli-erd-postgres.sql |
12.2 Gap to Target Architecture
The following are specified but not yet built in production code:
- Challenge catalog and enrollment APIs
- Deed submission and object storage integration
- Verification worker pipeline (rules, AI, manual review)
- Points engine and ledger tables
- Marketplace, orders, and gifting flows
- Badge and leaderboard projection jobs
- Blockchain anchor worker and proof API
- Admin console for trust operations
This gap is expected; the architecture packet defines the build order via Phases A–E.
13. Technology Stack
| Layer | Choice |
|---|---|
| Monorepo | Nx + Yarn workspaces |
| API | Node.js, Express, Sequelize (migrating toward Postgres-native schema) |
| Mobile | React Native, Expo, file-based routing |
| Database | PostgreSQL (target) |
| Queue | TBD — SQS, Redis/Bull, or cloud-native equivalent |
| Object storage | S3-compatible for deed media |
| AI | Gemini (vision) via server adapter |
| Blockchain | Polygon via Alchemy |
| CI | Lint, test, type-check per app; mobile native builds |
14. Go / No-Go Checklist (Architecture Freeze)
- [ ] HLD and invariants accepted by client and engineering
- [ ] Verification state machine and reason codes signed off
- [ ] Points calculation contract and snapshot model signed off
- [ ] Schema delta reviewed against ERD and migration plan agreed
- [ ] API/event contracts baselined for MVP slice
- [ ] Compliance controls mapped to features (consent, retention, DSAR)
- [ ] Risk register owners assigned
- [ ] Phase A kickoff date confirmed
15. Appendix — Reference Documents
| Document | Location |
|---|---|
| Core HLD | docs/architecture/touli-core-hld.md |
| Verification DLD | docs/architecture/touli-verification-dld.md |
| Points DLD | docs/architecture/touli-points-dld.md |
| Blockchain DLD | docs/architecture/touli-blockchain-dld.md |
| Schema delta | docs/architecture/touli-schema-delta-spec.md |
| API & events | docs/architecture/touli-api-event-contracts.md |
| Compliance | docs/architecture/touli-compliance-controls.md |
| Rollout & risks | docs/architecture/touli-rollout-risk-readiness.md |
| Gift economy flows | docs/architecture/touli-gift-economy-flowchart.md |
| Conceptual ERD | docs/touli-erd.md |
| Postgres DDL draft | docs/touli-erd-postgres.sql |
| Mobile dev setup | docs/mobile/setup-guide.md |
16. Glossary
| Term | Definition |
|---|---|
| Deed | A user submission proving completion of a challenge action |
| Touli Points | Platform currency earned by verified deeds and spent on gifts |
| Config snapshot | Immutable version of point rules used at credit time |
| Ledger entry | Append-only financial record of point credit or debit |
| Anchor batch | Group of verification outcomes hashed into a Merkle root for chain |
| Trust operator | Human reviewer for borderline or escalated submissions |
End of document. For questions or architecture change requests, track via the project decision log and ADR process.