# Lakshmi — Systems Deep Dive

> The `libs/lakshmi/` area: 24 Nx libraries that implement the **personal
> finance intelligence platform** — every financial engine (budgeting, tax,
> investments, retirement, debt, credit, estate, crypto…) plus the shared core,
> persistence, AI, security, and integration substrate they all build on.

## What this area is

Lakshmi (named for the Hindu goddess of wealth and prosperity, per
`libs/lakshmi/README.md`) is Oshun's comprehensive personal-finance domain. It
is not one package but **24 separate `@lakshmi/*` Nx libraries**, each owning
one slice of an individual's or household's financial life: account aggregation,
transaction categorization, budgeting, investment analytics, tax optimization,
debt payoff, credit, retirement, insurance, estate, real-estate, crypto, income
(equity comp), goals, behavioral finance, household collaboration, business /
self-employment finance, plus the cross-cutting `core`, `db`, `security`,
`ai-engine`, `integrations`, `reporting`, and `alerts` libraries.

The code is genuine, domain-specific financial engineering rather than CRUD.
Money is handled as integer cents throughout; engines implement real algorithms
— Newton-Raphson IRR/XIRR and geometrically-linked time-weighted return
(`libs/lakshmi/investments/src/performance/returns.ts`), Cholesky-correlated
Monte Carlo with normal / lognormal / Student's-t distributions
(`libs/lakshmi/core/src/calculations/monte-carlo.ts` and
`libs/lakshmi/retirement/src/monte-carlo-projection.ts`), 2025 IRS bracket /
wash-sale tax-loss-harvest scanning (`libs/lakshmi/tax/src/tlh/scanner.ts`),
TF-IDF cosine categorization with a merchant fast-path
(`libs/lakshmi/transactions/src/categorization/engine.ts`), and an additively-
homomorphic analytics scheme
(`libs/lakshmi/security/src/homomorphic-analytics.ts`). Zod is used for runtime
validation of domain types and contracts.

### How the area is layered

Every library carries `scope:lakshmi` Nx tags plus a `lakshmi:tier:*` tag that
places it in the unidirectional boundary `core → domain → feature → app`
documented in `libs/lakshmi/README.md`. `@lakshmi/core` is tagged
`lakshmi:tier:core`; aggregation-style domains like `@lakshmi/accounts` are
`lakshmi:tier:domain`; higher-level orchestrators like `@lakshmi/ai-engine`,
`@lakshmi/security`, and `@lakshmi/db` are `lakshmi:tier:feature`. Two libraries
underpin the rest: `@lakshmi/core` supplies the money/percentage/date-range
primitives, the financial-calculation kernel, caching, and metrics every other
library imports; `@lakshmi/db` owns the Drizzle/Postgres schema (one schema
module per domain) plus connection pooling, migrations, and seed data.

### How the libraries relate

The domain engines compose downward: `@lakshmi/retirement` and `@lakshmi/goals`
reuse `@lakshmi/core`'s Monte Carlo and time-value-of-money kernels;
`@lakshmi/tax`, `@lakshmi/crypto`, and `@lakshmi/investments` share tax-lot and
cost-basis concepts; `@lakshmi/debt`'s payoff strategies consume its own
inventory model; `@lakshmi/integrations` orchestrates over the provider adapters
that physically live in `@lakshmi/accounts`. Cross-cutting libraries
(`@lakshmi/alerts`, `@lakshmi/reporting`, `@lakshmi/behavioral`,
`@lakshmi/ai-engine`) read from many domains to produce notifications, reports,
nudges, and AI recommendations.

## How it fits the wider system

These libraries are the engine room behind the `apps/lakshmi/*` applications and
their BFF. Per the README's stack, Lakshmi targets PostgreSQL + pgvector /
TimescaleDB (via `@lakshmi/db`), Redis caching (via `@lakshmi/core`), MinIO for
document storage (via `@lakshmi/integrations`), and external aggregation
providers (Plaid / Yodlee / MX / Finicity / Tink) plus credit bureaus, payroll,
and crypto data feeds reached through `@lakshmi/integrations` and
`@lakshmi/accounts`. The boundary discipline is the value: a feature library can
depend on a domain library and on `core`, but not the reverse, so the financial
calculation kernel stays free of orchestration concerns and is reusable across
every engine. Walk the "used by" edges on any node below to see exactly who
depends on it.

## Entity reference

### @lakshmi/core

