All documentation

Production Code Audit Report

Phase 1 of the Beta Launch readiness pass — a code-level sweep for duplication, dead code, and performance/query issues. Every fix below was verified with tsc --noEmit + eslint + the full test suite passing after the change, and each is small and mechanical enough to be low-risk against a codebase this mature. Security is covered separately in docs/SECURITY_REVIEW.md (Module 9) and extended further in this same launch pass — see the Beta Launch materials for the full security audit.

What this audit did NOT try to do

npx knip (unused-exports/dead-file detection) was attempted but fails in this environment on a native-binding load error (oxc-resolver/@oxc-resolver/binding-win32-x64-msvc), unrelated to this codebase. Dead-code detection below was done manually — grep-based orphan-file detection (a file whose basename appears nowhere else in src//tests/ as an import specifier) cross-checked by hand, not an exhaustive automated sweep. A follow-up pass with working tooling would be worth doing but wasn't available here.

1. Duplicated code

Found and fixed: src/lib/connectors/mt5/reliability.ts carried a byte-for-byte duplicate of ReconnectScheduler, HeartbeatMonitor, and withLatency from src/lib/connectors/shared/reliability.ts. This was a deliberate, documented trade-off when shared/reliability.ts was first created (avoid touching the then-stable MT5 connector) — but every other connector (TradeLocker, Tradovate, Rithmic, DXtrade, cTrader, Match-Trader) already used the shared version, and the two files' implementations were confirmed still identical. Consolidated: MT5 now imports HeartbeatMonitor/ReconnectScheduler/withLatency from shared/reliability.ts alongside shouldAlertOnReconnectExhaustion (which it already imported from there), and the duplicate file is deleted (69 lines removed). No behavior change — same classes, same logic, one copy instead of two.

Checked, not duplicated: the per-connector sdk-adapter.ts files necessarily repeat a similar *shape* (login → normalize → cache) because each talks to a genuinely different wire protocol/REST API — this is the intended design (BaseConnector + TradingConnector interface factor out everything that IS truly shared; see docs/ARCHITECTURE.md). The design-system component library (src/components/ui/) was already fully consolidated in an earlier milestone — verified no leftover duplicate KpiCard/StatusBadge/BarChart/Sparkline/ PaginationControls/nav implementations remain outside ui/.

2. Dead code

Removed (confirmed zero importers anywhere in src//tests/, including barrel re-exports, and confirmed superseded by a newer component actually wired into the real routes):

  • src/components/copier/account-roles-panel.tsx — superseded by

master-accounts-panel.tsx + follower-accounts-panel.tsx, which the real /dashboard/copier/masters and /dashboard/copier/followers pages actually use.

  • src/components/copier/copy-logs-panel.tsx — superseded by

copy-logs-table.tsx, which the real /dashboard/copier/logs page actually uses. (Both files' own doc comments referenced each other and the deleted files by name — updated to stop pointing at removed code.)

Found, reviewed, deliberately retained (self-documented as intentional forward architecture not yet wired to a call site — the same "real port/function, honestly not connected this milestone" pattern already established for RithmicUnimplementedTransport and UnconfiguredPushProvider, just without an automatic default wiring that those two have):

  • src/lib/ai/services/memory-service.ts — a complete, real

AIMemoryService (extracts durable per-user facts from AI conversations into the real ai_memories table) that nothing calls today: no conversation flow invokes extractAndStoreMemories() after a chat, no UI calls listMemories(). Added a doc comment stating this plainly (it previously had none), since this codebase's convention is to say so explicitly rather than leave it silently unreferenced.

  • src/lib/automation/sync-bridge.ts's evaluateSyncEvent() — already

self-documented as "NOT called from anywhere in this codebase today," a wiring point for whenever a live inbound trade-signal receiver exists. Left as-is.

  • src/lib/ai/market/unconfigured-provider.ts and the MarketDataProvider

port it implements (market/types.ts) — already self-documented ("mirrors RithmicUnimplementedTransport... no vendor was named for this milestone"), and market/types.ts's doc comment is actively referenced by two other real, live files (automation-engine.ts, intelligence-service.ts) explaining their own honest "no live market-data feed" behavior. Deleting it would remove load-bearing documentation of a real product decision, not just unused code.

These three were judgment calls, not mechanical deletions — flagged here explicitly rather than silently deleted or silently left unmentioned.

3–4. Performance / unnecessary API calls / database queries

Fixed: AIEmbeddingService.embedAndStore() (src/lib/ai/services/embedding-service.ts) looped over every text chunk doing one AIProviderManager.embed() HTTP call AND one ai_embeddings insert per chunk — despite AIEmbeddingRequest.input already being typed string | string[] and OpenAI's real embeddings endpoint (the only provider STANDARD_EMBEDDING_MODEL is served by) natively accepting a batch and returning results in the same order. Rewrote to one embed() call with all chunk texts plus one batched insert() with every row — for a document chunked into N pieces, N sequential AI round-trips + N sequential DB writes become 1 + 1. Doesn't sub-batch beyond that (no call site in this codebase produces a document large enough to approach OpenAI's 2048-input batch limit).

Fixed: isFeatureEnabled() (src/lib/feature-flags/queries.ts) — the maintenance-mode check that runs on every single dashboard page load (src/app/dashboard/layout.tsx) — did two sequential round trips (fetch the flag, then fetch its overrides). Collapsed into one query using Supabase's embedded-resource join over the real feature_flag_overrides.flag_id foreign key (already indexed). Halves the DB round trips on the highest-traffic query path in the app.

Reviewed, not flagged as issues:

  • Every other select('*') found (supabase-conversation-persistence.ts,

incidents-queries.ts, feature-flags/queries.ts's admin listing) is against small, narrow tables where every returned column is actually consumed by the corresponding row-mapping function — not a real over-fetch.

  • No N+1 query loops found elsewhere: a targeted regex sweep for

for (const ... of ...) loops containing an await supabase/await svc call within them, across every file in src/lib, returned no other matches. Every admin list/analytics query already batches or uses Promise.all for independent reads (e.g. listFeatureFlagsWithOverrides fetches flags and overrides in parallel already — the pattern isFeatureEnabled above now follows too, via a join instead of two parallel queries since the second genuinely depends on the first's id).

  • No aggressive client-side polling found — grepped every

src/components/** for setInterval calls under 5 seconds; found none (the one setInterval hit was an unrelated state setter named setInterval in the billing plan toggle, not a timer). Every connector's REST-polling interval (TradeLocker/DXtrade/Match-Trader, 5s default) and every dashboard live-data refresh already uses Supabase Realtime subscriptions or manual refresh, not tight polling loops.

5. Security

Covered by docs/SECURITY_REVIEW.md (encryption, API keys, MFA, sessions, rate limiting, audit logging) and extended with a full audit across authentication, authorization/RLS, JWT handling, injection (SQL/XSS/CSRF), rate limiting, API abuse, and secrets/env var hygiene — see the Beta Launch security audit for the complete pass.

Verification

tsc --noEmit clean · eslint 0 errors (2 pre-existing unrelated warnings, unchanged) · full test suite passing · production build green — run after every change in this report, not just once at the end.