rebuild app as turbopack-first single-stack with internal api and openclaw tasks

This commit is contained in:
2026-02-23 23:38:06 -05:00
parent 5df09b714b
commit 6012dd3fcf
40 changed files with 1583 additions and 1578 deletions

5
.gitignore vendored
View File

@@ -2,6 +2,8 @@
node_modules/ node_modules/
.pnp .pnp
.pnp.js .pnp.js
.cache/
Library/
# Testing # Testing
coverage/ coverage/
@@ -33,3 +35,6 @@ out/
# Database # Database
*.db *.db
*.sqlite *.sqlite
# Local app runtime state
frontend/data/*.json

151
README.md
View File

@@ -1,60 +1,30 @@
# Fiscal Clone 2.0 # Fiscal Clone 3.0 (Turbopack Rebuild)
Ground-up rebuild of a `fiscal.ai`-style platform with: Ground-up rebuild into a single Next.js 16 application that runs with Turbopack and internal API routes.
- Better Auth for session-backed auth
- Next.js frontend
- high-throughput API service
- durable long-running task worker
- OpenClaw/ZeroClaw AI integration
- futuristic terminal UI language
## Feature Coverage ## What changed
- Authentication (email/password via Better Auth) - Removed hard runtime dependency on the external backend for core app workflows.
- Watchlist management - Added internal `app/api/*` services for watchlist, portfolio, filings, tasks, and health.
- SEC filings ingestion (10-K, 10-Q, 8-K) - Added durable local data store at runtime (`frontend/data/store.json`).
- Filing analysis jobs (async AI pipeline) - Added async task engine with retry support for:
- Portfolio holdings and summary analytics - `sync_filings`
- Price refresh jobs (async) - `refresh_prices`
- AI portfolio insight jobs (async) - `analyze_filing`
- Task tracking endpoint and UI polling - `portfolio_insights`
- Added OpenClaw integration through OpenAI-compatible `/v1/chat/completions`.
- Enforced Turbopack for both development and production builds.
## Architecture ## Architecture
- `frontend/`: Next.js App Router UI - `frontend/`: full app (UI + API + task engine)
- `backend/`: Elysia API + Better Auth + domain routes - `frontend/app/api/*`: route handlers
- `backend/src/worker.ts`: durable queue worker - `frontend/lib/server/*`: storage, task processors, SEC/pricing adapters, OpenClaw client
- `docs/REBUILD_DECISIONS.md`: one-by-one architecture decisions - `frontend/data/store.json`: generated local runtime state (git-ignored)
Runtime topology: The legacy `backend/` folder is retained in-repo but no longer required for the rebuilt local workflow.
1. Frontend web app
2. Backend API
3. Worker process for long tasks
4. PostgreSQL
## Local Setup ## Run
```bash
cp .env.example .env
```
### 1) Backend
```bash
cd backend
bun install
bun run db:migrate
bun run dev
```
### 2) Worker (new terminal)
```bash
cd backend
bun run dev:worker
```
### 3) Frontend (new terminal)
```bash ```bash
cd frontend cd frontend
@@ -62,74 +32,43 @@ npm install
npm run dev npm run dev
``` ```
Frontend: `http://localhost:3000` Open: [http://localhost:3000](http://localhost:3000)
Backend: `http://localhost:3001`
Swagger: `http://localhost:3001/swagger`
## Docker Compose ## Build (Turbopack)
```bash ```bash
docker compose up --build cd frontend
npm run build
npm run start
``` ```
This starts: `postgres`, `backend`, `worker`, `frontend`. ## OpenClaw setup
## Coolify Set in environment (for example `frontend/.env.local`):
Deploy using the root compose file and configure separate public domains for:
- `frontend` on port `3000`
- `backend` on port `3001`
Use the full guide in `COOLIFY.md`.
Critical variables for Coolify:
- `FRONTEND_URL` = frontend public URL
- `BETTER_AUTH_BASE_URL` = backend public URL
- `NEXT_PUBLIC_API_URL` = backend public URL (build-time in frontend)
## Core API Surface
Auth:
- `ALL /api/auth/*` (Better Auth handler)
- `GET /api/me`
Watchlist:
- `GET /api/watchlist`
- `POST /api/watchlist`
- `DELETE /api/watchlist/:id`
Portfolio:
- `GET /api/portfolio/holdings`
- `POST /api/portfolio/holdings`
- `PATCH /api/portfolio/holdings/:id`
- `DELETE /api/portfolio/holdings/:id`
- `GET /api/portfolio/summary`
- `POST /api/portfolio/refresh-prices` (queues task)
- `POST /api/portfolio/insights/generate` (queues task)
- `GET /api/portfolio/insights/latest`
Filings:
- `GET /api/filings?ticker=&limit=`
- `GET /api/filings/:accessionNumber`
- `POST /api/filings/sync` (queues task)
- `POST /api/filings/:accessionNumber/analyze` (queues task)
Task tracking:
- `GET /api/tasks`
- `GET /api/tasks/:taskId`
## OpenClaw / ZeroClaw Integration
Set these in `.env`:
```env ```env
OPENCLAW_BASE_URL=http://localhost:4000 OPENCLAW_BASE_URL=http://localhost:4000
OPENCLAW_API_KEY=... OPENCLAW_API_KEY=your_key
OPENCLAW_MODEL=zeroclaw OPENCLAW_MODEL=zeroclaw
SEC_USER_AGENT=Fiscal Clone <support@fiscal.local>
``` ```
The backend expects an OpenAI-compatible `/v1/chat/completions` endpoint. If OpenClaw is not configured, the app falls back to local analysis responses so task flows remain testable.
## Decision Log ## API surface
See `docs/REBUILD_DECISIONS.md` for the detailed rationale and tradeoffs behind each major design choice. - `GET /api/health`
- `GET /api/me`
- `GET|POST /api/watchlist`
- `DELETE /api/watchlist/:id`
- `GET|POST /api/portfolio/holdings`
- `PATCH|DELETE /api/portfolio/holdings/:id`
- `GET /api/portfolio/summary`
- `POST /api/portfolio/refresh-prices`
- `POST /api/portfolio/insights/generate`
- `GET /api/portfolio/insights/latest`
- `GET /api/filings`
- `POST /api/filings/sync`
- `POST /api/filings/:accessionNumber/analyze`
- `GET /api/tasks`
- `GET /api/tasks/:taskId`

View File

@@ -7,18 +7,14 @@
"dependencies": { "dependencies": {
"@elysiajs/cors": "^1.4.1", "@elysiajs/cors": "^1.4.1",
"@elysiajs/swagger": "^1.3.1", "@elysiajs/swagger": "^1.3.1",
"bcryptjs": "^3.0.3",
"better-auth": "^1.4.18", "better-auth": "^1.4.18",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"elysia": "^1.4.25", "elysia": "^1.4.25",
"jsonwebtoken": "^9.0.3",
"pg": "^8.18.0", "pg": "^8.18.0",
"postgres": "^3.4.8", "postgres": "^3.4.8",
"zod": "^4.3.6", "zod": "^4.3.6",
}, },
"devDependencies": { "devDependencies": {
"@types/bcryptjs": "^3.0.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/pg": "^8.16.0", "@types/pg": "^8.16.0",
"bun-types": "latest", "bun-types": "latest",
}, },
@@ -57,26 +53,16 @@
"@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="], "@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="],
"@types/bcryptjs": ["@types/bcryptjs@3.0.0", "", { "dependencies": { "bcryptjs": "*" } }, "sha512-WRZOuCuaz8UcZZE4R5HXTco2goQSI2XxjGY3hbM/xDvwmqFWd4ivooImsMx65OKM6CtNKbnZ5YL+YwAwK7c1dg=="],
"@types/jsonwebtoken": ["@types/jsonwebtoken@9.0.10", "", { "dependencies": { "@types/ms": "*", "@types/node": "*" } }, "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA=="],
"@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
"@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="], "@types/node": ["@types/node@25.3.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A=="],
"@types/pg": ["@types/pg@8.16.0", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ=="], "@types/pg": ["@types/pg@8.16.0", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-RmhMd/wD+CF8Dfo+cVIy3RR5cl8CyfXQ0tGgW6XBL8L4LM/UTEbNXYRbLwU6w+CgrKBNbrQWt4FUtTfaU5jSYQ=="],
"@unhead/schema": ["@unhead/schema@1.11.20", "", { "dependencies": { "hookable": "^5.5.3", "zhead": "^2.2.4" } }, "sha512-0zWykKAaJdm+/Y7yi/Yds20PrUK7XabLe9c3IRcjnwYmSWY6z0Cr19VIs3ozCj8P+GhR+/TI2mwtGlueCEYouA=="], "@unhead/schema": ["@unhead/schema@1.11.20", "", { "dependencies": { "hookable": "^5.5.3", "zhead": "^2.2.4" } }, "sha512-0zWykKAaJdm+/Y7yi/Yds20PrUK7XabLe9c3IRcjnwYmSWY6z0Cr19VIs3ozCj8P+GhR+/TI2mwtGlueCEYouA=="],
"bcryptjs": ["bcryptjs@3.0.3", "", { "bin": { "bcrypt": "bin/bcrypt" } }, "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g=="],
"better-auth": ["better-auth@1.4.18", "", { "dependencies": { "@better-auth/core": "1.4.18", "@better-auth/telemetry": "1.4.18", "@better-auth/utils": "0.3.0", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.0.0", "@noble/hashes": "^2.0.0", "better-call": "1.1.8", "defu": "^6.1.4", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1", "zod": "^4.3.5" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": ">=0.41.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-bnyifLWBPcYVltH3RhS7CM62MoelEqC6Q+GnZwfiDWNfepXoQZBjEvn4urcERC7NTKgKq5zNBM8rvPvRBa6xcg=="], "better-auth": ["better-auth@1.4.18", "", { "dependencies": { "@better-auth/core": "1.4.18", "@better-auth/telemetry": "1.4.18", "@better-auth/utils": "0.3.0", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.0.0", "@noble/hashes": "^2.0.0", "better-call": "1.1.8", "defu": "^6.1.4", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1", "zod": "^4.3.5" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": ">=0.41.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-bnyifLWBPcYVltH3RhS7CM62MoelEqC6Q+GnZwfiDWNfepXoQZBjEvn4urcERC7NTKgKq5zNBM8rvPvRBa6xcg=="],
"better-call": ["better-call@1.1.8", "", { "dependencies": { "@better-auth/utils": "^0.3.0", "@better-fetch/fetch": "^1.1.4", "rou3": "^0.7.10", "set-cookie-parser": "^2.7.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw=="], "better-call": ["better-call@1.1.8", "", { "dependencies": { "@better-auth/utils": "^0.3.0", "@better-fetch/fetch": "^1.1.4", "rou3": "^0.7.10", "set-cookie-parser": "^2.7.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw=="],
"buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
"bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="],
"cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
@@ -87,8 +73,6 @@
"dotenv": ["dotenv@17.3.1", "", {}, "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA=="], "dotenv": ["dotenv@17.3.1", "", {}, "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA=="],
"ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],
"elysia": ["elysia@1.4.25", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.7", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-liKjavH99Gpzrv9cDil6uYWmPuqESfPFV1FIaFSd3iNqo3y7e29sN43VxFIK8tWWnyi6eDAmi2SZk8hNAMQMyg=="], "elysia": ["elysia@1.4.25", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.7", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-liKjavH99Gpzrv9cDil6uYWmPuqESfPFV1FIaFSd3iNqo3y7e29sN43VxFIK8tWWnyi6eDAmi2SZk8hNAMQMyg=="],
"exact-mirror": ["exact-mirror@0.2.7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="], "exact-mirror": ["exact-mirror@0.2.7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="],
@@ -103,28 +87,8 @@
"jose": ["jose@6.1.3", "", {}, "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ=="], "jose": ["jose@6.1.3", "", {}, "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ=="],
"jsonwebtoken": ["jsonwebtoken@9.0.3", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],
"jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],
"jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
"kysely": ["kysely@0.28.11", "", {}, "sha512-zpGIFg0HuoC893rIjYX1BETkVWdDnzTzF5e0kWXJFg5lE0k1/LfNWBejrcnOFu8Q2Rfq/hTDTU7XLUM8QOrpzg=="], "kysely": ["kysely@0.28.11", "", {}, "sha512-zpGIFg0HuoC893rIjYX1BETkVWdDnzTzF5e0kWXJFg5lE0k1/LfNWBejrcnOFu8Q2Rfq/hTDTU7XLUM8QOrpzg=="],
"lodash.includes": ["lodash.includes@4.3.0", "", {}, "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="],
"lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="],
"lodash.isinteger": ["lodash.isinteger@4.0.4", "", {}, "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="],
"lodash.isnumber": ["lodash.isnumber@3.0.3", "", {}, "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="],
"lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="],
"lodash.isstring": ["lodash.isstring@4.0.1", "", {}, "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="],
"lodash.once": ["lodash.once@4.1.1", "", {}, "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="],
"memoirist": ["memoirist@0.4.0", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="], "memoirist": ["memoirist@0.4.0", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
@@ -165,10 +129,6 @@
"rou3": ["rou3@0.7.12", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="], "rou3": ["rou3@0.7.12", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="],
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
"set-cookie-parser": ["set-cookie-parser@2.7.2", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="], "set-cookie-parser": ["set-cookie-parser@2.7.2", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],
"split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],

View File

@@ -0,0 +1,26 @@
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { enqueueTask } from '@/lib/server/tasks';
type Context = {
params: Promise<{ accessionNumber: string }>;
};
export async function POST(_request: Request, context: Context) {
try {
const { accessionNumber } = await context.params;
if (!accessionNumber || accessionNumber.trim().length < 4) {
return jsonError('Invalid accession number');
}
const task = await enqueueTask({
taskType: 'analyze_filing',
payload: { accessionNumber: accessionNumber.trim() },
priority: 65
});
return Response.json({ task });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to queue filing analysis task'));
}
}

View File

@@ -0,0 +1,22 @@
import { getStoreSnapshot } from '@/lib/server/store';
export async function GET(request: Request) {
const url = new URL(request.url);
const tickerFilter = url.searchParams.get('ticker')?.trim().toUpperCase();
const limitValue = Number(url.searchParams.get('limit') ?? 50);
const limit = Number.isFinite(limitValue)
? Math.min(Math.max(Math.trunc(limitValue), 1), 250)
: 50;
const snapshot = await getStoreSnapshot();
const filtered = tickerFilter
? snapshot.filings.filter((filing) => filing.ticker === tickerFilter)
: snapshot.filings;
const filings = filtered
.slice()
.sort((a, b) => Date.parse(b.filing_date) - Date.parse(a.filing_date))
.slice(0, limit);
return Response.json({ filings });
}

View File

@@ -0,0 +1,28 @@
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { enqueueTask } from '@/lib/server/tasks';
export async function POST(request: Request) {
try {
const payload = await request.json() as {
ticker?: string;
limit?: number;
};
if (!payload.ticker || payload.ticker.trim().length < 1) {
return jsonError('ticker is required');
}
const task = await enqueueTask({
taskType: 'sync_filings',
payload: {
ticker: payload.ticker.trim().toUpperCase(),
limit: payload.limit ?? 20
},
priority: 90
});
return Response.json({ task });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to queue filings sync task'));
}
}

View File

@@ -0,0 +1,16 @@
import { getStoreSnapshot } from '@/lib/server/store';
export async function GET() {
const snapshot = await getStoreSnapshot();
const queue = snapshot.tasks.reduce<Record<string, number>>((acc, task) => {
acc[task.status] = (acc[task.status] ?? 0) + 1;
return acc;
}, {});
return Response.json({
status: 'ok',
version: '3.0.0',
timestamp: new Date().toISOString(),
queue
});
}

View File

@@ -0,0 +1,10 @@
export async function GET() {
return Response.json({
user: {
id: 1,
email: 'operator@local.fiscal',
name: 'Local Operator',
image: null
}
});
}

View File

@@ -0,0 +1,89 @@
import { jsonError } from '@/lib/server/http';
import { recalculateHolding } from '@/lib/server/portfolio';
import { withStore } from '@/lib/server/store';
type Context = {
params: Promise<{ id: string }>;
};
function nowIso() {
return new Date().toISOString();
}
function asPositiveNumber(value: unknown) {
const parsed = typeof value === 'number' ? value : Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}
export async function PATCH(request: Request, context: Context) {
const { id } = await context.params;
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
return jsonError('Invalid holding id');
}
const payload = await request.json() as {
shares?: number;
avgCost?: number;
currentPrice?: number;
};
let found = false;
let updated: unknown = null;
await withStore((store) => {
const index = store.holdings.findIndex((entry) => entry.id === numericId);
if (index < 0) {
return;
}
found = true;
const existing = store.holdings[index];
const shares = asPositiveNumber(payload.shares) ?? Number(existing.shares);
const avgCost = asPositiveNumber(payload.avgCost) ?? Number(existing.avg_cost);
const currentPrice = asPositiveNumber(payload.currentPrice) ?? Number(existing.current_price ?? existing.avg_cost);
const next = recalculateHolding({
...existing,
shares: shares.toFixed(6),
avg_cost: avgCost.toFixed(6),
current_price: currentPrice.toFixed(6),
updated_at: nowIso(),
last_price_at: nowIso()
});
store.holdings[index] = next;
updated = next;
});
if (!found) {
return jsonError('Holding not found', 404);
}
return Response.json({ holding: updated });
}
export async function DELETE(_request: Request, context: Context) {
const { id } = await context.params;
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
return jsonError('Invalid holding id');
}
let removed = false;
await withStore((store) => {
const next = store.holdings.filter((holding) => holding.id !== numericId);
removed = next.length !== store.holdings.length;
store.holdings = next;
});
if (!removed) {
return jsonError('Holding not found', 404);
}
return Response.json({ success: true });
}

View File

@@ -0,0 +1,97 @@
import type { Holding } from '@/lib/types';
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { recalculateHolding } from '@/lib/server/portfolio';
import { getStoreSnapshot, withStore } from '@/lib/server/store';
function nowIso() {
return new Date().toISOString();
}
function asPositiveNumber(value: unknown) {
const parsed = typeof value === 'number' ? value : Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}
export async function GET() {
const snapshot = await getStoreSnapshot();
const holdings = snapshot.holdings
.slice()
.sort((a, b) => Number(b.market_value) - Number(a.market_value));
return Response.json({ holdings });
}
export async function POST(request: Request) {
try {
const payload = await request.json() as {
ticker?: string;
shares?: number;
avgCost?: number;
currentPrice?: number;
};
if (!payload.ticker || payload.ticker.trim().length < 1) {
return jsonError('ticker is required');
}
const shares = asPositiveNumber(payload.shares);
const avgCost = asPositiveNumber(payload.avgCost);
if (shares === null) {
return jsonError('shares must be a positive number');
}
if (avgCost === null) {
return jsonError('avgCost must be a positive number');
}
const ticker = payload.ticker.trim().toUpperCase();
const now = nowIso();
let holding: Holding | null = null;
await withStore((store) => {
const existingIndex = store.holdings.findIndex((entry) => entry.ticker === ticker);
const currentPrice = asPositiveNumber(payload.currentPrice) ?? avgCost;
if (existingIndex >= 0) {
const existing = store.holdings[existingIndex];
const updated = recalculateHolding({
...existing,
ticker,
shares: shares.toFixed(6),
avg_cost: avgCost.toFixed(6),
current_price: currentPrice.toFixed(6),
updated_at: now,
last_price_at: now
});
store.holdings[existingIndex] = updated;
holding = updated;
return;
}
store.counters.holdings += 1;
const created = recalculateHolding({
id: store.counters.holdings,
user_id: 1,
ticker,
shares: shares.toFixed(6),
avg_cost: avgCost.toFixed(6),
current_price: currentPrice.toFixed(6),
market_value: '0',
gain_loss: '0',
gain_loss_pct: '0',
last_price_at: now,
created_at: now,
updated_at: now
});
store.holdings.unshift(created);
holding = created;
});
return Response.json({ holding });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to save holding'));
}
}

View File

@@ -0,0 +1,16 @@
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { enqueueTask } from '@/lib/server/tasks';
export async function POST() {
try {
const task = await enqueueTask({
taskType: 'portfolio_insights',
payload: {},
priority: 70
});
return Response.json({ task });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to queue insights task'));
}
}

View File

@@ -0,0 +1,10 @@
import { getStoreSnapshot } from '@/lib/server/store';
export async function GET() {
const snapshot = await getStoreSnapshot();
const insight = snapshot.insights
.slice()
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0] ?? null;
return Response.json({ insight });
}

View File

@@ -0,0 +1,16 @@
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { enqueueTask } from '@/lib/server/tasks';
export async function POST() {
try {
const task = await enqueueTask({
taskType: 'refresh_prices',
payload: {},
priority: 80
});
return Response.json({ task });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to queue refresh task'));
}
}

View File

@@ -0,0 +1,8 @@
import { buildPortfolioSummary } from '@/lib/server/portfolio';
import { getStoreSnapshot } from '@/lib/server/store';
export async function GET() {
const snapshot = await getStoreSnapshot();
const summary = buildPortfolioSummary(snapshot.holdings);
return Response.json({ summary });
}

View File

@@ -0,0 +1,17 @@
import { jsonError } from '@/lib/server/http';
import { getTaskById } from '@/lib/server/tasks';
type Context = {
params: Promise<{ taskId: string }>;
};
export async function GET(_request: Request, context: Context) {
const { taskId } = await context.params;
const task = await getTaskById(taskId);
if (!task) {
return jsonError('Task not found', 404);
}
return Response.json({ task });
}

View File

@@ -0,0 +1,20 @@
import type { TaskStatus } from '@/lib/types';
import { listRecentTasks } from '@/lib/server/tasks';
const ALLOWED_STATUSES: TaskStatus[] = ['queued', 'running', 'completed', 'failed'];
export async function GET(request: Request) {
const url = new URL(request.url);
const limitValue = Number(url.searchParams.get('limit') ?? 20);
const limit = Number.isFinite(limitValue)
? Math.min(Math.max(Math.trunc(limitValue), 1), 200)
: 20;
const rawStatuses = url.searchParams.getAll('status');
const statuses = rawStatuses.filter((status): status is TaskStatus => {
return ALLOWED_STATUSES.includes(status as TaskStatus);
});
const tasks = await listRecentTasks(limit, statuses.length > 0 ? statuses : undefined);
return Response.json({ tasks });
}

View File

@@ -0,0 +1,29 @@
import { jsonError } from '@/lib/server/http';
import { withStore } from '@/lib/server/store';
type Context = {
params: Promise<{ id: string }>;
};
export async function DELETE(_request: Request, context: Context) {
const { id } = await context.params;
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
return jsonError('Invalid watchlist id', 400);
}
let removed = false;
await withStore((store) => {
const next = store.watchlist.filter((item) => item.id !== numericId);
removed = next.length !== store.watchlist.length;
store.watchlist = next;
});
if (!removed) {
return jsonError('Watchlist item not found', 404);
}
return Response.json({ success: true });
}

View File

@@ -0,0 +1,71 @@
import type { WatchlistItem } from '@/lib/types';
import { asErrorMessage, jsonError } from '@/lib/server/http';
import { getStoreSnapshot, withStore } from '@/lib/server/store';
function nowIso() {
return new Date().toISOString();
}
export async function GET() {
const snapshot = await getStoreSnapshot();
const items = snapshot.watchlist
.slice()
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
return Response.json({ items });
}
export async function POST(request: Request) {
try {
const payload = await request.json() as {
ticker?: string;
companyName?: string;
sector?: string;
};
if (!payload.ticker || payload.ticker.trim().length < 1) {
return jsonError('ticker is required');
}
if (!payload.companyName || payload.companyName.trim().length < 1) {
return jsonError('companyName is required');
}
let item: WatchlistItem | null = null;
await withStore((store) => {
const ticker = payload.ticker!.trim().toUpperCase();
const existingIndex = store.watchlist.findIndex((entry) => entry.ticker === ticker);
if (existingIndex >= 0) {
const existing = store.watchlist[existingIndex];
const updated: WatchlistItem = {
...existing,
company_name: payload.companyName!.trim(),
sector: payload.sector?.trim() || null
};
store.watchlist[existingIndex] = updated;
item = updated;
return;
}
store.counters.watchlist += 1;
const created: WatchlistItem = {
id: store.counters.watchlist,
user_id: 1,
ticker,
company_name: payload.companyName!.trim(),
sector: payload.sector?.trim() || null,
created_at: nowIso()
};
store.watchlist.unshift(created);
item = created;
});
return Response.json({ item });
} catch (error) {
return jsonError(asErrorMessage(error, 'Failed to create watchlist item'));
}
}

View File

@@ -1,86 +1,32 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn, useSession } from '@/lib/better-auth';
import { AuthShell } from '@/components/auth/auth-shell'; import { AuthShell } from '@/components/auth/auth-shell';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
export default function SignInPage() { export default function SignInPage() {
const router = useRouter();
const { data: session, isPending: sessionPending } = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!sessionPending && session?.user) {
router.replace('/');
}
}, [sessionPending, session, router]);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError(null);
try {
const result = await signIn.email({ email, password });
if (result.error) {
setError(result.error.message || 'Invalid credentials');
} else {
router.replace('/');
router.refresh();
}
} catch {
setError('Sign in failed');
} finally {
setLoading(false);
}
};
return ( return (
<AuthShell <AuthShell
title="Sign in" title="Local Runtime Mode"
subtitle="Authenticate with Better Auth session-backed credentials." subtitle="Authentication is disabled in this rebuilt local-first environment."
footer={( footer={(
<> <>
No account yet?{' '} Need multi-user auth later?{' '}
<Link href="/auth/signup" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"> <Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Create one Open command center
</Link> </Link>
</> </>
)} )}
> >
<form onSubmit={handleSubmit} className="space-y-4"> <p className="text-sm text-[color:var(--terminal-muted)]">
<div> Continue directly into the fiscal terminal. API routes are same-origin and task execution is fully local with OpenClaw support.
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Email</label> </p>
<Input type="email" required value={email} onChange={(event) => setEmail(event.target.value)} placeholder="you@company.com" />
</div>
<div> <Link href="/" className="mt-6 block">
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Password</label> <Button type="button" className="w-full">
<Input Enter terminal
type="password"
required
minLength={8}
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="********"
/>
</div>
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
<Button type="submit" className="w-full" disabled={loading || sessionPending}>
{loading ? 'Signing in...' : 'Sign in'}
</Button> </Button>
</form> </Link>
</AuthShell> </AuthShell>
); );
} }

View File

@@ -1,96 +1,32 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { signUp, useSession } from '@/lib/better-auth';
import { AuthShell } from '@/components/auth/auth-shell'; import { AuthShell } from '@/components/auth/auth-shell';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
export default function SignUpPage() { export default function SignUpPage() {
const router = useRouter();
const { data: session, isPending: sessionPending } = useSession();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!sessionPending && session?.user) {
router.replace('/');
}
}, [sessionPending, session, router]);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError(null);
try {
const result = await signUp.email({
name,
email,
password
});
if (result.error) {
setError(result.error.message || 'Unable to create account');
} else {
router.replace('/');
router.refresh();
}
} catch {
setError('Sign up failed');
} finally {
setLoading(false);
}
};
return ( return (
<AuthShell <AuthShell
title="Create account" title="Workspace Provisioned"
subtitle="Provision an analyst workspace with Better Auth sessions." subtitle="This clone now runs in local-operator mode and does not require account creation."
footer={( footer={(
<> <>
Already registered?{' '} Already set?{' '}
<Link href="/auth/signin" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]"> <Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
Sign in Launch dashboard
</Link> </Link>
</> </>
)} )}
> >
<form onSubmit={handleSubmit} className="space-y-4"> <p className="text-sm text-[color:var(--terminal-muted)]">
<div> For production deployment you can reintroduce Better Auth, but the rebuilt stack is intentionally self-contained for fast iteration.
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Name</label> </p>
<Input required value={name} onChange={(event) => setName(event.target.value)} placeholder="Operator name" />
</div>
<div> <Link href="/" className="mt-6 block">
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Email</label> <Button type="button" className="w-full">
<Input type="email" required value={email} onChange={(event) => setEmail(event.target.value)} placeholder="you@company.com" /> Open fiscal desk
</div>
<div>
<label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Password</label>
<Input
type="password"
required
minLength={8}
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Minimum 8 characters"
/>
</div>
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
<Button type="submit" className="w-full" disabled={loading || sessionPending}>
{loading ? 'Creating account...' : 'Create account'}
</Button> </Button>
</form> </Link>
</AuthShell> </AuthShell>
); );
} }

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { Suspense } from 'react';
import { format } from 'date-fns'; import { format } from 'date-fns';
import { Bot, Download, Search, TimerReset } from 'lucide-react'; import { Bot, Download, Search, TimerReset } from 'lucide-react';
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
@@ -16,6 +17,14 @@ import type { Filing, Task } from '@/lib/types';
import { formatCompactCurrency } from '@/lib/format'; import { formatCompactCurrency } from '@/lib/format';
export default function FilingsPage() { export default function FilingsPage() {
return (
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Opening filings stream...</div>}>
<FilingsPageContent />
</Suspense>
);
}
function FilingsPageContent() {
const { isPending, isAuthenticated } = useAuthGuard(); const { isPending, isAuthenticated } = useAuthGuard();
const searchParams = useSearchParams(); const searchParams = useSearchParams();

View File

@@ -3,6 +3,8 @@
@tailwind utilities; @tailwind utilities;
:root { :root {
--font-display: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
--font-mono: "Menlo", "SFMono-Regular", "Consolas", "Liberation Mono", monospace;
--bg-0: #05080d; --bg-0: #05080d;
--bg-1: #08121a; --bg-1: #08121a;
--bg-2: #0b1f28; --bg-2: #0b1f28;

View File

@@ -1,16 +1,5 @@
import './globals.css'; import './globals.css';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { JetBrains_Mono, Space_Grotesk } from 'next/font/google';
const display = Space_Grotesk({
subsets: ['latin'],
variable: '--font-display'
});
const mono = JetBrains_Mono({
subsets: ['latin'],
variable: '--font-mono'
});
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Fiscal Clone', title: 'Fiscal Clone',
@@ -19,7 +8,7 @@ export const metadata: Metadata = {
export default function RootLayout({ children }: { children: React.ReactNode }) { export default function RootLayout({ children }: { children: React.ReactNode }) {
return ( return (
<html lang="en" className={`${display.variable} ${mono.variable}`}> <html lang="en">
<body>{children}</body> <body>{children}</body>
</html> </html>
); );

View File

@@ -1,9 +1,8 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { Activity, BookOpenText, ChartCandlestick, Eye, LogOut } from 'lucide-react'; import { Activity, BookOpenText, ChartCandlestick, Eye } from 'lucide-react';
import { signOut, useSession } from '@/lib/better-auth';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
type AppShellProps = { type AppShellProps = {
@@ -22,14 +21,6 @@ const NAV_ITEMS = [
export function AppShell({ title, subtitle, actions, children }: AppShellProps) { export function AppShell({ title, subtitle, actions, children }: AppShellProps) {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter();
const { data: session } = useSession();
const handleSignOut = async () => {
await signOut();
router.replace('/auth/signin');
router.refresh();
};
return ( return (
<div className="app-surface"> <div className="app-surface">
@@ -70,16 +61,11 @@ export function AppShell({ title, subtitle, actions, children }: AppShellProps)
</nav> </nav>
<div className="mt-auto rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-3"> <div className="mt-auto rounded-xl border border-[color:var(--line-weak)] bg-[color:var(--panel-soft)] p-3">
<p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Session</p> <p className="text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Runtime</p>
<p className="mt-1 truncate text-sm text-[color:var(--terminal-bright)]">{session?.user?.email ?? 'anonymous'}</p> <p className="mt-1 truncate text-sm text-[color:var(--terminal-bright)]">local operator mode</p>
<button <p className="mt-2 text-xs text-[color:var(--terminal-muted)]">
type="button" OpenClaw and market data are driven by environment configuration and live API tasks.
onClick={handleSignOut} </p>
className="mt-3 inline-flex w-full items-center justify-center gap-2 rounded-lg border border-[color:var(--line-weak)] bg-[color:var(--panel)] px-3 py-2 text-xs text-[color:var(--terminal-bright)] transition hover:border-[color:var(--line-strong)] hover:bg-[color:var(--panel-bright)]"
>
<LogOut className="size-3.5" />
Sign out
</button>
</div> </div>
</aside> </aside>

View File

@@ -1,22 +1,16 @@
'use client'; 'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from '@/lib/better-auth';
export function useAuthGuard() { export function useAuthGuard() {
const { data: session, isPending } = useSession();
const router = useRouter();
useEffect(() => {
if (!isPending && !session) {
router.replace('/auth/signin');
}
}, [isPending, session, router]);
return { return {
session, session: {
isPending, user: {
isAuthenticated: Boolean(session?.user) id: 1,
name: 'Local Operator',
email: 'operator@local.fiscal',
image: null
}
},
isPending: false,
isAuthenticated: true
}; };
} }

View File

@@ -1,11 +0,0 @@
import { createAuthClient } from 'better-auth/react';
import { resolveApiBaseURL } from '@/lib/runtime-url';
export const authClient = createAuthClient({
baseURL: resolveApiBaseURL(process.env.NEXT_PUBLIC_API_URL),
fetchOptions: {
credentials: 'include'
}
});
export const { signIn, signUp, signOut, useSession } = authClient;

View File

@@ -2,44 +2,12 @@ function trimTrailingSlash(value: string) {
return value.endsWith('/') ? value.slice(0, -1) : value; return value.endsWith('/') ? value.slice(0, -1) : value;
} }
function isInternalHost(hostname: string) {
return hostname === 'backend'
|| hostname === 'localhost'
|| hostname === '127.0.0.1'
|| hostname.endsWith('.internal');
}
function parseUrl(url: string) {
try {
return new URL(url);
} catch {
return null;
}
}
export function resolveApiBaseURL(configuredBaseURL: string | undefined) { export function resolveApiBaseURL(configuredBaseURL: string | undefined) {
const fallbackLocal = 'http://localhost:3001'; const candidate = configuredBaseURL?.trim();
const candidate = configuredBaseURL?.trim() || fallbackLocal;
if (typeof window === 'undefined') { if (!candidate) {
return trimTrailingSlash(candidate); return '';
} }
const parsed = parseUrl(candidate); return trimTrailingSlash(candidate);
if (!parsed) {
return `${window.location.origin}`;
}
const browserHost = window.location.hostname;
const browserIsLocal = browserHost === 'localhost' || browserHost === '127.0.0.1';
if (!browserIsLocal && isInternalHost(parsed.hostname)) {
console.warn(
`[fiscal] NEXT_PUBLIC_API_URL is internal (${parsed.hostname}); falling back to https://api.${browserHost}`
);
return trimTrailingSlash(`https://api.${browserHost}`);
}
return trimTrailingSlash(parsed.toString());
} }

View File

@@ -0,0 +1,11 @@
export function jsonError(message: string, status = 400) {
return Response.json({ error: message }, { status });
}
export function asErrorMessage(error: unknown, fallback: string) {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return fallback;
}

View File

@@ -0,0 +1,92 @@
type ChatCompletionResponse = {
choices?: Array<{
message?: {
content?: string;
};
}>;
};
function envValue(name: string) {
const value = process.env[name];
if (!value) {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
const DEFAULT_MODEL = 'zeroclaw';
function fallbackResponse(prompt: string) {
const clipped = prompt.split('\n').slice(0, 6).join(' ').slice(0, 260);
return [
'OpenClaw fallback mode is active (missing OPENCLAW_BASE_URL or OPENCLAW_API_KEY).',
'Thesis: Portfolio remains analyzable with local heuristics until live model access is configured.',
'Risk scan: Concentration and filing sentiment should be monitored after each sync cycle.',
`Context digest: ${clipped}`
].join('\n\n');
}
export function getOpenClawConfig() {
return {
baseUrl: envValue('OPENCLAW_BASE_URL'),
apiKey: envValue('OPENCLAW_API_KEY'),
model: envValue('OPENCLAW_MODEL') ?? DEFAULT_MODEL
};
}
export function isOpenClawConfigured() {
const config = getOpenClawConfig();
return Boolean(config.baseUrl && config.apiKey);
}
export async function runOpenClawAnalysis(prompt: string, systemPrompt?: string) {
const config = getOpenClawConfig();
if (!config.baseUrl || !config.apiKey) {
return {
provider: 'local-fallback',
model: config.model,
text: fallbackResponse(prompt)
};
}
const response = await fetch(`${config.baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.apiKey}`
},
body: JSON.stringify({
model: config.model,
temperature: 0.2,
messages: [
systemPrompt
? { role: 'system', content: systemPrompt }
: null,
{ role: 'user', content: prompt }
].filter(Boolean)
}),
cache: 'no-store'
});
if (!response.ok) {
const body = await response.text();
throw new Error(`OpenClaw request failed (${response.status}): ${body.slice(0, 220)}`);
}
const payload = await response.json() as ChatCompletionResponse;
const text = payload.choices?.[0]?.message?.content?.trim();
if (!text) {
throw new Error('OpenClaw returned an empty response');
}
return {
provider: 'openclaw',
model: config.model,
text
};
}

View File

@@ -0,0 +1,69 @@
import type { Holding, PortfolioSummary } from '@/lib/types';
function asFiniteNumber(value: string | number | null | undefined) {
if (value === null || value === undefined) {
return 0;
}
const parsed = typeof value === 'number' ? value : Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function toDecimalString(value: number, digits = 4) {
return value.toFixed(digits);
}
export function recalculateHolding(base: Holding): Holding {
const shares = asFiniteNumber(base.shares);
const avgCost = asFiniteNumber(base.avg_cost);
const price = base.current_price === null
? avgCost
: asFiniteNumber(base.current_price);
const marketValue = shares * price;
const costBasis = shares * avgCost;
const gainLoss = marketValue - costBasis;
const gainLossPct = costBasis > 0 ? (gainLoss / costBasis) * 100 : 0;
return {
...base,
shares: toDecimalString(shares, 6),
avg_cost: toDecimalString(avgCost, 6),
current_price: toDecimalString(price, 6),
market_value: toDecimalString(marketValue, 2),
gain_loss: toDecimalString(gainLoss, 2),
gain_loss_pct: toDecimalString(gainLossPct, 2)
};
}
export function buildPortfolioSummary(holdings: Holding[]): PortfolioSummary {
const positions = holdings.length;
const totals = holdings.reduce(
(acc, holding) => {
const shares = asFiniteNumber(holding.shares);
const avgCost = asFiniteNumber(holding.avg_cost);
const marketValue = asFiniteNumber(holding.market_value);
const gainLoss = asFiniteNumber(holding.gain_loss);
acc.totalValue += marketValue;
acc.totalGainLoss += gainLoss;
acc.totalCostBasis += shares * avgCost;
return acc;
},
{ totalValue: 0, totalGainLoss: 0, totalCostBasis: 0 }
);
const avgReturnPct = totals.totalCostBasis > 0
? (totals.totalGainLoss / totals.totalCostBasis) * 100
: 0;
return {
positions,
total_value: toDecimalString(totals.totalValue, 2),
total_gain_loss: toDecimalString(totals.totalGainLoss, 2),
total_cost_basis: toDecimalString(totals.totalCostBasis, 2),
avg_return_pct: toDecimalString(avgReturnPct, 2)
};
}

View File

@@ -0,0 +1,44 @@
const YAHOO_BASE = 'https://query1.finance.yahoo.com/v8/finance/chart';
function fallbackQuote(ticker: string) {
const normalized = ticker.trim().toUpperCase();
let hash = 0;
for (const char of normalized) {
hash = (hash * 31 + char.charCodeAt(0)) % 100000;
}
return 40 + (hash % 360) + ((hash % 100) / 100);
}
export async function getQuote(ticker: string): Promise<number> {
const normalizedTicker = ticker.trim().toUpperCase();
try {
const response = await fetch(`${YAHOO_BASE}/${normalizedTicker}?interval=1d&range=1d`, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; FiscalClone/3.0)'
},
cache: 'no-store'
});
if (!response.ok) {
return fallbackQuote(normalizedTicker);
}
const payload = await response.json() as {
chart?: {
result?: Array<{ meta?: { regularMarketPrice?: number } }>;
};
};
const price = payload.chart?.result?.[0]?.meta?.regularMarketPrice;
if (typeof price !== 'number' || !Number.isFinite(price)) {
return fallbackQuote(normalizedTicker);
}
return price;
} catch {
return fallbackQuote(normalizedTicker);
}
}

248
frontend/lib/server/sec.ts Normal file
View File

@@ -0,0 +1,248 @@
import type { Filing } from '@/lib/types';
type FilingType = Filing['filing_type'];
type TickerDirectoryRecord = {
cik_str: number;
ticker: string;
title: string;
};
type RecentFilingsPayload = {
filings?: {
recent?: {
accessionNumber?: string[];
filingDate?: string[];
form?: string[];
primaryDocument?: string[];
};
};
cik?: string;
name?: string;
};
type CompanyFactsPayload = {
facts?: {
'us-gaap'?: Record<string, { units?: Record<string, Array<{ val?: number; end?: string; filed?: string }>> }>;
};
};
type SecFiling = {
ticker: string;
cik: string;
companyName: string;
filingType: FilingType;
filingDate: string;
accessionNumber: string;
filingUrl: string | null;
};
const SUPPORTED_FORMS: FilingType[] = ['10-K', '10-Q', '8-K'];
const TICKER_CACHE_TTL_MS = 1000 * 60 * 60 * 12;
let tickerCache = new Map<string, TickerDirectoryRecord>();
let tickerCacheLoadedAt = 0;
function envUserAgent() {
return process.env.SEC_USER_AGENT || 'Fiscal Clone <support@fiscal.local>';
}
function todayIso() {
return new Date().toISOString().slice(0, 10);
}
function pseudoMetric(seed: string, min: number, max: number) {
let hash = 0;
for (const char of seed) {
hash = (hash * 33 + char.charCodeAt(0)) % 100000;
}
const fraction = (hash % 10000) / 10000;
return min + (max - min) * fraction;
}
function fallbackFilings(ticker: string, limit: number): SecFiling[] {
const normalized = ticker.trim().toUpperCase();
const companyName = `${normalized} Holdings Inc.`;
const filings: SecFiling[] = [];
for (let i = 0; i < limit; i += 1) {
const filingType = SUPPORTED_FORMS[i % SUPPORTED_FORMS.length];
const date = new Date(Date.now() - i * 1000 * 60 * 60 * 24 * 35).toISOString().slice(0, 10);
const accessionNumber = `${Date.now()}-${i}`;
filings.push({
ticker: normalized,
cik: String(100000 + i),
companyName,
filingType,
filingDate: date,
accessionNumber,
filingUrl: null
});
}
return filings;
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url, {
headers: {
'User-Agent': envUserAgent(),
Accept: 'application/json'
},
cache: 'no-store'
});
if (!response.ok) {
throw new Error(`SEC request failed (${response.status})`);
}
return await response.json() as T;
}
async function ensureTickerCache() {
const isFresh = Date.now() - tickerCacheLoadedAt < TICKER_CACHE_TTL_MS;
if (isFresh && tickerCache.size > 0) {
return;
}
const payload = await fetchJson<Record<string, TickerDirectoryRecord>>('https://www.sec.gov/files/company_tickers.json');
const next = new Map<string, TickerDirectoryRecord>();
for (const record of Object.values(payload)) {
next.set(record.ticker.toUpperCase(), record);
}
tickerCache = next;
tickerCacheLoadedAt = Date.now();
}
async function resolveTicker(ticker: string) {
await ensureTickerCache();
const normalized = ticker.trim().toUpperCase();
const record = tickerCache.get(normalized);
if (!record) {
throw new Error(`Ticker ${normalized} not found in SEC directory`);
}
return {
ticker: normalized,
cik: String(record.cik_str),
companyName: record.title
};
}
function pickLatestFact(payload: CompanyFactsPayload, tag: string): number | null {
const unitCollections = payload.facts?.['us-gaap']?.[tag]?.units;
if (!unitCollections) {
return null;
}
const preferredUnits = ['USD', 'USD/shares'];
for (const unit of preferredUnits) {
const series = unitCollections[unit];
if (!series?.length) {
continue;
}
const best = [...series]
.filter((item) => typeof item.val === 'number')
.sort((a, b) => {
const aDate = Date.parse(a.filed ?? a.end ?? '1970-01-01');
const bDate = Date.parse(b.filed ?? b.end ?? '1970-01-01');
return bDate - aDate;
})[0];
if (best?.val !== undefined) {
return best.val;
}
}
return null;
}
export async function fetchRecentFilings(ticker: string, limit = 20): Promise<SecFiling[]> {
const safeLimit = Math.min(Math.max(Math.trunc(limit), 1), 50);
try {
const company = await resolveTicker(ticker);
const cikPadded = company.cik.padStart(10, '0');
const payload = await fetchJson<RecentFilingsPayload>(`https://data.sec.gov/submissions/CIK${cikPadded}.json`);
const recent = payload.filings?.recent;
if (!recent) {
return fallbackFilings(company.ticker, safeLimit);
}
const forms = recent.form ?? [];
const accessionNumbers = recent.accessionNumber ?? [];
const filingDates = recent.filingDate ?? [];
const primaryDocuments = recent.primaryDocument ?? [];
const filings: SecFiling[] = [];
for (let i = 0; i < forms.length; i += 1) {
const filingType = forms[i] as FilingType;
if (!SUPPORTED_FORMS.includes(filingType)) {
continue;
}
const accessionNumber = accessionNumbers[i];
if (!accessionNumber) {
continue;
}
const compactAccession = accessionNumber.replace(/-/g, '');
const documentName = primaryDocuments[i];
const filingUrl = documentName
? `https://www.sec.gov/Archives/edgar/data/${Number(company.cik)}/${compactAccession}/${documentName}`
: null;
filings.push({
ticker: company.ticker,
cik: company.cik,
companyName: payload.name ?? company.companyName,
filingType,
filingDate: filingDates[i] ?? todayIso(),
accessionNumber,
filingUrl
});
if (filings.length >= safeLimit) {
break;
}
}
return filings.length > 0 ? filings : fallbackFilings(company.ticker, safeLimit);
} catch {
return fallbackFilings(ticker, safeLimit);
}
}
export async function fetchFilingMetrics(cik: string, ticker: string) {
try {
const normalized = cik.padStart(10, '0');
const payload = await fetchJson<CompanyFactsPayload>(`https://data.sec.gov/api/xbrl/companyfacts/CIK${normalized}.json`);
return {
revenue: pickLatestFact(payload, 'Revenues'),
netIncome: pickLatestFact(payload, 'NetIncomeLoss'),
totalAssets: pickLatestFact(payload, 'Assets'),
cash: pickLatestFact(payload, 'CashAndCashEquivalentsAtCarryingValue'),
debt: pickLatestFact(payload, 'LongTermDebt')
};
} catch {
return {
revenue: Math.round(pseudoMetric(`${ticker}-revenue`, 2_000_000_000, 350_000_000_000)),
netIncome: Math.round(pseudoMetric(`${ticker}-net`, 150_000_000, 40_000_000_000)),
totalAssets: Math.round(pseudoMetric(`${ticker}-assets`, 4_000_000_000, 500_000_000_000)),
cash: Math.round(pseudoMetric(`${ticker}-cash`, 200_000_000, 180_000_000_000)),
debt: Math.round(pseudoMetric(`${ticker}-debt`, 300_000_000, 220_000_000_000))
};
}
}

View File

@@ -0,0 +1,100 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { Filing, Holding, PortfolioInsight, Task, WatchlistItem } from '@/lib/types';
export type DataStore = {
counters: {
watchlist: number;
holdings: number;
filings: number;
insights: number;
};
watchlist: WatchlistItem[];
holdings: Holding[];
filings: Filing[];
tasks: Task[];
insights: PortfolioInsight[];
};
const DATA_DIR = path.join(process.cwd(), 'data');
const STORE_PATH = path.join(DATA_DIR, 'store.json');
let writeQueue = Promise.resolve();
function nowIso() {
return new Date().toISOString();
}
function createDefaultStore(): DataStore {
const now = nowIso();
return {
counters: {
watchlist: 0,
holdings: 0,
filings: 0,
insights: 0
},
watchlist: [],
holdings: [],
filings: [],
tasks: [],
insights: [
{
id: 1,
user_id: 1,
provider: 'local-bootstrap',
model: 'zeroclaw',
content: [
'System initialized in local-first mode.',
'Add holdings and sync filings to produce a live AI brief via OpenClaw.'
].join('\n'),
created_at: now
}
]
};
}
async function ensureStoreFile() {
await mkdir(DATA_DIR, { recursive: true });
try {
await readFile(STORE_PATH, 'utf8');
} catch {
const defaultStore = createDefaultStore();
defaultStore.counters.insights = defaultStore.insights.length;
await writeFile(STORE_PATH, JSON.stringify(defaultStore, null, 2), 'utf8');
}
}
async function readStore(): Promise<DataStore> {
await ensureStoreFile();
const raw = await readFile(STORE_PATH, 'utf8');
return JSON.parse(raw) as DataStore;
}
async function writeStore(store: DataStore) {
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), 'utf8');
}
function cloneStore(store: DataStore): DataStore {
return JSON.parse(JSON.stringify(store)) as DataStore;
}
export async function getStoreSnapshot() {
const store = await readStore();
return cloneStore(store);
}
export async function withStore<T>(mutator: (store: DataStore) => T | Promise<T>): Promise<T> {
const run = async () => {
const store = await readStore();
const result = await mutator(store);
await writeStore(store);
return result;
};
const nextRun = writeQueue.then(run, run);
writeQueue = nextRun.then(() => undefined, () => undefined);
return await nextRun;
}

View File

@@ -0,0 +1,404 @@
import { randomUUID } from 'node:crypto';
import type { Filing, Holding, PortfolioInsight, Task, TaskStatus, TaskType } from '@/lib/types';
import { runOpenClawAnalysis } from '@/lib/server/openclaw';
import { buildPortfolioSummary, recalculateHolding } from '@/lib/server/portfolio';
import { getQuote } from '@/lib/server/prices';
import { fetchFilingMetrics, fetchRecentFilings } from '@/lib/server/sec';
import { getStoreSnapshot, withStore } from '@/lib/server/store';
type EnqueueTaskInput = {
taskType: TaskType;
payload?: Record<string, unknown>;
priority?: number;
maxAttempts?: number;
};
const activeTaskRuns = new Set<string>();
function nowIso() {
return new Date().toISOString();
}
function toTaskResult(value: unknown): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return { value };
}
return value as Record<string, unknown>;
}
function parseTicker(raw: unknown) {
if (typeof raw !== 'string' || raw.trim().length < 1) {
throw new Error('Ticker is required');
}
return raw.trim().toUpperCase();
}
function parseLimit(raw: unknown, fallback: number, min: number, max: number) {
const numberValue = typeof raw === 'number' ? raw : Number(raw);
if (!Number.isFinite(numberValue)) {
return fallback;
}
const intValue = Math.trunc(numberValue);
return Math.min(Math.max(intValue, min), max);
}
function queueTaskRun(taskId: string, delayMs = 40) {
setTimeout(() => {
void processTask(taskId);
}, delayMs);
}
async function markTask(taskId: string, mutator: (task: Task) => void) {
await withStore((store) => {
const index = store.tasks.findIndex((task) => task.id === taskId);
if (index < 0) {
return;
}
const task = store.tasks[index];
mutator(task);
task.updated_at = nowIso();
});
}
async function processSyncFilings(task: Task) {
const ticker = parseTicker(task.payload.ticker);
const limit = parseLimit(task.payload.limit, 20, 1, 50);
const filings = await fetchRecentFilings(ticker, limit);
const metricsByCik = new Map<string, Filing['metrics']>();
for (const filing of filings) {
if (!metricsByCik.has(filing.cik)) {
const metrics = await fetchFilingMetrics(filing.cik, filing.ticker);
metricsByCik.set(filing.cik, metrics);
}
}
let insertedCount = 0;
let updatedCount = 0;
await withStore((store) => {
for (const filing of filings) {
const existingIndex = store.filings.findIndex((entry) => entry.accession_number === filing.accessionNumber);
const timestamp = nowIso();
const metrics = metricsByCik.get(filing.cik) ?? null;
if (existingIndex >= 0) {
const existing = store.filings[existingIndex];
store.filings[existingIndex] = {
...existing,
ticker: filing.ticker,
cik: filing.cik,
filing_type: filing.filingType,
filing_date: filing.filingDate,
company_name: filing.companyName,
filing_url: filing.filingUrl,
metrics,
updated_at: timestamp
};
updatedCount += 1;
} else {
store.counters.filings += 1;
store.filings.unshift({
id: store.counters.filings,
ticker: filing.ticker,
filing_type: filing.filingType,
filing_date: filing.filingDate,
accession_number: filing.accessionNumber,
cik: filing.cik,
company_name: filing.companyName,
filing_url: filing.filingUrl,
metrics,
analysis: null,
created_at: timestamp,
updated_at: timestamp
});
insertedCount += 1;
}
}
store.filings.sort((a, b) => {
const byDate = Date.parse(b.filing_date) - Date.parse(a.filing_date);
return Number.isFinite(byDate) && byDate !== 0
? byDate
: Date.parse(b.updated_at) - Date.parse(a.updated_at);
});
});
return {
ticker,
fetched: filings.length,
inserted: insertedCount,
updated: updatedCount
};
}
async function processRefreshPrices() {
const snapshot = await getStoreSnapshot();
const tickers = [...new Set(snapshot.holdings.map((holding) => holding.ticker))];
const quotes = new Map<string, number>();
for (const ticker of tickers) {
const quote = await getQuote(ticker);
quotes.set(ticker, quote);
}
let updatedCount = 0;
const updateTime = nowIso();
await withStore((store) => {
store.holdings = store.holdings.map((holding) => {
const quote = quotes.get(holding.ticker);
if (quote === undefined) {
return holding;
}
updatedCount += 1;
return recalculateHolding({
...holding,
current_price: quote.toFixed(6),
last_price_at: updateTime,
updated_at: updateTime
});
});
});
return {
updatedCount,
totalTickers: tickers.length
};
}
async function processAnalyzeFiling(task: Task) {
const accessionNumber = typeof task.payload.accessionNumber === 'string'
? task.payload.accessionNumber
: '';
if (!accessionNumber) {
throw new Error('accessionNumber is required');
}
const snapshot = await getStoreSnapshot();
const filing = snapshot.filings.find((entry) => entry.accession_number === accessionNumber);
if (!filing) {
throw new Error(`Filing ${accessionNumber} not found`);
}
const prompt = [
'You are a fiscal research assistant focused on regulatory signals.',
`Analyze this SEC filing from ${filing.company_name} (${filing.ticker}).`,
`Form: ${filing.filing_type}`,
`Filed: ${filing.filing_date}`,
`Metrics: ${JSON.stringify(filing.metrics ?? {})}`,
'Return concise sections: Thesis, Red Flags, Follow-up Questions, Portfolio Impact.'
].join('\n');
const analysis = await runOpenClawAnalysis(prompt, 'Use concise institutional analyst language.');
await withStore((store) => {
const index = store.filings.findIndex((entry) => entry.accession_number === accessionNumber);
if (index < 0) {
return;
}
store.filings[index] = {
...store.filings[index],
analysis: {
provider: analysis.provider,
model: analysis.model,
text: analysis.text
},
updated_at: nowIso()
};
});
return {
accessionNumber,
provider: analysis.provider,
model: analysis.model
};
}
function holdingDigest(holdings: Holding[]) {
return holdings.map((holding) => ({
ticker: holding.ticker,
shares: holding.shares,
avgCost: holding.avg_cost,
currentPrice: holding.current_price,
marketValue: holding.market_value,
gainLoss: holding.gain_loss,
gainLossPct: holding.gain_loss_pct
}));
}
async function processPortfolioInsights() {
const snapshot = await getStoreSnapshot();
const summary = buildPortfolioSummary(snapshot.holdings);
const prompt = [
'Generate portfolio intelligence with actionable recommendations.',
`Portfolio summary: ${JSON.stringify(summary)}`,
`Holdings: ${JSON.stringify(holdingDigest(snapshot.holdings))}`,
'Respond with: 1) health score (0-100), 2) top 3 risks, 3) top 3 opportunities, 4) next actions in 7 days.'
].join('\n');
const analysis = await runOpenClawAnalysis(prompt, 'Act as a risk-aware buy-side analyst.');
const createdAt = nowIso();
await withStore((store) => {
store.counters.insights += 1;
const insight: PortfolioInsight = {
id: store.counters.insights,
user_id: 1,
provider: analysis.provider,
model: analysis.model,
content: analysis.text,
created_at: createdAt
};
store.insights.unshift(insight);
});
return {
provider: analysis.provider,
model: analysis.model,
summary
};
}
async function runTaskProcessor(task: Task) {
switch (task.task_type) {
case 'sync_filings':
return await processSyncFilings(task);
case 'refresh_prices':
return await processRefreshPrices();
case 'analyze_filing':
return await processAnalyzeFiling(task);
case 'portfolio_insights':
return await processPortfolioInsights();
default:
throw new Error(`Unsupported task type: ${task.task_type}`);
}
}
async function processTask(taskId: string) {
if (activeTaskRuns.has(taskId)) {
return;
}
activeTaskRuns.add(taskId);
try {
const task = await withStore((store) => {
const index = store.tasks.findIndex((entry) => entry.id === taskId);
if (index < 0) {
return null;
}
const target = store.tasks[index];
if (target.status !== 'queued') {
return null;
}
target.status = 'running';
target.attempts += 1;
target.updated_at = nowIso();
return { ...target };
});
if (!task) {
return;
}
try {
const result = toTaskResult(await runTaskProcessor(task));
await markTask(taskId, (target) => {
target.status = 'completed';
target.result = result;
target.error = null;
target.finished_at = nowIso();
});
} catch (error) {
const reason = error instanceof Error ? error.message : 'Task failed unexpectedly';
const shouldRetry = task.attempts < task.max_attempts;
if (shouldRetry) {
await markTask(taskId, (target) => {
target.status = 'queued';
target.error = reason;
});
queueTaskRun(taskId, 1200);
} else {
await markTask(taskId, (target) => {
target.status = 'failed';
target.error = reason;
target.finished_at = nowIso();
});
}
}
} finally {
activeTaskRuns.delete(taskId);
}
}
export async function enqueueTask(input: EnqueueTaskInput) {
const createdAt = nowIso();
const task: Task = {
id: randomUUID(),
task_type: input.taskType,
status: 'queued',
priority: input.priority ?? 50,
payload: input.payload ?? {},
result: null,
error: null,
attempts: 0,
max_attempts: input.maxAttempts ?? 3,
created_at: createdAt,
updated_at: createdAt,
finished_at: null
};
await withStore((store) => {
store.tasks.unshift(task);
store.tasks.sort((a, b) => {
if (a.priority !== b.priority) {
return b.priority - a.priority;
}
return Date.parse(b.created_at) - Date.parse(a.created_at);
});
});
queueTaskRun(task.id);
return task;
}
export async function getTaskById(taskId: string) {
const snapshot = await getStoreSnapshot();
return snapshot.tasks.find((task) => task.id === taskId) ?? null;
}
export async function listRecentTasks(limit = 20, statuses?: TaskStatus[]) {
const safeLimit = Math.min(Math.max(Math.trunc(limit), 1), 200);
const snapshot = await getStoreSnapshot();
const filtered = statuses && statuses.length > 0
? snapshot.tasks.filter((task) => statuses.includes(task.status))
: snapshot.tasks;
return filtered
.slice()
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))
.slice(0, safeLimit);
}

View File

@@ -64,10 +64,11 @@ export type Filing = {
}; };
export type TaskStatus = 'queued' | 'running' | 'completed' | 'failed'; export type TaskStatus = 'queued' | 'running' | 'completed' | 'failed';
export type TaskType = 'sync_filings' | 'refresh_prices' | 'analyze_filing' | 'portfolio_insights';
export type Task = { export type Task = {
id: string; id: string;
task_type: 'sync_filings' | 'refresh_prices' | 'analyze_filing' | 'portfolio_insights'; task_type: TaskType;
status: TaskStatus; status: TaskStatus;
priority: number; priority: number;
payload: Record<string, unknown>; payload: Record<string, unknown>;

View File

@@ -1,5 +1,6 @@
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information. // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@@ -2,8 +2,11 @@
const nextConfig = { const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
output: 'standalone', output: 'standalone',
turbopack: {
root: __dirname
},
env: { env: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001' NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || ''
}, },
async headers() { async headers() {
return [ return [

File diff suppressed because it is too large Load Diff

View File

@@ -3,13 +3,12 @@
"version": "2.0.0", "version": "2.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev --turbopack",
"build": "next build", "build": "next build --turbopack",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"better-auth": "^1.4.18",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"lucide-react": "^0.574.0", "lucide-react": "^0.574.0",

View File

@@ -1,7 +1,11 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"], "lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
@@ -11,7 +15,7 @@
"moduleResolution": "bundler", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "react-jsx",
"incremental": true, "incremental": true,
"plugins": [ "plugins": [
{ {
@@ -19,9 +23,19 @@
} }
], ],
"paths": { "paths": {
"@/*": ["./*"] "@/*": [
"./*"
]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": [
"exclude": ["node_modules"] "next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
} }