Commit Graph
12 Commits
Author SHA1 Message Date
CatoandClaude Opus 5.5 da77411696 fix(ai): no timer or page load spends a free-tier AI key (#1146)
* fix(ai): no timer or page load spends a free-tier AI key

Standing rule (2026-09-25): the box's AI keys are free tiers, OpenRouter and
Gemini shared with every app, and may be spent only when a person asks.

- cat-health cron (nightly completion probe of every vendor): route + timer
  removed; the "Check Cat's status" click still runs the probe.
- reindex-embeddings cron (nightly embedding sweep): route + timer removed;
  a save still indexes its own row via the DB trigger -> admin route.
- orangecat-cat-eval.timer (nightly Cat eval + LLM judge on the free pool):
  unit removed; eval-cat.mjs is run by hand.
- cat-watches: topic watches embedded their topic every 15 min. The vector is
  now stored when the user creates the watch (migration adds
  cat_watches.topic_embedding); the timer matches with it via the new
  embed-free discovery-match module.
- GET /api/cat/nudges (dashboard mount + weekly-digest): LLM "smart" nudges
  and the bio embedding removed; rule-based nudges stay.
- GET /api/cat/suggestions (opening the chat): chips were LLM-written on load;
  now deterministic (cat-home-chips.ts deleted).
- deploy-selfhost.sh retires the old units on the box (RETIRED list).

cat-mentions stays: it only answers a message in which a person addressed @cat.

Regression: __tests__/unit/ci/no-background-ai.test.ts walks imports
transitively from every cron route, every page/layout and every GET route to
the model/embedding modules. Proven by mutation: re-importing exploreTopic in
proactive.ts, platform-llm in prompt-suggestions.ts, or platform-search in
nudges.ts each turns it red.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* test(ai): read without a stat-then-read race (CodeQL)

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 02:08:25 -07:00
CatoandClaude Opus 5 d42fe04fcb fix(eval): the judge the flag promised now exists (#996)
#989 made the `why` axis advisory and told the operator, in the run's own
output: "Set CAT_EVAL_JUDGE=1 (needs OPENROUTER_API_KEY) to judge it
semantically and gate on it."

There was no judge. The flag only flipped computePass to gate on `scores.why`
— which is still the regex count. Setting it would have gated on the very
phrase list the same commit declared unfit for gating, and worse than leaving
it off, because the operator would believe the number meant something.

That is the second time today I shipped a claim with no implementation behind
it. The first was telling the model Cat may post to Nostr when nothing
publishes a note (#995). A flag is a claim, and a claim needs an
implementation; the file whose subject is honesty does not get an exemption.

So `judgeWhy` is real: one YES/NO question about one property, temperature 0,
asked of a cheap model, and deliberately NOT asking for any particular word —
re-imposing a vocabulary is what the phrase list did.

The load-bearing value is NULL. No key, a refusal, a transport error, an
unparseable answer, an answer that is not YES or NO — all return null, which
means NOT JUDGED and is not the same as "this reply failed to explain itself".
`computePass` now takes `judged` and gates on `why` only when a judge answered
for EVERY probe. A half-judged run falls back to advisory rather than to the
regex, so flipping the flag can never quietly re-enable what it replaced.

One existing test asserted the old, wrong contract — that the flag alone gates
— and failed. It was rewritten rather than relaxed: the flag is the claim, the
judged count is the evidence.

A mutant escaped on the first pass and is worth recording: asserting the
system prompt matched /not required/ was satisfied by the original sentence
while the mutant ADDED a contradicting "the word because is required". The
negative assertion is the stronger half, again.

Verified: 3198 tests green, 0 lint errors, seven mutants all caught.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 08:40:07 -07:00
CatoandClaude Opus 5 bdfbfee1e5 fix(eval): the nightly Cat gate only fails for what it can measure (#989)
* fix(eval): the nightly Cat gate only fails for what it can measure

Found by running the eval by hand, not by anything telling anyone — which is
half the bug.

A SKIP reached nobody. Standing down to protect the user-facing free pool is
correct behaviour, but it returned with exit 0, systemd recorded success, and a
night on which Cat was never verified looked identical to a night on which Cat
was healthy. It skipped silently on 2026-09-10 and 2026-09-11. It still exits 0
— paging nightly for a budget ceiling is how an alarm gets muted for good — but
it now says so, upserted on its title so a run of skipped nights bumps one row
instead of stacking a pile nobody reads either.

The "why" axis is a list of fifteen English connectives. It asks whether Cat
used one of those phrasings, not whether Cat explained itself, and on
2026-09-12 the difference paged the founder: the g-bakery probe answered "As a
bakery, you already have the asset and the skill to turn your craft into
income", which is a reason by any reading, matched nothing, and reported
REGRESSION. Adding the single word "because" to that same sentence flips it to
PASS — the test asserts exactly that, so the blind spot is pinned rather than
described.

So `type` still gates, because it checks STRUCTURE — which draft card was
attached, whether a clarifying question was asked — and a regex can check
structure honestly. `why` is computed, printed, and advisory until something
can judge meaning. CAT_EVAL_JUDGE=1 turns it back into a real gate; it is off
by default because eight probes plus a 20-request reserve already do not fit in
50 free requests a day, and judging adds calls to exactly the pool that is
short. Built now, one env var away the day the ceiling is raised.

This is the same failure both times: the gate asserted something it could not
support. A gate that cries wolf is worse than no gate, because it trains
everyone to ignore the one alarm that turns out to be real — the lesson
eval-cat-retry.test.ts was already written for.

NOT fixed here, because it is a spend decision: the free-tier ceiling itself.
At 50 requests/day the eval stands down most nights, so Cat's judgment is
usually unverified. 10 OpenRouter credits raises it to 1000/day.

Verified: 3111 tests green, 0 lint errors.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw

* fix(eval): do not log the notification recipient id

CodeQL js/clear-text-logging, 2 high, on scripts/eval-cat.mjs. The recipient
is read from CAT_EVAL_NOTIFY_USER_ID, so interpolating it into the journal logs
an environment-derived value in the clear. Two of the three sites predate this
branch; editing the file put them in the diff, which is the right moment to fix
them rather than step around them.

The id was never the useful part of the line — "the founder was notified" is
the fact a reader needs. Nothing else changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw

* fix(eval): log the error's class, not the error

CodeQL js/clear-text-logging, high, on the notification-failure logs. The
helper builds its URL from CAT_EVAL_NOTIFY_USER_ID, so a thrown fetch error can
carry that environment-derived id in its message, and `${err}` put it in the
journal in the clear.

`err.name` still distinguishes a network fault from a bad response, which is
the part worth having at 04:30, and it is a class name that can never carry the
id. Applied at all three sites rather than only the one CodeQL called new — the
other two are the same defect and were already in this diff.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw

* fix(eval): log a literal, not anything taken from the error

Second attempt at the same CodeQL alert, and the first one was wrong for a
reason worth writing down: `err.name` is a property of the tainted object, so
the error still reaches the log. CodeQL kept flagging it and was right to.

Nothing derived from the error is interpolated now. A branch picks one of three
literals — network, rejected, unknown — which still answers the only question
worth asking at 04:30: could we not reach the box, or did it refuse us.

Why this matters at all here: these helpers build their URL from
CAT_EVAL_NOTIFY_USER_ID, so a failed fetch can carry that environment-derived
id inside its message and put it in the journal in the clear.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HJRuvHJEBd8t7iRA9Sb1iw

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 06:27:43 -07:00
CatoandClaude Fable 5.1 e2f8779837 feat(cat): ask for permission by name, check its own record, and select sections by turn (#967)
ADR-0006 D5, D6, and the section-selection mechanism — the three items left
open after #964 — plus the fix that lets the eval that gates them actually run.

D5, a first run that can do something. Most of it had already shipped as
grant-on-confirm (20260910203000_confirming_can_also_allow.sql): a denial for a
non-payment, non-high-risk action becomes a consent card reading "Allow and
confirm". What was missing was the other half of the conversation. The model
was told a plain "waiting for confirmation", so its reply announced a done deal
while the card asked for a permission the reply never mentioned. summariseForModel
now says NOT YET ALLOWED, names the category, and says one tap allows it; a hard
denial names the category to allow instead of "tell the user what to grant"
with nothing to say.

Two measured corrections with it. update_profile sat in the default-on 'context'
category with requiresConfirmation: false — a brand-new user's Cat could rewrite
their public @handle and bio on a stray sentence. It is now 'entities' and
confirmed, and reaches a new user through the consent card. And 'settings' was a
permission category with zero actions in it: a switch in the UI governing
nothing. Removed from the app; the Postgres enum value is left orphaned (cannot
be dropped in place, no row references it). The class is closed by a test —
every listed category must govern at least one enabled action.

D6, Cat can check its own work. track-record.ts already derived proposed →
published → funded plus setbacks from cat_action_log; it was ambient context
only. It is now also the read tool check_my_track_record, answered as prose by
formatTrackRecordForModel, which states Cat's own pattern as a fact to act on:
"3 things drafted, none published — offer to finish ONE before creating
anything new"; "2 published but nothing funded — the gap is reach or pricing";
"2 proposals never confirmed — ask what held them back". A null record says
"could not be read — do not reconstruct from memory", never "nothing yet".
Scoped to Cat's own actions in the router; the user's own numbers stay with
query_my_data.

Section selection, mechanism built, flag off. Two things were found by trying
to enable it. Nothing anywhere produced a turnDescriptor — the env flag was a
double gate that changed nothing when set. services/cat/turn-descriptor.ts now
builds one in chat-prepare from facts the caller has: the message, whether
history is empty (fetched before the brief now, so first-message is read not
guessed), the page, the entity. And selection ran BEFORE the capability strip,
so flag-on + actionsVia 'none' + a greeting threw: selection had already removed
an instruction section the strip then demanded. Strip runs first now. Measured
on the tools path: unselected 32,019 chars; a first-message greeting 23,097; a
pricing question 18,824.

The eval that is supposed to validate the flip has not run since 2026-09-10. It
logged "free-model budget 0/0 remaining — SKIPPED" every night. From the box:
OpenRouter answers HTTP 200 on the free model and sends NO x-ratelimit-*
headers; Number(null) is 0 and 0 is finite, so a missing header read as an
exhausted budget and the eval stood down to protect a reserve that was never in
danger — the exact thing the comment above that code says it must not do.
Header parsing is now scripts/eval-rate-limit.mjs, absent means unknown means
proceed, and the run logs when the budget is unknown so silence cannot read as
"checked". Unit-tested.

Gates proved by mutation: 16 mutants, 16 killed, sources sha256-verified
restored. Three survived the first pass and were diagnosed rather than
excused: two had matched update_entity's identical four-line block before
update_profile's (re-anchored on a unique comment), one kept both phrases the
test looked for (test now asserts a null record never reads "nothing yet").

Not built, stated in the ADR: the loop does not resume after confirmation; the
card confirms, the action runs, a system message reports it.


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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 23:57:17 -07:00
db284f5f96 refactor(ai): one platform-LLM path, one eval auth helper (#676)
Two duplicated blocks, both now living once:

- intent-router and offer-engine each carried their own copy of the
  platform provider call (Groq-first, OpenRouter fallback, json_object,
  failure logging). Both now go through callPlatformJson in
  platform-llm.ts — the SSOT the other four structured Cat features
  already use — so provider choice and the json-mode 400-retry apply
  everywhere, once. form-prefill-service stays separate on purpose: it
  accepts a user-supplied API key/model, so it is not a pure platform
  call.

- signIn/buildAuthCookie (GoTrue REST + forged @supabase/ssr cookie) was
  copied across eval-cat, eval-voice-routing and eval-wallet-routing.
  Extracted to scripts/eval-auth.mjs; deploy-selfhost.sh ships it next
  to eval-cat.mjs so the nightly timer on the box keeps resolving the
  import.

Verified: tsc clean, lint clean, 2153 unit tests green, and
eval:voice 13/13 against production through the new auth path.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 16:28:38 +00:00
afa221b4b5 fix(cat): the health check said "healthy" while Cat could not answer anyone (#639)
* fix(cat): the health check said "healthy" while Cat could not answer anyone

Production reported `catCanAnswer: true` / "Cat is healthy: groq probe returned
OK" on a day when Cat could not serve a single message. Both halves were true:
the Groq probe pings with ~5 tokens, so it returns 200 whenever the key and the
service are fine — while Cat's real prompt exceeds Groq's per-minute token
limit, so every actual message 413s and falls through to OpenRouter, whose free
tier was already exhausted (429). Together and Ollama are not configured, so
there was nothing else in the chain.

A probe that exercises the endpoint but not the payload measures the wrong
thing, and a green light nobody can act on is worse than a red one.

- `groqCanServeCatPrompt()` runs the real static prompt through the existing
  on-demand fit check; `catCanAnswer` and the summary now depend on it, and the
  report carries prompt fit as its own fact so shrinking work has a live signal.
- Gated by health-report-honesty.test.ts, mutation-tested: it fails on the old
  `groq.class === 'ok'` logic and passes on the new.

Measured against the live API while diagnosing (2026-08-06), correcting the
record:
- Cat's prompt is ~4.5 chars/token, not the ~6 this file claimed. That made the
  overshoot look like 52% when it is ~39% — the diet target was a third wrong.
- 12000 TPM is the BEST model on this key: llama-3.1-8b-instant is 6000 and
  openai/gpt-oss-{20b,120b} are 8000. There is no higher-TPM model to escape
  to, so the prompt genuinely has to shrink.
- TPM is a rolling per-minute budget, not a per-request ceiling, so back-to-back
  calls share it. Fit must be measured with one call in a drained window.

Also shrinks the prompt by 6,378 chars with no behavioural loss: the Actions
section repeated the identical exec_action JSON envelope 18 times. It is now
stated once, with each action as a compact `**id(params)**` signature carrying
its constraints, id sources, enums, confirm level and trigger phrases. Budget
ratchet lowered 60,500 -> 54,600. The reachability gate caught that the first
draft of this rewrite left all 18 actions undocumented in emittable form.

And removes two decommissioned Groq models (mixtral-8x7b-32768, gemma2-9b-it)
that answered 400 "has been decommissioned" — plus probeGroqModelCatalog, so
Groq model rot is watched the way OpenRouter's has been since its third
incident, instead of sitting in config unnoticed.

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

* perf(cat): stop diagnostics eating the capacity real users need

Two free levers toward Groq serving Cat, neither of which costs anything.

1. The nightly eval and real users drink from the same 50-requests/day free
   pool, and only one of them can wait. Eight probes is 16% of the day; with
   retries it has reached a third. On 2026-08-06 the pool was fully exhausted
   and a real user asking Cat a question got "Free AI capacity is maxed out
   right now" — diagnostics must never be the reason that happens.

   eval-cat now reads OpenRouter's X-RateLimit-Remaining before starting and
   stands down if running would push users under a reserve (default 20,
   CAT_EVAL_FREE_RESERVE). Verified live: it read 0/50 and skipped cleanly,
   reporting the reset time instead of failing eight probes into the wall.

2. GROQ_CHAT_MAX_TOKENS 2048 -> 1024. The reservation is prompt budget spent
   up-front, so 1024 fewer reserved output tokens buys ~4,600 more characters
   of prompt. Measured against the live API, this halves the remaining gap:
   the same prompt goes from needing 14,167 of a 12,000 budget to needing
   13,143. 1024 tokens is still a long chat reply, and the writing engine and
   reviser — the only callers that need more — already pass maxTokens
   explicitly, so this narrows nothing but the default.

Still ~5,100 characters short of fitting, so Groq cannot serve Cat yet; this
buys back user capacity today and halves what the diet has left to do.

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

* feat(cat): send the sections a turn needs, not all of them (flag off)

Investigated what is left to cut and the answer is: nothing safe. There are
zero duplicate lines and zero repeated sentences in the assembled prompt, and
every remaining rule — "never open with a list of questions", crisis handling,
"never pigeonhole" — is there because Cat got something wrong without it.
Cutting 13,000 more characters by editing means deleting behaviour.

The waste is not in the words, it is in sending ALL of them EVERY time. A
message about pricing a mug currently pays for crisis handling, proxy mode,
notification triage and multi-entity strategy.

So sections are classified once, in config/cat-prompt-sections.ts:

- CORE is always sent: capability, safety and output contracts — anything whose
  absence makes Cat unable or unsafe rather than merely less sharp.
- SITUATIONAL is sent when the turn is plausibly about it.

The line between them is the whole design. A missing situational section costs
sharpness; Cat still holds every action, tool and response format. A missing
core section costs capability or safety. So arguable sections go in CORE —
which is why "When Someone Needs Help, Not Strategy" and "Never Pigeonhole" are
core despite reading as situational: the cost of missing them lands on a person
having a bad day.

Invariants, because this is exactly the shrinking work the reachability gate
was written to survive:
- every section is deliberately classified, in both directions — a new one
  cannot drift into a bucket by default, and a renamed one fails the build
- an UNCLASSIFIED section is kept, never dropped; the safe reading of an
  oversight is "this might matter"
- core survives selection for every turn tried, including empty, emoji-only
  and non-English
- every enabled action stays emittable after selection, for every such turn

Correctly measured, this is necessary but not yet sufficient: on a greeting it
returns ~6,900 characters, and core alone is still ~39,000 — dominated by the
action catalog and the tool guide. The test says so out loud and ratchets the
remaining gap rather than asserting a fit that has not been achieved.

Flag CAT_PROMPT_SECTION_SELECTION is OFF. Turning it on changes how Cat
behaves, and the only instrument that can judge that is the 8-probe eval, which
needs free-model capacity the platform does not currently have. The machinery,
the classification and the invariants ship now so that flipping it later is a
one-line change made with a safety net instead of a guess.

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

* fix(cat): payment notes were being dropped — prompt said `message`, handler reads `memo`

Continuing the prompt work turned up a live bug. An action's shape is written
down in three places — the prompt (what Cat is told to emit), CAT_ACTIONS (the
declared contract) and the handler (what actually reads the parameters) — and
all three disagreed:

- send_payment: the prompt advertised `message`, the handler reads `params.memo`
  (handlers/payments.ts:134). So every note a user dictated — "send 0.001 to
  @alice with a note saying thanks" — was silently discarded and replaced with
  the default "Payment via My Cat".
- create_task: the handler supports `priority`, the prompt never mentioned it,
  so Cat could not set one at creation.
- post_to_timeline: the handler reads `visibility`, the registry never declared
  it; the prompt also never offered entity_id/entity_type, so Cat could not
  attach a post to a listing.
- send_message / invite_to_organization: the registry demanded `recipient_id` /
  `user_id`, ids Cat cannot possibly know. Both handlers already resolve a
  username, so the registry now declares what Cat can actually emit.

None of this was detectable at runtime. An unknown parameter is not rejected,
it is ignored — so the symptom is a missing note, not an error, which is why it
survived. Nothing could have caught it except a test that reads both sides.

prompt-registry-agreement.test.ts is that test: every advertised parameter must
be declared, and every required parameter must be advertised. Mutation-tested —
reintroducing `message` fails it. It also asserts it found signatures at all, so
a future change to the catalog format cannot make it vacuously pass, which is
the way the reachability gate silently died before (#634).

The section-selection ratchet then caught that these fixes GREW the prompt by
~114 characters. Rather than raise a budget whose whole contract is that it only
falls, the cost is paid back by tightening the action-appendix preamble and the
new wording — the gap is 3,089 characters, below where it started.

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

* chore(cat): absorb main, keep the prompt budget honest

Merging main brought connect_wallet (#641), a genuinely new enabled action, and
its catalog entry costs real prompt. Ported main's new add_wallet rule into the
compact catalog too: a savings goal is a bucket, not a way to get paid, so if
Payment Capabilities shows no receiving rail, connect_wallet has to run first
or the goal has nowhere to be funded.

The section-selection ratchet then failed, which is the mechanism working. What
this branch itself added was paid back by trimming — the action-appendix
preamble, the add_wallet enum and the save_economic_profile line are all
tighter than before. The remainder is connect_wallet's own cost, so the ratchet
moves 3,100 -> 3,400 with that reason recorded in the test. Growth has to be
argued, not forbidden.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 06:53:28 +00:00
e25801b641 fix(cat): a failed reply was throwing away the user's message (#623)
* fix(cat): a failed reply was throwing away the user's message

The streaming path saved a turn only `if (fullContent)`, so when the whole
provider fallback chain died, the exchange was discarded — including the
question the user had just typed. They reloaded to an empty thread, and we
kept no record of what they had asked.

Production showed the cost. Six real accounts each hold exactly one
conversation with zero messages (June 2026), created server-side by
chat-prepare during a send and then abandoned when the stream failed. Every
one of them tried Cat once and never came back, and we cannot see a single
thing they asked.

It also corrupted the metric: an unsaved turn is indistinguishable from
"opened the page and typed nothing", so those six failures counted as
engagement. Of nine accounts holding conversations, only two ever actually
sent a message, and both are ours (mao + a .test seed account).

Now the failure branch persists the turn: the user's words verbatim, plus an
assistant turn carrying the same sentence the client displayed, so the thread
reads back honestly. A half-streamed reply is stored with the partial text
marked truncated rather than passed off as complete.

The rule lives in a pure buildFailedTurnMessages() so it is testable without
booting the provider chain, and it always emits a user/assistant pair — a
dangling user turn would put two user messages back to back in replayed
history, a shape strict providers reject.

Also sweep stale eval conversations at run start. End-of-run cleanup only
knows the ids it holds in memory, so a hard kill strands them: 18 rows from a
single 2026-07-03 run were still in production a month later, over a third of
the entire conversations table.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(invariants): catch a Cat send that stored nothing

A DEFAULT conversation is created in exactly one place — chat-prepare, while
serving a send — so a default conversation holding zero messages means a
request reached the server and the user's message was never written.

That is the precise signature of the bug fixed in the previous commit, and it
went unnoticed for two months because the leftover row is indistinguishable
from "opened the page and never typed": the failure erased its own evidence
and then counted as engagement. No unit test can find that — only reading
production can, which is what this gate is for.

Verified against prod: widened to 120 days it reports exactly the six real
accounts frozen in that state since June 2026 and exits 1 under --gate.

Scoped to 30 days so those rows stay as evidence — they are the only trace of
those six attempts — without permanently reddening the gate. Empty NON-default
conversations are left alone: the rail's "new chat" button legitimately makes
one before anything is typed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 08:54:53 +00:00
f719331732 fix(eval): retry transient PostgREST 5xx instead of failing the nightly gate (#610)
* fix(eval): retry transient PostgREST 5xx instead of failing the nightly gate

PostgREST answers 503 PGRST002 ("Could not query the database for the schema
cache. Retrying.") while it reloads its cache in the background — a state that
clears itself in seconds. eval-cat.mjs had no retry, so on 2026-08-04 one blip
inside resetDailyCap killed the whole entity-type judgment gate and reported it
as a failed eval.

A gate that goes red because a cache warmed up trains you to ignore the gate.

rest() now retries 5xx and transport errors four times with linear backoff, and
still throws immediately on 4xx (a verdict about the request, not a blip). The
module gained a direct-invocation guard so it can be imported without starting a
real eval against production, which is what makes the behaviour testable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(eval): log the table, not the filtered path, on retry

CodeQL flagged the new retry log as clear-text logging of environment data, and
it was right: a PostgREST path carries its filters in the query string
(?user_id=eq.<uuid>) and those ids come from env, so the whole path leaked
identifiers into the journal for no diagnostic gain. The table name is the part
that tells you what was retried.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(eval): keep the request path out of the retry log entirely

split('?')[0] removes the filters but CodeQL does not model it as a sanitizer,
and being conservative there is correct: the path is caller-supplied and some
callers build it from env values. The retry warning does not need it — status
or 'transport' says what happened, and the error thrown once retries are
exhausted still names the full path for whoever is debugging.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-04 14:54:07 +00:00
5774475764 fix(eval): nightly Cat gate has been dead since Cat Credits shipped — pinned model is no longer free (#578)
* fix(eval): nightly Cat gate has been dead since Cat Credits shipped — pinned model is no longer free

The nightly judgment gate has reported "HARNESS ERROR — 8/8 probes failed at
the provider layer" every night. It was not a provider outage. Every probe
came back:

  HTTP 402 {"code":"INSUFFICIENT_CREDITS","message":"This is a paid frontier
  model. Top up Cat Credits..."}

eval-cat.mjs pinned the literal 'openai/gpt-oss-120b:free'. The registry now
carries 'openai/gpt-oss-120b' as a PAID model and only the 20b variant as
free, so OrangeCat's own paywall — live since Cat Credits launched
2026-08-01 — rejected the gate's every request. The gate died the day the
product started charging, and its error message pointed at the wrong layer,
which is why it read as an upstream flake for days.

Pinned to the registry's DEFAULT_FREE_MODEL_ID value, which is also what
users get by default, so the eval measures the real thing.

The literal stays a literal on purpose: this script runs on the box, where
only the standalone build ships and src/ does not exist, so it cannot import
the registry at runtime. The drift is caught in CI instead —
__tests__/unit/scripts/eval-cat-model.test.ts asserts the pinned string
equals DEFAULT_FREE_MODEL_ID *and* that the registry actually marks it free.
Verified the test does its job: reintroducing the old
'openai/gpt-oss-120b:free' pin fails 2 of 3 assertions; restoring it passes 3
of 3.

This is the same free-model-rot class that has now bitten four times. The
difference here is that the blast radius was a quality gate reporting a
misleading cause, so nobody chased it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(eval): retry backoff gave up just before free capacity returned

With the model pin corrected, the gate went from 0/8 to 6/8 probes passing
against production. The remaining two (g-bakery, h-charter) failed with the
free pool's own message: "Free AI capacity is maxed out right now. Try again
in a minute."

The longest backoff was 45s, so all attempts for those probes were spent
inside ~65s — giving up shortly before the capacity window the provider
itself names. Added a third 90s step (MAX_ATTEMPTS 3 → 4) so the retry
ladder honours what the provider asks for rather than a shorter guess.

The probes late in the run are the ones that starve, which is consistent
with a shared free pool draining over a ~5 minute run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 20:29:58 +02:00
GandClaude c318402fc3 feat(cat): bring platform notifications into the Cat's assistance scope (#448)
System/ops alerts (like the nightly eval harness failing) landed as raw
"go check journalctl" notifications the user had to decode alone — and
repeated nightly, stacking 18 unread duplicates. The Cat is the interface;
this kind of thing is exactly what it should be helping with.

- Cat context: new "Unread Platform Notifications" section — unread
  notifications fetched and coalesced by type+title (×N = one problem
  repeated N times), so the Cat can explain any alert in plain language
- New check_cat_health tool: live provider probes (extracted from
  GET /api/cat/diagnose into services/cat/health-probes.ts, route is now
  a thin wrapper) so the Cat can diagnose "provider layer failed" alerts
  itself instead of pointing at server logs
- System prompt: "Helping With Notifications" guidance — translate and
  resolve, connect eval/provider alerts to live health results, treat
  ×N as one recurring issue
- Notification center: "Ask the Cat" button on each item deep-links to
  /dashboard/cat?q=<prepared question>
- eval-cat.mjs: failure notifications now UPSERT (update the existing
  unread row per title, bumping metadata.occurrences) instead of
  inserting a duplicate every night, and action_url deep-links into the
  Cat chat for triage

Tests: coalescing + rendering unit tests; context snapshot unchanged
(notifications is an optional section).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-27 09:31:07 +02:00
Georgy Butaev f7ae05c88e ops(cat): lock nightly eval model 2026-07-03 21:58:35 +02:00
Georgy ButaevandClaude Fable 5 181772da9e ops(cat): nightly Cat-judgment eval gate — 8 canonical probes vs prod + systemd timer
scripts/eval-cat.mjs runs the 8 canonical entity-type probes (PR #375) against
the production /api/cat/chat streaming path and scores right-type / why-line /
duplicate-drafts, exiting non-zero below 7/8 on either axis.

Hygiene learned from the ad-hoc PR #375 harness: per-probe throwaway
conversations (shared history made the model answer the PREVIOUS unanswered
probe), run-window cat_memories purge (recall is per-user), full cleanup of
cat_conversations/cat_messages after, and daily platform_api_usage reset
before+after so the rail and the cap stay clean. Transient free-tier 429s get
backoff retries; the eval pins the platform default model so the gate measures
the judgment pipeline, not free-model roulette.

Box side: scripts/systemd/orangecat-cat-eval.{service,timer} (04:30 UTC,
Persistent) — repo is the SSOT; deploy-selfhost.sh now ships the script to
/opt/orangecat/scripts/ and (re)installs the units each deploy. On failure the
script inserts an in-app notification for the founder via the notifications
schema the NotificationDispatcher uses and logs to the unit journal.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 20:26:57 +02:00