# AMS — Architecture Diagrams

**Date:** 2026-05-17
**Status:** Living document — update when new layers / tables / flows land
**Sibling docs:** [AMS-INTEGRATION-PLAN-v1.md](AMS-INTEGRATION-PLAN-v1.md), [UNIFIED-FRAMEWORK-v1.md](UNIFIED-FRAMEWORK-v1.md)

Three views of the AMS architecture:
1. **System architecture** — components + layers + external integrations
2. **Database ER** — schema relationships across main / ams / accountability
3. **User flow** — invite-issue through service-access (the critical signup journey)

---

## 1. System architecture

```mermaid
graph TB
    Browser([Browser user])

    subgraph SMB["smb.a1prospect.com  ·  Apache + .htaccess"]
        direction TB
        Public["Public<br>/ams/index.html<br>/ams/_auth/login.html"]
        Auth["Auth layer<br>_auth/*<br>session_guard · login · logout<br>admin_guard · audit_logger<br>email_sender · check_email<br>check_username · accept_invite"]
        App["App layer<br>/ams/app/<br>launcher · settings · settings_save"]
        Admin["Admin layer<br>/ams/admin/<br>users · teams · invites · licenses"]
        API["API helpers<br>_api/<br>db.php · identity.php<br>entitlements.php"]
        Shell["Shared shell<br>_shell/header.php<br>+ topnav, user menu, banners"]
        Lenses["Data lenses<br>_data/freshness<br>_data/param-surface"]
    end

    subgraph DB["Postgres  ·  trsports_tradingjournal_dev"]
        direction TB
        Main[("main.*<br>users · teams · groups<br>user_groups · accounts<br>user_roles · user_sessions<br>audit_logs · reset_2fa_tokens<br>professional_profiles · enterprise_profiles")]
        Ams[("ams.*<br>services · user_service_access<br>license_keys · team_invitations<br>trade_sources · user_source_prefs")]
        Acct[("accountability.*<br>trades_closed · sessions<br>positions_current · traders<br>daily_settings · cto_events<br>processed_fills · service_heartbeats")]
        Alerts[("alerts_tradingview.*<br>indicator_alerts · fills<br>alert_users")]
    end

    subgraph Ext["External / Live systems"]
        direction TB
        HUD["Accountability HUD<br>/live-accountability-v2/hud/<br>(Phase 4: AMS-wrapped)"]
        TV["TradingView<br>webhooks"]
        KTI["KTI CLI + Kore<br>tick bridge"]
        Mail["PHP mail()<br>(Phase 5: notification adapter)"]
        Legacy["Legacy surfaces<br>/mgp · /scorecards<br>/playbooks · etc."]
    end

    Browser -->|HTTPS| Public
    Browser -->|HTTPS| Auth
    Auth --> App
    Auth --> Admin
    App --> Shell
    Admin --> Shell
    Lenses --> Shell
    App --> API
    Admin --> API
    Auth --> API
    Lenses --> API
    Auth --> Mail
    API --> Main
    API --> Ams
    API --> Acct
    Acct -.populated by.-> KTI
    Alerts -.populated by.-> TV
    HUD --> Acct
    App -.opens new tab.-> HUD
    App -.opens new tab.-> Legacy
```

### ASCII fallback

```
                              ┌────────────┐
                              │  Browser   │
                              └─────┬──────┘
                                    │ HTTPS
                                    ▼
        ┌─────────────────────────────────────────────────────────────┐
        │  smb.a1prospect.com  ·  Apache + .htaccess                  │
        │                                                             │
        │  PUBLIC          AUTH layer        APP layer    ADMIN       │
        │  /ams/index      _auth/login       app/        admin/users  │
        │  _auth/login.html  session_guard   settings    admin/teams  │
        │                  audit_logger     entitlement  admin/license│
        │                  email_sender                               │
        │                  accept_invite                              │
        │                                                             │
        │                        SHARED SHELL  _shell/header.php      │
        │                                                             │
        │                        API helpers   _api/db.php            │
        │                                       _api/identity.php     │
        │                                       _api/entitlements.php │
        └───────────────────────────────┬─────────────────────────────┘
                                        │
                                        ▼
        ┌─────────────────────────────────────────────────────────────┐
        │  Postgres   trsports_tradingjournal_dev                      │
        │                                                             │
        │  main.*          ams.*           accountability.*  alerts_*  │
        │  users           services        trades_closed     indicator │
        │  teams           user_service_   positions_curr.   _alerts   │
        │  groups          access          traders           fills     │
        │  user_groups     license_keys    daily_settings    alert_    │
        │  accounts        team_invitations cto_events       users     │
        │  user_sessions   trade_sources   sessions                    │
        │  audit_logs                                                  │
        └────────────────────┬──────────────────────┬─────────────────┘
                             │                      │
                  KTI sync ──┘                      └── TradingView webhooks
                  (Kore tick bridge)
```

