From 5d29b6bd70f7f5802a77f1dedeff395dd076ffbf Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Thu, 12 Nov 2026 13:12:49 +0100 Subject: [PATCH 1/3] docs: move agent doc narrative to on-demand docs The nested CLAUDE.md files load each time an agent reads a file in their folder. A web and core task loaded about 68 KB before work started. Long explanation filled most of it, and some rules were in a file that does not load for the code that they are about. Move the authorization matrix, the targets, the notifications, the REST pipeline, the CLI release, the display preferences and the stale-chunk reload to docs/domains, and keep a short rule list in each CLAUDE.md. Move the REST pipeline rules from apps/cli to apps/web, where server/api-route.ts lives. Fix the claim that apps/web has no tests. Add apps/mobile/CLAUDE.md with the platform design rule and the API compatibility rule. --- CLAUDE.md | 26 +++--- apps/cli/CLAUDE.md | 24 +++-- apps/mobile/AGENTS.md | 1 + apps/mobile/CLAUDE.md | 21 +++++ apps/web/CLAUDE.md | 30 ++++--- docs/domains/authorization.md | 25 ++++++ docs/domains/cli-distribution.md | 9 ++ docs/domains/compliance.md | 11 +++ docs/domains/deployment.md | 4 + docs/domains/display.md | 9 ++ docs/domains/notifications.md | 18 ++++ docs/domains/rest-api.md | 8 ++ packages/core/CLAUDE.md | 145 +++++++++---------------------- tools/oxlint/README.md | 15 ++++ 14 files changed, 203 insertions(+), 143 deletions(-) create mode 120000 apps/mobile/AGENTS.md create mode 100644 apps/mobile/CLAUDE.md create mode 100644 docs/domains/authorization.md create mode 100644 docs/domains/cli-distribution.md create mode 100644 docs/domains/compliance.md create mode 100644 docs/domains/display.md create mode 100644 docs/domains/notifications.md create mode 100644 docs/domains/rest-api.md create mode 100644 tools/oxlint/README.md diff --git a/CLAUDE.md b/CLAUDE.md index f6c4a2c5..0ddabe4c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,11 +71,11 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts - **`.oxfmtrc.json`** — tabs, double quotes, width 80, `sortImports`. It also formats JSON and CSS. Nothing lints CSS. - **`oxlint.config.ts`** — four layers, ignoring `.claude/**`, `tools/oxlint/**`, `routeTree.gen.ts`, `src/db/schema/auth.ts` and `dist`: 1. `plugins` + `categories.correctness` (react, react-hooks, jsx-a11y, typescript, oxc, import). - 2. **anti-slop** (vendored at `tools/oxlint/anti-slop/`, from [dmmulroy/anti-slop](https://github.com/dmmulroy/anti-slop)): fifteen rules that reject low-evidence TypeScript — `unknown` in a contract, a `Record` value type, a hand-rolled `typeof` narrowing where a parse belongs, a type assertion with no stated invariant. All `error`, and the tree is clean of them. - 3. **stella** (vendored at `tools/oxlint/stella/`, from [stella's `.oxlint-plugins`](https://github.com/stella/stella/tree/main/.oxlint-plugins), Apache-2.0): `no-vacuous-throw-assertion` (an argument-less `.toThrow()` passes for any thrown value), `no-document-cookie`, `require-suppression-description`, `no-foreign-directive` and `no-partial-record-satisfies`. The other ~126 upstream rules were measured against this repo and skipped: domain-specific, already covered, or already passing. + 2. **anti-slop** (`tools/oxlint/anti-slop/`): fifteen rules that reject low-evidence TypeScript — `unknown` in a contract, a `Record` value type, a hand-rolled `typeof` narrowing where a parse belongs, a type assertion with no stated invariant. All `error`, and the tree is clean of them. + 3. **stella** (`tools/oxlint/stella/`): five rules, among them `no-vacuous-throw-assertion` (an argument-less `.toThrow()` passes for any thrown value) and `require-suppression-description`. 4. A handful of named rules and overrides — among them the `no-restricted-imports` override that keeps `apps/cli` off the server graph (see `apps/cli/CLAUDE.md`). See the comments in the file. -**Both plugins are vendored, not depended on — those files are ours to edit.** Three anti-slop rules carry a `Local amendment to the upstream rule` comment saying why (Zod's `.shape`; a `.catch()` handler's parameter is `unknown`; leading comments on an `export const` attach to the ExportNamedDeclaration). Read the comment before "fixing" one back. Provenance for the stella rules is in `tools/oxlint/stella/index.ts`, so a re-sync stays a diff. +**Both plugins are vendored, not depended on — those files are ours to edit.** A rule with a `Local amendment to the upstream rule` comment says why it differs. Read the comment before "fixing" one back. The sources, the licence and the amendments are in `tools/oxlint/README.md`. **Every suppression needs a reason.** A bare `oxlint-disable` fails the build. The reason goes inline as a `-- ` trailer, or as a prose comment on the line above; the directive must be the **last** comment line either way. @@ -108,8 +108,8 @@ The split is deliberate: `packages/core` must stay reusable from another process **Boundary rule:** `packages/core` never imports TanStack/React. All business logic lives in `src/services/`, one file per aggregate. Every exported service function takes an explicit `ctx: { organizationId, userId }` (`src/services/types.ts`) as its first argument — **tenancy is a parameter, never ambient** — so the same function is callable from a server function, a REST route, a background job or an MCP tool. -`apps/web`, `apps/cli` and `packages/core` each carry their own `CLAUDE.md`: -`packages/core/CLAUDE.md`, `apps/web/CLAUDE.md` and `apps/cli/CLAUDE.md`. They +`packages/core`, `apps/web`, `apps/cli`, `apps/site` and `apps/mobile` each +carry their own `CLAUDE.md`. They hold the layout of the workspace and the rules that only apply inside it. Claude Code loads a nested file when it touches a file in that folder. Codex and similar tools read the `AGENTS.md` symlinks on the path from the root to @@ -135,11 +135,17 @@ you are about to change before you change it** — these are not loaded for you. | `docs/domains/webhooks.md` | the outbound webhooks — `services/events.ts`, `webhooks.service.ts`, `jobs/webhook-delivery.ts`, the signature or the SSRF guard | | `docs/domains/audit-log.md` | `services/audit.ts`, `recordAudit` / `recordSecurityEvent`, the better-auth audit hooks, the Audit log page, or any new service function that changes an organization | | `docs/domains/mobile.md` | `mobile-devices.service.ts`, `native-push.ts`, `lib/push-relay.ts`, the `native` channel in `notify.ts`, `api/v1/me/devices` or the timer's Live Activity | -| `docs/domains/deployment.md` | the Dockerfile, CI, the job schedulers, an env flag or PostHog | +| `docs/domains/deployment.md` | the Dockerfile, CI, the job schedulers, an env flag, PostHog, or the stale-chunk reload (`lib/stale-chunk.ts`) | +| `docs/domains/authorization.md` | `access.service.ts`, `guards.ts`, `team-leads.service.ts`, `services/context.ts`, `lib/project-access.ts`, or who can see or do what | +| `docs/domains/compliance.md` | `compliance.service.ts`, `hour-fund.service.ts`, `lib/day-marks.ts`, `components/targets.tsx` | +| `docs/domains/notifications.md` | `services/notify.ts`, `reminder-recipients.ts`, `reminder-settings.service.ts`, `jobs/log-reminders.ts`, `jobs/slack-reminders.ts` | +| `docs/domains/rest-api.md` | `server/api-route.ts`, `lib/posthog-api.ts`, or a new `api/v1` route | +| `docs/domains/cli-distribution.md` | `routes/cli/`, `server/cli-install.ts`, `server/cli-releases.ts`, `farmer update`, or `.github/workflows/cli-release.yml` | +| `docs/domains/display.md` | `styles.css`, `lib/theme.ts`, `lib/display-prefs.ts`, `lib/popup-layer.ts`, or a popup component | `docs/adr/` holds the decisions that a change may contradict. `docs/plans/` holds -the plans for the audit log, the instance settings migration and the reminder -settings. +the plans for the audit log, the instance settings migration, the reminder +settings, the mobile app and mobile parity. ## Rules that survive the split @@ -157,9 +163,9 @@ is in the file named beside it. ## Gotchas -- **Never read the org roster through better-auth's `auth.api.listMembers`.** It throws in an organization over 100 people, which a Harvest import makes routine — archived people count towards the total. `membersService.roster` (`members.service.ts`) queries the tables directly and is what `server/members.ts`'s `listMembers` server fn calls; `auth/index.ts` also raises `membershipLimit` to 10,000 for the paths that still go through better-auth. Don't confuse either with `projectsService.listMembers`, which is a per-project assignment read. +- **Never read the org roster through better-auth's `auth.api.listMembers`.** It throws in an organization over 100 people. Use `membersService.roster` (see "Members" in `packages/core/CLAUDE.md`). - Bun does not walk up parent directories for `.env` in a workspace — `bun run` inside `packages/core` or `apps/web` won't see the root `.env`. Each workspace package has a symlink to the root `.env`; do the same for any new workspace that reads the environment. -- `timeEntriesService.listRange` still performs writes on read by default — it recomputes (and drops) each day's fill block against the rows just read, bounded to the automation window. That is deliberate and commented, but a GET is not idempotent, including through the web app, `api/v1` time-entries and `farmer today`. `listRange(ctx, range, { persist: false })` is the read-only variant: it returns the same rows and stores nothing. `/home`, the MCP server's `list_time_entries` and the assistant use it, because an agent loop re-reads a range far harder than a person opens a screen. +- `timeEntriesService.listRange` still performs writes on read by default, so a GET is not idempotent, including through the web app, `api/v1` time-entries and `farmer today`. `listRange(ctx, range, { persist: false })` is the read-only variant. Use it where an agent loop re-reads a range (see "The ledger" in `packages/core/CLAUDE.md`). ## Agent skills diff --git a/apps/cli/CLAUDE.md b/apps/cli/CLAUDE.md index 9e24946b..ee4e947c 100644 --- a/apps/cli/CLAUDE.md +++ b/apps/cli/CLAUDE.md @@ -12,32 +12,30 @@ the commands and the lint rules. - **Login is the device authorization flow** — better-auth's `deviceAuthorization` plugin, client id `farmer-cli` (the mobile app also uses `farmer-mobile`; `DEVICE_CLIENT_IDS` lists both, and `/device` names the client from `server/device.ts`), 10-minute codes. `farmer login` shows a code and opens `/device` (`routes/device.tsx`), where the signed-in person approves it. **Opening the page is what binds the code to that person** (better-auth's `GET /device` claims it, and approve refuses an unclaimed code), so the page makes that call on mount, client-side, before Approve can work. It reads `user_code` from the raw query string, because the router `JSON.parse`s search values and `2E345678` comes back a number. - **The token is a better-auth session token, and the `bearer` plugin stays off.** With that plugin every server function would accept an `Authorization` header and `resolveMcpOrgContext`'s credential order would stop being safe. `resolveCliUser` (`server/api-auth.ts`) is the only reader: `internalAdapter.findSession`, then the sliding refresh `getSession` does, copied by hand because `findSession` does not slide — without it a token used every day dies seven days after login. The CLI keeps the token in the OS keyring (`Bun.secrets`), or a 0600 `credentials.json` where there is none. - **`FARMER_TOKEN` is the other credential** — a personal API token for a script, which wins over the stored login (`connect`, `session.ts`). A session built from it never deletes the stored login on a 401, never writes the config (`saveConfig` returns early, because a token bound to one workspace would replace the cached list), and refuses `farmer org use`; `farmer logout` does not revoke it. The server tells the two tokens apart by the `fmr_` prefix. See `docs/domains/api-tokens.md`. -- **Every route runs one pipeline, `server/api-route.ts`** (`apiRoute` for `api/v1/orgs/$orgSlug/*`, `userApiRoute` for `me` and `session`), in a fixed order: `CLI_ENABLED`, the per-address limit before any read, the `x-farmer-cli-version` check (426), the credential, the per-user and write limits, the Zod parse with the `src/schema/*` input, the service call. The organization is in the URL for MCP's reason, checked by the same `orgContextService.resolveBySlug`. -- **The pipeline is also where this surface is REPORTED** (`lib/posthog-api.ts`, deferred inside `serve` for the client-bundle rule above). Every exit runs through one `finish`, so a request refused by the flag, the rate limiter, the version check or the credential is counted exactly like one that was served — a CLI being turned away is what a per-route capture would miss, and there are nineteen routes that would each have to remember. One `api_request` event carries the route TEMPLATE (`/api/v1/orgs/:orgSlug/time-entries/:id`, never the slug or the row id), the method, the status, the duration and `api_caller` — `cli` or `browser`, taken from the version header rather than guessed from the user agent. A generic 500 also raises an `$exception`; a 403, a 404 and a 422 are answers this pipeline gives on purpose and are not faults. A request that resolved no person rides `$process_person_profile: false`, so a refused flood stays countable without minting people. The CLI BINARY stays uninstrumented on purpose: a tool installed on somebody's laptop cannot be asked to report truthfully, and an old binary would report nothing at all. -- **A session cookie counts on a GET, and on a write only with proof of the same origin** (`cookieUser` and `provesSameOrigin`, `server/api-route.ts`). A signed-in browser can read the URLs the CLI calls, which is how the answers get looked at in development. A write takes the cookie only when it carries `x-farmer-session: 1` (`lib/api-session-header.ts`) and, when the browser sends one, `Sec-Fetch-Site: same-origin` — that is what lets the API reference at `/api-docs` send requests as the reader. A cross-site form can POST `text/plain` with no preflight, but it cannot set a custom header, and a cross-site `fetch` that sets one needs a CORS preflight that nothing under `api/v1` answers. **Never add CORS headers to `api/v1`**: that is the whole defence. `DELETE /session` never takes the cookie (`userApiRoute` passes `writes: false`), since it revokes the credential it was sent. A request that sent `Authorization` never falls back to the cookie, so a dead token always gets the 401 that sends the CLI to `farmer login`. -- **Errors map by class, and one rule is only a convention.** `ZodError` and `DayCapacityError` are 422, `AccessError` 403. An error whose constructor is exactly `Error` is taken as a sentence a service threw on purpose and its message goes to the terminal (404 when it says "not found"); anything else is logged and answered 500. **Throw a subclass for anything that is not a sentence for the person** — `lib/github-client.ts` throws bare `Error`s carrying URLs, and is safe today only because no route reaches it. +- **The server side of the CLI's API is `apps/web/src/server/api-route.ts`.** Its rules (the pipeline order, the PostHog report, the cookie on a write, the error mapping) are in `apps/web/CLAUDE.md` and `docs/domains/rest-api.md`. **Never add CORS headers to `api/v1`.** **Throw a subclass of `Error` for anything that is not a sentence for the person**, because the pipeline sends the message of a bare `Error` to the terminal. - **A row number is an address the client recomputes, not state it keeps.** The `#` column of `today`, `week` and `ls` (`render.ts`) numbers the entries INSIDE their day, and `edit`/`rm` resolve it by reading that day again (`selectEntry`, `pick.ts`) — there is no "last list" file, so two terminals and a stale scrollback cannot disagree about what `3` is. Two things hold it up and both are load-bearing: `listRange` orders by `(date, createdAt, id)`, the id breaking a tie that `copy day` makes routinely, and `sortEntries` is the ONE sort both the table and the selection use. A number is 1-2 digits, an id prefix is longer — a day tops out at 96 rows (24 hours in 15-minute steps), and nobody types one character of an id. - **Routes answer projections, never rows** (`src/api/`). A new column must not become a field an installed binary depends on. Raise `MIN_CLI_VERSION` (`api/meta.ts`) when a shape changes in a way an old binary cannot read; `GET /api/v1/meta` hands it out unauthenticated and the pipeline enforces it on every request. - **Repository defaults are ids in a `.farmer.jsonc` the repository commits** (`apps/cli/src/repository-defaults.ts`, `farmer init`; the design is ADR 0002). The nearest file up to the git root names the `org` slug every command runs in, and the `project` and `task` ids `farmer log` and `farmer start` use when `-p`/`-t` are missing — never codes or names, which drift onto another project silently. A flag wins and `--org` turns the file off; each value taken is announced on stderr; a broken or stale file stops the command rather than falling back to the personal default organization. The MCP server cannot read the file, so its `instructions` (`routes/api/mcp/$orgSlug.ts`) teach the agent the same rules, and `list_projects` returns `code` for it. `farmer init` suggests projects from the git remote through `api/v1/orgs/$orgSlug/repository-projects` — a route, not a field on `ApiProject`, so an older server's 404 means "no suggestion". - **`CliError` carries the `status` and the `code` of the failure that made it** (`src/errors.ts`, set in `ApiClient.#failure`). A status alone cannot be branched on: `CLI_ENABLED=false` answers a JSON 404 with a code for every organization route, so only a 404 WITHOUT a code means "this server is older than this binary". `commands/timer.ts` is the first caller, and the pattern is what a command for any new route should use instead of raising `MIN_CLI_VERSION`. - **The stopwatch is one row on the server, not a file on the laptop** (`farmer start`, `continue`, `pause`, `resume`, `stop`, `timer`, `timer discard`; `docs/domains/timer.md`). It is keyed on the PERSON, so `farmer start` in a terminal is stopped by the Stop button in a browser, and a timer running in another workspace is reported rather than hidden. Nothing is logged until `farmer stop`, and the measured time is snapped to the 15-minute step every entry keeps. `pause` and `resume` post to routes that answer an already-held or already-running timer with the row as it stands rather than an error, so two surfaces driving one clock cannot disagree. `--head-start` is read by `parseHeadStart` in `@farmer/core/lib/time`, the one the web dialog and the schema use. On a continued entry `farmer stop --duration` ADDS to what the entry held (`stoppedDuration`), because `confirm` writes the figure as the entry's total; `-p none` sends `null` and an emptied note sends `""`, because an absent field keeps the continued entry's. `farmer continue` refuses a work-time block or time off locally (`whyNotContinued`, through `selectEntry`'s `refuse`), and its picker leaves them out. - **The CLI's import boundary is linted.** At runtime `apps/cli` may import only `@farmer/core/schema`, `/lib/time`, `/lib/search` and `/api`; `import type` from services is fine. The `no-restricted-imports` override in `oxlint.config.ts` fails the build on a runtime `@farmer/core/services|db|auth|jobs` import — that is what keeps the server graph out of a binary anyone can download. -- **Install is one command from the app; the binaries live on GitHub Releases.** `curl -fsSL /cli | sh`, or `irm /cli | iex` on Windows (`routes/cli/`, both scripts in `server/cli-install.ts`; `/cli` picks one by User-Agent, `/cli/install.sh` and `/cli/install.ps1` name them). The releases repository is public, so `/cli/download/` reads the newest `cli-v*` release with no token and 302s to the asset's public `browser_download_url` (`server/cli-releases.ts`). The repository is `CLI_RELEASES_REPO` (default in `@farmer/core/lib/source-repository`, the one place the upstream name is written), so a fork serves its own releases. The read is anonymous, so GitHub allows 60 requests an hour per server address, shared with the contributors card: `cachedRead` (`lib/github-public.ts`) keeps each answer for five minutes, shares one request between concurrent installs, serves the last good answer when GitHub refuses and waits for the rate-limit reset. The binary never passes through the server. The scripts download the `.gz` copy first (a Bun binary is mostly its runtime, and it compresses to less than half), fall back to the plain binary for a release without copies, verify the binary against `SHA256SUMS` and fail closed. -- **`farmer update` runs the server's install script over the running binary** (`commands/update.ts`), with `FARMER_INSTALL_DIR` set to the binary's directory and `FARMER_UPDATE=1`, rather than downloading a release itself — a second copy of the asset choice and checksum logic would drift. On Windows the script renames the running `farmer.exe` to `farmer.exe.old` first, because Windows refuses to overwrite a running exe and allows a rename. From source (`Bun.main` outside `/$bunfs/`) there is nothing to replace, and the command says so. -- **Releasing is a tag.** Bump `apps/cli/package.json`, push `cli-vX.Y.Z`, and `.github/workflows/cli-release.yml` cross-compiles the seven targets on Linux (`bun run build:release`), runs every binary on its own OS and CPU, and only then publishes, with a `.gz` copy of each binary written after the macOS re-sign. A pull request that touches `apps/cli` runs the same build and runs, without publishing. A deployment serves the new release within the five-minute release-lookup cache. -- **A Bun cross-compile leaves the macOS binaries with a code signature that does not match the file** (checked on 1.3.14 and 1.4.0), and Apple silicon kills such a binary. The workflow re-signs both ad hoc with `codesign` on a Mac runner and writes `SHA256SUMS` after that, so the sums `build:release` writes locally are not the release's. Do not "simplify" the workflow back to one Linux job. -- **The musl binaries need `libstdc++` and `libgcc`**, which Alpine's base image leaves out. The install script checks for both before it downloads, and the Alpine run in the workflow installs them. +- **Install and release are in `docs/domains/cli-distribution.md`.** Read it before you change the install scripts, `farmer update` or the release workflow. The rules: + - The binaries live on GitHub Releases, and the binary never passes through the server. The install scripts verify the binary against `SHA256SUMS` and fail closed. + - `farmer update` runs the server's install script over the running binary. Do not add a second copy of the asset choice and the checksum logic. + - **Releasing is a tag.** Bump `apps/cli/package.json` and push `cli-vX.Y.Z`. + - The workflow re-signs the macOS binaries on a Mac runner. Do not "simplify" the workflow back to one Linux job. + - The musl binaries need `libstdc++` and `libgcc`. - **Signed-in devices is the lost-laptop answer.** Preferences lists the person's sessions (`sessionsService`), labels a CLI one from `CLI_USER_AGENT_PREFIX` in its user agent, and deleting the row is the revocation — the CLI's next request gets a 401 and drops its token. Revoking the session you are using is refused: that is signing out. - **`CLI_ENABLED=false`** (env, default on, `lib/cli-flag.ts`) 404s `api/v1/orgs/*`, `me`, `session`, the device endpoints (gated in `routes/api/auth/$.ts`), `/device` and `/cli`; `meta` answers `cliEnabled: false`. - ## Testing `bun test` from `apps/cli` covers the duration and date parsers, the table format, the device flow and the API client against an injected `fetch`. -Everything testable about the CLI's **API** — the membership check, the -projections, the version compare, the flag — lives in `packages/core` instead, -because `apps/web` has no test suite. +Everything testable about the CLI's **API** that does not need a route — the +membership check, the projections, the version compare, the flag — lives in +`packages/core`. The guards of the real route handlers are tested in +`apps/web/src/server/*.test.ts`. ## See also diff --git a/apps/mobile/AGENTS.md b/apps/mobile/AGENTS.md new file mode 120000 index 00000000..681311eb --- /dev/null +++ b/apps/mobile/AGENTS.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/apps/mobile/CLAUDE.md b/apps/mobile/CLAUDE.md new file mode 100644 index 00000000..35b2b57d --- /dev/null +++ b/apps/mobile/CLAUDE.md @@ -0,0 +1,21 @@ +# apps/mobile + +`@farmer/mobile`, the Expo app for Android and iOS. Read the root `CLAUDE.md` first for the commands and the lint rules. + +```bash +bun run test # bun test three times: in the local zone, America/New_York and Pacific/Auckland +bun run typecheck +bun run make-icons # the app icon, the splash and the notification icon +``` + +## Read first + +- `apps/mobile/README.md`: where a screen lives, and the rules for a new screen (the settings-list kit, the icons, `usePalette()`, `useMotionPreference()`, `FarmerClient`). +- `docs/domains/mobile.md`: the push, the Live Activity, the sign-in exchange and the builds. +- `docs/adr/0005-native-mobile-app.md` and `docs/plans/mobile-app.md`: the decisions and the order of the work. + +## Rules + +- **Each platform has its own design system.** Android follows Material 3 Expressive. iOS follows the Apple Human Interface Guidelines. Do not mix them: a Material pill, an outlined field or a bottom-sheet menu on iOS is a bug. Put an Android visual change in a `.android.tsx` file or behind `Platform.OS === "android"`, and keep iOS on native controls. After a change to a shared file, check both platforms. +- **The app is published, so old app versions and old servers exist.** A new build parses each response with the Zod schemas of `@farmer/api-client`. A required field that an older server does not send fails the parse, and a new endpoint is a 404 there. Deploy the server before a `mobile-v*` tag that needs a new API field. An added response field is safe for an old app, because Zod strips unknown keys. +- The tests run in three timezones. A date test that passes only in your zone fails CI. diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md index 8d8f9811..586fd48f 100644 --- a/apps/web/CLAUDE.md +++ b/apps/web/CLAUDE.md @@ -25,7 +25,10 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts - **The stopwatch is mounted in three places** — the sidebar control card (`components/time/timer-row.tsx`), the button beside "Log time" on the Day view, and the cap on Settings → My schedule. Both stop controls HOLD the clock before they open the Log dialog, which is why that dialog's third button says Resume. All three read ONE query through `hooks/use-timer.ts`, so no two surfaces can disagree about what is running. The Start button on each entry row (it continues the entry) is not a fourth surface: the list reads the timed entry id once through `useTimedEntryId` in the same file and passes it to each row as a prop, so no row subscribes to the timer. Read `docs/domains/timer.md` before changing any of them. - **`lib/entry-options.ts` remembers per device** (localStorage) the last project and task per org and per dialog, and the `fillsDay`/`overtime` options per project and task. Repeat is deliberately not remembered. - **The week starts on the organization's `weekStartsOn`** (`organization.week_starts_on`, 1 = Monday by default, 0 = Sunday; Settings → Organization). `startOfWeekKey` and `resolveReportPeriod` take it as a required argument, so a new caller cannot forget it silently. Pages read it from the `/$orgSlug` route context (`useWeekStartsOn`, `useWeekdays`), services from `ctxWeekStartsOn`, and the CLI from `whoami`. Stored weekday numbers stay `Date#getDay()`'s (Sunday = 0); only the order a week is drawn in changes. -- **Light/dark is `data-theme` on `` and nothing else.** Both palettes are written out in `styles.css`; `lib/theme.ts` owns the attribute and the DOM is the state — no provider. `themeInitScript` runs inline in `` (`__root.tsx`) before React exists, because the choice lives in localStorage and applying it on hydrate flashes the light palette; that mismatch is why `` carries `suppressHydrationWarning`. No stored choice follows the OS. The calendar's category tints (`lib/category-colors.ts`) are light washes computed in JS and read bright in dark mode. **Preferences → Display is the same design**, per device and off by default: "High contrast" (`data-contrast="high"`), "Boring font" (`data-font="sans"`), "Less movement" (`data-motion="reduce"`) and "Compact tables" (`data-density="compact"`), all owned by `lib/display-prefs.ts` and set by `displayInitScript` in the same `` script. High contrast draws every mark harder on the SAME paper — the three surfaces and `--fg` do not move, and `--mut`, `--faint`, `--acc`, the status colors, the chart earths, the two hairlines and `--text-sel` each move in OKLCH lightness alone until they reach 7 against the worst surface (`--faint` answers to 4.5, so it stays a step quieter than `--mut`). Focus is one `*:focus-visible` outline rule rather than a token, because the house ring pattern writes its opacity into the class at about thirty call sites. Every number is fitted by `scripts/check-palette-contrast.ts` (`bun run check:palette`), which sweeps both contrast levels across the wheel — change a lightness in `styles.css` and change it there. Boring font re-points `--serif`, so a new display rule must read `var(--serif)`, never name Instrument Serif. Less movement ends every CSS animation and transition at once (`styles.css`) and sets Motion's `MotionGlobalConfig.instantAnimations`, so completion callbacks still fire but no animation is seen. Compact tables sets `--table-cell-py`, which only `TableCell`'s default padding reads — a cell with its own `py-*` keeps it. +- **Light/dark is `data-theme` on `` and nothing else.** `lib/theme.ts` owns the attribute and the DOM is the state — no provider. `themeInitScript` runs inline in `` (`__root.tsx`) before React exists, which is why `` carries `suppressHydrationWarning`. Preferences → Display is the same design, per device, owned by `lib/display-prefs.ts`. Read `docs/domains/display.md` before you change a colour, a Display preference or a popup. The rules: + - Change a lightness in `styles.css` and change it in `scripts/check-palette-contrast.ts` too (`bun run check:palette`). + - A new display rule reads `var(--serif)`. Never name Instrument Serif. + - Compact tables sets `--table-cell-py`, which only `TableCell`'s default padding reads. ## The client-bundle rule @@ -50,28 +53,27 @@ Dev is `vite dev`, which never loads `server.ts`. **Production is a Bun-native h **Every response gets baseline security headers** (`lib/security-headers.ts`) — a dynamic one in `server.ts`'s `/*` wrapper, a static asset in its own route handler, because the static routes answer before the wrapper: `frame-ancestors 'none'`, `nosniff` and a referrer policy. Not a full CSP, because the inline theme and PostHog scripts in `__root.tsx` would need hashes or a nonce first, and not HSTS, which belongs at the TLS edge. A header a route sets itself wins, which keeps `api/files/$.ts`'s `sandbox` policy whole. `vite dev` sends none of them. +## The API pipeline + +Every `api/v1` route runs one pipeline, `server/api-route.ts` (`apiRoute` for `api/v1/orgs/$orgSlug/*`, `userApiRoute` for `me` and `session`). Read `docs/domains/rest-api.md` before you change it. The rules: + +- The order is fixed: `CLI_ENABLED`, the per-address limit before any read, the `x-farmer-cli-version` check (426), the credential, the per-user and write limits, the Zod parse, the service call. +- Every exit runs through one `finish`, which sends one `api_request` event with the route TEMPLATE, never the slug or the row id. +- **Never add CORS headers to `api/v1`.** A write takes the session cookie only with `x-farmer-session: 1` and a same-origin proof (`cookieUser`, `provesSameOrigin`). A request that sent `Authorization` never falls back to the cookie. +- Errors map by class: `ZodError` and `DayCapacityError` are 422, `AccessError` 403. The message of a bare `Error` goes to the terminal. **Throw a subclass for anything that is not a sentence for the person.** + ## Gotchas - **On farmer.profi.co, `/` is the public site, so web code never targets `/`; use `/_`.** A full-page load to `/` (a `callbackURL`, `window.location`, a `Response.redirect`, a server `redirect`) lands on the marketing page. Use `/_`, or `{ to: "/$orgSlug", params: { orgSlug: "_" } }`. - **`vite build` can emit server code into `dist/client`, and `server.ts` serves everything it finds there.** A deferred `await import("@farmer/core/…")` in a client-reachable module is chunked by rolldown *before* the server-fn transform strips the handler, which leaves an orphan island (better-auth's config, the drizzle schema, services) published at `/assets/.js`. `apps/web/scripts/prune-client-assets.ts` runs as the second half of `bun run build`, deletes the island and prints what it removed. It currently prunes nothing; keep it anyway, because it is the detector. It computes reachability from what the server build can name and aborts rather than guess — don't "simplify" it into an unconditional delete, and don't drop it from the `build` script. -- **A tab opened before a deploy reloads once when a chunk is gone.** Each deploy replaces the hashed files in `/assets/`. A missing one is answered by the `/assets/*` route in `server.ts` with a bare 404 (`Cache-Control: no-cache`, no SSR render), so the import fails with "Failed to fetch dynamically imported module". The exact asset routes win over that wildcard. There are two reload paths. TanStack's `lazyRouteComponent` reloads once for each message on its own (a `sessionStorage` key `tanstack_router_reload:`, which `lib/stale-chunk.ts` never removes, because it is TanStack's loop guard). After that, each render of the route throws the cached error to the error screen. The error screen path (`lib/stale-chunk.ts`, called from `components/route-error.tsx` and the Rewind route's `errorComponent`) reloads at most once per 30 seconds (a `sessionStorage` stamp), and only for an error that TanStack does not handle, such as Vite's "Unable to preload CSS for". It never repeats a reload that TanStack already did, so a file that is really missing or a network that is down shows the error screen instead of a loop. On that screen, "Try again" reloads the page for a stale chunk error (a re-render throws the same cached error), and the fault is captured once per page load. There is deliberately no `vite:preloadError` handler: TanStack preloads on link intent, and for a component chunk `lazyRouteComponent` swallows the preload failure and reloads on the later render, so the event cannot tell a preload from a navigation and a reload there would drop the unsaved input of a person who only hovered a link. A reload is not captured as an exception, and neither is a later failure in the same page while the reload is pending. The next page sends one `stale_chunk_reloaded` event for each reload from `lib/posthog-client.ts`, right after the client starts, with `source: "router"` (TanStack) or `"error-screen"`. A blocked reload is captured as before. +- **A tab opened before a deploy reloads once when a chunk is gone** (`lib/stale-chunk.ts`, the `/assets/*` route in `server.ts`). Read "A stale chunk after a deploy" in `docs/domains/deployment.md` before you change it. Never remove TanStack's `tanstack_router_reload:` key, because it is TanStack's loop guard. There is deliberately no `vite:preloadError` handler: a reload there would drop the unsaved input of a person who only hovered a link. - **A PostHog call in a child effect must not run before the client started.** React runs child effects before the effects of the parent, and `@posthog/react` starts its client in the effect of its provider, so a `capture`, `identify`, `register` or `captureException` in the first commit was dropped. `lib/posthog-client.ts` (`startPostHog`) starts the client during the render of `PostHogRoot` in the browser, and the provider gets it as `client`. Do not pass `apiKey` and `options` to the provider again. A flag hook (`useFeatureFlagEnabled` and the others) reads this started client in its first render, so its value can differ from the server render. - Base UI shadcn components have runtime-only failure modes that typecheck/build/lint all miss: `