Files

24 KiB
Raw Permalink Blame History

AGENTS.md — Solon

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.

Governance rail for the OrangeCat stack: proposals, one-click or Bitcoin-signed votes, versioned policies, append-only audit. The treasury is watch-only — Solon stores addresses to observe and never holds keys or funds.

Read README.md for what the product is. This file is how to work in the repo.

Stack

  • Framework: Next.js 16.4 (App Router, output: 'standalone' for the Hetzner deploy)
  • Language: TypeScript 6.0 (strict)
  • Database: PostgreSQL via Drizzle ORM (drizzle-orm/node-postgres + pg Pool)
  • Auth: @bitbaum/accountkit/auth — Solon's own accounts (email and password, passkey, two-step codes); OrangeCat is one way in. Seats of people whose first way in was OrangeCat stay keyed on their OrangeCat actor id (legacyIdentityProvider)
  • Styling: Tailwind CSS 4, tokens from @bitbaum/design-tokens (installed under the alias @fleet/design-tokens)
  • Bitcoin: @noble/*, bs58check (message signing / signature verification)
  • Tests: Vitest (unit + integration), Playwright e2e, Puppeteer smoke (tests/)

Everyday commands

pnpm run dev          # next dev (localhost:3000)
pnpm run build        # next build (standalone) — no codegen step, Drizzle types come from the schema
pnpm run verify       # format:check + lint + typecheck + design:check + check:messages + check:places-literals + places:world-countries --check + check:cycles + test:coverage — run before every commit
pnpm run test         # the same tests without the coverage report, for a quick loop

pnpm run verify is the single source of truth for "is this change clean?" CI's verify job calls it verbatim, then adds the vendored-drift check and the build (see CI below), so green verify locally is necessary but not the whole of CI.

Drizzle / database

  • Schema SSOT: src/lib/db/schema.ts (9 governance models) and src/lib/db/places-schema.ts (Places: jurisdictions, names, identifiers, areas, relations, facts, sources, and the place_* registries). Types flow from them via $inferSelect; enum vocabulary lives in src/lib/db/enums.ts and src/lib/places/vocabulary.ts (dependency-free, safe for client code).
  • Places registries are projections of config. place_* tables are written only by pnpm run places:sync-config (every import run syncs first, in its own transaction). The config lives in src/lib/config/places/. Places rows are never deleted; a trigger refuses it. Design: docs/design/2026-09-places-and-jurisdictions.md.
  • Places data enters only through the importer. pnpm run places:import <source-key> <file> [--dry-run] (src/lib/places/importer/) snapshots, parses with the source's adapter (src/lib/places/adapters/), checks against config, applies in one transaction and runs the invariant engine; every run lands in place_import_runs. pnpm run places:fetch <source-key> [--backfill] [--dry-run] [--plan] retrieves what the adapter declares from the source's URL and imports each in turn; --backfill loads history once, on a source's first load only. Adapters parse a format; which levels and schemes rows become is the source's options in config. In production the box's hourly appcron timer calls POST /api/cron/places (CRON_SECRET), which starts a worker that imports every source the run log says is behind its cadence (src/lib/places/importer/queue.ts): a new source loads within the hour, a failed one is tried again a day later. The bundle has no scripts: a first load or --backfill runs places:fetch from a checkout of the deployed commit on the box (design §8.3, "In production"). No engine file names a country: Testland (src/lib/places/__tests__/fixtures/testland/) must keep importing and evaluating with changes only to its pack and fixtures. pnpm run check:places-literals (in verify) fails on any registry key, ISO region or currency code, or month-day literal in src/lib/places, the vendored tax model or the place page. Copy about places takes no side: the neutral-copy test scans messages/*.json against src/lib/config/places/neutral-terms.ts.
  • There is no codegen. Typecheck and build read the schema module directly.
  • Migrations live in drizzle/ (pnpm run db:generate after a schema change; pnpm run db:migrate applies them). Running migrations against a real database is manual / deploy-time only — do not add a push step to CI's verify job.
  • Migration history begins at drizzle/0000_init (baseline matching the tables the retired Prisma migrations created — byte-identical names, proven by pg_dump diff) plus drizzle/0001_seed_org1 (org #1 reference data). The production database predates this history and is baselined in the deploy ledger (public._deploy_schema_history), so these two files never run there.

Statistics

The statistics layer (/statistics, design docs/design/2026-11-freedom-framework.md, how to add content docs/development/adding-statistics.md) holds series as facts, curated links and events in the append-only statistic_records, and dimensions and axes in src/lib/config/statistics/. Three commands keep it honest: pnpm run statistics:sync writes the curated records, pnpm run statistics:quality reports gaps and large steps per series, and pnpm run statistics:verify fetches every page a record cites and checks the words it is expected to hold (a weekly workflow runs it). Every line of a curated record needs a source, a claim about an effect is a reported line with who made it, and every metric says what it covers (scope). Charts are screened by src/lib/statistics/sanity.ts (a figure outside its plausible band is left out and listed; misleading comparisons carry a warning) and every page can offer an AI explanation (brief.ts, explain.ts): the model sees only the page's numbered facts, and an answer with a number or citation not in them is dropped. A check that warns on correct data is a bug: remove or narrow it, do not add a caveat. /statistics/research (research.ts, research-tools.ts) lets a model read Solon's data and law with read-only tools: every fact a tool returns is a numbered source, and the report is checked with the same rules.

Budgets

Budgets (/budgets, design docs/design/2026-11-budgets.md) are one model over two inputs. The taxonomies in src/lib/config/budgets/ (COFOG for spending, ESA 2010 for revenue) are the single source: they generate the budget.<scope>.<side>.<code> metrics and the Eurostat source (eurostat_json adapter, one source for every country it covers, run like every Places source: pnpm run places:fetch eurostat-gov-world). A budget read from a law is a document under src/lib/config/budgets/documents/, its lines as printed and each placed on a category; its lines must add up to the totals the law states. src/lib/budgets/ turns both into one Budget and holds the arithmetic; pages and the contested places use only its components.

Money and language

Money on any page is in the reader's currency: src/lib/money/ converts at a year's average rate from data/money/rates.json (pnpm run money:rates, official publishers only) and never borrows another year's rate. The law reads in the reader's language: a version in it when the publisher has one, else a cached machine translation labelled as such (src/lib/law/translate.ts, text_translations), with the authentic text a click away. pnpm run law:translate --authority <key> translates an authority's titles ahead of readers; texts are translated when a page is first read.

Photos

The app box sends no photograph bytes and resizes nothing once the build has switched the bucket on. All an operator does: give the R2 bucket a public domain, and put PHOTOS_S3_ENDPOINT, PHOTOS_S3_BUCKET, PHOTOS_S3_ACCESS_KEY_ID, PHOTOS_S3_SECRET_ACCESS_KEY and MEDIA_PUBLIC_BASE (that domain) in /opt/fleet/env. The next deploy does the rest.

  • pnpm run build starts with scripts/media-ensure.ts. On the box's build (SELF_HOST=1; pnpm run media:ensure elsewhere) with those five set, it HEADs every variant the manifest names, renders (sharp, one image at a time) and uploads only the missing ones, reads one back through the public base, and only if that answers with the image writes NEXT_PUBLIC_MEDIA_BASE into .env.production.local (gitignored) for next build. Anything missing or failing is one log line and photographs stay on the app; it never fails the build. Keys carry the original's content hash, so a deploy with no new photograph only looks. An explicit NEXT_PUBLIC_MEDIA_BASE overrides it.
  • The site's own photographs (src/assets/images, registered in src/lib/content/photos.ts) are listed in src/lib/media/manifest.json, written by pnpm run media:render (also renders into .media/ for pnpm run media:upload, the manual path). A new or changed photograph needs media:render before it ships; src/lib/media/__tests__/variants.test.ts fails while the manifest lags. Draw one with MediaImage (src/lib/media/media-image.tsx), never bare next/image: it serves AVIF with a WebP fallback and keeps the blur.
  • Place photographs live in the bucket only, as place-photos/v2/<sha256 of the Commons file name, 24 hex>/<width>: only [0-9a-z/], so the public address is the key and needs no decoding. An object under the old raw key (place-photos/<file>@<width>) is copied to its current key inside the bucket the first time it is read. With a bucket configured nothing writes place_photo_bytes any more; it is only read, and the app drains it by itself (src/lib/places/photo-drain.ts, started from src/instrumentation.ts, under a Postgres advisory lock): batches of 8 at about 512 kB/s, each row deleted only after a HEAD shows the bucket holds the same length, type and MD5; errors back off up to 15 minutes; the empty table is TRUNCATEd (or, if the app's role may not, left to autovacuum). /api/health shows placePhotos (rows and bytes left, how it ended). PHOTO_DRAIN=0 stops it; PHOTO_DRAIN_KBPS sets the pace.
  • A page draws a place photograph straight from the bucket only when a public base is set AND the bucket is known to hold that photograph at that width (photo-bucket-index.ts: a listing every 15 minutes, plus every write); otherwise /api/place-photo, which puts it in the bucket for next time. PLACE_PHOTOS_DIRECT=0 is the kill switch. The share card reads the bucket only. pnpm run places:photos:to-r2 (dry run by default) reads photographs the bucket lacks from Commons ahead of readers; optional.
  • One manual item left: dropping the then-empty place_photo_bytes. apply-schema.sh (Loki) refuses any pending migration with DROP TABLE and aborts the deploy, so the drop is applied by hand on the box and its tag recorded in _deploy_schema_history, then removed from src/lib/db/places-schema.ts in the same change. Until then the table stays, empty and truncated.
  • src/lib/media/ and its scripts import nothing from the app: Heidi has the same pipeline, and both are to move into @bitbaum/sitekit. That extraction is pending; until it lands, change the two copies together.

Chat and text boxes

  • Every chat is chatkit's ChatApp or Composer, with the microphone and the paperclip on. Turning either off needs // experience-exempt: <reason> on the line.
  • Every text box people type into is TextBox (chatkit's DictationField, src/components/chat/text-box.tsx), never a bare <textarea>. A file that must have one says why in a first-line // experience-exempt: <reason>.
  • Never print a server's error text. Routes answer with a status and a code; chatkit names the problem from the status, in the reader's language.
  • The assistants' rate limit is @bitbaum/limitkit's decision over windows held in Postgres (src/lib/chat/rate-limit.ts, table rate_limit_windows), so it survives a deploy and is one allowance across instances. Solon's part is the numbers per bucket; a new route takes a bucket there, never its own counter.
  • Every label is in messages/*.json for ru, de, fr, it and en. A test fails when a chat label falls back to chatkit's English default.
  • The fleet experience audit (.github/workflows/experience.yml) fails over the ceiling in package-plan.json, which is zero. Do not raise it.

CI

.github/workflows/ci.yml runs two jobs on every push/PR to main:

Job What it does
verify pnpm install --frozen-lockfile → pnpm run verify → check:vendored-drift → governance-ratification check (PRs only; warns, never fails) → pnpm run build
integration drizzle-kit migrate on a fresh Postgres → places:sync-config and --check → every *.integration.test.ts → render checks → production-shaped smoke

The integration job is why migrations must replay cleanly from the baseline: it builds the database from scratch every run.

Green PRs merge and deploy themselves — the fleet-wide sweep in bitbaum/fleet (.github/workflows/auto-merge-sweep.yml) holds the policy for every repo in the fleet, and merging to main deploys via Loki's selfhost-deploy.yml. This repo used to keep its own copy of that script; it was deleted so a fix to the sweep reaches here without being re-ported.

Design

  • Tokens live in the shared @bitbaum/design-tokens package only (repo bitbaum/design-tokens, installed here under the alias @fleet/design-tokens); tailwind.config.js consumes its Tailwind preset and never holds a literal value, and src/app/globals.css carries Solon-specific rules, no tokens.
  • Loki and OrangeCat depend on the same package (the latter in orangecat/package.json). Solon is light and dark: the device decides unless the reader picks one in the header (src/components/theme/). The legacy navy / solon-* palette is deleted — using it fails the build.
  • pnpm run design:check (part of verify) enforces this. See docs/development/ui-guidelines.md.

What Solon governs

Solon is the governance plane of an entity. An entity is anything that can hold a wallet and is better for holding one — a test rather than a list, so the list is open in principle. The same entity sits on three planes: OrangeCat is its economy (it can hold, receive and send value), Solon its governance (its decisions can be put to a signed vote), Loki its execution (it can be worked on, built and shipped).

Loki's plane was called "engineering" until 2026-09-20. The rename matters here because the old word made two thirds of that product look misplaced: Loki also holds the people an operator works with, what they owe and what they spend, and no other product has a surface for those. What separates the three planes is AUDIENCE — OrangeCat is public by design, Loki private by default, Solon shared with its members — not subject matter.

Producer, and the only place the list of types lives: orangecat/src/config/entity-registry.ts, where every type carries wallet: { holds, why }. Do not restate that list here — three copies of it lived in orangecat's own agent-read docs and all three had drifted. See bitbaum/fleet AGENTS.md → Producers.

This is why "who may decide" is not Solon's to invent per surface: an entity that can hold value is the thing a vote is about.

Notes for agents

  • Never commit secrets. .env.example lists the variables the app reads; copy it to .env and fill it in.
  • User-facing copy on translated pages lives in messages/<locale>.json (see "Language" below) — never hard-code a sentence on a page that is in TRANSLATED_ROUTES.
  • Domain logic belongs in src/lib/domain/ and stays free of HTTP and UI.
  • Which decision categories are humans-only is each organization's own list (organizations.humans_only_categories). Every organization starts with AID_DISBURSEMENT, MEMBERSHIP, SAFETY and GOVERNANCE_RULES (DEFAULT_HUMANS_ONLY_CATEGORIES in src/lib/config/governance.ts) and changes it only by a GOVERNANCE_RULES decision with a humans_only effect. Generic pages describe the default; anything about one organization reads its list.

Language

Eight languages: English, German, French, Italian, Russian, Chinese (Simplified), Japanese, Korean — next-intl, the fleet's choice for i18n (fleet STACK.md; evig, hirnli and four others use it). Chinese, Japanese and Korean were translated by a model on 2026-12-01 and have not yet been read by a native speaker; their essays stay pending, as for every language.

  • src/i18n/routing.ts is the one list of locales. English is the source and the default: unprefixed (/hire); the others are prefixed (/de/hire). The URL decides, never the browser.
  • Every sentence lives in messages/<locale>.json. src/i18n/types.d.ts types t() keys against en.json, so a misspelt or missing key fails typecheck.
  • src/i18n/__tests__/parity.test.ts fails if a language lacks a key English has, has one English lacks, drops a {placeholder}, or leaves a string empty.
  • pnpm run check:messages (@bitbaum/langkit, in verify) reads every message as ICU and fails on what the parity test cannot see: a <tag> or argument English has and a language drops, and a plural without the forms its language needs (Russian: one, few, many, other). It and the parity test leave out the same pending namespaces, per language (src/i18n/pending.ts; Amend outside AMEND_LOCALES). An ASCII apostrophe directly before < or { opens an ICU quote and the tag renders as text (L'<a>… shows L<a>…): write the typographic ’.
  • Pages move under src/app/[locale]/; API routes stay outside it. Link with Link / useRouter / redirect from @/i18n/navigation, never next/link, or a German reader clicks into English.
  • A page not yet translated stays English and shows a notice in the reader's language. TRANSLATED_ROUTES in site-config.ts lists the ones that are. Translation can also be per language: Amend (proposing a change to the law) is written in the languages of AMEND_LOCALES only, and only there do its pages lose the notice. An official route's words per language live on the route (OfficialRoute.text, src/lib/config/law/routes.ts); English is the fallback. The world routes and the local-say examples keep theirs in src/lib/config/law/routes-world-text/<locale>.ts, by route key and by an example's place and year: machine-translated on 2026-12-02, not yet read by a native speaker, every English number kept (src/lib/config/__tests__/law-routes-world-text.test.ts). Each language's whoMaySign and signatureBase must read inside its own routeBar / routeShare (German dative after "von", Russian genitive after "%"). A pending namespace may be filled in part: Chinese, Japanese and Korean have the Amend.amendment labels the route card prints, and the checks read what is there and excuse only what is missing.
  • Words in the configuration (a rubric, a budget line, a source's attribution, who published a series) are written once, in English, beside their source. Their other languages live in data/i18n/config.json, keyed by the English words, and localized() / cite() read it (src/lib/i18n/). A changed English text has no translation until one is written, so a stale one is never shown. pnpm run i18n:config lists what is missing (--json prints a skeleton to fill), and src/lib/i18n/__tests__/config-texts.test.ts fails while any text a translated page shows lacks a language.
  • German uses Swiss spelling (ss, never ß).
  • NEUTRAL_COPY_TERMS (src/lib/config/places/neutral-terms.ts) lists, per language, the words that take a side about a place; Chinese, Japanese and Korean terms match anywhere in a text (MATCHES_ANYWHERE), since those languages run words together. A new language needs its list before it ships.

The one habit that matters: never assemble a sentence by concatenation. "You have " + n + " votes" cannot be translated; You have {n} votes can.

Translate the product surface first, not the essays. Nav, forms, the ballot, the buttons — the words someone must read to cast a vote correctly. The /governance teaching pages are precision prose about terms of art, and a machine translation that renders sociocratic consent as Zustimmung rather than Konsent teaches the opposite of what the page exists to teach. Terms of art get one fixed translation per language, in the glossary, reviewed by a native speaker before an essay ships in that language.

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.