---

## 2. Database ER (entity relationships)

```mermaid
erDiagram
    USERS ||--o{ USER_GROUPS : "member of"
    USERS ||--o{ USER_ROLES  : "has role"
    USERS ||--o{ USER_SESSIONS : "logged in"
    USERS ||--o{ AUDIT_LOGS : "produces"
    USERS ||--o{ USER_SERVICE_ACCESS : "granted"
    USERS ||--o| ACCOUNTS : "owns"
    USERS ||--o{ TEAM_INVITATIONS : "invited or invited-by"

    TEAMS ||--o{ GROUPS : "contains"
    GROUPS ||--o{ USER_GROUPS : "has member"
    GROUPS ||--o{ GROUP_ACCOUNTS : "shares"
    GROUP_ACCOUNTS }o--|| ACCOUNTS : "to"

    TEAMS ||--o{ TEAM_INVITATIONS : "issued for"

    SERVICES ||--o{ USER_SERVICE_ACCESS : "grants"
    SERVICES ||--o{ LICENSE_KEYS : "tied to"
    LICENSE_KEYS ||..o{ USER_SERVICE_ACCESS : "redeems via"

    ACCOUNTS }o..o| TRADERS : "bridges (account_name = account_id)"
    TRADERS ||--o{ TRADES_CLOSED : "executes"
    TRADERS ||--o{ POSITIONS_CURRENT : "holds"
    TRADERS ||--o{ DAILY_SETTINGS : "configures"
    TRADERS ||--o{ SESSIONS : "rolls up"

    USERS {
        int id PK
        string username UK
        string email UK
        string password_bcrypt
        string role
        string status
        bool is_verified
        bool is_2fa_enabled
        bool must_change_password
        int session_timeout
        ts last_login_at
    }

    TEAMS {
        int id PK
        string name
        string slug UK
        bool is_active
    }

    GROUPS {
        int id PK
        string name
        string slug
        int team_id FK
    }

    USER_GROUPS {
        int user_id FK
        int group_id FK
        ts assigned_at
    }

    TEAM_INVITATIONS {
        int id PK
        int team_id FK
        string email
        string token_hash UK
        ts expires_at
        string status
        int accepted_user_id FK
    }

    SERVICES {
        int id PK
        string name UK
        string label
        string url
        string status
        bool requires_license
    }

    USER_SERVICE_ACCESS {
        int user_id FK
        string service_name FK
        bool active
        ts expires_at
        string license_key
    }

    LICENSE_KEYS {
        string key PK
        string service_name FK
        ts valid_until
        int max_uses
        int redeemed_count
    }

    ACCOUNTS {
        int id PK
        string account_name
        int owner_id FK
    }

    TRADERS {
        string account_id PK
        string short_name UK
        string full_name
        numeric daily_stop
    }

    TRADES_CLOSED {
        int trade_id PK
        string account_id FK
        string symbol
        string side
        numeric qty
        numeric entry_price
        numeric exit_price
        numeric net_pnl
    }

    AUDIT_LOGS {
        int id PK
        int user_id FK
        string action
        string entity
        jsonb details
    }
```

### Three schemas, one bridge

```
   main.*  ────── identity / auth / teams ──────── (humans + orgs)
     │
     │  account_name (varchar)
     │      ════ bridge via main.resolve_identity() ════
     ▼  account_id  (varchar)
   accountability.*  ────── live trade data ──────── (positions + sessions)
     ▲
     │  trade_id / fill_id soft links
     │
   alerts_tradingview.*  ────── webhook ingestion ── (indicator alerts)


   ams.*  ────── plug-and-play registries ──────── (services + invitations + sources)
     │
     │  user_id FK → main.users
     │  service_name FK → ams.services
     │  team_id FK → main.teams
```

`main.resolve_identity('14859')` walks:
**`accountability.traders`** → `main.accounts.account_name` → `main.accounts.owner_id` → **`main.users.id`**

---

## 3. User flow — invite to first service access

