* fix(ai): pick chain vendors by id, and make main green again
main has been red since #203 bumped @bitbaum/ai-kit to 1.10, which put
Gemini second in freeChain('BOTSMANN'). vendorChain() indexed [1] for
OpenRouter, so a BYOK OpenRouter user's key would have been sent down the
Gemini link. Look vendors up by id instead (code and both tests).
Also clears the rest of the red verify from the same bump: prettier 3.x
reformat of six files and the new next lint rule on relative
window.location.href assignments (sign-out keeps its full reload).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
* fix(ai): context extraction runs only on the user's own key
Every professional-chat turn fired a second, unasked model call
(extractAndSaveContext, fire-and-forget after the answer) on the shared
free-tier Groq key. Standing rule (2026-09-25): free-tier keys are spent
only when a person deliberately asks. Extraction now requires the user's
own key and uses their provider; without one it returns before any call.
Adds tests/__tests__/no-free-background-ai.test.ts: walks the import graph
from the timer route (/api/rebuild, appcron-botsmann-rebuild), /api/warmup
and /api/health and fails if any reaches a model client. Proven by
mutation: importing lib/nlp into /api/rebuild fails it, and dropping the
own-key guard fails the three new extractor cases.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
---------
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(rate-limit): one limiter from limitkit, keyed on the proxy's hop
Two hand-rolled limiters lived side by side — lib/rate-limit.ts and
lib/middleware/rate-limit.ts — each with its own window maths, its own
header names and its own idea of who the caller is. Both are gone; the
decision now comes from limitkit (fleet/SHARED.md), and what stays here
is the one table of app budgets in lib/rate-limit.ts. A route names a
bucket; it does not get to invent a number.
The reason this matters beyond tidiness: both copies keyed the limit on
the FIRST hop of X-Forwarded-For. That hop is written by the client, so
any caller could mint a fresh budget per request by adding a header —
the limiter looked like it worked and enforced nothing. limitkit counts
from the right, i.e. the hop our own proxy wrote. A test now pins it:
a forged first hop must not mint a fresh bucket.
Also removed the Supabase check_rate_limit RPC path, which failed OPEN
on every error — the limiter switched itself off whenever the database
hiccupped. And 429s now carry Retry-After and X-RateLimit-* headers plus
a retryAfter field, which is what the auth forms count down.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(icons): each icon body written once
Icons.tsx repeated the same 24-box outline SVG wrapper for every icon —
a 121-line self-clone. One `Outline` frame and one `icon(paths, ...)`
builder replace it; an icon is now its path data and nothing else.
Every export and every path string is byte-identical to before, so the
rendered output does not move.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(create): one QuickCreateFlow behind /create and /personal
The two pages held the same three-step flow twice — 192 cloned lines of
state machine, header, progress indicator and step switch. They differ
only in the copy around the template picker, so that is what the pages
now pass in: /personal supplies its title block and its link out to the
professionals, /create supplies neither.
Both renders are unchanged, including that /personal's intro and outro
only appear on the picker step.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(auth): one shell, one field, one submit button for the auth screens
signup, signin, forgot-password and verify-email each carried their own
copy of the page frame, the error line, the labelled input and the
submit button — six clone pairs with signup in every one. They now share
AuthShell / AuthAlert / AuthField / AuthSubmitButton, and the per-form
error-plus-countdown state lives once in useAuthError.
One real fix falls out of it: isRateLimitError compared the error code
against 'RATE_LIMITED', but the API has always sent 'RATE_LIMIT'. The
rate-limit countdown therefore never showed. It does now.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* chore(lint): console.info is not logging, and every disable says why
`no-console` allowed `info`, so debug lines shipped as operator output:
the blog route narrated every render to the server log at info level.
Those lines now go through lib/logger (the single logger) at the level
they actually are, and the allowance is gone — warn and error only. The
21 remaining console.log calls are all in scripts/test-db-connection.ts,
where printing to the terminal is the point.
The eslint-disable count drops 16 -> 13. Comments.tsx no longer needs one
(useSyncExternalStore is the supported way to ask "are we on the client"),
and lib/supabase.ts no longer needs its `any` — the SSG mock casts once at
the return instead. The 13 that remain each name their reason: external
avatar URLs that next/image would need a host allowlist for, and effects
that seed state from an external store.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Found by driving the Lex demo in production: the chat answered "I'm sorry,
I encountered an error processing your request." Behind it, every AI feature
on the site is down and has been invisible.
The box has an invalid Groq key, no other provider key, and no Ollama:
Groq API error: 401 (model openai/gpt-oss-120b) {"code":"invalid_api_key"}
Groq API error: 401 (model openai/gpt-oss-20b) {"code":"invalid_api_key"}
Every endpoint answered HTTP 200 anyway:
/api/demo/chat {"success":true,"data":{"response":""}}
/api/quick-chat {"success":true,"data":{"response":"I'm having a moment..."}}
/api/professional-chat same
/api/health {"success":true,"data":{"status":"healthy"}}
Green everywhere, product dead. demo/chat was the worst of the three: its
catch returns `content: context`, and a bot demo has no context, so a failed
generation became a successful empty string.
- demo/chat throws LLMUnavailableError when there is nothing to fall back
on; the knowledge-base demo still serves its retrieved passage
- quick-chat and professional-chat return 503 LLM_UNAVAILABLE instead of
apologising with 200
- lib/llm-health.ts records what generations actually did; /api/health
reports it and returns 503 once the chain is consistently failing, so
"healthy" stops meaning "the database answered"
tests/__tests__/api/professional-chat.test.ts asserted the bug -- 200, the
word "moment", provider 'fallback'. It now asserts 503 LLM_UNAVAILABLE. A
test that pins broken behaviour is worse than no test.
Never-twice: tests/__tests__/lib/llm-health.test.ts covers the tracker's
state machine and asserts at source level that no chat route answers an LLM
failure with success, and that health consults the LLM chain.
This makes the outage visible. It does NOT fix it -- that needs a valid
GROQ_API_KEY (or OPENROUTER_API_KEY) in /opt/botsmann/shared/.env on the box.
Until then these endpoints will correctly return 503.
verify: format, lint, typecheck, 268 tests, build -- all green.
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG
Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
app/api/demo/chat is public and unauthenticated, and
app/api/custom-bots/[id]/chat lets anonymous callers chat with public
bots billed to the bot OWNER's API key. Neither had a limit. Nothing
failed, because nothing was checking.
Both are closed. The custom-bot limit is scoped per bot id so one hot
bot cannot drain another's budget.
The reason they drifted is that each route hand-rolled the same block:
read the IP, call checkRateLimit with inline magic numbers, return a
429 written slightly differently each time. So the budgets now live in
one place (RATE_LIMITS) behind one helper (enforceRateLimit), and the
seven existing copies were migrated onto it -- removing three different
429 response shapes and a hand-rolled copy of getClientIp.
Never-twice: tests/__tests__/api/rate-limit-coverage.test.ts reads every
route file and fails if one imports the LLM client without enforcing a
limit, or calls checkRateLimit directly with its own numbers. Verified
by mutation -- removing a limit makes it fail and name the file.
verify: format, lint, typecheck, 240 tests, build -- all green.
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG
Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Botsmann now runs self-hosted on the Hetzner box "bitbaum" behind Caddy
(botsmann.orangecat.ch); Vercel is fully decommissioned.
- CI: rename the "Deploy to Vercel" workflow to a vendor-neutral CI workflow
(build/lint/test only). Actual deploy runs from .husky/pre-push → Hetzner
deploy script. Remove vercel.json and the Vercel-only deploy-monitor.sh.
- Docs: rewrite current-setup deploy/hosting text in .claude/CLAUDE.md,
README badge, docs/COMMANDS.md and docs/SHARED_CONTEXT.md to the self-hosted
box. Repoint the dead botsmann.vercel.app URL → botsmann.orangecat.ch.
- Code: neutralize "(Vercel)" route-segment comments; reword the warmup cron
comment; update the demo page tech-stack line to self-hosted.
- Keep: secret-scan guardrail (VERCEL_OIDC_TOKEN) and `env -u VERCEL` in the
husky hooks, the educational hosting-comparison page, historical docs/archive,
and executive-docs business/finance planning material (see PR body).
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Create searchUserDocuments() that encapsulates the common pattern:
embed query → match_documents RPC → filter → build context + sources.
Used by both chat/route.ts and professional-chat/route.ts, removing
~50 duplicated lines across the two routes.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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>
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>
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>
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>
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>
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>