Commit Graph
533 Commits
Author SHA1 Message Date
g-butandClaude Opus 4.6 06531355bf feat(security): add security headers via next.config.js
Add CSP, HSTS (1 year), X-Content-Type-Options, X-Frame-Options,
Referrer-Policy, and Permissions-Policy headers to all routes.
CSP allows required external sources (Groq, OpenRouter, Supabase,
GitHub, YouTube, Giscus).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 09:51:15 +01:00
g-butandClaude Sonnet 4.6 aa515d3d89 chore: fix prettier formatting across 28 files
CI format:check was failing. Auto-formatted all files to match
Prettier config.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 09:45:47 +01:00
g-butandClaude Opus 4.6 5c046fd1dc refactor(logging): replace console calls with structured logger
Create lib/logger.ts — lightweight wrapper that outputs plain text in dev
and structured JSON in production. Replace 117 console.log/error/warn
calls across 31 files (27 API routes + 4 lib files) with logger.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:55:28 +01:00
g-butandClaude Opus 4.6 75c9d7bb37 fix(ci): upgrade Node.js 18→22 for pdf-parse DOMMatrix support
pdf-parse v2 depends on @napi-rs/canvas which requires DOMMatrix
(available via process.getBuiltinModule in Node 22+). The build
crashes with "ReferenceError: DOMMatrix is not defined" on Node 18.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:17 +01:00
g-butandClaude Opus 4.6 33c9c835bd fix: apply remaining audit fixes (API standardization, SSOT configs)
Standardize signup route to use jsonSuccess/jsonError helpers, extract
connection status config, clean up StatusBadge/ProviderCard inline maps,
add input validation to knowledge route, fix domain validation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:17 +01:00
g-butandClaude Opus 4.6 dc99135009 test(api): add professional-chat route tests
6 tests covering: validation (missing message/prompt), successful
unauthenticated response, rate limiting, LLM error fallback, and
conversation history threading. All dependencies mocked.

Total: 138 tests passing (6 new)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:16 +01:00
g-butandClaude Opus 4.6 61fe42d15b feat(documents): auto-detect domains during document processing
When a document is processed and has no user-assigned domains, analyze
its text content with the keyword-based domain detector and auto-tag it.
This ensures documents are correctly filtered when professionals search
for relevant context.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:16 +01:00
g-butandClaude Opus 4.6 45d94d515d test(lib): add tests for chat utils, rate limiting, and domain detection
- domain-detector: 10 tests covering all 6 domains, multi-domain, edge cases
- chat-utils: 13 tests for truncateChunks, joinContext, parseResponseWithSuggestions
- rate-limit: 5 tests for Supabase RPC integration + fail-open fallback behavior
- Add collectCoverageFrom config to jest.config.js

Total: 132 tests passing (30 new)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:16 +01:00
g-butandClaude Opus 4.6 b32b30c4cb feat(context): add user context accumulation system
Core differentiator: professionals learn about users over time.

- Add user_context table with vector embeddings (migration 011)
- Add get_relevant_context() SQL function for semantic search
- Create lib/context/ module:
  - store.ts: save and retrieve user context entries
  - extractor.ts: LLM-based fact extraction from conversations
  - domain-detector.ts: keyword-based domain classification
- Integrate into professional-chat route:
  - Retrieve relevant user context and inject into system prompt
  - Async extraction of facts after each conversation turn

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:15 +01:00
g-butandClaude Opus 4.6 82e4623105 feat(rate-limit): replace in-memory rate limiting with Supabase-based
In-memory rate limiting (LRU cache + Map) doesn't work correctly in
serverless — each function instance has its own memory. Replace with
a Supabase PostgreSQL function that atomically checks and increments
per key, shared across all instances.

- Add rate_limits table + check_rate_limit SQL function (migration 010)
- Rewrite lib/rate-limit.ts to call Supabase RPC instead of LRU cache
- Simplify lib/middleware/rate-limit.ts to wrap the new checkRateLimit
- Update all 7 routes using the old LRU-based limiter
- Remove lru-cache and @types/lru-cache dependencies
- Auth routes (5) unchanged — they already use the middleware wrapper

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:15 +01:00
g-butandClaude Opus 4.6 a1c40907b4 refactor(components): split god components into focused modules
Split 3 god pages (1828 lines total) into thin orchestrators (443 lines)
with 5 extracted components:

documents/page.tsx (685→177): Extract DocumentUploadButton,
DocumentListPanel, DocumentChatPanel into components/documents/