```mermaid
sequenceDiagram
    autonumber
    participant Admin
    participant AMS as AMS Admin UI
    participant DB as Postgres
    participant Mail as PHP mail()
    participant Invitee
    participant Browser as Invitee Browser

    Admin->>AMS: Click "+ Invite by email"<br>(team page → invite.php)
    Admin->>AMS: Submit email + expiry (e.g. 5 min for test)
    AMS->>DB: INSERT ams.team_invitations<br>(token_hash = sha256(rand 32 bytes),<br> email, team_id, expires_at, status='pending')
    AMS->>Mail: ams_send_email(invitee, "You're invited", html)
    Mail-->>Invitee: Email with "Accept invitation →" button
    AMS->>DB: ams_audit_log('admin_invite_issued')<br>+ ams_audit_log('admin_invite_emailed', send_ok=true|false)
    AMS-->>Admin: Success page: "Sent to X" or "Send failed — copy URL"

    Note over Admin,Invitee: If email failed: admin DMs URL out-of-band

    Invitee->>Browser: Click accept link (from email or DM)
    Browser->>AMS: GET /ams/_auth/accept_invite.php?token=<plain>
    AMS->>DB: UPDATE expired pending invites → 'expired'<br>SELECT WHERE token_hash = sha256(plain)
    alt token valid + pending + unexpired
        AMS-->>Browser: Render signup form<br>(team name, email locked, pick username/password)
    else token invalid/expired/used
        AMS-->>Browser: Error page<br>"Invalid invitation" / "Expired" / "Already accepted"
    end

    Invitee->>Browser: Fill username, password, name<br>(real-time ✅/❌ via check_username.php)
    Browser->>AMS: POST accept_invite.php with token + form
    AMS->>DB: BEGIN TRANSACTION
    AMS->>DB: SELECT status FROM team_invitations FOR UPDATE<br>(race guard)
    AMS->>DB: INSERT main.users<br>(bcrypt pw, status='active', is_verified=TRUE,<br> must_change_password=FALSE)
    AMS->>DB: INSERT main.user_groups<br>(user_id, default group of team)
    AMS->>DB: UPDATE ams.team_invitations<br>SET status='accepted', accepted_user_id, accepted_at
    AMS->>DB: COMMIT
    AMS->>DB: ams_audit_log('invite_accepted')
    AMS->>AMS: session_start + session_regenerate_id<br>set $_SESSION user_id, username, role, etc.
    AMS->>DB: UPDATE last_login_at + INSERT main.user_sessions
    AMS-->>Browser: 302 → /ams/app/?welcome=1

    Browser->>AMS: GET /ams/app/
    AMS->>DB: ams_require_session() — load identity
    AMS->>DB: ams_list_services_for_user(user_id)<br>(joins ams.services + user_service_access + role)
    AMS-->>Browser: Service launcher renders<br>(cards: live/planned, granted/locked)

    Invitee->>Browser: Click "Accountability HUD" card
    Browser->>HUD as Live HUD: opens in new tab<br>(external URL → preserves AMS shell)
```

### ASCII fallback (one-page)

```
   ADMIN                      AMS                   POSTGRES              INVITEE
     │                         │                       │                     │
     │  click "+ Invite"       │                       │                     │
     ├────────────────────────►│                       │                     │
     │                         │  INSERT invitation    │                     │
     │                         ├──────────────────────►│                     │
     │                         │  ams_send_email()     │                     │
     │                         ├─── PHP mail() ────────┼────────────────────►│  (email arrives)
     │ "sent — or copy URL"    │                       │                     │
     │◄────────────────────────┤                       │                     │
     │                         │                       │                     │
     │           [admin DMs URL out-of-band if email failed]                 │
     │                         │                       │                     │
     │                         │  GET accept_invite.php?token=X              │
     │                         │◄────────────────────────────────────────────┤
     │                         │  SELECT WHERE         │                     │
     │                         │  token_hash=sha(X)    │                     │
     │                         ├──────────────────────►│                     │
     │                         │  signup form          │                     │
     │                         ├─────────────────────────────────────────────►│
     │                         │                       │                     │
     │                         │  POST username/password/name                │
     │                         │◄────────────────────────────────────────────┤
     │                         │  TX: INSERT users     │                     │
     │                         │      INSERT user_grps │                     │
     │                         │      UPDATE invite    │                     │
     │                         ├──────────────────────►│                     │
     │                         │  start session        │                     │
     │                         │  302 → /ams/app/      │                     │
     │                         ├─────────────────────────────────────────────►│
     │                         │                       │                     │
     │                         │  GET /ams/app/        │                     │
     │                         │◄────────────────────────────────────────────┤
     │                         │  ams_list_services_   │                     │
     │                         │  for_user()           │                     │
     │                         ├──────────────────────►│                     │
     │                         │  launcher cards       │                     │
     │                         ├─────────────────────────────────────────────►│
```

---

## What each diagram is for

| Diagram | Audience | When to update |
|---|---|---|
| **System architecture** | Onboarding new builders, briefing James/Jimbo on what lives where | When a new layer ships (e.g., new admin page category, new external integration) |
| **Database ER** | Anyone writing SQL or designing migrations | When migration N adds tables/columns/FKs |
| **User flow** | Anyone debugging the signup/login path or explaining it to users | When the flow itself changes (e.g., 2FA gate, email-verify gate added) |

## How to render

- **GitHub / VS Code / Obsidian:** Mermaid renders natively in markdown preview
- **Anywhere else:** Paste any Mermaid block into [mermaid.live](https://mermaid.live) to view + export as PNG/SVG
- **No Mermaid available:** the ASCII fallbacks above are always readable

## How to keep current

When a meaningful structural change ships, edit this file (don't create a new version). Bump the date at the top. Old versions are in git history.
