Commit History
-
fix: upgrade Meta Graph API from deprecated v18/v19 to v22.0
CognxSafeTrackAll hardcoded v18.0 and v19.0 references replaced with a centralized META_GRAPH_API_VERSION env var (default: v22.0). v19.0 was deprecated in February 2026 causing messaging_limit_tier to silently disappear from the /clients daily-limit card. Also improves error visibility: the catch block in fetchMetaStatus now logs the full error instead of swallowing it silently, and a warn is emitted when messaging_limit_tier is absent even on a successful response (signals a missing BUSINESS_MANAGEMENT permission).b25d16e
-
fix(audit): resolve all remaining technical debt issues
CognxSafeTrackC2 - analytics SQL injection: UNION detection, ALLOWED_TABLES allowlist, remove SQL from error responses to prevent schema leakage H1/H2 - override-feedback: move organizationId validation to top of handler before any DB mutation; scope enrollment.findFirst to org H6 - UserListPage: add pagination controls (Précédent/Suivant, 20 per page) L4 - TrackDaysPage: await load() before closing editor to prevent stale data race L5 - admin.ts: replace getOrganizationId() with req.organizationId at 3 call sites, remove now-unused import M1 - EntityResolver: replace any[] types with proper Prisma payload types (ResolvedUser/Contact/Organization/Enrollment with exact include shapes) L8 - AI command fuzzy org match: return pending_confirmation when org found by partial name match, inject orgId for unambiguous confirmation retrya888244 -
feat: CSV export, monthly report, and quota alert plan filter
CognxSafeTrack- BillingPage: add "CSV" download button that exports all wallet transactions (date, type, description, amount, balance) as UTF-8 CSV - scheduler.ts: add startMonthlyReportScheduler() — cron on 1st of month 07:30 UTC; sends per-org recap of AI calls, WhatsApp messages, top-3 features, credits recharged/spent, and current balance - index.ts: register startMonthlyReportScheduler() alongside existing crons - usage-tracker.ts: quota alert (85% threshold) now only fires for GROWTH, SCALE, and ENTERPRISE plans; STARTER alerts were high-noise / low-valuea24fb7f
-
fix: security hardening, real AI costs, traceId propagation & audit logging
CognxSafeTrack +1: Claude Sonnet 4.6- S1: enforceOrgIsolation — organizationId always from JWT for non-SUPER_ADMIN (header ignored) - S4: auditService.log() on ORG_MODE_CHANGED, ORG_PERSONALITY_UPDATED, ORG_BYOK_KEYS_UPDATED - O1: traceId (UUID) generated at webhook, forwarded via x-trace-id header, injected into BullMQ job data, threaded through whatsapp-logic handler chain - D3: /v1/analytics/usage now aggregates real UsageEvent.costUsd + tokens (tokensIn/Out) with per-feature breakdown instead of token estimates - D4: BrandingDataSchema added to shared-types — brandingData strictly typed (logoUrl, primaryColor, orgName) instead of z.any() - A6: InboundHandler fetches user.language in parallel with org token, passes it to Whisper - A2: sendLessonDay() caches personalized lesson text in Redis 6h by (trackDayId, activity, language) - P1: sendLessonDay() parallelized — user+trackDay batched in one include, userProgress fetched in parallel - D2: ExerciseHandler Redis 30s dedup lock prevents double exercise submission Co-A…87afdf1 -
feat(agentic-week1): conversational memory, RAG threshold, wallet alerts, weekly reports, campaign scheduling
CognxSafeTrack +1: Claude Sonnet 4.6- AIAgentHandler: Redis sliding window (20 entries, TTL 24h) for conversation history injected into system prompt — AI_AGENT now remembers context - IndexingService.searchRelevantContext: cosine threshold 0.70 — returns '' if no chunk is relevant so agent responds honestly instead of hallucinating - add-hnsw-index.ts: one-shot HNSW index script (m=16, ef=64) for ~10x faster pgvector cosine search on large knowledge bases - scheduler.ts: hourly wallet alert (email via Brevo if < 3 days runway, 6h Redis suppression) + weekly report every Monday 07:00 UTC with trend vs previous week and color-coded wallet status - queue.ts + campaigns.ts: sendAt ISO-8601 parameter on broadcast/campaign routes — BullMQ delay option schedules jobs natively, no cron needed - docs/agentic/: roadmap updated with Semaine 1 marked complete Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>98240fd -
refactor(worker): Sprint 2 — dead code removal and queue consolidation
CognxSafeTrack +1: Claude Sonnet 4.6H1: Delete credit-guard.ts (worker) and credit-cache.ts (api) — both fully superseded by wallet.ts/requireCredits.ts since the wallet migration. H6: Introduce lib/queues.ts with shared whatsappQueue and notificationQueue instances. Replace all 10 inline `new Queue(...)` calls across wallet.ts, usage-tracker.ts, whatsapp-logic.ts, scheduler.ts, and 4 handlers. Removes 10 redundant Redis connections; drops `q.close()` calls on ephemeral instances that were killing the shared connection. Shutdown handler now explicitly closes both shared queues. Scratch: Move apps/api/scratch/ one-shot DB scripts to scripts/db-ops/ so they don't ship in the production API bundle. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>37fb9ce -
fix(security): Sprint 1 — five critical debt fixes
CognxSafeTrack +1: Claude Sonnet 4.6C1: Await debitWallet() in usage-tracker and broadcast/campaign handlers so billing failures are caught and logged, not silently swallowed. C2+C3: Rewrite debitWallet() as a single Prisma interactive transaction: balanceAfter now set atomically; isHardStopped flag set in the same transaction as the balance decrement — no window between debit and stop. C4: Add X-Hub-Signature-256 HMAC-SHA256 verification to POST /webhook. Uses preParsing hook for raw body capture; fails open when WHATSAPP_APP_SECRET is not configured. H3: Fix payment webhook race condition — use updateMany(where: PENDING) as atomic idempotency guard; only the request that flips PENDING→COMPLETED proceeds to enrollment creation. H7: Replace $queryRawUnsafe/$executeRawUnsafe with $queryRaw/$executeRaw Prisma.sql template literals in indexing.ts; user-controlled values (organizationId, limit) are properly parametrized. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>fae3e96 -
feat(billing): implement full wallet/ledger system with hard-stop enforcement
CognxSafeTrack +1: Claude Sonnet 4.6- Add walletBalance + isHardStopped to Organization schema; WalletTransaction ledger model with full audit trail - wallet.ts (worker): debitWallet (atomic $transaction), creditWallet (with AuditLog), checkWalletBalance (Redis 30s cache), alert queuing (low/critical/exhausted/restored) - wallet.ts (api): creditWallet for admin top-up with cache invalidation - usage-tracker.ts: debitWallet integrated into trackAiUsage, trackAudioUsage, trackWhatsAppSent; BYOK orgs skipped - BroadcastHandler + CampaignHandler: bulk debit after send (BROADCAST_PER_USER per recipient) - requireCredits.ts: migrated from aiCreditsUsed/Limit to walletBalance/isHardStopped; shares Redis cache key with worker - whatsapp-logic.ts: replaced assertCredits/CreditExhaustedError with checkWalletBalance/WalletExhaustedError - ai.ts: added requireCredits preHandler to all 11 AI routes (was 4) - billing.ts: /admin/allocate now calls creditWallet(); new GET /wallet route (balance + 20 last txns) - BillingPage: wallet card…0fd3320 -
feat(billing): enforce AI credit limits across all surfaces
CognxSafeTrack +1: Claude Sonnet 4.6- credit-guard.ts (worker): assertCredits() blocks AI when creditsUsed >= creditsLimit; Redis cache 60s prevents DB hit on every message - whatsapp-logic.ts: credit guard injected before handler chain; RECHARGE keyword bypasses the guard so users can always request a payment link - CommandHandler: new RECHARGE keyword sends payment URL or contact message - i18n: credit_exhausted + recharge_link + recharge_contact in 5 languages - requireCredits middleware (api): 402 on personalize-lesson, tts, generate-feedback, crm/generate-campaign - billing route: POST /v1/billing/admin/allocate (SUPER_ADMIN only) supports set/add actions + optional usage reset + Redis cache invalidation - ClientsManagementView: "Crédits IA" button (SUPER_ADMIN only) per org opens allocation modal with set/add/reset controls - BillingPage: red exhaustion banner when creditsUsed >= creditsLimit Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>6484585
-
feat(billing): complete billing system, push notifications, and tech debt fixes
CognxSafeTrack +1: Claude Sonnet 4.6- Usage tracking: instrument pedagogy, audio transcription, AI Agent mode (was silently untracked) - EmailHandler: implement templates 2 (password reset), 3 (quota alert), 4 (monthly report) - Quota alert: auto-queue email + push at 85% threshold via maybeQueueQuotaAlert - Push notifications: PushHandler + send-push BullMQ job; sendPushToUser scoped by organizationId to prevent cross-tenant reads - BillingPage: add credit recharge modal with 3 packs, null guard for missing orgId - i18n: add nav.billing key in fr/en/es/pt locales - Tests: billing.test.ts (10 tests), payments.test.ts (13 tests) - Tech debt: fix empty catch blocks in ai-pedagogy.ts, exclude usage tokens from CRM API response, pass organizationId to generateChat in AIAgentHandler - Docs: add backlog and business model to docs/business/ Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>8280d7d
-
refactor(debt): resolve all 10 technical debt items from audit
CognxSafeTrack +1: Claude Sonnet 4.6- Redis: singleton pattern (lib/redis.ts) in api + worker, removes 16+ new Redis() calls - Meta token: systemUserTokenIssuedAt field + weekly cron monitor (warn @50d, critical @55d) - Rate limiting: @fastify/rate-limit global 200/min, login 10/min, forgot-password 3/min - Dead code: delete WhatsAppConnectButton.tsx, archive one-off scripts - Silent catches: logger.warn(err) on all backend catch blocks, console.warn on frontend - Meta API types: 5 typed interfaces replace 6 as any casts in organization.ts - Frontend logger: lib/logger.ts wraps Sentry (active when VITE_SENTRY_DSN is set) - Migration: add systemUserTokenIssuedAt + metaBusinessId to Organization schema Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>a966957
-
fix(webhook+worker): restore gateway forwarding and fix token decryption
CognxSafeTrack +1: Claude Sonnet 4.61. Gateway architecture restored (whatsapp.ts) - When RAILWAY_INTERNAL_URL is set (HF Space), forward raw payload to Railway worker bridge instead of adding directly to Redis. - Original architecture: HF → Railway bridge → Redis → Worker. - Root cause of INSCRIPTION silence: direct Redis queue from HF Space was failing because Redis connection doesn't work from HF containers. 2. MessageHandler: decrypt systemUserToken before use - Was reading org.systemUserToken raw (AES-encrypted) from prisma, sending encrypted string to Meta → auth failure. - Now uses getCachedOrganization() which calls decryptOrgSecrets(). 3. AdminHandler: eliminate double DB query + empty enrollmentId - Was calling prisma.enrollment.findFirst() twice for same record. - Validates enrollment exists before proceeding; adds mediaUrl to Response. 4. CommandHandler: route MENU_HISTORIQUE through queue - Direct sendInteractiveListMessage() call bypassed tenant config. - Now use…2b96936
-
feat: implement whatsapp templates management with security hardening, audit logs, and crm integration
CognxSafeTrack0f2f80a -
chore: stabilization, audit fixes and project synchronization
CognxSafeTrack7b0c22b
-
fix: log silent catch blocks, remove emojis from production logs
CognxSafeTrack +1: Claude Sonnet 4.6- MediaHandler.ts: .catch(()=>({})) on normalization rules now logs warning with err context before returning empty fallback - indexing.ts: catch{} on URL parsing now logs at debug level; remove duplicate logger import - index.ts: remove emoji characters from logger calls (🚀 ❌ 🛑 👋) — replaced with plain ASCII text prefixes for clean log aggregation Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>3165bfa -
fix: security hardening, log all silent catch blocks, remove prisma cast
CognxSafeTrack +1: Claude Sonnet 4.6Security: - whatsapp.ts: remove WHATSAPP_VERIFY_TOKEN hardcoded fallback — return 500 if env var is missing instead of silently accepting a public default - rateLimit.ts: key by req.ip (not spoofable x-organization-id header) Code quality — 7 empty catch blocks now log with context: - NudgeHandler, AdminHandler (+ missing logger import), EnrollHandler (x2), MediaHandler (x2), organization.ts invalidateOrgCache - admin.ts: remove (prisma as any).normalizationRule — model is in schema, cast was unnecessary Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>aa4f69f -
fix: worker cleanup await, Stripe upsert completeness, redundant schema index
CognxSafeTrack +1: Claude Sonnet 4.6- cleanup.ts: cron callback now async/await so cleanWorkerTempFiles() errors are caught instead of silently dropped fire-and-forget - payments.ts: upsert update clause now includes status, amount, currency so a Stripe webhook replay fully idempotent instead of leaving stale fields - schema.prisma: remove redundant @@index([userId, trackId]) on UserProgress — the @@unique constraint already creates a B-tree index on those columns Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>ec9b5da -
feat: centralize AI logic in @repo /ai-sdk, harmonize worker HTTP clients
CognxSafeTrack +1: Claude Sonnet 4.6Architecture refactoring: - Extract all AI providers (OpenAI, Gemini, ProviderRegistry, ffmpeg, search) from apps/api/src/services/ai/ into new packages/ai-sdk package - API's services/ai/index.ts is now a thin wrapper that injects prisma, redis and organization context into the shared AIService - Worker gains @repo/ai-sdk dependency; ai-pedagogy.ts delegates to aiService.generatePersonalizedLesson instead of duplicating logic - New apiClient (Axios, 30s timeout) and whatsappClient replace bare fetch calls in InboundHandler and MediaHandler for consistent error handling - Prisma seed fixed: Tracks now include organizationId for multi-tenant compliance Build: all 8 packages pass pnpm turbo run build from clean state. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>2849f33 -
feat(crm): optimize multimedia pipeline and harden contact schema
CognxSafeTrack- Refactored CrmConversationalDashboard into modular components and hooks (FileImporter, useAudioRecorder) - Centralized contact normalization and bulk import in ContactService - Implemented binary streaming for media proxy to reduce memory pressure - Hardened database schema with MediaType Enum for better data integrityc5fde49 -
feat: implement inbound audio/image transcription, secure media proxy, and client-side bulk contact import
CognxSafeTrack30d60ea
-
chore: CRM stabilization sprint completion
CognxSafeTrack- Refactor: Decomposed CrmConversationalDashboard into modular components (Inbox, AIAssistant, StatsHeader) - Fix: Centralized entity resolution with EntityResolver service (API & Worker) - Fix: Strict Prisma typing, removed 'as any' casts in organization and whatsapp routes - Fix: Implemented broadcast message persistence and accurate usage quota tracking - Schema: Added MessageStatus and status field to Message model4339e77 -
refactor: resolve critical tech debt in CRM broadcasts and usage tracking
CognxSafeTrackd983a7d -
fix: resolve prisma type mismatches in monorepo using explicit casts
CognxSafeTrack2088906 -
feat: implement inbound message tracking and CRM inbox view
CognxSafeTracke01e314 -
chore: finalize Sprint P2 & P3 optimizations, baseline prisma migrations, and update technical audit docs
CognxSafeTrackcfbb685 -
fix(worker): align BullMQ to v5, Fastify to v5, drop node-fetch v2 CVE
CognxSafeTrack +1: Claude Sonnet 4.6API was on BullMQ 5.x while worker stayed on 4.x — jobs enqueued by the API were silently unprocessable by the worker. Both now resolve to 5.69.3. Fastify upgraded from 4.x to 5.x for consistency with the API container. node-fetch v2 (CVE) removed; Node 20 native fetch used instead. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>83f9d2d
-
audit: implement storage isolation and worker bridge hardening
CognxSafeTrack6019d2d
-
feat: migrate to multi-tenant SaaS architecture with JWT auth and BullMQ notifications
CognxSafeTrack2ab1980
-
feat: Premium Onboarding with Meta SDK and Technical Debt resolution
CognxSafeTrack6248bf4
-
feat: B2B SaaS Multi-tenant architecture & Tech Debt Resolution
CognxSafeTracke289c5c -
chore: stabilize whatsapp-worker with strict typing and multi-tenant hardening
CognxSafeTrack1a00f18
-
feat: finalize multi-tenant WhatsApp architecture for Meta Tech Provider review
CognxSafeTrack3bf9adc
-
Refactor: Modularize WhatsAppLogic into specialized Handlers (Command Pattern)
CognxSafeTrackfb4b8be -
Fix: Add Garbage Collector (GC) for media and temp files
CognxSafeTrackf4e46e8 -
Fix: Add Cascade Delete for UserBadge and TeamMember during INSCRIPTION reset
CognxSafeTrack2e888dc -
Refactor: Technical Debt Repayment (Clean Dashboard, Strict Typing, Pino Logging, SQL Migration)
CognxSafeTrackde6a95b
-
feat: Fix Time-Travel Replay & Deep Dive logic via Redis Context Override
CognxSafeTrack0785ad1
-
feat: Time-Travel complet via Redis — effectiveDay override, coupe-circuits SUITE/INSCRIPTION, skip COMPLETED en mode replay
CognxSafeTrackd978795 -
feat: 4 UX/backend fixes — anti-ghost image, time-travel replay, UX message order, contextual AI remediation
CognxSafeTracka4ce760 -
fix: comprehensive vision hardening (loosen wordcount bypass + 60s timeout)
CognxSafeTrack184eeee
-
feat: upgrade Vision to GPT-4o with J11 bypass and enhanced logging
CognxSafeTrack5fae74c -
fix: restore image interception and vision pipeline with [IMAGE-FLOW] logs
CognxSafeTrack78e4fe8 -
feat: Implement Non-Blocking Card UX and Prompt Hook Hook
CognxSafeTrack635e9f4 -
fix: Unlock Day 7 Button Handlers and Optimize AI Latency
CognxSafeTrack582a75d -
fix: Implement 5-minute re-validation window and Flow Sync Logging
CognxSafeTrackcd7ba04 -
fix: Resolve Production Crash & Add UX Guidance for Completed Exercises
CognxSafeTrackd9186b1 -
chore: Add observability log for feedback enqueuing
CognxSafeTrackcaa20c8 -
fix: Resolve Production Crash (Gemini 404, OpenAI Zod, Job Payload mismatch)
CognxSafeTrack9f4922e -
feat: Async-First Webhook Architecture & Idempotency Hardening
CognxSafeTrack74e06ff