try/page.tsx (586→109): Extract TryDocumentsPanel, TryChatPanel
into components/try/

my-data/page.tsx (557→157): Reuse DocumentUploadButton,
DocumentListPanel, DocumentChatPanel — eliminating duplicated
document management code entirely.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:15 +01:00
g-butandClaude Opus 4.6 372fe46261 refactor(chat): extract shared utilities from 3 chat API routes
Create lib/chat/ module with shared utilities:
- embedding.ts: generateEmbeddingWithTimeout (embedding + timeout guard)
- settings.ts: getUserLLMSettings (provider/apiKey/ollamaUrl lookup)
- context.ts: truncateChunks + joinContext (context building)
- llm-errors.ts: handleLLMError (API key fallback, Ollama, AI unavailable)
- parse.ts: parseResponseWithSuggestions (extract >>> suggestions)

Update all 3 chat routes to use shared utilities, removing ~220 lines of
duplicated code. Also fix module-scope getServerEnv() call in llm-client
that caused SSG build failure.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:14 +01:00
g-butandClaude Opus 4.6 26f48352da refactor(deps): remove deprecated @supabase/auth-helpers-nextjs
Replaced imports in lib/api-utils.ts (-> ./supabase-server) and
app/auth/callback/page.tsx (-> @/lib/supabase) with existing local
wrappers. Removed the deprecated package from dependencies.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:14 +01:00
g-butandClaude Opus 4.6 0ae19d22a2 refactor(hooks): extract useLocalStorageFlag hook for dismiss state
Created lib/hooks/useLocalStorage.ts with SSR-safe boolean persistence.
Updated ChatAuthCTA and OnboardingChecklist to use it instead of raw
localStorage calls.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:13 +01:00
g-butandClaude Opus 4.6 8e637e3508 refactor(lib): remove 30 debug console statements from lib/
Removed noise console.info/error from blog.ts (20), knowledge.ts (6),
nlp.ts (2), api/responses.ts (1), platforms/ricardo.ts (1),
platforms/amazon.ts (1). Kept legitimate error boundaries in
llm-client.ts, email/service.ts, and middleware/monitoring.ts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:12 +01:00
g-butandClaude Opus 4.6 c6f00645a2 feat(config): add Zod environment validation with fail-fast
Created lib/config/env.ts as SSOT for all env vars with Zod schemas
(client + server split). Updated supabase.ts, supabase-server.ts, and
llm-client.ts to use getClientEnv()/getServerEnv() instead of raw
process.env access. Missing required vars now fail with clear messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:12 +01:00
g-butandClaude Opus 4.6 7186bdd049 refactor(config): move welcome messages from switch to data config
Added welcomeMessage field to Professional interface and each professional
entry in data/professionals.ts. Removed 6-case switch in ProfessionalDemo.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:12 +01:00
g-butandClaude Opus 4.6 57083ad34f refactor(colors): centralize 8 duplicated color mappings into SSOT
Added 9 new mapping exports to lib/config/colors.ts (button, focus-ring,
checkbox, starter, message, dropzone, progress, context-panel, hero,
template-hover). Removed local accentColorClasses definitions from all
8 consumer components.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:12 +01:00
g-butandClaude Opus 4.6 e1d9b18532 fix(api): fix document query using non-existent 'category' column
The professional-chat route queried .in('category', ...) but the
documents table has 'domains TEXT[]' (added in migration 009), not
'category'. Changed to .overlaps('domains', ...) for correct array
overlap matching. Updated Document interface to use domains[] field.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:11 +01:00
G e5a9646781 chore: add MIT license 2026-02-26 19:29:55 +01:00
G 45f00fd65d chore: update .gitignore with runtime artifact patterns 2026-02-26 19:29:36 +01:00
G cb0266113f chore: remove runtime artifacts from version control 2026-02-26 19:27:38 +01:00
G 38d847d4b9 chore: remove runtime artifacts from version control 2026-02-26 19:27:37 +01:00
G ce0b1d15bf chore: remove runtime artifacts from version control 2026-02-26 19:27:36 +01:00
G ad6c545565 chore: remove runtime artifacts from version control 2026-02-26 19:27:35 +01:00
G 68c527d81a chore: remove runtime artifacts from version control 2026-02-26 19:27:34 +01:00
G 22e2785791 chore: remove runtime artifacts from version control 2026-02-26 19:27:32 +01:00
G 90b57a2826 chore: remove runtime artifacts from version control 2026-02-26 19:27:31 +01:00
G 2e66a99d82 chore: remove runtime artifacts from version control 2026-02-26 19:27:29 +01:00
G 799066c564 chore: remove runtime artifacts from version control 2026-02-26 19:27:28 +01:00
G 9607ae71e4 chore: remove runtime artifacts from version control 2026-02-26 19:27:26 +01:00
G 677d23b891 chore: remove runtime artifacts from version control 2026-02-26 19:27:25 +01:00
G 3b6d8f0dfa chore: remove runtime artifacts from version control 2026-02-26 19:27:22 +01:00
G a635e3137f chore: remove AI work artifact 2026-02-26 19:27:21 +01:00
G 79a52bb5cf chore: remove AI work artifact 2026-02-26 19:27:18 +01:00
G 1fb039ab4e chore: remove AI work artifact 2026-02-26 19:27:16 +01:00
G 58fe9a9fcd chore: remove AI work artifact 2026-02-26 19:27:13 +01:00
g-butandClaude Opus 4.6 2e2563dbb8 Rewrite README with multi-LLM routing and RAG architecture
Surface multi-provider strategy (Ollama/Groq/OpenRouter), 6 domain
professionals, RAG via pgvector with client-side embeddings, 4-layer
prompt injection defense, and custom bot creation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 08:32:21 +01:00
g-but 6cc2196201 fix(api): mark auth stats/settings routes as dynamic 2026-02-17 17:20:49 +01:00
g-butandClaude Opus 4.6 2d5dc85501 refactor: remove dead code, archive historical docs, fix README
- Remove duplicate ApiResponse, apiSuccess, apiError, withErrorHandling,
  requireAuth, ERROR_MESSAGES from lib/api-utils.ts — only verifyUser
  was actually imported anywhere. Response utils SSOT is lib/api/responses.ts
