# expense-budget-tracker Open-source expense and budget tracker: expenses, budgets, balances, transfers, and multi-currency reporting on Postgres. ## Rules - Use English for code comments and documentation. - Prefer functional programming and pure functions. - Use classes only for connectors to external systems. - Use strict typing across functions, variables, and collections. - Avoid fallback logic unless explicitly requested. - Raise explicit, actionable errors with context. - Runtime discovery is the canonical machine API documentation. Keep its actions, instructions, and source links in sync with runtime behavior; `/v1/openapi.json` and `/v1/swagger.json` are public source-discovery compatibility probes, not specification endpoints. - Version-bump requests must follow `docs/version-bump.md` and keep `scripts/checks/pr/check-version-alignment.mjs` green. - Never bump the version during ordinary work: a release publishes the version already in the repository, and a separate request bumps it right after each MCP Registry publication (`docs/mcp-registry-publishing.md`). - Keep changes minimal and scoped to the current request. - A pull request that changes anything visible opens its description with screenshots, before any text: before and after side by side for each affected screen, with the same viewport, theme, and data, at phone and desktop widths when the layout is responsive. Attach the images to the description or host them outside the PR branch; never commit them to it. - Before considering a large block of work complete, run the relevant type checks and builds, and for web changes a production build (`cd apps/web && npm run lint && npm run build`). - Prefer non-interactive terminal commands. - The web app supports multiple languages. When adding or changing any translation in `apps/web/src/i18n/`, update the same keys in every locale file in that directory in the same change. - Change schema via new files in `db/migrations/` only; never edit already-applied migrations. - CI/CD is GitHub Actions on push to `main` (`.github/workflows/deploy.yml`), filtered by its `paths:` list: a merge touching nothing in that list produces no Deploy run, which is correct and not a missed trigger. - The deploy process intentionally may update the web service before running migrations; this accepted deploy order is not an issue by itself. - Do not build AWS SDK bundles or other AWS deployment artifacts locally. Push code to `main`, and let CI/CD build and deploy everything. - Themeable colors belong in `apps/web/src/app/styles/tokens.css` under both `:root` and `:root[data-theme="dark"]`; write no new hex color anywhere else under `apps/web/src`, and keep `scripts/checks/pr/check-css-hex-colors.mjs` green. - RTL support is required: - In CSS, use logical properties such as `inset-inline-start`/`end`, `margin-inline-start`/`end`, `padding-inline-start`/`end`, `border-inline-start`/`end`, and `text-align: start`/`end` instead of physical left/right variants. - Use `[dir="rtl"]` overrides only when no logical equivalent exists (for example `box-shadow`). - In JS, account for RTL when handling `scrollLeft`, element positioning, and resize logic. ## Components - `apps/web/`: Next.js app with UI dashboards and API routes for transactions, balances, budget, and FX data; SQL via `pg.Pool`. The web app also includes an AI chat where the user can open `/chat` and talk to their workspace data directly from the browser. - `apps/worker/`: TypeScript process that fetches daily ECB, CBR, NBS, NBU, KuCoin, and USDT exchange rates into `fx_rates_raw`; runs on a schedule (Docker) or as AWS Lambda - `apps/admin/`: separate Next.js admin app at `admin.*` with product analytics; read-only, Cognito session plus `ADMIN_EMAILS`, see `docs/admin-app.md` - Postgres: single source of truth; schema in `db/migrations/`, views in `db/views/`, reference SQL in `db/queries/` ## Supported Clients - AI agent flows reach the data over three transports: the web app has its own built-in chat with conversations, while external client agents use the hosted MCP server or the public machine API. The hosted MCP server and the web chat render the same five agent tools from the shared catalog in `packages/agent-shared/src/agentTools.ts`, so neither has a private SQL tool; the `/v1` machine API is a separate REST surface over the same restricted SQL. The client list below is about the external/API flow for reference. - Web app: supported - Terminal / AI agents: full functionality is supported through the canonical machine API entrypoint `GET https://api.nentaf.com/v1/` (the discovery response includes the next-step instructions for signup/login and email OTP onboarding) - Direct HTTP clients and scripts: supported through the same `https://api.nentaf.com/v1` surface with `Authorization: ApiKey ` ## Key Paths | Path | Description | | --- | --- | | `apps/web/src/app/api/` | Next.js API routes (`budget-grid`, `transactions`, `balances-summary`, and others) | | `apps/web/src/app/chat/page.tsx` | Web AI chat page at `/chat`; fullscreen browser entrypoint for chatting with workspace data | | `apps/web/src/app/api/chat/route.ts` | Server API entrypoint for the web AI chat (`POST` stream, `DELETE` reset) | | `apps/web/src/server/chat/openai/loop.ts` | Main app-managed OpenAI chat loop for the web app | | `apps/web/src/server/chat/openai/tooling/tools.ts` | Web chat rendering of the shared agent tool catalog into OpenAI function tools, and their execution | | `apps/web/src/server/chat/dataService.ts` | Read-only workspace and schema discovery backing the web chat's `list_workspaces` and `get_schema` | | `apps/web/src/server/` | Server-side data functions for budget, balances, and transactions | | `apps/web/src/ui/` | React components: tables, charts, hooks | | `apps/web/src/proxy.ts` | Auth proxy logic controlled by `AUTH_MODE` | | `apps/worker/src/fetchers/` | FX rate fetchers: `ecb.ts`, `cbr.ts`, `nbs.ts`, `nbu.ts`, `kucoin.ts`, `usdt.ts` | | `db/migrations/` | Postgres migrations applied in order by `scripts/migrate.sh` | | `db/views/` | Postgres views such as `accounts` | | `db/queries/` | Reference SQL: `balances.sql`, `budget_grid.sql`, `fx_breakdown.sql`, `transactions.sql` | | `apps/web/src/server/agent/connections.ts` | Agent connections: API key minting and hashing, listing, active-key cap, revocation | | `apps/web/src/app/api/agent-connections/` | Agent connection endpoints: `GET`/`POST` on the collection, `POST` on the `revoke` routes | | `apps/admin/src/proxy.ts` | Admin app auth gate: Cognito session, `ADMIN_EMAILS`, GET/HEAD only | | `apps/admin/src/server/reports/` | Admin analytics report queries over `counted_users` | | `db/migrations/0090_analytics_activity_days.sql` | `analytics.user_open_days` and `analytics.user_track_days`, with the `ledger_entries` track-day trigger | | `apps/sql-api/` | SQL API Lambda handlers for API Gateway: `ApiKey` authorizer, v1 machine API, and the OAuth MCP server in `src/mcp/server.ts` | | `apps/sql-api/Dockerfile` | Container image for the same code: the default command serves `/v1`, `node dist/serve-mcp.js` serves `/mcp` | | `packages/agent-shared/src/agentTools.ts` | Shared catalog of the five agent tools (`list_workspaces`, `get_schema`, `get_guide`, `sql_query`, `sql_execute`) that both the MCP server and the web chat render | | `packages/agent-shared/src/agentResults.ts` | Shared agent tool result envelope and the remediation instructions both surfaces return | | `apps/web/src/server/demo/data.ts` | Static demo data for demo mode without a DB | | `apps/web/src/lib/demoMode.ts` | Demo mode check; enabled by `demo=true` browser cookie toggled in the UI, no env var needed | | `infra/docker/compose.yml` | Local Docker Compose for Postgres, migrate, web, and worker | | `infra/docker/compose.selfhost.yml` | Standalone self-hosting stack (`AUTH_MODE=proxy_jwt`) behind an edge proxy; see `docs/self-hosting.md` | | `infra/aws/` | AWS CDK stack for ECS Fargate, RDS, ALB/Cognito, API Gateway, Lambda, and WAF | | `scripts/migrate.sh` | Runs migrations and views against `DATABASE_URL` | | `.env.example` | Environment variable reference | ## Cloudflare Cloudflare credentials are stored locally in `scripts/cloudflare/.env` (gitignored). Scripts in `scripts/cloudflare/` manage DNS, SSL, and cache rules via the Cloudflare API. ## AWS Deployment Before querying AWS resources: 1. Read `infra/aws/cdk.context.local.json` for region, domain, certificate ARNs, and account-specific settings. It is gitignored, so it exists only in the main checkout; from a worktree read it from that checkout's root. 2. Check `~/.aws/config` for the CLI profile targeting the same account and region. 3. Always use matching `--profile` and `--region` flags. - CDK context: `infra/aws/cdk.context.local.json` - CDK stack name: `ExpenseBudgetTracker` - CI/CD: GitHub Actions deploys CDK, builds and pushes Docker images to ECR, runs the ECS migration task, and updates the ECS service. Secrets: `AWS_DEPLOY_ROLE_ARN`, `CDK_CONTEXT` ## Local Development For UI work, run the Next.js dev server directly: ```bash cd apps/web && npm run dev ``` For local browser tryouts, set local auth explicitly and make `CORS_ORIGIN` match the exact origin opened in the browser: ```bash cd apps/web AUTH_MODE=none CORS_ORIGIN=http://localhost:3000 npm run dev ``` If the browser uses another local host or port, set the same origin in `CORS_ORIGIN` and in the dev server command: ```bash cd apps/web AUTH_MODE=none CORS_ORIGIN=http://127.0.0.1:3001 npm run dev -- -H 127.0.0.1 -p 3001 ``` Toggle Demo mode with the All/Demo button in the header. It sets a `demo=true` browser cookie and serves data from `apps/web/src/server/demo/data.ts` in memory, so no Postgres is required and code changes hot-reload immediately. Use `make dev` (Docker Compose) only when you need a real database, such as for migrations, SQL queries, or the worker. Docker runs a production Next.js build, so each code change requires `make build`. ## Logging Use the structured server logger in `apps/web/src/server/logger.ts`. Log through `log()` only; never use raw `console.log` or `console.error`. Add new event types to the `LogEvent` union. For CloudWatch investigations, avoid complex OR filter patterns. Fetch fresh events first, then filter locally by `requestId` and chat error signals. ## Data Sources AWS profile and region setup is in `## AWS Deployment`. Start from logs and traces; most investigations need no database access. | Source | How to reach it | Use for | | --- | --- | --- | | Postgres, prod | No direct connection by design: RDS is private, with no bastion. Read through `POST https://api.nentaf.com/v1/sql/query` with `Authorization: ApiKey ` — a fixed relation list, scoped to the selected workspace. Anything wider needs a temporary path opened deliberately; never add standing database access while debugging. The admin-reader Lambda below is the one deliberate read-only exception. | workspace data, counts, data shape | | Postgres, local | `make dev`, then `psql` with `DATABASE_URL` from `.env.example` | schema, views, query development | | CloudWatch Logs | `/expense-tracker/web` (30-day retention), `/expense-tracker/auth`, `/expense-tracker/admin`, `/expense-tracker/migrate`; Lambda groups under `/aws/lambda/` for FX, authorizer, SQL API, and MCP handlers; API Gateway access logs and agent tool-call queries in [docs/agent-telemetry.md](docs/agent-telemetry.md) | request-level debugging by `requestId`, agent tool-call failures | | CloudWatch metrics | custom namespace `ExpenseBudgetTracker/Db`, metric `PoolErrors`; alarms and metric filters in `infra/aws/lib/monitoring.ts` | error rates, DB pool failures, ECS, RDS, and API Gateway health | | ALB access logs | S3 bucket `expense-tracker-alb-logs-`, 90-day expiration | traffic, status codes, client IPs | | LLM telemetry and chats, prod | `scripts/admin-read.sh` (private admin-reader Lambda, read-only, IAM); see [docs/admin-reader.md](docs/admin-reader.md) and [docs/llm-telemetry.md](docs/llm-telemetry.md) | chat spans, model and tool behavior, token usage, transcripts across users | | GitHub Actions | `gh run list --workflow deploy.yml` | deploy and migration failures | ## Reference - [docs/architecture.md](docs/architecture.md) - system overview, data model, agent tool surfaces, multi-currency design, auth model - [docs/deployment.md](docs/deployment.md) - local Docker Compose and AWS CDK setup - [docs/self-hosting.md](docs/self-hosting.md) - running the whole product outside AWS behind an edge proxy: hostnames, bypass list, revocation - [docs/account-email-changes.md](docs/account-email-changes.md) - the admin-only procedure for changing an account email, and the heads-up it requires - [docs/llm-telemetry.md](docs/llm-telemetry.md) - chat span tree, `llm_telemetry_spans` columns and attributes, optional OTLP export - [docs/agent-telemetry.md](docs/agent-telemetry.md) - what each agent surface records about tool calls, and the CloudWatch queries that count failures - [docs/admin-app.md](docs/admin-app.md) - admin app, analytics tables, access model, rollout, adding an admin - [infra/aws/README.md](infra/aws/README.md) - full AWS CDK deployment guide - [Makefile](Makefile) - `make up`, `make down`, `make migrate`, `make build`, `make lint`