# AMS (Accountability Management System) — Integration Plan v1

**Status:** Draft 1 — proposed architecture + 17-week project plan
**Date:** 2026-05-16
**Owner:** James (decisions); Claude (drafting); Jimbo + Alex + Roberto (build collaborators)
**Hub-role:** Sits alongside [UNIFIED-FRAMEWORK-v1.md](UNIFIED-FRAMEWORK-v1.md). UF = doctrine (what the platform *is*). This = integration plan (how the *existing* pieces become one cohesive product).

**Read first:**
- [`UNIFIED-FRAMEWORK-v1.md`](UNIFIED-FRAMEWORK-v1.md) — spine/cockpit/lens doctrine
- Memory: `project_system_contract.md` — single-source-of-truth rules
- Memory: `project_phase0_foundation_freeze.md` — the 6 foundation deliverables
- 2026-05-16 audit: `/todos/audit/2026-05-16/` — system-level state assessment

---

## 0 — Feasibility Verdict

**Feasible. High confidence. ~16–18 calendar weeks of mixed solo + small-team work, ending ~mid-September 2026.**

The reason this is feasible is that **every load-bearing component already exists in production form**:

| Need | Where it lives today | Maturity |
|---|---|---|
| Auth + 2FA + sessions + password reset | `a1p_journal/src/php/login_user.php` etc. | Working in legacy journal |
| Users / roles / teams / groups / accounts schema | `main.users`, `main.roles`, `main.teams`, `main.groups`, `main.user_groups`, `main.accounts`, `main.group_accounts` (with `access_level`) | DDL in `a1p_journal/src/ddl/` — well-designed, partially populated |
| Audit log | `main.audit_logs` | Working in legacy login flow |
| Real-time cockpit | `accountability-v2` (HUD + 2 Node daemons + SSE + Kore tick bridge) | Live, demo-ready (BUILT.md 2026-04-24) |
| Daily Stop tool | `accountability-v2/api/daily-settings.php` + `daily_settings` table | Live at `/daily-stop/` |
| TradingView ingestion | `tradingview_smb_indicator_trigger.php` → `alerts_tradingview.indicator_alerts` | Live, healthy (161 alerts on 5/15) |
| KTI sync (Gr8Trade trades) | `accountability-v2/scripts/sync-*.js` (2.5s and 60s loops) | Live |
| Analytical lenses | MGP, Scorecards, Playbooks, Strategy Library, Param Surface, Monthly, MTF VP, Live Classifier | All live and rendering |
| Cross-property nav | `/_shared/nav.js` injected on every page | Live |
| PM hub + task taxonomy | `/todos/index.html` + `todos.json` | Live, owns the 11-property registry |

**What's missing** is the integration glue, not the components:
1. **One auth boundary** in front of all surfaces (today everything is public/IP-restricted)
2. **One identity function** (`account_id → user_id → trader_name`) used by every query — currently 4 surfaces have 4 different identity paths (this is `p0-identity-fn` in the foundation queue)
3. **Scope-aware queries** — the team/group schema exists but no surface actually joins through `user_groups → group_accounts` to scope what the logged-in user can see
4. **A unified app shell** that ties the surfaces together with auth context, not just a nav bar
5. **The 6 Phase 0 foundation deliverables** (already prioritized in the audit) — orchestrator, freshness dashboard, identity fn, daily summary view, param surface registry, indicator alerts DDL
6. **Docroot consolidation** — trsports_gd/html vs gt_dev split is bridged by symlinks today; long-term needs one home

None of those six is a research problem. All are buildable from the inventory.

**Risk-flagged but tractable:** the HUD-off-limits constraint (`feedback_hud_off_limits.md`) means the live cockpit can't be edited autonomously — every Phase 4 cockpit change ships through Jimbo. This is a coordination cost, not a feasibility blocker. Build the dev branch in `accountability_dev` schema, demo, promote.

---

## 1 — Current State (Compressed)

### 1.1 The seven realities the plan must respect

1. **Spine schemas:** `main.*` (users/teams/identity + legacy journal), `accountability.*` (live trades + sessions + positions + daily settings), `alerts_tradingview.*` (indicator alerts + fills + alert_users)
2. **`main.journal` is empty by design** — the audit confirmed this. Real trade data lives in `accountability.trades_closed` (live) and KTI CLI (authoritative ledger). Plans referencing `main.journal` need re-scoping.
3. **HUD = source of truth for P&L** — `monthly` and `scorecards` already read from `live-accountability-v2/api/trader-range.php` instead of recomputing. Keep that pattern.
4. **Daily Stop is wired into accountability-v2**, not into MGP. The integration is a one-way pipe: Daily Stop endpoint → MGP renderer reads it.
5. **HUD is off-limits to autonomous edits** — Jimbo owns it; v2 schema (`accountability_dev` → `accountability` after promotion) is the safe build surface.
6. **Two docroots, one product:** `trsportsacademy.com → /trsports_gd/html` and `smb.a1prospect.com → /gt_dev` are bridged today by Linux symlinks (mgp, system, playbooks, scorecards) in two places (`/gt_dev` root and `/gt_dev/ams/`). Both domains serve the same files for now.
7. **No auth anywhere on the user-facing surfaces today.** Pages are open to anyone who can reach the URL.