- Archive 14 historical LEX-era design docs to docs/archive/ — docs/
  now has only 9 active reference files (down from 29)
- Remove mock data and placeholder images from Amazon/Ricardo platform
  integrations — functions return [] until real APIs are implemented
- Update platform tests to match actual behavior
- Fix README.md: update backend tech (Groq/OpenRouter), add Supabase
  to prerequisites

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 10:46:04 +01:00
g-butandClaude Opus 4.6 9bf4630fd2 chore: clean up stale docs, fix outdated dates and content
- Archive 10 stale/completed docs to docs/archive/ (MongoDB-era,
  migration plans, stale status snapshots, AGENTS.md.new)
- Rewrite SHARED_CONTEXT.md: remove MongoDB sections, update env vars
  table to Supabase, fix project structure to match reality, fix data
  flow diagrams
- Fix "January 2025" typo → "January 2026" across 6 doc files
- Update governance demo dates from 2023 to 2026
- Fix "launching 2025" → "launching 2026" in techno-capital
- Update bot roadmap timelines and expected launch dates
- Fix demo chat bot status from "coming soon" to "demo available"
- Add missing OPENROUTER_API_KEY to .env.example
- Fix stale path in RALPH.md (src/lib/schemas/ → lib/validations/)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 10:22:39 +01:00
g-butandClaude Opus 4.6 d21cc37bad fix: replace remaining dynamic Tailwind class interpolations
- APIKeyInput: add focusRing field to ProviderColorClasses, replace
  focus:${colors.ring} with static ${colors.focusRing} lookup
- ProfessionalCard: add groupHoverText field to accent color classes,
  replace group-hover:${colors.text} with static ${colors.groupHoverText}
- Zero dynamic Tailwind interpolations remain in the codebase

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 05:39:06 +01:00
g-butandClaude Opus 4.6 be1f76ea9e refactor: fix DRY/SSOT violations and Tailwind build bug
- Fix dynamic Tailwind classes in ProfessionalDemo.tsx that were purged
  at build time by replacing string interpolation with static lookups
- Deduplicate LLM config by importing GROQ/OpenRouter constants from
  API_CONFIG instead of defining them locally in llm-client.ts
- Remove duplicate input type interfaces from types/ that duplicated
  Zod-inferred types in lib/validations/, re-export from SSOT
- Extract shared navigation config (AUTH_NAV_ITEMS) and icon components
  used by both AuthNav and MobileNav into lib/config/navigation.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 23:15:08 +01:00