The shared foundation every other Lakshmi library imports
(`libs/lakshmi/core/src/index.ts` re-exports `cache`, `metrics`, `primitives`,
`types`, and `calculations`). It owns the financial primitives (`money.ts`,
`percentage.ts`, `exchange-rate.ts`, `date-range.ts`, `time-series.ts`) and the
calculation kernel — compound interest, amortization, time-value-of-money
(`tvm.ts`), risk metrics, Social Security, tax brackets, and the
Cholesky-correlated Monte Carlo engine in `calculations/monte-carlo.ts` that
supports normal / lognormal / fat-tailed (Student's-t) return distributions.
Tagged `lakshmi:tier:core`; it is the bottom of the dependency graph.

### @lakshmi/db

The persistence layer (`lakshmi:tier:feature`). `src/schema/` holds one Drizzle
schema module per domain (`accounts.ts`, `transactions.ts`, `investments.ts`,
`tax.ts`, `retirement.ts`, … plus `enums.ts` and `namespaces.ts`), and
`src/connection.ts` builds workload-profiled `pg` pools fed by the
`LAKSHMI_DATABASE_URL` env var (it throws if unset — an honest fail-loud seam
rather than a silent default). It also carries a migration registry
(`migration-registry.ts`), migration runner (`migrations.ts`), and a real
seed-data set (`seed-data/` for tax brackets, contribution limits, retirement
tables, credit-score factors, insurance products, transaction categories, and
benchmarks) plus seed generators.

### @lakshmi/accounts

Open-banking account aggregation (`lakshmi:tier:domain`). Holds concrete
provider adapters under `src/providers/` (`plaid.ts`, `yodlee.ts`, `mx.ts`,
`finicity.ts`, `tink.ts`) behind a `router.ts` and shared `types.ts`, a `sync/`
engine (`engine.ts`, `polling.ts`, `mfa.ts`, `reconciliation.ts`,
`health-monitor.ts`), statement `import/` parsers for CSV / OFX / QIF / SWIFT /
PDF with dedup, and account `management/` (manual accounts, groups, metadata,
archive, export). This is the library that physically owns the provider
integrations that `@lakshmi/integrations` orchestrates over.

### @lakshmi/transactions

Transaction ingestion and enrichment. The `categorization/` engine (`engine.ts`)
is a TF-IDF cosine-similarity classifier over a category taxonomy
(`taxonomy.ts`) with confidence tiers (HIGH/MEDIUM/LOW/VERY_LOW) and a merchant
fast-path, alongside `rules.ts`, `multi-label.ts`, and `personalization.ts`. It
also has merchant normalization/enrichment/geolocation/graph modules
(`merchants/`), spending `analysis/` (anomaly, fees, recurring, subscriptions,
refunds, splits, pending, international), and a receipt pipeline (`receipts/`:
OCR, email/Amazon parsing, matching, MinIO storage).

### @lakshmi/budgeting

Budgeting and cash-flow forecasting. `src/budget/` implements multiple
methodologies — `zero-based.ts`, `category-based.ts`, `cash-flow.ts`,
`paycheck.ts`, `sinking-funds.ts`, `rollover.ts`, `periods.ts`, `templates.ts` —
while `src/forecast/` covers spending velocity, income irregularity, and forward
forecasting. A `src/bills/` module handles the bill calendar, deduplication,
subscription detection, and negotiation. Real budgeting logic, exercised by
`budgeting.test.ts`.

### @lakshmi/investments

Institutional-grade portfolio analytics. `performance/returns.ts` implements
time-weighted return (daily geometric linking), money-weighted return / IRR via
Newton-Raphson, and XIRR with day-fraction exponents; `performance/benchmark.ts`
adds benchmark comparison. `portfolio/` covers aggregation, allocation, a
security master, and fund X-ray; `risk/` covers metrics and Value-at-Risk
(`var.ts`); `rebalancing/engine.ts` drives rebalancing; and `advanced/` adds
factor analysis, fee analysis, dividend/fixed-income, concentrated-position IPS,
and options/ESG/alternatives.

### @lakshmi/tax

Continuous tax optimization built on real 2025 IRS brackets and capital-gains
rates (`tax/src/tlh/scanner.ts` documents this). `tlh/` is the tax-loss-harvest
suite — scanner, wash-sale detection, lot optimizer, replacement-security
selection, annual optimizer. `income/` handles bracket management, estimated
tax, and Roth-conversion ladders; `deductions/` handles the optimizer plus AMT /
NIIT; and `planning/` covers projection, simulation, state tax, self-employment,
withdrawal sequencing, a tax calendar, deadline reminders, and document
tracking.

### @lakshmi/debt

Debt payoff optimization. `inventory/` models the debt set (inventory,
dashboard, manual entry, rate tracking, timeline); `payoff/` implements the
avalanche (`avalanche.ts`, highest-rate-first cents-precise simulation),
snowball, and hybrid strategies plus impact and opportunity-cost analysis; and
`refinancing/` is a scanner with specialized analyzers for mortgages, credit
cards, student loans, medical debt, and consolidation. Each module has a paired
`.test.ts`.

### @lakshmi/credit

Credit-score monitoring, simulation, and optimization. Modules include
`score-tracking.ts`, `score-simulator.ts`, `factor-decomposition.ts`,
`utilization-optimizer.ts`, `credit-mix-optimizer.ts`, `credit-age-tracker.ts`,
`authorized-user-strategy.ts`, a bureau `dispute-workflow.ts`,
`report-monitoring.ts`, `credit-freeze-management.ts`,
`alternative-credit-data.ts`, a `credit-card-recommender.ts`, plus
identity-protection pieces (`dark-web-monitoring.ts`,
`identity-theft-recovery.ts`). Each ships with a correctness test.

### @lakshmi/retirement

Multi-decade retirement planning (`lakshmi:tier:feature` style engine).
`monte-carlo-projection.ts` runs retirement-specific simulations with real
returns, inflation, longevity, and spending variability and reports
probability-of-success plus percentile/confidence outcomes. It also includes a
deep Social Security suite (estimator, claiming optimizer, earnings test,
spousal coordinator, survivor analyzer), RMD calculator, contribution
limit/optimizer, employer-match optimizer, FIRE calculator, dynamic withdrawal
rate, tax-efficient withdrawal sequencing, healthcare-cost projector,
longevity-risk analyzer, and a readiness score.

### @lakshmi/insurance

Insurance portfolio analysis. Modules cover policy management, a portfolio
dashboard, spend dashboard, renewal calendar, claims history, and a
`coverage-gap-detector.ts`, plus needs/adequacy analyzers for life
(`life-insurance-needs.ts`), disability, long-term care, umbrella liability, and
deductible optimization, with health-plan comparison and a Medicare-enrollment
planner. Each module is paired with a test.

### @lakshmi/estate

Estate planning and administration. Includes an `asset-inventory.ts`,
`document-vault.ts`, `beneficiary-tracker.ts` and beneficiary-change-impact
analysis, asset-titling and probate-avoidance analyzers, federal and
state/inheritance estate-tax projectors, a gift-tax tracker, trust analysis, an
executor/trustee toolkit, emergency-access protocol, digital-legacy manager,
cryptocurrency-succession planner, and life-event review triggers. All modules
carry tests.

### @lakshmi/real-estate

Real-estate wealth management. Provides a `home-valuation-engine.ts` (AVM),
rental-property and rental-income/expense analyzers, mortgage tracker and
refinancing analyzer, a `home-equity-dashboard.ts`, PMI-removal and property-tax
trackers, depreciation tracker, a 1031-exchange planner, buy-vs-rent and
home-affordability calculators, a property-portfolio dashboard, an allocation
tracker, and a vacancy/maintenance-reserve planner.

### @lakshmi/crypto

Multi-chain crypto and DeFi tracking. `wallet-aggregation.ts` and
`exchange-integration.ts` ingest positions; `crypto-tax-lot-tracker.ts`,
`crypto-transaction-classifier.ts`, `defi-tax-handler.ts`, and
`form-8949-generator.ts` handle tax; and `defi-position-monitor.ts`,
`impermanent-loss-calculator.ts`, `staking-reward-tracker.ts`,
`airdrop-valuation-scanner.ts`, `gas-fee-analytics.ts`,
`nft-portfolio-tracker.ts`, `token-approval-manager.ts`,
`wallet-security-scoring.ts`, and `portfolio-integration.ts` cover positions,
security, and integration with the broader portfolio. Each module has a test.

### @lakshmi/income

Income engineering and equity-compensation optimization. Holds RSU
(`rsu-tracker.ts`), ISO (`iso-exercise-optimizer.ts`), NSO
(`nso-exercise-analyzer.ts`), and ESPP (`espp-analyzer.ts`) analyzers, an 83(b)
election analyzer, a pay-stub analysis engine, an income-detection engine, a
quarterly-estimated-tax engine, multi-stream and passive-income dashboards,
salary benchmarking, freelance-income and self-employed-retirement managers, a
business-expense categorizer, and an entity-structure optimizer.

### @lakshmi/goals

Financial goal planning. `multi-goal-engine.ts` coordinates competing goals;
`goal-probability-scoring.ts`, `goal-funding-analysis.ts`, and
`goal-trade-off-analyzer.ts` score and reconcile them; and there are dedicated
planners for education savings, home purchase, major/baby-child costs, emergency
fund adequacy, financial independence, career change, and life-event
auto-detection. A feature-tier library that reuses `@lakshmi/core`'s projection
math.

### @lakshmi/household

Multi-user household collaboration. Modules include membership management with
account designation, a net-worth dashboard, an advisor portal and recommendation
inbox, secure report sharing, spending allowances, a financial calendar, and
life-stage planners for children's finance, elder care, divorce, prenuptial
transparency, family support, and family-meeting prep. Tagged in the feature
tier per the README's collaboration role.

### @lakshmi/business

Self-employment and small-business finance. Provides a cash-flow forecaster,
quarterly-tax automation, an entity-structure optimizer, an S-corp salary
analyzer, a QBI-deduction analyzer, a home-office-deduction tracker, a
vehicle-mileage tracker, invoicing/receivables and contractor/vendor managers, a
business-valuation tracker, a business-insurance analyzer, an expense-report
generator, a transaction separator (business vs. personal), and a self-employed
retirement-plan optimizer. Each module is tested.

### @lakshmi/ai-engine

The autonomous-agent and NLP layer (`lakshmi:tier:feature`). Contains agentic
engines — `financial-advisor-agent.ts`, `tax-optimization-agent.ts`,
`bill-negotiation-agent.ts`, `anomaly-investigator.ts` — plus a conversational
query engine and `financial-query-compiler.ts`, a financial-plan generator,
insight narrator, financial-dialogue and voice-query interfaces, and predictive
engines (`predictive-cash-flow-engine.ts`, `opportunity-cost-engine.ts`,
`life-event-impact-modeler.ts`, `subscription-price-increase-predictor.ts`,
`tax-move-recommender.ts`). Each has a paired test.

### @lakshmi/behavioral

Behavioral-finance engine. Implements scoring models
(`financial-health-score.ts`, `financial-health-assessment.ts`,
`financial-resilience-score.ts`, `financial-stress-index.ts`), a
`nudge-engine.ts`, peer benchmarking, lifestyle- inflation and impulse-purchase
detectors, loss-aversion protection, smart-default configuration, a
smart-savings-automation engine, a spending-behavior pattern analyzer,
habit-streak tracker, achievement-badge and financial-challenge gamification
systems, and a weekly-reflection generator. All tested.

### @lakshmi/security

The privacy and security substrate (`lakshmi:tier:feature`).
`homomorphic-analytics.ts` is a real additively-homomorphic analytics scheme
(fixed-point encoding plus secret-modulus masking, with homomorphic
add/sum/scalar-multiply/linear-score/trend, built on `@noble/hashes`) exposing
`tfhe-rs` and `openfhe-ckks` scheme profiles — native FHE backends being the
production target it models. Alongside it: `encryption.ts`,
`end-to-end-encryption.ts`, `zero-knowledge.ts`, `differential-privacy.ts`,
`federated-learning.ts`, RBAC, MFA, biometric and device-trust auth, session
management, audit logging, data-residency, and GDPR/CCPA/SOC2 compliance
modules.

### @lakshmi/integrations

The outward-facing integration gateway (`lakshmi:tier:feature`).
`aggregation-provider-gateway.ts` is a high-level orchestration layer over the
bank-aggregation provider adapters that physically live in `@lakshmi/accounts`,
plus an `open-banking-api-gateway.ts`, credit-bureau, payroll,
insurance-carrier, crypto-data, and real-estate-data provider integrations, a
GraphQL API layer, a webhook-notification system, accounting-software and
spreadsheet sync, automation-platform connectors, tax-software export, and a
MinIO `storage.ts` service that provisions the platform's document buckets with
SSE-S3 encryption and lifecycle policies.

### @lakshmi/reporting

Financial reporting and exports. Generates a personal balance sheet, personal
cash-flow statement, net-worth tracker and projected-net-worth report,
income/expense analysis, category-spending deep-dives, investment-performance
and debt-payoff-progress reports, a financial-snapshot one-pager, a tax-ready
report suite, and year-over-year comparison charts, with a custom-dashboard
builder, an interactive-visualization library, a report-export engine, scheduled
delivery, and shareable report links.

### @lakshmi/alerts

Real-time alerting. Each alert type is its own engine: budget-threshold,
low-balance, large-transaction, unusual-activity, bill-due-reminder,
subscription-renewal, rate-change, credit-score-change, investment-rebalancing,
and goal-milestone-celebration, plus a custom-alert-rules engine and a
`multi-channel-delivery-system.ts` for fan-out. Every engine has a paired
correctness test.