### 1.2 The 11 working surfaces (from `/todos/` properties registry)

| # | Property | URL (today) | Trade-data source | Cockpit/Lens | Auth today |
|---|---|---|---|---|---|
| 1 | Strategy Library | `/strategies/` | (none — doctrine) | Lens | none |
| 2 | Playbooks | `/playbooks/` | (none — teaching) | Lens | none |
| 3 | MGP | `/mgp/` | KTI + alerts_tradingview | Lens (live pre-market) | none |
| 4 | Accountability HUD v2 | `smb.a1prospect.com/live-accountability-v2/hud/` | accountability.* (KTI sync + tick bridge) | Cockpit | none |
| 5 | Daily Stop | `/daily-stop/` | accountability.daily_settings | Cockpit | none |
| 6 | Live Classifier | (subpage) | alerts_tradingview | Cockpit | none |
| 7 | Scorecards | `/scorecards/` | KTI + HUD API + alerts_tradingview | Lens | none |
| 8 | Monthly Reports | `smb.a1prospect.com/db_reports/james-monthly-reports/` | HUD API + KTI | Lens | none |
| 9 | Param Surface | `smb.a1prospect.com/.../vwap-bands/param-surface-db/` | Backtest DB | Lens | none |
| 10 | MTF VP Scanner | `smb.a1prospect.com/db_reports/.../mtf-vp/` | Self-contained DB | Lens | none |
| 11 | Todos / PM Hub | `/todos/` | todos.json | PM | none |

Also alive: System Hub `/system/`, Drift Report, Classifier Divergence dashboard.

### 1.3 What's already in the foundation queue (audit, 2026-05-16)

The audit identifies 7 compounding-infra tasks that ≥3 properties each consume. **All seven are in this plan's Phase 0 wrap or Phase 2.**

- `p0-freshness-dashboard` — 7 properties
- `p0-orchestrator` — 5 properties (nightly job runner + central log)
- `p0-identity-fn` — 4 properties (the keystone for this plan)
- `p0-daily-summary-view` — 3 properties (needs re-scope per audit)
- `p0-param-surface-registry` — 3 properties
- `catalog-refactor-shared-json` — 5 properties (consumer cutover, catalog already at `/system/strategies.json`)
- `shared-user-dropdown` — 4 properties (blocked on identity-fn)

---

## 2 — Target Architecture

### 2.1 Diagram (text — keep terminal-readable)

```
                              EXTERNAL USERS (browser)
                                       │
                                       │  HTTPS
                                       ▼
        ┌──────────────────────────────────────────────────────────────────┐
        │   Apache vhost  ams.a1prospect.com  (or smb.a1prospect.com/ams/) │
        │   docroot = /gt_dev/ams/                                         │
        │   ┌────────────────────────────────────────────────────────────┐ │
        │   │  AUTH WALL                                                 │ │
        │   │  /ams/login.php   /ams/2fa.php   /ams/logout.php           │ │
        │   │  PHP session cookie scoped to .a1prospect.com              │ │
        │   │  Apache mod_auth_request → /ams/_auth/check.php            │ │
        │   │  All deeper routes require session + (role-gated) 2FA       │ │
        │   └────────────────────────────────────────────────────────────┘ │
        │                                                                  │
        │   ┌────────────────────────────────────────────────────────────┐ │
        │   │  APP SHELL  (sticky topnav + role-aware menu + identity    │ │
        │   │              chip + impersonation hint when admin "switched │ │
        │   │              user")                                         │ │
        │   │  Renders any of the 11 properties as inner content         │ │
        │   └────────────────────────────────────────────────────────────┘ │
        │                                                                  │
        │   ┌─────────────┬─────────────┬─────────────┬─────────────────┐ │
        │   │  COCKPITS   │   LENSES    │   PM HUB    │   ADMIN         │ │
        │   │ ─────────── │ ─────────── │ ─────────── │ ─────────────── │ │
        │   │ HUD v2      │ Scorecards  │ Todos       │ Users/Teams     │ │
        │   │ Daily Stop  │ Monthly     │ Audit       │ Daily-stop      │ │
        │   │ Live Classi │ Playbooks   │ Drift       │   defaults      │ │
        │   │ MGP intra-d │ Param Surf  │ Freshness   │ Switch user     │ │
        │   │             │ MTF VP      │             │ Audit log       │ │
        │   │             │ Strategies  │             │                 │ │
        │   │             │ MGP morning │             │                 │ │
        │   └──────┬──────┴──────┬──────┴──────┬──────┴───────┬─────────┘ │
        └──────────┼─────────────┼─────────────┼──────────────┼───────────┘
                   │             │             │              │
                   ▼             ▼             ▼              ▼
        ┌────────────────────────────────────────────────────────────────┐
        │  SHARED HELPERS (every request loads these)                    │
        │  - identity_resolve($session)  → user_id, trader_name, roles   │
        │  - auth_scope_clause($user_id) → SQL fragment "WHERE account_id│
        │                                   IN (… scope …)"              │
        │  - audit_log($user_id, $action, $entity, $entity_id, $details) │
        │  - freshness_check($source)    → fresh|stale|blocked           │
        └────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
        ┌────────────────────────────────────────────────────────────────┐
        │  SPINE — PostgreSQL trsports_tradingjournal (prod)             │
        │                       trsports_tradingjournal_dev (staging)    │
        │                                                                │
        │  schema main.*                                                 │
        │    users, roles, user_roles, teams, groups, user_groups,       │
        │    accounts, group_accounts (access_level), user_plans,        │
        │    professional_profiles, enterprise_profiles, audit_logs      │
        │    [LEGACY, READ-OK]: journal, closed_trades, trade_tracking,  │
        │                       raw_trades, daily_report_cards           │
        │                                                                │
        │  schema accountability.*                                       │
        │    traders, sessions, positions_current, positions_history,    │
        │    trades_closed, processed_fills, daily_settings, app_config, │
        │    position_snapshots, cto_events, trade_action_requests,      │
        │    hud_usage_events, service_heartbeats, kti_daily_summary     │
        │                                                                │
        │  schema alerts_tradingview.*                                   │
        │    indicator_alerts, fills, alert_users,                       │
        │    fashionably_late_trades [DEPRECATED]                        │
        └────────────────────────────────────────────────────────────────┘
                          ▲                          ▲
                          │                          │
            ┌─────────────┴────────────┐  ┌──────────┴─────────────┐
            │  TradingView webhooks    │  │  KTI CLI + Kore tick    │
            │  → indicator_alerts      │  │  bridge → trades_closed │
            │  shared-secret per user  │  │  + positions_current    │
            └──────────────────────────┘  └─────────────────────────┘
```

