Skip to content
Docs
Changelog

Backend conventions

The rules for code in packages/api, each with its reason, an example, the anti-pattern and what enforces it.

Markdown

These rules apply to packages/api. Each one has the same shape: rule, why, example, anti-pattern and enforcement. The enforcement level is one of [type], [lint], [test], [build], [deploy] or [convention]. A [convention] rule depends on review alone, so it is the first candidate for a stronger check. The reasons behind the larger rules are recorded in ADR-0011 (feature shape) and ADR-0010 (Effect in procedures).

One folder per feature, one name per role

Rule. A feature lives in packages/api/src/features/<feature>/. Its files are named <feature>.<role>.ts:

RoleFileRequired
Contract<f>.contract.tswhen the feature has procedures
Procedures<f>.procedures.tswhen the feature is exposed through oRPC
Service<f>.service.tswhen the feature has procedures
Errors<f>.errors.tswhen the feature has domain failures
Rules, enums, policy<f>.rules.ts, <f>.enums.ts, <f>.policy.tsoptional, no I/O
Jobs<f>.jobs.tswhen the feature runs in the cron tick
HTTP edge<f>.http.tswhen a Worker route sits outside oRPC
Internals<f>.<topic>.tsas needed
Tests<f>.<topic>.test.ts; procedure tests are <f>.procedures.test.tsas needed

Code that belongs to no feature lives in packages/api/src/platform/ (rpc, effect, jobs, http, data-table).

Why. The name of a file tells you what it may import and who may import it. A feature can be read, moved or deleted as one folder.

Example.

features/documents/
  documents.contract.ts      documents.procedures.ts   documents.service.ts
  documents.errors.ts        documents.policy.ts       documents.jobs.ts
  documents.queue.ts         documents.chunk.ts        documents.lifecycle-plugin.ts

Anti-pattern. A sub-folder per layer (documents/services/), a second name for the same role (router.ts next to procedures.ts), or queries written inside a procedures file.

Enforcement. [test] scripts/feature-boundaries.test.mjs (in pnpm test) · [lint] direction overrides in oxlint.config.ts.

The contract is a leaf

