Files
CatoandClaude 3857c7ae79 docs(agents): one AGENTS.md — fold verified rules in, delete the rest (#1859)
AGENTS.md is now the only repo-specific instruction file. CLAUDE.md and
.claude/CLAUDE.md are one-line pointers. Deleted: .claude/rules/* (6
files), .cursor/rules/* (7), docs/api/AGENTS.md (its machine-buyer
walkthrough moved into src/app/api/v1/README.md), .claude/README.md
(described the deleted layout) and the archived
docs/archive/development/guides/AGENTS.md.

Every rule kept was checked against the code. The deploy and verify
sections no longer describe GitHub Actions (off since 2026-11-15):
forge/verify merges, forge-ops on Gitea deploys. Ownership and money
lines corrected: owner column from getUserIdField, entity prices in
their own currency.

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-28 20:56:48 +01:00

22 KiB

AGENTS.md

Org rules

Read bitbaum/fleet AGENTS.md, SHARED.md and the registers it names before inventing a host, a name, a page or a shared behaviour. Do not copy their facts into this file.

  • Packages first. If a @bitbaum/* package (or bip-kit, limitkit, threadkit, ai-forms) already does it, use it and fix a defect in the package, not in this app. Every chat is @bitbaum/chatkit, every search box @bitbaum/searchkit, every chart @bitbaum/chartkit, accounts @bitbaum/accountkit, model calls @bitbaum/ai-kit. Review this product's package-plan.json before building anything. When a second product needs what one product built (a map, a globe, a calculator), extract it into a package before writing the second copy.
  • The experience belongs to the package. Anywhere a person types words there is a microphone (@bitbaum/chatkit: Composer, DictationField); articles are @bitbaum/writingkit/react, comments are chatkit's CommentThread, header, menu, tab bar and footer are @bitbaum/sitekit. Apps own brand, words and backend, not the behaviour or the layout. If a component cannot do what the product needs, extend the package in the same session (fleet AGENTS.md, "The experience belongs to the package").
  • A gap is a task, not an answer. Never end the work, or a reply, at "not supported" or "not available". When a source cannot be read or a case does not fit the model, find another way (another format or publisher, the official tool measured, the model extended) and do it. What truly cannot be done yet is tracked with its plan, never presented as a limit of the product.
  • Every page leads to an action. What a reader learns, they can act on from the same screen: file, pay, apply, compare, ask, contact.
  • One shape per kind. Things of the same kind look the same and sit in the same place (fleet AGENTS.md, "One shape per kind").
  • Finished work ships by itself. Open a non-draft pull request; the fleet forge merge check (forge/verify) is the only merge path. Never merge by hand, through the merge API, with --auto or with an admin bypass, and never force-push a shared branch.
  • Nothing made up. A fact on a page or in a doc needs a source that was opened; where there is none, the line is removed or softened. A gap is filled with sourced data, never with a guess.
  • Bitcoin orange is for Bitcoin and top-of-funnel actions only.
  • No model identifier in anything pushed to a repository.
  • Before you finish, run node <fleet>/scripts/ci/docs-truth-audit.mjs --dir .: the same check the sweep runs on every pull request.

Operational guide for any coding agent working in this repo. CLAUDE.md points here; this file is the source.

What this is

OrangeCat — an AI-native platform for universal economic and governance participation ("My Cat" AI agent: earn, fund, lend, invest, govern in any currency). Bitcoin/Lightning native. In one sentence: your AI economic agent, and the platform where it operates.

Loki is a live customer here (a typed "customer" stakeholder edge and a shared BTC wallet): changes to stakeholder relationships or project profiles change Loki's experience and every later customer's.

Principles

  1. The Cat is the interface. "My Cat" is every user's and group's primary agent; entities are the structured context it reads and acts on. Ask of a feature: does it serve the Cat, a human by hand, or both? Prefer both.
  2. Pseudonymous by default. Real identity is opt-in; any pseudonymous actor is a full economic participant.
  3. Any currency. Bitcoin/Lightning is native and preferred; Twint, PayPal, bank transfer and regional rails are first-class. Payment fields support any method — a wallet is one kind of payment method. The rails are SSOT in src/config/payment-methods.ts, built on identity, custody and reach (docs/architecture/MONEY_RAILS.md); listing a fiat rail is the opt-in to real identity, and a handle can be on_request instead of printed.
  4. The full economic spectrum — gift, loan, investment — belongs here.
  5. Private where needed, transparent where chosen. E2E-encrypted messaging and Nostr are on the roadmap, not shipped: direct messages are stored as plaintext today. Never describe messaging as encrypted until it is; build it with encryption and Nostr in mind.
  6. Entities are the Cat's world model.

What an entity is

An entity is anything that can hold a wallet and is better for holding one — a test, not a list. Each sits on three planes, whose one-word roles are SSOT in src/config/ecosystem.ts → ECOSYSTEM_PILLARS: economy (OrangeCat — hold, receive, send value), governance (Solon — decisions put to a signed vote) and execution (Loki — worked on, built, shipped). What separates them is audience: OrangeCat is public by design, Loki private by default, Solon shared with its members; work crosses when it needs to be seen, paid or decided on.

The list has one producer: ENTITY_TYPES in src/config/entity-registry.ts. Every type carries wallet: { holds, why }, the admission test answered in the owner's terms, enforced by __tests__/unit/config/entity-admission.test.ts. wallet and document are the two pinned exceptions (a ratchet that may shrink, never grow). Never copy the list into a doc.

Stack

Layer Technology
Framework Next.js 16 (App Router), React 19, TypeScript 6
Styling Tailwind CSS 4 (tokens are CSS vars in src/app/globals.css)
Database Self-hosted Supabase (Postgres + Auth + RLS) at supabase.orangecat.ch
Bitcoin Lightning Network, BTCPay, NWC
Deployment Self-hosted on Hetzner (bitbaum, behind Caddy) — no Vercel

Run it

pnpm install --frozen-lockfile # install (pnpm only — never write a package-lock.json)
pnpm run dev -p 3020           # dev server on :3020 (avoids conflicts)

Verify before you commit (single source of truth)

pnpm run verify

verify is the ONE gate. scripts/verify.mjs is the list of what it runs (type-check, lint, audit:routes, test:unit and the check:* guards, in parallel lanes) — read it there rather than a copy. The forge merge check (forge/verify) runs this same verify on the PR's merge result, so green locally ⇒ green check. Add or remove a check in the verify script only. (E2E/Playwright is a separate gate; it needs a running server + secrets and is not part of verify.)

Database & migrations

  • SSOT is the self-hosted Supabase on Hetzner (supabase.orangecat.ch). The managed Supabase Cloud project is retired — do NOT use it or the Supabase MCP.

  • Migrations live in supabase/migrations/*.sql. Immutable once applied — never edit an existing one; always add a new file. Migrations are the schema SSOT.

  • Schema changes: write the migration and merge it; never apply it by hand. scripts/deploy-selfhost.sh runs scripts/apply-migrations.sh on every deploy, applying pending files in filename order, each in one transaction, recorded in public.schema_migrations; a failed one aborts the deploy and leaves the live release untouched.

  • Read through PostgREST with the keys in .env.local (plain HTTPS, works from a sandbox; the service-role key bypasses RLS, so treat results as privileged):

    curl -s -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \
         -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" \
         "$NEXT_PUBLIC_SUPABASE_URL/rest/v1/projects?select=id,title&limit=5"
    

    Ask for a column to learn whether it exists, even on an empty table: …/rest/v1/<table>?select=<column>&limit=0 → 200, or 400 with code 42703.

  • POSTGRES_URL points at a local tunnel (127.0.0.1:5433) that is normally not running — a failure there is a missing tunnel, not a missing permission. For DDL or anything PostgREST cannot express, go through the box: ssh ubuntu@167.233.22.31 'docker exec supabase-db psql -U postgres -d postgres -c "\d+ projects"'.

  • Do not run a local Supabase stack (supabase start) for normal work. __tests__/unit/ci/agent-instructions.test.ts fails if anything under .claude/ demonstrates the retired MCP or drives the repo with npm.

Deploy path

Nobody merges by hand. A green, non-draft PR is squash-merged by the forge merge check (forge/verify), and bitbaum/forge-ops on Gitea deploys main. How both work is in fleet AGENTS.md, "Where the code lives". Read it there. The deploy itself is scripts/deploy-selfhost.sh: atomic swap, boot test and rollback, with pending supabase/migrations/*.sql applied on the way. GitHub Actions has run nothing in the org since 2026-11-15, so nothing in .github/workflows/ tests, merges, deploys or alerts. Do not wait on a workflow or fix one to unblock a change. Hold work back with a draft PR or a hold label.

Finished work ships without asking: the owner checks results on the live site and does not read GitHub. When asked work is done and verified, open a non-draft PR, stay on it until it is deployed, and give the owner the live URL. Ask the owner about the product, never about git, and offer options rather than an open question.

Every step you ask of the owner carries its link. Never write "open the Cat", "go to Settings → AI" or "look in Cat → Controls" without the full address beside it, written out so it can be tapped (https://orangecat.ch/companions/talk?with=cat, https://orangecat.ch/settings/ai). The owner reads on a phone and should never have to find a page you already know the address of. Take the path from src/config/routes.ts, not from memory; if a step has no page of its own, say which page it is on and link that. This holds for every message, not only the last one: a status update that names a page links it too.

Core conventions (don't fight these)

  • Entity registry is SSOT: src/config/entity-registry.ts. Never hardcode table names, API paths, or entity labels — read them from the registry (ENTITY_REGISTRY[type].tableName, .basePath; getTableName(type), getApiEndpoint(type)). A new entity is a registry entry (with its wallet: { holds, why }), a schema in src/lib/validation/<domain>.ts re-exported from src/lib/validation/index.ts, a form config src/config/entity-configs/<type>-config.ts registered in get-config.ts, and a migration file.
  • Actor ownership: everything is owned by an actor (users and groups both have one). Take an entity's owner column from getUserIdField(type) (most are actor_id; wallets use profile_id, groups created_by), never assume user_id. A user's actor is getUserActorId(supabase, userId) (src/domain/actors); never inline an actors query — one user can have several rows.
  • Bitcoin: wallet and payment amounts are BTC in NUMERIC(18,8) (never integer sats). A fixed-price entity's price is in its own currency (default CHF), in the column the registry names as priceColumn. Display through useDisplayCurrency(): formatAmountBtc for BTC, formatPrice(amount, currency) for prices, formatSats only for values already in sats. There is no formatAmount.
  • Non-custodial: the recipient's own wallet mints the invoice (NWC make_invoice or their Lightning-address provider); OrangeCat never holds funds. Payments: src/domain/payments/; <username>@orangecat.ch: src/domain/lightning-address/; NWC: src/lib/nostr/nwc.ts; BOLT11: src/lib/bitcoin/bolt11.ts.
  • Entity statuses differ by type: transitions are ENTITY_STATUS_TRANSITIONS and "live" is LIVE_ENTITY_STATUSES (src/config/entity-status.ts).
  • API routes are thin: authenticate, validate, delegate to a domain service in src/domain/ (exported functions, not classes; entity services wrap src/domain/base/entityService.ts), answer through src/lib/api/standardResponse.ts.
  • Design tokens: CSS custom properties in src/app/globals.css are the only SSOT for color/radius/shadow. No hardcoded hex in components or Tailwind config.
  • Layering: config/ (what exists) → domain/ (business logic, no HTTP/UI) → app/api/ (thin HTTP) → components/ (UI) → hooks/ (data fetching).

API routes

  • Entity routes come from the factories in src/lib/api/, not by hand: createEntityListHandler, createEntityPostHandler, createEntityCrudHandlers({ entityType, schema, buildUpdatePayload }) (GET/PUT/DELETE for [id]), createEntityGetByIdHandler. Actor-owned entities set ownershipField: 'actor_id', useActorOwnership: true.
  • Auth: wrap the handler in withAuth / withOptionalAuth (@/lib/api/withAuth); they put user and supabase on the request. Rate limits and body validation: compose(withRequestId(), withRateLimit('read' | 'write'), withZodBody(schema)). Limiters live only in src/lib/rate-limit.ts (@bitbaum/limitkit).
  • Answer with apiSuccess(data, { page, limit, total, cache }), apiError(message, code, status), apiValidationError(message, details) (422); end a catch with handleApiError(error), which already maps ZodError and the Supabase codes. Cache by preset (CACHE_PRESETS, src/lib/api/cache-policy.ts), not by seconds.
  • await createServerClient() (@/lib/supabase/server). createAdminClient() bypasses RLS: a route that uses it checks ownership itself.
  • No literal /api/… outside src/config/**, src/app/api/**, middleware and tests (ESLint): use API_ROUTES (src/config/api-routes.ts) or PUBLIC_API_BASE for v1.
  • Search goes through src/services/search/find.ts (search_public candidates, @bitbaum/searchkit ranking); never a second search query.
  • Log with logger (@/utils/logger); ESLint allows only console.warn and console.error.
  • After a migration has deployed, regenerate src/types/database.generated.ts with OC_BOX=ubuntu@167.233.22.31 pnpm run gen:types; never hand-edit it.

Code gates (in verify, all ratchets: lower, never raise)

  • check:sizes (scripts/check-file-sizes.js): src/app/**/route.ts ≤ 150 lines, other .tsx ≤ 300, .ts in src/services/ or src/domain/ ≤ 500. Split the file; never add to EXCEPTIONS, and remove an entry once its file is under the limit.
  • check:duplication (jscpd over src/): extract a shared helper instead of copying; lower BASELINE_PERCENT when you reduce duplication.
  • ESLint: @typescript-eslint/no-explicit-any is an error (an escape hatch carries an eslint-disable with its reason); max-lines-per-function sits just above the longest function — lower it when you split one.
  • .husky/pre-push runs type-check, check:sizes, audit:routes and test:unit; nothing wires .claude/hooks/* into a session. Neither is the gate: pnpm run verify is.

Words

A payment to a person or entity is "Support", "Fund" or "Back" — never "Donate", "Tip", "Crowdfunding" or "crypto". "Donation" is only the literal donation to OrangeCat on /support. Pay-state words are shared from src/config/pay-words.ts.

Design system

Tokens are SSOT in src/app/globals.css; tailwind.config.ts only maps utilities onto those vars and never declares a hex. Two layers: the legacy shadcn-style HSL tokens and brand palette (bg-card, text-foreground, tiffany-*, orange-*), and the semantic tier new code uses (text-fg-*, bg-surface-*, border-*, bg-accent-warm, bg-status-*, tracking-display, max-w-shell). Existing components migrate as touched; no new uses of tiffany or orange-*. Fonts ship in @bitbaum/design-tokens (src/app/fonts.ts is generated from it), wired in src/app/layout.tsx: Space Grotesk (font-heading), Inter (font-sans), IBM Plex Mono (font-mono). The end state is monochrome surfaces, one orange, and status colours only for status.

One orange. --public-accent resolves to --bitcoin-orange (#f7931a), so bg-accent-warm and bg-bitcoinOrange are one colour. Orange means exactly two things: Bitcoin (balances, Lightning, icons — bg-bitcoinOrange) and the one action that brings someone in (the accent Button variant, on public top-of-funnel surfaces only). In-app actions are monochrome primary. Orange is never decoration, a second button or a disabled state. Ink on it is text-on-accent. There is no bitcoin-orange utility class and no accent-primary one.

Ink follows its fill. A fill that flips with the theme (bg-fg-primary, a GRADIENTS key) and the positive and negative status fills take text-fg-inverted, never text-white; the warning fill is amber in both themes and takes text-warning-foreground. The band that is near-black in both themes (bg-surface-public) takes text-on-public, never text-fg-inverted, which flips. Copy is text-fg-primary, -secondary or -tertiary, each held at 4.5:1 on every surface in both themes (check:token-contrast). text-fg-muted is not for words, and neither is a resting alpha on text-fg-secondary, text-fg-tertiary or a status colour; check:accent-ink fails both, and the ink mistakes above.

Orange as text is text-bitcoin-text (#f7931a fails contrast on light surfaces); text-bitcoinOrange is for icons only. Font sizes come from the scale (text-post, text-figure, …), never text-[15px] or an inline fontSize (check:type-scale). A compact min-h-* under 11 on a raw <a>, <Link>, <button> or <summary> is paired with pointer-coarse:min-h-11 (check:tap-targets). Use Button (isLoading for busy, href for a link; no hand-rolled spinner), EmptyState for an empty list, Skeleton for loading, UI_TOKENS.focus (src/config/design-system.ts) for focus rings, and react-hook-form + zodResolver with @/components/ui/form. Individual vs group context is useNavigationContext().

Two global rules fight your classes: every <p> has a bottom margin (give stacked paragraphs mb-0 and let the parent set the gap), and every text <input> is pinned to 16px so iOS does not zoom — a larger input uses oc-figure-input, the one exemption.

One shape per kind, here

The reference implementation is the money surface (/receive, /send, /requests, /pay/<username>):

Rule Where it lives
Siblings share one frame: title, one line, tabs, content src/components/money/MoneyPage.tsx — no icon prop, on purpose
A public page opens with the one public header src/components/layout/PublicPageHeader.tsx, two page widths
Pick one of a few → equal cells in one row src/components/ui/SegmentedControl.tsx
A few suggestions → an even grid AmountField presets: grid grid-cols-4
Two actions together → two equal cells ReceiveCode: Copy link · Share
Rows of one list have one anatomy WaysToPay, OtherWaysToPay, RequestList
Closed-until-wanted is a button that says so src/components/money/OptionalNoteField.tsx
An amount is a figure: number large, unit small src/components/money/MoneyFigure.tsx
The object gets the surface, not the page ReceiveCode: only the QR is a plate
A row of a list has a face RailGlyph; only the Bitcoin tile is orange

Gates (in pnpm run verify except the last): check:choice-rows, check:accent-ink, check:token-contrast, check:tap-targets, check:public-frame (a page under src/app/(public) writes no <h1> of its own), check:type-scale, grep -rn '\[#' src/, and BASE_URL=http://localhost:3020 pnpm run check:broken-words (a word drawn across two lines on the landing page, the Cat chat and the money surface at 320/390/1440, measured in Chromium; E2E_USER_EMAIL / E2E_USER_PASSWORD open the signed-in pages). It is slow: with 39 screens it ran past 20 minutes (2026-11-12), so add a page to it with that in mind.

Before a PR with a screen in it, do fleet AGENTS.md's screen checks (390px, 44px targets, beside its siblings) and run the gates above.

Protected files (back up before touching)

.env.local, supabase/migrations/*, src/config/entity-registry.ts. Back up .env.local with node scripts/utils/env-manager.js backup.

This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in node_modules/next/dist/docs/ (resolved from this file's directory; in monorepos the next package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by next dev — verify at node_modules/next/dist/server/lib/generate-agent-files.js. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

For the shared authoring extraction and its unfinished UI work, read the writing checkpoint.