compliance: flag-gate AI portfolio + cloud sync + Stripe; de-risk prompts; harden reviewer

Implements docs/read-markets-compliance-changes.md as flag-gated changes
(no deletions) so paused features stay in the tree for future re-enable.
All four flags default False so a fresh deploy is compliance-safe.

- New env flags: PORTFOLIO_AI_ENABLED, PORTFOLIO_SYNC_ENABLED,
  TICKER_UNIVERSE_AGGREGATE_ENABLED, SUBSCRIPTIONS_ENABLED.
- Gates: /api/analyze, /api/portfolio/sync*, /api/stripe/*, /pricing,
  ticker_universe writes, portfolio_analysis.analyse(). is_paid_active()
  returns True for any auth'd user when subscriptions are paused.
- Prompts (PROMPT_VERSION 10): universal _COMPLIANCE_RIDER prepended to
  every system prompt; watch list removed; price-target / close-above-below
  / trigger / forward-state-as-description rules added; SPECULATIVE
  pivoted to regime-only scenarios; daily + weekly digests tightened.
- Reviewer: deterministic regex/lexicon pre-check fail-closed under the
  Haiku call; portfolio rider gated by PORTFOLIO_AI_ENABLED; base prompt
  sharpened for forward-state and MAR forward-opinion patterns;
  ReviewerVerdict audit table; generate_with_review retry helper.
- Migration 0026: purge portfolio_sync + ticker_universe; create
  reviewer_verdicts.
- Copy: MAR cite fixed to Art 3(1)(35) + Art 20 + Del Reg 2016/958;
  portfolio reframed as browser-only viewer in disclaimer / privacy /
  terms / about / pricing / landing (en + it). TODO(legal) marker for
  lawyer sign-off on disclaimer.
- Tests: 13 lexicon + 6 reviewer compliance regressions; conftest enables
  all flags so existing 402 tests still cover their code paths.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Giorgio Gilestro 2026-05-29 19:57:12 +02:00
parent ee8384f1ba
commit 47dce1a1a4
38 changed files with 1188 additions and 279 deletions

View file

@ -188,7 +188,8 @@ async def chat(
# leading question; the generator's system prompt forbids it,
# but the reviewer is the enforcement layer. ~1-2 s extra
# latency per turn on top of the generation call.
verdict = await review_read(client, result.content)
verdict = await review_read(client, result.content,
surface="chat", session=session)
except Exception as e:
session.add(AICall(
model=s.OPENROUTER_MODEL, status="error", error=str(e)[:500],

View file

@ -16,6 +16,7 @@ from fastapi.responses import HTMLResponse
from app.auth import CurrentUser, maybe_current_user
from app.services.access import is_paid_active
from app.services.feature_flags import require_flag
from app.templates_env import templates
@ -29,7 +30,11 @@ def _ctx(request: Request, cu: CurrentUser | None) -> dict:
return {"cu": cu}
@router.get("/pricing", response_class=HTMLResponse)
@router.get(
"/pricing",
response_class=HTMLResponse,
dependencies=[Depends(require_flag("SUBSCRIPTIONS_ENABLED"))],
)
async def pricing_page(
request: Request,
cu: CurrentUser | None = Depends(maybe_current_user),

View file

@ -34,10 +34,16 @@ from app.config import get_settings
from app.db import get_session, utcnow
from app.logging import get_logger
from app.models import StripeEvent, User
from app.services.feature_flags import require_flag
log = get_logger("stripe_billing")
router = APIRouter()
# Whole router gated by SUBSCRIPTIONS_ENABLED: checkout, portal, and webhook
# all 404 when the subscription system is paused. The webhook gate keeps us
# from accidentally processing a late delivery while the surface is "off".
router = APIRouter(
dependencies=[Depends(require_flag("SUBSCRIPTIONS_ENABLED"))],
)
# Cap stored payload at 16 KiB so a hostile (or buggy) sender can't

View file

@ -20,11 +20,17 @@ from app.db import get_session
from app.logging import get_logger
from app.services import portfolio_sync as svc
from app.services.access import require_paid
from app.services.feature_flags import require_flag
log = get_logger("portfolio_sync_router")
router = APIRouter(prefix="/api/portfolio/sync")
# Whole router gated by PORTFOLIO_SYNC_ENABLED: when the flag is off, every
# endpoint here 404s — indistinguishable from a non-existent surface.
router = APIRouter(
prefix="/api/portfolio/sync",
dependencies=[Depends(require_flag("PORTFOLIO_SYNC_ENABLED"))],
)
# A 256 KB cap is ~200× a typical pie's serialized size — generous

View file

@ -41,6 +41,7 @@ from app.models import Quote, QuoteDaily
from app.services import fx, portfolio_analysis, ticker_universe
from app.services.access import require_paid
from app.services.csv_import import CSVImportError, parse_t212_csv
from app.services.feature_flags import require_flag
from app.services.instrument_map import resolve_slice
from app.services.market import fetch as market_fetch
@ -338,7 +339,10 @@ async def parse_portfolio(
# ---------------------------------------------------------------------------
@router.post("/analyze")
@router.post(
"/analyze",
dependencies=[Depends(require_flag("PORTFOLIO_AI_ENABLED"))],
)
async def analyze_portfolio(
request: Request,
session: AsyncSession = Depends(get_session),
@ -349,8 +353,8 @@ async def analyze_portfolio(
is persisted. The ai_calls ledger row records tokens + cost, never
holdings.
Gated behind ``require_paid``: free-tier users get 402.
Admin bearer-token bypasses the gate for testing."""
Gated behind ``PORTFOLIO_AI_ENABLED`` (404 when off) and ``require_paid``
(402 for free tier when subscriptions are active)."""
# Read JSON body manually so we can enforce a hard size cap. FastAPI's
# default body limit is generous; we want tighter control here.
body = await request.body()