Rule. <f>.contract.ts starts with the LEAF MODULE header. It imports only zod, other leaves (db/schema/*.enums, *.enums.ts, other contracts) and import type from anywhere.

Why. Web and mobile import the contract. One value import of a server module puts server code in a browser bundle or an app binary (ADR-0002).

Example.

// LEAF MODULE: imported by web and mobile. Only zod, leaves and `import type`.
import { PRIORITIES } from "@fofo/db/schema/todo.enums";
import { z } from "zod";

export const todoCreateInput = z.object({ text: z.string().min(1), priority: z.enum(PRIORITIES) });

Anti-pattern. Importing a constant from a Drizzle table module, or from a service, "because it is already there".

Enforcement. [test] scripts/leaf-modules.test.mjs, which also fails when a features/*/*.contract.ts lacks the header · [lint] packages/config/oxlint-client-boundary.mts · [build] assert-client-bundle-clean.mjs.

No barrel; the public surface is exports

Rule. No index.ts re-exports a feature. Other packages and apps import an enumerated subpath of @fofo/api. Canonical subpaths are ./<feature>/<role>, for example ./todo/contract and ./billing/http. Web and mobile use the canonical subpaths only; the earlier ./routers/*.schema aliases were removed once the mobile app moved to them.

Why. A barrel is how server code reached the browser. An enumerated map makes every new cross-package import a reviewed decision.

Example. import { todoListInput } from "@fofo/api/todo/contract";

Anti-pattern. A wildcard "./*" export, or a ./routers/* subpath brought back.

Enforcement. [test] packages/api/src/exports.test.ts: every target exists, no ./routers/* subpath comes back, nothing exports a procedure, job or service beyond the listed server entries, and every subpath web and mobile import exists. A removed subpath also fails tsc in the app that imports it.

Imports flow one way

Rule.

  • Only platform/rpc/app-router.ts and the agent tool catalog import *.procedures.
  • Only platform/jobs/run.ts imports *.jobs.
  • platform/** does not import features, except those two files and two declared edges: platform/rpc/procedures.ts reads features/admin/admin.roles (the admin guard) and platform/rpc/context.ts builds features/admin/admin.api (the adminApi capability).
  • A feature imports another feature's contract, enums, service, errors, policy or rules. Any other cross-feature import is declared in the boundary test.
  • *.procedures.ts imports no drizzle-orm and no table module (enums are fine): queries live in the service. The lint rule refuses value imports of drizzle-orm, the schema barrel @fofo/db/schema and the per-table modules @fofo/db/schema/<table> (enum leaves and import type pass). A relational query through context.db.query.* needs no import, so the rule cannot see it; that one is left to review.
  • A job lives in <feature>.jobs.ts. The cron tick's job table (platform/jobs/run.ts) imports a feature only by *.jobs, *.config, *.settings or *.outbox (C6): a job in a service file is a job that D4 does not see.
  • There are no import cycles in packages/api/src and packages/db/src.

Why. Each rule keeps a dependency the reader can predict. A domain module that imports a router or a job is the first sign the layering has rotted.

Example. todo.service.ts imports enqueueUserWebhooks from webhooks.events.ts, a declared edge, to queue deliveries inside its transaction.

Anti-pattern. A service that imports another feature's queue or lease module to "reuse a query".

Enforcement. [lint] no-restricted-imports overrides in oxlint.config.ts: D3 (procedures), D4 (jobs), D5 (platform) and D8 (queries in procedures, every feature) · [test] scripts/feature-boundaries.test.mjs (D6; a declared edge that disappears also fails, so the list only shrinks) and the job table's imports (C6) · [test] scripts/import-cycles.test.mjs (D7). The cycle check runs in pnpm test, not in pnpm lint, because oxlint's import plugin made the whole lint about 3.7 times slower.

Tenant data goes through context.db

Rule. A procedure, tool or gateway reads and writes tenant data through context.db, which runs as app_tenant for the session's User and Active Organization. The organizationId filter stays in every query. Crossing tenants is possible only through asSystem(db, reason, fn) with a listed SystemReason, and the work happens inside fn.

Why. Row-level security enforces isolation in the database; the filters are defence in depth (ADR-0009).

Example.

export const listTodos = Effect.fn("todo.list")(function* (
  db: Database,
  organizationId: string,
  input: TodoListInput,
) {
  return yield* query(() => db.select().from(todo).where(eq(todo.organizationId, organizationId)));
});

Anti-pattern. Opening a pool with createDb in a feature. Returning the handle from asSystem. Network I/O inside withTenant.

Enforcement. [lint] the pool-import restriction and check-system-call-sites.mjs · [test] RLS isolation, catalog and matrix suites · [convention] no network I/O inside withTenant.

Sensitive procedures read the database session

Rule. Use userProcedure, orgUserProcedure (Organization data), adminProcedure or platformProcedure for procedures that create, reveal or redirect credentials, presigned URLs or standing outbound channels, change who can act for an account, administer Users, touch billing or push registration, or approve a pending agent tool call that lets a run continue (agentTools.resolve). Resolving a stored proposal (proposals.resolve) is a one-shot data write, like the manual path, and uses the request session. These four builders contain one of the two authority middlewares of platform/rpc/procedures.ts; a feature cannot declare a middleware of its own authoritative.

Why. A revoked session snapshot can remain valid for 60 seconds. A credential or channel created in that window can outlive it.

Enforcement. [test] packages/api/src/platform/rpc/session-authority.test.ts.

One module decides who acts

Rule. Who is acting, at which authority, in which Active Organization, with which Org role and on which tenant handle is the answer of the request authority, platform/rpc/request-authority.ts. It owns the request session and the database session, the comparison between them, the captured scope, the membership read with its memo and tenantDatabase. A caller asks context.authority.actor(authority) or .tenant(authority, context.db) with "request" or "database", and translates an AuthorityRefused into its own error: the procedure builders into APP_ERRORS, the tool authorization into an ORPCError (askAuthority), the files gateway into files-sdk's 401. No feature reads a session, compares one, queries member to authorize or opens a tenant handle.

Why. Three modules each worked this out before, and they had drifted: two membership queries, a database comparison only the files gateway made and an "Active Organization changed" check only the tools made (ADR-0015, amendment). A rule about revocation or about the Active Organization now has one place to change and one suite to prove it.

Example. const tenant = await askAuthority(() => context.authority.tenant("database", context.db)) in the tool authorization; orgUserProcedure for a procedure that mints a presigned URL.

Anti-pattern. tenantDatabase(context.systemDb, { userId, organizationId }) in a feature. getAuthorizedSession(...) followed by a hand-written comparison. A second query on member to decide access.

Enforcement. [lint] tenantDatabase may be value-imported only under packages/api/src/platform/rpc/ (oxlint.config.ts) · [test] packages/api/src/platform/rpc/request-authority.test.ts (Better Auth sessions and Postgres), session-authority.test.ts, session-revocation.test.ts.

Org roles are checked only where a product rule needs them

Rule. Membership in the Active Organization is the default authorization for Organization data (orgProcedure). When a product rule limits an operation to some Org roles, chain requireOrgRole from platform/rpc/require-org-role.ts after orgProcedure. Do not compare role strings inside a service.

Why. orgProcedure already reads the Member's role in its membership statement, so the check costs no extra round trip, and a missing or unknown role fails closed with FORBIDDEN. Row-level security checks membership, not roles, so the role check belongs in the procedure (ADR-0009).

Example.

remove: todoProcedure
  .use(requireOrgRole("owner", "admin"))
  .input(z.object({ id: z.number() }))
  .handler(({ db, organizationId }, input) => deleteTodo(db, organizationId, input.id)),

Roles are not hierarchical: requireOrgRole("admin") refuses an owner, so list every role that may act. Chain it after orgProcedure, which reads the role: the middleware requires organizationRole in its input context, so protectedProcedure.use(requireOrgRole(...)) is a type error. The middleware exists and is tested (owner, admin and admin,member pass; member and unknown roles are refused), but no procedure applies it yet: today every Member may do everything in their Organization.

Prefer a permission over a role list: requirePermission({ feedback: ["triage"] }) from platform/rpc/require-permission.ts also honours the Organization's Custom roles, reads them through context.db under RLS and decides with the same access control as Better Auth. On a platform screen use platformProcedure({ analytics: ["read"] }) from platform/rpc/procedures.ts, which re-reads the database session. A procedure that returns another Member's sensitive data chains sensitiveDataRead({ category, subject }) from platform/rpc/sensitive-data.ts: permission, current Consent and a sensitive_data.viewed Audit Event in one transaction. See Roles and permissions and ADR-0016.

Anti-pattern. Reading member.role again in a service, comparing role names instead of checking a permission, or treating the platform role (user/admin/support/analyst) as an Org role.

Enforcement. [test] platform/rpc/require-org-role.test.ts, features/access/access.procedures.test.ts, features/consent/consent.procedures.test.ts · [convention] where it is applied.

Domain failures are tagged errors, mapped once

Rule. A failure a caller can act on is a Schema.TaggedError in <f>.errors.ts. The feature exports one mapper, a switch on _tag ending in satisfies never, that turns each failure into an ORPCError with an APP_ERRORS code. Services never import @orpc/*.

Why. The failures of an operation become a closed type, the mapper is exhaustive by construction, and the client keeps seeing the stable codes it localizes (error handling).

Example.

// abridged from packages/api/src/features/documents/documents.errors.ts
export class DocumentNotFound extends Schema.TaggedError<DocumentNotFound>()(
  "DocumentNotFound",
  {},
) {}
export type DocumentError = DocumentNotFound | DocumentSourceChanged;

export function documentRpcError(error: DocumentError) {
  switch (error._tag) {
    case "DocumentNotFound":
      return new ORPCError("NOT_FOUND");
    case "DocumentSourceChanged":
      return new ORPCError("CONFLICT", { message: "The original document changed" });
    default:
      return error satisfies never;
  }
}

Keep the code and message the client saw before a migration. documents.errors.ts repeats the messages the service used to throw; todo.errors.ts passes APP_ERRORS.NOT_FOUND.message, because the handler used to throw errors.NOT_FOUND(). A switch over a union with one member ends in return error._tag satisfies never.

Anti-pattern. throw new ORPCError("CONFLICT") inside a service. A string error. A new code that is missing from a locale.

Enforcement. [type] the exhaustive mapper · [lint] D2 in oxlint.config.ts: no @orpc/* in the services, rules and policies of any feature, nor in the split service modules listed in serviceTopics · [test] characterization tests in packages/api/src/testing/characterization/, locale tests.

A procedure runs one program

Rule. A feature builds its procedures with one effectProcedure(orgProcedure, <feature>RpcError) from platform/rpc/effect-procedure.ts. Each handler returns the service program; the builder's handler is the only place that runs it with the feature mapper, the request signal, the request ID and the request's tracing. The call's span, rpc.<path>, is opened before that by the head of every procedure chain; a handler or a service never opens one for the call itself. There are two tiers (ADR-0010, amendment):

  • Tier 1 (every feature). The service is a Promise that throws the feature's tagged errors. The feature passes its guard as the builder's third argument, effectProcedure(orgProcedure, importRpcError, isImportError), and the builder runs the Promise through runService: a recognised rejection is mapped once, anything else is rethrown as a defect (500). imports, proposals, notifications, flags, tenancy, assistant, uploads, admin, audit, agent-tools and the billing procedures are Tier 1. The builder requires a signed-in chain. The public handlers appConfig.get and healthCheck are listed individually in scripts/feature-boundaries.test.mjs.
  • Tier 2 (when the program composes). The service is an Effect.fn because it needs a timeout, idempotentRead, Effect.all, a race against the caller's abort or interruption that drains a transaction. The handler returns the Effect and the builder runs it through runProcedure; the program's error type must fit the mapper's union, or tsc fails. todo, documents, diagnostics and the billing reconciliation are Tier 2. Promotion is local: return an Effect instead of a Promise; the errors file and the procedures do not change.

A handler may be async to read configuration before calling the service; what it returns is still the one program. The signal is honoured only before the program starts: an already aborted request is refused, but once the program runs, a client that goes away does not interrupt it, so the write and its Audit Event commit and the response goes unread. A service is an Effect.fn that receives db, organizationId and, when it reaches the bucket, the request's storage or direct handle as arguments; it never builds a dependency itself or as a default parameter. Database work uses query and transaction from platform/effect/db.ts. Both drain: if the program itself is interrupted (a timeout or deadline inside it), the statement or transaction settles before the program ends. query(run) hands run that interruption signal, not the client's, which a service may pass to an external read (the documents pilot passes it to the storage HEAD).

Why. There is one place where typed failures become transport errors, where cancellation is handled and where request capabilities are threaded, instead of one copy per handler. An audited procedure runs inside the transaction withAudit opens around the handler, so a handler that rejected because the client left would roll back the write and its audit; finishing the started program prevents that (todo.abort.test.ts, documents.abort.test.ts). A running transaction is drained instead of abandoned (ADR-0010, ADR-0005).

Example.

const documentsProcedure = effectProcedure(orgProcedure, documentRpcError);

export const documentsRouter = {
  source: documentsProcedure
    .input(documentIdentityInput)
    .handler(({ db, organizationId }, input) => documentSource(db, organizationId, input.fileId)),
  confirmText: documentsProcedure
    .input(documentIdentityInput)
    .handler(({ db, organizationId, storage }, input) =>
      confirmDocumentText(db, organizationId, input.fileId, storage),
    ),
};

The handler's context is the chain's context as oRPC narrowed it: after orgProcedure, organizationId is a string and session is non-null, so there is no !. userId and signal are spelled out next to it.

Anti-pattern.

  • context.organizationId!, or a hand-written runProcedure(..., { signal, requestId }) in a handler.
  • createStorage() or createDirectStorage() inside a service or as a default parameter.
  • Effect.tryPromise around db.transaction only to catchTag one failure into a result; a Promise with try/catch says the same with less (Tier 1).
  • Effect.runPromise inside a service, or a Promise facade called from inside another program (two runtimes per call).
  • A second run* in the same call.
  • A Layer, Context.Service or ManagedRuntime that holds a pool, whether at module scope or per request.
  • Handling interruption by hand.

Enforcement. [type] the program's error type against the mapper (Tier 2) · [test] platform/rpc/procedure-edge.test.ts (runProcedure, runService) and platform/effect/db.test.ts · [lint] D8 keeps queries out of migrated procedures · [convention] one program per handler, no Layer or runtime; grep "Effect.runPromise(" outside platform/effect and platform/rpc/procedure-edge.ts is empty.

The Context carries capabilities, not options

Rule. Context (platform/rpc/context.ts) is what every procedure, tool and gateway may count on: db, systemDb, session, authority, ip, userAgent, requestOrigin, requestId, storage and direct are always present. Only createContext, createMcpContext and the test adapter src/testing/make-context.ts assemble one. A capability is optional only when a real request can lack it, and the type says when: tracing and waitUntil (outside workerd), adminApi (MCP-originated contexts) and organizationId/organizationRole (before orgProcedure).

Why. A fallback such as context.systemDb ?? context.db or authority?.actor(...) is a second code path that only tests exercised, and a throw INTERNAL_SERVER_ERROR for a missing capability is a runtime check of what the type should have said. Storage built once per request shares the request's abort signal and is handed down like db (ADR-0010, amendment).

Example. A test context is makeContext({ db, user, organizationId, storage: memoryStorage().files }); a tool scope is a spread of the Context with db and organizationId replaced.

Anti-pattern. A test that writes { db, session } and calls it a Context. A vi.mock("@fofo/storage") where makeContext({ storage }) or openStorage in the job options would do.

Enforcement. [type] the Context type · [convention] one factory per entry point.

The entry forwards the request facts

Rule. The request id and the client address are derived once, by the Worker entry (apps/web/src/server.ts), with deriveRequestFacts from @fofo/auth/request-runtime, and handed to the request through runWithRequestRuntime. A handler asks requestFacts(request), or reads context.requestId and context.ip, which createContext and createMcpContext fill from it. No handler reads cf-ray or cf-connecting-ip, and no handler passes an address along by hand: a request built in-process on behalf of the one being served (the MCP JWKS read) gets the same facts.

Why. Seven modules each worked out the id or the address before, and two of them (the Web Vitals limiter and the error reporter's tag) did it differently from the rest. One module that derives and one entry that forwards is also the seam a second Worker needs: behind a service binding the facts arrive from the first Worker, and only the entry changes.

Example. const key = requestFacts(request).clientIp ?? "unknown" in the Web Vitals limiter; tagRequest(facts.requestId) in the entry, so an unhandled error carries the id of the x-request-id header.

Anti-pattern. request.headers.get("cf-connecting-ip") in a handler. A function that takes trustedClientIp as an option so a caller can forward it.

Enforcement. [test] scripts/request-facts.test.mjs: only request-runtime.ts reads the two headers, and only the entry calls deriveRequestFacts · [test] packages/auth/src/request-runtime.test.ts.

Authentication has one composition root

Rule. packages/auth/src/index.ts is the one module that opens the request's database pool and builds its Better Auth instance. It exports createRequestScope and nothing else: createRequestScopes((request, waitUntil) => ({ db: createDb(), auth: createAuth(…), waitUntil })). The modules below it each have one job and never import it: auth-options.ts (the Better Auth configuration), auth-hooks.ts (its lifecycle and endpoint hooks), auth-effects.ts (what a write causes outside its rows, registered on the unit of work), auth-handler.ts (createAuth, the instance and its transactional handler), request-scope.ts (one scope per request, for whatever function opens it) and request-runtime.ts (what the Worker entry hands a request). A type or a function of one of them is imported from that module (@fofo/auth/auth-handler, /request-scope, …), never from the root.

Why. The root used to be one 830-line module that was options, hooks, handler and scope factory at once, and it installed its factory into request-scope.ts as a side effect of being imported (bindRequestScopeCreate). createRequestScope then threw "request scope factory is not bound" unless some other import had happened first, a test bound a stub into state every later test in the file shared, and import type { createAuth } from the root named a module whose import validates the server env. With an explicit factory the interface says what it needs, a test builds its own scopes, and a second entry point (another Worker, a job) composes its own root from the same modules.

Example. A test that needs a scope: const createRequestScope = createRequestScopes(() => ({ db, auth })). The admin API takes import type { createAuth } from "@fofo/auth/auth-handler".

Anti-pattern. A re-export from packages/auth/src/index.ts. A let in request-scope.ts that an import or a bind… function fills. A hook in auth-hooks.ts that calls sendEmail or deletes an object directly instead of going through AuthEffects.

Enforcement. [test] scripts/auth-composition-root.test.mjs: the root exports only createRequestScope, no module of the package imports it, and request-scope.ts keeps no module-level state · [lint] createDb is importable only by the root (oxlint.config.ts) and @fofo/auth/auth-handler is refused in client code (packages/config/oxlint-client-boundary.mts) · [test] packages/auth/src/request-scope.test.ts.

What follows a write waits for COMMIT

Rule. A write that has something to do afterwards (move its Audit Event to history, delete storage objects, send an email) runs in a unit of work: committed(db, async (tx, unit) => …, { system, waitUntil }) from @fofo/db/committed. Inside, unit.audit(entry) writes the Audit Event with the change and unit.afterCommit({ name, run, background }) registers the rest. The module runs each registered effect once after COMMIT, in order, and never for a unit that rolled back or was aborted (unit.abort(reason)); an effect that fails is reported and cannot fail the unit, which is already durable. A unit opened on the transaction of another unit is a savepoint of it and its effects wait for the outer COMMIT. An audited tenant unit supplies the connection-role handle as system. The unit validates this handle before COMMIT. One Audit Event outside a transaction is recordAudit(db, entry, { system, waitUntil }), which joins an open unit when db belongs to one.

A caught PostgreSQL statement error can leave the transaction aborted. PostgreSQL then replies to COMMIT with a ROLLBACK command tag. Drizzle's node-postgres adapter discards that reply, so this repo patches the pinned version (patches/drizzle-orm@1.0.0-rc.6.patch) to read it and reject before the unit runs its effects. A Drizzle bump must carry the patch over or show that upstream now checks the reply (dependency upgrades); committed.test.ts covers it on real PostgreSQL. PostgreSQL COMMIT

Why. This protocol was written by hand at nine sites (the Better Auth handler, the admin API, withAudit, the sensitive-data guard, both tool approval paths and four billing sites), each with its own array of audit ids and its own flush, and they had drifted: the admin path deleted a removed User's images through another storage handle, dropped the failure count, and would have sent a notification email before its transaction committed. Every new deferred effect had to be added to each copy.

Example. withAudit is committed(context.db, async (tx, unit) => { const result = await next({ context: { db: tx } }); await unit.audit({ … }); return result; }, { system: context.systemDb, waitUntil: context.waitUntil }). Better Auth's hooks receive the unit of their request (or of the admin write) and call unit.audit and unit.afterCommit.

Anti-pattern. db.transaction(…) that returns audit ids for the caller to flush. finishQueuedAudits in a feature. An email or a storage delete inside a transaction callback. A callback option such as onAuditQueued to let a caller defer an effect.

Enforcement. [test] packages/db/src/committed.test.ts (Postgres: rolled back → nothing, committed → each effect once, nesting, failure policy), packages/auth/src/unit-of-work.test.ts, packages/auth/src/user-objects.test.ts · [convention] new deferred effects are registered on the unit.

External I/O has a deadline; only reads retry

Rule. A service that calls storage or a provider sets a timeout. It retries only idempotent reads, with idempotentRead. A PUT, a provider POST, a webhook delivery or an email send makes one attempt. An outbound HTTP call goes through the outbound call module, outboundCallEffect in @fofo/http/outbound (or its Promise facade outboundCall): it sets the deadline, never follows a redirect (redirect: "manual", a 3xx is a failure that is not retried), reads the answer within a size bound and classifies the failure. No other Worker-side code calls fetch. A stream is read with readBounded, boundedChunks or readBoundedJson from @fofo/http/read-bounded; no other code takes a stream reader.

Why. A repeated write can duplicate a side effect. The outbox and lease policy decides when to try again. A followed redirect could carry a provider key or a signed payload to another host, past the webhook SSRF check. The Fetch standard's "error" mode is not an option: workerd does not implement it and throws a TypeError when the request is built, before anything is sent (Cloudflare: Request), so code using it passes its tests on Node and fails on the deployed Worker. That fix had to be made in six files, and two call sites that never named a redirect mode passed a scan that looked for the wrong value. With one module the next runtime quirk is fixed once, and a new call site cannot forget the deadline, the redirect mode or the bound, because it never states them.

Example. providerRequestEffect (Stripe, Polar, Pagar.me), verifyRevenueCatEffect, the Expo push request, webhookAttempt (its SSRF check runs first, at the site), the Resend and Cloudflare REST email providers, the error tunnel's forward, the Cloudflare analytics read, the GitHub issue POST and the S3 control requests each call the module and keep only their domain mapping: what a refusal, a redirect or an unreadable answer means for a payment, an email or a delivery. idempotentRead wraps the RevenueCat subscriber GET, Expo getReceipts and the import source reads at the call site, with the deadline of the whole read; OutboundFailure already has the retryable and retryAfterMs the schedule reads. The storage HEAD that confirms Document Text (documents.service.ts) has a 10 s timeout, retries: 0 and the program's abort signal, and runs before any lock or transaction; the documents pilot kept that behavior instead of adding a retry. The signed PUT the browser performs is never retried by the server. readStoredObject (packages/api/src/platform/storage/stored-object.ts) is the storage variant of the bounded read: the object's bytes if it still is the version its row names and fits the feature's cap.

Anti-pattern. Effect.retry around a POST. A fetch( in a feature, a transport or another package: its deadline, redirect mode and body bound are then that file's to remember. A provider answer read with response.json() or response.arrayBuffer(), which have no size bound. A hand-written getReader() loop. A transport test that asserts redirect: "manual" or a timeout again; those cases live once, in packages/http/src/outbound.test.ts, and a transport test asserts its domain mapping with a fake fetch.

Enforcement. [test] scripts/outbound-http.test.mjs: on the Worker (the server-capable packages and the Worker-side files of apps/web/src: *.server.*, routes/api/, server.ts) only packages/http/src/outbound.ts calls fetch, and in everything we ship only packages/http/src/read-bounded.ts takes a stream reader (two browser readers are listed with their reason) · [test] packages/http/src/outbound.test.ts and read-bounded.test.ts for the behavior · [test] retry tests with TestClock · [convention] one attempt for a write.

Configuration is declared once

Rule. Every environment variable is declared in packages/env and read through it, including runtime switches such as DB_TENANT_PIPELINE and TRUSTED_PROXIES.

Why. The schema is the list of what the deploy must provide. A missing or malformed server secret fails validation when the server environment loads. The runtime switches in @fofo/env/runtime-flags are read on every call instead: an invalid value never becomes a different setting, but falls back to the safe behavior and is logged once per isolate (runtime switches).

A feature that validates its own group of variables takes the env record by its own names: parseBillingSettings(env) reads env.STRIPE_SECRET_KEY, the way readErrorReportingEnv(runtimeEnv) does. A new variable is then two edits, its declaration in packages/env and its use in the parser, and the parser's tests read like the env file.

Anti-pattern. process.env.SOMETHING in a feature. An input type that renames every variable (STRIPE_SECRET_KEY to stripeSecretKey) between the env and the parser: it is a third place to edit and it validates nothing.

Enforcement. [lint] node/no-process-env for packages/** in oxlint.config.ts and for apps/web/src in its nested config. NODE_ENV and EXPO_OS are allowed because bundlers replace them. Named exceptions: packages/env/**, tests and packages/api/src/testing/**, CLIs (packages/*/scripts/**, project-setup-cli, db/src/seed.ts) and the test-only provider switch in assistant.provider.ts. Runtime switches go through @fofo/env/runtime-flags, which reads them on every call.

Logs separate expected from unexpected

Rule. An expected failure (a mapped 4xx) is not logged as an error; the server error handler writes it at debug level. An unexpected failure (a defect, a 500) is logged once by the server error handler, with the request ID that the response also returns in x-request-id. Logs carry identifiers, never credentials, prompts or private payloads.

Why. Error logs then mean something needs attention, and a user can quote one ID that leads to the log line.

Anti-pattern. console.error in a service for a NOT_FOUND.

Enforcement. [test] the server error handler tests · [convention] for payload content.

Lists page one way per endpoint

Rule. Use the pagination rule in oRPC conventions. Use a cursor for lists that grow without bound. Use offset only where the interface needs a total or page numbers. Every query has a total order with an id tie-breaker.

Enforcement. [test] list tests · [convention] the choice of strategy.

No non-null assertion

Rule. packages/api/src and apps/mobile/src contain no non-null assertion (value!) outside tests. Narrow the value (const [row] = rows; if (!row) throw new TodoNotFound();), let the type say it (a tuple with a rest for a list an external schema guarantees is not empty, a function that returns the narrowed value), or use firstRow(rows) for a statement that always returns a row (INSERT … RETURNING, an aggregate). No as cast in its place.

Why. ! tells the compiler that a value exists and checks nothing. When it does not exist, the failure is a TypeError some lines later, far from its cause, and under noUncheckedIndexedAccess every rows[0]! is such a promise. In the native app the React Compiler memoizes a closure that contains x!.id and reads it while x is still null. A descendant project wrote context.organizationId! 178 times before effectProcedure gave handlers a narrowed context.

Example. billing.web-http.ts: receive(request, "stripe", deps) returns the provider's settings as NonNullable<BillingSettings["stripe"]>, because it already answered 404 for a provider that is not configured. feedback.images.ts reads header fields through a DataView, which returns a number where an indexed byte is number | undefined.

Anti-pattern. return row!; after an insert; settings.stripe! after a check in another function; bytes[offset]! << 8; value as NonNullable<typeof value>.

Enforcement. [lint] typescript/no-non-null-assertion as an error in oxlint.config.ts (packages/api/src/**) and apps/mobile/src/oxlint.config.mts; *.test.ts is exempt.

Files stay short

Rule. At most 400 lines of code in a file under packages/*/src (blank lines and comments not counted). Tests and testing/** are exempt. packages/ui/src is not covered: its components are vendored from shadcn, ReUI and Bklit and keep upstream's layout. A feature that outgrows a file splits by topic, <feature>.<topic>.ts, in the same folder (ADR-0011): todo.service.ts keeps the list, the stats and the single-todo writes, todo.board.ts has the lanes read and the card move, todo.calendar.ts the window read.

Why. A service past 400 lines is usually several topics that share a few helpers. Split by topic, each file can be read whole, and a change to the board does not scroll past the calendar. The web and mobile trees have had the rule (at 250) since ADR-0012; without one here the largest files of the repository were all in the backend.

Anti-pattern. Splitting by layer instead of topic (todo.queries.ts, todo.mutations.ts), or moving helpers into a utils file to get under the number.

Enforcement. [lint] max-lines as an error for packages/*/src in oxlint.config.ts. The files that were over the limit on 2026-11-28 and still are (seven of the eight) are exempt there and recorded with their size in packages/config/max-lines-baseline.json. [test] scripts/max-lines.test.mjs keeps that baseline shrinking: it fails when a listed file grows, when a listed file is under the limit again (remove it from both lists), when a new file joins, or when the lint exemptions and the baseline differ.

Key files

Database rate limits

Use consumeRateLimit from packages/api/src/platform/rate-limit.ts when a feature needs a shared database counter. The module owns the atomic upsert on Better Auth's rate_limit table and calculates the retry delay. The caller supplies its key, maximum and window, keeps its existing asSystem authorization, and decides how to handle denial or database failure. MCP, the assistant, feedback, analytics and error-envelope ingest all use this interface.

The counter rolls from the last accepted request. A blocked request leaves the stored timestamp in place. The platform suite checks that behavior, exact concurrent counting and the single-statement accepted path against PostgreSQL.

Keyed collection writes

COLLECTION_WRITES lists the procedures a client may queue. For each listed procedure, declare .input(), .use(withAudit()), and .output() in that order. Compose the handler's program with exactlyOnce on the audited database handle. The receipt contains only the write identity. An invalid output rolls back the ledger claim and domain write. Return a null audit target for a replay or a no-op.

A keyed request carries its captured scope header, expected User and Organization, and a UUIDv7 key. Keep the key and payload on a retry. The server accepts keys for six days, retains receipts for seven, and rechecks live database authority before returning a receipt. See ADR-0010 and ADR-0015.

Edit on GitHubDocumentation is in English.
Cookie settings
We use essential cookies to make our app work. With your consent, we also use optional cookies to improve your experience.

Read our Cookie Policy and Privacy Policy.