37 Commits
Author SHA1 Message Date
Cato d57afbeec1 feat(planner): a reminder tells you when it is due (in-app notification, no model call) (#1845)
The Cat's set_reminder stored a task with is_reminder and a due date, and
nothing read it at its time. A job every 5 minutes (api/cron/task-reminders,
systemd orangecat-cron@task-reminders.timer) now sends the owner an in-app
notification once (tasks.reminded_at), linking to the task. No model call.
2026-11-19 20:29:17 +01:00
Cato ab03ca70c3 fix(deploy): cap the app's V8 heap below its cgroup memory limit (#1784)
The app froze six times on 14-15 Nov with its main thread stuck in
__mem_cgroup_handle_over_high: memory sat at 790-850 MiB against the
unit's 768M memory.high, so the kernel throttled it instead of killing
it, and every stop needed SIGKILL. V8 sizes its heap from the machine's
RAM, not the cgroup, so it never ran a full collection before crossing
the throttle point. Run node with --max-old-space-size=512, self-healed
into the box launch.sh on each deploy like the header-size flag.
2026-11-15 07:33:59 +01:00
CatoandClaude 553d330843 feat(oauth): a client for every fleet sign-in page, given its secret on the box (#1523)
The owner's rule (2026-11-01): every fleet app offers every sign-in method,
"Continue with OrangeCat" included. Ten apps with a sign-in page had no
client: aoz-begleitung, biaslens, botsmann, diplodoctor, hirnli (on both
hosts), keller, kivvi, printcraft, reparaturbonus-zh and vitareba (vita and
vitareba hosts). They are now in client-specs.ts, identity-only.

Creating a client used to mean running register-client.ts on the box and
copying the printed secret by hand. Now the deploy's client SQL also creates a
missing row, switched off and with no secret: inert twice over (getClient
reads only enabled rows; verifyClientSecret rejects a null hash). loki
app-secrets.sh (kind oc-client, bitbaum/loki#1533) then writes the secret
into the app's env and its sha256 into the row, and switches it on, printing
neither. register-client.ts now mints a secret for such a row instead of
re-enabling it secretless.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 21:55:29 +01:00
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
Cato 741e908057 fix(deploy): stage and verify public package artifact receipts (#1456) 2026-10-27 23:12:21 +01:00
CatoandClaude Fable 5.1 cbf8296b92 feat(oauth): an app may list a service in your name — the fee of a builder booked through Loki (#1366)
* feat(oauth): an app may list a service in your name; the fee of a builder booked through Loki

Track 3 of Loki's docs/master-plan-2026-10.md, the OrangeCat half: a builder
booked on someone's project is paid through a service in the builder's own
name, listed by Loki with the builder's token, paid to the builder's wallet.

- `service.write` scope, sensitive, on the consent screen like timeline.write.
  Loki's ceiling carries it; every other client stays identity-only.
- CLIENT_SPECS moves to scripts/oauth/client-specs.ts (pure) so two readers
  share it: register-client.ts by hand, and the deploy, which now refreshes the
  scope ceiling of every REGISTERED client right after the migrations
  (client-scopes-sql.ts → box psql). It creates nothing: a missing client is
  still registered by hand, where its secret is printed once. A scope widened
  in the code used to reach the live sign-in only when someone re-ran the
  registration on the box.
- createService honours a validated `active` status (a fee Loki lists has
  nobody to press Publish); paused/unavailable still cannot be created.
- The settled-payment signal to Loki fires for a service bought outright, not
  only for project funding, so the booking is marked paid from the payment.
- product, service, cause and document creates carry the resolved actor
  (withResolvedActor): a type argument on createEntity<Row>( had hidden these
  four from the check that pins the carrier; the check now sees past it.

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

* fix(ci): align the playwright CLI with @playwright/test so the browser install matches

#1362 bumped @playwright/test to 1.64.1 and left `playwright` at 1.62.1, so
`pnpm exec playwright install chromium` fetched 1.62.1's browser while the
test runner looked for 1.64.1's headless shell (1248): build-and-smoke has
been red on main since, and on every PR. One package, one version.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-20 13:07:41 +02: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 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
Cato 10bd7ef099 fix(ci): reuse verified bundle and skip duplicate deploys (#1115) 2026-09-23 02:42:03 -07:00
CatoandClaude Opus 5 3e6c202c59 refactor(config): the deploy target is configuration, not a literal (#1061)
Three hardcoded things in a public repo, each of which is someone else's
value baked into the source.

The box address had a literal fallback in five places: the CD workflow and
four operational shell scripts. A fallback literal guarantees the variable
is never exercised — if the variable were missing or wrong, every run would
still succeed against the baked-in address and nobody would find out until
the address changed. So:

  - cd.yml takes the address from vars.OC_BOX, or root@ the HETZNER_IP
    variable, and a new guard step fails the run with ::error:: when the
    result is empty. The ssh-keyscan and ssh-config host now derive from
    the host half of OC_BOX instead of repeating the literal, so the two
    cannot drift apart silently.
  - apply-migrations.sh, db/dump-live-schema.sh, db/gen-types.sh and
    deploy-selfhost.sh use ${OC_BOX:?...}: they stop with one clear line
    instead of reaching for a default. The two of them invoked by the
    deploy script are already passed OC_BOX explicitly, and the workflow
    sets it in the job env, so the configured path is unchanged.

An audit log was committed under logs/ in 2025-10 with 14 absolute paths
from a developer's machine. Nothing in the repo reads it (the only mentions
of the filename are inside the file itself). The `logs/` ignore rule was
added five days after the file, so it never applied to it — removed, and
the rule now says why, because ignoring a directory does not untrack what
is already inside it.

scripts/db/setup-db.ts signed in as a personal email address written into
the source. It now reads USER_EMAIL, matching the USER_PASSWORD it already
read, and exits with a clear message when unset.

Verified: bash -n on all four scripts and each one run with OC_BOX unset
(exit 1, clear message); the workflow parses and the guard step is in
place; pnpm run type-check:scripts green; prettier clean; the two unit
tests that read deploy-selfhost.sh pass.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 01:07:48 -07:00
CatoandClaude Opus 5 474caac67d feat(deploy): record which commit is serving (#1045)
"What is live?" was an inference. The deploy now writes
/opt/orangecat/app/.release — sha, ref, deployed_at — so it is a fact:

    ssh ubuntu@167.233.22.31 'cat /opt/orangecat/app/.release'

WRITTEN INTO THE STAGING TREE, which is the part that matters. It rsyncs with
the release and swaps atomically with it, so there is never a window where the
directory and the marker disagree. And a rollback restores the right marker for
free: `app-old` carries its own .release from when IT was deployed, so
`mv app-old app` moves the truth back with the code. A marker written after the
swap, or kept outside the release dir, would survive a rollback and then lie
about what is running — which is worse than having none.

The gap it closes, from today. Verifying a deploy meant grepping the built
bundle for a string the change happened to introduce, and that works by luck
rather than by construction. It ran out twice:

  - a refactor that adds no new literal is unverifiable that way — #1042 moved
    code between modules and introduced no new string, so there was nothing to
    grep for, and chunk CO-LOCATION does not discriminate because the strings
    that moved were already bundled together;
  - a literal that already existed elsewhere gives a FALSE POSITIVE —
    `qwen/qwen3.8-27b` "confirmed" a deploy that had not happened, because that
    id was already sitting in an unrelated map.

Degrades to `unknown` rather than to an empty file. An empty marker reads as a
blank truth; absent data should look absent — the same three-state discipline
the catalogue check applies to "could not look" versus "nothing is there".
GITHUB_SHA in CI, the working tree's HEAD for a local deploy, `unknown` when
neither is available. All three paths exercised before committing.

Verified by mutation, control green:
  marker written AFTER the swap (a rollback would then lie) -> 1 test fails
  empty fallback instead of `unknown`                        -> 1 test fails
  rsync excludes the dotfile, so it never leaves the host    -> 1 test fails

3063 unit tests pass across 347 files (5 new), type-check clean, bash -n clean.

Not a fix for the pipeline, which turned out not to need one: merge to live
measured 7-8 minutes consistently today, and the `cancelled` runs that prompted
this are the re-arm working as designed — a GITHUB_TOKEN push cannot trigger
workflows, so the sweep dispatches CI explicitly and concurrency cancels the
redundant twin. This is about being able to ANSWER the question, not about
anything being broken.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 03:20:04 -07:00
CatoandClaude Fable 5.1 9a352d3646 refactor: rename FleetCrown to Loki across the integration (#1016)
The sibling product was renamed on 2026-09-14. Every reference follows:
service and route paths (src/services/loki, /api/integrations/loki),
env keys (LOKI_*), the build-intent audience and timeline source ('loki'),
ecosystem config, docs, tests, and 13 file names.

Tool labels keep "Loki" capitalised: the old name had an internal capital
and passed the "looks like a name" shape test for free; a one-word name
needs listing, so softLower now carries a small PROPER_NOUNS set.

Box and data were moved ahead of this: LOKI_* keys sit beside the old ones
in the app env, the OAuth client is `loki` with the new callback host, and
timeline/metadata rows carrying the old name were rewritten.


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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:40:27 -07:00
CatoandClaude Fable 5.1 0e450e9173 fix(deploy): ship every eval script sibling, so a new one cannot break the timer (#968)
#967 added scripts/eval-rate-limit.mjs and made eval-cat.mjs import it. The
deploy copied eval scripts to /opt/orangecat/scripts by a hand-written list of
three files — right under a comment warning "eval-cat.mjs imports this next
to itself — ship them together or the timer breaks". The new file was not in
the list. After the deploy of e2f87798 the box had the NEW eval-cat.mjs
importing a sibling that was not there; the nightly orangecat-cat-eval timer
would have crashed on import at 04:30 UTC with a harness error. Found by
checking the box after deploy, repaired by hand (install -m 644) for tonight.

The list is now one glob, scripts/eval-*.mjs — a glob cannot forget a file —
and __tests__/unit/scripts/eval-siblings-shipped.test.ts pins the class: the
glob must be present in the deploy script (comments stripped, so a mention
cannot satisfy it), and every relative import of every eval script must be a
sibling the glob covers. Mutation-proved: hand list restored → red; glob left
only in a comment → red; an import of a non-eval-named sibling → red.


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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 00:30:05 -07:00
CatoandClaude Opus 5 4740894792 fix(deploy): ship the standalone tree as a tarball so its symlinks survive (#915)
CD failed on 4fda8351 with `Cannot find module
'@swc/helpers/_/_interop_require_default'`, and succeeded on 817bdf60 from the
same workflow and the same artifact path. The difference was not in the code.

Next's standalone output under pnpm is a symlink farm. `node_modules/next` is a
link into `node_modules/.pnpm/next@…/node_modules/next`, and next's peers —
`@swc/helpers` among them — are linked in as its SIBLINGS there. Node resolves
the peer by walking up from the real path, so the link is not a convenience;
it is the resolution mechanism.

upload-artifact takes a directory and does not reliably preserve links. When it
dereferences, `next` is materialised as a real directory at
`node_modules/next`, which lifts it out of the directory where its peers live.
The `@swc/helpers` store entry still ships. Nothing can reach it.

Measured on the box, same workflow, consecutive deploys:

  live release (booted):   137 symlinks, node_modules/next -> .pnpm/next@…
  failed release:            0 symlinks, node_modules/next a real directory

and booting the failed tree by hand reproduces the error exactly, with the
require stack terminating at next/dist/shared/lib/constants.js.

tar records links as links, so the tree arrives byte-identical and the variable
is gone rather than merely less likely. Three changes:

- CI packages `.next/standalone` into a tarball and uploads that.
- CD unpacks it and ASSERTS the tree still contains symlinks. A pnpm standalone
  always has them; zero is not a warning, it is this bug. It fails there,
  one line from the cause, instead of forty minutes away in a boot test on the
  box — and deliberately does not fall through to a rebuild, because a silent
  rebuild ships green and leaves the artifact path broken forever.
- The boot test greps the cause BEFORE the tail. Node prints the one line that
  identifies the failure first, then a stack that runs well past twenty lines,
  so `tail -25` kept everything that identifies nothing and cut the only line
  that mattered.

Note CI's existing "Start server (standalone)" step could not have caught this:
it runs against the local tree, before the artifact round-trip, so it passes on
a tree that is not the one shipped.


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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 04:31:55 -07:00
CatoandClaude Fable 5 b867d9ed45 feat(longform): one pipeline — bip-kit typed blocks render blog + articles (#913)
* feat(longform): one pipeline — bip-kit typed blocks render both the blog and community articles

OrangeCat had two long-form stacks: /blog/[slug] compiled content/blog/*.mdx
through @next/mdx with a bespoke component map, and /articles/[slug] rendered
DB markdown through react-markdown + remark-gfm + rehype-sanitize in a ~90-line
ArticleMarkdown. Both now parse through bip-kit v0.2.1's typed-block parser and
render through its reference renderer (ArticleBody), themed onto the semantic
token tier via a route-scoped --bp-* mapping (src/lib/longform/longform.css).

- src/lib/longform/ is the ONE pipeline: normalize (bullet aliases, h1→h2,
  flatten nested items) + parse (blocks, TOC, reading time), server renderer
  (LongformBody: shiki via setHighlighterLoader, MermaidBlock override), and
  the composer's client preview (LongformPreviewBody — same blocks, honest
  no-shiki fallback).
- The 10 blog .mdx files become plain .md; the only body edit is dropping the
  first-line `# title` that duplicated the frontmatter title the page header
  already renders (word-level parity verified for all 10 files and all 9 live
  DB articles — zero content loss).
- Typed blocks are the security model for user-authored article bodies: no
  HTML passthrough exists, so rehype-sanitize is unnecessary by construction.
  Deleted: ArticleMarkdown.tsx, the MDX component map (incl. the unused Alert/
  SecurityFeature components — no content ever referenced them), the bespoke
  ReadingProgress (bip-kit's island replaces it).
- New on BOTH surfaces: sticky scroll-spy TOC, heading anchors, server-side
  shiki dual-theme highlighting, figures/galleries with Lightbox, GitHub
  callouts, mermaid diagrams, pull quotes, footnotes, video embeds.
- Deps: + bip-kit@^0.2.1 (minimumReleaseAgeExclude: ours, inside the window),
  shiki, mermaid; − @next/mdx, @mdx-js/*, next-mdx-remote, react-markdown,
  remark, remark-gfm, rehype-sanitize.
- next.config.js: withMDX gone; `turbopack: {}` acknowledges Turbopack (Next
  16 makes a webpack-only config a FATAL build error once @next/mdx no longer
  supplies the turbopack key — the failure mode is an opaque WorkerError).
- deploy-selfhost.sh links standalone node_modules/shiki from the traced
  .pnpm store entry (FleetCrown #513 trap: tracing copies the store files but
  never the top-level symlink; without it prod silently loses highlighting).
- check:mdx → check:content: the verify gate now parses every content/**/*.md
  with the same bip-kit pipeline the site renders with, and refuses stray
  .mdx files.

Verified: SELF_HOST=1 standalone build green; standalone smoke shows
bp-article/bp-toc/bp-progress + bp-codeblock-highlighted with dual-theme
--shiki-light/--shiki-dark spans; full 21-check verify green (2704 unit tests).

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

* fix(longform): delete the root mdx-components.tsx — dead with the MDX pipeline

Next.js only consults this file through @next/mdx, which is gone; with
@types/mdx removed it fails tsc in CI's clean-room worktree (locally a stale
virtual-store copy of mdx/types still resolved, hiding it).

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

* chore(sizes): drop the blog page's stale size exception — the ratchet tightens

The bip-kit migration deleted the ~100-line inline MDX component map, putting
/blog/[slug]/page.tsx back under its limit.

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

* chore(type-scale): baseline 13 → 12 — the bip-kit migration removed an arbitrary font size

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-07 11:16:19 +00:00
30f6d45216 chore: pnpm — the fleet has one package manager (#889)
* chore: pnpm — the fleet has one package manager

- packageManager pnpm@11.25.0; lockfile via pnpm import, package-lock.json
  removed
- npm "overrides" moved to pnpm-workspace.yaml overrides (pnpm ignores the
  npm-only package.json field); nested gray-matter>js-yaml pin kept; $sharp
  reference spelled out (pnpm 11 deprecates $ syntax)
- allowBuilds for native/postinstall deps; temporary minimumReleaseAgeExclude
  for our own @bitbaum/ai-kit@0.6.2 (published <24h ago — pnpm 11's
  supply-chain window would refuse it)
- postinstall dropped: it was the npm optional-deps sharp workaround
  (npm/cli#4828); pnpm resolves optional deps correctly
- CI/CD/e2e-auth workflows: pnpm/action-setup@v6, store-dir pinned outside
  the action's bin dir, cache: pnpm, frozen-lockfile installs, pnpm run;
  Next cache key now hashes pnpm-lock.yaml; npm audit → pnpm audit --prod
- phantom deps declared: espree (eslint.config.mjs) and @mdx-js/mdx
  (scripts/check-mdx.mjs), previously resolved via npm hoisting only
- package.json scripts, husky hooks, deploy-selfhost.sh converted to pnpm

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

* fix: another phantom dep only the CI clean room could see

@radix-ui/react-visually-hidden (CommandPalette.tsx) resolved locally through
the parent repo's hoisted npm node_modules. Declared; a full src/ bare-import
sweep against package.json now reports no other undeclared specifier.

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

* fix: declare wait-on — npx fetched it on the fly, pnpm exec requires it

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

* fix(ci): security job — no install means no pnpm store, so no cache to save

The audit step itself passed (2 moderate, below the high gate); the job went
red in setup-node's POST step, which fails when the cache path it was told to
save (the pnpm store) was never created. This job only needs the lockfile.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-04 10:47:14 +00:00
07885c971b fix(deploy): boot-test cleanup used pkill -f, which cannot match a Next server (#832)
Found 2026-08-29 auditing the box for services bound to 0.0.0.0: a leaked
boot-test instance was squatting on port 4099, actively serving 500s from
a stale build, with no systemd unit, no owner, alive since an earlier deploy.

Root cause, verified with an isolated reproduction (not just reasoned about):
Next's standalone server rewrites its own process title to "next-server
(v...)" during startup, and — confirmed by reading /proc/PID/cmdline
directly, both on the box and in a minimal local repro — that rewrite
changes the process's actual argv as seen by /proc, not just what `ps`
displays. `pkill -f 'app-next/server.js'` matches against that same argv,
so once the server finishes booting (routinely before this line runs, since
the health-check loop above can take up to 20s), there is nothing left
containing "app-next/server.js" to match. Confirmed both directions in the
repro: pkill -f fails to kill a title-rewritten process; fuser -k on the
actual bound port kills it every time.

This is not cosmetic. A leaked boot-test process on $OC_BOOT_PORT silently
threatens every subsequent deploy: the next boot-test's own health check can
hit the STALE process instead of the new build, or fail outright on a port
collision — either way, a deploy could report success (or a confusing
failure) without ever having actually tested the new code.

Replaced with `fuser -k "$BOOT/tcp"` — kills whatever is actually listening
on the scratch port, independent of what the process calls itself.


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 08:16:01 +02: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
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
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
f3e59bd201 perf(ci/cd): build the shippable standalone once, ship that exact artifact (#393)
Reproducible-artifact (tested == shipped) + drop CD's rebuild. Built defensively
so it can never break deploys.

CI (ci.yml):
- Build the SELF_HOST=1 standalone (not the default output), baking the same
  client env CD bakes (adds NEXT_PUBLIC_LIGHTNING/BITCOIN vars for parity).
- Assemble static + public into the standalone tree, then run E2E against
  `node .next/standalone/server.js` — the EXACT entrypoint CD ships, so CI now
  tests the shipped bundle, not a different `next start` build. (Validated
  locally: standalone server Ready in 405ms, / -> 200, /api/health -> healthy.)
- Upload the assembled standalone as an artifact on main pushes.

CD (cd.yml):
- Download that artifact from the triggering CI run and deploy --no-build,
  removing the second ~7-min build. If the download fails, or it's a manual
  workflow_dispatch with no CI run, fall back to building. So a broken artifact
  path degrades to today's behavior; it can never break a deploy.

deploy-selfhost.sh: the static/public assembly step now skips missing sources,
so a pre-assembled downloaded artifact deploys cleanly (a fresh build still
assembles as before).

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:36:04 +02:00
6ed1d1a15c chore(deploy): harden deploy gates, enforce migration safety, speed CI (#389)
Pipeline-reliability batch of the DevOps overhaul:

- deploy-selfhost.sh schema-drift gate no longer fails OPEN: the live-schema
  dump is retried, and if the box schema truly can't be read we BLOCK rather
  than deploy unguarded (every later step needs ssh anyway, so it's not a
  benign hiccup).
- deploy-selfhost.sh keeps the previous release at app-old until the next
  deploy, giving a manual-rollback target between deploys (it was deleted on
  success, leaving none). Deliberately NOT auto-rolling-back on a failed public
  health check: local health already passed, so a public failure is Caddy/DNS,
  and reverting a healthy app wouldn't fix it.
- New expand/contract gate: scripts/db/check-migration-safety.mjs flags
  unacknowledged contract-phase DDL (DROP/RENAME/TRUNCATE/type-change) in
  changed migrations, run as a fast job in migration-replay.yml. Auto-rollback
  reverts code but not an applied migration, so a destructive migration the
  previous release still uses breaks rollback — acknowledge intentional ones
  with "-- migration-safety: contract-ok <reason>".
- ci.yml: concurrency group (cancel superseded runs so only the newest commit's
  CI+CD proceed) + Next.js .next/cache reuse across runs for faster builds.

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-07 20:20:13 +02:00
G 78d9a7fe8d Merge pull request #384 from maonakamoto/ops/cat-eval-harness
ops(cat): nightly eval harness with alerting
2026-07-03 20:55:36 +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
Georgy ButaevandClaude Fable 5 6cff710873 ops(migrations): extract auto-apply into scripts/apply-migrations.sh SSOT
The deploy path already applied pending supabase/migrations/*.sql inline in
deploy-selfhost.sh; this promotes that block to a standalone, hardened SSOT
script and documents the whole migration story.

scripts/apply-migrations.sh:
- ensures public.schema_migrations (filename PK, applied_at) exists
- --backfill bootstrap mode (record all current files as applied, run nothing)
  + a guard that refuses a full replay when the tracking table is empty but
  core app tables exist
- applies pending files in filename order, each in a single transaction
  (psql -1 -v ON_ERROR_STOP=1), records only after success, aborts non-zero
  on first failure with the failing filename
- --dry-run lists pending without changing anything
- integrity-checked tracked-list fetch (count vs rows in one psql call) +
  per-file DB recheck before executing — a truncated list over ssh once made
  an already-applied 2025 file look pending and re-execute against prod
  during live testing of this script (harmless: CREATE OR REPLACE only)
- all SQL travels via stdin, never -c, killing nested-quoting across
  shell→ssh→docker-exec

deploy-selfhost.sh delegates to it before the boot-test/swap; a migration
failure still aborts the deploy loudly with the live release untouched.
cd.yml already runs deploy-selfhost.sh --no-build, so merged migrations
auto-apply on every deploy — no workflow change needed.

Live-tested against the box: dry-run 0-pending after reconcile (162 tracked
== 162 files), no-op migration applied+recorded+cleaned, failing migration
aborted exit-1 without being recorded.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 19:54:37 +02:00
Georgy ButaevandClaude Opus 4.8 b0358d360e feat(deploy): schema-drift gate — fail deploy on code↔box DB drift
The deploy already auto-applies pending migrations, but that's necessary-not-
sufficient: the box can still lack an object the code needs — a migration
backfilled-as-applied-but-never-run (the ai_conversations outage), or a manual
change. Until now that surfaced as silent prod 500s. This makes drift loud.

- scripts/db/dump-live-schema.sh — dump the box's REAL public schema (incl.
  views) as the { table: [cols] } JSON the auditor consumes.
- scripts/db/audit-schema-drift.mjs — (1) accept a schema path via
  LIVE_SCHEMA_PATH so it can run against a fresh box dump, not just the stale
  committed snapshot; (2) NEW missing-table check — a resolvable `.from()` to a
  table absent from the live schema is now flagged instead of silently skipped
  (the exact gap that hid the ai_conversations drift).
- scripts/deploy-selfhost.sh — after applying migrations and BEFORE the swap,
  dump the live schema and run the auditor against it; abort the deploy on drift
  (live release untouched). Dump failure is non-fatal (no blocking on ssh flake).
- scripts/db/live-schema.json — refreshed from the box (104 tables/views).

The check surfaced a real backlog: 14 tables the code queries are MISSING on the
box (group_invitations, project_support(_stats), project_updates, research_*,
contracts, user_presence, typing_indicators, audit_logs, loan_collateral,
channel_waitlist, wallet_ownerships) — those features 500 in prod. Allowlisted as
documented KNOWN DRIFT in the auditor so the gate stays green for the backlog
while failing on any NEW drift; remediation = apply each create migration.

Also fixes a bug this check caught in new code: assistant-charge bumped
ai_assistants.total_messages, which isn't a column on the box (only total_revenue
is) — that update silently failed; now only total_revenue is bumped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 16:46:08 +02:00
Georgy ButaevandClaude Opus 4.8 d2d38248b1 fix(deploy): apply migrations in a single transaction (-1) to prevent partial apply
A stale, out-of-order migration (20260404000001) that drops a view then later
references a since-renamed column (amount_sats → amount_btc) half-applied under
ON_ERROR_STOP: it dropped the live enriched_timeline_events view, then failed
before recreating it — a real prod regression (timeline view missing) even though
the app release stayed untouched. Adding psql -1 wraps each migration in
BEGIN/COMMIT so any failure rolls the whole file back; the schema is never left
half-applied. Verified no migration uses CREATE INDEX CONCURRENTLY, so single-
transaction mode is safe for the whole set.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 02:26:40 +02:00
Georgy ButaevandClaude Opus 4.8 56c231872f fix(design+infra): eliminate /400 opacity leaks + auto-apply migrations on deploy (P0)
Design: the `bg-surface-raised/400` class (Tailwind opacity caps at /100, so it was
silently dropped) appeared 11×. Where paired with text-white it was invisible in light
mode (blog filter chips, own-message bubble) → switched to the inverting
bg-fg-primary/text-fg-inverted pill. The rest (badges, dots, progress, a /400/10 double
typo, a raw hover:bg-gray-600) → valid semantic classes. Site-wide invalid-opacity
count now 0.

Infra P0 (the migration-drift root cause behind this session's 500s): the self-host had
NO migration tracking, so the box drifted from supabase/migrations/* and I hand-psql'd
~10 fixes. Now: a public.schema_migrations table (backfilled with the 147 existing
migrations) + deploy-selfhost.sh applies any unrecorded *.sql to the box, in order,
before boot-test, ON_ERROR_STOP + abort-on-fail. No more manual migrations or silent drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 18:08:13 +02:00
Georgy ButaevandClaude Opus 4.8 424586b16e fix(deploy): raise Node max-http-header-size to 64KB (Brave 431 on big cookie jar)
orangecat.ch failed in Brave with HTTP 431 (Request Header Fields Too Large).
Cause: the standalone Node server caps request headers at the default 16KB, and a
browser that has accumulated many sb-* Supabase auth cookies (from repeated login/
test cycles) sends a Cookie header past that → hard 431. Chrome had fewer cookies,
so it was Brave-only. Reproduced: 20KB cookie → 431, 8KB → 200.

Fix applied live on the box (launch.sh now runs `node --max-http-header-size=65536
server.js`; restarted — 20KB & 40KB cookie headers now 200) and made durable here:
the deploy guard re-asserts the flag on the staged launch.sh every deploy (idempotent).

Follow-up worth tracking: WHY the cookie jar grows so large (stale/chunked auth
cookies not cleared) — raising the cap handles realistic sizes but the accumulation
itself may be a separate bug.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 22:07:02 +02:00
Georgy ButaevandClaude Opus 4.8 b805e32a9a fix(deploy): evict stale HTTP/3 cache in Brave via Alt-Svc: clear
orangecat.ch opened in Chrome but hung in Brave. Root cause: the box serves
h1/h2 only (no UDP/QUIC listener) but ufw allows 443/udp, so a Brave instance
holding a STALE cached `alt-svc: h3` (from an earlier deploy when h3 was on)
fires QUIC at a dead UDP port and hangs retrying instead of falling back to TCP.
The existing `protocols h1 h2` guard stops NEW h3 advertising but cannot undo a
cache that was already set — which is why Brave kept failing after that fix.

Applied live on the box (orangecat.ch block now sends `Alt-Svc: clear`, validated
+ caddy reloaded, health 200) and made durable here: deploy-selfhost.sh's caddy
guard now asserts BOTH protocols-h1-h2 AND `header Alt-Svc "clear"` on every
deploy (idempotent, single backup, validate-or-restore). `Alt-Svc: clear` tells
any browser to drop cached alternative-service (h3) entries → Brave stops trying
QUIC and uses h2.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:59:52 +02:00
Georgy ButaevandClaude Opus 4.8 3262fdc31c fix(deploy): self-heal Caddy HTTP/3-disable so the site stays usable in Brave
Recurring bug: Caddy defaults to advertising `alt-svc: h3` (cached 30 days).
Brave honours it aggressively and hangs when QUIC/h3 is flaky (SSE over h3 was
timing out on the box) — the site "won't open in Brave" while Chrome falls back
to h2. The cure is a global `{ servers { protocols h1 h2 } }` block, but the box
Caddyfile is hand-maintained and the block has been dropped when the file was
rewritten — so the fix kept regressing.

deploy-selfhost.sh now re-asserts the global block idempotently on every deploy
(validate-before-reload, install -m 644 so the caddy user can read it — the
permission-denied trap that breaks `systemctl reload`). Future rewrites that
drop it self-repair on the next deploy.

Live Caddyfile already fixed + reloaded on the box; this versions the cure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:35:14 +02:00
Georgy ButaevandClaude Opus 4.8 ddc67a50dc fix(ci): make type-check reliable + fail-fast — and fix project_roles casts
The project_roles build failed at deploy on a TS2352 that `npm run type-check`
and a manual `tsc --noEmit` both reported as clean — because tsconfig has
`incremental: true` and, under concurrent builds (revampit/FleetCrown running
tsc/next simultaneously), tsc trusted a stale .tsbuildinfo and skipped
re-checking the new file. The error only surfaced after a ~7-min `next build`.

Root-cause fixes so a type error can't reach deploy undetected again:
- type-check is now NON-incremental (`--incremental false`) → deterministic; the
  incremental cache is a dev-speed optimization that can't be trusted as a gate.
- pre-push now runs type-check BEFORE tests (it previously ran only unit + e2e,
  so `git push` never type-checked).
- deploy-selfhost.sh runs type-check (~30s) BEFORE the ~7-min build → fail fast.

Also fixes the actual error: postgrest-js infers the `projects(...)` embed as an
array type, but the to-one embed is a single object at runtime, so the
`as ProjectRole[]`/`as ProjectRole` casts now route through `unknown` (runtime
unchanged).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 09:07:37 +02:00
Georgy ButaevandClaude Opus 4.8 24e958e290 ci(deploy): version OrangeCat's self-host deploy verb + dormant CD
OrangeCat is a hand-rolled snowflake on bitbaum (not in fleetcrown's apps.conf,
no push-deploy hook) so it was the only fleet app still deployed by hand — its
safe atomic-swap+rollback flow lived only in the runbook prose + ad-hoc SSH.

- scripts/deploy-selfhost.sh: the deploy verb, committed. build → assemble →
  rsync to staging → boot-test on :4099 → atomic swap (keeps app-old) → restart
  → health-check → auto-rollback → verify public. Proven flow from the runbook.
  Safer than fleetcrown/scripts/hetzner/deploy.sh (which rsyncs over the live
  tree with no rollback) — that pattern should be promoted into the shared verb.
- .github/workflows/cd.yml: GH-Actions CD after green CI, builds standalone
  off-box (the box OOMs on build) and ships via the script. DORMANT by design —
  every step gated on the SELFHOST_SSH_KEY secret, so merging is a safe no-op
  until deploys are opted into.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 16:27:27 +02:00