49 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 9d5c25a26f feat(chat): run every in-page chat on chatkit's thread and composer (#328)
Seven hand-built chats (/demo, the professional demos, quick-create, /try,
/my-data documents, custom bots and the guided demo) now share one
EmbeddedChat panel: chatkit's ChatThread and Composer with the microphone,
Copy/Listen, Stop, Retry on a failed turn, starters and suggested replies.
Each surface keeps its own prompt, route and persistence through a small
useChatTurns hook.

Also fixes /demo and the /my-data document chat reading the answer from the
wrong level of the jsonSuccess envelope, which showed empty answers.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 18:48:44 +01:00
CatoandClaude Opus 5.5 6dcae92a78 fix(auth): a deleted account takes its documents, bots and conversations (#292)
* fix(auth): a deleted account takes its documents, bots and conversations

When people were GoTrue users, deleting the auth.users row cascaded through
every botsmann table. Since accounts are AccountKit's (#289), deleting an
account in the account panel removed the account and left the person's
documents, chunks, bots, conversations, context, settings and profile
behind, under an id nobody holds. onAccountDeleted now removes them, and
the person's uploaded files in the documents bucket.

A test reads the migrations and fails when a table that referenced
auth.users is missing from PERSON_ROWS.

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

* ci(auth): a navigation sent on after landing is not a failed journey

The settings page can send a just-signed-in browser on once more while its
session loads; Playwright reports the first navigation as aborted. The
journey now waits for the page to arrive, however it gets there.

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

* fix(auth): ask the server before sending a signed-in visitor to sign in

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:51:09 +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
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 Fable 5.1 bade0a1b8e chore: rename FleetCrown to Loki (#197)
The product was renamed on 2026-09-14: bitbaum/loki, loki.orangecat.ch,
LOKI_* env keys, loki-* units. This repo referenced the old name in
15 files changed, 29 insertions(+), 29 deletions(-).
Email addresses at the old sending domain stay until the new domain is
verified in Resend.


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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:23:24 -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
CatoandClaude Opus 5 a6906851d5 refactor(content): one markdown pipeline — bip-kit typed blocks replace MDX and two GitHub content repos (#183)
The blog and the Knowledge Center each fetched their markdown from a
SEPARATE GitHub repository at request time (g-but/botsmann-blog-content,
g-but/botsmann-knowledge-content) and rendered it through next-mdx-remote
with a hand-rolled component map per surface. Two maps for one markdown
vocabulary, already drifted: the blog slugged headings with rehype-slug, the
guides with a different inline regex; the guides highlighted code, the blog
did not; each had its own Callout. The content itself lived where nobody
reviewed it, behind a GitHub handle rename that now answers only via a 301.

Both surfaces now read content/*.md from this repo and render through
bip-kit's typed-block parser and reference renderer:

- content/blog/*.md (5 posts) and content/knowledge/**/*.md (10 guides) are
  vendered verbatim from the two content repos — word-level parity verified
  across all 15 files, zero words lost. Post images moved to public/blog/.
- The three app/blog/<slug>/page.mdx files came along as drafts. They were
  never routes: `page.mdx` only serves as a page when pageExtensions includes
  mdx, and this app never configured that, so all three were dead files. They
  are committed with `published: false` rather than deleted.
- lib/longform/ is the one pipeline both routes call: a fence-aware
  normalizer (`# ` → `## `, `*`/`+` bullets → `-`, nested items flattened —
  the guides carry 74 indented items and ~130 shell-comment `#` lines inside
  fences that a naive normalizer would have corrupted), then parse → blocks +
  TOC + reading time.
- setHighlighterLoader(() => import('shiki')) is registered at module scope.
  This app builds `output: standalone`, where bip-kit's zero-config shiki
  import is invisible to Next's file tracer — without the explicit literal,
  production ships unhighlighted while dev looks right.
- The TOC is derived from the same parse that renders the page, so a TOC
  anchor can no longer point at a heading id built by a different slug rule.
  types/knowledge.ts loses TableOfContentsItem accordingly.

Retired: next-mdx-remote, remark-gfm, rehype-slug, rehype-autolink-headings,
gray-matter (deps), components/blog/{Server,Client}MDXContent + MDXComponents,
components/knowledge/{Callout,CodeBlock,TableOfContents}. next.config drops
the raw.githubusercontent image pattern and the GitHub hosts from CSP
connect-src, and points frame-src at the privacy video players bip-kit uses.

Article typography now flows from the token SSOT: lib/longform/longform.css
maps globals.css onto bip-kit's --bp-* contract, replacing ~40 hardcoded
Tailwind greys. The mapping covers every --bp-* colour and pins the article
light, because Botsmann has no dark theme anywhere (zero `dark:` utilities,
no theme provider, light-only chrome) — letting bip-kit's dark defaults
through would put a dark article inside a white page. When the site grows a
dark tier, this file follows it by changing values in globals.css only.

tests/__tests__/lib/longform-content.test.ts walks every content file through
the real pipeline: committed content is bip-kit's trust boundary and a
malformed chart/stats fence throws at parse time, which without a test would
surface as a 500 on the live page.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 14:24:40 +00:00
CatoandClaude Opus 5 b51a7635f7 refactor(llm): complete() owns the request — and a test asserted the bug (#181)
This file already walked ai-kit's chain but kept its own fetch, so the
CHAIN came from the package and the REQUEST did not. That is where the
remaining defects lived, and they are the fleet's most common ones
(census 2026-09-06: 9 of 12 hand-rolled clients share them):

  - `data.choices[0]?.message?.content || ''` handed an EMPTY 200 to the
    user as the bot's reply, and the chain stopped there, satisfied. A
    reasoning model that spends its budget thinking returns exactly that.
  - a 429 became `throw new Error('Groq API error: ' + status)`: the body
    was read, logged and discarded. Capacity, request-too-large and daily
    quota share that status code and want opposite responses — retry
    shortly, send less, or come back tomorrow.
  - neither call had a DEADLINE. A vendor that accepted the connection
    and never answered held the chat open indefinitely, and the fallback
    beneath it was never reached.

Also removes the last decision this file was still making: the `attempt`
callback branched on `provider.id` to choose a key. Keys now resolve
through a synthetic env, which is the seam complete() reads, so a BYOK
caller's key and the server's own take one path instead of two. The two
per-vendor call functions and both model loops are gone (-134 lines).

Attribution is preserved deliberately. The OpenRouter call sends
HTTP-Referer and X-Title, which OpenRouter ranks apps by; complete() had
no way to send them, so ai-kit grew `extraHeaders` (0.10.0) rather than
this adoption quietly dropping Botsmann off that list. Now tested.

THREE TEST DEFECTS, all found by the conversion:

  - one test asserted THE BUG: "returns empty string when no content in
    response" expected `result.content === ''`. It is replaced by two
    tests — an empty 200 demotes to the next link, and an empty 200 at
    every link throws rather than answering with nothing.
  - the fetch mocks were `{ ok, json }` literals with no `text()`. That
    encoded an assumption about HOW the client reads a body and broke the
    moment it read the text first (to keep the vendor's body in the
    error). Real Response objects now.
  - `mockResolvedValue(new Response(...))` handed every link the SAME
    object, and a Response body can only be read once — so link two
    always failed with "Body has already been read", a fake failure
    standing in front of the real behaviour. Anything walking a chain
    needs a factory, not a value.

The `vi.mock('@/lib/constants')` for the endpoint URLs is removed: the
client takes them from the same ai-kit provider record that supplies the
model list, so mocking them asserted a copy nothing reads. Verified the
resulting URLs are byte-identical to the constants they replace.

verify green: format, lint, typecheck, selfhost check, 277 tests, build.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 23:01:43 +00:00
a04d484451 refactor(email): SES -> @bitbaum/mail-kit; drop @aws-sdk/client-ses (#178)
The playbook expected no SES call sites, but lib/email/service.ts is live
(consultations route sends welcome + admin mails through it), so a bare dep
removal would have broken the build. Instead the transport is swapped to the
fleet's mail layer:

- EmailService now sends via @bitbaum/mail-kit sendMail; the throw-on-failure
  contract is preserved for the catching caller
- Sender comes from RESEND_FROM (fleet SSOT) with conventionalFrom('Botsmann')
  fallback; FROM_EMAIL and NEXT_AWS_* reads deleted from email config paths
- @aws-sdk/client-ses removed; tests mock @bitbaum/mail-kit instead of SES,
  with a new failed-send assertion


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-09-05 10:14:55 +00:00
7f6c8db4f6 refactor(deps): ai-kit comes from npm — @bitbaum/ai-kit ^0.6.2 (#174)
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-09-03 14:54:30 +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
GandMao Nakamoto 8ba5b82859 fix(nlp): route product-search query parsing through the multi-vendor LLM chain (#172)
lib/nlp.ts's processQuery() made a hardcoded direct fetch to
api.openai.com with a single model (gpt-3.5-turbo) and no fallback.
OPENAI_API_KEY is not configured in production, so this path always
threw before even reaching the network -- silently dead code on every
call from app/api/products/search/route.ts since deployment, papered
over only by the pre-existing basic-search fallback.

Replace the hardcoded OpenAI call with generateWithBestProvider from
lib/llm-client.ts, the same Ollama -> Groq -> OpenRouter chain every
other AI call path in this repo already uses. Preserves processQuery's
signature and its existing graceful-degradation contract (malformed
JSON or a fully unavailable chain still falls back to a basic keyword
search instead of throwing to the route).

Found by this session's fleet-wide AI-reliability audit, which has
been fixing this exact "single-vendor bypass, no fallback" shape
across the fleet.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-02 10:36:17 +02: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
GandClaude Opus 5 9cf91812aa refactor(test): jest -> vitest (#165)
Jest is CJS-rooted, needs transform configuration for ESM and TypeScript, and
every shared CI template has to accommodate its dialect. vitest is ESM/TS
native and jest-compatible at the API level.

`globals: true` keeps describe/it/expect/beforeEach/vi available without
imports, so the diff is the jest.* API names and nothing else. Only TYPES had
to be imported, because a type cannot come from a global.

next/jest supplied the path alias, the next/server mock and the jsdom
environment implicitly; vitest.config.ts states them, so they are visible
rather than inherited. The transformIgnorePatterns override for ESM-only
packages (ai-kit) is DELETED rather than translated — jest ran CJS and died on
`Unexpected token export`, which is the entire reason that workaround existed.
vitest loads ESM natively.

Three things only running the suite could have found:

  * __mocks__/next/server.ts was outside the first rewrite pass, so every test
    importing it died with `jest is not defined`.
  * vitest builds a mocked constructor with Reflect.construct, and an ARROW
    function is not constructible — `vi.fn().mockImplementation(() => ({...}))`
    threw "is not a constructor" the moment the code did `new SESClient()`.
    jest tolerated it. Two mocks needed function expressions.
  * removing @types/jest took the global describe/it/expect declarations with
    it; tsconfig now carries "types": ["vitest/globals"].

Verified locally before pushing: 272 passed, 2 skipped, 23 files.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:15:12 +00:00
a95373b3a5 refactor: adopt ai-kit's tryChain + createHealthTracker (#164)
botsmann's own generateWithBestProvider/getProviderChain and llm-health.ts
were the source this session extracted ai-kit v0.5.0's tryChain and
createHealthTracker from. This adopts that package for real, closing the
gap flagged by a fleet-wide audit: botsmann had ai-kit installed for model
lists only, while the actual retry/health logic stayed hand-rolled here.

- generateWithBestProvider now builds one flat provider+model chain via
  ai-kit's usableChain/freeChain and walks it with tryChain, instead of
  two separate hand-rolled loops (provider here, model inside
  generateWithGroq/generateWithOpenRouter). Ollama stays a special-cased
  first check -- its availability is a live ping, not an API key, so it
  does not fit ai-kit's Provider shape.
- generateWithGroq/generateWithOpenRouter are unchanged in behavior,
  refactored into thin loops over new callGroqModel/callOpenRouterModel
  single-shot primitives -- the same primitives generateWithBestProvider's
  chain walk now calls directly, so there is exactly one fetch
  implementation per vendor, not two.
- llm-health.ts keeps its exact five-function API (every route and test
  still imports recordLLMSuccess/recordLLMFailure/getLLMHealth/
  resetLLMHealth unchanged) but now wraps ai-kit's createHealthTracker
  instead of hand-rolled module state.

One test's assertion on the aggregate-failure error wording updated
("provider(s)" -> "link(s)") to match ai-kit's more precise per-link
failure report; no other test needed changes. Full verify green: format,
lint, typecheck, 272 tests, production build.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 10:05:34 +02:00
a5ca4af8b9 fix(ai): a revoked key on the first provider took the whole chain down (#154)
generateWithBestProvider picked ONE provider and called it once. Being
configured counted as being available, so a present-but-revoked key was
indistinguishable from a working one: botsmann's Groq key started returning
401 and the entire AI layer went down, with no attempt at anything else.

kivvi survives the same dead-Groq situation on this box because it has an
OpenRouter key and reaches it. botsmann would not have, even after adding
one -- Groq is chosen first for merely existing, and its 401 was terminal.

  getProviderChain()          every configured provider, in preference order
                              (Ollama, Groq, OpenRouter) rather than the first
  generateWithBestProvider()  walks that chain, demoting on failure, and only
                              throws once every provider has been tried

generateLLMResponse already walks the model list within a provider (#137), so
this is the layer above: models, then providers. The error now names each
provider that failed and why, instead of surfacing whichever one happened to
be first.

This does NOT restore botsmann's AI. Every working LLM key on the box belongs
to a client -- AOZ's and RevampIT's -- and botsmann is a bitbaum product, so
pointing it at one would bill a client for our usage. It needs its own key.
What this does is make sure that once a second key exists, one dead key can
never take the product down again.

verify: format, lint, typecheck, 272 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 16:09:06 +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
393a7e2b02 fix(design): the homepage had a fifth colour system, and the guard missed it (#149)
#148 shipped with the guard passing and the homepage still emitting
bg-blue-100, text-indigo-600, bg-purple-100. Both were true, because the
guard only walked app/ and components/.

The palette was in data/professionals.ts -- its own getAccentColorClasses,
giving each of the six first-party professionals a colour (blue, green,
indigo, red, amber, purple). Same mistake as the bots in #144, in the one
directory the scanner did not read. That is the whole lesson: a source
scanner is blind in exactly the shapes you forget to look at, so its first
clean run proves nothing.

  - the six professionals now use the brand, like the six bots
  - the guard walks data/ and lib/ too
  - data/menuItems.ts lost a blue/purple gradient

Two files are now DOCUMENTED exceptions rather than debt, because their
colour is categorical and has to stay mutually distinguishable:

  lib/constants.ts                    document status -- pending yellow,
                                      processing blue, ready green, error red.
                                      Recolouring "processing" to ochre would
                                      make state read as brand chrome.
  lib/infrastructure/providers.ts     per-provider identity, so Ollama and
                                      OpenAI are tellable apart at a glance.

Both sit alongside Callout.tsx's info/warning/error triad, each with its
reason written next to it.

verify: format, lint, typecheck, 256 tests, build -- all green. Homepage
confirmed to emit no raw palette class at all.


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 10:04:44 +00:00
f04d13bf39 refactor(design): finish the colour sweep, and make it enforceable (#148)
#144 put the bot pages on the brand. This does the other 60 files, so the
whole product reads as one thing, and adds the guard that keeps it that way.

~410 raw palette classes became semantic tokens across the public marketing
surface (/try, /enterprise, /about, /knowledge, /personal, /professionals,
/bots, blog, navigation) and the app internals (dashboard, documents, chat,
conversations, onboarding, auth, settings, profile).

Gradient text is gone. Fifteen headings were
`bg-gradient-to-r from-X to-Y bg-clip-text text-transparent`; they are now
solid text-ink or text-action. globals.css says the identity is carried by
typography, and a serif display does not need a gradient to do that.

The 'B' mark was still a blue/purple gradient in BotNavigation's MOBILE menu.
#144 only fixed the desktop header. Both now render the shared <Logo>.

Three defects introduced mid-sweep and corrected, all caught by reading the
diff rather than trusting the regex:
  - degenerate gradients (`from-action-tint to-action-tint`) collapsed to solid
  - dead hovers (tint on tint) rebased to bg-surface + hover:bg-action-tint
  - `to-action\b` matched the prefix of `to-action-hover`, so a collapse left a
    stray `bg-action-hover` as a BASE background in 11 places -- those are the
    primary, not the hover shade

Deliberately NOT changed:
  - components/knowledge/Callout.tsx -- its blue is the `info` half of an
    info/warning/error triad. Semantic status colour is a separate scale from
    the brand accent, and warning is amber, so ochre-ing info would make the
    two nearly indistinguishable.
  - the custom-bot surfaces -- custom_bots.accent_color is a real column with
    a CHECK constraint and the owner picks it. User data, not a design token.

Never-twice: tests/__tests__/lib/design-tokens.test.ts refuses any raw
brand-palette class, and any bg-clip-text, outside those two documented
exceptions. Mutation-verified -- swap one token back to bg-blue-600 and it
fails and names the file. No allowlist debt: every other file was swept rather
than excused.

verify: format, lint, typecheck, 256 tests, build -- all green. Twelve pages
smoke-tested and checked visually against a local production build.


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 09:53:41 +00:00
4447a97afb fix(bots): repair 20 dead nav links, restore Imhotep's lost content (#146)
The config-driven refactor (4600019e) deleted ~16,000 lines of bot page
content but left data/bots.ts still advertising it. Every bot's nav kept
linking to sections that no longer existed:

  swiss-german-teacher  communication, culture, waitlist
  research-assistant    scraping, drafts, questions, discovery,
                        integration, roadmap
  medical-expert        harm-reduction
  artistic-advisor      styles, techniques, get-started
  product-manager       workflow, showcase, examples, integration,
                        testimonials, pricing, get-started
  legal-expert          get-started

Twenty menu items that scrolled nowhere, on the live site, for seven months.
Nothing failed because nothing compared data/bots.ts to bot-pages.ts.

Now they do: tests/__tests__/lib/bot-nav-integrity.test.ts asserts every nav
item targets a section the page actually renders, and that ids are unique.
Mutation-verified -- repoint one item at a missing section and it fails and
names it.

legal-expert's 'Get Started' was repointed to the cta section it clearly
meant. The rest are removed, because the sections they named are gone.

Content restored for medical-expert, recovered from the deleted components
and ported as config (no new components needed):
  medbox         MedBox home health lab -- the 6 sensors
  health-topics  the 6 topics Imhotep covers
  regimens       Basic / Advanced, and how they compare to Blueprint

Its page goes from 7 sections to 10, and from 3,833 to 5,380 rendered
characters. The nav gains MedBox and Topics in place of the dead link.

NOT restored: the harm-reduction section, a substance comparison table
covering heroin, methamphetamine, MDMA, LSD and psilocybin. On a site
offering AI health guidance that is a product and possibly a regulatory
decision, not a cleanup one. It stays in git at 4600019e^ pending a call:
  git show 4600019e^:app/bots/medical-expert/components/features/HarmReductionSection.tsx

The other four bots still need their content ported; this is the pattern.

verify: format, lint, typecheck, 253 tests, build -- all green. Verified
visually against a local production build.


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 10:42:26 +02: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
93d6ed067b fix(db): our tables are not in orangecat's schema — tell every client (#138)
/api/health has returned 503 because `public.consultations` does not exist. It
never did. Botsmann shares one self-hosted Supabase database with orangecat,
which owns `public` and its 128 tables; ours were nowhere, because all eleven
migrations were unapplied.

The schema half is fixed in the deploy pipeline (fleetcrown#398): botsmann now
declares `supabase:botsmann` and its migrations apply into a schema of its own,
exactly as printcraft's do. That has run — all 11 tags are recorded and the 12
tables exist.

This is the other half. A Supabase client that is not told the schema queries
`public`, so it would still get PGRST205. Measured against production just now:

  GET /rest/v1/consultations                      -> 404 PGRST205
  GET /rest/v1/consultations  Accept-Profile: botsmann -> 200 []

`db: { schema }` is what sends that header, and it was missing from all four
client factories — anon, service-role, browser and route-handler.

The schema name is one constant in lib/constants.ts, not four literals. The
second copy is how the first goes stale, and this repo has just spent a day
proving what duplicated configuration costs.

Two things this also removes:

  * `scripts/run-migration.ts` and `scripts/migrate-via-api.ts` applied SQL
    through the service-role client with no schema set. They are from the era
    when migrations were run by hand; now they would create our tables inside
    orangecat's `public`. Schema is the pipeline's job, and a second way to do
    it is a second way to do it wrong. Nothing references them.
  * The bare `SupabaseClient` type hardcodes `'public'`, so annotating with it
    silently asserts we query orangecat's tables — and rejects the client we
    actually build. The type is now derived from the factory, which keeps the
    two in step and survives supabase-js reordering its generics.

New test pins it per file, by count: every `createClient` call in a client file
must set the schema, from the shared constant, with comments stripped first so
the guard cannot be fooled by prose. Adding a fifth unscoped factory fails the
test instead of production. Mutation-checked: unscoping the browser client
fails it.

verify green: 237 tests, lint, typecheck, build.


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-27 19:57:39 +00:00
GandClaude Opus 5 198e54d38d fix(llm): take model ids from ai-kit, and try more than one (#137)
Both ids in `API_CONFIG` have been retired by their vendors:
`llama-3.1-8b-instant` at Groq and `openai/gpt-oss-20b:free` at OpenRouter. With
a valid key, this app's chatbot was answering 404.

Nothing was neglected here. The constant carried the correct instruction —
"free catalogues rot; when it does, replace it with another `:free` id" — and
that is precisely the maintenance that did not happen, because nothing tells a
constant when it has stopped being true. So the ids leave this repo. `ai-kit`
holds one list for the fleet, re-probes it against the live catalogues, and
dotfiles' daily audit asks both vendors whether those ids still exist.

One id was also not enough on its own. `generateWithBestProvider` picks ONE
provider and calls it exactly once, so a retirement had nothing between it and
a dead chatbot. Each vendor's call now walks that vendor's list: a 404 (retired)
or a 429 (busy or spent) steps to the next model instead of surfacing.

This is model-level fallback, not vendor-level — provider selection is untouched.
That is the smaller half of the protection, since a spent daily budget is
org-wide and kills every model at a vendor together. It is also the half that
covers rot, which is what actually happened here, twice.

An explicit caller override is still honoured as-is and alone. If someone names
a model, quietly answering from a different one is worse than failing.

The cost rule that lived in the deleted comment survives, and got stronger.
`free-fallback.test.ts` used to regex ONE constant; it now runs `modelCost` over
every OpenRouter id this app could send, using the same function the rest of the
fleet prices models with. OpenRouter is only reached when Groq's free tier is
spent — when nobody is watching — so a paid id there turns an outage into a bill.

The old tests deserve a note, because they passed throughout the outage: they
mocked `llama-3.1-8b-instant` and asserted it back, agreeing with production
about an id production was refusing. Worse, the OpenRouter test asserted
`anthropic/claude-sonnet-5` — a paid model on the free-tier fallback path, the
exact thing the fleet rule forbids, green the whole time. They now assert
against the chain, plus two new cases: a retired first model falls through to a
different one, and exhausting the list names the whole list.

`jest.config.js` transforms `ai-kit`, which is ESM-only. The comment there says
what does NOT belong in that list, since a transitive entry would mean a package
leaking a dependency through a re-export — a bug to fix at the source.

verify: format, lint, typecheck, 232 tests, build.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:07:23 +00:00
G 7a4d2f20d1 fix(ai): the OpenRouter fallback was a premium paid model (#135)
OPENROUTER_DEFAULT_MODEL was `anthropic/claude-sonnet-5`. OpenRouter is the
FALLBACK here — it is reached when Groq's free tier is spent — so the failure
mode of 'the free tier ran out' was not a degraded answer or an honest refusal.
It was a bill, on a premium model, produced by the one code path nobody watches
because it only runs when something else has already broken.

A fallback is a reliability mechanism; paying is a business decision. Wiring the
second to the first lets an outage make the decision at the worst moment,
without anyone choosing it. It also broke the standing fleet rule that Anthropic
is never a primary or fallback provider.

Now `openai/gpt-oss-20b:free`, which reports pricing.prompt = 0 in OpenRouter's
own catalogue (checked 2026-08-16) and was probed live for tool support on
2026-08-15.

Guarded by a test, because this path is invisible in normal operation: the
default must end in `:free` and must never be an Anthropic id. The rule mirrors
`modelCost` in the shared ai-ration package — a routed id is free ONLY with the
`:free` suffix, which is the entire difference between free routing and a
per-call charge for identical weights.

The same mistake was found in three apps on the same day (also kivvi and evig).
2026-08-16 12:43:31 +00:00
GandClaude Fable 5 e9f0193937 fix(ai): replace retired Claude model defaults (#123)
- providers.py: claude-sonnet-4-20250514 (deprecated, retires Jun 2026) -> claude-sonnet-5
- constants.ts: anthropic/claude-3.5-sonnet (retired Oct 2025 on OpenRouter) -> anthropic/claude-sonnet-5 (verified against OpenRouter's live model list)
- test fixtures updated to match

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 16:38:13 +02:00
g-butandClaude Opus 4.6 40d525a5a0 test: add 5 test files for core business logic
Cover prompt-sanitizer (injection defense), embeddings (cosine similarity,
chunking), context/store (CRUD operations), context/extractor (fact
extraction), and llm-client (provider selection, fallback). Brings test
count from 138 to 227.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 10:26:14 +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 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 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.5 37f193b226 chore: remove orphaned bot navigation components
- Remove swiss-german-teacher/components/shared/ (unused DemoModeOverlay, DemoPopup, Navigation)
- Remove swiss-german-teacher/components/navigation/ (unused Navigation)
- Remove medical-expert/components/navigation/ (unused Navigation)
- Remove product-manager/components/navigation/ (unused Navigation)
- Remove research-assistant/components/navigation/ (unused Navigation)
- Fix test to use valid ErrorCode type

All bots now use BotPageTemplate's shared navigation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 14:57:32 +01:00
g-butandClaude Opus 4.5 21187ba285 chore: remove dead code files
- Delete lib/groq.ts (replaced by lib/llm-client.ts)
- Delete tests/api.test.js.bak (orphaned backup file)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 01:11:27 +01:00
g-butandClaude Opus 4.5 e4425ffaea fix: resolve test infrastructure issues
- Add next/server mock for Jest to handle NextRequest/NextResponse imports
- Fix api-responses tests to match actual function signatures:
  - jsonSuccess wraps data in response.data property
  - jsonValidationError expects ValidationError[] not object
  - formatZodErrors returns array not object with field properties

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:35:32 +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 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-butandClaude Opus 4.5 e06e68f5fe Migrate database from MongoDB to Supabase
- Replace MongoDB/Mongoose with Supabase (free tier)
- Add lib/supabase.ts client with lazy loading
- Update consultations API to use Supabase
- Update health endpoint for Supabase
- Add SQL migration for consultations table
- Remove MongoDB dependencies from package.json
- Update .env.example with Supabase variables

Cost: $0/month (Supabase free tier)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 11:55:15 +01:00
g-butandClaude Opus 4.5 b86367ac10 test: add unit tests for validation and format utilities
- Add comprehensive tests for lib/validation.ts
  - isValidEmail, isNotEmpty, hasMinLength, hasMaxLength
  - formatErrorMessage, EMAIL_REGEX
- Add comprehensive tests for lib/format.ts
  - formatCurrency, formatNumber, formatDate
  - formatPercent, toISOString
- 26 new test cases, all passing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 22:08:36 +01:00
g-butandClaude Opus 4.5 da5e38e209 fix: improve test suite reliability and configuration
- Add TextEncoder/TextDecoder polyfills for MongoDB/Mongoose tests
- Mock AWS SES client in email service tests
- Fix platform tests to properly handle missing credentials
- Skip MongoDB integration tests when MONGODB_URI not available
- Restore env vars between tests to prevent test pollution
- Install node-mocks-http for API route testing

Test suite: 11 passed, 1 skipped (integration test)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-11 17:18:52 +01:00
g-butandClaude Opus 4.5 532457299e refactor: major codebase cleanup and consolidation
## Dead Code Removed
- lib/nlp.ts (418 lines - unused duplicate)
- DemoSection.old.tsx (obsolete file)
- src/components/bots/BotPage.tsx (never imported)
- TextGenerator.tsx & EmailGenerator.tsx duplicates

## Unused Packages Removed
- @sendgrid/mail (not used - only AWS SES active)
- mailgun.js (not used)
- form-data (not used)

## Structure Consolidated
- Moved all src/lib/* to lib/ (SSOT)
- Moved src/components/navigation/* to components/
- Removed empty src/ directory
- Updated all imports to use @/lib/

## Type Fixes
- Fixed implicit any types in WorkspaceDashboard.tsx
- Fixed type union in AICaseAnalysis.tsx
- Fixed typed routes issue in page.tsx
- Fixed MongoDB module load-time error

## Build
- npm run build passes successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 00:01:42 +01:00
Devin AIandcato 163428ef40 chore: update test configuration to use Netlify URL
Co-Authored-By: G <butaeff@gmail.com>
2025-02-12 08:50:16 +00:00
Devin AIandcato 0573d0eac9 test: add email service tests
Co-Authored-By: G <butaeff@gmail.com>
2025-02-10 23:42:05 +00:00
Devin AIandcato 65c87bb051 feat: add MongoDB integration for consultation form
Co-Authored-By: G <butaeff@gmail.com>
2025-02-09 20:34:49 +00:00
Devin AIandcato cd4c9df2ac chore: clean up obsolete files and consolidate code
Co-Authored-By: G <butaeff@gmail.com>
2025-02-09 20:24:14 +00:00
Devin AIandcato 39efe783b4 test: add NLP and platform integration tests
Co-Authored-By: G <butaeff@gmail.com>
2025-02-08 17:20:36 +00:00
George 3a778438c7 Initial commit 2024-12-31 20:54:54 +01:00