70 Commits
Author SHA1 Message Date
CatoandClaude Opus 5.5 9dde8fbee9 feat(forms): prose fields on chatkit DictationField, with a working microphone (#330)
* wip: prose fields on chatkit DictationField (awaits chatkit 0.45)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuMRAXYWNkfowAXVfi

* feat(forms): prose fields on chatkit DictationField, with a working microphone

- Bump @bitbaum/chatkit to ^0.45.0.
- One app wrapper, components/forms/TextBox, around DictationField. Used by
  the bot builder (name, description, knowledge topic and content, system
  prompt), the custom-bot edit page (name, description, system prompt,
  greeting), the contact message, the demo intake questions, quick-create
  (name, relationship, memories) and the consultation form's
  react-hook-form message field ({...register('message')}).
- app/api/transcribe: dictation server leg on ai-kit's speechChain and
  transcribe(), rate limited, recordings and transcripts neither stored nor
  logged. Every field and every in-page chat points voice at it, so the
  microphone works where the browser has no recogniser of its own.
- Permissions-Policy allowed no microphone at all (microphone=()), which
  blocked every mic on the site; it now allows the site itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuMRAXYWNkfowAXVfi

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-19 14:23:42 +01:00
CatoandClaude Opus 5.5 ebe51fa38e feat(auth): every way in on AccountKit's own screens (#289)
* feat(auth): every way in on AccountKit's own screens

Botsmann signed people in against OrangeCat's GoTrue (auth.users). It now
runs on AccountKit (@bitbaum/accountkit 0.23) with AccountKit's own forms:
/auth/signin offers email and password, an emailed sign-in link, a
passkey, recovery through the mailed link and the second factor;
/auth/signup is sign-up; /account carries the account panel ("Sign-in and
security" in the account menu). "Continue with OrangeCat" and the shared
sign-in show when their clients are set, the link and recovery when mail
is. The GoTrue routes (/api/auth/signin, signup, forgot-password,
resend-verification, profile) and pages (callback, forgot-password,
reset-password, verify-email) and the cookie-session client are gone.

AccountKit's tables live in a host accounts database (drizzle/, loki
accounts-db.conf); the data stays in the botsmann supabase schema, which
every route already read with the service-role client. verifyUser now reads
AccountKit's session; /api/user/profile moves onto it too. New accounts get
uuid ids, and migration 013 drops the person columns' keys to auth.users,
which a new person's id is not in. Nothing is deleted. The profile editor
writes AccountKit's name and image.

Existing people keep their rows: scripts/db/accountkit-people.sql lists
everyone who owns rows with their OrangeCat actor id, and
scripts/db/accountkit-import.sql gives each an account under the same id,
linked to OrangeCat by that actor id, never by address (loki
accountkit-supabase.yml rehearses it rolled back, then imports).

Pages were served with public, max-age=3600 to every browser, account pages
included: after sign-out the browser showed its cached /account. /account
and /auth/* are now private, no-store. The account menu's trigger has a name.

tests/__tests__/accounts runs the ways in and the import on the committed
migration; browser-smoke.yml's account job rehearses the import and runs
the browser journey against the production build with AccountKit's real
mail caught by a sink.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* fix(auth): send a signed-out visitor to sign in with the router

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci(auth): the shared sign-in's button is matched by how it starts

AccountKit 0.24 names only the providers Morulia publishes, so the label
changes with Morulia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci(auth): expect the shared sign-in only once Morulia publishes a provider

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci: run the checks on the journey change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-02 23:27:16 +01:00
Cato 6e2e2a0069 feat(auth): one password rule from accountkit (non-empty, up to 128); drop local minimum and hint placeholders (#244) 2026-10-28 03:52:50 +01:00
Cato cd15ab47e9 fix(contact): save real requests and add browser rollout journeys (#239)
* fix(contact): require saved requests and add real browser rollout journeys

* test(browser): preserve project viewport in no-script journey

* test(browser): use published long article for contents navigation

* test(browser): exercise production runtime and retain failure diagnostics

* test(browser): target the contact alert and real standalone entrypoint
2026-10-27 23:26:11 +01:00
Cato f0903ed178 feat: adopt shared visual AI answers (#235) 2026-10-21 12:59:28 +02:00
CatoandClaude Opus 5.5 4fd7cf0195 fix(settings): API keys are sealed at rest and checked before they are saved (#208)
* fix(settings): API keys are sealed at rest and checked before they are saved

Readers' Groq/OpenRouter keys sat in user_settings as plaintext, and GET
/api/settings returned the whole row — keys included — to the browser.

- Keys are sealed with @bitbaum/ai-kit/seal (BYOK_SEAL_SECRET); GET returns
  only a hint (…abcd). Without the secret nothing new is stored (503).
- Legacy plaintext rows keep working and are sealed in place on first read.
- Save checks a new key with probeByokKey first; a key the provider refuses is
  never stored, and the reason is the provider's own words.
- An empty key field keeps the saved key (removing is explicit); the old PUT
  wrote key || null, which would have wiped keys once they stopped being sent.
- The key check now runs on its own after pasting, and actually passes:
  both pages read the jsonSuccess payload at the top level, so settings never
  loaded and every key — good or bad — was reported invalid.
- OpenRouter is checked on /key: its /models is public and 200s a dead key.

ai-kit ^1.18.0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(settings): type the seal-secret lookup for plain env objects

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 12:35:30 -07:00
CatoandClaude Opus 5.5 ce98b0cc24 fix(ai): context extraction only on the user's own key; vendors by id (main green again) (#205)
* 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>
2026-09-25 00:44:17 -07:00
CatoandClaude Opus 5 376b94f89d refactor: one rate limiter, one auth shell, one create flow, one icon frame (#198)
* 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>
2026-09-15 01:24:12 -07:00
CatoandClaude Opus 5 d050d1589c feat(health): /api/health/ai — make the 2026-08-28 outage observable BEFORE a user hits it (#184)
On 2026-08-28 /api/health reported "healthy" while every AI feature on
this site was failing on an invalid Groq key. Carrying `llm` in that body
fixed the REPORTING. It did not make the state observable before a user
hit it, because nothing calls a provider until somebody uses the bot — so
straight after a deploy the field reads "unknown", and unknown is what it
stays.

  GET /api/health/ai            free. What the last real call did.
  GET /api/health/ai?probe=1    a real call. 200 or 503. Needs the secret.

Opposite contract to /api/health on purpose: that route is LIVENESS and
must stay 200 while the LLM is down, because restarting does not fix an
expired key and failing on it would get a healthy process killed. This
one is the inverse, so an uptime monitor can page on a real AI outage
without paging on every deploy.

It probes THIS app's chain: `ask` (ai-kit 0.15.0) calls
generateWithBestProvider, the same function the chat routes use. A probe
built from its own provider list would test a path nothing else takes and
would drift from this one the first time the chain changed.

The secret is a GETTER — the handler is built once and reused, so a
captured string would be whatever the environment held on the first
request: un-rotatable without a restart, and untestable.

TWO THINGS THE TESTS TAUGHT ME, both about this app rather than the
probe:

  - generateWithBestProvider goes through getServerEnv(), which validates
    the WHOLE server env and throws on the first missing var. A probe
    test that sets only the AI keys fails on SUPABASE_SERVICE_ROLE_KEY,
    nowhere near the chain.
  - Ollama is tried first and its availability is a LIVE PING, so a fetch
    mock that answers every URL makes a local runtime appear to exist and
    win the chain. The mock now refuses :11434, which is prod's real
    shape — and the "which vendor served it" assertion looks at every
    call rather than calls[0], because calls[0] is that ping.

verify green — 301 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 14:56:46 +00:00
652b14a61f fix(health): stop gating HTTP status on AI vendor health in strict mode (#173)
?strict=1 turned an LLM outage into an HTTP 503 for the health endpoint,
which a monitoring/orchestration system reading that status would treat
as a reason to restart the process -- but a dead API key or exhausted
free-tier budget can't be fixed by a restart, so that's a pointless
restart loop for a problem restarting can't solve. Liveness now always
answers 200 once the database is reachable; LLM state stays in the body
as an informational field, unconditionally. The strict param existed
only to drive this gating, so it's removed rather than left as dead
branching.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 11:24:10 +00:00
8582b92f90 refactor(deps): Tailwind 4 (CSS-first) + Zod 4 + ESLint 10 + types/node 26 + ai-kit 0.6.2 (#168)
Tailwind 3.4 -> 4.3:
- tailwind.config.js DELETED; tokens now live in an @theme inline block in
  app/globals.css (semantic names unchanged: action, paper, edge, ink...)
- postcss.config.js -> @tailwindcss/postcss; autoprefixer dropped (built in)
- @tailwind directives -> @import 'tailwindcss'; forms/typography via @plugin
- daisyui removed (no daisyui class used anywhere)
- next/font vars renamed --font-inter/--font-fraunces to break the circular
  var() the old --font-sans binding would create inside @theme
- v4 deleted *-opacity-* utilities: every bg/text/ring-opacity-N rewritten to
  slash syntax (bg-action/90, ring-black/5, ...); dynamic accent tint gets a
  literal class map in lib/config/colors.ts so the scanner sees each class
- dead v3-era aspect-w/h custom utilities removed (unused; v4 has aspect-*)

Zod 3.24 -> 4.5:
- .errors -> .issues everywhere
- z.string().uuid( -> .guid( (v4 uuid() is RFC-variant-strict; DB ids aren't)
- z.record(z.unknown()) -> z.record(z.string(), z.unknown())
- object .default({}) -> .prefault({}) (v4 default takes the full output value)

ESLint 9 -> 10: eslint-plugin-react's version:'detect' calls the removed
context.getFilename; pin settings.react.version='19' AFTER the next configs.

Verify (format+lint+typecheck+selfhost+test+build) green: 272 tests pass.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 12:45:49 +00:00
222a57c781 fix(health): liveness must not fail on something a restart cannot fix (#153)
#151 made /api/health return 503 whenever the LLM chain was down. That is
right for alerting and wrong for liveness: restarting botsmann does not
repair an expired Groq key, so the only effect of failing there is to get a
healthy process killed, and to fail deploy gates on a problem no deploy
caused. That is the failure class that teaches people to bypass the gate.

  GET /api/health            liveness -- 200 while the process serves and the
                             database answers. The body still carries
                             status: healthy | degraded | down and the full
                             llm block, so the outage stays visible.
  GET /api/health?strict=1   readiness -- 503 once the chain is consistently
                             failing. Point alerting here.

'unknown' (nothing has exercised the chain since this process started) is not
evidence of a problem, so it reports healthy rather than degraded.

The deploy gate was never at risk -- selfhost-deploy.yml curls the homepage,
not this endpoint -- but the shape was wrong regardless, and the guidance in
CLAUDE.md does point a post-deploy check at /api/health.

The guard now asserts the 503-on-LLM path stays behind `strict`, so this
cannot quietly become unconditional again.

verify: format, lint, typecheck, 269 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>
2026-08-28 12:10:46 +00:00
b5b2f967fe fix(ai): a total LLM outage was reporting itself as success (#151)
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>
2026-08-28 11:57:09 +00:00
9284c00dc7 fix(api): two LLM endpoints spent money with no rate limit (#139)
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>
2026-08-28 08:09:06 +02:00
GandClaude Opus 4.8 26b042cd86 chore(infra): remove Vercel references — self-hosted now (#120)
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>
2026-07-28 09:23:49 +02:00
Mao NakamotoandClaude Opus 4.8 354b432326 chore(deps): upgrade Next.js 14 → 15.5.21 (clears 15 Dependabot alerts)
Bumps next + eslint-config-next 14.2.35 → 15.5.21. React stays on 18
(Next 15 supports React ^18.2.0), so no forced React 19 migration.

Clears all 15 open next-related Dependabot alerts (4 high) — the highest
patched version required is 15.5.16, so jumping to Next 16 would add
breakage (React 19, Turbopack default) for zero additional security gain.

Next 15 breaking-change migration:
- Async request APIs: params/searchParams awaited in the 6 dynamic pages
  that consume them as props; cookies() is now async, so
  createRouteHandlerClient() became async (9 call sites awaited).
- next.config: serverComponentsExternalPackages → top-level
  serverExternalPackages (renamed/destabilized in Next 15).
- typedRoutes tightening: object href {pathname, hash} is no longer
  accepted → string href "/path#hash" (4 governance pages).
- eslint: ignore the Next-generated next-env.d.ts (Next 15 adds a
  triple-slash routes.d.ts reference that trips no-triple-slash-reference).

Verified: `next build` green — compiles, type-checks, lints, and
prerenders all 81 pages. Client components using the useParams()
hook are unaffected and left untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 00:25:12 +02:00
g-butandClaude Opus 4.6 318d0f7a65 refactor(chat): extract shared document search into lib/chat/search.ts
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>
2026-03-03 10:04:16 +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 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 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 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 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 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-but 6cc2196201 fix(api): mark auth stats/settings routes as dynamic 2026-02-17 17:20:49 +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.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 d10360c231 refactor: code quality improvements (DRY, SSOT, inline styles)
- Remove duplicate MAX_FILE_SIZE constant, use VALIDATION.MAX_FILE_SIZE (SSOT)
- Refactor CustomBotPage sendMessage logic to eliminate code duplication (DRY)
- Convert inline animation-delay styles to Tailwind arbitrary values
- Add development-only check to ErrorBoundary console.error
- Remove deprecated MAX_FILE_SIZE export from types/document.ts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 01:06:06 +01:00
g-butandClaude Opus 4.5 6c25dc8dfe refactor: comprehensive code quality improvements (DRY, SSOT, SoC)
## Broken Links Fixed
- Fix /projects/governance/build link to /contact in HeroSection.tsx

## Console Statements Removed (production code)
- Remove console.log/error from client components
- Replace with silent error handling or UI feedback
- Files: documents/page.tsx, try/page.tsx, settings/page.tsx,
  ConversationList.tsx, ProfessionalDemo.tsx, and more

## Inline Styles Converted to Tailwind
- Replace animation-delay inline styles with Tailwind arbitrary values
- Files: DemoMessage.tsx, DemoChat.tsx, ProfessionalDemo.tsx,
  QuickChat.tsx, demo/page.tsx, HeroSection.tsx

## Governance Types Consolidated (SSOT)
- Create app/projects/governance/types.ts as single source of truth
- Create app/projects/governance/utils.ts for formatting functions
- Remove duplicate EnhancedTransaction from TransactionWithTraceability.tsx
- Update component type files to re-export from SSOT

## Colors Config Extended
- Extend COLOR_CLASSES to support all 16 accent colors
- Fix type mismatch in custom bot pages

## Magic Numbers Extracted
- Add formatBytes utility to lib/format.ts (DRY)
- Add DEMO_MAX_FILE_SIZE to VALIDATION constants
- Update try/page.tsx to use centralized constants

## Minor Fixes
- Fix unused variable warning in CollaborationForm.tsx

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 00:24:27 +01:00
g-butandClaude Opus 4.5 ff84bdedd5 feat(llm): add multi-provider support with Ollama priority
- Add auto-detection of best available LLM provider
- Priority: Ollama (local) > Groq (cloud) > OpenRouter (paid)
- Add isOllamaAvailable() check with 2s timeout
- Add generateWithBestProvider() for automatic provider selection
- Add 60s timeout to Ollama requests for model loading
- Update demo chat API to use unified LLM client
- Provider info now shown in API responses

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 16:41:30 +01:00
g-butandClaude Opus 4.5 1c7abeebac docs(claude): add global standards reference and update date
- Add @~/.claude/CLAUDE.md import for global engineering standards
- Update Last Updated date to 2026-01-23

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:22:36 +01:00
g-butandClaude Opus 4.5 4929569807 chore: Remove obsolete pre-launch waitlist code
The waitlist feature was from the pre-launch phase when collecting
early signups. Now that Botsmann is live, this code is no longer needed.

Removed:
- app/api/waitlist/route.ts
- lib/models/waitlist.ts
- lib/schemas/waitlist.ts
- supabase/migrations/010_waitlist.sql (was just created in error)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 11:32:53 +01:00
g-butandClaude Opus 4.5 842abc3590 feat: Migrate waitlist to Supabase and add error boundaries
- Replace file-based JSON storage with Supabase for waitlist API
- Add SQL migration for waitlist table (010_waitlist.sql)
- Add error.tsx for segment-level error handling
- Add global-error.tsx for root-level error handling
- Add not-found.tsx for 404 page
- Add reusable ErrorBoundary component for client components
- Remove unused data/waitlist.json

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 11:01:43 +01:00
g-butandClaude Opus 4.5 842673d2ba fix: migrate from deprecated @supabase/auth-helpers-nextjs to @supabase/ssr
- Replace deprecated auth helpers with @supabase/ssr package
- Split supabase utilities into client (supabase.ts) and server (supabase-server.ts) files
- Add SSG-safe mock client to prevent build errors during static generation
- Wrap auth callback page in Suspense boundary for Next.js 14 compatibility
- Add missing route constants (PROFESSIONALS, MY_DATA, ENTERPRISE)
- Fix email config to use fallback defaults during build
- Update waitlist model to use lazy-loaded service client
- Add explicit type annotations to auth context hooks
- Install pdf-parse dependency for document processing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 09:52:46 +01:00
g-butandClaude Opus 4.5 beae8512a7 feat: add user-centric architecture with profiles and domain tagging
Implements user-centric data model where users are the constant and
professionals are lenses into their data. Follows DRY, SSOT, and SoC principles.

Database changes (migration 009):
- Add user_profiles table with RLS policies
- Add domains column to documents table (TEXT[])
- Add professional_slug column to conversations table
- Add triggers for auto-updating user stats
- Add ensure_user_profile() helper function

New files:
- lib/domains.ts: SSOT for all domain definitions
- lib/validations/domain.ts: Zod schemas for domain validation
- lib/validations/user-profile.ts: User profile validation schemas
- app/api/user/profile/route.ts: GET/PATCH user profile API
- app/api/documents/[id]/route.ts: GET/PATCH document API

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-22 15:10:53 +01:00
g-butandClaude Opus 4.5 a93e462e4f feat: improve UX with skip option, PDF support, and better CTAs
- Add "Skip and chat directly" button in DemoIntake to reduce friction
- Create /api/demo/parse-pdf endpoint for unauthenticated PDF parsing
- Add PDF upload support to /try page
- Change homepage CTA from "Meet Your Professionals" to "Try Now - Free"
- Add typing indicator with animated bouncing dots in DemoChat
- Fix pdf-parse v2 import (use named export and class API)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 23:41:39 +01:00
g-butandClaude Opus 4.5 84298dce51 feat: add missing platform pages and demo components
- Add /api/quick-chat endpoint for professional chat demos
- Add /create page for building custom bots
- Add /enterprise page for B2B landing
- Add /my-data page for user document management
- Add /personal page for memorial/companion bots
- Add demo components (DemoSection, DemoChat, DemoIntake, etc.)
- Add shared components (HowItWorks, PrivacySection, EnterpriseSection)
- Add bot templates and demo configurations

These files enable the professional demo chats and the
full platform experience with custom bot creation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 14:35:25 +01:00
g-butandClaude Opus 4.5 cd50a7e3bd feat: add public document chat demo at /try
- Create /try page for public document chat without login
- Upload TXT/MD files directly to browser memory
- Chat with documents using Groq API (no auth required)
- Documents stay client-side for privacy
- Rate limited to prevent abuse

This allows visitors to try the document chat feature immediately
without creating an account.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 13:33:04 +01:00
g-butandClaude Opus 4.5 7c5640ed34 feat(auth): add rate limiting, email verification, password reset, and user profile
- Add rate limiting middleware with configurable limits per route type
- Create rate-limited API routes for signin, signup, forgot-password, resend-verification
- Implement password reset flow with forgot-password and reset-password pages
- Add email verification with callback handler and verify-email page
- Create EmailVerificationBanner component for unverified users
- Add user profile editing (display name, avatar URL) to settings page
- Update auth context with profile functions and rate limit error helpers
- Enhance UserAvatar component to support avatar URLs
- Update AuthNav to show display name and avatar
- Add Zod schemas for all auth forms (SSOT for validation)
- Fix duplicate 'dynamic' variable conflict in app/page.tsx

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 22:10:26 +01:00
g-butandClaude Sonnet 4.5 9aa417e273 refactor: clean up API routes and components, add shared utilities
Refactored multiple API routes and components to improve code organization and reduce duplication:
- Simplified API route implementations across chat, documents, consultations, and other endpoints
- Reorganized navigation components for better maintainability
- Added shared utility functions and hooks
- Created reusable Avatar and Logo components
- Added validation schemas and API utilities
- Improved type definitions and constants management

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-16 11:04:19 +01:00
g-but 8645f5bec0 feat: add warmup endpoint to pre-load embedding model
- Add /api/warmup endpoint that loads the embedding model
- Add cron job every 5 minutes to keep function warm
- This addresses cold start timeouts on Vercel
2026-01-15 04:24:49 +01:00
g-but e648f4cca7 feat: add extended timeouts for embedding routes and improve error handling
- Add maxDuration config for chat, search, and process routes
- Add timeout wrapper for embedding generation with clear error message
- Add detailed logging throughout chat API for debugging
2026-01-15 04:20:51 +01:00
g-but 676ed7ef3e Add detailed logging to chat API for debugging 503 errors 2026-01-15 04:12:24 +01:00
g-butandClaude Opus 4.5 f392e4b551 fix(chat): user-friendly error messages
- Remove technical API key messages from error responses
- Show "AI service temporarily unavailable" instead of asking users to get API keys
- Simplify context-only fallback message
- Better error logging for debugging

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 01:23:38 +01:00
g-butandClaude Opus 4.5 7aadd04f29 feat(chat): add context-only fallback when LLM API key is missing
When no Groq/OpenAI API key is configured, the chat now returns the
retrieved document context instead of just an error. This allows users
to see that the RAG retrieval is working even before configuring an
LLM provider.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 13:08:19 +01:00
g-butandClaude Opus 4.5 403c9bf5a7 Add Phase 3: Document upload and RAG chat
- Add Transformers.js for local embeddings generation
- Create document upload API with Supabase Storage
- Create document processing pipeline (parse, chunk, embed)
- Create semantic search API using pgvector
- Create RAG chat API combining search + LLM
- Add documents page UI with upload, process, and chat
- Add database migration for document status columns
- Configure Next.js to externalize ONNX packages

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 12:39:43 +01:00
g-butandClaude Opus 4.5 fbf436fd23 Add user authentication and model selection (Phase 2)
- Add Supabase Auth integration with AuthProvider
- Create sign in/sign up pages at /auth/signin and /auth/signup
- Create settings page at /settings with model selection
- Add multi-provider LLM client (Groq/OpenAI/Ollama)
- Create settings API for persisting user preferences
- Add Providers component for client-side context

Users can now:
- Create accounts and sign in
- Choose their preferred LLM provider
- Bring their own API keys (BYOK)
- Configure local Ollama instances

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 12:10:53 +01:00