agents.md holds the instructions, claude.md points at it
opencode discovers only AGENTS.md, Claude Code only CLAUDE.md — so with the content living in CLAUDE.md, every doc here was invisible to opencode. Swaps all five pairs (root, src/apps, src/databases, themes, plugins): AGENTS.md now holds the full text verbatim, CLAUDE.md is a short pointer. docs-check's permission-count regex now reads root AGENTS.md instead of CLAUDE.md; the workspace-level officer-dev/CLAUDE.md check is untouched, out of scope.
This commit is contained in:
@@ -1,41 +1,563 @@
|
||||
# AGENTS.md
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for any coding agent working in the Officer platform repo.
|
||||
## Project Overview
|
||||
|
||||
**The instructions live in [`CLAUDE.md`](CLAUDE.md). Read it first — this file only points there.**
|
||||
Officer is a self-hosted platform built around one person — the server owner — which since 2026-08-07
|
||||
also admits **additional accounts holding a strict subset of it**. It bundles an AI agent, a terminal,
|
||||
a file browser, a code editor, a bitcoin wallet, a remote desktop and customisable dashboards
|
||||
behind a single web app.
|
||||
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
**The owner/member split, and where the line falls.** This file said "single-user is a hard invariant,
|
||||
not a stage" until 2026-08-07. That is no longer true and had already stopped being true when it was
|
||||
written: `users` holds six rows. The accurate statement is narrower and more useful —
|
||||
|
||||
## Orientation
|
||||
- **One owner.** User id 1, role `Super Admin`, created by `POST /auth/bootstrap` while the table is
|
||||
empty, pinned there by a CHECK constraint. The owner bypasses every permission check.
|
||||
- **Other accounts get only what their ROLE is granted.** Roles are `Admin`, `Member`, `Developer`;
|
||||
grants live in `role_permissions`, keyed on role, never on user. Absence denies — there is no row
|
||||
meaning "no", so an empty table is a server where members reach nothing but their own profile.
|
||||
- **Some things can never be shared, structurally.** Tasks, items, desktop and browser are
|
||||
`kind: 'execution'`: they run as the owner's OS user in the owner's home, so there is no level of
|
||||
"read" that makes them safe. They have no level at all and the grants API refuses to store one.
|
||||
- **And some are shared only because the kernel enforces it.** Terminal, chat and files are
|
||||
`kind: 'confined'`, added 2026-08-11 with per-user Linux accounts. They still touch the filesystem
|
||||
and still run processes — but not the _owner's_, because the account has its own Linux user, its own
|
||||
home, and the kernel refusing everything above it.
|
||||
|
||||
Officer is a self-hosted platform built around **one owner** (user id 1, role `Super Admin`, who
|
||||
bypasses every permission check), which since 2026-08-07 also admits **additional accounts holding a
|
||||
strict subset of it**. Roles are `Admin` / `Member` / `Developer`; what each may reach is decided by
|
||||
per-role permission grants, resolved on every request.
|
||||
The distinction earns its keep in one place: **a confined grant means nothing without that Linux
|
||||
user.** `authorize.ts` drops it for an account whose `osUser` is null, so "granted but unconfined"
|
||||
resolves to no access rather than to the owner's home — which is what it would otherwise resolve to,
|
||||
since `getOwnerHomeDir` ignores the email it is passed. That rule lives there once and covers the
|
||||
HTTP routes, the websocket doors and the dock together.
|
||||
|
||||
If a design question turns on "which user", the answer depends on the surface: real for the **app**
|
||||
permissions (gitea, music, photos, calendar…), and still always **the owner** for anything
|
||||
that executes code or touches the disk — terminal, chat, tasks, files, desktop, browser are
|
||||
`kind: 'execution'` and can never be granted. `src/servers/permissions/registry.ts` is the authority.
|
||||
So "which user is this" has a real answer for the **app** surface (gitea, music, photos,
|
||||
calendar…) and for the **confined** one (terminal, chat, files), and is still always "the owner" for
|
||||
anything under `execution`.
|
||||
|
||||
**Mounting a router without a registry entry makes the server refuse to boot.** Read the "Permissions"
|
||||
section of `CLAUDE.md` before adding one.
|
||||
`src/servers/permissions/registry.ts` is the authority and reads as the design document for this.
|
||||
**Mounting a router without a registry entry makes the server refuse to boot** — see "Permissions"
|
||||
below before adding one.
|
||||
|
||||
This file previously described Officer as strictly single-user with "no tenancy, no roles, no user
|
||||
management". That was written to correct an _older_ drift in the opposite direction — a fictional
|
||||
multi-user intranet with a user-invitation API — and it overshot. Both are now superseded by the
|
||||
paragraph above; treat the permission registry as the source of truth over either.
|
||||
**Account creation exists.** `POST /api/users` (owner-gated), with a form under Settings → User Management:
|
||||
it validates the password with the same rules bootstrap uses, refuses a role that is not a row in `roles`,
|
||||
refuses `Super Admin` outright because there is exactly one owner, optionally takes an inbound SSH key, and
|
||||
provisions the Linux account. `POST /users/:id/provision-linux` retries that half if the host was not ready.
|
||||
|
||||
This repo is one of two. The other, `permissions/`, holds the agent's tasks, tools and skills as
|
||||
plain files, and is where most changes belong — adding or changing a task needs no code change here
|
||||
and no restart.
|
||||
This file said "there is no way to create a second account" for some days after `69a31051` shipped one, and
|
||||
`docs/roles-and-teams.md` sequenced a whole phase around building it. Neither is checkable by
|
||||
`bun run docs:check` — it compares numbers, and this was prose. Worth knowing as the shape of the failure:
|
||||
the counts stay right and the sentences rot.
|
||||
|
||||
- [`CLAUDE.md`](CLAUDE.md) — this repo's architecture, conventions and code style
|
||||
- [`docs/working-on-officer.md`](docs/working-on-officer.md) — the deployment-wide guide: which
|
||||
directory a change belongs in, how to run and verify it, the task system, and the failure modes
|
||||
worth knowing about
|
||||
- `CONVENTIONS.md` — component organisation and React patterns, with rationale
|
||||
- `TODO.md` — current direction; takes precedence where it disagrees with anything else
|
||||
## Architecture
|
||||
|
||||
Treat the code as the source of truth where anything disagrees with it.
|
||||
One Bun process (`src/server.tsx`) serves everything:
|
||||
|
||||
- the React SPA, via Bun's HTML import of `src/apps/officer-web/index.html` (HMR in dev)
|
||||
- the REST API, a Hono app mounted at `/api` (`src/servers/hono.ts`)
|
||||
- eight WebSocket providers — terminal, chat, task-runner, pipeline, cliamp, cliamp-audio, desktop,
|
||||
vault — plus a sidecar registration socket. `terminal` is a byte relay onto the pty sidecar's own
|
||||
listener, not a translating bridge; `vault` is the same shape onto Vaultwarden's notifications hub.
|
||||
- ~~a browser relay on its own port~~ — switched off 2026-08-13, awaiting extraction into a plugin.
|
||||
The extension and `api/browser/` stay on disk; the listener and the `/api/browser` mount do not.
|
||||
|
||||
Long-running and privileged work lives in **sidecars**: separate processes that dial back in over
|
||||
`/api/sidecar/register` and are tracked in `src/servers/sidecar-registry.ts`. PM2 runs them
|
||||
(the generated `ecosystem.config.cjs` — see below): `officer` (the server), `officer-anthropic-proxy`, `officer-claude-code`,
|
||||
`officer-opencode`, `officer-pty`, `officer-vnc`, `officer-music`, `officer-vault`,
|
||||
`officer-slskd`, `officer-headscale`, `officer-transmission`, `officer-invoiceshelf`, `officer-wallet`,
|
||||
`officer-photos`, `officer-notify`, `officer-caldav`, `officer-memos`, `officer-jellyfin`, `officer-gitea`
|
||||
— twenty as of 2026-08-06, and a list that goes stale every time a sidecar lands. `pm2 jlist` is the
|
||||
source of truth.
|
||||
|
||||
**`officer-anthropic-proxy` and `officer-claude-code` are not the same thing.** (The second was
|
||||
called `officer-agent` until 2026-08-13; older docs use that name.) The proxy holds the Anthropic
|
||||
credential and forwards API traffic; the agent is the process that spawns `claude`. They were one entry
|
||||
named `officer-claude` until the sidecar-isolation work — which is exactly how the false claim that
|
||||
"restarting officer doesn't disturb the agent" survived so long. Every sidecar is a PM2 peer of
|
||||
`officer`, so **no sidecar is a child of the server and restarting the server does not kill one.**
|
||||
|
||||
Agents run **unsandboxed as the server owner**, with `--dangerously-skip-permissions`. This is
|
||||
deliberate — it is the owner's own machine. Do not add a jail without being asked.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
```
|
||||
src/
|
||||
├── server.tsx # the single entrypoint: routes, WS upgrades, static files
|
||||
├── apps/
|
||||
│ └── officer-web/ # the SPA shell — Screens/Authentication + Screens/Dashboard
|
||||
├── servers/
|
||||
│ ├── hono.ts # router composition; everything under /api
|
||||
│ ├── _middlewares/ # auth, body parsing, the permission gate, rate limiting
|
||||
│ ├── api/<feature>/ # one folder per feature, each exporting a router
|
||||
│ ├── channels/ # send-claude-code / send-opencode — how /chat drives an agent turn
|
||||
│ ├── queue/ # background job engine
|
||||
│ └── sidecar/ # sidecar implementations + the wire protocol
|
||||
├── databases/officer_db/ # the only database (Postgres + Drizzle)
|
||||
├── extensions/browser-relay/
|
||||
└── workspaces/ # shared packages, each a bun workspace
|
||||
```
|
||||
|
||||
`src/workspaces/officerdev` is the biggest of these: the windowed "apps" (FileBrowser, Chat,
|
||||
Terminal, CodeEditor, Desktop, Dashboards, Wallet…) that the shell hosts, behind an `AppRegistry`.
|
||||
`src/apps/officer-web` is only the shell — screens, routing and settings.
|
||||
|
||||
**Path aliases** (`tsconfig.json`): `@/*` → `src/apps/officer-web`, `@/components/*` →
|
||||
`src/workspaces/components`, `@@/*` → `src/servers`, `@/public/*` → `public`. Workspace packages are
|
||||
imported by their package name (`officerdev`, `hooks`, `state`, `types`, `helpers`, …).
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Runtime**: Bun (Node 22 or newer is enforced by a `preinstall` check)
|
||||
|
||||
That check demanded _exactly_ 22 until 2026-08-12. The reason was a `node-pty` build
|
||||
failure some months earlier, whose details were not recorded. It was relaxed to `>= 22`
|
||||
after confirming node-pty ships **no Linux prebuilds** — its install script always falls
|
||||
through to `node-gyp rebuild`, so it compiles against whatever Node is present and there
|
||||
is no ABI to mismatch. Untested on 24 at the time of the change. If `bun install` fails
|
||||
building node-pty, or `officer-pty` cannot load its native module, restore the exact pin
|
||||
first. The source build also needs `build-essential` and `python3`.
|
||||
|
||||
**Bun itself is held at the 1.3 series, on purpose and temporarily.** 1.4.0 was published
|
||||
2026-08-20; the owner asked on 2026-08-22 to stay on 1.3 for a few months until 1.4 has been
|
||||
watched. Two places carry that number and they move together: `BUN_SERIES` in
|
||||
`scripts/setup/machine-setup/lib/dev.sh`, which resolves the newest `1.3.x` from the npm registry
|
||||
and passes it to the installer as a release tag, and `engines.bun` in `package.json`, which is
|
||||
what `bun run doctor` reads. bun ignores `engines` (verified — an install declaring `1.9.x` ran
|
||||
clean under 1.3.14), so that field is the declaration and doctor is the enforcement.
|
||||
|
||||
**Do not run `bun upgrade` on a machine running Officer.** It takes no version argument — latest
|
||||
stable or `--canary`, nothing else — so it jumps straight past the pin and says nothing. That is
|
||||
the whole reason `doctor` checks the running version at all; `machine-setup.sh --only 'JavaScript
|
||||
runtimes'` offers to pin a drifted machine back down. Lifting the hold is `todo/infra/`.
|
||||
|
||||
- **Language**: TypeScript, strict. `bunx tsgo` is clean — keep it that way.
|
||||
- **Frontend**: React 19, React Router 7, React Query, Tailwind 4, shadcn/ui + custom components
|
||||
- **Backend**: Hono
|
||||
- **Database**: Postgres via Drizzle — `officer` for the platform, plus `officer_marketplace` on the
|
||||
host that serves marketplace.officer.dev (see `docs/marketplace.md`)
|
||||
- **Agents**: Claude Code and opencode, driven through sidecars; tools exposed over MCP
|
||||
|
||||
## Data
|
||||
|
||||
Two stores, and the split matters:
|
||||
|
||||
**Postgres** (`src/databases/officer_db`) holds the account, passkeys, settings, dashboards,
|
||||
queue and pipeline jobs. Since 2026-08-16 there is a SECOND database,
|
||||
`officer_marketplace` (`src/databases/marketplace_db`), and the split is deliberate: it is a public
|
||||
catalogue served by a process with no login, no session and no user, so sharing a connection would put
|
||||
an unauthenticated surface one query away from every private table. It runs only on the host serving
|
||||
marketplace.officer.dev — `docs/marketplace.md`. One directory per feature holding `schema.ts` and
|
||||
`queries.ts` beside each other; `src/schema.ts` is what `db:push` reads, and it lists the core tables
|
||||
with the plugin ones commented out. Types inferred from the schema in `src/types.ts`.
|
||||
|
||||
**The filesystem** holds everything the agent authors. `OFFICER_ITEMS_DIR` (`$OFFICER_ROOT/capabilities`)
|
||||
contains one directory per item under `skills/`, `tools/`, `tasks/`, `processes/`, `extensions/` — no
|
||||
database rows, no scope tiers. `DATA_PATH/<email>/` holds the managed home and attachments. It also holds
|
||||
`email_accounts/`, which is the **email plugin's** — the platform pre-creates the directory and never opens
|
||||
what is inside it.
|
||||
|
||||
**None of those paths is configured.** Since 2026-08-13 `src/servers/data-path.ts` derives the install
|
||||
root as `resolve(process.cwd(), '..')` and hangs `data/`, `permissions/` and `dockers/` off it. That
|
||||
replaced `DATA_PATH`, `OFFICER_ITEMS_DIR` and `HOME_DIR` in `.env` — three values that had to agree with
|
||||
each other and with the tree on disk. `assertInstallLayout` refuses to boot when the working directory
|
||||
is not the repo, because otherwise a wrong `cwd` relocates the whole install silently rather than
|
||||
failing.
|
||||
|
||||
Note `getHomeDir` (the managed home under `DATA_PATH`, now used only for NON-owner accounts and by
|
||||
pipeline-executor) versus `getOwnerHomeDir` (the owner's real login home, where terminals, chats and
|
||||
task runs execute — captured from `homedir()` once at module load, and it ignores the email it is
|
||||
passed).
|
||||
|
||||
### Schema changes use `push`, not migrations
|
||||
|
||||
This database is kept in sync with `bun db:push`, which diffs the schema code against the live
|
||||
database and alters it directly. **`drizzle-kit migrate` has never been run here** — there is no
|
||||
`__drizzle_migrations` table. Change the schema, run `bun db:push`, done.
|
||||
|
||||
`bun db:gen` writes files to `officer_db/migrations/`, but nothing applies them; the old numbered
|
||||
history was deleted because it had drifted from the real schema. Treat the schema code, not those
|
||||
files, as the source of truth.
|
||||
|
||||
**Declare multi-column uniqueness as `uniqueIndex('uq_…').on(a, b)`, never `unique('uq_…').on(a, b)`** —
|
||||
drizzle-kit mis-diffs named composite unique _constraints_ and re-creates them on every push, which used
|
||||
to stop `db:push` on an unanswerable truncate prompt. Same for any foreign key whose generated name would
|
||||
exceed Postgres's 63-character identifier limit: name it explicitly. See `src/databases/CLAUDE.md` →
|
||||
"Composite keys" before adding either.
|
||||
|
||||
## Security Model
|
||||
|
||||
- `IS_DEV_BUILD` (`src/servers/build-env.ts`) is true **only** when `PUBLIC_BUILD_ENV` is explicitly
|
||||
`dev`/`development`. Everything else, including unset, is hardened. Rate limiting and password
|
||||
rules key off it — they fail closed.
|
||||
- **There is no origin checking.** It was removed on 2026-08-13, along with `ALLOW_ANY_ORIGIN` and
|
||||
`ALLOW_ANY_ORIGIN_MUSIC`. The flag defaulted to ON, so origin validation ran on no real install —
|
||||
what came out was documented defence in depth that was already switched off. Origin was never
|
||||
authentication here anyway: an app's `officer://<hex>` origin is chosen by the client, forgeable
|
||||
outside a browser, and extractable from a shipped binary. The perimeter is the tailnet, and the lock
|
||||
is a valid token on every protected route plus the permission gate below.
|
||||
- JWTs are 30-day, blacklisted on signout, and invalidated by a password change (`passwordChangedAt`).
|
||||
**The role is deliberately not a claim** — every authorization decision re-reads `users.role` from
|
||||
Postgres, so a grant or a revoke takes effect on the next request rather than at next sign-in.
|
||||
- A panic lockdown (`src/servers/api/auth/panic.ts`) is in-memory only and refuses every
|
||||
authenticated request until the server restarts.
|
||||
|
||||
### Permissions — read this before mounting a router
|
||||
|
||||
Authorization is one system, and it is not in `userMiddleware` (which only answers "is this token
|
||||
valid"). It is `_middlewares/permission-gate.ts` → `permissions/authorize.ts`, mounted globally in `hono.ts`
|
||||
ahead of everything, and it re-verifies the token itself so it covers routes that never mount
|
||||
`userMiddleware`.
|
||||
|
||||
- `permissions/registry.ts` — the single enumeration of what the platform can do, in five kinds:
|
||||
`core` (every account, not deniable), `app` (**the grantable surface**), `confined` (grantable, but
|
||||
only to an account that has a Linux user), `execution` and `admin` (owner only, and `execution` is
|
||||
never grantable at any level). **21 entries as of 2026-08-27** — verified by `bun run docs:check`, which fails if this number drifts again: 6 core, 2 app, 4 confined, 3 execution, 6 admin (`todos`, the todo board, is the sixth). It was 22 until caldav became a plugin and took `calendar` with it — a plugin's permission is registered at runtime from its manifest, so it is real but not in this file's count. `notify` moved from `app` to `core` on 2026-08-24: it was grantable, nothing granted it, and every Member's app was silently 403'd registering its own push token. It said 27 for nine days. The execution count dropped by one when Minesweeper became a plugin — see `plugins/minesweeper/manifest.ts` for why that was a fix rather than a downgrade.
|
||||
- `permissions/authorize.ts` — resolves "may this account do this". Owner short-circuits first; every
|
||||
other answer is role grants plus core, with `execution`/`admin` stripped even if a row grants them,
|
||||
and `confined` stripped for an account with no `osUser`.
|
||||
**Every catch returns deny.** Grants are cached by role and the cache's whole invalidation contract
|
||||
is `invalidateRoleGrants`, called by the one writer in `api/users/permissions-routes.ts`.
|
||||
- `permissions/totality.ts` — `assertPermissionTotality` runs in `server.tsx` **before `serve()` and
|
||||
throws**. Mount a router or a socket without a registry entry and `pm2 restart officer` fails,
|
||||
naming what is missing. That is deliberate: the hole it closes was a Member 403'ing on
|
||||
`GET /api/tasks` and opening `/api/tasks/pipeline/ws` with a 101 in the same minute, because Bun's
|
||||
route table matches the socket before the `/api/*` catch-all that reaches Hono. A patch does not
|
||||
survive the next door; refusing to boot does.
|
||||
|
||||
So **adding a router means adding one line to `CAPABILITIES`**. If the surface genuinely is not
|
||||
user-gated, add it to `EXEMPT_API_PREFIXES` in `totality.ts` _with a reason_ — an unexplained exemption
|
||||
is how the hole happened the first time.
|
||||
|
||||
The frontend hook `usePermissions` **fails open** on purpose: hiding a dock icon is a courtesy, the
|
||||
403 is the lock, and an owner locked out by a transient network error is worse than a member clicking
|
||||
into a refusal.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
bun dev # the whole app — SPA + API + WebSockets, watched
|
||||
bun start # production
|
||||
bunx tsgo # typecheck (not tsc)
|
||||
bun test # tests
|
||||
bun format # prettier over every dirty file — see the note below before running it
|
||||
bun db:push # apply the schema to Postgres
|
||||
bun docs:check # do the docs still match the code? REQUIRED before tagging a release
|
||||
bun setup # runs scripts/install.sh — blank machine to running platform
|
||||
```
|
||||
|
||||
**`bun docs:check` before every release, and leave it green.** It compares documented claims against values
|
||||
derived at run time — the permission count, the PM2 entry count, every settings route Spotlight offers — and
|
||||
exits non-zero on drift. A check must never compare a doc against a second hard-coded copy; that is one more
|
||||
place to drift, and it drifts in the same edit that misses the doc.
|
||||
|
||||
It is narrow on purpose. It cannot read prose and judge it, only claims with a machine-checkable
|
||||
counterpart — which is a small part of the documentation and the part that rots fastest, because a number is
|
||||
exactly what nobody re-derives while editing the sentence around it. Both claims it found on the day it was
|
||||
written had been wrong for over a week.
|
||||
|
||||
`scripts/install.sh` is only an orchestrator — it runs the two halves in order and does nothing itself:
|
||||
`setup/machine-setup/machine-setup.sh` (28 sections: packages, tailnet, runtimes, docker, shell) then
|
||||
`setup/officer-setup.sh` (11: pre-flight, layout, repository, dependencies, database, environment, secrets,
|
||||
schema, build, services, verify). Either runs alone — `--machine-only`, `--officer-only`, or by path — because
|
||||
a machine you already trust needs only the second. Both are re-runnable: each records the steps it finished
|
||||
and skips them, so stopping halfway costs nothing. **Run it as yourself**; it re-execs through `sudo` when it
|
||||
needs to, and on macOS never does, because Homebrew refuses to run as root.
|
||||
|
||||
Sidecar control is PM2, not npm scripts: `pm2 restart officer-<name>`, `pm2 logs officer-<name>`.
|
||||
See `docs/working-on-officer.md` for which process a given change needs restarted.
|
||||
|
||||
### Installs are frozen. Never resolve a dependency you did not ask for.
|
||||
|
||||
`bunfig.toml` sets `[install] frozenLockfile = true`, so **`bun install` resolves from `bun.lock` and
|
||||
nothing else** — it fails rather than quietly picking up a newer version, including a transitive one
|
||||
nobody chose. Verified on bun 1.3.10: a lockfile that no longer satisfies `package.json` exits 1 with
|
||||
`error: lockfile had changes, but lockfile is frozen`.
|
||||
|
||||
It is config rather than a habit because a supply-chain compromise does not wait for the one time
|
||||
somebody forgets a flag. On **2026-08-04** eleven cache packages — `keyv`, `flat-cache`,
|
||||
`file-entry-cache`, `cacheable-request`, `cache-manager`, the `@cacheable/*` scope, `ecto` — were
|
||||
published with a `preinstall` dropper that harvested npm and GitHub tokens, AWS and Kubernetes
|
||||
credentials, SSH and PEM keys, `.env` files and `.claude/settings.json`, then republished itself
|
||||
through any npm token it found. It reached 434 further packages across 1,381 versions. This machine was
|
||||
unaffected only because nothing had installed since 2026-08-02.
|
||||
|
||||
**To change a dependency:** edit `package.json`, allow the lockfile to change deliberately, **read the
|
||||
diff**, and commit it. Note that `--no-frozen-lockfile` — which this file and `bunfig.toml` both used to
|
||||
name — is NOT a flag bun 1.3.14 has; it is silently ignored and the install still fails frozen. Comment
|
||||
out `frozenLockfile` in `bunfig.toml` for the one command, then put it back. The friction is the point — an unexplained lockfile change
|
||||
in a diff is the signal this exists to produce.
|
||||
|
||||
**Do not** add `--no-frozen-lockfile` to a script, a Dockerfile or CI to make an error go away. The
|
||||
error means the lockfile and `package.json` disagree, and that is worth a human look every time.
|
||||
|
||||
**Format your own files, not the whole dirty tree.** `bun format` globs `git diff --name-only HEAD`,
|
||||
so it rewrites every uncommitted file — including work in progress that isn't yours, which then shows
|
||||
up as unexplained whitespace churn in someone else's diff. Run `bunx prettier --write <paths>` on the
|
||||
files you actually touched. `bun format` is only safe when the tree is otherwise clean.
|
||||
|
||||
## Code Style
|
||||
|
||||
- **Paradigm**: functional — pure functions, immutability, composition
|
||||
- **TypeScript**: strict, no `any`. Type-only imports are required (`verbatimModuleSyntax`).
|
||||
- **Comments**: minimal, and about _why_. Don't narrate what the code already says.
|
||||
- **Async**: always async/await
|
||||
- **Exports**: named only, no defaults
|
||||
- **Files**: `PascalCase.tsx` for components, `kebab-case.ts` for everything else
|
||||
- **Prettier**: single quotes in JS, double in JSX, semicolons, trailing commas, 120 cols
|
||||
|
||||
### Imports
|
||||
|
||||
Order: types → external → workspace → relative.
|
||||
|
||||
```ts
|
||||
import type { User } from 'types';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { formatDate } from 'helpers/formatters';
|
||||
import { useWebsites } from '../useWebsites';
|
||||
```
|
||||
|
||||
In app code import types from `'types'`, which re-exports the database types. Only server and
|
||||
database code imports from `officerdb/types` directly.
|
||||
|
||||
### Functions
|
||||
|
||||
Arrow functions for one-liners, regular functions for anything with real logic. No multiline
|
||||
parameter lists — extract a params type instead.
|
||||
|
||||
```ts
|
||||
type ProcessDataParams = { body: Record<string, unknown> | undefined; query: Record<string, string> };
|
||||
export function processData({ body, query }: ProcessDataParams): Result { ... }
|
||||
```
|
||||
|
||||
### Components and hooks
|
||||
|
||||
```tsx
|
||||
type ExperimentCardProps = { experiment: Experiment; onSelect: (id: number) => void };
|
||||
|
||||
export const ExperimentCard = ({ experiment, onSelect }: ExperimentCardProps) => { ... };
|
||||
```
|
||||
|
||||
Complex hooks return objects; simple state hooks return `as const` tuples. Event parameters are
|
||||
always named `ev`, never `e`.
|
||||
|
||||
### API calls
|
||||
|
||||
`useClient()` returns typed verbs — `client.get<Foo>('/foo')` really does return `Foo`, so pass the
|
||||
type parameter and let inference flow from it.
|
||||
|
||||
## Working With Me
|
||||
|
||||
- **Ask first** — confirm the approach before a significant change
|
||||
- **Explore thoroughly** — read the related files before editing
|
||||
- **Keep it simple** — no over-engineering, no premature abstraction
|
||||
- **Be explicit** — no magic, no implicit behaviour
|
||||
- **Stay focused** — note unrelated problems, don't fix them uninvited
|
||||
- **Report honestly** — say what you verified and what you didn't
|
||||
|
||||
**Always commit and push when you finish implementing — including when it went wrong.** Don't wait to be
|
||||
asked, and don't hold a branch back because it is unfinished, untested or turned out to be a dead end. The
|
||||
history of the mistakes is worth having: a reverted commit and its message explain why an approach was
|
||||
abandoned, which is exactly the thing that gets lost when a failed attempt is quietly discarded. Say what
|
||||
state it is in — in the commit message and in `COMMS/` if another agent will pick it up — rather than
|
||||
withholding the commit until it is good.
|
||||
|
||||
Commit messages: simple lowercase, no prefixes.
|
||||
|
||||
**Stage and commit in ONE step, naming the paths.** `git add <path>` then a bare `git commit` commits the
|
||||
whole **index**, not the path just named — so anything a concurrent session had staged goes into your
|
||||
commit, under your message and your session trailer. Use `git commit -- <paths>` instead, which does what
|
||||
the two-step form only looks like it does.
|
||||
|
||||
This is not hypothetical and it is not rare: two agents share this working tree most nights. On
|
||||
2026-08-23 commit `6e092c32` says "marketplace: minesweeper in the catalogue" and contains nine files of
|
||||
another session's roles work, swept up mid-`git add`. The other session was right not to amend it —
|
||||
rewriting shared history to fix a message is the worse trade — so the record was corrected with a
|
||||
follow-up note instead. Cheap to avoid, awkward to undo.
|
||||
|
||||
Two things about the form itself, both learned the same night. `-m`/`-F` goes BEFORE the `--`, or git
|
||||
reads the message as a pathspec. And it only works on **tracked** files — a new file must be `git add`ed
|
||||
first, so a commit introducing one is `git add <new>` then `git commit -- <paths>`, naming every path.
|
||||
Getting that wrong fails loudly, which is the good case: the release tag that followed it went onto the
|
||||
wrong commit, and only because the tag was checked afterwards did that surface at all.
|
||||
|
||||
**An agent's commit names the session that made it.** A trailer, below `Co-Authored-By`:
|
||||
|
||||
```
|
||||
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
|
||||
```
|
||||
|
||||
The transcript id, not the session name — names are not stable. On 2026-08-23 one session was
|
||||
`platform-e2` and then `platform-18`, and another `platform-59` then `platform-72`, both renamed by a
|
||||
restart in a single night. The transcript id survived both.
|
||||
|
||||
Why it earns a line in every commit: three agents committed to this repository in one night and `git log`
|
||||
could not tell them apart. `Co-Authored-By` says "an agent", which stopped being useful the moment there was
|
||||
more than one. And the transcript holds the reasoning a commit message cannot — the arguments considered and
|
||||
dropped, what was measured, what the owner decided and why. A commit that names its session is a commit
|
||||
whose "why" is still answerable in six months.
|
||||
|
||||
**The precondition, and it is not built yet:** an agent cannot reliably discover its own transcript id. The
|
||||
only exposure is that a background task's output path contains it, which means starting a job to learn who
|
||||
you are. `commanderBlock` already hands a commander its id in the preamble, so the mechanism exists —
|
||||
`todo/agent-coordination/` carries giving it to every session. Until then, an agent that knows its id should
|
||||
add the trailer and one that does not should leave it out rather than guess.
|
||||
|
||||
## Frontend route conventions (apply to EVERY new dashboard route)
|
||||
|
||||
Worked examples: `/soulseek`, `/music`, `/chat`.
|
||||
|
||||
- **Workspace/Panel framework, always — never a standalone single screen.** The screen renders
|
||||
`<WorkspaceView workspace={ws} locked />` where
|
||||
`ws = useDashboardState<LayoutNode>('screens/<name>', defaultLayout)`, guarded by a `normalizeLayout`
|
||||
that pins `appType`s to an allow-list. Panels are windowed apps under
|
||||
`src/workspaces/officerdev/src/apps/<Feature>/`, each exporting `appRegistryMetas`
|
||||
(`{ key, name, icon, component, availableOnPanel: false }`) and registered in `AppRegistry.tsx`.
|
||||
The Workspace/Panel framework is orthogonal to routing — it contains no route navigation, and panels
|
||||
live inside the Route element tree, so they can call `useParams`/`useSearchParams` directly.
|
||||
- **Page title by route.** Automatic — no rule to add. `titleForPath` in
|
||||
`src/apps/officer-web/state/usePageTitle.ts` takes the URL's first path segment, turns `kebab-case`
|
||||
into `Title Case`, and that's the tab title; `usePageTitleSync` does the rest. A screen that wants to
|
||||
say more than its route does (a chat's own name, not just "Chat") publishes an override instead —
|
||||
`usePublishPageTitle` in `officerdev`.
|
||||
|
||||
### The URL is the source of truth for selection
|
||||
|
||||
`docs/navigation-audit.md` is the authority here — read it before building a screen that selects
|
||||
things. It names the **"opaque click" anti-pattern**: an element that opens something addressable but
|
||||
keeps the id in an onClick closure instead of the DOM, leaves the URL unchanged, holds the selection
|
||||
in `usePanelChannel`/`useGlobal`, and has no anchor semantics (no cmd-click, no middle-click, not
|
||||
link-focusable). Half the app still does this; none of the new code should.
|
||||
|
||||
- **Addressable state goes in the URL** (`useParams` / `useSearchParams`), never in a channel.
|
||||
`usePanelChannel` is for genuine signals and refresh buses (`files:refresh-signal`,
|
||||
`SLSKD_REFRESH_CHANNEL`, `MUSIC_RESYNC_CHANNEL`) — and declare one with `defineChannel` in
|
||||
`officerdev/src/channels.ts` rather than spelling the name and type at each site.
|
||||
"Which thing is open" is a URL. Panels each read the URL rather than passing it between themselves.
|
||||
- **Rows and nav items are real links.** `<Link>` for rows (exemplar: the `/chat` session list,
|
||||
`f35c145`); **react-router's `<NavLink>`** for nav chrome, so active state comes from the router.
|
||||
The hand-rolled `isActive` in `Dock`/`Header` is scheduled for replacement (audit Phase 4) — don't
|
||||
copy it. A disabled entry renders as a `<span>`; a disabled `<a>` is not a thing. A control that
|
||||
_mutates_ rather than navigates stays a `<button>`.
|
||||
- **Route pairs.** A bare screen route plus a param route rendering the same component: `/chat` +
|
||||
`/chat/:sessionId`, `/jobs` + `/jobs/:id`, `/headscale` +
|
||||
`/headscale/:section`. One `<Navigate … replace />` guard in the screen, placed after all hooks,
|
||||
canonicalises both the bare route and a bogus param.
|
||||
- **Master list + live preview uses `?selected=<id>`**, not the detail route — linking rows straight
|
||||
to `/x/:id` destroys preview-on-list, because that route is the full page. Rows link to
|
||||
`/x?selected=id` on-page and `/x/:id` off-page; list, mobile panel and preview all read the param.
|
||||
Action buttons are **siblings** of the anchor, never nested inside it.
|
||||
- **`src/workspaces/components/NavLink.tsx` is not react-router's `NavLink`** — it's a `<Link>`
|
||||
wrapper that appends `useGlobalQueryString()` and provides no active state. Import react-router's
|
||||
when you want `isActive`.
|
||||
- Route helpers shared between an `officerdev` panel app and an `officer-web` screen must be
|
||||
re-exported from `src/workspaces/officerdev/src/index.ts` (named exports only — the barrel
|
||||
deliberately avoids `export *` for app modules to keep `appRegistryMetas` from colliding).
|
||||
|
||||
## COMMS — a channel between agents, when one is open
|
||||
|
||||
`COMMS/<work-stream>/` is a **tracked** channel between agents working on this repo from different machines.
|
||||
It exists because findings used to reach each other by the owner relaying them from memory at the end of long
|
||||
sessions.
|
||||
|
||||
**There is no open channel right now.** `COMMS/sidecar-app-store/` ran for one night — per-user Linux
|
||||
accounts through to a member's first agent turn — and was deleted when the work landed, which is the
|
||||
convention rather than an oversight: a spent channel left in place gets read as current.
|
||||
|
||||
If you open one:
|
||||
|
||||
- **Read it before starting**, if your task touches its work stream. It carries what is verified, what is
|
||||
assumed, what is broken, and what is waiting on a decision — the parts a commit message does not hold.
|
||||
- **Number the files and alternate**, one per turn, odd for one agent and even for the other. The parity is
|
||||
the author; the alternation is the protocol. A push with no doc is then visibly a break rather than
|
||||
something to find by diffing, and "nothing to report" is still a turn worth taking — silence and a crashed
|
||||
agent read identically.
|
||||
- **End on a checkable condition**, not on either party's judgement: no open item is actionable by a
|
||||
participant. "I think we're done" can close a thread with work still in it.
|
||||
- **Durable reasoning goes in `docs/` or next to the code.** The channel is for coordination. When the work
|
||||
lands, delete the channel and move anything still open to `TODO.md`.
|
||||
|
||||
Two things that made it work, and neither is about either agent being more careful. One writes, the other
|
||||
verifies, and only the verifier runs things on a real machine — most of what was caught was invisible to
|
||||
reading and needed a live filesystem. And the author of a comment is the worst-placed person to notice the
|
||||
code disagrees with it: the two most serious defects were both found by whoever had not written the sentence
|
||||
explaining why it was safe.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- `docs/navigation-audit.md` — **authoritative** on routing/navigation: the opaque-click anti-pattern,
|
||||
a severity-ranked findings table, the channel-selection map and the four-phase plan
|
||||
- `docs/email-recall.md` — **design, not built**: recall over your own correspondence. The split that
|
||||
matters is counting (needs every message judged) versus retrieval (needs the best few, fast) — and why
|
||||
a number produced by searching is confidently wrong with no signal that it is
|
||||
- `docs/find-my-device.md` — **design, not built**: locating your own devices from Officer. What is
|
||||
assembly (most of it), what is impossible (offline finding — there is no crowd to relay it), and the
|
||||
question to settle first, which is retention rather than anything technical
|
||||
- `docs/affordances.md` — what an affordance is, the three tests for whether something qualifies (including
|
||||
the one that catches most bad ones: _can it be fixed instead?_), the file format, and how they reach the
|
||||
agent. Read before writing one
|
||||
- `docs/agent-coordination.md` — **the north star** for the workspace/panel work: agents on one
|
||||
dashboard coordinating with each other instead of through the human, the handoff protocol, and what
|
||||
is deliberately _not_ being built. Read it before ranking, deferring or starting any panel item —
|
||||
it is what `docs/workspace-panel-todo.md` is ranked against.
|
||||
- `docs/workspace-panels.md` — how the Workspace/Panel framework works: the layout tree, how a panel is
|
||||
mounted and what it knows, the URL-vs-channel split for panel-to-panel communication, and the
|
||||
persistence key families. Read before building a panel app. Its defect list is
|
||||
`docs/workspace-panel-todo.md`.
|
||||
- `docs/multi-server-push.md` — **design, not built**: one Officer app receiving notifications from every
|
||||
server it is signed into. Works already, bar one missing field — and why the `mv` catalogue-version
|
||||
check turns into an endless resync between servers without it. The server identifier is an SSO decision
|
||||
- `docs/visual-regression-plan.md` — **plan, not built**: nightly screenshot regression against a JWT
|
||||
dashboard on a second server. The blocker is that a JWT lives in `localStorage` and iris copies only
|
||||
cookies, so an authenticated capture silently renders the login page — plus why diffing must happen
|
||||
before any agent is asked to look
|
||||
- `docs/plugin-dependency-scope.md` — a plugin declares WHO must be able to run each host binary. Why the
|
||||
owner's login shell is the wrong question for a `confined` plugin, the two-part reachability check
|
||||
(world-executable AND every parent traversable), and why members' binaries on alpha worked only because
|
||||
one home directory happened to be mode 751
|
||||
- `docs/plugin-route-authorization.md` — **design, not built**: making a plugin's settings routes
|
||||
owner-only while the plugin itself stays grantable. What the proxy should pass (`isOwner` and a level,
|
||||
never the role name), why declaring owner-only paths in the manifest beats trusting every plugin to
|
||||
remember, and the credential-resolution work that has to land first
|
||||
- `docs/roles-and-teams.md` — **plan, phase 0 built**: roles as a table, teams as scopes, and the one
|
||||
change that has to land first — the owner becomes an identity rather than whoever holds a role name,
|
||||
because otherwise "add a role" and "become the owner" are the same feature
|
||||
- `docs/localization.md` — **plan, not built**, with a working 5% skeleton already in the tree: taking the
|
||||
web UI to more than one language. What exists and what it cannot do yet, why the server should return
|
||||
error CODES rather than prose (and why a code must not leak more than the prose it replaced), the key
|
||||
naming convention, and the four phases. Read before adding a user-facing string
|
||||
- `docs/secret-store.md` — **design, not built**: moving the encryption and signing keys out of `.env`
|
||||
into a SQLite store, why they cannot live in Postgres, and key rotation. Also records the core/plugin
|
||||
split it assumes — light plus `officer-headscale` is the core; Vaultwarden and the wallet are plugins
|
||||
- `docs/sidecar-topology.md` — where the sidecar architecture is going, and what was considered and dropped
|
||||
- `docs/working-on-officer.md` — how to run, restart and check your work on this machine
|
||||
- `docs/wallet-key-custody.md` — what the platform can and cannot see of the wallet
|
||||
- `docs/editor-buffer-corruption.md` — an open bug with a trap set for it: background-job output appearing
|
||||
inside a file open in the editor. Read it BEFORE investigating a report of that, and before re-testing
|
||||
anything it already rules out
|
||||
- `docs/commander-directory.md` — **designed, not built**: a commander is a directory, not a session. Why
|
||||
its identity is currently borrowed from Claude's transcript id and what that costs — an ordering problem,
|
||||
a first-turn interlock that is a side effect rather than a signal, and a commander that dies with its
|
||||
conversation. The CLAUDE.md in its own working directory is the living document, for free
|
||||
- `docs/claude-md-touchpoints.md` — **audit**: every place the platform writes, appends to or reads a
|
||||
`CLAUDE.md` — three writers total (commander creation, the plugin chat-brief copier, and a one-off
|
||||
credential-backfill migration) plus one read-only doc-drift check, and three places that deliberately
|
||||
do NOT write one. Read before changing any part of the mechanism; includes a per-plugin table (only
|
||||
`proxy-manager` ships a chat brief today)
|
||||
- `docs/plugin-capabilities.md` — **built**: a plugin's tasks, skills and affordances are
|
||||
READ where they live, never copied into `capabilities/`. Why copying breaks a forkable repository, why it
|
||||
goes stale on update and survives a disable, and why separate directories beat namespaced paths —
|
||||
a namespace makes provenance readable, separate directories make it structural
|
||||
- `docs/filesystem-quotas.md` — **planned, not done**: the host-side half of per-user and per-team storage
|
||||
limits. Why the kernel has to enforce it rather than the platform (members have `terminal` and can write
|
||||
past anything we count), why `usrquota`+`grpquota` and not project quotas, and the one thing easiest to
|
||||
get wrong — a team folder that is not `setgid` charges nothing to the team
|
||||
- `TODO.md` — current direction and deferred work; **takes precedence over this file where they disagree**
|
||||
- `src/apps/CLAUDE.md` — shared frontend patterns
|
||||
- `src/databases/CLAUDE.md` — database patterns
|
||||
- `CONVENTIONS.md` — component organisation, state management and React patterns, with rationale;
|
||||
`src/workspaces/officerdev/APP_CONVENTIONS.md` and `HOOK_CONVENTIONS.md` for panel apps and hooks
|
||||
|
||||
Treat the code as the source of truth where anything here disagrees with it.
|
||||
|
||||
@@ -1,563 +1,6 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Project Overview
|
||||
**The instructions live in [`AGENTS.md`](AGENTS.md). Read it first — this file only points there.**
|
||||
|
||||
Officer is a self-hosted platform built around one person — the server owner — which since 2026-08-07
|
||||
also admits **additional accounts holding a strict subset of it**. It bundles an AI agent, a terminal,
|
||||
a file browser, a code editor, a bitcoin wallet, a remote desktop and customisable dashboards
|
||||
behind a single web app.
|
||||
|
||||
**The owner/member split, and where the line falls.** This file said "single-user is a hard invariant,
|
||||
not a stage" until 2026-08-07. That is no longer true and had already stopped being true when it was
|
||||
written: `users` holds six rows. The accurate statement is narrower and more useful —
|
||||
|
||||
- **One owner.** User id 1, role `Super Admin`, created by `POST /auth/bootstrap` while the table is
|
||||
empty, pinned there by a CHECK constraint. The owner bypasses every permission check.
|
||||
- **Other accounts get only what their ROLE is granted.** Roles are `Admin`, `Member`, `Developer`;
|
||||
grants live in `role_permissions`, keyed on role, never on user. Absence denies — there is no row
|
||||
meaning "no", so an empty table is a server where members reach nothing but their own profile.
|
||||
- **Some things can never be shared, structurally.** Tasks, items, desktop and browser are
|
||||
`kind: 'execution'`: they run as the owner's OS user in the owner's home, so there is no level of
|
||||
"read" that makes them safe. They have no level at all and the grants API refuses to store one.
|
||||
- **And some are shared only because the kernel enforces it.** Terminal, chat and files are
|
||||
`kind: 'confined'`, added 2026-08-11 with per-user Linux accounts. They still touch the filesystem
|
||||
and still run processes — but not the _owner's_, because the account has its own Linux user, its own
|
||||
home, and the kernel refusing everything above it.
|
||||
|
||||
The distinction earns its keep in one place: **a confined grant means nothing without that Linux
|
||||
user.** `authorize.ts` drops it for an account whose `osUser` is null, so "granted but unconfined"
|
||||
resolves to no access rather than to the owner's home — which is what it would otherwise resolve to,
|
||||
since `getOwnerHomeDir` ignores the email it is passed. That rule lives there once and covers the
|
||||
HTTP routes, the websocket doors and the dock together.
|
||||
|
||||
So "which user is this" has a real answer for the **app** surface (gitea, music, photos,
|
||||
calendar…) and for the **confined** one (terminal, chat, files), and is still always "the owner" for
|
||||
anything under `execution`.
|
||||
|
||||
`src/servers/permissions/registry.ts` is the authority and reads as the design document for this.
|
||||
**Mounting a router without a registry entry makes the server refuse to boot** — see "Permissions"
|
||||
below before adding one.
|
||||
|
||||
**Account creation exists.** `POST /api/users` (owner-gated), with a form under Settings → User Management:
|
||||
it validates the password with the same rules bootstrap uses, refuses a role that is not a row in `roles`,
|
||||
refuses `Super Admin` outright because there is exactly one owner, optionally takes an inbound SSH key, and
|
||||
provisions the Linux account. `POST /users/:id/provision-linux` retries that half if the host was not ready.
|
||||
|
||||
This file said "there is no way to create a second account" for some days after `69a31051` shipped one, and
|
||||
`docs/roles-and-teams.md` sequenced a whole phase around building it. Neither is checkable by
|
||||
`bun run docs:check` — it compares numbers, and this was prose. Worth knowing as the shape of the failure:
|
||||
the counts stay right and the sentences rot.
|
||||
|
||||
## Architecture
|
||||
|
||||
One Bun process (`src/server.tsx`) serves everything:
|
||||
|
||||
- the React SPA, via Bun's HTML import of `src/apps/officer-web/index.html` (HMR in dev)
|
||||
- the REST API, a Hono app mounted at `/api` (`src/servers/hono.ts`)
|
||||
- eight WebSocket providers — terminal, chat, task-runner, pipeline, cliamp, cliamp-audio, desktop,
|
||||
vault — plus a sidecar registration socket. `terminal` is a byte relay onto the pty sidecar's own
|
||||
listener, not a translating bridge; `vault` is the same shape onto Vaultwarden's notifications hub.
|
||||
- ~~a browser relay on its own port~~ — switched off 2026-08-13, awaiting extraction into a plugin.
|
||||
The extension and `api/browser/` stay on disk; the listener and the `/api/browser` mount do not.
|
||||
|
||||
Long-running and privileged work lives in **sidecars**: separate processes that dial back in over
|
||||
`/api/sidecar/register` and are tracked in `src/servers/sidecar-registry.ts`. PM2 runs them
|
||||
(the generated `ecosystem.config.cjs` — see below): `officer` (the server), `officer-anthropic-proxy`, `officer-claude-code`,
|
||||
`officer-opencode`, `officer-pty`, `officer-vnc`, `officer-music`, `officer-vault`,
|
||||
`officer-slskd`, `officer-headscale`, `officer-transmission`, `officer-invoiceshelf`, `officer-wallet`,
|
||||
`officer-photos`, `officer-notify`, `officer-caldav`, `officer-memos`, `officer-jellyfin`, `officer-gitea`
|
||||
— twenty as of 2026-08-06, and a list that goes stale every time a sidecar lands. `pm2 jlist` is the
|
||||
source of truth.
|
||||
|
||||
**`officer-anthropic-proxy` and `officer-claude-code` are not the same thing.** (The second was
|
||||
called `officer-agent` until 2026-08-13; older docs use that name.) The proxy holds the Anthropic
|
||||
credential and forwards API traffic; the agent is the process that spawns `claude`. They were one entry
|
||||
named `officer-claude` until the sidecar-isolation work — which is exactly how the false claim that
|
||||
"restarting officer doesn't disturb the agent" survived so long. Every sidecar is a PM2 peer of
|
||||
`officer`, so **no sidecar is a child of the server and restarting the server does not kill one.**
|
||||
|
||||
Agents run **unsandboxed as the server owner**, with `--dangerously-skip-permissions`. This is
|
||||
deliberate — it is the owner's own machine. Do not add a jail without being asked.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
```
|
||||
src/
|
||||
├── server.tsx # the single entrypoint: routes, WS upgrades, static files
|
||||
├── apps/
|
||||
│ └── officer-web/ # the SPA shell — Screens/Authentication + Screens/Dashboard
|
||||
├── servers/
|
||||
│ ├── hono.ts # router composition; everything under /api
|
||||
│ ├── _middlewares/ # auth, body parsing, the permission gate, rate limiting
|
||||
│ ├── api/<feature>/ # one folder per feature, each exporting a router
|
||||
│ ├── channels/ # send-claude-code / send-opencode — how /chat drives an agent turn
|
||||
│ ├── queue/ # background job engine
|
||||
│ └── sidecar/ # sidecar implementations + the wire protocol
|
||||
├── databases/officer_db/ # the only database (Postgres + Drizzle)
|
||||
├── extensions/browser-relay/
|
||||
└── workspaces/ # shared packages, each a bun workspace
|
||||
```
|
||||
|
||||
`src/workspaces/officerdev` is the biggest of these: the windowed "apps" (FileBrowser, Chat,
|
||||
Terminal, CodeEditor, Desktop, Dashboards, Wallet…) that the shell hosts, behind an `AppRegistry`.
|
||||
`src/apps/officer-web` is only the shell — screens, routing and settings.
|
||||
|
||||
**Path aliases** (`tsconfig.json`): `@/*` → `src/apps/officer-web`, `@/components/*` →
|
||||
`src/workspaces/components`, `@@/*` → `src/servers`, `@/public/*` → `public`. Workspace packages are
|
||||
imported by their package name (`officerdev`, `hooks`, `state`, `types`, `helpers`, …).
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Runtime**: Bun (Node 22 or newer is enforced by a `preinstall` check)
|
||||
|
||||
That check demanded _exactly_ 22 until 2026-08-12. The reason was a `node-pty` build
|
||||
failure some months earlier, whose details were not recorded. It was relaxed to `>= 22`
|
||||
after confirming node-pty ships **no Linux prebuilds** — its install script always falls
|
||||
through to `node-gyp rebuild`, so it compiles against whatever Node is present and there
|
||||
is no ABI to mismatch. Untested on 24 at the time of the change. If `bun install` fails
|
||||
building node-pty, or `officer-pty` cannot load its native module, restore the exact pin
|
||||
first. The source build also needs `build-essential` and `python3`.
|
||||
|
||||
**Bun itself is held at the 1.3 series, on purpose and temporarily.** 1.4.0 was published
|
||||
2026-08-20; the owner asked on 2026-08-22 to stay on 1.3 for a few months until 1.4 has been
|
||||
watched. Two places carry that number and they move together: `BUN_SERIES` in
|
||||
`scripts/setup/machine-setup/lib/dev.sh`, which resolves the newest `1.3.x` from the npm registry
|
||||
and passes it to the installer as a release tag, and `engines.bun` in `package.json`, which is
|
||||
what `bun run doctor` reads. bun ignores `engines` (verified — an install declaring `1.9.x` ran
|
||||
clean under 1.3.14), so that field is the declaration and doctor is the enforcement.
|
||||
|
||||
**Do not run `bun upgrade` on a machine running Officer.** It takes no version argument — latest
|
||||
stable or `--canary`, nothing else — so it jumps straight past the pin and says nothing. That is
|
||||
the whole reason `doctor` checks the running version at all; `machine-setup.sh --only 'JavaScript
|
||||
runtimes'` offers to pin a drifted machine back down. Lifting the hold is `todo/infra/`.
|
||||
|
||||
- **Language**: TypeScript, strict. `bunx tsgo` is clean — keep it that way.
|
||||
- **Frontend**: React 19, React Router 7, React Query, Tailwind 4, shadcn/ui + custom components
|
||||
- **Backend**: Hono
|
||||
- **Database**: Postgres via Drizzle — `officer` for the platform, plus `officer_marketplace` on the
|
||||
host that serves marketplace.officer.dev (see `docs/marketplace.md`)
|
||||
- **Agents**: Claude Code and opencode, driven through sidecars; tools exposed over MCP
|
||||
|
||||
## Data
|
||||
|
||||
Two stores, and the split matters:
|
||||
|
||||
**Postgres** (`src/databases/officer_db`) holds the account, passkeys, settings, dashboards,
|
||||
queue and pipeline jobs. Since 2026-08-16 there is a SECOND database,
|
||||
`officer_marketplace` (`src/databases/marketplace_db`), and the split is deliberate: it is a public
|
||||
catalogue served by a process with no login, no session and no user, so sharing a connection would put
|
||||
an unauthenticated surface one query away from every private table. It runs only on the host serving
|
||||
marketplace.officer.dev — `docs/marketplace.md`. One directory per feature holding `schema.ts` and
|
||||
`queries.ts` beside each other; `src/schema.ts` is what `db:push` reads, and it lists the core tables
|
||||
with the plugin ones commented out. Types inferred from the schema in `src/types.ts`.
|
||||
|
||||
**The filesystem** holds everything the agent authors. `OFFICER_ITEMS_DIR` (`$OFFICER_ROOT/capabilities`)
|
||||
contains one directory per item under `skills/`, `tools/`, `tasks/`, `processes/`, `extensions/` — no
|
||||
database rows, no scope tiers. `DATA_PATH/<email>/` holds the managed home and attachments. It also holds
|
||||
`email_accounts/`, which is the **email plugin's** — the platform pre-creates the directory and never opens
|
||||
what is inside it.
|
||||
|
||||
**None of those paths is configured.** Since 2026-08-13 `src/servers/data-path.ts` derives the install
|
||||
root as `resolve(process.cwd(), '..')` and hangs `data/`, `permissions/` and `dockers/` off it. That
|
||||
replaced `DATA_PATH`, `OFFICER_ITEMS_DIR` and `HOME_DIR` in `.env` — three values that had to agree with
|
||||
each other and with the tree on disk. `assertInstallLayout` refuses to boot when the working directory
|
||||
is not the repo, because otherwise a wrong `cwd` relocates the whole install silently rather than
|
||||
failing.
|
||||
|
||||
Note `getHomeDir` (the managed home under `DATA_PATH`, now used only for NON-owner accounts and by
|
||||
pipeline-executor) versus `getOwnerHomeDir` (the owner's real login home, where terminals, chats and
|
||||
task runs execute — captured from `homedir()` once at module load, and it ignores the email it is
|
||||
passed).
|
||||
|
||||
### Schema changes use `push`, not migrations
|
||||
|
||||
This database is kept in sync with `bun db:push`, which diffs the schema code against the live
|
||||
database and alters it directly. **`drizzle-kit migrate` has never been run here** — there is no
|
||||
`__drizzle_migrations` table. Change the schema, run `bun db:push`, done.
|
||||
|
||||
`bun db:gen` writes files to `officer_db/migrations/`, but nothing applies them; the old numbered
|
||||
history was deleted because it had drifted from the real schema. Treat the schema code, not those
|
||||
files, as the source of truth.
|
||||
|
||||
**Declare multi-column uniqueness as `uniqueIndex('uq_…').on(a, b)`, never `unique('uq_…').on(a, b)`** —
|
||||
drizzle-kit mis-diffs named composite unique _constraints_ and re-creates them on every push, which used
|
||||
to stop `db:push` on an unanswerable truncate prompt. Same for any foreign key whose generated name would
|
||||
exceed Postgres's 63-character identifier limit: name it explicitly. See `src/databases/CLAUDE.md` →
|
||||
"Composite keys" before adding either.
|
||||
|
||||
## Security Model
|
||||
|
||||
- `IS_DEV_BUILD` (`src/servers/build-env.ts`) is true **only** when `PUBLIC_BUILD_ENV` is explicitly
|
||||
`dev`/`development`. Everything else, including unset, is hardened. Rate limiting and password
|
||||
rules key off it — they fail closed.
|
||||
- **There is no origin checking.** It was removed on 2026-08-13, along with `ALLOW_ANY_ORIGIN` and
|
||||
`ALLOW_ANY_ORIGIN_MUSIC`. The flag defaulted to ON, so origin validation ran on no real install —
|
||||
what came out was documented defence in depth that was already switched off. Origin was never
|
||||
authentication here anyway: an app's `officer://<hex>` origin is chosen by the client, forgeable
|
||||
outside a browser, and extractable from a shipped binary. The perimeter is the tailnet, and the lock
|
||||
is a valid token on every protected route plus the permission gate below.
|
||||
- JWTs are 30-day, blacklisted on signout, and invalidated by a password change (`passwordChangedAt`).
|
||||
**The role is deliberately not a claim** — every authorization decision re-reads `users.role` from
|
||||
Postgres, so a grant or a revoke takes effect on the next request rather than at next sign-in.
|
||||
- A panic lockdown (`src/servers/api/auth/panic.ts`) is in-memory only and refuses every
|
||||
authenticated request until the server restarts.
|
||||
|
||||
### Permissions — read this before mounting a router
|
||||
|
||||
Authorization is one system, and it is not in `userMiddleware` (which only answers "is this token
|
||||
valid"). It is `_middlewares/permission-gate.ts` → `permissions/authorize.ts`, mounted globally in `hono.ts`
|
||||
ahead of everything, and it re-verifies the token itself so it covers routes that never mount
|
||||
`userMiddleware`.
|
||||
|
||||
- `permissions/registry.ts` — the single enumeration of what the platform can do, in five kinds:
|
||||
`core` (every account, not deniable), `app` (**the grantable surface**), `confined` (grantable, but
|
||||
only to an account that has a Linux user), `execution` and `admin` (owner only, and `execution` is
|
||||
never grantable at any level). **21 entries as of 2026-08-27** — verified by `bun run docs:check`, which fails if this number drifts again: 6 core, 2 app, 4 confined, 3 execution, 6 admin (`todos`, the todo board, is the sixth). It was 22 until caldav became a plugin and took `calendar` with it — a plugin's permission is registered at runtime from its manifest, so it is real but not in this file's count. `notify` moved from `app` to `core` on 2026-08-24: it was grantable, nothing granted it, and every Member's app was silently 403'd registering its own push token. It said 27 for nine days. The execution count dropped by one when Minesweeper became a plugin — see `plugins/minesweeper/manifest.ts` for why that was a fix rather than a downgrade.
|
||||
- `permissions/authorize.ts` — resolves "may this account do this". Owner short-circuits first; every
|
||||
other answer is role grants plus core, with `execution`/`admin` stripped even if a row grants them,
|
||||
and `confined` stripped for an account with no `osUser`.
|
||||
**Every catch returns deny.** Grants are cached by role and the cache's whole invalidation contract
|
||||
is `invalidateRoleGrants`, called by the one writer in `api/users/permissions-routes.ts`.
|
||||
- `permissions/totality.ts` — `assertPermissionTotality` runs in `server.tsx` **before `serve()` and
|
||||
throws**. Mount a router or a socket without a registry entry and `pm2 restart officer` fails,
|
||||
naming what is missing. That is deliberate: the hole it closes was a Member 403'ing on
|
||||
`GET /api/tasks` and opening `/api/tasks/pipeline/ws` with a 101 in the same minute, because Bun's
|
||||
route table matches the socket before the `/api/*` catch-all that reaches Hono. A patch does not
|
||||
survive the next door; refusing to boot does.
|
||||
|
||||
So **adding a router means adding one line to `CAPABILITIES`**. If the surface genuinely is not
|
||||
user-gated, add it to `EXEMPT_API_PREFIXES` in `totality.ts` _with a reason_ — an unexplained exemption
|
||||
is how the hole happened the first time.
|
||||
|
||||
The frontend hook `usePermissions` **fails open** on purpose: hiding a dock icon is a courtesy, the
|
||||
403 is the lock, and an owner locked out by a transient network error is worse than a member clicking
|
||||
into a refusal.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
bun dev # the whole app — SPA + API + WebSockets, watched
|
||||
bun start # production
|
||||
bunx tsgo # typecheck (not tsc)
|
||||
bun test # tests
|
||||
bun format # prettier over every dirty file — see the note below before running it
|
||||
bun db:push # apply the schema to Postgres
|
||||
bun docs:check # do the docs still match the code? REQUIRED before tagging a release
|
||||
bun setup # runs scripts/install.sh — blank machine to running platform
|
||||
```
|
||||
|
||||
**`bun docs:check` before every release, and leave it green.** It compares documented claims against values
|
||||
derived at run time — the permission count, the PM2 entry count, every settings route Spotlight offers — and
|
||||
exits non-zero on drift. A check must never compare a doc against a second hard-coded copy; that is one more
|
||||
place to drift, and it drifts in the same edit that misses the doc.
|
||||
|
||||
It is narrow on purpose. It cannot read prose and judge it, only claims with a machine-checkable
|
||||
counterpart — which is a small part of the documentation and the part that rots fastest, because a number is
|
||||
exactly what nobody re-derives while editing the sentence around it. Both claims it found on the day it was
|
||||
written had been wrong for over a week.
|
||||
|
||||
`scripts/install.sh` is only an orchestrator — it runs the two halves in order and does nothing itself:
|
||||
`setup/machine-setup/machine-setup.sh` (28 sections: packages, tailnet, runtimes, docker, shell) then
|
||||
`setup/officer-setup.sh` (11: pre-flight, layout, repository, dependencies, database, environment, secrets,
|
||||
schema, build, services, verify). Either runs alone — `--machine-only`, `--officer-only`, or by path — because
|
||||
a machine you already trust needs only the second. Both are re-runnable: each records the steps it finished
|
||||
and skips them, so stopping halfway costs nothing. **Run it as yourself**; it re-execs through `sudo` when it
|
||||
needs to, and on macOS never does, because Homebrew refuses to run as root.
|
||||
|
||||
Sidecar control is PM2, not npm scripts: `pm2 restart officer-<name>`, `pm2 logs officer-<name>`.
|
||||
See `docs/working-on-officer.md` for which process a given change needs restarted.
|
||||
|
||||
### Installs are frozen. Never resolve a dependency you did not ask for.
|
||||
|
||||
`bunfig.toml` sets `[install] frozenLockfile = true`, so **`bun install` resolves from `bun.lock` and
|
||||
nothing else** — it fails rather than quietly picking up a newer version, including a transitive one
|
||||
nobody chose. Verified on bun 1.3.10: a lockfile that no longer satisfies `package.json` exits 1 with
|
||||
`error: lockfile had changes, but lockfile is frozen`.
|
||||
|
||||
It is config rather than a habit because a supply-chain compromise does not wait for the one time
|
||||
somebody forgets a flag. On **2026-08-04** eleven cache packages — `keyv`, `flat-cache`,
|
||||
`file-entry-cache`, `cacheable-request`, `cache-manager`, the `@cacheable/*` scope, `ecto` — were
|
||||
published with a `preinstall` dropper that harvested npm and GitHub tokens, AWS and Kubernetes
|
||||
credentials, SSH and PEM keys, `.env` files and `.claude/settings.json`, then republished itself
|
||||
through any npm token it found. It reached 434 further packages across 1,381 versions. This machine was
|
||||
unaffected only because nothing had installed since 2026-08-02.
|
||||
|
||||
**To change a dependency:** edit `package.json`, allow the lockfile to change deliberately, **read the
|
||||
diff**, and commit it. Note that `--no-frozen-lockfile` — which this file and `bunfig.toml` both used to
|
||||
name — is NOT a flag bun 1.3.14 has; it is silently ignored and the install still fails frozen. Comment
|
||||
out `frozenLockfile` in `bunfig.toml` for the one command, then put it back. The friction is the point — an unexplained lockfile change
|
||||
in a diff is the signal this exists to produce.
|
||||
|
||||
**Do not** add `--no-frozen-lockfile` to a script, a Dockerfile or CI to make an error go away. The
|
||||
error means the lockfile and `package.json` disagree, and that is worth a human look every time.
|
||||
|
||||
**Format your own files, not the whole dirty tree.** `bun format` globs `git diff --name-only HEAD`,
|
||||
so it rewrites every uncommitted file — including work in progress that isn't yours, which then shows
|
||||
up as unexplained whitespace churn in someone else's diff. Run `bunx prettier --write <paths>` on the
|
||||
files you actually touched. `bun format` is only safe when the tree is otherwise clean.
|
||||
|
||||
## Code Style
|
||||
|
||||
- **Paradigm**: functional — pure functions, immutability, composition
|
||||
- **TypeScript**: strict, no `any`. Type-only imports are required (`verbatimModuleSyntax`).
|
||||
- **Comments**: minimal, and about _why_. Don't narrate what the code already says.
|
||||
- **Async**: always async/await
|
||||
- **Exports**: named only, no defaults
|
||||
- **Files**: `PascalCase.tsx` for components, `kebab-case.ts` for everything else
|
||||
- **Prettier**: single quotes in JS, double in JSX, semicolons, trailing commas, 120 cols
|
||||
|
||||
### Imports
|
||||
|
||||
Order: types → external → workspace → relative.
|
||||
|
||||
```ts
|
||||
import type { User } from 'types';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { formatDate } from 'helpers/formatters';
|
||||
import { useWebsites } from '../useWebsites';
|
||||
```
|
||||
|
||||
In app code import types from `'types'`, which re-exports the database types. Only server and
|
||||
database code imports from `officerdb/types` directly.
|
||||
|
||||
### Functions
|
||||
|
||||
Arrow functions for one-liners, regular functions for anything with real logic. No multiline
|
||||
parameter lists — extract a params type instead.
|
||||
|
||||
```ts
|
||||
type ProcessDataParams = { body: Record<string, unknown> | undefined; query: Record<string, string> };
|
||||
export function processData({ body, query }: ProcessDataParams): Result { ... }
|
||||
```
|
||||
|
||||
### Components and hooks
|
||||
|
||||
```tsx
|
||||
type ExperimentCardProps = { experiment: Experiment; onSelect: (id: number) => void };
|
||||
|
||||
export const ExperimentCard = ({ experiment, onSelect }: ExperimentCardProps) => { ... };
|
||||
```
|
||||
|
||||
Complex hooks return objects; simple state hooks return `as const` tuples. Event parameters are
|
||||
always named `ev`, never `e`.
|
||||
|
||||
### API calls
|
||||
|
||||
`useClient()` returns typed verbs — `client.get<Foo>('/foo')` really does return `Foo`, so pass the
|
||||
type parameter and let inference flow from it.
|
||||
|
||||
## Working With Me
|
||||
|
||||
- **Ask first** — confirm the approach before a significant change
|
||||
- **Explore thoroughly** — read the related files before editing
|
||||
- **Keep it simple** — no over-engineering, no premature abstraction
|
||||
- **Be explicit** — no magic, no implicit behaviour
|
||||
- **Stay focused** — note unrelated problems, don't fix them uninvited
|
||||
- **Report honestly** — say what you verified and what you didn't
|
||||
|
||||
**Always commit and push when you finish implementing — including when it went wrong.** Don't wait to be
|
||||
asked, and don't hold a branch back because it is unfinished, untested or turned out to be a dead end. The
|
||||
history of the mistakes is worth having: a reverted commit and its message explain why an approach was
|
||||
abandoned, which is exactly the thing that gets lost when a failed attempt is quietly discarded. Say what
|
||||
state it is in — in the commit message and in `COMMS/` if another agent will pick it up — rather than
|
||||
withholding the commit until it is good.
|
||||
|
||||
Commit messages: simple lowercase, no prefixes.
|
||||
|
||||
**Stage and commit in ONE step, naming the paths.** `git add <path>` then a bare `git commit` commits the
|
||||
whole **index**, not the path just named — so anything a concurrent session had staged goes into your
|
||||
commit, under your message and your session trailer. Use `git commit -- <paths>` instead, which does what
|
||||
the two-step form only looks like it does.
|
||||
|
||||
This is not hypothetical and it is not rare: two agents share this working tree most nights. On
|
||||
2026-08-23 commit `6e092c32` says "marketplace: minesweeper in the catalogue" and contains nine files of
|
||||
another session's roles work, swept up mid-`git add`. The other session was right not to amend it —
|
||||
rewriting shared history to fix a message is the worse trade — so the record was corrected with a
|
||||
follow-up note instead. Cheap to avoid, awkward to undo.
|
||||
|
||||
Two things about the form itself, both learned the same night. `-m`/`-F` goes BEFORE the `--`, or git
|
||||
reads the message as a pathspec. And it only works on **tracked** files — a new file must be `git add`ed
|
||||
first, so a commit introducing one is `git add <new>` then `git commit -- <paths>`, naming every path.
|
||||
Getting that wrong fails loudly, which is the good case: the release tag that followed it went onto the
|
||||
wrong commit, and only because the tag was checked afterwards did that surface at all.
|
||||
|
||||
**An agent's commit names the session that made it.** A trailer, below `Co-Authored-By`:
|
||||
|
||||
```
|
||||
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
|
||||
```
|
||||
|
||||
The transcript id, not the session name — names are not stable. On 2026-08-23 one session was
|
||||
`platform-e2` and then `platform-18`, and another `platform-59` then `platform-72`, both renamed by a
|
||||
restart in a single night. The transcript id survived both.
|
||||
|
||||
Why it earns a line in every commit: three agents committed to this repository in one night and `git log`
|
||||
could not tell them apart. `Co-Authored-By` says "an agent", which stopped being useful the moment there was
|
||||
more than one. And the transcript holds the reasoning a commit message cannot — the arguments considered and
|
||||
dropped, what was measured, what the owner decided and why. A commit that names its session is a commit
|
||||
whose "why" is still answerable in six months.
|
||||
|
||||
**The precondition, and it is not built yet:** an agent cannot reliably discover its own transcript id. The
|
||||
only exposure is that a background task's output path contains it, which means starting a job to learn who
|
||||
you are. `commanderBlock` already hands a commander its id in the preamble, so the mechanism exists —
|
||||
`todo/agent-coordination/` carries giving it to every session. Until then, an agent that knows its id should
|
||||
add the trailer and one that does not should leave it out rather than guess.
|
||||
|
||||
## Frontend route conventions (apply to EVERY new dashboard route)
|
||||
|
||||
Worked examples: `/soulseek`, `/music`, `/chat`.
|
||||
|
||||
- **Workspace/Panel framework, always — never a standalone single screen.** The screen renders
|
||||
`<WorkspaceView workspace={ws} locked />` where
|
||||
`ws = useDashboardState<LayoutNode>('screens/<name>', defaultLayout)`, guarded by a `normalizeLayout`
|
||||
that pins `appType`s to an allow-list. Panels are windowed apps under
|
||||
`src/workspaces/officerdev/src/apps/<Feature>/`, each exporting `appRegistryMetas`
|
||||
(`{ key, name, icon, component, availableOnPanel: false }`) and registered in `AppRegistry.tsx`.
|
||||
The Workspace/Panel framework is orthogonal to routing — it contains no route navigation, and panels
|
||||
live inside the Route element tree, so they can call `useParams`/`useSearchParams` directly.
|
||||
- **Page title by route.** Automatic — no rule to add. `titleForPath` in
|
||||
`src/apps/officer-web/state/usePageTitle.ts` takes the URL's first path segment, turns `kebab-case`
|
||||
into `Title Case`, and that's the tab title; `usePageTitleSync` does the rest. A screen that wants to
|
||||
say more than its route does (a chat's own name, not just "Chat") publishes an override instead —
|
||||
`usePublishPageTitle` in `officerdev`.
|
||||
|
||||
### The URL is the source of truth for selection
|
||||
|
||||
`docs/navigation-audit.md` is the authority here — read it before building a screen that selects
|
||||
things. It names the **"opaque click" anti-pattern**: an element that opens something addressable but
|
||||
keeps the id in an onClick closure instead of the DOM, leaves the URL unchanged, holds the selection
|
||||
in `usePanelChannel`/`useGlobal`, and has no anchor semantics (no cmd-click, no middle-click, not
|
||||
link-focusable). Half the app still does this; none of the new code should.
|
||||
|
||||
- **Addressable state goes in the URL** (`useParams` / `useSearchParams`), never in a channel.
|
||||
`usePanelChannel` is for genuine signals and refresh buses (`files:refresh-signal`,
|
||||
`SLSKD_REFRESH_CHANNEL`, `MUSIC_RESYNC_CHANNEL`) — and declare one with `defineChannel` in
|
||||
`officerdev/src/channels.ts` rather than spelling the name and type at each site.
|
||||
"Which thing is open" is a URL. Panels each read the URL rather than passing it between themselves.
|
||||
- **Rows and nav items are real links.** `<Link>` for rows (exemplar: the `/chat` session list,
|
||||
`f35c145`); **react-router's `<NavLink>`** for nav chrome, so active state comes from the router.
|
||||
The hand-rolled `isActive` in `Dock`/`Header` is scheduled for replacement (audit Phase 4) — don't
|
||||
copy it. A disabled entry renders as a `<span>`; a disabled `<a>` is not a thing. A control that
|
||||
_mutates_ rather than navigates stays a `<button>`.
|
||||
- **Route pairs.** A bare screen route plus a param route rendering the same component: `/chat` +
|
||||
`/chat/:sessionId`, `/jobs` + `/jobs/:id`, `/headscale` +
|
||||
`/headscale/:section`. One `<Navigate … replace />` guard in the screen, placed after all hooks,
|
||||
canonicalises both the bare route and a bogus param.
|
||||
- **Master list + live preview uses `?selected=<id>`**, not the detail route — linking rows straight
|
||||
to `/x/:id` destroys preview-on-list, because that route is the full page. Rows link to
|
||||
`/x?selected=id` on-page and `/x/:id` off-page; list, mobile panel and preview all read the param.
|
||||
Action buttons are **siblings** of the anchor, never nested inside it.
|
||||
- **`src/workspaces/components/NavLink.tsx` is not react-router's `NavLink`** — it's a `<Link>`
|
||||
wrapper that appends `useGlobalQueryString()` and provides no active state. Import react-router's
|
||||
when you want `isActive`.
|
||||
- Route helpers shared between an `officerdev` panel app and an `officer-web` screen must be
|
||||
re-exported from `src/workspaces/officerdev/src/index.ts` (named exports only — the barrel
|
||||
deliberately avoids `export *` for app modules to keep `appRegistryMetas` from colliding).
|
||||
|
||||
## COMMS — a channel between agents, when one is open
|
||||
|
||||
`COMMS/<work-stream>/` is a **tracked** channel between agents working on this repo from different machines.
|
||||
It exists because findings used to reach each other by the owner relaying them from memory at the end of long
|
||||
sessions.
|
||||
|
||||
**There is no open channel right now.** `COMMS/sidecar-app-store/` ran for one night — per-user Linux
|
||||
accounts through to a member's first agent turn — and was deleted when the work landed, which is the
|
||||
convention rather than an oversight: a spent channel left in place gets read as current.
|
||||
|
||||
If you open one:
|
||||
|
||||
- **Read it before starting**, if your task touches its work stream. It carries what is verified, what is
|
||||
assumed, what is broken, and what is waiting on a decision — the parts a commit message does not hold.
|
||||
- **Number the files and alternate**, one per turn, odd for one agent and even for the other. The parity is
|
||||
the author; the alternation is the protocol. A push with no doc is then visibly a break rather than
|
||||
something to find by diffing, and "nothing to report" is still a turn worth taking — silence and a crashed
|
||||
agent read identically.
|
||||
- **End on a checkable condition**, not on either party's judgement: no open item is actionable by a
|
||||
participant. "I think we're done" can close a thread with work still in it.
|
||||
- **Durable reasoning goes in `docs/` or next to the code.** The channel is for coordination. When the work
|
||||
lands, delete the channel and move anything still open to `TODO.md`.
|
||||
|
||||
Two things that made it work, and neither is about either agent being more careful. One writes, the other
|
||||
verifies, and only the verifier runs things on a real machine — most of what was caught was invisible to
|
||||
reading and needed a live filesystem. And the author of a comment is the worst-placed person to notice the
|
||||
code disagrees with it: the two most serious defects were both found by whoever had not written the sentence
|
||||
explaining why it was safe.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- `docs/navigation-audit.md` — **authoritative** on routing/navigation: the opaque-click anti-pattern,
|
||||
a severity-ranked findings table, the channel-selection map and the four-phase plan
|
||||
- `docs/email-recall.md` — **design, not built**: recall over your own correspondence. The split that
|
||||
matters is counting (needs every message judged) versus retrieval (needs the best few, fast) — and why
|
||||
a number produced by searching is confidently wrong with no signal that it is
|
||||
- `docs/find-my-device.md` — **design, not built**: locating your own devices from Officer. What is
|
||||
assembly (most of it), what is impossible (offline finding — there is no crowd to relay it), and the
|
||||
question to settle first, which is retention rather than anything technical
|
||||
- `docs/affordances.md` — what an affordance is, the three tests for whether something qualifies (including
|
||||
the one that catches most bad ones: _can it be fixed instead?_), the file format, and how they reach the
|
||||
agent. Read before writing one
|
||||
- `docs/agent-coordination.md` — **the north star** for the workspace/panel work: agents on one
|
||||
dashboard coordinating with each other instead of through the human, the handoff protocol, and what
|
||||
is deliberately _not_ being built. Read it before ranking, deferring or starting any panel item —
|
||||
it is what `docs/workspace-panel-todo.md` is ranked against.
|
||||
- `docs/workspace-panels.md` — how the Workspace/Panel framework works: the layout tree, how a panel is
|
||||
mounted and what it knows, the URL-vs-channel split for panel-to-panel communication, and the
|
||||
persistence key families. Read before building a panel app. Its defect list is
|
||||
`docs/workspace-panel-todo.md`.
|
||||
- `docs/multi-server-push.md` — **design, not built**: one Officer app receiving notifications from every
|
||||
server it is signed into. Works already, bar one missing field — and why the `mv` catalogue-version
|
||||
check turns into an endless resync between servers without it. The server identifier is an SSO decision
|
||||
- `docs/visual-regression-plan.md` — **plan, not built**: nightly screenshot regression against a JWT
|
||||
dashboard on a second server. The blocker is that a JWT lives in `localStorage` and iris copies only
|
||||
cookies, so an authenticated capture silently renders the login page — plus why diffing must happen
|
||||
before any agent is asked to look
|
||||
- `docs/plugin-dependency-scope.md` — a plugin declares WHO must be able to run each host binary. Why the
|
||||
owner's login shell is the wrong question for a `confined` plugin, the two-part reachability check
|
||||
(world-executable AND every parent traversable), and why members' binaries on alpha worked only because
|
||||
one home directory happened to be mode 751
|
||||
- `docs/plugin-route-authorization.md` — **design, not built**: making a plugin's settings routes
|
||||
owner-only while the plugin itself stays grantable. What the proxy should pass (`isOwner` and a level,
|
||||
never the role name), why declaring owner-only paths in the manifest beats trusting every plugin to
|
||||
remember, and the credential-resolution work that has to land first
|
||||
- `docs/roles-and-teams.md` — **plan, phase 0 built**: roles as a table, teams as scopes, and the one
|
||||
change that has to land first — the owner becomes an identity rather than whoever holds a role name,
|
||||
because otherwise "add a role" and "become the owner" are the same feature
|
||||
- `docs/localization.md` — **plan, not built**, with a working 5% skeleton already in the tree: taking the
|
||||
web UI to more than one language. What exists and what it cannot do yet, why the server should return
|
||||
error CODES rather than prose (and why a code must not leak more than the prose it replaced), the key
|
||||
naming convention, and the four phases. Read before adding a user-facing string
|
||||
- `docs/secret-store.md` — **design, not built**: moving the encryption and signing keys out of `.env`
|
||||
into a SQLite store, why they cannot live in Postgres, and key rotation. Also records the core/plugin
|
||||
split it assumes — light plus `officer-headscale` is the core; Vaultwarden and the wallet are plugins
|
||||
- `docs/sidecar-topology.md` — where the sidecar architecture is going, and what was considered and dropped
|
||||
- `docs/working-on-officer.md` — how to run, restart and check your work on this machine
|
||||
- `docs/wallet-key-custody.md` — what the platform can and cannot see of the wallet
|
||||
- `docs/editor-buffer-corruption.md` — an open bug with a trap set for it: background-job output appearing
|
||||
inside a file open in the editor. Read it BEFORE investigating a report of that, and before re-testing
|
||||
anything it already rules out
|
||||
- `docs/commander-directory.md` — **designed, not built**: a commander is a directory, not a session. Why
|
||||
its identity is currently borrowed from Claude's transcript id and what that costs — an ordering problem,
|
||||
a first-turn interlock that is a side effect rather than a signal, and a commander that dies with its
|
||||
conversation. The CLAUDE.md in its own working directory is the living document, for free
|
||||
- `docs/claude-md-touchpoints.md` — **audit**: every place the platform writes, appends to or reads a
|
||||
`CLAUDE.md` — three writers total (commander creation, the plugin chat-brief copier, and a one-off
|
||||
credential-backfill migration) plus one read-only doc-drift check, and three places that deliberately
|
||||
do NOT write one. Read before changing any part of the mechanism; includes a per-plugin table (only
|
||||
`proxy-manager` ships a chat brief today)
|
||||
- `docs/plugin-capabilities.md` — **built**: a plugin's tasks, skills and affordances are
|
||||
READ where they live, never copied into `capabilities/`. Why copying breaks a forkable repository, why it
|
||||
goes stale on update and survives a disable, and why separate directories beat namespaced paths —
|
||||
a namespace makes provenance readable, separate directories make it structural
|
||||
- `docs/filesystem-quotas.md` — **planned, not done**: the host-side half of per-user and per-team storage
|
||||
limits. Why the kernel has to enforce it rather than the platform (members have `terminal` and can write
|
||||
past anything we count), why `usrquota`+`grpquota` and not project quotas, and the one thing easiest to
|
||||
get wrong — a team folder that is not `setgid` charges nothing to the team
|
||||
- `TODO.md` — current direction and deferred work; **takes precedence over this file where they disagree**
|
||||
- `src/apps/CLAUDE.md` — shared frontend patterns
|
||||
- `src/databases/CLAUDE.md` — database patterns
|
||||
- `CONVENTIONS.md` — component organisation, state management and React patterns, with rationale;
|
||||
`src/workspaces/officerdev/APP_CONVENTIONS.md` and `HOOK_CONVENTIONS.md` for panel apps and hooks
|
||||
|
||||
Treat the code as the source of truth where anything here disagrees with it.
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Plugins
|
||||
|
||||
`EXTRACTING-A-PLUGIN.md` is the runbook for turning a platform feature into a plugin, and
|
||||
`EXTRACT-A-PLUGIN-PROMPT.md` is the way to hand that to a fresh agent. This file is for the concepts a
|
||||
plugin author needs that are not procedure.
|
||||
|
||||
**This directory holds documentation, not plugins.** Every plugin is its own repository; `plugins/<name>/`
|
||||
appears by `git clone` when somebody installs one, and is gitignored here.
|
||||
|
||||
---
|
||||
|
||||
## Affordances
|
||||
|
||||
**`docs/affordances.md` is the authority** — what one is, the three tests for whether something qualifies,
|
||||
the file format and how they reach the agent. Read it before writing one. What follows is only the part
|
||||
that is specific to shipping one from a plugin.
|
||||
|
||||
> An affordance is something the surface on the other end of the conversation offers the agent — declared
|
||||
> by the code that implements it, and read by the agent at runtime. Not what the agent can do; what the
|
||||
> client will honour.
|
||||
|
||||
A plugin ships an `affordances/` directory of markdown-with-frontmatter in its repository. Installing
|
||||
copies it to `capabilities/affordances/<publisher>/<appName>/`, uninstalling removes it — the same shape
|
||||
as `assets/` and `publishAssets`, and the namespace comes from where it lands rather than from anything
|
||||
inside the file.
|
||||
|
||||
**The test that catches most bad ones: can it be fixed instead?** If the answer is yes, fix it. An
|
||||
affordance describing a defect gives that defect a rationale, and the rationale outlives everyone's memory
|
||||
that it was a bug. See the two worked examples in `docs/affordances.md`.
|
||||
|
||||
Keep it short — every affordance is loaded into every conversation on this machine, including turns that
|
||||
have nothing to do with your plugin.
|
||||
|
||||
### A plugin-contributed one, for reference## Notifications — the same shape, for push
|
||||
|
||||
A plugin can also declare what its push notifications MEAN. Same mechanism, different store:
|
||||
|
||||
```
|
||||
capabilities/notifications/
|
||||
officerdev/music/
|
||||
catalogue.yaml
|
||||
```
|
||||
|
||||
```yaml
|
||||
nowPlaying:
|
||||
title: 'Now playing'
|
||||
route: 'officer://music/{id}'
|
||||
```
|
||||
|
||||
That becomes the code `officerdev/music:nowPlaying`. A push carries the code and integers — never content —
|
||||
and the device renders the title and follows the route. The point is that **adding a notification is a
|
||||
server change and never an app build**, because the mapping is synced to the device rather than compiled
|
||||
into it.
|
||||
|
||||
**The namespace comes from where the file lands, not from what it says.** Writing `officer/core:test` as a
|
||||
key in your own catalogue produces `<you>/<yourplugin>:officer/core:test`, not the core code — the same
|
||||
rule as `mountPrefix`, and pinned by test in `src/servers/notifications/catalogue.test.ts`.
|
||||
|
||||
An entry needs a `title`; `body`, `target`, `route` and `thread` are optional, `thread` defaults to your
|
||||
namespace, and unknown keys are dropped rather than forwarded to the device. Broken YAML in one plugin's
|
||||
catalogue is skipped without affecting anyone else's.
|
||||
|
||||
See `docs/push-notifications.md`.
|
||||
|
||||
### A plugin-contributed one, for reference
|
||||
|
||||
This is the gitea plugin's, and it shows what these are for: the agent cannot discover from the
|
||||
filesystem that `tea` is authenticated, or that it should prefer `git` for the things git already does.
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: Gitea
|
||||
description: Use when working with git repositories, or with Gitea issues and pull requests.
|
||||
version: 1
|
||||
---
|
||||
|
||||
For anything git already does — clone, fetch, pull, push, branches, tags — use plain `git`. It talks
|
||||
to the server directly.
|
||||
|
||||
For anything git does not — pull requests, issues, comments, releases, creating a repository — use
|
||||
`tea`. It is already logged in as the current user, with that user's own permissions. Do not
|
||||
configure it, and do not ask the user for a token.
|
||||
```
|
||||
|
||||
### On the word
|
||||
|
||||
`capability` was taken — `CAPABILITIES` is the permission registry. `skill` was taken twice: by
|
||||
`capabilities/skills/` here and by the wider AI ecosystem.
|
||||
|
||||
`affordance` is the exact term for what an environment offers an actor, and the precision earns the
|
||||
slight awkwardness: rendering an image is not a skill the agent has, it is something the client on the
|
||||
other end permits. Keeping that distinction in the name saves explaining it every time.
|
||||
+3
-89
@@ -1,92 +1,6 @@
|
||||
# Plugins
|
||||
|
||||
`EXTRACTING-A-PLUGIN.md` is the runbook for turning a platform feature into a plugin, and
|
||||
`EXTRACT-A-PLUGIN-PROMPT.md` is the way to hand that to a fresh agent. This file is for the concepts a
|
||||
plugin author needs that are not procedure.
|
||||
**The instructions live in [`AGENTS.md`](AGENTS.md). Read it first — this file only points there.**
|
||||
|
||||
**This directory holds documentation, not plugins.** Every plugin is its own repository; `plugins/<name>/`
|
||||
appears by `git clone` when somebody installs one, and is gitignored here.
|
||||
|
||||
---
|
||||
|
||||
## Affordances
|
||||
|
||||
**`docs/affordances.md` is the authority** — what one is, the three tests for whether something qualifies,
|
||||
the file format and how they reach the agent. Read it before writing one. What follows is only the part
|
||||
that is specific to shipping one from a plugin.
|
||||
|
||||
> An affordance is something the surface on the other end of the conversation offers the agent — declared
|
||||
> by the code that implements it, and read by the agent at runtime. Not what the agent can do; what the
|
||||
> client will honour.
|
||||
|
||||
A plugin ships an `affordances/` directory of markdown-with-frontmatter in its repository. Installing
|
||||
copies it to `capabilities/affordances/<publisher>/<appName>/`, uninstalling removes it — the same shape
|
||||
as `assets/` and `publishAssets`, and the namespace comes from where it lands rather than from anything
|
||||
inside the file.
|
||||
|
||||
**The test that catches most bad ones: can it be fixed instead?** If the answer is yes, fix it. An
|
||||
affordance describing a defect gives that defect a rationale, and the rationale outlives everyone's memory
|
||||
that it was a bug. See the two worked examples in `docs/affordances.md`.
|
||||
|
||||
Keep it short — every affordance is loaded into every conversation on this machine, including turns that
|
||||
have nothing to do with your plugin.
|
||||
|
||||
### A plugin-contributed one, for reference## Notifications — the same shape, for push
|
||||
|
||||
A plugin can also declare what its push notifications MEAN. Same mechanism, different store:
|
||||
|
||||
```
|
||||
capabilities/notifications/
|
||||
officerdev/music/
|
||||
catalogue.yaml
|
||||
```
|
||||
|
||||
```yaml
|
||||
nowPlaying:
|
||||
title: 'Now playing'
|
||||
route: 'officer://music/{id}'
|
||||
```
|
||||
|
||||
That becomes the code `officerdev/music:nowPlaying`. A push carries the code and integers — never content —
|
||||
and the device renders the title and follows the route. The point is that **adding a notification is a
|
||||
server change and never an app build**, because the mapping is synced to the device rather than compiled
|
||||
into it.
|
||||
|
||||
**The namespace comes from where the file lands, not from what it says.** Writing `officer/core:test` as a
|
||||
key in your own catalogue produces `<you>/<yourplugin>:officer/core:test`, not the core code — the same
|
||||
rule as `mountPrefix`, and pinned by test in `src/servers/notifications/catalogue.test.ts`.
|
||||
|
||||
An entry needs a `title`; `body`, `target`, `route` and `thread` are optional, `thread` defaults to your
|
||||
namespace, and unknown keys are dropped rather than forwarded to the device. Broken YAML in one plugin's
|
||||
catalogue is skipped without affecting anyone else's.
|
||||
|
||||
See `docs/push-notifications.md`.
|
||||
|
||||
### A plugin-contributed one, for reference
|
||||
|
||||
This is the gitea plugin's, and it shows what these are for: the agent cannot discover from the
|
||||
filesystem that `tea` is authenticated, or that it should prefer `git` for the things git already does.
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: Gitea
|
||||
description: Use when working with git repositories, or with Gitea issues and pull requests.
|
||||
version: 1
|
||||
---
|
||||
|
||||
For anything git already does — clone, fetch, pull, push, branches, tags — use plain `git`. It talks
|
||||
to the server directly.
|
||||
|
||||
For anything git does not — pull requests, issues, comments, releases, creating a repository — use
|
||||
`tea`. It is already logged in as the current user, with that user's own permissions. Do not
|
||||
configure it, and do not ask the user for a token.
|
||||
```
|
||||
|
||||
### On the word
|
||||
|
||||
`capability` was taken — `CAPABILITIES` is the permission registry. `skill` was taken twice: by
|
||||
`capabilities/skills/` here and by the wider AI ecosystem.
|
||||
|
||||
`affordance` is the exact term for what an environment offers an actor, and the precision earns the
|
||||
slight awkwardness: rendering an image is not a skill the agent has, it is something the client on the
|
||||
other end permits. Keeping that distinction in the name saves explaining it every time.
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
|
||||
@@ -89,7 +89,7 @@ async function main(): Promise<void> {
|
||||
const { PERMISSIONS } = await import('../src/servers/permissions/registry');
|
||||
record(
|
||||
checkCount(
|
||||
join(ROOT, 'CLAUDE.md'),
|
||||
join(ROOT, 'AGENTS.md'),
|
||||
/([0-9]+|[a-z-]+) entries as of/gi,
|
||||
PERMISSIONS.length,
|
||||
'permission registry entries',
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
# Frontend Apps
|
||||
|
||||
Shared patterns and conventions for all frontend applications (dashboard, editor, runtime).
|
||||
|
||||
## UI Components
|
||||
|
||||
### shadcn/ui (Base)
|
||||
Location: `src/workspaces/components/ui/`
|
||||
|
||||
Standard shadcn/ui components with Tailwind CSS. Import via:
|
||||
```tsx
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
||||
```
|
||||
|
||||
### Custom Components
|
||||
Location: `src/workspaces/components/`
|
||||
|
||||
Built on top of shadcn primitives:
|
||||
- `Avatar.tsx` - User avatars
|
||||
- `Card.tsx` - Custom card wrapper
|
||||
- `ColorPicker.tsx` - Color selection
|
||||
- `DataTable/` - Table with sorting, filtering, pagination (see below)
|
||||
- `Dialogs/` - Common dialog patterns
|
||||
- `ErrorDialogs/` - Error display dialogs
|
||||
- `MetricCard.tsx` - Stats display card
|
||||
- `SearchInput.tsx` - Search with debounce
|
||||
- `Select.tsx` - Enhanced select
|
||||
- `Slider/` - Custom slider
|
||||
- `Tabs/` - Enhanced tabs
|
||||
|
||||
### DataTable + useDataControl
|
||||
|
||||
A complete data table solution with sorting, filtering, and pagination.
|
||||
|
||||
**Pattern:**
|
||||
```tsx
|
||||
import { DataTable, useDataControl } from '@/components/DataTable';
|
||||
|
||||
function JobsLibrary() {
|
||||
const { jobs } = useJobs();
|
||||
const dataController = useDataControl<Job>(jobs || []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Wire search input to controller */}
|
||||
<SearchInput
|
||||
value={dataController.searchQuery}
|
||||
handleSearch={dataController.setSearchQuery}
|
||||
/>
|
||||
|
||||
<DataTable<Job>
|
||||
dataController={dataController}
|
||||
pageSize={10}
|
||||
columns={[
|
||||
{ field: 'id', label: 'ID', sortKey: 'id' },
|
||||
{ field: 'type', label: 'Type', sortKey: 'type' },
|
||||
{
|
||||
field: 'status',
|
||||
label: 'Status',
|
||||
condition: view === 'All', // conditional column
|
||||
format: ({ value, item }) => <Badge>{value}</Badge>
|
||||
},
|
||||
{
|
||||
label: 'Actions',
|
||||
format: ({ item }) => <ActionsCell job={item} />
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**useDataControl returns:**
|
||||
- `data` - Current page of filtered/sorted data
|
||||
- `rawData` - Original unfiltered data
|
||||
- `searchQuery`, `setSearchQuery` - Search state
|
||||
- `searchKeys`, `setSearchKeys` - Which fields to search
|
||||
- `sortedBy`, `setSortedBy`, `sortBy` - Sort state
|
||||
- `sortKey`, `sortDirection` - Parsed sort info
|
||||
- `currentPage`, `changePage`, `pageCount` - Pagination
|
||||
- `pageSize`, `setPageSize` - Items per page
|
||||
- `setCustomSort` - Custom sort function
|
||||
|
||||
**Column options:**
|
||||
- `field` - Key in data object
|
||||
- `label` / `labelMobile` - Header text
|
||||
- `sortKey` - Enable sorting on this column
|
||||
- `format` - Custom render: `({ value, item, data, idx }) => ReactNode`
|
||||
- `condition` - Show/hide column: `boolean | () => boolean`
|
||||
- `tooltip` - Header tooltip text
|
||||
- `headerClassName` / `cellClassName` - Styling
|
||||
|
||||
**Features:**
|
||||
- Auto-generates columns from data if not specified
|
||||
- Resets to page 1 on search/sort change
|
||||
- Search strips diacritics for accent-insensitive matching
|
||||
- Built-in pagination bar (shows when data exceeds pageSize)
|
||||
|
||||
## Hooks
|
||||
|
||||
Location: `src/workspaces/hooks/src/`
|
||||
|
||||
### Data Fetching - `useClient`
|
||||
HTTP client with auth token handling:
|
||||
```tsx
|
||||
const client = useClient();
|
||||
const data = await client.get<User[]>("/users");
|
||||
await client.post("/experiments", payload);
|
||||
```
|
||||
|
||||
Methods: `get`, `getText`, `getBlob`, `post`, `put`, `patch`, `delete`
|
||||
|
||||
Auto-attaches Bearer token from localStorage/sessionStorage.
|
||||
|
||||
### Forms - `useForm`
|
||||
Custom form hook (not react-hook-form):
|
||||
```tsx
|
||||
const { state, formRef, update, reset, isValid } = useForm<FormState>(
|
||||
initialState,
|
||||
validateFn
|
||||
);
|
||||
|
||||
return <form ref={formRef}>...</form>;
|
||||
```
|
||||
|
||||
Features:
|
||||
- Auto-syncs form inputs with state via `name` attribute
|
||||
- Handles checkboxes, radios, selects, number inputs
|
||||
- Nested object support via data attributes
|
||||
- Validation function support
|
||||
|
||||
### Other Hooks
|
||||
- `useAuth/` - Authentication state and methods
|
||||
- `useDebounce` - Debounced values
|
||||
- `useDragAndDrop` - Drag and drop functionality
|
||||
- `useFullscreen/` - Fullscreen API wrapper
|
||||
- `useIsMobile` - Responsive breakpoint detection
|
||||
- `useLocalStorageState` - Persisted state
|
||||
- `useMounted` - Component mount status
|
||||
- `usePopover` - Popover state management
|
||||
- `useTimeout` - Timeout management
|
||||
- `useTimer` - Interval-based timer
|
||||
- `useChatWebSocket` - the chat socket, with reconnect + replay cursor
|
||||
- `usePanelChannel` - panel-to-panel signals (refresh buses, NOT selection — selection is the URL)
|
||||
- `useJobs` - background jobs
|
||||
- `useCustomSorter`, `useImageLoader`, `useIsProduction`, `usePhotoEditor`
|
||||
|
||||
## State Management
|
||||
|
||||
Uses React Query cache as both server and client state manager.
|
||||
|
||||
### Global State - `useGlobal`
|
||||
|
||||
Uses React Query cache as a global state store (no Context providers needed):
|
||||
|
||||
```tsx
|
||||
const [value, setValue, refresh, reset] = useGlobal<string>("SIDEBAR_STATE", "expanded");
|
||||
|
||||
// Any component using the same key shares state and reacts to changes
|
||||
setValue("collapsed");
|
||||
```
|
||||
|
||||
How it works:
|
||||
- `enabled: false` + `staleTime: Infinity` = never fetches, just stores
|
||||
- Automatic re-renders when state changes
|
||||
- Visible in React Query DevTools
|
||||
- Supports functional updates: `setValue(prev => ...)`
|
||||
|
||||
### URL Query State - `useQueryState`
|
||||
|
||||
Syncs state with URL query parameters:
|
||||
|
||||
```tsx
|
||||
const [page, setPage, reset, clear] = useQueryState<number>("page", 1);
|
||||
const [filter, setFilter] = useQueryState<string>("filter", null, true); // isGlobal = true
|
||||
```
|
||||
|
||||
Features:
|
||||
- Updates URL via `history.replaceState` (no page reload)
|
||||
- `isGlobal = true`: persists across navigation, uses `useGlobal` internally
|
||||
- `isGlobal = false`: local to component, uses `useState`
|
||||
- Auto-rebuilds URL when pathname changes (preserves global query state)
|
||||
- Type coercion based on `defaultValue` type
|
||||
|
||||
### Server State
|
||||
|
||||
Domain-specific hooks in `state/` directories wrap React Query:
|
||||
|
||||
```tsx
|
||||
// src/workspaces/hooks/src/useJobs.ts
|
||||
const { jobs, isLoading } = useJobs();
|
||||
```
|
||||
|
||||
### When to Use What
|
||||
|
||||
| Scenario | Hook |
|
||||
|----------|------|
|
||||
| API data | Domain hooks (`useJobs`, `useModels`, …) |
|
||||
| Shared UI state | `useGlobal` |
|
||||
| URL-driven state (filters, pagination) | `useQueryState` |
|
||||
| Component-only state | `useState` |
|
||||
| Shared UI state that must survive a refresh, per tab | `useSessionState` |
|
||||
| Persisted to localStorage | `useLocalStorageState` |
|
||||
|
||||
## Event Handlers
|
||||
|
||||
**Always use `ev` for event parameters**, not `e`:
|
||||
```tsx
|
||||
// ✅ Good
|
||||
onChange={(ev) => setName(ev.target.value)}
|
||||
onKeyDown={(ev) => {
|
||||
if (ev.key === 'Enter') {
|
||||
ev.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
}}
|
||||
const handleSubmit = async (ev: React.FormEvent) => {
|
||||
ev.preventDefault();
|
||||
// ...
|
||||
};
|
||||
|
||||
// ❌ Bad
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
```
|
||||
|
||||
## React 19 Patterns
|
||||
|
||||
**RefObject includes null**: In React 19, `useRef` returns `RefObject<T | null>`. Update prop types accordingly:
|
||||
```tsx
|
||||
// ✅ Good - allow null in ref type
|
||||
type PanelProps = {
|
||||
triggerRef: React.RefObject<HTMLButtonElement | null>;
|
||||
};
|
||||
|
||||
// ❌ Bad - will error when passing useRef result
|
||||
type PanelProps = {
|
||||
triggerRef: React.RefObject<HTMLButtonElement>;
|
||||
};
|
||||
```
|
||||
|
||||
**Hook return types**: Use `ReturnType<typeof hookName>` for typing hook returns in props:
|
||||
```tsx
|
||||
import { useJobs } from 'hooks/useJobs';
|
||||
|
||||
type TopHeaderProps = {
|
||||
manager: ReturnType<typeof useJobs>;
|
||||
};
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Toast notifications** via Sonner:
|
||||
```tsx
|
||||
import { toast } from "sonner";
|
||||
|
||||
toast.error("Something went wrong");
|
||||
toast.success("Saved successfully");
|
||||
```
|
||||
|
||||
API errors automatically trigger via `useClient.config.onError`.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- `../../CLAUDE.md` — architecture and the frontend route conventions
|
||||
- `../../docs/navigation-audit.md` — **authoritative** on routing and selection. The short version:
|
||||
addressable state lives in the URL (`useParams` / `?selected=`), never in a channel or a global; rows
|
||||
and nav items are real `<Link>`/`<NavLink>`s. Read it before building a screen that selects things.
|
||||
- `../../CONVENTIONS.md` — component organisation and React patterns
|
||||
- `../workspaces/officerdev/APP_CONVENTIONS.md` — panel apps and the AppRegistry
|
||||
+3
-268
@@ -1,271 +1,6 @@
|
||||
# Frontend Apps
|
||||
|
||||
Shared patterns and conventions for all frontend applications (dashboard, editor, runtime).
|
||||
**The instructions live in [`AGENTS.md`](AGENTS.md). Read it first — this file only points there.**
|
||||
|
||||
## UI Components
|
||||
|
||||
### shadcn/ui (Base)
|
||||
Location: `src/workspaces/components/ui/`
|
||||
|
||||
Standard shadcn/ui components with Tailwind CSS. Import via:
|
||||
```tsx
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
||||
```
|
||||
|
||||
### Custom Components
|
||||
Location: `src/workspaces/components/`
|
||||
|
||||
Built on top of shadcn primitives:
|
||||
- `Avatar.tsx` - User avatars
|
||||
- `Card.tsx` - Custom card wrapper
|
||||
- `ColorPicker.tsx` - Color selection
|
||||
- `DataTable/` - Table with sorting, filtering, pagination (see below)
|
||||
- `Dialogs/` - Common dialog patterns
|
||||
- `ErrorDialogs/` - Error display dialogs
|
||||
- `MetricCard.tsx` - Stats display card
|
||||
- `SearchInput.tsx` - Search with debounce
|
||||
- `Select.tsx` - Enhanced select
|
||||
- `Slider/` - Custom slider
|
||||
- `Tabs/` - Enhanced tabs
|
||||
|
||||
### DataTable + useDataControl
|
||||
|
||||
A complete data table solution with sorting, filtering, and pagination.
|
||||
|
||||
**Pattern:**
|
||||
```tsx
|
||||
import { DataTable, useDataControl } from '@/components/DataTable';
|
||||
|
||||
function JobsLibrary() {
|
||||
const { jobs } = useJobs();
|
||||
const dataController = useDataControl<Job>(jobs || []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Wire search input to controller */}
|
||||
<SearchInput
|
||||
value={dataController.searchQuery}
|
||||
handleSearch={dataController.setSearchQuery}
|
||||
/>
|
||||
|
||||
<DataTable<Job>
|
||||
dataController={dataController}
|
||||
pageSize={10}
|
||||
columns={[
|
||||
{ field: 'id', label: 'ID', sortKey: 'id' },
|
||||
{ field: 'type', label: 'Type', sortKey: 'type' },
|
||||
{
|
||||
field: 'status',
|
||||
label: 'Status',
|
||||
condition: view === 'All', // conditional column
|
||||
format: ({ value, item }) => <Badge>{value}</Badge>
|
||||
},
|
||||
{
|
||||
label: 'Actions',
|
||||
format: ({ item }) => <ActionsCell job={item} />
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**useDataControl returns:**
|
||||
- `data` - Current page of filtered/sorted data
|
||||
- `rawData` - Original unfiltered data
|
||||
- `searchQuery`, `setSearchQuery` - Search state
|
||||
- `searchKeys`, `setSearchKeys` - Which fields to search
|
||||
- `sortedBy`, `setSortedBy`, `sortBy` - Sort state
|
||||
- `sortKey`, `sortDirection` - Parsed sort info
|
||||
- `currentPage`, `changePage`, `pageCount` - Pagination
|
||||
- `pageSize`, `setPageSize` - Items per page
|
||||
- `setCustomSort` - Custom sort function
|
||||
|
||||
**Column options:**
|
||||
- `field` - Key in data object
|
||||
- `label` / `labelMobile` - Header text
|
||||
- `sortKey` - Enable sorting on this column
|
||||
- `format` - Custom render: `({ value, item, data, idx }) => ReactNode`
|
||||
- `condition` - Show/hide column: `boolean | () => boolean`
|
||||
- `tooltip` - Header tooltip text
|
||||
- `headerClassName` / `cellClassName` - Styling
|
||||
|
||||
**Features:**
|
||||
- Auto-generates columns from data if not specified
|
||||
- Resets to page 1 on search/sort change
|
||||
- Search strips diacritics for accent-insensitive matching
|
||||
- Built-in pagination bar (shows when data exceeds pageSize)
|
||||
|
||||
## Hooks
|
||||
|
||||
Location: `src/workspaces/hooks/src/`
|
||||
|
||||
### Data Fetching - `useClient`
|
||||
HTTP client with auth token handling:
|
||||
```tsx
|
||||
const client = useClient();
|
||||
const data = await client.get<User[]>("/users");
|
||||
await client.post("/experiments", payload);
|
||||
```
|
||||
|
||||
Methods: `get`, `getText`, `getBlob`, `post`, `put`, `patch`, `delete`
|
||||
|
||||
Auto-attaches Bearer token from localStorage/sessionStorage.
|
||||
|
||||
### Forms - `useForm`
|
||||
Custom form hook (not react-hook-form):
|
||||
```tsx
|
||||
const { state, formRef, update, reset, isValid } = useForm<FormState>(
|
||||
initialState,
|
||||
validateFn
|
||||
);
|
||||
|
||||
return <form ref={formRef}>...</form>;
|
||||
```
|
||||
|
||||
Features:
|
||||
- Auto-syncs form inputs with state via `name` attribute
|
||||
- Handles checkboxes, radios, selects, number inputs
|
||||
- Nested object support via data attributes
|
||||
- Validation function support
|
||||
|
||||
### Other Hooks
|
||||
- `useAuth/` - Authentication state and methods
|
||||
- `useDebounce` - Debounced values
|
||||
- `useDragAndDrop` - Drag and drop functionality
|
||||
- `useFullscreen/` - Fullscreen API wrapper
|
||||
- `useIsMobile` - Responsive breakpoint detection
|
||||
- `useLocalStorageState` - Persisted state
|
||||
- `useMounted` - Component mount status
|
||||
- `usePopover` - Popover state management
|
||||
- `useTimeout` - Timeout management
|
||||
- `useTimer` - Interval-based timer
|
||||
- `useChatWebSocket` - the chat socket, with reconnect + replay cursor
|
||||
- `usePanelChannel` - panel-to-panel signals (refresh buses, NOT selection — selection is the URL)
|
||||
- `useJobs` - background jobs
|
||||
- `useCustomSorter`, `useImageLoader`, `useIsProduction`, `usePhotoEditor`
|
||||
|
||||
## State Management
|
||||
|
||||
Uses React Query cache as both server and client state manager.
|
||||
|
||||
### Global State - `useGlobal`
|
||||
|
||||
Uses React Query cache as a global state store (no Context providers needed):
|
||||
|
||||
```tsx
|
||||
const [value, setValue, refresh, reset] = useGlobal<string>("SIDEBAR_STATE", "expanded");
|
||||
|
||||
// Any component using the same key shares state and reacts to changes
|
||||
setValue("collapsed");
|
||||
```
|
||||
|
||||
How it works:
|
||||
- `enabled: false` + `staleTime: Infinity` = never fetches, just stores
|
||||
- Automatic re-renders when state changes
|
||||
- Visible in React Query DevTools
|
||||
- Supports functional updates: `setValue(prev => ...)`
|
||||
|
||||
### URL Query State - `useQueryState`
|
||||
|
||||
Syncs state with URL query parameters:
|
||||
|
||||
```tsx
|
||||
const [page, setPage, reset, clear] = useQueryState<number>("page", 1);
|
||||
const [filter, setFilter] = useQueryState<string>("filter", null, true); // isGlobal = true
|
||||
```
|
||||
|
||||
Features:
|
||||
- Updates URL via `history.replaceState` (no page reload)
|
||||
- `isGlobal = true`: persists across navigation, uses `useGlobal` internally
|
||||
- `isGlobal = false`: local to component, uses `useState`
|
||||
- Auto-rebuilds URL when pathname changes (preserves global query state)
|
||||
- Type coercion based on `defaultValue` type
|
||||
|
||||
### Server State
|
||||
|
||||
Domain-specific hooks in `state/` directories wrap React Query:
|
||||
|
||||
```tsx
|
||||
// src/workspaces/hooks/src/useJobs.ts
|
||||
const { jobs, isLoading } = useJobs();
|
||||
```
|
||||
|
||||
### When to Use What
|
||||
|
||||
| Scenario | Hook |
|
||||
|----------|------|
|
||||
| API data | Domain hooks (`useJobs`, `useModels`, …) |
|
||||
| Shared UI state | `useGlobal` |
|
||||
| URL-driven state (filters, pagination) | `useQueryState` |
|
||||
| Component-only state | `useState` |
|
||||
| Shared UI state that must survive a refresh, per tab | `useSessionState` |
|
||||
| Persisted to localStorage | `useLocalStorageState` |
|
||||
|
||||
## Event Handlers
|
||||
|
||||
**Always use `ev` for event parameters**, not `e`:
|
||||
```tsx
|
||||
// ✅ Good
|
||||
onChange={(ev) => setName(ev.target.value)}
|
||||
onKeyDown={(ev) => {
|
||||
if (ev.key === 'Enter') {
|
||||
ev.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
}}
|
||||
const handleSubmit = async (ev: React.FormEvent) => {
|
||||
ev.preventDefault();
|
||||
// ...
|
||||
};
|
||||
|
||||
// ❌ Bad
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
```
|
||||
|
||||
## React 19 Patterns
|
||||
|
||||
**RefObject includes null**: In React 19, `useRef` returns `RefObject<T | null>`. Update prop types accordingly:
|
||||
```tsx
|
||||
// ✅ Good - allow null in ref type
|
||||
type PanelProps = {
|
||||
triggerRef: React.RefObject<HTMLButtonElement | null>;
|
||||
};
|
||||
|
||||
// ❌ Bad - will error when passing useRef result
|
||||
type PanelProps = {
|
||||
triggerRef: React.RefObject<HTMLButtonElement>;
|
||||
};
|
||||
```
|
||||
|
||||
**Hook return types**: Use `ReturnType<typeof hookName>` for typing hook returns in props:
|
||||
```tsx
|
||||
import { useJobs } from 'hooks/useJobs';
|
||||
|
||||
type TopHeaderProps = {
|
||||
manager: ReturnType<typeof useJobs>;
|
||||
};
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Toast notifications** via Sonner:
|
||||
```tsx
|
||||
import { toast } from "sonner";
|
||||
|
||||
toast.error("Something went wrong");
|
||||
toast.success("Saved successfully");
|
||||
```
|
||||
|
||||
API errors automatically trigger via `useClient.config.onError`.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- `../../CLAUDE.md` — architecture and the frontend route conventions
|
||||
- `../../docs/navigation-audit.md` — **authoritative** on routing and selection. The short version:
|
||||
addressable state lives in the URL (`useParams` / `?selected=`), never in a channel or a global; rows
|
||||
and nav items are real `<Link>`/`<NavLink>`s. Read it before building a screen that selects things.
|
||||
- `../../CONVENTIONS.md` — component organisation and React patterns
|
||||
- `../workspaces/officerdev/APP_CONVENTIONS.md` — panel apps and the AppRegistry
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
# Database Patterns
|
||||
|
||||
## Dropping and adding a column in the same push makes drizzle ASK
|
||||
|
||||
`drizzle-kit push` cannot tell a drop-plus-add from a rename, so it stops and asks:
|
||||
|
||||
```
|
||||
Is grants_postgres column in roles table created or renamed from another column?
|
||||
❯ + grants_postgres create column
|
||||
~ provisioning_script › grants_postgres rename column
|
||||
```
|
||||
|
||||
**Non-interactively that is fatal and silent.** With stdin closed it bails, `bun db:push` still exits 0, and
|
||||
the `postdb:push` seed then runs against a schema that never changed — which is how you get a confusing
|
||||
error about a column that does not exist, several steps from the thing that failed.
|
||||
|
||||
Hit on 2026-08-23 replacing `roles.provisioning_script` with `grants_postgres`/`grants_docker`. It is the
|
||||
same family as the composite-unique truncate prompt below, and it matters more on a deploy: no agent driving
|
||||
a rollout over SSH has a terminal to answer with.
|
||||
|
||||
**So a release whose schema drops a column carries the SQL in its plan**, guarded and idempotent, and treats
|
||||
`bun db:push` as the check that it worked rather than the thing that does it:
|
||||
|
||||
```sql
|
||||
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_postgres boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_docker boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE roles DROP COLUMN IF EXISTS provisioning_script;
|
||||
```
|
||||
|
||||
Then push, and expect zero DDL. If it still wants to change something, the SQL was wrong.
|
||||
|
||||
## Overview
|
||||
|
||||
**One PostgreSQL database**, `officer_db`, exposed as the workspace package `officerdb`. Managed with
|
||||
Drizzle ORM. There is no second database and no cache database — anything that used to say otherwise was
|
||||
describing a different codebase.
|
||||
|
||||
```
|
||||
src/databases/officer_db/
|
||||
├── src/
|
||||
│ ├── db.ts # the connection
|
||||
│ ├── index.ts # public surface: one `export * from './<feature>'` per line
|
||||
│ ├── schema.ts # what db:push creates — see below
|
||||
│ ├── types.ts # every type export (Select / Insert / extended)
|
||||
│ ├── crypto.ts # at-rest encryption, one key per purpose
|
||||
│ ├── secret-store.ts # the key store itself (SQLite, outside Postgres)
|
||||
│ └── <feature>/
|
||||
│ ├── index.ts # what this feature exports — declared here, not in a list three levels up
|
||||
│ ├── schema.ts # its tables
|
||||
│ └── queries.ts # everything that reads or writes them
|
||||
└── package.json # exports ".", "./types", "./db", "./schema", "./secret-store", "./*"
|
||||
```
|
||||
|
||||
**A feature owns its own public surface.** `src/index.ts` is one `export *` per feature and nothing
|
||||
else; what a feature exports is declared in its own `index.ts`, beside the code it describes. Adding a
|
||||
query function is one file in one directory, rather than that file plus a hand-written list of every
|
||||
symbol in the package. That list was 297 lines until 2026-08-13 and it had already drifted — twelve
|
||||
features listed twice, `db` and `schema` buried at line 270 with three feature blocks after them.
|
||||
|
||||
**One directory per feature, holding both halves.** Restructured 2026-08-13 from parallel `schema/` and
|
||||
`queries/` trees, where the two sides had drifted: four features were named differently on each side
|
||||
(`app-store`/`sidecar-installs`, `email`/`email-accounts`, `server`/`server-config`), `operations` had no
|
||||
query file at all, and `integrations` had no schema file.
|
||||
|
||||
One directory is still lopsided and says so by its contents: `integrations/` has only queries, because it
|
||||
spans `server` and `user-data`. (`operations/` was the other, and was deleted on 2026-08-13 along with the
|
||||
Task Logs feature — see below.)
|
||||
|
||||
**`src/schema.ts` is drizzle-kit's view, not the runtime's.** `drizzle.config.ts` points at it, so a
|
||||
commented line there removes a table from the DATABASE without removing a line of code — every query
|
||||
imports its tables from `./schema` inside its own feature directory. That is what lets a fresh install
|
||||
create only the core tables, with the plugin ones commented out until their plugin is installed.
|
||||
|
||||
## Schema changes use `push`, not migrations
|
||||
|
||||
`bun db:push` diffs the schema code against the live database and alters it directly. **`drizzle-kit
|
||||
migrate` has never been run here** — there is no `__drizzle_migrations` table. Change the schema, run
|
||||
push, done. `bun db:gen` writes files to `migrations/`, but nothing applies them; treat the schema code
|
||||
as the source of truth, never those files.
|
||||
|
||||
**The schema is the source of truth for what the database may contain**, not just for its shape. Where a
|
||||
column has a known set of legal values, say so with a `check()` rather than leaving it free `text` —
|
||||
otherwise a value the code stopped supporting sits there unnoticed. `serverIntegrations.provider` is the
|
||||
worked example: rows for deleted chat integrations kept their bot tokens long after the code that read
|
||||
them was gone, because nothing structural said they had become illegal.
|
||||
|
||||
```ts
|
||||
const SERVER_PROVIDERS = ['google', 'apify'] as const;
|
||||
|
||||
check(
|
||||
'ck_server_integrations_provider',
|
||||
// sql.raw, not sql`${p}` — an interpolated JS string binds as a parameter, so the constraint is
|
||||
// emitted as `IN ($1, $2)` and Postgres refuses it, breaking push for the WHOLE schema.
|
||||
sql`${table.provider} IN (${sql.join(
|
||||
SERVER_PROVIDERS.map((p) => sql.raw(`'${p}'`)),
|
||||
sql`, `,
|
||||
)})`,
|
||||
);
|
||||
```
|
||||
|
||||
Adding a constraint fails while existing rows violate it. That is the point: push refusing tells you the
|
||||
database has drifted, instead of quietly accepting it. Clean the rows, then push.
|
||||
|
||||
### Composite keys: use `uniqueIndex`, and name any long foreign key
|
||||
|
||||
**Declare a multi-column uniqueness rule as `uniqueIndex('uq_…').on(a, b)`, never `unique('uq_…').on(a, b)`.**
|
||||
|
||||
drizzle-kit mis-diffs named composite unique CONSTRAINTS. It reads them back from the database, compares
|
||||
them against a schema that declares exactly the same name, columns and order, decides they differ, and
|
||||
emits a `DROP CONSTRAINT` + `ADD CONSTRAINT` pair — on every push, forever. Fifteen of them made
|
||||
`db:push` plan 32 statements against a database that already matched, and `ADD UNIQUE` on a populated
|
||||
table is a data-risk statement, so push stopped on an interactive _"do you want to truncate?"_ prompt
|
||||
that could never be resolved by answering it.
|
||||
|
||||
Reproduced on a database drizzle had itself created seconds earlier, so it is not drift and not
|
||||
something your change caused. Single-column `.unique()` is diffed correctly and is unaffected — only the
|
||||
table-level `unique('name').on(...)` form. Unique indexes are diffed on a different code path and are
|
||||
stable. Verified on drizzle-kit 0.31.9 / drizzle-orm 0.45.1.
|
||||
|
||||
A unique index enforces exactly what the constraint did, and `onConflictDoUpdate({ target: [...] })`
|
||||
accepts it as an arbiter. The one thing it cannot do is be the target of a foreign key — Postgres
|
||||
requires a unique _constraint_ there. Nothing here has a composite foreign-key target; check before
|
||||
adding one.
|
||||
|
||||
**Name a foreign key explicitly when drizzle's generated name would exceed 63 characters.** Postgres
|
||||
truncates identifiers at 63 and stores the shortened form, so drizzle keeps comparing against its own
|
||||
longer version and re-creates the constraint on every push.
|
||||
`user_integrations_server_integration_id_server_integrations_id_fk` was 65, and is now declared with
|
||||
`foreignKey({ name: 'fk_user_integrations_server_integration', … })`.
|
||||
|
||||
**Known remaining churn, harmless:** a composite `primaryKey` has the same diffing bug and there is no
|
||||
index form to escape to — a primary key must be a constraint. `music_now_playing` therefore drops and
|
||||
re-adds `pk_music_now_playing` on every push. Two statements, silent, no prompt even with rows in the
|
||||
table, data unaffected. Neither naming it nor un-naming it helps — both were tested. Leave it.
|
||||
|
||||
**All six over-long foreign keys are now named, 2026-08-23.** They were deferred as "noise rather than a
|
||||
fault" for four days. What ended that was a deploy plan saying _"expect no changes, stop and report if it
|
||||
wants to alter something"_ — which this made impossible to satisfy on any host, forcing the deploy agent to
|
||||
overrule its own instructions and continue. A documented annoyance became a plan instruction nobody could
|
||||
follow.
|
||||
|
||||
The six, and where each lives:
|
||||
|
||||
fk_command_hq_watcher_fires_session officer_db/src/command-hq/schema.ts
|
||||
fk_command_hq_session_tags_session officer_db/src/command-hq/schema.ts
|
||||
fk_bitcoin_wallet_frozen_utxos_wallet plugins/bitcoin-wallet/db/schema.ts
|
||||
fk_bitcoin_wallet_chain_cache_wallet plugins/bitcoin-wallet/db/schema.ts
|
||||
fk_atelier_collection_items_collection plugins/atelier/sidecar/db/collections/schema.ts
|
||||
fk_atelier_collection_items_generation plugins/atelier/sidecar/db/collections/schema.ts
|
||||
|
||||
Two things worth knowing if you add another. Naming it means REMOVING the inline `.references()` on the
|
||||
column, or drizzle creates both. And `walletChainCache` had to move from the two-argument `pgTable` form to
|
||||
the three-argument one, because there was nowhere else to put the declaration.
|
||||
|
||||
**`pk_music_now_playing` still churns, and it cannot be fixed.** Two statements per push. Tested on
|
||||
2026-08-23 rather than assumed: removing the explicit name produces the identical drop-and-re-add under
|
||||
drizzle's generated name (`music_now_playing_user_id_device_pk`), so this is the named-composite mis-diff
|
||||
rather than the truncation one, and there is no index form to escape to because a primary key must be a
|
||||
constraint. **A push is therefore expected to print exactly these two statements and nothing else** — which
|
||||
is a far more useful baseline than ten, because anything else really is your change.
|
||||
|
||||
**Rules that still apply:**
|
||||
|
||||
1. **Never answer "Yes, truncate the table"** if a prompt ever does appear. It destroys rows and fixes
|
||||
nothing — whatever is being re-created gets re-created next push regardless.
|
||||
2. **Never delete a constraint from the schema to quiet a diff.** The schema is right. Removing a
|
||||
uniqueness rule would break the upserts that depend on it.
|
||||
3. **Do not use `--force`.** It auto-accepts data-loss statements and nobody has established which
|
||||
branch it takes at a truncate prompt.
|
||||
4. **Read the plan before applying it:**
|
||||
`bunx drizzle-kit push --config=drizzle.config.ts --verbose` prints every statement first. Expect the
|
||||
two `pk_music_now_playing` lines and the eight from the four over-long foreign keys above — ten in
|
||||
all. Anything else is your change.
|
||||
|
||||
To test a schema change without touching `officer_dev`: `createdb officer_scratch`, then
|
||||
`POSTGRES_URL=postgresql://postgres:postgres@127.0.0.1:5432/officer_scratch bunx drizzle-kit push
|
||||
--config=drizzle.config.ts`. Push twice — the second run tells you whether your declaration is stable.
|
||||
|
||||
## Type naming
|
||||
|
||||
```ts
|
||||
// types.ts — inferred from the schema, never hand-written
|
||||
export type UserSelect = typeof Schema.users.$inferSelect;
|
||||
export type UserInsert = typeof Schema.users.$inferInsert;
|
||||
|
||||
// The bare name is the hydrated shape, when a table has relations worth carrying
|
||||
export type User = UserSelect & {
|
||||
passkeys: PasskeySelect[];
|
||||
};
|
||||
```
|
||||
|
||||
Organise `types.ts` by domain with section comments, mirroring the schema files.
|
||||
|
||||
## Queries
|
||||
|
||||
Hand-written, one `queries.ts` per feature directory, importing tables from `./schema` beside it and
|
||||
types from `../types`:
|
||||
|
||||
```ts
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { db } from '../db';
|
||||
import { users, passkeys } from '../schema';
|
||||
import type { UserSelect } from '../types';
|
||||
|
||||
export async function getUsers(): Promise<UserSelect[]> { … }
|
||||
```
|
||||
|
||||
Every query is exported from `src/index.ts`, which is the only surface callers use.
|
||||
|
||||
## Importing
|
||||
|
||||
```ts
|
||||
// ✅ types from the types subpath
|
||||
import type { User } from 'officerdb/types';
|
||||
// ✅ queries, schema and drizzle helpers from the package root
|
||||
import { getUserById, eq } from 'officerdb';
|
||||
|
||||
// ❌ never reach into src/schema or src/queries directly
|
||||
// ❌ never hand-write a type a table can infer
|
||||
```
|
||||
|
||||
In app code import from `'types'`, which re-exports the database types. Only server and database code
|
||||
imports `officerdb/types` directly.
|
||||
|
||||
## Conventions
|
||||
|
||||
- `serial` for ids on small tables; `bigserial` with `mode: 'number'` where the row count is unbounded
|
||||
(`chat_session_events` is the example — its id is also the replay cursor).
|
||||
- `timestamp('…', { withTimezone: true })`, always.
|
||||
- Index anything you filter on. Drizzle-inferred types reflect nullability correctly, so guard rather
|
||||
than cast.
|
||||
+3
-228
@@ -1,231 +1,6 @@
|
||||
# Database Patterns
|
||||
|
||||
## Dropping and adding a column in the same push makes drizzle ASK
|
||||
**The instructions live in [`AGENTS.md`](AGENTS.md). Read it first — this file only points there.**
|
||||
|
||||
`drizzle-kit push` cannot tell a drop-plus-add from a rename, so it stops and asks:
|
||||
|
||||
```
|
||||
Is grants_postgres column in roles table created or renamed from another column?
|
||||
❯ + grants_postgres create column
|
||||
~ provisioning_script › grants_postgres rename column
|
||||
```
|
||||
|
||||
**Non-interactively that is fatal and silent.** With stdin closed it bails, `bun db:push` still exits 0, and
|
||||
the `postdb:push` seed then runs against a schema that never changed — which is how you get a confusing
|
||||
error about a column that does not exist, several steps from the thing that failed.
|
||||
|
||||
Hit on 2026-08-23 replacing `roles.provisioning_script` with `grants_postgres`/`grants_docker`. It is the
|
||||
same family as the composite-unique truncate prompt below, and it matters more on a deploy: no agent driving
|
||||
a rollout over SSH has a terminal to answer with.
|
||||
|
||||
**So a release whose schema drops a column carries the SQL in its plan**, guarded and idempotent, and treats
|
||||
`bun db:push` as the check that it worked rather than the thing that does it:
|
||||
|
||||
```sql
|
||||
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_postgres boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE roles ADD COLUMN IF NOT EXISTS grants_docker boolean NOT NULL DEFAULT false;
|
||||
ALTER TABLE roles DROP COLUMN IF EXISTS provisioning_script;
|
||||
```
|
||||
|
||||
Then push, and expect zero DDL. If it still wants to change something, the SQL was wrong.
|
||||
|
||||
## Overview
|
||||
|
||||
**One PostgreSQL database**, `officer_db`, exposed as the workspace package `officerdb`. Managed with
|
||||
Drizzle ORM. There is no second database and no cache database — anything that used to say otherwise was
|
||||
describing a different codebase.
|
||||
|
||||
```
|
||||
src/databases/officer_db/
|
||||
├── src/
|
||||
│ ├── db.ts # the connection
|
||||
│ ├── index.ts # public surface: one `export * from './<feature>'` per line
|
||||
│ ├── schema.ts # what db:push creates — see below
|
||||
│ ├── types.ts # every type export (Select / Insert / extended)
|
||||
│ ├── crypto.ts # at-rest encryption, one key per purpose
|
||||
│ ├── secret-store.ts # the key store itself (SQLite, outside Postgres)
|
||||
│ └── <feature>/
|
||||
│ ├── index.ts # what this feature exports — declared here, not in a list three levels up
|
||||
│ ├── schema.ts # its tables
|
||||
│ └── queries.ts # everything that reads or writes them
|
||||
└── package.json # exports ".", "./types", "./db", "./schema", "./secret-store", "./*"
|
||||
```
|
||||
|
||||
**A feature owns its own public surface.** `src/index.ts` is one `export *` per feature and nothing
|
||||
else; what a feature exports is declared in its own `index.ts`, beside the code it describes. Adding a
|
||||
query function is one file in one directory, rather than that file plus a hand-written list of every
|
||||
symbol in the package. That list was 297 lines until 2026-08-13 and it had already drifted — twelve
|
||||
features listed twice, `db` and `schema` buried at line 270 with three feature blocks after them.
|
||||
|
||||
**One directory per feature, holding both halves.** Restructured 2026-08-13 from parallel `schema/` and
|
||||
`queries/` trees, where the two sides had drifted: four features were named differently on each side
|
||||
(`app-store`/`sidecar-installs`, `email`/`email-accounts`, `server`/`server-config`), `operations` had no
|
||||
query file at all, and `integrations` had no schema file.
|
||||
|
||||
One directory is still lopsided and says so by its contents: `integrations/` has only queries, because it
|
||||
spans `server` and `user-data`. (`operations/` was the other, and was deleted on 2026-08-13 along with the
|
||||
Task Logs feature — see below.)
|
||||
|
||||
**`src/schema.ts` is drizzle-kit's view, not the runtime's.** `drizzle.config.ts` points at it, so a
|
||||
commented line there removes a table from the DATABASE without removing a line of code — every query
|
||||
imports its tables from `./schema` inside its own feature directory. That is what lets a fresh install
|
||||
create only the core tables, with the plugin ones commented out until their plugin is installed.
|
||||
|
||||
## Schema changes use `push`, not migrations
|
||||
|
||||
`bun db:push` diffs the schema code against the live database and alters it directly. **`drizzle-kit
|
||||
migrate` has never been run here** — there is no `__drizzle_migrations` table. Change the schema, run
|
||||
push, done. `bun db:gen` writes files to `migrations/`, but nothing applies them; treat the schema code
|
||||
as the source of truth, never those files.
|
||||
|
||||
**The schema is the source of truth for what the database may contain**, not just for its shape. Where a
|
||||
column has a known set of legal values, say so with a `check()` rather than leaving it free `text` —
|
||||
otherwise a value the code stopped supporting sits there unnoticed. `serverIntegrations.provider` is the
|
||||
worked example: rows for deleted chat integrations kept their bot tokens long after the code that read
|
||||
them was gone, because nothing structural said they had become illegal.
|
||||
|
||||
```ts
|
||||
const SERVER_PROVIDERS = ['google', 'apify'] as const;
|
||||
|
||||
check(
|
||||
'ck_server_integrations_provider',
|
||||
// sql.raw, not sql`${p}` — an interpolated JS string binds as a parameter, so the constraint is
|
||||
// emitted as `IN ($1, $2)` and Postgres refuses it, breaking push for the WHOLE schema.
|
||||
sql`${table.provider} IN (${sql.join(
|
||||
SERVER_PROVIDERS.map((p) => sql.raw(`'${p}'`)),
|
||||
sql`, `,
|
||||
)})`,
|
||||
);
|
||||
```
|
||||
|
||||
Adding a constraint fails while existing rows violate it. That is the point: push refusing tells you the
|
||||
database has drifted, instead of quietly accepting it. Clean the rows, then push.
|
||||
|
||||
### Composite keys: use `uniqueIndex`, and name any long foreign key
|
||||
|
||||
**Declare a multi-column uniqueness rule as `uniqueIndex('uq_…').on(a, b)`, never `unique('uq_…').on(a, b)`.**
|
||||
|
||||
drizzle-kit mis-diffs named composite unique CONSTRAINTS. It reads them back from the database, compares
|
||||
them against a schema that declares exactly the same name, columns and order, decides they differ, and
|
||||
emits a `DROP CONSTRAINT` + `ADD CONSTRAINT` pair — on every push, forever. Fifteen of them made
|
||||
`db:push` plan 32 statements against a database that already matched, and `ADD UNIQUE` on a populated
|
||||
table is a data-risk statement, so push stopped on an interactive _"do you want to truncate?"_ prompt
|
||||
that could never be resolved by answering it.
|
||||
|
||||
Reproduced on a database drizzle had itself created seconds earlier, so it is not drift and not
|
||||
something your change caused. Single-column `.unique()` is diffed correctly and is unaffected — only the
|
||||
table-level `unique('name').on(...)` form. Unique indexes are diffed on a different code path and are
|
||||
stable. Verified on drizzle-kit 0.31.9 / drizzle-orm 0.45.1.
|
||||
|
||||
A unique index enforces exactly what the constraint did, and `onConflictDoUpdate({ target: [...] })`
|
||||
accepts it as an arbiter. The one thing it cannot do is be the target of a foreign key — Postgres
|
||||
requires a unique _constraint_ there. Nothing here has a composite foreign-key target; check before
|
||||
adding one.
|
||||
|
||||
**Name a foreign key explicitly when drizzle's generated name would exceed 63 characters.** Postgres
|
||||
truncates identifiers at 63 and stores the shortened form, so drizzle keeps comparing against its own
|
||||
longer version and re-creates the constraint on every push.
|
||||
`user_integrations_server_integration_id_server_integrations_id_fk` was 65, and is now declared with
|
||||
`foreignKey({ name: 'fk_user_integrations_server_integration', … })`.
|
||||
|
||||
**Known remaining churn, harmless:** a composite `primaryKey` has the same diffing bug and there is no
|
||||
index form to escape to — a primary key must be a constraint. `music_now_playing` therefore drops and
|
||||
re-adds `pk_music_now_playing` on every push. Two statements, silent, no prompt even with rows in the
|
||||
table, data unaffected. Neither naming it nor un-naming it helps — both were tested. Leave it.
|
||||
|
||||
**All six over-long foreign keys are now named, 2026-08-23.** They were deferred as "noise rather than a
|
||||
fault" for four days. What ended that was a deploy plan saying _"expect no changes, stop and report if it
|
||||
wants to alter something"_ — which this made impossible to satisfy on any host, forcing the deploy agent to
|
||||
overrule its own instructions and continue. A documented annoyance became a plan instruction nobody could
|
||||
follow.
|
||||
|
||||
The six, and where each lives:
|
||||
|
||||
fk_command_hq_watcher_fires_session officer_db/src/command-hq/schema.ts
|
||||
fk_command_hq_session_tags_session officer_db/src/command-hq/schema.ts
|
||||
fk_bitcoin_wallet_frozen_utxos_wallet plugins/bitcoin-wallet/db/schema.ts
|
||||
fk_bitcoin_wallet_chain_cache_wallet plugins/bitcoin-wallet/db/schema.ts
|
||||
fk_atelier_collection_items_collection plugins/atelier/sidecar/db/collections/schema.ts
|
||||
fk_atelier_collection_items_generation plugins/atelier/sidecar/db/collections/schema.ts
|
||||
|
||||
Two things worth knowing if you add another. Naming it means REMOVING the inline `.references()` on the
|
||||
column, or drizzle creates both. And `walletChainCache` had to move from the two-argument `pgTable` form to
|
||||
the three-argument one, because there was nowhere else to put the declaration.
|
||||
|
||||
**`pk_music_now_playing` still churns, and it cannot be fixed.** Two statements per push. Tested on
|
||||
2026-08-23 rather than assumed: removing the explicit name produces the identical drop-and-re-add under
|
||||
drizzle's generated name (`music_now_playing_user_id_device_pk`), so this is the named-composite mis-diff
|
||||
rather than the truncation one, and there is no index form to escape to because a primary key must be a
|
||||
constraint. **A push is therefore expected to print exactly these two statements and nothing else** — which
|
||||
is a far more useful baseline than ten, because anything else really is your change.
|
||||
|
||||
**Rules that still apply:**
|
||||
|
||||
1. **Never answer "Yes, truncate the table"** if a prompt ever does appear. It destroys rows and fixes
|
||||
nothing — whatever is being re-created gets re-created next push regardless.
|
||||
2. **Never delete a constraint from the schema to quiet a diff.** The schema is right. Removing a
|
||||
uniqueness rule would break the upserts that depend on it.
|
||||
3. **Do not use `--force`.** It auto-accepts data-loss statements and nobody has established which
|
||||
branch it takes at a truncate prompt.
|
||||
4. **Read the plan before applying it:**
|
||||
`bunx drizzle-kit push --config=drizzle.config.ts --verbose` prints every statement first. Expect the
|
||||
two `pk_music_now_playing` lines and the eight from the four over-long foreign keys above — ten in
|
||||
all. Anything else is your change.
|
||||
|
||||
To test a schema change without touching `officer_dev`: `createdb officer_scratch`, then
|
||||
`POSTGRES_URL=postgresql://postgres:postgres@127.0.0.1:5432/officer_scratch bunx drizzle-kit push
|
||||
--config=drizzle.config.ts`. Push twice — the second run tells you whether your declaration is stable.
|
||||
|
||||
## Type naming
|
||||
|
||||
```ts
|
||||
// types.ts — inferred from the schema, never hand-written
|
||||
export type UserSelect = typeof Schema.users.$inferSelect;
|
||||
export type UserInsert = typeof Schema.users.$inferInsert;
|
||||
|
||||
// The bare name is the hydrated shape, when a table has relations worth carrying
|
||||
export type User = UserSelect & {
|
||||
passkeys: PasskeySelect[];
|
||||
};
|
||||
```
|
||||
|
||||
Organise `types.ts` by domain with section comments, mirroring the schema files.
|
||||
|
||||
## Queries
|
||||
|
||||
Hand-written, one `queries.ts` per feature directory, importing tables from `./schema` beside it and
|
||||
types from `../types`:
|
||||
|
||||
```ts
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { db } from '../db';
|
||||
import { users, passkeys } from '../schema';
|
||||
import type { UserSelect } from '../types';
|
||||
|
||||
export async function getUsers(): Promise<UserSelect[]> { … }
|
||||
```
|
||||
|
||||
Every query is exported from `src/index.ts`, which is the only surface callers use.
|
||||
|
||||
## Importing
|
||||
|
||||
```ts
|
||||
// ✅ types from the types subpath
|
||||
import type { User } from 'officerdb/types';
|
||||
// ✅ queries, schema and drizzle helpers from the package root
|
||||
import { getUserById, eq } from 'officerdb';
|
||||
|
||||
// ❌ never reach into src/schema or src/queries directly
|
||||
// ❌ never hand-write a type a table can infer
|
||||
```
|
||||
|
||||
In app code import from `'types'`, which re-exports the database types. Only server and database code
|
||||
imports `officerdb/types` directly.
|
||||
|
||||
## Conventions
|
||||
|
||||
- `serial` for ids on small tables; `bigserial` with `mode: 'number'` where the row count is unbounded
|
||||
(`chat_session_events` is the example — its id is also the replay cursor).
|
||||
- `timestamp('…', { withTimezone: true })`, always.
|
||||
- Index anything you filter on. Drizzle-inferred types reflect nullability correctly, so guard rather
|
||||
than cast.
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# Themes
|
||||
|
||||
Drop a theme in here and it appears in the picker on the next page load. No install step, no rebuild, no
|
||||
restart — a theme is a block of CSS custom properties, and none of that needs compiling.
|
||||
|
||||
**This directory is untracked**, exactly like `plugins/`. Only this file is in the repository. Your themes
|
||||
are yours; the platform's own live in `src/workspaces/theme/css/themes/`.
|
||||
|
||||
---
|
||||
|
||||
## The shape
|
||||
|
||||
```
|
||||
themes/
|
||||
my-theme/
|
||||
theme.css required — the values
|
||||
theme.json required — the name a person reads
|
||||
assets/ optional — a wallpaper, a logo
|
||||
```
|
||||
|
||||
The directory name **is** the theme's id. It is not repeated in the manifest, because an id that can
|
||||
disagree with where its files sit eventually will.
|
||||
|
||||
### `theme.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "My Theme",
|
||||
"family": "My Theme",
|
||||
"dark": true
|
||||
}
|
||||
```
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `name` | required — what the picker shows |
|
||||
| `family` | optional — groups variants together, like `Duck Light` and `Duck Dark`. Defaults to `name` |
|
||||
| `dark` | optional — adds the `.dark` class. Set it for a dark theme; several hundred `dark:` utilities still resolve against it |
|
||||
|
||||
### `theme.css`
|
||||
|
||||
Must target its own directory name, or nothing will happen and it will be baffling:
|
||||
|
||||
```css
|
||||
[data-theme='my-theme'] {
|
||||
--background: #1e1e2e;
|
||||
--foreground: #cdd6f4;
|
||||
/* …the rest */
|
||||
}
|
||||
```
|
||||
|
||||
The server checks this on discovery and reports it rather than letting you wonder.
|
||||
|
||||
---
|
||||
|
||||
## What to put in it
|
||||
|
||||
**Twenty tokens are required.** They are the standard shadcn set, which is what every published palette
|
||||
already ships — Tokyo Night, Catppuccin, Gruvbox, Nord all come in this vocabulary, so porting one is
|
||||
mostly copy-paste.
|
||||
|
||||
```
|
||||
background foreground · card card-foreground · popover popover-foreground
|
||||
primary primary-foreground · secondary secondary-foreground
|
||||
muted muted-foreground · accent accent-foreground
|
||||
destructive destructive-foreground · border input ring · radius
|
||||
```
|
||||
|
||||
**Everything else is derived from those.** Panels, the header, the dock, glass, grid lines, scrollbars —
|
||||
all computed from `card`, `border`, `background` and `foreground`. A palette theme never mentions them.
|
||||
|
||||
**Four more are worth setting**, because the standard set has no notion of them and the defaults are
|
||||
generic: `--success`, `--warning`, `--info`, `--busy`, each with a `-foreground`. `busy` means *running*,
|
||||
not *warning* — it is what a live job wears.
|
||||
|
||||
**Anything else you want to change, you can.** Declaring a variable in your theme beats the derived
|
||||
default, because both land on `<html>` and yours is more specific. That is how a theme gets a *texture*
|
||||
rather than just a palette:
|
||||
|
||||
```css
|
||||
[data-theme='my-theme'] {
|
||||
--panel-bg: rgba(255, 255, 255, 0.08); /* glass instead of a flat card */
|
||||
--panel-blur: 20px;
|
||||
--panel-radius: 0; /* square panels */
|
||||
--page-bg-src: '/themes/my-theme/assets/wallpaper.webp';
|
||||
--logo-src: '/themes/my-theme/assets/logo.svg';
|
||||
}
|
||||
```
|
||||
|
||||
The full list of what you can override is in `src/workspaces/theme/README.md`, and
|
||||
`src/workspaces/theme/css/themes/duck-dark.css` is a worked example of a textured theme.
|
||||
|
||||
**Assets are quoted paths, not `url(...)`.** The bundler resolves `url()` at build time and your files are
|
||||
served at runtime, so a `url()` token would break. The app wraps the path for you.
|
||||
|
||||
---
|
||||
|
||||
## Writing one
|
||||
|
||||
Start from `src/workspaces/theme/css/themes/plain.css` rather than from a Duck theme. Plain is white,
|
||||
black and grey throughout, so every value you change is one you decided about, with nothing inherited from
|
||||
someone else's brand.
|
||||
|
||||
Then: reload the page, open the picker or press `ctrl+shift+space`, and use `j`/`k` to browse. `l` applies
|
||||
the focused theme to the app behind the list, so you can watch your own theme against real screens.
|
||||
|
||||
Editing `theme.css` and reloading is the whole loop. The stylesheet is cached for a minute.
|
||||
|
||||
---
|
||||
|
||||
## Checking your work
|
||||
|
||||
Render the app under **Plain** first if something looks wrong under yours. Anything still coloured under
|
||||
Plain is a component painting itself rather than reading a token — that is a platform bug, not yours, and
|
||||
worth reporting.
|
||||
|
||||
`bun run check:theme` counts hardcoded colours in the platform. It does not check themes, but it is why
|
||||
your theme has a chance of working: the number can only go down.
|
||||
+3
-115
@@ -1,118 +1,6 @@
|
||||
# Themes
|
||||
|
||||
Drop a theme in here and it appears in the picker on the next page load. No install step, no rebuild, no
|
||||
restart — a theme is a block of CSS custom properties, and none of that needs compiling.
|
||||
**The instructions live in [`AGENTS.md`](AGENTS.md). Read it first — this file only points there.**
|
||||
|
||||
**This directory is untracked**, exactly like `plugins/`. Only this file is in the repository. Your themes
|
||||
are yours; the platform's own live in `src/workspaces/theme/css/themes/`.
|
||||
|
||||
---
|
||||
|
||||
## The shape
|
||||
|
||||
```
|
||||
themes/
|
||||
my-theme/
|
||||
theme.css required — the values
|
||||
theme.json required — the name a person reads
|
||||
assets/ optional — a wallpaper, a logo
|
||||
```
|
||||
|
||||
The directory name **is** the theme's id. It is not repeated in the manifest, because an id that can
|
||||
disagree with where its files sit eventually will.
|
||||
|
||||
### `theme.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "My Theme",
|
||||
"family": "My Theme",
|
||||
"dark": true
|
||||
}
|
||||
```
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `name` | required — what the picker shows |
|
||||
| `family` | optional — groups variants together, like `Duck Light` and `Duck Dark`. Defaults to `name` |
|
||||
| `dark` | optional — adds the `.dark` class. Set it for a dark theme; several hundred `dark:` utilities still resolve against it |
|
||||
|
||||
### `theme.css`
|
||||
|
||||
Must target its own directory name, or nothing will happen and it will be baffling:
|
||||
|
||||
```css
|
||||
[data-theme='my-theme'] {
|
||||
--background: #1e1e2e;
|
||||
--foreground: #cdd6f4;
|
||||
/* …the rest */
|
||||
}
|
||||
```
|
||||
|
||||
The server checks this on discovery and reports it rather than letting you wonder.
|
||||
|
||||
---
|
||||
|
||||
## What to put in it
|
||||
|
||||
**Twenty tokens are required.** They are the standard shadcn set, which is what every published palette
|
||||
already ships — Tokyo Night, Catppuccin, Gruvbox, Nord all come in this vocabulary, so porting one is
|
||||
mostly copy-paste.
|
||||
|
||||
```
|
||||
background foreground · card card-foreground · popover popover-foreground
|
||||
primary primary-foreground · secondary secondary-foreground
|
||||
muted muted-foreground · accent accent-foreground
|
||||
destructive destructive-foreground · border input ring · radius
|
||||
```
|
||||
|
||||
**Everything else is derived from those.** Panels, the header, the dock, glass, grid lines, scrollbars —
|
||||
all computed from `card`, `border`, `background` and `foreground`. A palette theme never mentions them.
|
||||
|
||||
**Four more are worth setting**, because the standard set has no notion of them and the defaults are
|
||||
generic: `--success`, `--warning`, `--info`, `--busy`, each with a `-foreground`. `busy` means *running*,
|
||||
not *warning* — it is what a live job wears.
|
||||
|
||||
**Anything else you want to change, you can.** Declaring a variable in your theme beats the derived
|
||||
default, because both land on `<html>` and yours is more specific. That is how a theme gets a *texture*
|
||||
rather than just a palette:
|
||||
|
||||
```css
|
||||
[data-theme='my-theme'] {
|
||||
--panel-bg: rgba(255, 255, 255, 0.08); /* glass instead of a flat card */
|
||||
--panel-blur: 20px;
|
||||
--panel-radius: 0; /* square panels */
|
||||
--page-bg-src: '/themes/my-theme/assets/wallpaper.webp';
|
||||
--logo-src: '/themes/my-theme/assets/logo.svg';
|
||||
}
|
||||
```
|
||||
|
||||
The full list of what you can override is in `src/workspaces/theme/README.md`, and
|
||||
`src/workspaces/theme/css/themes/duck-dark.css` is a worked example of a textured theme.
|
||||
|
||||
**Assets are quoted paths, not `url(...)`.** The bundler resolves `url()` at build time and your files are
|
||||
served at runtime, so a `url()` token would break. The app wraps the path for you.
|
||||
|
||||
---
|
||||
|
||||
## Writing one
|
||||
|
||||
Start from `src/workspaces/theme/css/themes/plain.css` rather than from a Duck theme. Plain is white,
|
||||
black and grey throughout, so every value you change is one you decided about, with nothing inherited from
|
||||
someone else's brand.
|
||||
|
||||
Then: reload the page, open the picker or press `ctrl+shift+space`, and use `j`/`k` to browse. `l` applies
|
||||
the focused theme to the app behind the list, so you can watch your own theme against real screens.
|
||||
|
||||
Editing `theme.css` and reloading is the whole loop. The stylesheet is cached for a minute.
|
||||
|
||||
---
|
||||
|
||||
## Checking your work
|
||||
|
||||
Render the app under **Plain** first if something looks wrong under yours. Anything still coloured under
|
||||
Plain is a component painting itself rather than reading a token — that is a platform bug, not yours, and
|
||||
worth reporting.
|
||||
|
||||
`bun run check:theme` counts hardcoded colours in the platform. It does not check themes, but it is why
|
||||
your theme has a chance of working: the number can only go down.
|
||||
Kept separate so agents that look for `AGENTS.md` by convention find the same guidance as those that
|
||||
look for `CLAUDE.md`, without the two drifting apart.
|
||||
|
||||
Reference in New Issue
Block a user