Commit Graph
15 Commits
Author SHA1 Message Date
CatoandClaude Fable 5.1 30ed087aef feat(bots): a bot writes first on the person's own key, and can ask Loki as them (#1503)
* feat(bots): a bot writes first, on the person's own key

A person can tell one of their bots to write first, every day at a time
they pick, with a prompt they wrote. The run happens on the person's own
OpenRouter key only; without a key the routine is kept, shown as waiting,
and skipped with the reason, so no platform key is ever spent by a timer
(fleet standing rule 2026-09-25).

- companion_routines table (one per person per bot, owner-only RLS),
  routines-store (time validation, next run in the person's zone) and the
  runner behind a cron route + 15-minute systemd timer, registered as a
  person-asked timer in the no-background-ai gate with a marker check.
- GET/PUT/DELETE /api/ai-assistants/[id]/routine for the owner.
- RoutineRow in a bot's own chat: "Writes first, every day", time and
  prompt inline, a line to Settings when a key is missing.
- Hands: the proposal line names what will be set up, never only "Sure";
  a created event's outcome carries its link.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

* feat(bots): a bot can ask Loki, as the person — the first connector

ask_loki: a Cat action (communication, low risk, confirmed) in the hands
launch set. The bot relays a question over the signed OrangeCat → Loki rail
to Loki's POST /api/orangecat/ask, which runs a read-only turn as the Loki
user linked to the actor; Loki's own sentence is the outcome the person
reads, and a refusal (no linked account, a spent budget) is relayed as
written. A relayed question can never dispatch, approve or spend: that stays
with send_task_to_loki, and the two verbs name each other so a question is
never dispatched as a task.

ADR-0013: D6 first connector and D7 recorded as shipped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

* fix(bots): the routine's day-in-zone comes from the timezone helper

check:app-locale (new on main) refuses a literal locale handed to Intl; the
routine's next-run computation now takes the day in the person's zone from
instantToWallTime, the one rendering the app already trusts.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

* fix(bots): the chip knows the verb of ask_loki

The tool-label table of leading verbs gains ask → Asking / Asked, so the
chip for a bot's question to Loki never falls back to the generic label.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrXvMqAqZtbpQ4x3et

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 07:40:33 +01:00
CatoandClaude 72a107760e feat(reputation): ask people to review their deals (ADR-0010 D9) (#1229)
Most people never review unless asked, and a track record nobody writes
stays empty.

- review-nudges cron (hourly systemd timer, deterministic, no model):
  asks each side that has not reviewed once 3 days after the deal
  settles, and once more in the last 5 days of the window. Sent in-app
  and by email (notification type deal_review).
- deal_review_nudges records each nudge BEFORE sending, so a crash loses
  one and never sends a second.
- When one side reviews, the other is told that it happened, never what
  was said.
- The Cat's dashboard suggestions carry the most urgent unreviewed deal,
  using the same timing rule as the cron (EN + DE copy).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-05 10:41:55 -07:00
CatoandClaude Opus 5.5 ad37b55679 fix(ops): orangecat-app restarts after a SIGTERM nobody asked for (#1155)
2026-09-26 01:53:42 UTC a SIGTERM hit every *-app unit on the box at once.
About 20 units restarted in 3s; orangecat stayed down for 3h45m (502 on the
whole site) and nothing paged.

Cause: this unit alone sets SuccessExitStatus=143 SIGTERM (so deploys don't
log as crashes). With Restart=on-failure, that makes any SIGTERM a "success",
so there's no restart and no OnFailure alert. Its comment assumed SIGTERM is
always a requested stop; it isn't.

Restart=always keeps the clean deploy journal (systemd never restarts after an
explicit stop/restart) and restarts after anything else. Already applied on
the box and proven: kill -TERM <main pid> → new PID, NRestarts=1, health 200.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 23:04:45 -07:00
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 817bdf6019 fix(ops): a requested stop is not a failure, and a dead NWC URI is not an error (#910)
* fix(ops): a requested stop is not a failure, and a dead NWC URI is not an error

Two loose ends from the sweep.

1. systemd recorded every deploy as a failure.
   A deploy stops the unit with SIGTERM and Next exits 143. With no
   SuccessExitStatus, systemd logged
     orangecat-app.service: Failed with result 'exit-code'
   and fired OnFailure= on every ordinary deploy.

   CORRECTION to what I reported earlier: this was NOT causing false pages.
   notify-failure.sh is recovery-aware — it waits 8s, sees the unit active
   again and logs "failed but recovered (restart/transient) — not paging".
   38 such suppressions in the last 7 days across the box. I claimed it paged
   without checking the notifier; it does not.

   It is a DIAGNOSIS bug, which is worth fixing on its own. In this unit's
   journal a routine deploy is indistinguishable from a crash: three "Failed
   with result 'exit-code'" lines in one afternoon read as a crash loop and
   cost real time to rule out while chasing an unrelated report. Telling
   systemd that a requested stop is success makes the journal mean what it
   says, and stops spawning a notifier per deploy to conclude nothing happened.

   Safe because SIGTERM here is always a requested stop — the OOM killer uses
   SIGKILL, which still counts as a failure and still pages.

   Applied to the box and verified by an actual restart: "Deactivated
   successfully", Result=success, no OnFailure, health 200.

2. A permanently undecryptable NWC URI logged at error on every resolution.
   Diagnosed on the box: the key is present and well-formed (32-byte hex,
   single unquoted line) and the ciphertext is intact (213 bytes), but GCM
   authentication fails — so it was encrypted under a DIFFERENT key. The
   plaintext is gone; this is real data loss, not a config outage.

   That is a permanent, per-wallet, OWNER-fixable state, and the product
   already handles it correctly: receiveStatus.ts flags the wallet and
   WalletCard renders "This connection can't be used by OrangeCat ... Edit it
   and paste the connection string again." So the log line is a breadcrumb,
   not an incident — but at error level, firing on every payment resolution
   and never able to self-resolve, one dead test wallet produced 21 of the 25
   error-level lines this app emitted in three days. Enough to bury a real one.

   Now warn, with the remedy in the payload. Deliberately NOT clearing the
   stored ciphertext: findUnusableConnections keys on it being non-null, so
   deleting it would remove the very signal that tells the owner to reconnect
   and leave the wallet looking merely empty.

241 payments/wallets tests pass; type-check and lint clean.

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

* fix(payments): keep the NWC note inside the file size gate

CI caught walletResolutionService at 516 lines against a 500 limit — the
explanatory comment I added pushed it over. The file sits at 496 on main, so
there were only 4 lines of headroom and I had not re-run check:sizes after
that edit.

Condensed to fit exactly, rather than adding a size exception (that list only
shrinks) or splitting a 500-line payment-resolution service as a side effect
of a log-level change. The full reasoning lives in the commit below it and in
PR #910, which is where someone asking "why warn?" will look.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 10:40:09 +00:00
cc6038ba9a fix(security): bind orangecat to localhost only, not every interface (#830)
launch.sh did `unset HOSTNAME` before starting the standalone server. That
does not default to localhost — Next's standalone server reads HOSTNAME as
the bind address, and unsetting it falls back to Next's own default,
0.0.0.0 (every interface). Confirmed against the actual bind on the box:
orangecat-app was listening on 0.0.0.0:4003, not 127.0.0.1:4003 like every
other app in the fleet.

Not an active incident — ufw's default-deny only allows 22/80/443, so the
port was never actually internet-reachable — but relying on the firewall
alone to cover a bind-address mistake is exactly the kind of thing that
breaks quietly the day firewall config changes for an unrelated reason.

Already applied directly to the running box (this file is vendored TO the
box, not FROM it on regular deploys — deploy-selfhost.sh preserves whatever
launch.sh is already there rather than overwriting it from the repo, per
its own comment). This commit is the repo catching up to what's already
live, so the next full box provision starts from the correct file instead
of reintroducing the bug.

Same fix shipped for fleetcrown (bitbaum/fleetcrown#437) — this repo had
the identical bug, independently.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 05:39:22 +00:00
9036cb3fb2 fix(cat): break the bootstrap deadlock that would have kept @cat inert (#768)
Caught by checking production rather than by reading the code: the queue
had deployed, and the Cat still had no account. Following that through,
it never would have got one.

The circularity: resolveMentions can only flag @cat when a Cat PROFILE
exists, so with no account nothing is ever queued — and the worker called
ensureCatAccount AFTER its empty-queue early return, so an empty queue
established nothing. Nothing queued, so nothing was established, so
nothing queued. A freshly deployed platform would sit there with @cat
resolving to nobody, looking exactly like a working feature that nobody
had used yet.

The worker now establishes the account before it looks at the queue. One
primary-key lookup per tick when it is a no-op, which is every tick after
the first, and the every-minute timer therefore becomes what brings the
Cat into existence.

Second half of the same bug, in the timer: `Persistent=true` only
replays a run MISSED while the machine was down. A timer enabled for the
first time just waits for the next OnCalendar — for a daily timer, up to
24 hours. Production confirmed it: the unit was installed and enabled,
LAST was "-", NEXT was 12 hours away. OnActiveSec=1min makes a freshly
deployed Cat exist within the minute.

Pinned by a test that asserts the ORDERING, not just the call, and proven
by restoring the old arrangement — two tests go red.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 11:52:34 +00:00
57431cbaaa feat(cat): answer @cat in private messages (#767)
Tagging the Cat in a conversation now gets an answer in that
conversation, from the Cat's own account.

The shape is a queue with two payers. The write path records that a
reply is owed and returns, because an LLM round trip must not sit inside
the sender's POST; a worker pays the debt. The systemd timer is the
DURABILITY path rather than the latency path — the write also kicks a
run, so a reply normally lands in seconds, and the tick is what
guarantees the question survives a process dying mid-thought. An
assistant that silently drops a question is worse than one that is slow.

Idempotency is the unique key on (source_type, source_id), which is what
makes an at-least-once producer safe, and 23505 is therefore treated as
success rather than failure. Concurrency is FOR UPDATE SKIP LOCKED
inside claim_cat_mentions, so an inline run overlapping a timer tick
cannot answer the same mention twice. Proven on production with two
concurrent sessions: two mentions seeded, "A claimed: 1", "B claimed: 1",
distinct rows claimed 2 of 2, nothing left pending, scratch table
dropped.

The dedupe key is the MESSAGE id, and the first draft got that wrong. It
fell back to the conversation id when no message id was passed, which
would have meant the first question ever asked in a conversation was the
only one ever answered — every later insert colliding with the unique
constraint and being read as "already queued". The parameter is now
required and the fallback is gone, with a test that fails if it returns.

"@cat what do you think about this?" works because "this" means the
conversation. The Cat reads CAT_CONTEXT_MESSAGE_WINDOW recent messages
of the thread it was tagged in and nothing else — no other conversation,
no history beyond the window. That is a stated product promise about
what tagging consents to, which is why the number lives in config and
not in a query.

The Cat STAYS in the conversation once tagged, so a follow-up needs no
second tag and both people can see it is there, and it can be removed
like any participant. That was one of the two open product calls; it is
recorded here as an assumption and is reversible.

A failure to think is still answered. CAT_FALLBACK_REPLY goes out rather
than nothing, because a tag that produces silence is indistinguishable
from a broken feature, and this codebase has shipped exactly that before.

Layering: parse (pure) -> resolve (one query) -> note (the seam a write
path calls) -> queue (durability) -> worker (dispatch) -> reply
(what it says). Nothing was added to chat-orchestrator.ts or memory.ts,
already 837 and 1062 lines. A new surface gains all of this by calling
noteCatMention.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 11:32:01 +00:00
06772cc506 feat(cat): give the Cat an account, and stop the deploy list from drifting (#766)
The Cat is a real profile rather than a rendering convention, which is
what lets a Cat reply be an ordinary messages or timeline_events row —
read receipts, search, deletion, threading, moderation and realtime all
work on it without a branch. The cost of that is exactly this: something
has to create the row.

ensureCatAccount is idempotent and cheap when it is a no-op (one indexed
lookup), so it is safe on every tick, and running it on a schedule makes
the identity self-healing: @cat is linked wherever it is written, so a
missing profile silently resolves every mention on the platform to
nobody. Daily re-assertion turns that from a support ticket into an
invariant.

The login address is cat@orangecat.invalid, and both halves are
load-bearing. `.invalid` is reserved by RFC 2606 and can never be
delivered to or registered, which matters because an account's email is
its password-reset channel — a bot identity with a routable address is
one somebody can eventually take. There is no password either, so there
is no credential to phish. The local part is what makes the handle `cat`
at all: handle_new_user derives the username from
split_part(email, '@', 1). That trigger is also the answer to why
production contains handles like m.schaupensteiner and butaeff+ocauth2 —
signup derives usernames from email addresses and never sees the
validator.

It recovers from a half-built account rather than assuming a clean slate:
the auth user survives a deleted profile row, so "already registered" is
the expected second run, not a failure. When it genuinely cannot
establish an account it returns null and says so loudly, because a caller
that improvises a sender is worse than one that stays quiet.

Also collapses the deploy script's systemd list, which was written three
times — the scp arguments, the install loop and the enable calls. Adding
a timer meant editing three places, and missing the third shipped a unit
file that never ran: the same silent-failure shape as a cron route
nothing invokes. There is now one array, and every .timer in it is
enabled from that same array.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 11:12:06 +00:00
7d8db12ce2 feat(cat): interest discovery + real introductions (#612)
* fix(cat): forget_memories now matches inflected forms and real similarity scores

Prod incident 2026-08-02: the user asked Cat to forget photography /
handmade ceramics / French / weekends-only; the model passed exactly those
phrases, the action completed — and every targeted memory survived.

Two dead layers:
- Lexical: exact-substring token matching can't see inflections
  (photography≠photographer, ceramics≠ceramic, speaking≠speaks) and the
  hard >=2-hit rule killed the rest. Now: light suffix-stripping stemmer +
  majority-of-significant-stems rule, stems compared by equality only.
- Semantic: floor 0.75 sat above what true targets score with
  text-embedding-3-small (measured against prod: 0.39-0.61, noise <=0.29).
  Now 0.45.

Also list exactly WHAT was removed in the displayMessage (not just counts)
so an over-match is visible and re-addable at a glance.

Regression suite pins the incident corpus + phrases.

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

* fix(cat): pre-flight skip for platform Groq when the prompt can't fit its TPM limit

Every Cat message in prod was paying a guaranteed-failing Groq round-trip:
the assembled prompt (memories + history + page excerpt) exceeds Groq's
on-demand 12k TPM limit, so the primary 413'd on every single message and
the reply always came from the OpenRouter fallback anyway (confirmed via
journalctl + a measured 413 against the platform key).

The chain now skips a PLATFORM Groq link up front when the prompt clearly
won't fit — only when another link can serve, never for BYOK Groq keys
(possibly a higher tier), and a pre-flight skip never marks the link down
globally (other users' smaller prompts still fit it).

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

* feat(cat): query_my_data read verb — Cat can now answer questions about the user's own live data

Listings, earnings, bookings, wallets, notifications, tasks (+ overview),
wired as a platform tool with trigger keywords, routing-prompt entry, chip
labels, and honest per-section degradation.

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

* feat(cat): memory CRUD + suppression — remember_fact, edit_memory, and forgotten facts stay forgotten

- cat_forgotten_facts table (+ match RPC, RLS) records what forget_memories
  deleted; passive extraction now skips suppressed candidates so a disowned
  fact can't be silently re-learned from old context
- remember_fact: explicit store, lifts matching suppressions, dedupes
- edit_memory: corrects exactly one memory or refuses with candidates
- prompt catalog + honesty rule updated for the three memory verbs

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

* feat(cat): every action visible + executable — generated prompt catalog, create_circle, drift guard

- system prompt now appends a machine-generated one-liner catalog for every
  enabled action without a prose section (13 verbs were invisible to the model)
- create_circle action + handler (last creatable type without a create path)
- action-registry-drift test: action↔handler↔prompt can never drift again

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

* feat(cat): proactive layer — memory notes with undo, daily brief, watches, next-step chips

- MemoryNoteCard: every new memory surfaces in chat as an undoable 'Cat noted'
  card (no more silent memory writes)
- /api/cron/cat-brief: data-only morning brief (sales, bookings, overdue,
  unread) for active Cat users, idempotent per day, skipped when empty
- /api/cron/cat-watches + cat_watches table + create_watch/cancel_watch verbs:
  'tell me when funding hits X / someone books me / next sale', checked every
  15 min via systemd timers (units + deploy wiring included)
- prompt: proactive next-move quick replies after completed actions

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

* feat(cat): demand-side verbs — follow, react, comment, bookings, inbox

follow_user/unfollow_user (@username resolution + courtesy notification),
like_post/comment_on_post, mark_notifications_read, book_service (provider
confirms), accept_booking/decline_booking. All registered, handled, and
auto-visible via the generated prompt catalog; email stack lazy-imported.

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

* feat(cat): autonomy ladder — per-action Off / Ask first / Automatic

cat_permissions already stored trust as two booleans; users think in three
levels. New cat-autonomy SSOT maps between them, the permissions API returns
each action's EFFECTIVE level (row → category → default, same resolution the
executor uses), and the settings screen replaces the binary switch with a
segmented control. High-risk actions never offer Automatic — enforced in the
API, not just hidden in the UI.

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

* refactor(cat): split entity handlers into create/manage modules

entities.ts hit 515 lines (500-line service limit) after create_circle. Split
along the natural seam — creating new things vs changing existing ones — with
entities.ts kept as the barrel so the handler map is unchanged.

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

* fix(cat): forgetting a two-word fact could delete an unrelated memory

The majority rule (ceil(n/2)) meant a two-word fact needed only ONE stem hit,
so 'photography skills' also deleted 'Has strong cooking skills' — they share
nothing but the stem 'skill'. Reproduced against the shipped code; this is
live data loss.

Multi-word facts now require TWO stem hits (requiredStemHits), single words
still match on one plus containment. Looser paraphrases ('speaking French' →
'Knows French') are handled by the semantic layer, which scores them 0.45+
while unrelated pairs stay <=0.29. Forget, suppression, and edit_memory now
share ONE matcher (stemOverlapMatches) so they cannot diverge.

Also fixes the capped quota chip: two nowrap links overflowed the toolbar on
phones and collided with the panel toggle. Capped state is now a single
shrinkable chip, and its copy moved into the CAT_UPSELL SSOT.

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

* feat(cat): interest discovery + real introductions

'I'm interested in longevity' now works end to end. Three things silently
blocked it:

1. The phrase matched NO trigger keyword, so the tool pass never ran and the
   whole discovery path was unreachable. Added interest/intro keywords.
2. research + ai_assistant + event were absent from the semantic corpus — a
   topic search could not surface the research literally about that topic.
   They index now (their public gate is is_public AND status, not status alone).
3. Index freshness had NO safety net: per-row DB triggers POST to a hardcoded
   public URL via pg_net and fail silently. Added /api/cron/reindex-embeddings
   + timer — the sweep the reindexer's own docs promised but never had.

explore_topic: semantic match across every indexed type, each hit re-read
through its public gate (index can lag), test rows excluded, owner resolved,
and — the key move — PEOPLE aggregated from entity ownership. Only 5 of 115
profiles have a bio, so people are discoverable through what they published,
not their profile text; each person carries the work that makes them relevant.
Degraded index reports honestly instead of implying the platform is empty.

request_introduction: opens a real conversation with an entity's owner and
sends the user's intro. High risk / always confirms — messaging has no block
list, so the confirmation is the consent gate.

Splits to stay under the service size limit: reindexService → +reindex-sources
+reindex-scoring; tool-executor → +tool-handlers-lookup.

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-04 16:33:07 +02:00
09923c2b8f feat(cat): Cat can read, remember correctly, act platform-wide, and speak first (#571)
* fix(cat): forget_memories now matches inflected forms and real similarity scores

Prod incident 2026-08-02: the user asked Cat to forget photography /
handmade ceramics / French / weekends-only; the model passed exactly those
phrases, the action completed — and every targeted memory survived.

Two dead layers:
- Lexical: exact-substring token matching can't see inflections
  (photography≠photographer, ceramics≠ceramic, speaking≠speaks) and the
  hard >=2-hit rule killed the rest. Now: light suffix-stripping stemmer +
  majority-of-significant-stems rule, stems compared by equality only.
- Semantic: floor 0.75 sat above what true targets score with
  text-embedding-3-small (measured against prod: 0.39-0.61, noise <=0.29).
  Now 0.45.

Also list exactly WHAT was removed in the displayMessage (not just counts)
so an over-match is visible and re-addable at a glance.

Regression suite pins the incident corpus + phrases.

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

* fix(cat): pre-flight skip for platform Groq when the prompt can't fit its TPM limit

Every Cat message in prod was paying a guaranteed-failing Groq round-trip:
the assembled prompt (memories + history + page excerpt) exceeds Groq's
on-demand 12k TPM limit, so the primary 413'd on every single message and
the reply always came from the OpenRouter fallback anyway (confirmed via
journalctl + a measured 413 against the platform key).

The chain now skips a PLATFORM Groq link up front when the prompt clearly
won't fit — only when another link can serve, never for BYOK Groq keys
(possibly a higher tier), and a pre-flight skip never marks the link down
globally (other users' smaller prompts still fit it).

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

* feat(cat): query_my_data read verb — Cat can now answer questions about the user's own live data

Listings, earnings, bookings, wallets, notifications, tasks (+ overview),
wired as a platform tool with trigger keywords, routing-prompt entry, chip
labels, and honest per-section degradation.

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

* feat(cat): memory CRUD + suppression — remember_fact, edit_memory, and forgotten facts stay forgotten

- cat_forgotten_facts table (+ match RPC, RLS) records what forget_memories
  deleted; passive extraction now skips suppressed candidates so a disowned
  fact can't be silently re-learned from old context
- remember_fact: explicit store, lifts matching suppressions, dedupes
- edit_memory: corrects exactly one memory or refuses with candidates
- prompt catalog + honesty rule updated for the three memory verbs

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

* feat(cat): every action visible + executable — generated prompt catalog, create_circle, drift guard

- system prompt now appends a machine-generated one-liner catalog for every
  enabled action without a prose section (13 verbs were invisible to the model)
- create_circle action + handler (last creatable type without a create path)
- action-registry-drift test: action↔handler↔prompt can never drift again

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

* feat(cat): proactive layer — memory notes with undo, daily brief, watches, next-step chips

- MemoryNoteCard: every new memory surfaces in chat as an undoable 'Cat noted'
  card (no more silent memory writes)
- /api/cron/cat-brief: data-only morning brief (sales, bookings, overdue,
  unread) for active Cat users, idempotent per day, skipped when empty
- /api/cron/cat-watches + cat_watches table + create_watch/cancel_watch verbs:
  'tell me when funding hits X / someone books me / next sale', checked every
  15 min via systemd timers (units + deploy wiring included)
- prompt: proactive next-move quick replies after completed actions

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

* feat(cat): demand-side verbs — follow, react, comment, bookings, inbox

follow_user/unfollow_user (@username resolution + courtesy notification),
like_post/comment_on_post, mark_notifications_read, book_service (provider
confirms), accept_booking/decline_booking. All registered, handled, and
auto-visible via the generated prompt catalog; email stack lazy-imported.

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

* feat(cat): autonomy ladder — per-action Off / Ask first / Automatic

cat_permissions already stored trust as two booleans; users think in three
levels. New cat-autonomy SSOT maps between them, the permissions API returns
each action's EFFECTIVE level (row → category → default, same resolution the
executor uses), and the settings screen replaces the binary switch with a
segmented control. High-risk actions never offer Automatic — enforced in the
API, not just hidden in the UI.

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

* refactor(cat): split entity handlers into create/manage modules

entities.ts hit 515 lines (500-line service limit) after create_circle. Split
along the natural seam — creating new things vs changing existing ones — with
entities.ts kept as the barrel so the handler map is unchanged.

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 19:58:13 +02:00
f3a649980b feat(ops): nightly data-invariant gate — test the rows prod has, not the rows mocks imagine (#574)
Every test in this repo runs against mocks, and that is precisely why the
shared-wallet disclosure shipped wrong three times today with a fully green
suite. The mocks encoded the data shape we assumed — one address per wallet
row, links pointing at live entities — while production held a different one:
the same address spread across 2 to 11 wallet rows, and 8 of 10 entity_wallets
links pointing at deleted entities. No amount of unit testing finds that class.
Only reading production does, so this puts the reading on a schedule.

Four invariants, each a claim the product makes to a user about their money:
- entity_wallets links point at entities that still exist (the orphan class
  fixed in #573 — this is its regression guard)
- no entity has two primary links (resolveLinkedEntityWallet has no tiebreaker,
  so duplicates make payment routing nondeterministic)
- every active wallet has some usable receiving rail
- every paid intent carries a settlement timestamp (status written outside
  claimPaidTransition is money-state divergence)

An unknown entity_type is reported rather than skipped, so a new entity type
cannot quietly opt out of the orphan check. A check that throws is recorded as
a finding — an exception must never read as "invariant holds".

Wired into deploy-selfhost.sh alongside the existing nightly gates, 05:00 UTC
so the three never overlap, with OnFailure notification like its siblings.

Verified against production both ways: passes clean on real data, and with a
deliberately inserted orphan row it correctly failed with exit 1 and named the
offending link (row removed afterwards; entity_wallets back to 2).

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 19:30:23 +02:00
c81266a6be fix(create): wallet selector for research/wishlist/circle + nightly outcome gate (#521)
* feat(cat): enforce BTC spend caps — per-action cap + daily budget

max_btc_per_action existed since baseline but was never read; every Cat
payment ignored it. Now enforced in CatPermissionService.checkSpendCaps
(stricter of specific-action and category caps wins), checked early in
executeAction and re-checked as a backstop in performAction so the
confirm-later path can't bypass a cap that changed after proposal.

- New max_btc_per_day column: daily BTC budget derived from
  cat_action_log.amount_btc (executing+completed rows; no new state)
- API: maxSatsPerAction renamed maxBtcPerAction — old name validated
  .int() but stored raw into the BTC column (a '100 sats' cap would have
  stored 100 BTC); caps now omitted=keep, null=clear so grant toggles
  no longer wipe limits
- Spending caps editor on the payments category row (semantic tokens,
  fiat equivalent via useDisplayCurrency)
- 12 new tests: pure cap-combination, service checks, executor wiring

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

* feat(api): machine-payable v1 payments — the agent buy loop

Closes the discover → quote → pay → verify loop under the /api/v1
contract. Discovery (entity list/get, /v1/search) already accepted
integration keys; payment creation and settlement polling did not.

- POST /api/v1/payments: dual-auth (ock_ keys with payments.write scope,
  or session), per-key rate bucket, wraps initiatePayment. Key callers
  are gated on the entity being anonymously visible so service-role
  writes can't reach non-public listings
- GET /api/v1/payments/{id}: settlement status (payments.read) —
  'paid' is verified against the receiving wallet, not claimed
- OpenAPI: payments paths registered, including the previously
  unregistered anonymous /payments/public flow; scopes + endpoints
  added to the public-api SSOT (discovery + key-minting UI pick them up)
- docs/api/AGENTS.md: the whole loop with curl examples; v1 README table
- knownPaymentErrors extracted (shared by internal + v1 routes)
- 8 tests: auth/scope/visibility gates + spec-generation pin

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

* fix(cat): surface spend-cap denial reasons on /api/cat/actions

Live E2E of the caps found the route flattening every denial to
'Action not permitted', hiding which cap tripped and what to change.
Denial reasons are derived from the user's own settings — safe and
meant to be shown.

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

* fix(create): wallet selector on research, wishlist, and circle create forms

Three entity types were registry-supportable (canReceiveSupport) but their
create configs had no wallet selector — supportable on paper, unpayable in
practice. research + wishlist were known (PR #504 follow-up); circle was
found by the new guard test, which asserts every canReceiveSupport entity
config exposes the WalletSelectorField group (never again this class).

Zero migrations: the selector's _wallet_id links via /api/entity-wallets
on the client after create, same as products/services.

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

* feat(ops): nightly Cat outcome gate on the box (04:45 UTC)

eval-cat-outcomes.mjs --gate as a systemd timer beside the judgment
eval — trips when assistant activity exists but zero actions were
logged (the dead-audit-pipeline tripwire). OnFailure wires into the
box's notify-failure@ Telegram alert. Units are repo-SSOT and shipped
by deploy-selfhost.sh; already installed and verified on bitbaum
(first run: proposed 1 → published 0 → funded 0, exit 0).

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-07-31 11:42:22 +02:00
1669da5604 docs(ops): vendor app systemd unit + launch.sh, add resilience runbook (#391)
Box-side resilience prep from the DevOps audit (advisory + SSOT artifacts —
zero runtime change; the founder applies the runbook steps box-side):

- Vendor the OrangeCat systemd unit + launcher into the repo (they lived ONLY on
  the box), so a fresh-box rebuild is a scripted install, not archaeology:
  scripts/systemd/orangecat-app.service, scripts/systemd/launch.sh (verbatim
  from the box; no secrets — env is externalized to .env).
- docs/operations/RESILIENCE.md — actionable, copy-paste runbook for the four
  proactive gaps: (1) single-box SPOF → scripted OC bring-up + publish RTO +
  optional warm standby; (2) off-site backups are deletable → B2 Object-Lock +
  non-delete key + off-box retention + ≥2 RESTIC_PASSWORD copies; (3) root
  deploy credential → non-root oc-deploy user with scoped sudoers; (4) the
  fleetcrown-owned backup pipeline dependency + the container-dump must-hold.

Full box-wide IaC stays in fleetcrown's shared hetzner toolkit (noted), not
forked here.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 09:11:49 +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