### 2.2 Architecture decisions (each one is reversible)

| # | Decision | Recommended | Why | Alternative |
|---|---|---|---|---|
| A1 | Auth stack | **PHP sessions + bcrypt + TOTP (as-is from a1p_journal)** | Already built, working, copy-paste port. Adding a framework is a 4-week detour. | Laravel migration (deferred to a v2 hardening pass) |
| A2 | Session cookie scope | `Domain=.a1prospect.com; Secure; HttpOnly; SameSite=Lax` | Lets one login span ams.a1prospect.com, smb.a1prospect.com, live-accountability-v2 subdir | per-vhost cookies (would force re-login on every property) |
| A3 | Static page protection | Apache `mod_auth_request` → `/ams/_auth/check.php` | Lets HTML/JSON files require session without modifying every static file | Convert all .html to .php (high churn) |
| A4 | Identity function | **Single SQL function `main.resolve_identity(account_id)`** returning `(user_id, trader_name, team_id)`; one PHP wrapper `identity_resolve()`; one Python wrapper `resolve_user()` | The `p0-identity-fn` task already specifies this. 4 surfaces converge on one signature. | Per-property identity helpers (status quo — the problem we're solving) |
| A5 | Scope clause | **Single helper `auth_scope_clause($user_id)` returning a parameterized SQL fragment** | Every read query that involves accounts/trades calls this once. Sharing rules live in one place. | Inline `WHERE user_id = ?` (status quo — doesn't support teams) |
| A6 | Docroot | **Long-term: everything in `/gt_dev/ams/`**; short-term: keep symlinks | Single source of truth on smb.a1prospect.com. trsportsacademy.com becomes a redirect or marketing site. | Live with symlinks forever (works but confusing) |
| A7 | DB target | Build everything against `*_dev` first, promote with one migration once green | Matches current accountability_dev → accountability pattern | Build directly in prod (rejected) |
| A8 | Sharing model | Default: each trader sees only their own trades. Team-share is opt-in per `main.users.willing_to_share=true` AND team-mate is in same `main.groups` row. Admin sees all. | Conservative, matches `willing_to_share` column that already exists | Default-open within team (rejected — violates privacy expectations) |
| A9 | Phase order | **Foundation (Phase 0) finishes → auth in front (Phase 1) → identity + scope (Phase 2) → shell (Phase 3) → per-surface wiring (Phase 4) → migration polish (Phase 5)** | Auth and identity gate every later step. Doing surfaces first means re-doing them. | Auth-last (rejected — leaves data exposed during the rebuild) |
| A10 | What "integrated" means concretely | (a) one login, (b) one nav, (c) every query scoped to logged-in user's accounts + shared team accounts, (d) one freshness dashboard, (e) one PM hub, (f) one audit log | Matches what James asked for: "single cohesive, well-integrated, usable" | Looser definition (rejected — defeats the point) |

### 2.3 Identity & Auth Design (concrete)

**Identity resolution flow:**

```
HTTP request → Apache → check session cookie → /ams/_auth/check.php
                                                      │
                                                      ▼
                                       SELECT u.id, u.username, u.role,
                                              u.is_2fa_enabled, u.willing_to_share
                                       FROM main.users u
                                       WHERE u.id = $_SESSION['user_id']
                                              │
                                              ▼
                                       Returns user context to caller via $_SERVER['REMOTE_USER']
                                       (or 401 if no session)
```

**Scope SQL function** (`main.user_scope(p_user_id BIGINT)` → setof BIGINT account_id):

```sql
CREATE OR REPLACE FUNCTION main.user_scope(p_user_id BIGINT)
RETURNS TABLE(account_id BIGINT) AS $$
  -- 1. Own accounts (directly owned)
  SELECT a.id FROM main.accounts a WHERE a.owner_id = p_user_id
  UNION
  -- 2. Accounts in groups where user is a member AND owner allows sharing
  SELECT ga.account_id
  FROM main.user_groups ug
  JOIN main.group_accounts ga ON ga.group_id = ug.group_id
  JOIN main.accounts a ON a.id = ga.account_id
  JOIN main.users owner ON owner.id = a.owner_id
  WHERE ug.user_id = p_user_id
    AND owner.willing_to_share = TRUE
    AND ga.access_level IN ('read','write','admin')
  UNION
  -- 3. Admin sees everything
  SELECT a.id FROM main.accounts a
  WHERE EXISTS (
    SELECT 1 FROM main.user_roles ur
    WHERE ur.user_id = p_user_id AND ur.role IN ('enterprise_admin','admin')
  );
$$ LANGUAGE SQL STABLE;
```

Every read in Phase 4 becomes: `WHERE account_id IN (SELECT account_id FROM main.user_scope($1))`.

**Role matrix (initial):**

| Role | Login | Own trades | Team trades (opt-in) | All trades | Daily-stop edit | User mgmt | Switch-user |
|---|---|---|---|---|---|---|---|
| trader | ✓ | ✓ | ✓ | — | self only | — | — |
| professional_user | ✓ | ✓ | ✓ | — | self only | — | — |
| enterprise_admin | ✓ | ✓ | ✓ | within enterprise | within enterprise | within enterprise | within enterprise |
| admin | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ (auditable) |

Maps cleanly onto existing `main.roles` + `main.user_roles` tables.

---

## 3 — Phase Plan

Six phases, ~17 calendar weeks. Each phase has: deliverables, dependencies, exit criteria, and start/end dates. Dates assume Mon 2026-05-18 kickoff.

### Phase 0 — Foundation wrap (in flight)

**Window:** Mon 2026-05-18 → Fri 2026-05-29 (2 weeks)
**Owner mix:** Claude (autonomous) + James (review) + Jimbo (HUD watch)
**Goal:** Land the 6 foundation deliverables that everything else assumes

**Deliverables:**
1. `p0-freshness-dashboard` — `/system/freshness.html` consumes `/system/freshness.json`, banner on every property when stale
2. `p0-orchestrator` — one nightly cron entry that runs all generators, logs to `/z/logs/nightly-YYYY-MM-DD.log`, fails loud
3. `p0-identity-fn` — `main.resolve_identity()` SQL function + PHP `identity_resolve()` + Python `resolve_user()` helpers
4. `p0-param-surface-registry` — `/system/param-surface-registry.json` indexed by strategy id
5. `catalog-refactor-shared-json` — consumers (`_scientific_overlay.js`, `/strategies/`, `classify/*.json`, `playbooks.json`) load from `/system/strategies.json`
6. `p0-indicator-alerts-ddl` — schema dump committed to `/docs/`; downstream tasks (`audit-webhook-coverage`, `wire-webhooks`) unblock

**Exit criteria:**
- Freshness dashboard shows green on ≥10 of 13 properties
- Orchestrator has run successfully for 3 consecutive nights
- Identity helper used by ≥1 property (proof of integration)

**Dependencies:** None — all in foundation queue.

**Risk:** `p0-daily-summary-view` is intentionally **deferred** to Phase 2 because audit found its source assumption (main.journal canonical) is wrong. Re-scoped in Phase 2.

---

### Phase 1 — Auth Boundary

**Window:** Mon 2026-06-01 → Fri 2026-06-19 (3 weeks)
**Owner mix:** Claude (lift code from a1p_journal) + James (review + first user) + Roberto (review)
**Goal:** Put login in front of every surface

**Deliverables:**
1. New PHP module `/gt_dev/ams/_auth/` containing:
   - `login.php` (port from `a1p_journal/src/php/login_user.php`)
   - `logout.php`, `2fa.php` (TOTP), `enable_2fa.php`, `confirm_2fa_setup.php` (ports)
   - `request_password_reset.php`, `reset_password.php` (ports)
   - `check.php` (Apache mod_auth_request endpoint — returns 200 if session valid, 401 otherwise)
   - `session_guard.php` (already exists in legacy — port + harden token storage)
   - `audit_logger.php` (port + adapt to new context)
2. Apache vhost config for `smb.a1prospect.com/ams/`:
   - `<Location /ams>` → `AuthType` configured to require session via `mod_auth_request → /ams/_auth/check.php`
   - Carve-out for `/ams/_auth/login.php`, `/ams/_auth/2fa.php`, `/ams/_auth/reset_password.php`, static `/ams/_assets/*` (no auth)
3. Session cookie hardening:
   - `Domain=.a1prospect.com; Secure; HttpOnly; SameSite=Lax`
   - 30-min idle timeout (already in legacy `session_guard.php`)
   - Optional 8-hour hard timeout for non-2FA sessions
4. Password reset email pipeline (port from legacy + use existing send_grumpy_email infra)
5. User-management admin pages (port `enable_2fa.php`, add `users.html` listing all users, add `user-edit.php`)
6. **Token store hardening:** legacy stores `reset_token` plaintext — swap to hashed token (SHA-256 of secret + per-user salt)

**Exit criteria:**
- All 4 internal users (Nolan/Preston/Brian/Thomas) + James + Jimbo can log in with 2FA enabled
- `/ams/` redirects to `/ams/_auth/login.php` when not logged in
- Failed-login lockout fires after 5 attempts
- Password reset works end-to-end
- Audit log records every login, logout, password change, 2FA enable

**Dependencies:** none (auth code is standalone). Can start Day 1.

**Risk:** **MEDIUM** — porting auth means handling real credentials. Mitigation: build in dev DB, force re-enrollment for first login (don't migrate password hashes from legacy until verified).

---

### Phase 2 — Identity & Scoping

**Window:** Mon 2026-06-22 → Fri 2026-07-03 (2 weeks)
**Owner mix:** Claude (code) + James (data review) + Roberto (classifier-side review)
**Goal:** Every query that returns trade data is scoped to the logged-in user's accounts

**Deliverables:**
1. `main.user_scope(p_user_id)` SQL function (per §2.3)
2. PHP helper `auth_scope_clause($user_id)` → returns parameterized SQL fragment + bound params
3. Python helper `auth_scope_clause(user_id)` → same contract
4. `/ams/_data/scope-debug.php` admin tool showing "for user X, the visible accounts are: …"
5. **Team/group population:** seed `main.teams`, `main.groups`, `main.user_groups`, `main.group_accounts` for the 6-trader firm (Nolan/Preston/Brian/Thomas + James/Jimbo as admins). Use the `share_with_team` column.
6. Re-scope of `p0-daily-summary-view` (per audit Q5): redefine as a view on `accountability.sessions + alerts_tradingview.indicator_alerts` (NOT `main.journal`). One SQL view, three consumers (scorecards, monthly, accountability) point at it.
7. Re-scope of `add-strategy-id-column-to-indicator-alerts-main-jo` (per audit drift #1): drop the `main.journal` half; only add `strategy_id` to `alerts_tradingview.indicator_alerts`.
8. `/ams/admin/users.html` — list users, edit role, view scope, view audit
9. Per audit recommendation: kill `risk_hud` cluster after dedup decision (`risk-hud-accountability-hud-dedup-review`)

**Exit criteria:**
- `auth_scope_clause()` used in ≥3 read paths (proof of integration, but no surface rewires yet — that's Phase 4)
- `scope-debug.php` shows correct visibility for each of the 6 traders
- `daily-summary` view returns identical numbers to current scorecard for ≥5 trader-days

**Dependencies:** Phase 1 (need real session context to test).

**Risk:** **LOW** — additive work. Doesn't touch live surfaces yet.

---

### Phase 3 — App Shell + Unified Nav

**Window:** Mon 2026-07-06 → Fri 2026-07-17 (2 weeks)
**Owner mix:** Claude (build) + James (UX review) + Jimbo (HUD-adjacent review)
**Goal:** One visual shell that renders any property + injects identity context

**Deliverables:**
1. `/ams/_shell/` containing:
   - `header.php` — sticky topnav (port from `/_shared/nav.js` but server-side rendered with role awareness)
   - `footer.php` — common footer
   - `layout.php` — `<?php include header ?> $content <?php include footer ?>` wrapper
   - `nav-config.json` — single source for the cross-property menu (replaces hardcoded URLs in nav.js)
2. Identity chip in topnav: `[James ▾]` with dropdown showing username, role, "Switch user" (admin only, audited), "Settings", "Sign out"
3. Freshness badge on every page (consumes `/system/freshness.json`)
4. **Theme registry:** extract dark-theme tokens from inline CSS to one `/ams/_assets/theme.css`. Each property keeps its own page CSS but inherits theme tokens.
5. Apache `RewriteRule` mapping legacy paths to new shell-wrapped paths (so `/mgp/` still works but renders inside the shell)
6. Mobile-responsive shell (current nav.js is desktop-only)

**Exit criteria:**
- All 11 properties load inside the shell with consistent header/footer
- Logged-in user's name visible in every page
- Freshness badge functional on every page
- No surface required a rewrite to consume the shell

**Dependencies:** Phase 1 (need session for identity chip), Phase 2 (need identity_resolve to populate chip).

**Risk:** **LOW** — shell is additive. Per-property CSS isn't modified; only theme tokens.

---

### Phase 4 — Per-Surface Wiring (the big phase)

**Window:** Mon 2026-07-20 → Fri 2026-08-28 (6 weeks)
**Owner mix:** Claude + Jimbo (HUD-touch tasks) + Alex (range-break strategy) + Roberto (classifier)
**Goal:** Every surface uses identity + scope; team-sharing actually works

This is where the surfaces actually become an integrated product. Many of these tasks **can parallelize** because they don't share code.

**Workstreams (parallel where possible):**

#### 4A — Cockpits (sequential due to HUD-off-limits coordination with Jimbo)
- **HUD v2** — wire trader-range.php through `auth_scope_clause()`. Add team-view toggle. Add "shared with you" indicator. **OWNED BY JIMBO** — Claude provides PR, Jimbo merges.
- **Daily Stop** — already trader-specific; just wrap in auth + audit log every change
- **Live Classifier** — Roberto-owned. Wire through identity_resolve so per-trader overrides work.

#### 4B — Lenses (parallelizable across 4 weeks)
- **Scorecards** — `gen_scorecard.py` already takes `--account`. Add `--user_id`; replace hardcoded `DEFAULT_ACCOUNT=14859` with `resolve_user($user_id).account_id`. Wire trade-data query through `auth_scope_clause()`.
- **Monthly Reports** — `gen_monthly_dashboard.py` currently hardcoded to James. Replace with `--user_id` flag; per-user output paths.
- **Param Surface** — wire through registry (Phase 0 deliverable). Per-strategy grids visible based on what user has access to.
- **MGP** — add daily-stop read (already an open task: `mgp-daily-stop-pipe`); per-user customization (read user's daily_stop via daily-settings endpoint).
- **Strategy Library** — wire `add-user-role-approval` (already in queue): traders can submit strategies, admin approves.
- **Playbooks** — wire owner field (already in `playbook_owner` per memory `user_team.md`); show "owned by team", "shared with you", "private to author".
- **MTF VP Scanner** — wire the TradingView ticket-in handler (already in queue: `mtf-vp-tradingview-handler`).

#### 4C — PM hub (last in phase 4)
- **Todos** — already has all 11 properties wired. Add per-user filter ("show only tasks where owner = me"). Add team-view ("show all tasks in my team").
- **Audit page** — `/ams/admin/audit.html` reading `main.audit_logs`. Filter by user, action, date range.

**Exit criteria:**
- Every surface authenticates
- Every surface scopes to logged-in user
- A team-mate seeing my surface sees only what I shared (`willing_to_share=true` + same group)
- Admin can "switch user" with auditable event
- All four internal traders (Nolan/Preston/Brian/Thomas) have valid logins + are visible in their own scorecards

**Dependencies:** Phases 1+2+3 complete.

**Risk:** **MEDIUM-HIGH.** This is where regressions hide. Mitigation:
- Each surface ships with a "before/after" screenshot in the PR
- Cockpit changes go through Jimbo (HUD-off-limits)
- Each surface is feature-flagged: `AMS_AUTH_ENFORCED=true` flag in env, default false for first week of each rollout

---

### Phase 5 — Migration & Polish

**Window:** Mon 2026-08-31 → Fri 2026-09-11 (2 weeks)
**Owner mix:** Claude + James (decisions on docroot consolidation)
**Goal:** One docroot, one domain primary, symlinks retired

**Deliverables:**
1. **Decision on canonical domain:**
   - Recommend: `smb.a1prospect.com` is canonical. `trsportsacademy.com` becomes a `301 → smb` for all paths under `/mgp`, `/system`, `/playbooks`, `/scorecards`.
   - OR keep both with the symlinks indefinitely. Defer-able.
2. **Physical file move:** copy `/trsports_gd/html/{mgp,system,playbooks,scorecards}` → `/gt_dev/ams/`. Delete symlinks. Update `nav-config.json` paths.
3. **Update freshness JSON** to write to one path
4. **Update todos.json properties[].url** to canonical `/ams/<prop>/` paths
5. **Final audit pass** — Claude runs the 2026-05-16 audit format again. Compare scorecard.
6. **Backup + rollback plan** documented in `/system/AMS-INTEGRATION-PLAN-v1-runbook.md`
7. **User docs:** one-page onboarding for new trader joining the system

**Exit criteria:**
- Audit re-run shows 0 cross-property duplicate-source bugs
- One physical file tree under `/gt_dev/ams/`
- 301 redirects honored from old paths
- Onboarding doc validated by adding 1 test user end-to-end

**Dependencies:** Phase 4 complete.

**Risk:** **MEDIUM** — file moves break bookmarks. Mitigation: maintain 301s for 90 days; announce 30 days before any decommission.

---

## 4 — GANTT Chart

```mermaid
gantt
    title AMS Integration Plan v1 — 2026-05-18 to 2026-09-11
    dateFormat YYYY-MM-DD
    axisFormat %m/%d

    section Phase 0 Foundation
    p0-freshness-dashboard       :p0a, 2026-05-18, 5d
    p0-orchestrator              :p0b, 2026-05-18, 7d
    p0-identity-fn               :p0c, 2026-05-20, 6d
    catalog-refactor-shared-json :p0d, 2026-05-21, 5d
    p0-param-surface-registry    :p0e, 2026-05-25, 4d
    p0-indicator-alerts-ddl      :p0f, 2026-05-18, 2d
    Phase 0 exit review          :milestone, p0x, 2026-05-29, 0d

    section Phase 1 Auth
    Port login + 2FA             :p1a, after p0x, 7d
    Port reset + lockout         :p1b, after p1a, 3d
    Apache mod_auth_request      :p1c, after p1a, 4d
    Session cookie hardening     :p1d, after p1c, 2d
    Admin user-management page   :p1e, after p1b, 5d
    Phase 1 exit review          :milestone, p1x, 2026-06-19, 0d

    section Phase 2 Identity
    user_scope SQL fn            :p2a, after p1x, 3d
    auth_scope_clause helpers    :p2b, after p2a, 3d
    Seed teams/groups            :p2c, after p1x, 2d
    Re-scope daily-summary-view  :p2d, after p2b, 4d
    scope-debug admin tool       :p2e, after p2b, 2d
    Phase 2 exit review          :milestone, p2x, 2026-07-03, 0d

    section Phase 3 Shell
    /_shell/ header+footer       :p3a, after p2x, 4d
    Identity chip + freshness    :p3b, after p3a, 3d
    Theme tokens extraction      :p3c, after p3a, 4d
    Apache rewrites              :p3d, after p3b, 2d
    Mobile responsive            :p3e, after p3b, 3d
    Phase 3 exit review          :milestone, p3x, 2026-07-17, 0d

    section Phase 4A Cockpits
    HUD v2 scope wiring (Jimbo)  :p4a1, after p3x, 10d
    Daily Stop auth wrap         :p4a2, after p3x, 3d
    Live Classifier (Roberto)    :p4a3, after p3x, 7d

    section Phase 4B Lenses
    Scorecards rewire            :p4b1, after p3x, 7d
    Monthly Reports rewire       :p4b2, after p4b1, 5d
    Param Surface registry use   :p4b3, after p3x, 6d
    MGP daily-stop pipe          :p4b4, after p3x, 4d
    Strategy Library + approval  :p4b5, after p3x, 5d
    Playbooks owner/share        :p4b6, after p4b5, 5d
    MTF VP TradingView handler   :p4b7, after p3x, 6d

    section Phase 4C PM
    Todos per-user filter        :p4c1, after p4b6, 4d
    Audit log admin page         :p4c2, after p4c1, 3d
    Phase 4 exit review          :milestone, p4x, 2026-08-28, 0d

    section Phase 5 Migration
    Domain decision              :p5a, after p4x, 2d
    Physical file move           :p5b, after p5a, 3d
    301 redirects                :p5c, after p5b, 2d
    Audit re-run                 :p5d, after p5c, 2d
    Onboarding docs              :p5e, after p5c, 3d
    Final exit review            :milestone, p5x, 2026-09-11, 0d
```

(Mermaid renders in any Markdown viewer that supports it — GitHub, VS Code, Obsidian. If you want a static image, the same chart description converts cleanly to mermaid.live for export.)

---

## 5 — Critical Path

```
p0-identity-fn (5/20→5/26)
    → user_scope SQL fn (6/22→6/24)
        → auth_scope_clause helpers (6/25→6/27)
            → Scorecards rewire (7/20→7/27)
                → Monthly Reports rewire (7/28→8/01)
                    → Todos per-user filter (8/22→8/26)
                        → Audit log page (8/27→8/29)
                            → Final exit review (9/11)
```

**Total critical path length:** 17 weeks (2026-05-18 → 2026-09-11)

If `p0-identity-fn` slips, **every** downstream phase slips by the same amount. Same for `user_scope` SQL fn. Protect these two.

**Slack on parallel branches:**
- HUD v2 wiring depends only on Phase 3 exit + Jimbo availability — has ~2 weeks of slack against Phase 4 close
- MTF VP TradingView handler — independent, ~3 weeks of slack
- Playbooks owner/share — depends on Strategy Library approval pattern but otherwise independent

---

## 6 — Dependency Matrix (cross-phase)

| Downstream | Upstream blockers |
|---|---|
| Auth (Phase 1) | none |
| user_scope SQL fn (P2) | `p0-identity-fn` (P0) |
| App Shell (P3) | Phase 1, Phase 2 |
| Each cockpit (P4A) | Phase 3, HUD-off-limits sign-off from Jimbo |
| Each lens (P4B) | Phase 3, `p0-identity-fn`, generator already exists |
| Scorecards rewire | `daily-summary-view` re-scoped (P2) |
| Monthly Reports rewire | Scorecards proves the pattern first |
| Strategy Library + approval | `add-user-role-approval` (already in queue), `catalog-refactor-shared-json` (P0) |
| MGP daily-stop pipe | `daily-settings.php` exists (it does) |
| Migration (P5) | Phase 4 complete + James decides domain |

---

## 7 — Risk Register

| # | Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|---|
| R1 | Phase 0 deliverable slips (identity-fn especially) | MEDIUM | Critical path slip | Identity-fn is the smallest of the 6 — front-load it. Two paths in parallel: SQL fn + PHP wrapper. |
| R2 | HUD-off-limits coordination drag with Jimbo | HIGH | Phase 4A slip up to 2 weeks | Carve HUD work into PRs Jimbo reviews on his cadence. Other lenses keep moving. |
| R3 | Auth code lift introduces a credential-handling bug | MEDIUM | Could leak tokens or lock everyone out | Build in dev, force re-enrollment, run 1 week with James-only access before opening to team. |
| R4 | Per-surface rewires reveal hidden hardcoded user_ids (more than the audit found) | HIGH | Phase 4B extends by 1-2 weeks | Time-box each surface to 1 week. If overrun, ship with explicit `--user_id=2` flag for safety, fix in Phase 5. |
| R5 | Symlink/docroot inconsistencies cause 404s during migration | MEDIUM | User-visible breakage | Phase 5 with 301 redirects + 30-day notice + announced cutover. |
| R6 | Roberto unavailable for Live Classifier wiring | MEDIUM | Phase 4A slips for one cockpit | Live Classifier already has 2 open tasks owned by Roberto — coordinate via Tracker tickets before Phase 4 start. |
| R7 | "Default not shared" policy frustrates the team in daily use | LOW-MEDIUM | Adoption friction | Bulk-set `willing_to_share=true` for internal team during Phase 2 seeding; document opt-out. |
| R8 | `accountability_dev` → `accountability` promotion timing conflicts with Phase 4 wiring | MEDIUM | Cockpit double-rewire | Coordinate with `acct-v2-promote-dev-to-prod` task — promote BEFORE Phase 4A starts. |
| R9 | Discovery of TradingView webhook secrets needing rotation post-auth-rollout | LOW | Inbound alerts pause for hours | Rotate per-user `alert_users.shared_secret` AFTER Phase 1 stable, with 24h dual-secret overlap. |
| R10 | New trader onboarding breaks mid-rollout | LOW | Single-user impact | Use the Phase 5 onboarding doc as the test; if it fails, fix before declaring done. |

---

## 8 — Open Decisions (need James input — non-blocking for plan publication)

| # | Decision | Recommended default | When it must be made |
|---|---|---|---|
| D1 | Canonical domain: smb.a1prospect.com or trsportsacademy.com? | smb.a1prospect.com | Before Phase 5 file move (8/31) |
| D2 | Auth stack: stay on raw PHP sessions or invest in framework now? | Stay on raw PHP sessions (port from journal) | Before Phase 1 start (6/01) |
| D3 | DB: build everything in `_dev` and promote, or split per-property? | Build in `_dev` schemas, promote all at once before Phase 4B start | Before Phase 2 start (6/22) |
| D4 | Team sharing default: opt-in (`willing_to_share`) or opt-out? | Opt-in for non-firm users; bulk-enable for the 6-trader internal firm | Before Phase 2 team seeding (6/25) |
| D5 | Should risk_hud be archived (per audit) or built? | Archive — accountability-v2 subsumes it | Before Phase 0 exit (5/29) |
| D6 | Mandatory 2FA for which roles? | Required for admin + enterprise_admin; remembered-device for trader | Before Phase 1 testing (6/12) |
| D7 | Old Daily Stop tool at `/daily-stop/` — keep as-is or fold into HUD? | Keep as-is (Phase 4A2 just wraps it in auth). HUD-fold is a v2 question. | Before Phase 4A start (7/20) |

---

## 9 — Success Metrics

Plan succeeds when, on 2026-09-11:

1. **One login** lands a user (e.g. Nolan) on a dashboard scoped to his trades only
2. **One nav** lets him reach every property; HUD shows his P&L, Scorecards his execution grade, Monthly his trend
3. **Sharing works:** if Brian sets `willing_to_share=true` and is in Nolan's group, Nolan sees Brian's trades in the team-view toggle (but not by default)
4. **One audit log** records every login, every "switch user" admin action, every daily-stop change
5. **No surface is broken** — re-running the 2026-05-16 audit format shows 0 cross-property duplicate-source bugs
6. **One docroot** physically holds all 11 properties (`/gt_dev/ams/`)
7. **One onboarding doc** can take a new trader from zero to logged-in-and-trading in under 30 minutes

---

## 10 — What This Plan Does NOT Cover

Out of scope (deferred or already covered elsewhere):

- **Building new strategies** (handled in Strategy Library workflow)
- **Backtest infrastructure changes** (param-surface-registry is the only relevant piece)
- **Production-grade monitoring/alerting** (orchestrator + freshness dashboard cover the basics; deeper observability is post-v1)
- **Mobile-native app** (web responsive only)
- **Customer-facing marketing site / signup flow** — trsportsacademy.com keeps that role if D1 chooses smb as canonical
- **Compliance/SOC2 hardening** (audit log is foundation; full compliance is post-v1)
- **Replacing PHP with a framework** (recommended deferred to v2 — would add ~6 weeks)

---

## 11 — Next Concrete Actions

If James approves this plan as v1:

1. **Today (5/16):** James reviews this doc; records decisions on D1-D7 in the Open Decisions table
2. **Mon 5/18:** Claude starts Phase 0 work autonomously from the foundation queue (already audit-blessed)
3. **Wed 5/20:** Mid-week check-in — does the Phase 0 cadence match the GANTT?
4. **Fri 5/29:** Phase 0 exit review with James → decide whether to proceed to Phase 1 on Monday 6/01
5. **Each phase exit:** 30-min review meeting between James + Claude + relevant builders, signed off in `/system/AMS-INTEGRATION-PLAN-v1-status.md`

---

**End of plan v1.** Revisions will create v1.1, v1.2 etc. with diff log in a new section. Decisions in §8 should be answered before Phase 1 kickoff.