g-butandClaude Opus 4.5 4b768683f3 fix(test): remove unused ts-expect-error directives
TextEncoder/TextDecoder are globally available in modern Node.js.
Fixes build failure due to strict unused directive check.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 13:08:12 +01:00
g-butandClaude Opus 4.5 59f1f0512e fix(deps): patch fast-xml-parser vulnerability and improve Link usage
Security fixes:
- Add npm override for fast-xml-parser@^5.3.4 to fix RangeError DoS
- Update @aws-sdk/client-ses to 3.980.0
- Reduces vulnerabilities from 25 to 8 (fixed 17 high severity)

Code improvements (prep for future Next.js 15):
- Replace <a> tags with <Link> components for internal navigation
- Create ConsultationFormLoader client wrapper for dynamic imports
- Use direct Analytics import instead of dynamic with ssr:false
- Add eslint-disable for global-error.tsx (intentional <a> usage)

Remaining vulnerabilities (require breaking changes):
- 7 moderate: eslint circular reference stack overflow
- 1 high: Next.js DoS (specific conditions, low practical risk)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 12:53:40 +01:00
g-butandClaude Opus 4.5 24e7caa1cb perf(api): add HTTP caching headers to reduce database load
Add Cache-Control header support to API response utilities:
- NONE: no-store for mutations and sensitive data
- PRIVATE_SHORT: 1 minute for user-specific data
- PRIVATE_MEDIUM: 5 minutes for less frequent user data
- PUBLIC_SHORT: 5 minutes for public data
- PUBLIC_MEDIUM: 1 hour for semi-static data
- IMMUTABLE: 1 day for truly static data

Apply caching to key routes:
- GET /api/settings: private, 1 min cache
- GET /api/health: public, 5 min cache
- GET /api/documents: private, 1 min cache
- GET /api/stats: private, 1 min cache
- GET /api/conversations: private, 1 min cache
- All mutations (POST/PUT/DELETE): no-store
- All errors: no-store (automatic)

Expected impact: 2-3x reduction in database queries for
repeated requests within cache window.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 12:06:43 +01:00
g-butandClaude Opus 4.5 274c3812ed fix(security): add prompt injection protection to all chat APIs
Add comprehensive prompt sanitization to prevent LLM prompt injection:
- Create lib/prompt-sanitizer.ts with detection and filtering
- Detect injection patterns (instruction overrides, role manipulation, jailbreaks)
- Escape delimiter sequences that could break prompt structure
- Wrap user-provided context in XML-like tags with data-not-instructions note
- Apply sanitization to all 4 chat API routes:
  - /api/quick-chat
  - /api/professional-chat
  - /api/demo/chat
  - /api/demo/document-chat

Security measures:
- Length limits on all user inputs
- Injection pattern detection with filtering
- Control character removal
- Clear separation between instructions and user data

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 11:56:08 +01:00
g-butandClaude Opus 4.5 cc632bb57c feat: add document categories and professional chat API
Port features from legacy codebase:
- Add DocumentCategory type with 7 categories (legal, health, research, etc.)
- Add PROFESSIONAL_DOCUMENT_ACCESS mapping for category-based access
- Add CategoryBadge and CategorySelector components
- Add professional-chat API with document context integration
- Add ErrorBoundary component for error handling
- Add professionals layout with metadata
- Add useRateLimitCountdown hook

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 11:14:27 +01:00
g-butandClaude Opus 4.5 50a04ec062 feat(chat): add model indicator, selector, privacy tiers & auth CTA
Add model visibility and switching UI for AI professionals:
- ModelIndicator: shows current model with icon in chat header
- ModelSelector: dropdown to switch models (auth-gated for guests)
- PrivacyTierInfo: expandable Cloud vs Self-Hosted comparison
- ChatAuthCTA: dismissible guest conversion banner

Config files (SSOT):
- privacy-tiers.ts: tier definitions, model display config
- auth-cta.ts: CTA content for guest/authenticated users

Also increases quick-chat maxTokens from 256 to 1024 to prevent
response cutoff.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 10:40:12 +01:00
g-butandClaude Opus 4.5 ea7baec755 refactor(bots): make bots.ts SSOT for footer, menu, and bots page
Reduces files needed to add a new bot from 7-8 to 3-4 by eliminating
hardcoded bot lists in multiple locations:

- Add `display` field to Bot interface for bots list page metadata
- Footer.tsx: Generate AI Assistants links from bots array
- app/bots/page.tsx: Remove 100-line botDetails Record, derive from bot.display
- menuItems.ts: Generate Professionals menu children from bots array

Adding a new bot now automatically updates the footer, navigation menu,
and bots list page without any additional code changes.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 21:08:04 +01:00