Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Revise agent and API documentation for clarity and structure

Lewis Carhartd4adafa0e9c1
diff --git a/AGENTS.md b/AGENTS.md
index 9d102bf6..3eb88c93 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,36 +1,41 @@
-# Strict rules - Always review before starting any work
-
-You should always check and see if there are any relevant skill files you should review before starting a task e.g. if you're working on better-auth, always review the better auth best practice skill - if you're working on prisma, review your prisma-database-setup skill.
-
-Please check below, if you're working on anything related review the rules and let the user know you've read them:
-
-## Code Comments
-Do not add code comments to the code you write, ever.
-
-## Design
-Read @docs/design.md
-
-## API:
-Read @docs/api.md
-
-## The research agent (`apps/agent`):
-Read @docs/agent.md
-
-Every piece of intelligence in this repo lives there, not in the API. The
-complete eve documentation ships in `apps/agent/node_modules/eve/docs` and
-matches the installed version — read the relevant guide before writing eve code
-rather than working from memory of the API.
-
-ABSOLUTELY, no coauthoring commits.
-
-## Environment / configuration:
-Read @docs/environment.md
-
-There is **one `.env`, at the root of the repo**, and `.env.example` is its
-documentation. If you add a variable, add it to `.env.example` with a note on
-what it does — and if the API reads it, declare it in
-`apps/api/src/config/env.validation.ts` too. Never add a per-package `.env`.
-
-Anything a self-hoster might not have is optional, and the code must work
-without it: a missing key removes a capability, it never throws. See
-`apps/agent/agent/lib/capabilities.ts` for the pattern.
+# Strict rules — review before starting any work
+
+**Read the doc for the area you are touching before you touch it.** The table
+below is the whole index. These are plain paths, not imports: they are not in your
+context until you read them, and the rules in them are not optional.
+
+| Working on | Read first |
+| --- | --- |
+| Anything in `apps/api` — tRPC, auth, logging, sync, currency, deletes, caching | `docs/api.md` |
+| `apps/agent` — the eve research agent, tools, tasks, the Agent panel | `docs/agent.md` |
+| `.env`, configuration, deployment, Google/Gmail setup, secrets | `docs/environment.md` |
+| UI in `apps/app` or `packages/ui` | `docs/design.md` (below) |
+
+Also check `.agents/skills/` for a relevant skill before starting — better-auth,
+prisma, nestjs-trpc, eve, shadcn, nuqs and others have one. Tell the user which
+rules and skills you read.
+
+## Always true
+
+- **Never add code comments.** Not to new code, not to code you edit.
+- **No coauthoring commits.** No `Co-Authored-By` trailer, ever.
+- **Intelligence lives in `apps/agent`, never in the API.** No vendor client, no
+ enrichment, no scoring, no identity matching in Nest — it writes an `AgentTask`
+ row and lets the agent decide. See `docs/api.md`.
+- **One `.env`, at the repo root.** `.env.example` is its documentation: add every
+ new variable there with a note on what it does, and declare it in
+ `apps/api/src/config/env.validation.ts` if the API reads it. Never add a
+ per-package `.env`.
+- **Anything a self-hoster might not have is optional and must never throw.** A
+ missing key removes a capability. `apps/agent/agent/lib/capabilities.ts` is the
+ pattern.
+- **`/packages/ui` is the single source of truth for UI.** Shared shadcn
+ components only; a new variant is implemented there, not overridden at the call
+ site.
+- **eve's own docs ship in `apps/agent/node_modules/eve/docs`** and match the
+ installed version. Read the relevant guide before writing eve code rather than
+ working from memory — guessing typechecks, builds, and then behaves differently.
+
+## Design
+
+@docs/design.md
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index 09283f3e..c47f123e 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -116,6 +116,7 @@ export class DashboardService {
amount: true,
currency: true,
baseAmount: true,
+ baseCurrency: true,
expectedCloseDate: true,
stageChangedAt: true,
company: {
@@ -187,12 +188,14 @@ export class DashboardService {
const wonPrevMonth = { count: 0, valueCents: 0 };
let wins = 0;
let losses = 0;
+ let valuedWins = 0;
let wonCents = 0;
let cycleDays = 0;
for (const deal of recentDeals) {
- const cents =
- deal.baseCurrency === base ? (toCents(deal.baseAmount) ?? 0) : 0;
+ const valued =
+ deal.baseCurrency === base ? toCents(deal.baseAmount) : null;
+ const cents = valued ?? 0;
const created = trend[monthKey(deal.createdAt) - firstBucket];
if (created) created.created += cents;
@@ -217,7 +220,10 @@ export class DashboardService {
if (closedAt < rateStart) continue;
if (won) {
wins += 1;
- wonCents += cents;
+ if (valued !== null) {
+ valuedWins += 1;
+ wonCents += cents;
+ }
cycleDays += (closedAt.getTime() - deal.createdAt.getTime()) / DAY_MS;
} else if (stage === DealStage.CLOSED_LOST) {
losses += 1;
@@ -242,7 +248,8 @@ export class DashboardService {
wins,
losses,
winRate: decided === 0 ? null : wins / decided,
- avgDealCents: wins === 0 ? null : Math.round(wonCents / wins),
+ avgDealCents:
+ valuedWins === 0 ? null : Math.round(wonCents / valuedWins),
avgCycleDays: wins === 0 ? null : Math.round(cycleDays / wins),
},
trend,
@@ -250,21 +257,24 @@ export class DashboardService {
count: closingThisMonthTotals._count._all,
valueCents: toCents(closingThisMonthTotals._sum.baseAmount) ?? 0,
},
- biggestOpen: biggestOpen.map(
- ({
- amount,
- baseAmount,
- expectedCloseDate,
- stageChangedAt,
- ...deal
- }) => ({
- ...deal,
- amountCents: toCents(amount),
- baseAmountCents: toCents(baseAmount),
- expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
- stageChangedAt: stageChangedAt.toISOString(),
- }),
- ),
+ biggestOpen: biggestOpen
+ .map(
+ ({
+ amount,
+ baseAmount,
+ baseCurrency,
+ expectedCloseDate,
+ stageChangedAt,
+ ...deal
+ }) => ({
+ ...deal,
+ amountCents: toCents(amount),
+ baseAmountCents: baseCurrency === base ? toCents(baseAmount) : null,
+ expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
+ stageChangedAt: stageChangedAt.toISOString(),
+ }),
+ )
+ .sort((a, b) => (b.baseAmountCents ?? -1) - (a.baseAmountCents ?? -1)),
overdueTasks: overdueTasks.map(({ dueAt, ...task }) => ({
...task,
dueAt: dueAt?.toISOString() ?? null,
diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.ts
index 990fb45a..69d9cb28 100644
--- a/apps/api/test/currency-totals.integration.spec.ts
+++ b/apps/api/test/currency-totals.integration.spec.ts
@@ -1,5 +1,5 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
-import { db, RateSource } from "@crm/db";
+import { DealStage, db, RateSource } from "@crm/db";
import { normalizeCurrency } from "@crm/db/currency";
import { SETTINGS_ID, writeReportingCurrency } from "@crm/db/settings";
import { ActivityStampService } from "../src/crm/activity-stamp.service";
@@ -414,3 +414,92 @@ describe("a converted figure knows which currency it is in", () => {
await rate("EUR", "1.10", RateSource.FETCHED);
});
});
+
+describe("the dashboard only values what it can convert", () => {
+ const analystId = `analyst-${suffix}`;
+
+ beforeAll(async () => {
+ await writeReportingCurrency(db, "USD");
+
+ await db.user.upsert({
+ where: { id: analystId },
+ create: {
+ id: analystId,
+ name: "Dashboard Tester",
+ email: `dashboard@${domain}`,
+ emailVerified: true,
+ },
+ update: {},
+ });
+ });
+
+ afterAll(async () => {
+ await db.deal.deleteMany({ where: { ownerId: analystId } });
+ await db.user.deleteMany({ where: { id: analystId } });
+ });
+
+ async function stale(name: string, stage: DealStage) {
+ const closed = stage === DealStage.CLOSED_WON;
+
+ return db.deal.create({
+ data: {
+ name: `${name} ${suffix}`,
+ companyId,
+ ownerId: analystId,
+ stage,
+ amount: 9_000,
+ currency: "USD",
+ baseAmount: 9_000,
+ baseCurrency: "JPY",
+ fxRate: 1,
+ fxRateAt: new Date(),
+ closedAt: closed ? new Date() : null,
+ },
+ select: { id: true },
+ });
+ }
+
+ it("does not average a won deal it cannot value into the rest", async () => {
+ const won = await deals.create({
+ name: `Valued win ${suffix}`,
+ companyId,
+ ownerId: analystId,
+ amountCents: 10_000,
+ currency: "USD",
+ stage: DealStage.CLOSED_WON,
+ });
+
+ const unvalued = await stale("Stale win", DealStage.CLOSED_WON);
+
+ const summary = await dashboard.summary(analystId, { scope: "me" });
+
+ expect(summary.performance.wins).toBe(2);
+ expect(summary.performance.avgDealCents).toBe(10_000);
+ expect(summary.unconverted.count).toBe(1);
+
+ await db.deal.deleteMany({ where: { id: { in: [won.id, unvalued.id] } } });
+ });
+
+ it("does not let a stale figure set the largest open deal", async () => {
+ const open = await deals.create({
+ name: `Valued open ${suffix}`,
+ companyId,
+ ownerId: analystId,
+ amountCents: 10_000,
+ currency: "USD",
+ });
+
+ const unvalued = await stale("Stale open", DealStage.DEMO_BOOKED);
+
+ const summary = await dashboard.summary(analystId, { scope: "me" });
+
+ expect(summary.biggestOpen[0]?.id).toBe(open.id);
+ expect(summary.biggestOpen[0]?.baseAmountCents).toBe(10_000);
+ expect(
+ summary.biggestOpen.find((deal) => deal.id === unvalued.id)
+ ?.baseAmountCents,
+ ).toBeNull();
+
+ await db.deal.deleteMany({ where: { id: { in: [open.id, unvalued.id] } } });
+ });
+});
diff --git a/apps/app/app/(app)/[slug]/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsx
index a40ad2fd..7881c8dd 100644
--- a/apps/app/app/(app)/[slug]/deals/deals-table.tsx
+++ b/apps/app/app/(app)/[slug]/deals/deals-table.tsx
@@ -161,6 +161,8 @@ export function DealsTable() {
const openValueCents = deals.data?.openValueCents;
const reportingCurrency = deals.data?.reportingCurrency;
const unconverted = deals.data?.unconverted;
+ const uncounted = unconverted?.count ?? 0;
+ const openPipelineCents = openValueCents ?? (uncounted > 0 ? 0 : null);
return (
<DataTable
@@ -185,11 +187,11 @@ export function DealsTable() {
onRowClick={(row) => openRecord({ kind: "deal", id: row.id })}
empty="No deals match this view."
meta={
- openValueCents === null || openValueCents === undefined ? undefined : (
+ openPipelineCents === null ? undefined : (
<span>
{deals.data?.total ?? 0} deals ·{" "}
<span className="tabular-nums">
- {formatMoney(openValueCents, reportingCurrency)}
+ {formatMoney(openPipelineCents, reportingCurrency)}
</span>{" "}
open pipeline
{unconverted && unconverted.count > 0 ? (
diff --git a/docs/agent.md b/docs/agent.md
index 907e5132..7f0536a9 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -1,884 +1,320 @@
-# Agent — Rules for working on `apps/agent`
+# Agent — `apps/agent`
-The research agent works out who the people in the CRM are. It is an
-[eve](https://eve.dev/docs) app, it is **its own deployment**, and it owns every
-piece of intelligence in this repo.
+An [eve](https://eve.dev/docs) app, its **own deployment**, owning every piece of
+intelligence in this repo. Read with `api.md`, whose first rule is that none of this
+may move into the API.
-Read this with [`api.md`](./api.md) — whose first rule is that none of this may
-move into the API — and
-[`plan/contact-intelligence-agent.md`](./plan/contact-intelligence-agent.md),
-which is why it is shaped this way.
+**Read the eve guide before writing eve code** —
+`apps/agent/node_modules/eve/docs/README.md` matches the installed version;
+`.agents/skills/eve` is the skill. Guessing typechecks, builds, then misbehaves.
-## The framework is the source of truth
+## Model
-The complete eve documentation ships inside the package, matching the installed
-version exactly:
+Default `zai/glm-5.2-fast`; `DEFAULT_AGENT_MODEL` in `@crm/db/settings` because the
+agent and the API both need it.
-```
-apps/agent/node_modules/eve/docs/README.md
-```
-
-Read the relevant guide there before writing eve code and then check your eve skill knowledge-base shipped in .agents/skills/eve. Guessing at this API is expensive in a specific way: it typechecks, builds, and then behaves differently
-from what you assumed — see the note on principal mapping under [the
-bridge](#the-bridge).
-
-## The model is a setting, not a deploy
-
-The agent runs on **`zai/glm-5.2-fast`** by default, and a rep can change that
-on the settings page without touching the code.
-
-`DEFAULT_AGENT_MODEL` lives in [`@crm/db/settings`](../packages/db/src/settings.ts)
-because two processes need the same answer — the agent, to compile its
-fallback, and the API, to tell the settings page what "Default" resolves to.
-A second copy of that string is a second answer to the question.
-
-- **The choice is a row, not an env var.** `AppSetting` holds one record, and
- `agent.ts` resolves it through `defineDynamic` on `session.started` — so a
- change applies to the next session rather than the next deployment, which
- matters in an install whose owner cannot redeploy. A conversation already
- open finishes on the model it started with, and that is deliberate: prompt
- caches are per model, so switching part-way re-ingests the thread at uncached
- prices.
-- **The window travels with the id.** eve never inherits
- `modelContextWindowTokens` from the fallback, so `lib/model.ts` always sends
- it. A model with a smaller window than the default would otherwise be
- compacted against a number it does not have, and the turn fails at the
- provider after the context has been assembled and paid for.
-- **A failed read degrades, it does not throw.** No row, no database, a
- resolver that raises — all of them leave the compiled fallback in force.
- `lib/model.ts` logs the reason, because the alternative is a session quietly
- running on a model nobody chose.
-- **The chooser only offers models this agent can run.** Every read the agent
- has is a tool, so `ModelCatalogService` filters the gateway catalog to
- language models tagged `tool-use`. An unreachable gateway makes the chooser
- read-only rather than failing the page, and the id already stored keeps
- running.
-- **Not a frontier model, on purpose.** The hard part of this job is refusing a
- plausible-looking wrong answer, and that is enforced by the tools and the
- evidence model below rather than by model strength. What the job does want is
- a long window — a company preamble hands over every contact on the account —
- and answers fast enough that the sheet's Agent tab reads as a conversation.
+- **A row (`AppSetting`), not an env var**, via `defineDynamic` on `session.started`.
+ Open conversations keep their model — prompt caches are per model.
+- **`lib/model.ts` always sends `modelContextWindowTokens`**; eve never inherits it.
+- **A failed read logs and keeps the compiled fallback.** Never throws.
+- **The chooser offers only `tool-use` models** (`ModelCatalogService`); an
+ unreachable gateway makes it read-only.
+- **Not a frontier model, deliberately** — refusing wrong answers is enforced by the
+ tools and evidence model, not model strength.
## Pictures are copied, never linked
-A logo and a profile photograph both arrive as somebody else's URL, and neither
-may be stored as one. LinkedIn signs its CDN URLs with an expiry roughly three
-weeks out; a brand's own CDN is fine until it is a rate limit on a page drawing
-forty logos. Either way the failure is the same and it is the worst shape a
-failure can take here — a picture that works today and is a broken image next
-month, with nothing to connect the two.
-
-So `mirror()` copies the bytes into Vercel Blob and the record points at our
-copy.
-
-**It lives in [`@crm/db/blob`](../packages/db/src/blob.ts), not in the agent.**
-It started here, on the reasoning that whoever writes the URL onto the record
-should own fetching the bytes — which is still right, and is exactly why it had
-to move once more than one thing wrote one. There are four writers now, in three
-processes:
-
-| Writer | What it copies |
-| --- | --- |
-| `lib/brand-images.ts` (agent) | The four artwork columns on a company |
-| `lib/portrait.ts` (agent) | A contact's photograph |
-| `FaviconService` (API) | The icon a domain's own site serves |
-| `ImageMirrorService` (API) | Anything on an existing row still pointing off-site, including a signed-in user's Google avatar |
-
-`packages/db/prisma/seed.ts` is the fifth, and it matters more than it sounds:
-demo rows outlive their sources, and a clone seeded today is still open in six
-months.
-
-- **The key carries a hash of the bytes.** That is what makes re-running both
- idempotent and correct: unchanged artwork lands on the same URL and the record
- does not move, while a brand that redesigns its mark gets a *new* URL rather
- than the same one behind a month of CDN cache.
-- **One list of the columns that hold a picture**, `COMPANY_IMAGE_FIELDS` in
- [`@crm/db/images`](../packages/db/src/images.ts). Four things read it and a
- column missing from one of them is a picture that is never brought in-house,
- with nothing anywhere to say so.
-- **It fetches through `@crm/db/safe-fetch`**, which is the favicon resolver's
- own guard, exported rather than copied. The URL came from a vendor's answer
- about a domain a rep typed, so a logo link pointing at `169.254.169.254` is a
- request forgery from inside our network. One copy of that rule, several
- callers.
-- **No `BLOB_READ_WRITE_TOKEN` means no photographs**, and everything else keeps
- the origin's URL. The distinction is deliberate: a face comes from a signed
- CDN link that expires, so storing one would promise a picture that breaks in
- three weeks, while a logo or a favicon merely stays somebody else's to serve.
- It is an optional capability like every other, and it is in
- `lib/capabilities.ts` so the agent is told before it plans.
-- **A mirrored URL is what lets the browser optimize it.** `isOptimizable` in
- `@crm/db/images` is the whole of that decision and both halves are load
- bearing: `next.config.ts` allow-lists our Blob host and nothing else, because
- a wildcard would make the deployment an open image proxy — and a mirrored
- *SVG* is still refused, because Blob's separate origin is the only reason we
- store SVG at all, and `/_next/image` would re-serve those bytes from ours.
- Everything that fails the check renders as the plain `<img>` it always was.
-- **Faces are not optimized, and that is not an oversight.** `EntityLogo` uses
- `<Image>`; `AvatarImage` deliberately does not. Radix establishes an avatar's
- load state by probing the URL with its own `new window.Image()`, so an
- optimized child would request a second, different URL — two fetches per face
- on a table drawing forty. There is nothing to win for the second one either:
- every photograph we store arrives pre-thumbnailed by its source
- (`shrink_100_100`, `=s96-c`), while brand artwork arrives at whatever size the
- brand publishes.
-- **A photograph is only ever taken from a source already tied to this person.**
- `lib/portrait.ts` holds the write and `lib/portrait-sources.ts` holds the
- chain, in order of certainty: their LinkedIn profile, their GitHub account,
- their employer's own team page. Every one is keyed on an identifier already on
- the record, so each asks *what does this account look like* rather than *who
- is this name*.
-- **There is no image search by name, and there must never be.** It is the
- obvious fourth step and the one that breaks everything else. A search for
- "Paula Marchetti" returned Brightwater's CEO, an HR lead at Reply and a data
- engineer in Seattle, all confidently — and those were names, which a rep can
- read and smell. Nobody audits a face. Guess where to look, never what you will
- find: a team page is a guess about a URL, and the name printed beside the
- photograph is the answer.
-- **`get_linkedin_profile` stores the picture itself** the moment it computes
- `isSamePerson`, in code, rather than asking the model to remember a follow-up
- call.
-
-### Two lanes: what a rep sees, and what a rep asks for
-
-`schedules/dispatch.ts` drains the queue in **two independent lanes**, and which
-lane a row lands in is decided by one list — `DIRECT_KINDS` in
-[`@crm/db/agent-tasks`](../packages/db/src/agent-tasks.ts).
-
-| | Kinds | How it runs | Per tick |
+`mirror()` copies bytes to Vercel Blob; the record points at our copy. Lives in
+**`@crm/db/blob`** — writers are `lib/brand-images.ts`, `lib/portrait.ts`,
+`FaviconService`, `ImageMirrorService`, `prisma/seed.ts`.
+
+- **The key hashes the bytes** — idempotent, and a redesigned mark gets a new URL.
+- **`COMPANY_IMAGE_FIELDS` (`@crm/db/images`) is the one list of picture columns.**
+- **Fetch through `@crm/db/safe-fetch`** — vendor URLs are SSRF vectors.
+- **No `BLOB_READ_WRITE_TOKEN` means no photographs**; logos keep the origin URL.
+- **`isOptimizable` (`@crm/db/images`) is the whole rule**: `next.config.ts`
+ allow-lists only our Blob host (a wildcard makes us an open image proxy), and a
+ mirrored **SVG is still refused**.
+- **Faces are not optimized** — `AvatarImage` skips `<Image>` because Radix probes
+ the URL itself, doubling fetches.
+- **A photograph only comes from a source already tied to this person** —
+ `lib/portrait-sources.ts`: their LinkedIn, their GitHub, their employer's team
+ page, each keyed on an identifier already on the record.
+- **There is no image search by name, and there must never be.** Nobody audits a
+ face. **Guess where to look, never what you will find.**
+- `get_linkedin_profile` stores the picture in code at `isSamePerson`.
+
+## Two lanes
+
+`schedules/dispatch.ts`, split by `DIRECT_KINDS` in `@crm/db/agent-tasks`.
+
+| | Kinds | How | Per tick |
| --- | --- | --- | --- |
-| **Visible** | `brand`, `portrait` | Directly, no `receive`, no model | 60, six at a time |
+| **Visible** | `brand`, `portrait` | Directly — no `receive`, no model | 60, six at a time |
| **Research** | everything else | One eve session per row | 12 |
-**Neither kind in the visible lane has anything in it to decide.** A portrait is
-three reads keyed on identifiers already on the record and a byte copy. A brand
-is a domain in, Context.dev out, map, mirror, write — `lib/brand.ts`, and there
-is not one judgement in the whole path. Routing either through a session buys a
-context window in order to make no decisions with it.
-
-Routed through a session it also did not work, twice, the same way. Seven queued
-faces sat behind sixty LLM sessions at five a minute and had not landed twenty
-five minutes later. Then `company-profile` — which is how a logo used to get
-fetched — sat at the *bottom* of one shared queue at priority 10, behind every
-contact task, so `stripe.com` showed as `stripe.com` in a grey square while the
-agent wrote paragraphs about people who worked there.
-
-Lanes are why that cannot recur. A logo does not queue behind research, because
-it is not in that queue. `test/lanes.integration.spec.ts` pins it: thirty
-`identify` rows do not delay one `brand` row.
-
-The schedule still decides nothing, which is the rule it has to keep. The row
-says what the work is; the lane only says whether it needs a conversation.
-
-### Priority is what a rep sees first
-
-One table, in `@crm/db/agent-tasks` because the API writes these and the agent
-reads them, and two copies of an ordering is two orderings.
-
-| | | |
-| --- | --- | --- |
-| `brand` | 900 | the logo and the real name, on every row of the list |
-| `portrait` | 800 | the face |
-| `workspace` | 500 | who *we* are — every later session opens with it |
-| `requested` | 300 | a rep pressed Research |
-| `meeting` | 200 | a meeting is coming |
-| `identify` | 100 | a new contact |
-| `sweep` | 50 | the sign-in backfill |
-| `companyProfile` | 40 | the written brief |
-| `recheck` | 0 | come back in ninety days |
-
-The top two are the highest on purpose: they are what a rep reads *before*
-deciding whether to open anything, they cost one vendor call each, and they
-finish in seconds. Everything below is worth a wait; a grey square with initials
-in it is not.
-
-`claimDue` sorts what it claims. Postgres does **not** order an `UPDATE …
-RETURNING` by the `ORDER BY` of its own sub-select — it returns rows in whatever
-order it touched them — so the priority that chose the batch would otherwise be
-thrown away at the point the batch is handed to a concurrency-limited pool.
-
-### Starting now instead of on the minute
-
-`POST /internal/crm/dispatch` on the crm channel drains **both lanes** on demand,
-and `AgentTriggerService.poke()` calls it after writing *any* `AgentTask` row.
-Add a company and its logo appears; add a contact and the research starts. You do
-not wait out the cron.
-
-The poke is **fire-and-forget and never awaited**: the `AgentTask` row is still
-the message, exactly as [`api.md`](./api.md) requires, and the cron still claims
-anything the poke missed. An agent that is down, redeploying or unreachable costs
-sixty seconds, not the work.
-
-It used to run the visible lane only, on the reasoning that a lane needing no
-`receive` and no session auth keeps eve's principal plumbing out of the route.
-That was true and it cost more than it saved, because it made the two lanes
-behave differently in the one environment where the cron does not exist. Under
-`eve dev` the visible lane ran on every poke and the research lane ran *never* —
-so a fresh clone showed every logo resolving within seconds while twenty
-`identify` rows sat at `attempts = 0` and `AgentEvent` stayed empty. Nothing
-errored. A dead lane is very hard to tell from a slow one when the lane beside it
-is visibly working.
-
-So the route starts sessions too. It calls the channel's own `send` rather than
-`receive`, since it is already *on* the crm channel — `receive` is for handing
-work to a different one. The principal comes from `APP_AUTH` in
-[`lib/app-auth.ts`](../apps/agent/agent/lib/app-auth.ts), which is the one copy of
-eve's app principal in this repo: `lib/approval.ts` already hard-coded those three
-strings to decide whether a turn may write unattended, and eve does not export
-`SCHEDULE_APP_AUTH` publicly. `taskAuth()` builds the attributes both callers
-need, so the schedule and the route cannot drift on what a session is told about
-its task. The schedule still passes eve's own `appAuth` where it has it.
-
-**Both callers go through `drainAll`, and it collapses.** The cron ran alone once
-a minute, so overlap was never a question it had to answer; the poke fires per
-enqueued row, and a sync creating forty contacts calls it forty times in a few
-seconds. `claimDue` hands each caller a *disjoint* batch, so without a guard that
-is forty research sessions at once instead of the twelve a minute the cron
-allows — a cost and rate-limit spike triggered by nothing more than a busy inbox.
-`collapsing()` in [`lib/pool.ts`](../apps/agent/agent/lib/pool.ts) keeps one drain
-in flight and folds everything that arrives during it into a single trailing run,
-so work queued mid-drain is still picked up immediately rather than waiting out
-the next tick. It is per-process: cross-process overlap stays the job of leases
-and `FOR UPDATE SKIP LOCKED`, which already handle it.
-
-`AGENT_BRIDGE_SECRET` authorises it, and **unset means the route refuses rather
-than opens**, the same rule the rep bridge follows.
-
-### Checking a key belongs to the person who typed it
-
-`POST /internal/crm/verify-key` is the crm channel's second internal route, and
-it exists because the API is not allowed to call Context.dev and this agent
-already does. It takes a candidate key, probes with it, and answers `valid`,
-`invalid` or `unknown` — no session, no model, no task row, because there is
-nothing here to decide.
-
-- **The probe is free and it is chosen to be.** A brand lookup only bills when
- it resolves a brand, and a free-provider address is refused with a documented
- `422` first, so `[email protected]` authenticates without buying anything.
- Do not "improve" this to a real domain: that is ten credits every time
- somebody saves a key, including every time they correct a typo.
-- **`classifyKey` rejects on `401` and nothing else.** Every other status came
- back *after* the key was accepted, so it says something about the plan, the
- quota or Context's afternoon — not about the key. Treating a `429` as a bad
- key would refuse a perfectly good one at the worst possible moment.
-- **It is the candidate key, never the stored one.** `verifyKey` builds a
- throwaway client from the argument, so checking a new key cannot be confused
- with exercising the one already saved.
-
-The API's half is `ResearchKeyService`, and an `unknown` answer there saves the
-key anyway — see
-[the environment rules](./environment.md#the-context-key-is-asked-for-not-configured).
-
-### Catching up what was missed
-
-Enrichment is queued when a record is created, so anything created before a
-capability existed never gets it. Two routes, and picking the wrong one is
-expensive:
-
-| | Covers | Cost |
-| --- | --- | --- |
-| Automatic sweep, on sign-in | Records never successfully looked up | Ten credits per company |
-| `ImageMirrorService`, in the same sweep | Rows whose picture is still served from somebody else's origin | Nothing |
-| `bun run --filter=agent backfill:images` | Records already enriched, missing only the *pictures* | Nothing |
-
-The middle row is the one that keeps "every picture is ours" true rather than
-true-since-Tuesday. Every writer copies as it writes, but that says nothing
-about rows written before it did, or rows whose copy failed at the time because
-the origin was down. Left alone those never resolve, and nothing looks broken —
-the pictures render perfectly, off someone else's server, forever. It is capped
-at twenty five rows per table per sweep, so a backlog drains over several
-sign-ins instead of in one burst that looks like a scrape.
-
-**A photo sweep queues anyone with a LinkedIn URL, a GitHub URL, or an employer
-with a website — the three doors the chain knows. The third reads the company's
-team page and costs Context.dev credits, which is why a **finished `portrait`
-task stands that contact down for thirty days**. Most people are not on their
-employer's team page and never will be; without the stand-down every sweep would
-pay to re-read the same sites and find the same nothing, forever. The task's
-`outcome` carries what was actually tried, so a month of paid lookups leaves
-something readable behind.
-
-The sweep has no button, deliberately.** It had one on each list page, and a
-control whose correct usage is "press it whenever you notice blanks" is a chore
-dressed as a feature — a rep has no way of knowing which records predate the
-favicon resolver, and no business fixing that by hand.
-
-The trigger is **signing in**, which is the one moment nothing else in the app
-can see. `packages/auth` owns it, through a Better Auth
-`databaseHooks.session.create.after`; `BackfillService.onModuleInit` subscribes
-via `onSignedIn`. The registry exists because the arrow cannot point the other
-way — `@crm/auth` is a dependency of the API, so it must not import a Nest
-provider — and it means the Next.js app, which imports the package only to read
-sessions, runs none of this.
-
-`BackfillService` has no router at all as a result. Nothing calls it; it is
-subscribed. A five-minute stand-down collapses a burst — a team arriving at
-nine, or Google linking an account mid-sign-in — and `auto()` returns before any
-work starts, so nothing is between a person and their CRM.
-
-It writes `AgentTask` rows and decides nothing, which is what keeps it on the
-API's side of the line in [`api.md`](./api.md); whether a given company is worth
-the credits stays the agent's call. Each pass is capped at 500 rows and the
-leftover is logged rather than rounded away.
-
-**The cap is on the pass, not on each query inside it.** A company sweep has two
-sets of candidates — never successfully looked up, and still missing its
-artwork — and it used to take 500 of each and hand the union to `backfill`, so
-one sign-in could enqueue a thousand `brand` rows at priority 900 and fill the
-[direct lane](#two-lanes-what-a-rep-sees-and-what-a-rep-asks-for) with twice the
-declared budget. The union is deduplicated and cut to 500 before it is queued,
-and `remaining` is counted against the union in one query — the two sets overlap
-heavily, since a company that was never looked up rarely has a logo — so the
-figure the log prints is the work actually left rather than the leftover of one
-of the two halves.
-
-The script is the cheap half: it re-derives from the `CompanyEnrichment.raw`
-payloads already on disk, which is what keeping them was for. Reach for it when
-the records are fine and only the images are missing.
+**Neither visible kind has anything to decide**, and through a session they queued
+behind sixty LLM runs for 25 minutes. `test/lanes.integration.spec.ts` pins it. **The
+row says what the work is; the lane only says whether it needs a conversation.**
+
+**Priority** (`@crm/db/agent-tasks`): `brand` 900 · `portrait` 800 · `workspace` 500
+· `requested` 300 · `meeting` 200 · `identify` 100 · `sweep` 50 · `companyProfile` 40
+· `recheck` 0. The top two are what a rep reads *before* deciding what to open.
+
+**`claimDue` sorts what it claims** — Postgres does not order `UPDATE … RETURNING` by
+its sub-select's `ORDER BY`.
+
+### Dispatch on demand
+
+`POST /internal/crm/dispatch` drains **both lanes**; `AgentTriggerService.poke()`
+calls it after writing any `AgentTask`.
+
+- **Fire-and-forget, never awaited** — the row is still the message.
+- **Both lanes.** Visible-only made them diverge under `eve dev`, where there is no
+ cron: logos resolved instantly while `identify` sat at `attempts = 0` forever.
+- **Calls the channel's own `send`, not `receive`** — it is already on the crm
+ channel. Principal from `APP_AUTH` (`lib/app-auth.ts`); `taskAuth()` keeps schedule
+ and route from drifting.
+- **`drainAll` collapses** via `collapsing()` (`lib/pool.ts`) — forty new contacts
+ poke forty times, and `claimDue` hands each a disjoint batch. Per-process;
+ cross-process overlap is leases and `FOR UPDATE SKIP LOCKED`.
+- **`AGENT_BRIDGE_SECRET` unset refuses rather than opens.**
+
+### `POST /internal/crm/verify-key`
+
+Probes a candidate Context key → `valid`/`invalid`/`unknown`. No session, no model,
+no task row; exists because the API may not call Context.
+
+- **The probe is free and chosen to be** — a free-provider address gets a `422`
+ before billable resolution. **Do not point it at a real domain**: ten credits per
+ typo correction.
+- **`classifyKey` rejects on `401` and nothing else.**
+- **The candidate key, never the stored one.**
+
+### Backfills
+
+Sign-in sweep covers records never looked up (10 credits/company);
+`ImageMirrorService` in the same sweep re-hosts off-site pictures (free);
+`backfill:images` fixes enriched records missing only pictures (free).
+
+- **The image sweep keeps "every picture is ours" true**, not true-since-Tuesday.
+ 25 rows/table/sweep.
+- **A finished `portrait` task stands that contact down for thirty days** — that
+ third source costs credits and usually finds nothing.
+- **No button, deliberately** — a rep cannot know which records predate a resolver.
+- **The trigger is signing in**, via `databaseHooks.session.create.after` in
+ `packages/auth`; `BackfillService` subscribes with `onSignedIn` and has no router
+ (`@crm/auth` must not import a Nest provider). Five-minute stand-down, and `auto()`
+ returns before work starts.
+- **The 500-row cap is on the pass, not each query in it.** Deduplicate the union,
+ cut to 500, count `remaining` against the union.
## Evidence, not confidence
-**No tool accepts a confidence, a score, or a `sourceUrl` offered as proof.** A
-tool reports what it *observed* — `crm.signature-block`, `github.account-identity`
-— and `lib/evidence.ts` prices it. This is the rule the whole design rests on:
-a model asked to grade its own certainty will, and it will be wrong in the
-direction that makes it look useful.
-
-- `lib/evidence.ts` — the weights, the combination rule, the bands.
-- `lib/facts.ts` — the only write path to a contact's fields. Applies at
- `VERIFIED`, stores a proposal below it, and enforces three things a prompt
- cannot: never overwrite a human, never re-offer a dismissal, never write
- without a primary source.
-- The bands are behaviour, not labels. `PROBABLE` means *a rep decides*, and
- that is a correct outcome — four Marchettis work at Fernhill.
+**No tool accepts a confidence, a score, or a `sourceUrl` offered as proof.** Tools
+report what they *observed* (`crm.signature-block`, `github.account-identity`) and
+`lib/evidence.ts` prices it. A model asked to grade its own certainty will, and will
+be wrong in the direction that looks useful.
-Adding a fact field means adding it to `FIELDS` in `lib/facts.ts` **and** to
-`FACT_COLUMNS` in `apps/api/src/contacts/contacts.service.ts`, which is where an
-accepted proposal writes through.
+- **`lib/facts.ts` is the only write path to a contact's fields.** Applies at
+ `VERIFIED`, proposes below it, and enforces three things a prompt cannot: never
+ overwrite a human, never re-offer a dismissal, never write without a primary source.
+- **Bands are behaviour.** `PROBABLE` means *a rep decides* — a correct outcome.
+- **A new fact field goes in `FIELDS` (`lib/facts.ts`) *and* `FACT_COLUMNS`**
+ (`apps/api/src/contacts/contacts.service.ts`).
## Optional by default
-Every outside source is optional and the agent is designed to run with none.
-`lib/capabilities.ts` is the single place that knows what is set: it prints the
-list at boot, states it in the session instructions so the agent plans around
-what it has, and gives tools a shared "not configured, and retrying will not
-help" result — checked **before** the research budget is charged.
-
-A missing key removes a place to look. It is never an error, and it must never
-throw.
-
-**Not all of them are environment variables, which is why `capabilities()` is
-async.** The Context.dev key is a row a rep can set on Settings → General — see
-[the environment rules](./environment.md#the-context-key-is-asked-for-not-configured)
-— so the answer to *what can I use here* now involves a read, and `enabled()`
-and `capabilitiesMarkdown()` are awaited with it. `capabilitiesFrom()` and
-`markdownFor()` are the pure halves, which is what keeps
-`test/capabilities.spec.ts` a unit test rather than something that reports a
-different answer depending on what the developer happens to have saved locally.
-
-`contextDevKey()` is the only resolver, and `lib/context-dev.ts` builds its
-client from it rather than from `process.env` — memoised on the key string, so
-replacing the key swaps the client and nothing else does. There is no cache in
-front of the read: a key saved in the browser applies to the next vendor call,
-not the next deploy.
-
-## Budget, and deciding what to do next
-
-- `lib/focus.ts` holds the per-session budget in `defineState`. Every vendor
- call charges it. Running out is a normal ending.
-- `lib/tasks.ts` is the work queue. `claimDue` leases rows with
- `FOR UPDATE SKIP LOCKED`, so two dispatchers take disjoint work and a run that
- dies frees its row when the lease expires.
-- `schedules/dispatch.ts` is the **only** schedule. It decides nothing: it
- leases what is due and starts a session per row. Anything that looks like
- "every N minutes, the oldest ten contacts" belongs in a task's `dueAt`, not in
- a cron expression.
-- `tools/schedule_recheck.ts` is how the agent books its own next look, and its
- `reason` is shown to the rep. An agent that cannot say why it will be back in
- fourteen days does not have a reason, it has a default.
-
-## Three records, and no dead ends between them
-
-The CRM has contacts, companies and deals, and the agent is opened on any of
-them. Every read hands back the **ids** of the neighbouring records, and that
-rule is not decoration — the two worst answers this agent has given both came
-from breaking it:
-
-> I don't have a tool that lists contacts by company, only ones that look up a
-> specific contact by ID or email. Could you paste the contact's name or email
-> address?
-
-Said to a rep who had the company open, with the contacts on screen. The
-company preamble reported a *count* of contacts, the only read took a
-`contactId`, and the agent correctly concluded it had nowhere to go. And, on a
-contact who plainly worked somewhere, that no company was available: the
-history returned `companyName`, a display string, while every company tool
-takes an id.
-
-So:
-
-| Read | Free | Hands back |
-| --- | --- | --- |
-| `read_crm_history` | yes | the contact's **company id**, the deals they are on, their colleagues |
-| `read_company_history` | yes | **every contact with their id**, every deal, the account's threads and meetings, the notes |
-| `read_deal_history` | yes | the stage clock, every stage it moved through, the people on it with ids, the last reply |
-| `search_crm` | yes | contacts, companies and deals matching what a person would type |
-
-**A preamble or a tool result that names a record without its id is a bug**,
-because the only recovery available to the agent is to ask the human — which is
-the CRM handing its own join back to the person using it. Ambiguity is
-different, and fine: four Marchettis come back as four rows with their titles,
-and asking which one is a question rather than a chore.
-
-`search_crm` deliberately does no fuzzy matching. "Northwind" reaching
-"Northwind Savings Group" is useful; "Marchetti" reaching "Marchetta" is a
-wrong record in a CRM, and a wrong record about a real person is the one
-failure this whole design exists to prevent.
-
-### A session is a conversation, and they are not all the same one
-
-`lib/preamble.ts` builds what a session is told before it speaks, and it varies
-on two axes:
-
-- **Which record.** A person is asked who they are, a company what it does and
- who we know there, a deal where it stands. Each preamble names that record's
- neighbours, with ids, and points at the read to start from.
-- **Who opened it.** A dispatched task is a research pass with a budget; a rep
- in the sheet is a conversation. Told neither, the agent assumed the first,
- which is how a question got a work plan back. `taskKind` is the tell — the
- dispatcher sets it and the panel never does.
-
-The prose lives in `lib/preamble.ts` rather than in `instructions/task.ts` so
-that `test/preamble.integration.spec.ts` can assert the thing that actually
-matters: that a company session can name its own contacts. `task.ts` is the
-resolver, and it owns the one side effect — seeding `lib/focus.ts`, without
-which the audit hook files a session's events against nothing.
-
-Adding a fourth record kind is an entry in `sessionPreamble`, a read beside the
-other three, and a line in `TOOL_VERBS` (`apps/app/lib/agent-transcript.ts`),
-which a test enforces so no tool ever shows a rep a bare slug.
-
-### Every session also knows who *we* are
-
-A research agent that knows everything about the person and nothing about the
-company employing it writes a dossier, not a briefing. Asked about a contact
-before a call it returned six accurate paragraphs on him and could not say what
-any of it meant for us, because nothing had ever told it what we sell.
-
-So `composeClosing()` puts a **Who we are** block in front of the capabilities
-in *every* preamble — contact, company, deal, and the record-less one — and
-`lib/workspace.ts` is the only thing that renders it.
-
-- **It is deliberately tiny**, and the write path enforces that rather than the
- prompt asking nicely: 320 characters of narrative and one short line each for
- what we sell, who we sell to, and what we are picked over (`MAX_NARRATIVE` and
- `MAX_LINE` in [`@crm/db/workspace`](../packages/db/src/workspace.ts)). It rides
- in front of every question a rep asks, so a page of it would crowd out the
- record they are actually asking about — and it is prompt-cached, so it is paid
- for once and then read on every turn forever.
-- **It says what the context is for.** "Say what this record means for us — a
- fit, a competitor, a partner, or nothing worth saying — and never write a
- pitch: the rep already knows what we sell." Without that line the model has
- the facts and no instruction, and starts selling our own product back to us.
-- **A workspace with no profile still gets the name line**, followed by *do not
- guess at what we sell*. The failure mode of the alternative is a confident
- invention drawn from our customers' industries.
-- **The profile belongs to a website, and dies with it.**
- `readWorkspaceIdentity` returns the profile only when its `website` still
- matches the workspace's. Change the website and the block silently drops to
- the name line until the new one is researched, rather than describing the
- company we used to be.
-- **It is not a `Company` row.** A self company would need excluding from every
- list, facet, sweep and join in the app — the always-the-same-`organizationId`
- trap from [`api.md`](./api.md) wearing a different hat. It is one row in
- `WorkspaceProfile`, keyed on `WORKSPACE_ID`, which is why that constant now
- lives in `@crm/db` and `@crm/auth` re-exports it: the agent has no dependency
- on the auth package and there must not be a second copy of the string.
-
-The research pass is a `workspace-profile` task with no `contactId` and no
-`companyId`, dispatched like everything else. Its preamble sends the session to
-our own site with `web_fetch` — no vendor credits — and `write_workspace_profile`
-is the only way to file the result. `WorkspaceService.update` queues it when the
-website changes, and the sign-in sweep queues it when a website has no profile
-behind it, which covers the install that filled the settings page in before any
-of this existed and the one whose first attempt failed.
-
-**A finished attempt stands the sweep down for seven days**, the same shape as
-the portrait stand-down above and for the same reason. There is one workspace,
-so a website that cannot be read into a profile — a holding page, a site that
-blocks the fetch — was a `workspace-profile` session queued on *every* sign-in
-sweep for the life of the install, at the highest research priority there is,
-never getting a different answer. Changing the website still queues one
-immediately through `WorkspaceService.update`, so the stand-down only paces the
-retry of a failure, and it is shorter than a contact's thirty days because this
-one row rides in front of every question a rep asks.
-
-## What the agent may read, and what may leave
-
-It may read **everything**, including full email bodies — single-tenant internal
-tool, and a signature block is the best source of a job title there is. The
-boundary is egress, and it is three rules:
+`lib/capabilities.ts` is the single place that knows what is set: prints it at boot,
+states it in the session instructions, and gives tools a shared "not configured,
+retrying will not help" result — **checked before the research budget is charged**. A
+missing key removes a place to look. **Never an error, never throws.**
-1. No customer text in a third-party query. Derived questions only.
-2. Nothing from a mailbox into `/workspace`. The sandbox has a different
- lifetime.
-3. Nothing sensitive logged. Reading is not logging.
+**`capabilities()` is async** because the Context key is a row;
+`capabilitiesFrom()`/`markdownFor()` are the pure halves. `contextDevKey()` is the
+only resolver, and `lib/context-dev.ts` memoises its client on the key string with no
+cache in front of the read.
-`skills/data-boundaries.md` is the agent's copy of this. Keep them in step.
+## Budget and scheduling
-## The sandbox
+- `lib/focus.ts` — per-session budget in `defineState`; running out is a normal ending.
+- `lib/tasks.ts` — `claimDue` leases with `FOR UPDATE SKIP LOCKED`.
+- **`schedules/dispatch.ts` is the only schedule and decides nothing.** "Every N
+ minutes, the oldest ten contacts" belongs in a `dueAt`.
+- `tools/schedule_recheck.ts` — its `reason` is shown to the rep.
-`agent/sandbox/sandbox.ts` turns on `bash`, the file tools, and a `/workspace`,
-with **`deny-all` egress** set on the backend factory so it cannot be forgotten
-per session. That costs nothing: `web_fetch` runs in the app runtime and
-`web_search` at the model provider, so retrieval is unaffected.
+## Three records, no dead ends
-**Never give the sandbox `DATABASE_URL`.** CRM access is authored tools in the
-app runtime. A shell with credentials and network is exfiltration-shaped even in
-an internal tool; a shell with neither is a text processor.
+**Every read hands back the ids of neighbouring records.** Breaking this made the
+agent ask a rep who had a company open, contacts on screen, to paste an email.
-## The bridge
+| Read (all free) | Hands back |
+| --- | --- |
+| `read_crm_history` | the contact's **company id**, their deals, their colleagues |
+| `read_company_history` | **every contact with id**, deals, threads, meetings, notes |
+| `read_deal_history` | stage clock and history, **people with ids**, last reply |
+| `search_crm` | contacts, companies and deals matching typed text |
-The contact sheet's **Agent** tab talks to a running agent. The path:
+**A preamble or tool result naming a record without its id is a bug** — the only
+recovery is asking the human. Ambiguity is fine: four Marchettis is four rows with
+titles. **`search_crm` does no fuzzy matching** — "Marchetti" reaching "Marchetta" is
+a wrong record about a real person.
-```
-browser → /eve/v1/* (same origin, session cookie)
- + x-crm-contact: the record the rep has open
- → apps/app/app/eve/v1/[...path]/route.ts
- checks the Better Auth session
- strips the cookie
- mints a 2-minute HS256 token naming the rep
- and carrying the contact id
- → AGENT_URL/eve/v1/*
- agent/channels/eve.ts → repFromCrm() verifies it
- instructions/task.ts reads attributes.contactId
-```
+### Preambles
-**The record travels in the token, never in the message.** The panel used to
-prefix everything a rep typed with `About contact <cuid> (Name):` so the agent
-knew what it was looking at, which meant the rep read their own question back
-with plumbing bolted to the front. The claim reaches the agent through the same
-`session.auth.attributes` path the dispatcher uses, so the message stays theirs.
-
-Mounted at `/eve/v1/*` deliberately: that is where `useEveAgent()` looks by
-default, so the hook needs no `host` and there is no CORS and no cross-site
-cookie anywhere in it. It is the same trade the app already makes for the API.
-
-Three things worth knowing before you touch it:
-
-- **The proxy is an enforcement point, not a passthrough.** The agent never sees
- the session cookie, so if that route did not check the session, nothing
- downstream would.
-- **eve's `jwtHmac()` helper resolves an HMAC token to
- `principalType: "service"`** with a namespaced `principalId`. Correct for a
- machine credential, wrong for a person — and `lib/approval.ts` decides whether
- to pause for a human by reading exactly those fields, so a rep would have been
- refused a sensitive write while sitting there watching. `repFromCrm` wraps
- `verifyJwtHmac` and maps the subject to a real user principal.
- `test/channel-auth.spec.ts` pins it.
-- **`AGENT_BRIDGE_SECRET` unset skips the auth entry rather than opening it.**
- The panel stops working; the agent keeps running its own schedule. An
- optional capability's absence must never widen access.
-
-### The panel knows which record it is on
-
-`lib/agent-record.ts` is the single place that maps a record kind to everything
-downstream: the header the panel sends, the claim the proxy mints, the field a
-conversation is filed under, and the questions offered on an empty thread. A
-contact is asked "Who is this person?", a company "What do they do?", a deal
-"Where does this stand?" — offering the first of those on a company is the tell
-that a chat box was bolted on rather than built into the record.
-
-The agent gets the same context: `instructions/task.ts` opens a session with a
-preamble built from the record, so a deal session starts knowing the stage, the
-amount, the close date and who is on it, rather than spending its first two tool
-calls finding out.
-
-Adding a fourth kind is one entry in `COPY` plus a branch in the agent's
-preamble — not four edits in four layers.
-
-### Conversations are kept
-
-A record accumulates conversations, and they survive a reload. `AgentConversation`
-holds the *handle* — the durable eve session id plus its cursor — while the
-transcript itself is already in `AgentEvent`, written by the audit hook. Nothing
-is stored twice.
-
-- **Resuming.** The panel passes the saved cursor as `initialSession`, so
- reopening a contact continues last week's thread rather than starting another.
- eve keeps sessions for 30 days.
-- **Replay from the start.** `streamIndex: 0` on resume, deliberately — the
- saved index is where the *last reader* stopped, and a reopened thread should
- show what was said in it, not only what has happened since.
-- **Which thread is open lives in the URL** (`?thread=`), like every other view
- state in the sheet, so a refresh keeps your place and a conversation is a link.
- It is cleared when the record or the tab changes, by the same rule that drops
- a half-typed quick-add form.
-- **Nothing mounts until the list has loaded.** Rendering a thread while the
- history is still in flight starts a *new* eve session and then remounts onto
- the real one — which presents as "the history only appears if I refresh".
-- **The thread the panel landed on is captured once.** Re-deriving "the latest"
- as the list changes would swap the open conversation out from under a live
- answer the moment the first save adds a row. `resolveThread` in
- `lib/agent-transcript.ts` holds the rule, and it is tested.
-- **The panel is not unmounted when you switch tabs.** It holds a live stream,
- and Radix drops an inactive tab by default — which aborts the stream
- mid-answer, so the reply landed in the durable session with nothing attached
- to receive it. That is the "I went to another tab and the answer never came
- back" bug, and no amount of re-reading state on the way in could fix it,
- because the events had been dropped. `keepMounted` on the tab descriptor
- (`detail-sheet.tsx`) keeps it alive; it renders nothing until the tab is
- opened once, so flicking through records costs nothing.
-- **A thread is loaded with `session.snapshot()`, not by hand.** One call
- returns the complete event prefix, the cursor that continues from it, and a
- continuation token *if and only if* eve will accept another turn — about 30ms
- against a hundred-event thread. `lib/agent-session.ts` is the whole of it.
-
- What it replaced is worth remembering, because every panel bug of the last
- day came out of it: a raw `fetch` of `…/stream?startIndex=-1`, parsing the
- last line into a state machine. The endpoint *follows*, so awaiting the body
- never returned. The stream opens with a bare newline, so "the first line" was
- empty — which failed closed to "busy" and locked **every** reopened
- conversation with "still working on the last question", including ones parked
- with a perfectly good token. And a read that failed reported the *session* as
- working rather than reporting itself as broken, so it could never recover.
- The framework had a documented answer to the exact question that code was
- asking. Read the guide before hand-rolling the protocol.
-- **The token is the authority on whether a message can be sent**, not our
- reading of the events. eve returns one only when the captured prefix ends
- parked, which is precisely the condition under which the next send lands.
-- **A turn that has gone quiet for 90 seconds is over, not working.** A
- restarted agent leaves sessions with no closing boundary; they never park, and
- treating them as in-flight locks that thread forever.
-- **An unreachable agent is `offline`, not `working`.** One is a fact about us
- and the other a claim about the session; stated as the latter it is both
- untrue and unrecoverable, since the read fails identically next time. The
- transcript then comes from our own `AgentEvent` archive — which is also what
- makes a thread older than eve's 30-day retention still readable — and the
- composer stays usable.
-- **An ended thread gets a button, not a locked box.** Ended and working both
- disable the composer and mean completely different things: one is a wait of
- seconds, the other is permanent. `composerState()` keeps them apart, and an
- ended thread offers **Start a new conversation**, which moves the picker to a
- new thread. The transcript stays on screen throughout, and the save hook
- treats the fresh session as a new conversation by comparing session ids
- rather than by whether the panel started empty.
-- **`autoScroll` and nothing else.** The scroller is a state machine
- (`following-bottom`, `free-scrolling`, `anchored-to-message`) and
- `scrollAnchor` selects the third, which *stops it following the bottom* — the
- answer then streams below the fold while the modes fight over each new row.
- Left alone, `autoScroll` follows the tail while the reader is at the bottom
- and releases the moment they scroll away, which lights the jump-to-end button.
-- **One `MessageScrollerItem` per message, not per part.** The row is what the
- scroller measures; a row per tool call adds a boundary every few hundred
- milliseconds during an answer. Part ids prefer `toolCallId`, which is stable
- across a call's streaming states.
-- **A thread nobody has spoken in is loaded from nothing.** The snapshot query
- is disabled without a conversation; a brand-new thread mounts with no session
- and no events, and its first message creates both.
-- **Scoped to the rep.** Two people asking about the same contact are having two
- conversations. `ConversationsService` filters on the caller, and a session id
- in a request body decides which row, never whose.
-- **Cached the way `api.md` prescribes**: read through
- `cache-manager` (Redis when `REDIS_URL` is set), write on miss, explicit
- invalidation on every save. The list is read on every sheet open and changes
- only when somebody sends a message, which is the shape a cache is for.
-
-This lives in the API rather than the agent, and that is not a breach of rule
-one: listing a record's history researches nothing, scores nothing and decides
-nothing. The agent owns judgement; the data surface owns filing.
-
-### Turning it on
-
-Same value in both processes, from the one root `.env`:
+`lib/preamble.ts` varies on **which record** (each names its neighbours with ids and
+points at the read to start from) and **who opened it** — a dispatched task is a
+research pass with a budget, a rep in the sheet is a conversation. Told neither, the
+agent answered a question with a work plan. `taskKind` is the tell.
-```sh
-AGENT_URL="http://127.0.0.1:2000" # the default
-AGENT_BRIDGE_SECRET="$(openssl rand -base64 32)"
-```
+Prose lives in `lib/preamble.ts` so `test/preamble.integration.spec.ts` can assert a
+company session names its own contacts. `task.ts` is the resolver and owns one side
+effect: seeding `lib/focus.ts`, without which the audit hook files events against
+nothing.
-Then `bun run dev` (the agent serves on `:2000`) and open any contact.
+**A fourth record kind** = `sessionPreamble` entry + a read + a `TOOL_VERBS` line
+(`apps/app/lib/agent-transcript.ts`) + a `COPY` entry (`lib/agent-record.ts`).
-**If the Agent tab errors:**
+### Every session knows who *we* are
-| Symptom | Cause |
-| --- | --- |
-| `503`, "not configured for this install" | `AGENT_BRIDGE_SECRET` is unset in the app's process |
-| `401` | The two processes hold *different* secrets |
-| `502`, "not reachable" | The agent is not running, or `AGENT_URL` is wrong |
+`composeClosing()` puts a **Who we are** block before the capabilities in every
+preamble; `lib/workspace.ts` is the only renderer.
-`eve dev` takes about five seconds to bind, and it listens on **IPv4 only**.
-That is why `AGENT_URL` defaults to `http://127.0.0.1:2000` rather than
-`http://localhost:2000`: Node resolves `localhost` to `::1` first, so the
-`localhost` form fails to connect on a machine where the agent is plainly
-running — and reports itself as "not reachable", which sends you looking in the
-wrong place.
+- **Tiny, enforced by the write path** — `MAX_NARRATIVE` (320) and `MAX_LINE` in
+ `@crm/db/workspace`. It is prompt-cached and precedes every question.
+- **It says what the context is for** — fit, competitor, partner, or nothing — and
+ **never a pitch**, or the model sells our own product back to us.
+- **No profile still gets the name line**, plus *do not guess at what we sell*.
+- **The profile dies with its website** — `readWorkspaceIdentity` returns it only
+ while `website` matches.
+- **Not a `Company` row** — that needs excluding from every list, facet and join. One
+ `WorkspaceProfile` keyed on `WORKSPACE_ID`.
-A variable in `.env` is not enough on its own: Turbo runs in strict env mode, so
-`apps/app/turbo.json` and `apps/agent/turbo.json` both declare the pair in
-`passThroughEnv`. Adding a variable and not declaring it produces exactly the
-`401` above.
+The pass is a `workspace-profile` task using `web_fetch` (no credits), filed only via
+`write_workspace_profile`, queued by `WorkspaceService.update` on a website change.
+**A finished attempt stands the sweep down for seven days.**
-### Checking it without a browser
+## What may be read, and what may leave
-`localDev()` accepts anything on loopback, so a bare `curl` to `127.0.0.1`
-proves nothing about the bridge. Send a non-loopback `Host` to make that entry
-skip:
+It may read **everything**, including full email bodies — internal single-tenant tool,
+and a signature block is the best source of a job title there is. The boundary is
+egress:
-```sh
-curl -s -o /dev/null -w '%{http_code}\n' \
- -H 'Host: agent.example.com' \
- http://127.0.0.1:2000/eve/v1/info # 401
+1. No customer text in a third-party query. Derived questions only.
+2. Nothing from a mailbox into `/workspace` — different lifetime.
+3. Nothing sensitive logged. Reading is not logging.
+
+`skills/data-boundaries.md` is the agent's copy. Keep them in step.
+
+## Sandbox
+
+`agent/sandbox/sandbox.ts`: `bash`, file tools, `/workspace`, **`deny-all` egress on
+the backend factory** so it cannot be forgotten per session. Costs nothing —
+`web_fetch` runs in the app runtime, `web_search` at the provider.
+
+**Never give the sandbox `DATABASE_URL`.** CRM access is authored tools. A shell with
+credentials and network is exfiltration-shaped; with neither it is a text processor.
+
+## The bridge
-curl -s -H 'Host: agent.example.com' \
- -H "authorization: Bearer $TOKEN" \
- http://127.0.0.1:2000/eve/v1/info | jq '.tools.available | length'
```
+browser → /eve/v1/* (same origin, session cookie, x-crm-contact header)
+ → apps/app/app/eve/v1/[...path]/route.ts
+ checks the Better Auth session, strips the cookie,
+ mints a 2-minute HS256 token naming the rep + record
+ → AGENT_URL/eve/v1/* → channels/eve.ts repFromCrm()
+ → instructions/task.ts reads attributes.contactId
+```
+
+- **The record travels in the token, never in the message.**
+- **Mounted at `/eve/v1/*`** because that is where `useEveAgent()` looks — no `host`,
+ no CORS, no cross-site cookie.
+- **The proxy is an enforcement point, not a passthrough** — the agent never sees the
+ session cookie, so if that route did not check, nothing would.
+- **eve's `jwtHmac()` resolves to `principalType: "service"`** — wrong for a person,
+ and `lib/approval.ts` reads exactly those fields to decide whether to pause for a
+ human. `repFromCrm` maps the subject to a real user principal
+ (`test/channel-auth.spec.ts`).
+- **`AGENT_BRIDGE_SECRET` unset skips the auth entry rather than opening it.**
-`GET /eve/v1/info` is the whole inventory — tools, skills, schedules, channels,
-sandbox, and a `diagnostics` count that is the fastest way to find a file eve
-silently ignored.
-
-## Watching it work
-
-`eve dev` shows every tool call, every result and every token — but only in its
-interactive TUI, and under `bun run dev` that TUI is unreadable. Turbo gives each
-task a pty, so eve believes it owns a terminal and paints a full-screen UI into a
-pane that turbo is also drawing; the two redraws interleave and what a rep of the
-agent's work actually looks like is `Building your agent compiling
-agent[agent] on LinkedIn (RAPIDAPI_KEY)`. The prompt at the bottom is real and
-you cannot type at it usefully either.
-
-So **`dev` is `eve dev --no-ui`**, and `dev:tui` keeps the interactive one for
-when you run the agent on its own and want to talk to it. `--no-ui` changes
-nothing about the server — same port, same routes, same watcher — it only stops
-eve taking over the terminal, which is the whole of the problem.
-
-That leaves nothing narrating the session, and `hooks/activity.ts` is that
-narration: a line per tool call with its arguments, a line per result with how
-long it took, the finish reason and token spend of each step, and any failure
-with its code.
-
-- **The lines go to stderr, not stdout.** The TUI's default log mode is `stderr`
- and it keeps stdout buffered and hidden, so a `console.log` here would be
- invisible in the mode it exists to serve. Written to stderr the same lines show
- under `--no-ui`, under the TUI, and in `eve logs`.
-- **Contents print outside production; the shape prints everywhere.** Which tool
- ran, whether it worked, what it cost — none of that is anybody's data, so it
- logs wherever the agent runs. Arguments and replies carry names, addresses and
- whatever a rep typed, which is the "nothing sensitive logged" rule above, so
- they are gated on `NODE_ENV`. In production the durable record is an
- `AgentEvent` row, not a log drain.
-- **It is not the audit trail.** `hooks/audit.ts` writes every event to
- `AgentEvent` whatever this prints, and the panel's transcript is read back from
- there. A change to one is not a change to the other.
-- **A call is timed by remembering it, because the result event does not carry
- the tool name or a duration.** The map of in-flight calls is bounded rather
- than trusted: a turn that dies between request and result would otherwise leak
- an entry per call, forever, in a process that stays up for days.
-
-`eve logs` reads the full record back, but only for an **interactive** `eve dev`
-— that is the process that writes `.eve/logs/`. Under `--no-ui` the pane is the
-record, so keep the turbo scrollback rather than going looking for a file that
-was never written.
-
-Two consequences of running headless, both worth recognising rather than
-debugging:
-
-- **A second `bun run dev` fails the whole turbo run.** An interactive `eve dev`
- reconnects to a local server that is already up; a headless one rejects it and
- exits non-zero, and turbo then tears down the other tasks in *that*
- invocation — the first one keeps running untouched. `A dev server is already
- running for this eve agent` means exactly what it says: you already have one.
- Use the terminal it is in, or stop it before starting another.
-- **An orphaned agent holds the port.** If turbo dies without reaping its child,
- nothing on screen says so and every later `bun run dev` fails the same way.
- `lsof -nP -iTCP:2000 -sTCP:LISTEN` names the process to kill.
-
-### Nothing is researching, and the queue only grows
-
-**`eve dev` never fires schedules on their cron cadence.** It is one line in
-eve's own [schedules guide](../apps/agent/node_modules/eve/docs/schedules.mdx),
-and it used to be the single most confusing thing about working on this agent,
-because every visible part of the loop worked: the Research button wrote its
-`AgentTask` row, the sheet said *Queued*, the toast promised the page would
-update — and `schedules/dispatch.ts`, the only thing that turns a row into a
-session, was never called. Twenty rows sat with `attempts = 0` and `AgentEvent`
-was empty. Nothing was broken and nothing reported a problem, because nothing
-ran.
-
-**The poke is what makes dev behave like production now**, which is most of why
-it was widened to both lanes — see [starting now](#starting-now-instead-of-on-the-minute).
-A row written by the API is dispatched immediately whatever the clock is doing,
-so the schedule is a backstop rather than the only door.
-
-**It only does that when `AGENT_BRIDGE_SECRET` is set**, and that variable is
-optional: `poke()` reads it first and returns without sending anything when it is
-unset. So an install that has not set it is back at the paragraph above with no
-cron behind it either — rows queue, nothing dispatches, and the queue looks
-exactly like a slow agent. Set it, or run the dispatch below by hand.
-
-That leaves two cases where the clock's absence bites even with the poke
-working, and both look identical to the above: **a task the API did not
-write** — `schedule_recheck`,
-which books its own `dueAt` weeks out — and **anything queued while the agent was
-down**, since a missed poke is not retried. For those, the dev server mounts a
-one-shot route that runs the exact dispatch path production cron uses:
+### The panel
+
+`lib/agent-record.ts` maps a record kind to everything downstream: the header sent,
+the claim minted, the field a conversation is filed under, the empty-thread questions.
+`AgentConversation` holds only the handle (session id + cursor); the transcript is in
+`AgentEvent` from the audit hook.
+
+- **Load with `session.snapshot()`, never by hand** — one call returns the event
+ prefix, the cursor, and a continuation token *iff* eve will accept another turn.
+ Hand-rolling the stream produced every panel bug this thing has had.
+- **The token is the authority on whether a message can be sent**, not our reading of
+ the events.
+- **`streamIndex: 0` on resume** — the saved index is where the last *reader* stopped.
+- **Quiet for 90 seconds is over, not working** — restarted agents leave sessions with
+ no closing boundary, which would lock the thread forever.
+- **An unreachable agent is `offline`, not `working`** — fall back to the `AgentEvent`
+ archive and keep the composer usable.
+- **An ended thread gets a Start-a-new-conversation button, not a locked box**;
+ `composerState()` keeps ended and working apart.
+- **Nothing mounts until the list has loaded**, or a new session starts and remounts.
+- **The landed thread is captured once** (`resolveThread`), or the first save swaps the
+ open conversation out from under a live answer. It lives in `?thread=`.
+- **`keepMounted` on the tab descriptor** (`detail-sheet.tsx`) — Radix drops an
+ inactive tab, aborting the stream mid-answer.
+- **`autoScroll` and nothing else**; `scrollAnchor` stops it following the bottom.
+- **One `MessageScrollerItem` per message, not per part**; ids prefer `toolCallId`.
+- **Scoped to the rep** — a session id in a body decides which row, never whose.
+- Cached per `api.md`: read through `cache-manager`, invalidate on save.
+
+This lives in the API and is not a breach of rule one: listing history decides nothing.
+
+## Dev
```sh
-bun run --filter=agent dispatch
-# {"scheduleId":"dispatch","sessionIds":["wrun_01KZ…", …]}
+AGENT_URL="http://127.0.0.1:2000" # 127.0.0.1, not localhost: eve dev is IPv4-only
+AGENT_BRIDGE_SECRET="$(openssl rand -base64 32)"
```
-It drains **both lanes**, exactly as the cron does: up to `VISIBLE_BATCH` (60)
-`brand` and `portrait` rows six at a time, handled in the process with no session
-at all, and `RESEARCH_BATCH` (12) research rows, one session each. So the
-`sessionIds` it prints are the research rows only — a run that resolved forty
-logos prints an empty list and was not idle. Either way it spends real credits, a
-vendor call per visible row and a model session per research one; that is the
-point of it, and the reason it is a command you run rather than a ticker somebody
-leaves on. Watch the agent pane; the session ids it returns are also streamable at
-`GET /eve/v1/session/:id/stream`.
-
-`eve start` on a built app *does* run the schedule, and so does Vercel, where
-each `defineSchedule` becomes a Cron Job. Dev is the only place the clock is
-missing.
-
-### The continuation token you write is not the one you read
-
-**eve namespaces a continuation token with the channel's name.** `channels/crm.ts`
-mints `task:<id>`; by the time `session.waiting` hands it back on the channel
-context it is `crm:task:<id>`. The `eve` channel's own sessions read back as
-`eve:<uuid>` for the same reason.
-
-This is worth stating because of how it failed, which was silently and
-completely. `taskToken()` used to mint `crm:task:<id>` itself, so the handler was
-matching `startsWith("crm:task:")` against `crm:crm:task:<id>`, getting `null`,
-and returning before `completeTask`. Nothing errored. The research ran, facts
-were written, briefs were saved, and the agent pane showed a clean session — but
-**no task ever reached `finishedAt`**, so every contact sat on "Researching"
-forever and the sweep re-queued work that had already been done. Twenty-eight
-tasks, zero finished.
-
-Two things made it survive a reading:
-
-- **The event data and the channel accessor disagree.** `session.waiting`'s
- `data.continuationToken` carries the token *as stored* — un-namespaced — while
- `channel.continuationToken` carries it namespaced. Debugging from the archived
- event says the token is fine, because from that angle it is.
-- **Nothing downstream depends on settling.** The record's status is the only
- thing that notices, and "still researching" is indistinguishable from
- "researching slowly" until you look at `attempts` in the table.
-
-So `taskFromToken` keys on the `task:` marker rather than a fixed prefix, which
-reads correctly whoever namespaced it and still settles sessions parked before
-the fix. `test/crm-token.spec.ts` pins all three forms.
-
-The general rule: **a channel handler must not assume the token it receives is
-byte-identical to the one it sent.** Parse for your own marker.
+`503` = secret unset in the app · `401` = the two processes differ, or `turbo.json`
+`passThroughEnv` is missing the pair (Turbo is strict-env) · `502` = agent down or
+wrong URL.
+
+**`bun run dev` is `eve dev --no-ui`** (turbo's pty makes the TUI unreadable);
+`dev:tui` keeps the interactive one, and only that writes `.eve/logs/` for `eve logs`.
+`hooks/activity.ts` is the replacement narration, **to stderr**, printing shape
+everywhere and argument contents outside production only. It is **not the audit
+trail** — `hooks/audit.ts` writes `AgentEvent` regardless. A second `bun run dev`
+fails the whole turbo run; an orphaned agent holds the port
+(`lsof -nP -iTCP:2000 -sTCP:LISTEN`).
+
+**`eve dev` never fires schedules on their cron cadence**, and everything visible
+still works — the row is written, the sheet says *Queued*, and `dispatch.ts` is never
+called. **The poke covers this only when `AGENT_BRIDGE_SECRET` is set**; unset,
+`poke()` returns silently and the queue looks exactly like a slow agent. Tasks the API
+did not write (`schedule_recheck`) and anything queued while the agent was down still
+need `bun run --filter=agent dispatch` — the exact production path, both lanes, real
+credits. Its printed `sessionIds` are research rows only, so a run that resolved forty
+logos prints an empty list and was not idle. `eve start` and Vercel do run the
+schedule.
+
+`localDev()` accepts any loopback request, so `curl 127.0.0.1` proves nothing about
+the bridge — send `-H 'Host: agent.example.com'`. `GET /eve/v1/info` is the whole
+inventory, including a `diagnostics` count that finds files eve ignored.
+
+### Continuation tokens are namespaced
+
+**eve prefixes them with the channel name.** `channels/crm.ts` mints `task:<id>`;
+`session.waiting` returns `crm:task:<id>`. Minting the prefix ourselves meant matching
+against `crm:crm:task:<id>` and returning before `completeTask` — research ran, facts
+were written, sessions looked clean, but **no task reached `finishedAt`**, so contacts
+sat on "Researching" forever. Hidden because the archived event's
+`data.continuationToken` is *un-namespaced* while `channel.continuationToken` is not.
+
+**`taskFromToken` keys on the `task:` marker, not a fixed prefix**
+(`test/crm-token.spec.ts`). **A channel handler must not assume the token it receives
+is byte-identical to the one it sent.**
## Tests
-`bun run --filter=agent test`. The integration specs need `DATABASE_URL` and run
-against a real Postgres, which is the point — "never overwrite a human" is only
-true if the transaction says so.
+`bun run --filter=agent test`. Integration specs need `DATABASE_URL` and a real
+Postgres — "never overwrite a human" is only true if the transaction says so.
diff --git a/docs/api.md b/docs/api.md
index 2d9457c8..024c0a13 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,813 +1,273 @@
+# API Rules
-# API Rules - Always review when working on our API
-
-## Logging: use the Nest logger, attach fields, never `console.log`
-
-Logging lives in `apps/api/src/logging`. `ContextLogger` extends Nest's
-`ConsoleLogger` and is installed in `main.ts`, so `new Logger(Thing.name)`
-anywhere in the app picks it up. **Format and level are not configurable** —
-they follow `NODE_ENV`: JSON at `log` and above in production, colourised with
-`debug`/`verbose` locally.
-
-- **Attach data as one object, not extra arguments.** Nest prints one line per
- argument, so `logger.log("Saved", { userId })` emits two lines. Write
- `logger.log({ message: "Saved", userId })` instead — the fields are hoisted to
- the top level in JSON and rendered after the text in development.
-- **Errors pass the stack as the second argument**:
- `logger.error({ message: "…" }, error instanceof Error ? error.stack : String(error))`.
- Handing Nest the error object instead prints it as a second message and drops
- the trace.
-- **Every request carries a `requestId`**, generated (or taken from an inbound
- `x-request-id`) by `RequestLoggerMiddleware`, returned on the response header,
- included in error bodies, and stored in `AsyncLocalStorage` so every log line
- during that request is correlated. `UserContextInterceptor` adds `userId` once
- the auth guard has resolved the session.
-- **Better Auth routes are logged through its `middleware` option**
- (`BetterAuthModule.forRoot({ auth, middleware: logAuthRoute })`). It mounts its
- handler straight onto the HTTP adapter during module configuration, before
- Nest applies anything from `MiddlewareConsumer`, so `/api/auth/*` would
- otherwise never reach the middleware. `LoggingModule` must stay **first** in
- `AppModule`'s imports for the same reason.
-- **Never log headers, query strings, or request bodies.** They routinely carry
- session cookies and personal data. Log the specific fields a handler knows are
- safe.
-- **Prisma statement logging is opt-in** via `PRISMA_LOG_QUERIES=true`, and is
- emitted at `debug`. It is off by default because it buries every other line
- under a wall of `SELECT`s. Bound parameters are dropped even when it is on.
- Prisma warnings and errors always flow through the app logger via
- `PrismaLogBridge`; outside the API (seeds, scripts, the Next.js app) they fall
- back to the console sink in `packages/db/src/client.ts`.
+## Logging
+
+`apps/api/src/logging`. `new Logger(Thing.name)` picks up `ContextLogger`. **Never
+`console.log`.** Format follows `NODE_ENV` and is not configurable.
+
+- **One object, not extra arguments** — `logger.log({ message: "Saved", userId })`;
+ Nest prints a line per argument.
+- **Errors pass the stack second** — `logger.error({ message }, err.stack)`. Passing
+ the error object drops the trace.
+- **Never log headers, query strings, or bodies** — cookies and personal data.
+- **`LoggingModule` stays first in `AppModule`'s imports**, and Better Auth routes log
+ via its own `middleware` option — it mounts before `MiddlewareConsumer`, so
+ `/api/auth/*` never reaches ours.
+- `requestId` from `RequestLoggerMiddleware` via `AsyncLocalStorage`;
+ `UserContextInterceptor` adds `userId`. Prisma statements are opt-in
+ (`PRISMA_LOG_QUERIES`).
## Intelligence never lives in the API
-This is an **agentic-first platform**. The API serves HTTP, auth, tRPC and the
-Google sync. It does not research, enrich, score, summarise, match identities or
-decide anything about a person or a company — not as a fallback, not "just the
-cheap bit", not behind a flag. That work belongs to the eve agent in
-`apps/agent`, which owns the vendor clients, the confidence model and the
-writes.
-
-Nest's half of the contract is to **report that something happened** — a thread
-was ingested, a company was created, an attendee is unknown — and let the agent
-decide what it means. A Nest service that calls an enrichment API is a bug, and
-the reason is in the tree: two identity matchers were copied across `apps/api`
-and `apps/agent`, and the copies silently drifted until one of them matched
-every employer on earth. See
-[`docs/plan/contact-intelligence-agent.md`](./plan/contact-intelligence-agent.md).
-
-`apps/api/src/enrichment/` is gone. What replaced it is
-`apps/api/src/agent/agent-trigger.service.ts` — one service with one verb, which
-writes an `AgentTask` row saying *this happened* and why it might matter. A row
-rather than an HTTP call: the agent leases work from that table already, so the
-row *is* the message, and it survives the agent being down, redeployed, or
-slower than the request that produced it.
-
-If you are about to add a vendor client to `apps/api`, you want
-`apps/agent/agent/lib` instead.
-
-## There is exactly one organization, and it is not a tenancy boundary
-
-This is an internal tool behind Google sign-in, and it is **single tenant**.
-There is no `x-organization-slug` header, no org context interceptor, no
-org-scoped cache keys, and **no `organizationId` on any CRM record**. A company,
-a contact, a deal and an activity are scoped by nothing, because there is
-nothing to scope them to.
-
-What does exist is a **singleton workspace**: the Better Auth `organization`
-plugin, holding one row whose id is the literal string `workspace`
-(`WORKSPACE_ID`, defined in [`@crm/db`](../packages/db/src/workspace.ts) and
-re-exported by `@crm/auth` — the agent reads workspace rows and does not depend
-on the auth package, and one id must not be two strings). It is there to answer
-three questions a CRM has to answer about *itself* — what is this company
-called, who works here, and what do we sell — and for nothing else.
-
-- **The id is a constant, never a parameter.** Every read says
- `where: { id: WORKSPACE_ID }`. The moment a function takes an
- `organizationId`, the plugin has become tenancy plumbing and the rule above
- is broken. If you are porting something from the Comp AI MVP, delete the org
- threading rather than stubbing it — an `organizationId` that is always the
- same value is a column, an index and a `where` clause that buy nothing.
-- **Signing in is the join, and there is no invite flow.**
- `ensureWorkspaceMembership` runs in `databaseHooks.session.create.before`, so
- the workspace and the caller's `Member` row exist by the time any request is
- served. `ALLOWED_SIGN_IN` already decides who may sign in; an invitation
- would be a second, quieter answer to the same question. The plugin's
- `invitation` table is created because the plugin owns its own schema — it is
- unused, and nothing in this repo writes to it.
-- **The first account is the owner; everyone after is a member.** When the
- workspace row is created the hook enrols *every user that already exists*,
- oldest first as owner — otherwise an install that predates the plugin shows
- an empty Members page until each person happens to sign in again, which looks
- identical to being broken.
-- **`ensureWorkspaceMembership` degrades, it does not throw.** A failure there
- would fail the session create, which is to say it would lock everyone out of
- the CRM to protect a settings page. It logs, returns `undefined`, and the next
- sign-in retries — the hook runs on every session, so it is self-healing.
-- **Permissions are read from one place.** `canRenameWorkspace` and
- `canChangeRole` in `@crm/auth` are what the service enforces *and* what the
- UI disables its controls on, so the button and the 403 can never disagree.
- They match the plugin's own default statements — owner and admin — rather
- than inventing a second model beside it. `WorkspaceService` adds the one
- invariant the plugin has no opinion about: **the last owner cannot be
- demoted.** It is enforced in a transaction that takes `FOR UPDATE` on the
- owner rows before counting them, because counting and then updating is two
- statements: two admins demoting the two remaining owners at the same moment
- both counted two and both wrote, and a workspace with no owner is a workspace
- nobody can rename or hand back. The lock makes the second one read the first
- one's result and refuse.
-- **Reads and writes go through tRPC, not `authClient.organization.*`.**
- Renaming the workspace is data, not authentication, so it belongs on the data
- surface with everything else — see the next rule.
-- **The name and the website are asked for once, at the door, and there is no
- skipping it.** Both fields are `required` in the form *and* in
- `updateWorkspaceInput`, so the website cannot be dropped later from the
- settings page either — a CRM that knows what we sell on Monday and not on
- Tuesday is worse than one that never knew. The gate only catches somebody who
- could *answer* it (`canRename`), so a member never meets a form they are
- forbidden to submit, and it posts the same `workspace.update` mutation as the
- settings page rather than a second write path.
-- **The state is `onboardedAt` inside the organization's `metadata`, not a
- column beside it.** The plugin ships that blob and owns the table; a second
- timestamp column is a second place the same fact is recorded, and the two
- drifted the first time somebody wrote a website through a revision of
- `WorkspaceService.update` that predated the column. A row with a name, a
- website and a null timestamp is a workspace that has plainly answered the
- question and is asked it forever. `isOnboarded` and `markOnboarded` in
- [`@crm/db/workspace`](../packages/db/src/workspace.ts) are the only readers
- and the only writer; `markOnboarded` keeps the first answer and preserves
- every other key, because the blob is the plugin's, not ours.
-- **The gate is `proxy.ts`, and it asks the server every time.** It used to
- live in `(app)/layout.tsx`, with a second, opposing redirect on the
- `/onboarding` page to stop the first one looping — two redirects pointing at
- each other is not a gate, it is a latch waiting for the two reads to
- disagree.
- - **`getSessionCookie()` decides signed-in, not a session lookup.** That is
- Better Auth's documented optimistic check for proxy, and it is all a
- redirect needs; every page behind it still resolves the real session
- server-side through `requireGoogleAccess()`.
- - **Nothing is cached in a cookie, and that is the second thing this got
- wrong.** The answers were kept in httpOnly `crm.onboarded` and
- `crm.research` markers with a year's life, on the reasoning that they
- change once in the life of an install. They do not: reset the database and
- both facts revert while the browser goes on insisting the gate was
- satisfied — so a fresh workspace was never asked to name itself and never
- asked for a key, and nothing anywhere said why. A cache with no
- invalidation is only correct for a fact that cannot go back, and neither of
- these is one.
- - **Both reads run concurrently**, so asking every time costs one round trip
- rather than two. Which question is asked *first* is still decided in order
- — a rep who has not named the workspace is sent to `/onboarding`, not to
- the key form — but there is no reason to wait for that answer before
- starting the other read.
- - **If the cost ever matters, cache it in the API**, where there is a place
- to invalidate from: `settings.setResearchKey` and `WorkspaceService.update`
- are the only two writers, and `cache-manager` is already the documented
- pattern for exactly that shape. Do not put it back in the browser.
- - **`/sign-in`, `/grant-access` and `/eve` are ungated.**
- `requireGoogleAccess()` redirects to `/grant-access`, so gating it would
- ping-pong against the onboarding redirect for anyone who signed in without
- both scopes.
- - **`/sign-in` is the only path a stranger may read**, and that list is a
- different one from the ungated paths above. `/` joins it only when
- `IS_MARKETING` is set: the landing page in `app/(landing)` markets *this*
- product, so an install that is somebody else's sends a stranger arriving at
- the root to `/sign-in` rather than to a page selling them a CRM they are
- already running. See
- [the environment rules](./environment.md#the-landing-page-is-a-flag-and-it-is-off).
- - **The flag is read per request, not captured at import.** `isMarketing()`
- in `apps/app/lib/env.ts` is a function for that reason — `proxy.ts` runs
- in the Node runtime, so the variable is a live read, and a deployment that
- changes it does not need a rebuild to be believed.
- - **It changes nothing for anyone signed in.** A rep at `/` is sent to their
- workspace by `appPath` either way, so the flag is exactly one decision:
- what a stranger at the root is shown.
- - **An unreachable API fails open.** Each read returns `unknown` on a
- non-200, a timeout or a parse failure, and an unknown gate lets the request
- through. The alternative is an install that cannot reach its own API
- redirecting every request to a form that cannot be submitted.
-- **There is a second gate behind the first**, `/onboarding/research`, which
- asks for the Context API key that gives the agent somewhere to look — see
- [the environment rules](./environment.md#the-context-key-is-asked-for-not-configured).
- It is the same shape as the onboarding gate and shares its machinery: a read
- (`settings.researchKey`), a `required`/`settled`/`unknown` answer, an httpOnly
- marker so it is asked once per browser, and fail-open on an unreachable API.
- - **The order is fixed and the second read is not made early.** A rep who has
- not named the workspace goes to `/onboarding` and `settings.researchKey` is
- never called — there is no point asking the second question while the first
- is open, and the test pins that the call count stays at zero.
- - **A settled workspace is remembered even while the key is outstanding.**
- The marker is written onto the *redirect* to the key form, so the workspace
- is not re-read on every request during the window a rep is being asked
- something else.
- - **There is no way past it but to answer, and that is the point.** It had a
- Skip, and Skip was the one path that could strand an install: every company
- added afterwards sits `PENDING` waiting for a key nobody is going to be
- asked for again, and nothing anywhere says so. A gate whose escape hatch
- silently accumulates broken records is not a gate. If it should become
- optional again, the missing piece is somewhere that surfaces *N companies
- are waiting on a key* — not a link that hides the question.
- - **Settings → General is the same write.** `settings.setResearchKey` is
- posted by both, so there is one write path and no second opinion about what
- a valid key looks like — including the check: that mutation asks the agent
- whether Context recognises the key and refuses to save one that comes back
- `401`. See
- [the environment rules](./environment.md#the-context-key-is-asked-for-not-configured)
- for why the call is the agent's to make and why a check that cannot be made
- still saves.
-- **The name arrives as a placeholder, not as an answer.** A workspace is
- created as `DEFAULT_WORKSPACE_NAME` — the literal string `CRM` — and the field
- is empty with that behind it. It used to be derived from the sign-in domain,
- which put `Trycomp` in the box as though somebody had typed it, and a guess
- presented as an answer is a guess that gets accepted.
- - **Anything printing the name beside the product name has to allow for
- that.** The header renders `<name> CRM`, so the placeholder read `CRM CRM`
- until somebody typed something else. `workspaceLabel` in
- `components/app-header.tsx` tests the name rather than comparing it to the
- default, because a workspace genuinely called `Acme CRM` has the same
- problem and no comparison to `DEFAULT_WORKSPACE_NAME` would catch it.
-- **The name is also the URL, and `workspaceSlug` is the one thing that says
- so.** The CRM is served under the workspace's slug — `/comp-ai/companies`,
- never `/companies` — which is what leaves `/` free for the landing page in
- `app/(landing)`. It is a **cosmetic** prefix and it is emphatically not the
- tenancy this file spends its first paragraphs refusing: no read takes it, no
- record carries it, and the app resolves every query through `WORKSPACE_ID`
- exactly as before. It exists so a rep reads their own company's name in the
- address bar instead of somebody's route table.
- - **The slug is the plugin's column, derived from the name.** Better Auth's
- organization plugin owns `organization.slug` and enforces its uniqueness, so
- that column is the answer and `workspace.get` returns it verbatim. What is
- derived is what gets *written*: `workspaceSlug(name)` in
- [`@crm/db/workspace`](../packages/db/src/workspace.ts) is the single rule,
- applied by `WorkspaceService.update` on a rename and at create. Deriving on
- *read* instead was the tempting shortcut and it is wrong the moment anything
- else — the plugin, a script, a future admin UI — writes the column: two
- answers to one question, and the URL a rep bookmarked disagreeing with the
- row.
- - **`ensureWorkspaceMembership` reconciles it**, in the same
- `databaseHooks.session.create.before` hook that already guarantees the
- workspace row and the caller's membership exist. That is what backfills an
- install created before the slug meant anything — its row says `workspace`
- and its name says `Comp AI` — without a migration that would restate the
- slug rule in SQL. It writes only when the two disagree, and it degrades like
- everything else in that hook.
- - **A slug never collides with a route the app serves.** `RESERVED_SLUGS`
- holds them — `sign-in`, `onboarding`, `settings`, `companies`, and the rest
- — and a name that slugifies onto one gets `-crm` appended. Without it a
- company called Settings has a CRM it cannot reach, and a static route in
- `(landing)` wins over `[slug]` silently.
- - **The proxy puts the slug on, and it is the only thing that does.** A path
- with no slug is a link that predates the move (`/companies`); a path with
- the wrong one is a stale bookmark from before a rename. Both are the same
- request with the wrong front on it, so both are redirected onto the current
- slug with the query string intact, rather than 404ing at somebody who did
- nothing wrong. `app/(app)/[slug]/layout.tsx` is the backstop and
- `notFound()`s on a mismatch the proxy could not read the slug to correct.
- - **A signed-in rep does not see the landing page.** `/` resolves to their
- workspace, which is what keeps every `callbackURL` and post-onboarding
- `redirect("/")` in the codebase correct without any of them learning what a
- slug is. There is one place to change that if the landing page should ever
- outrank the CRM: `appPath` in `proxy.ts`.
- - **Renaming moves the URL, so the form moves with it.** `workspace.update`
- returns the new slug and `workspace-form.tsx` replaces the current location
- onto it. Without that, saving a rename leaves the browser sitting on a slug
- that no longer resolves, and the next navigation 404s at the person who just
- renamed their own company.
-- **The website is the field with a consequence.** Saving it queues the agent's
- `workspace-profile` task, and what comes back is read into the opening context
- of every session the agent runs — see
- [the agent's rules](./agent.md#every-session-also-knows-who-we-are). The API
- writes the row and decides nothing about it, which is what keeps this on the
- right side of the first rule in this file.
-- **It is a hostname, and `normalizeDomain` is the one thing that says so.**
- `WorkspaceService.update` runs the field through the same helper a company's
- domain goes through (`apps/api/src/companies/domain.ts`) and rejects what
- comes back null, so the message about entering `acme.com` is now true — it
- used to strip `https://` and a trailing slash and store whatever was left,
- which meant a typed sentence was accepted, marked the workspace onboarded,
- and sent the agent to research a website that does not exist. A second
- hostname rule beside that helper would be a second answer to one question.
- The value is stored canonical (lower case, no `www.`, no path), so saving a
- website that was previously stored uncanonically counts as a *change*: the
- existing `WorkspaceProfile` stops matching and is dropped by `profileOf`, and
- the same save queues the research that replaces it. That is the intended
- order — a profile that no longer matches the website is a description of the
- company we used to be.
+The API serves HTTP, auth, tRPC and the Google sync. It does **not** research, enrich,
+score, summarise, match identities or decide anything about a person or company — not
+as a fallback, not behind a flag. That is the eve agent in `apps/agent`, which owns
+the vendor clients, the confidence model and the writes.
+
+Nest's half is to report *that something happened*: `AgentTriggerService` writes an
+`AgentTask` row. A row, not an HTTP call — the agent already leases from that table,
+so the row survives the agent being down.
+
+About to add a vendor client to `apps/api`? You want `apps/agent/agent/lib`. One
+documented exception, for timing: the exchange-rate fetcher, below.
+
+## One organization, and it is not a tenancy boundary
+
+Single tenant. No org header, no org interceptor, no org-scoped cache keys, **no
+`organizationId` on any CRM record.**
+
+A **singleton workspace** exists — Better Auth's `organization` plugin, one row with
+id `WORKSPACE_ID` (the literal `workspace`, in `@crm/db`, re-exported by `@crm/auth`
+so the agent needn't depend on it). It answers only: what are we called, who works
+here, what do we sell.
+
+- **The id is a constant, never a parameter.** A function taking an `organizationId`
+ has turned the plugin into tenancy plumbing.
+- **Signing in is the join; no invite flow.** `ensureWorkspaceMembership` runs in
+ `databaseHooks.session.create.before` and **degrades, never throws** — a throw fails
+ the session create and locks everyone out. The plugin's `invitation` table is unused.
+- **First account is owner**, and the hook enrols pre-existing users, oldest first.
+- **Permissions come from `@crm/auth`** — `canRenameWorkspace`, `canChangeRole`,
+ `canConfigureSso`, `canManageCurrency` — enforced by the service *and* used to
+ disable the UI control, so the button and the 403 cannot disagree.
+ `WorkspaceService` adds one invariant: **the last owner cannot be demoted**, with
+ `FOR UPDATE` on the owner rows before counting.
+- **Reads and writes go through tRPC**, not `authClient.organization.*`.
+- **Name and website are required at onboarding and cannot be skipped**, in the form
+ *and* in `updateWorkspaceInput`, posting the same `workspace.update` as settings.
+- **Onboarded state is `onboardedAt` inside the plugin's `metadata` blob**, not a
+ column; `isOnboarded`/`markOnboarded` (`@crm/db/workspace`) are the only accessors,
+ and `markOnboarded` preserves every other key.
+- **The name starts as `DEFAULT_WORKSPACE_NAME` (`CRM`), a placeholder not an
+ answer.** The header renders `<name> CRM`, so `workspaceLabel` tests the name rather
+ than comparing to the default.
+- **The website queues the agent's `workspace-profile` task** and goes through
+ `normalizeDomain`, rejecting null. Stored canonical, so re-saving uncanonically
+ counts as a change and re-queues research.
+
+### Gates in `proxy.ts`
+
+Onboarding, then `/onboarding/research` for the Context key. Asked server-side every
+request.
+
+- **`getSessionCookie()` decides signed-in**; pages still resolve the real session via
+ `requireGoogleAccess()`.
+- **Nothing is cached in a cookie** — both facts revert on a database reset while a
+ year-long marker insists the gate passed. Cache in the API if cost ever matters.
+- **Both reads run concurrently**, but order decides which is *asked* — the research
+ read is never made while onboarding is open.
+- **An unreachable API fails open** (`unknown` lets the request through).
+- **`/sign-in`, `/grant-access`, `/eve` are ungated.** `/sign-in` is the only path a
+ stranger may read; `/` joins it only when `IS_MARKETING` is set.
+- **There is no way past the key gate but to answer** — Skip stranded installs, every
+ later company sitting `PENDING` with nothing saying so.
+
+### The name is also the URL
+
+Served under the workspace slug (`/comp-ai/companies`). **Cosmetic, not tenancy** —
+every query still resolves through `WORKSPACE_ID`.
+
+- **The slug is the plugin's column**, written by `workspaceSlug(name)`
+ (`@crm/db/workspace`) on rename and create. **Never derive it on read.**
+- `ensureWorkspaceMembership` reconciles it; `RESERVED_SLUGS` prevents collision with
+ a real route (a collision gets `-crm`).
+- **The proxy is the only thing that puts the slug on.** Missing or stale slugs are
+ redirected with the query string intact, not 404'd; `[slug]/layout.tsx` is the
+ backstop.
+- `appPath` in `proxy.ts` is the one place `/` resolves for a signed-in rep, which
+ keeps every `callbackURL` correct without knowing about slugs.
+- **Renaming moves the URL**, so `workspace-form.tsx` replaces the location onto the
+ slug `workspace.update` returns.
## SSO is a row, not a deployment
-Google is the sign-in method a clone starts with. An install that has its own
-identity provider adds one on **Settings → SSO**, and the whole of that
-configuration is an `ssoProvider` row written by Better Auth's
-[`sso` plugin](https://www.better-auth.com/docs/plugins/sso) — not an
-environment variable, because a self-hoster's admin cannot redeploy.
-
-- **OpenID Connect only.** `apps/api/src/sso` registers a provider from an
- issuer, a client id and a client secret; everything else — the authorization,
- token, JWKS and userinfo endpoints — is read from the issuer's discovery
- document at registration time. The plugin can do SAML as well and there is
- deliberately no UI for it: SAML needs an X.509 certificate and an SP signing
- key this app has nowhere to generate or keep, and a half-configured SAML
- provider fails at the IdP with an error nobody here can read.
-- **The provider belongs to the workspace, and the id is still a constant.**
- `SsoService` passes `WORKSPACE_ID`; it is never an input. That is also what
- gives the plugin's own `sso/register` its permission check for free, and
- `canConfigureSso` in [`@crm/auth`](../packages/auth/src/sso.ts) is the second
- half — the same owner-or-admin answer the settings page disables its button
- on, beside `canRenameWorkspace`.
-- **The management surface is tRPC; signing in is not.** Listing, adding and
- removing a provider is configuration, so it goes through `sso.*` like every
- other read and write. `authClient.signIn.sso()` stays on the auth client,
- because that one *is* authentication.
-- **`sso.signInOptions` is the one public procedure in the app.** The sign-in
- page is unauthenticated and has to know what it may offer, so it returns each
- provider's id and the name to print on the button, plus whether a Google
- client is configured at all — nothing else. `sso.list` carries the issuer, the
- domains and the last four of the client id, and it — like `sso.settings`,
- `sso.register` and `sso.remove` — takes `AuthMiddleware` at the method rather
- than the router, which is what leaves `sso.signInOptions` open. A client
- secret is never read back out of any of them.
-- **It is the API's answer, not the app's.** Both processes read one `.env`, but
- `/api/auth/*` is served by the API, so whether Google sign-in works is a fact
- about *its* environment. The app asking itself would be right until the day
- the two are deployed with different configuration, and then it would offer a
- button that 500s.
-- **An install with neither says so.** No Google client and no provider is not
- an empty sign-in page: it is the one state where the reader is the person who
- can fix it, so `/sign-in` names the two variables to set. A read that *fails*
- is different and must not print that — an unreachable API is not a missing
- configuration, so the page falls back to offering Google.
-- **A configured provider replaces the Google button, it does not disable
- Google.** `/sign-in?method=google` still offers it. Hiding is the point —
- locking an admin out of their own CRM because they typed an issuer URL wrong
- is not. It only offers it when there *is* a Google client, so the escape hatch
- is never a button that cannot work.
-- **Signing in with an IdP does not cost you Gmail.** Google is two separate
- things here — a way to prove who you are, and a mailbox to read — and an
- install that replaced the first still wants the second. So Gmail and Calendar
- are a *connection* for an SSO rep, not a condition of entry: `needsGoogleGrant`
- in [`@crm/auth`](../packages/auth/src/scopes.ts) walls only an account whose
- sole sign-in row is Google, and Settings → Connections carries the button that
- links one. See [the sync rules](./environment.md#gmail-and-calendar-sync).
-- **`ALLOWED_SIGN_IN` still decides who gets in.** SSO says where someone
- authenticates; the allow-list says whether that address may have an account,
- and `databaseHooks.user.create.before` enforces it on an SSO sign-up exactly
- as it does on a Google one. Two questions, one answer each.
-- **The plugin does not do the workspace join.**
- `organizationProvisioning: { disabled: true }`, because
- `ensureWorkspaceMembership` already runs on every session create. Two things
- enrolling the same person is two things to keep in step.
-
-## tRPC is the data surface; REST is for auth and health
-
-Everything the app reads or writes goes through `nestjs-trpc` routers under
-`/api/trpc`, wired in `apps/api/src/trpc`. The remaining REST controllers are
-`/api/auth/*` (Better Auth) and `/health`.
-
-- **One router per module**, named `*.router.ts` so the codegen glob finds it,
- carrying `@Router({ alias: "…" })` and `@UseMiddlewares(AuthMiddleware)`.
- A router with no `AuthMiddleware` is public — there is no other guard.
-- **Routers are thin.** They validate input with zod and call a service; the
- Prisma work lives in `*.service.ts`, which is also where a REST controller or
- a background job would call in.
-- **Services throw Nest's `HttpException` family** (`NotFoundException`,
- `BadRequestException`, …). `DomainErrorMiddleware` maps those onto tRPC error
- codes, so a service does not need to know it is being called over tRPC.
-- **Filtering, sorting and pagination happen in Prisma.** List procedures take
- the shared `listInput` (`apps/api/src/trpc/list-input.ts`) and return
- `{ rows, total, facetCounts }`. Never return a whole table and filter in the
- browser, and never interpolate `sort` into a Prisma field name — resolve it
- through `resolveOrderBy` against the columns that module allows.
-- **The router type is generated**, not hand-written:
- `bun run --filter=api trpc:generate` writes `src/generated/server.ts`, which
- the app imports as `type { AppRouter } from "api/app-router"`. `bun run dev`
- keeps it in watch mode. If the app cannot see a new procedure, the generator
- has not run.
-- **`src/generated/server.ts` is committed, and `build` must never regenerate
- it.** The generator ships a native binary that needs GLIBC 2.39 — newer than
- Vercel's build image — so a `build` task that depends on `trpc:generate` fails
- every deploy. That is why `apps/api/.gitignore` ignores `src/generated/*` with
- a `!src/generated/server.ts` exception, and why only `check-types` and `dev`
- run the generator. Regenerate locally and commit the result with the router
- change that caused it.
+An `ssoProvider` row via Better Auth's `sso` plugin, on Settings → SSO, because a
+self-hoster's admin cannot redeploy.
+
+- **OpenID Connect only** — issuer, client id, secret; endpoints from discovery. No
+ SAML UI: it needs an X.509 cert and SP signing key we have nowhere to keep.
+- `SsoService` passes `WORKSPACE_ID`, never an input.
+- **Management is tRPC (`sso.*`); signing in is `authClient.signIn.sso()`.**
+- **`sso.signInOptions` is the one public procedure in the app.** Every other `sso.*`
+ takes `AuthMiddleware` at the *method*, which is what leaves it open. A client
+ secret is never read back out.
+- **It is the API's answer, not the app's** — the API serves `/api/auth/*`.
+- **An install with neither Google nor a provider says so**, naming the two variables;
+ a read that *fails* falls back to offering Google.
+- **A provider hides the Google button, it does not disable it** —
+ `/sign-in?method=google` still works, so a mistyped issuer cannot lock an admin out.
+- **Signing in with an IdP does not cost you Gmail.** `needsGoogleGrant` (`@crm/auth`)
+ walls only an account whose sole sign-in row is Google.
+- `ALLOWED_SIGN_IN` still decides who gets an account, in
+ `databaseHooks.user.create.before`, for SSO sign-ups too.
+- `organizationProvisioning: { disabled: true }` — `ensureWorkspaceMembership` already
+ does the join.
+
+## tRPC is the data surface; REST is auth and health only
+
+- **One router per module**, `*.router.ts` (the codegen glob), with
+ `@Router({ alias })` and `@UseMiddlewares(AuthMiddleware)`. **No `AuthMiddleware`
+ means public — there is no other guard.**
+- **Routers are thin**: zod in, service call out; Prisma lives in `*.service.ts`.
+- Services throw Nest's `HttpException` family; `DomainErrorMiddleware` maps them.
+- **Filter, sort and paginate in Prisma.** List procedures take `listInput` and return
+ `{ rows, total, facetCounts }`. Never filter a whole table in the browser; never
+ interpolate `sort` into a field name — use `resolveOrderBy`.
+- **`src/generated/server.ts` is generated *and committed*, and `build` must never
+ regenerate it** — the generator needs GLIBC 2.39, newer than Vercel's build image.
+ Only `check-types` and `dev` run it. If the app cannot see a new procedure, it has
+ not run.
## Not every address on a thread is a person
-`externalParticipants` (`apps/api/src/google/participants.ts`) is the one gate
-between what Google returns and what becomes a record, and it has to throw away
-three different kinds of thing before it gets to a lead: **us** (the allow-list
-domains and the `User` table), **a decision a rep made** (`SuppressedContact`,
-`SuppressedDomain`), and **an address no human has ever read**.
-
-The third is `isMachineAddress`, and it exists because of a company called
-`group.calendar.google.com` with one contact on it named "Interviews
-scheduled". A secondary Google calendar is invited to an event as an ordinary
-attendee — it is not flagged `resource`, the way a meeting room is — so it
-arrived with a display name and a plausible-looking domain and the sync did
-exactly what it does for a stranger at a customer: made a person, made a
-company, and queued research on both.
-
-- **A machine domain never becomes a company.** `isMachineDomain` in
- `apps/api/src/companies/domain.ts` sits beside `FREE_EMAIL_DOMAINS` because
- the two answer the same question — *is this host a company* — and
- `domainFromEmail` returns `null` for both. That is the load-bearing half:
- `companyForEmail` is the only way a company is derived from an address, so a
- caller that never heard of this rule still cannot create one.
- `.calendar.google.com` covers the shared calendars, the rooms, the imported
- ICS feeds and the holiday calendars in one entry.
-- **It matches the *host*, never a substring.** `calendar.acme.com` and
- `sendgrid.com` are somebody's real company; only the exact hosts and the
- listed suffixes are refused.
-- **An opaque local part is the second door.** `c_f5ec…@` and a bare UUID are
- identifiers, not names, and they come from providers whose infrastructure
- hostname we have not learned yet. The patterns are deliberately narrow — 24
- hex characters or a formatted UUID — because the cost of a false positive
- here is a real customer who is silently never filed.
-- **It is not a suppression, and it leaves no row.** A rep can still type any of
- these into the quick-add form; the rule is only that the *inbox* may not
- decide they are worth a record. `SuppressedContact` is for a person a rep
- deleted, and writing one for a calendar id would be recording a decision
- nobody made.
-- **The attendee list is filtered too.** `syncAttendees` drops the same
- addresses beside `attendee.resource`, so a shared calendar is not listed as
- somebody who came to the meeting.
-
-Shared inboxes and the machines that send invitations are a separate list,
-`isAutomatedAddress` — `sales@`, `noreply@`, `bookings@`. That one is about the
-*local part*, and it is the reason `[email protected]` never becomes a lead at a
-company we do genuinely sell to.
-
-## Deleting a record is a decision the sync has to respect
-
-Each of the three records can be deleted from the three-dot menu in its sheet —
-`contacts.delete`, `companies.delete`, `deals.delete`, one confirm dialog each.
-There is no soft delete and no archive: a row a rep meant to be gone that is
-still in every list, facet and count is worse than either.
-
-**A deleted contact is remembered by address.** Deleting the row is not enough,
-because the Gmail and Calendar sync creates contacts from whoever is on a thread
-— so the next message from that person put them straight back, with a fresh
-`identify` task behind them, and the rep's only recourse was to delete them
-again every few days. `ContactsService.delete` writes a `SuppressedContact` row
-keyed on the email, and `externalParticipants`
-(`apps/api/src/google/participants.ts`) drops that address exactly as it drops a
-domain in `SuppressedDomain` — one filter, one place, so the address is
-invisible to contact creation, company auto-creation and thread attribution at
-once.
-
-- **It suppresses the address, not the person.** A contact with no email cannot
- be recreated by the sync in the first place — the sync only knows people by
- address — so there is nothing to write down.
-- **The key is the address as the sync will see it: lower case.**
- `parseAddress` lower-cases everything Google hands us, so a rep who typed
- `[email protected]` into the quick-add form and then deleted the
- contact left a suppression nothing would ever match, and the next thread put
- them straight back — the exact loop the row exists to break. `normalizeEmail`
- (`apps/api/src/crm/values.ts`) is the one canonicaliser, applied where a rep's
- typing enters the system: `contacts.create`, `contacts.update` and the
- suppression written by `contacts.delete`. The conflict check on create and
- `allowAgain` both match case-insensitively so a row written before this rule
- still answers.
-- **The address is taken from the delete itself, not from a read before it.**
- `contacts.delete` runs `tx.contact.delete({ select: { email: true } })` inside
- the transaction and suppresses what comes back, so the row it writes down is
- the address the contact had at the moment it ceased to exist. A pre-check read
- is a different question asked earlier: a rep correcting the address in one tab
- while another deletes the record left the old address suppressed and the new
- one open, which is the same recreated-contact loop wearing a different hat.
- It is also what supplies the name in the `reason`, and the 404 — a missing
- contact is now the delete's own `P2025` through `translate`, rather than a
- pre-check that a concurrent delete could pass.
-- **The colleagues are untouched.** Only the deleted address is filtered, so a
- thread with three other people at that company still files against them. A
- thread where the deleted person was the *only* outsider files against nobody,
- which is the correct reading of "we do not track this person".
-- **A rep can always add them back, and doing so lifts the suppression.**
- `allowAgain` runs on `contacts.create` and on an `update` that sets the email,
- **inside the same transaction as the write**. Outside it, a database blip
- between the two left a contact the sync still ignores, and the retry hit the
- "already uses that email" conflict — a record a rep can see and cannot fix.
- The rule is *not added back automatically* — somebody typing the address in is
- not the inbox making the decision for them.
-- **Deleting a company does not suppress its domain.** Its people survive the
- delete with no company, and a domain-wide suppression would silently stop
- filing their email too. Turning off a whole domain stays the explicit control
- on Settings → Connections, where it says what it does.
-
-**What the database does not cascade, the service does.** `AgentTask` and
-`AgentEvent` carry a `contactId` and a `companyId` as plain columns with no
-foreign key — they outlive the records they name on purpose, so the queue
-survives a redeploy — which means a delete has to clear them itself. Leaving
-them behind queues research about a person who no longer exists, and the
-dispatcher spends a session finding that out.
-
-**The stamps are then recomputed on the records the delete actually reached,
-and no others.** Deleting a record deletes its activities, and `lastActivityAt`
-on whatever else those activities touched is a cached maximum that nothing else
-recomputes — a company whose only recent activity was on a deleted deal would
-sort as though the work were still fresh, forever.
-
-- **The affected set is read before the rows go, inside the delete's own
- transaction.** `ActivityStampService.targetsOf(where)` groups the activities a
- delete is about to destroy by each of their three foreign keys and hands back
- the ids; `recomputeMany` restamps exactly those rows, one `UPDATE … SET
- lastActivityAt = (SELECT MAX(…))` per table, which covers "has newer
- activities" and "has none left, so null" in the same statement. Reading it
- after the delete is not an option — the evidence is what was deleted.
-- **A company's `where` follows the deals it takes with it**, `{ OR: [{
- companyId }, { deal: { companyId } }] }`. Deleting a company cascades to its
- deals and those cascade to their activities, so a surviving contact whose only
- activity hung off one of those deals would keep a stamp for work that no
- longer exists. `test/record-delete.spec.ts` pins that branch specifically.
-- **`recomputeAll()` is still there and is still right for a purge.** It rebuilds
- every stamp in the CRM with six full-table statements, which is what
- disconnecting Google and dropping everything it synced needs. It is the wrong
- tool for deleting one record: it made the cost of removing a contact a
- function of the size of the entire CRM, and it repaired rows the rep's action
- never touched.
-
-**Recomputing runs after the delete has committed, so it logs rather than
-throws.** The
-row is already gone by the time the stamps are rebuilt; letting that failure out
-reports a completed destructive action as a failure, the browser never
-invalidates its caches, and the rep's retry answers `No contact with id …`. A
-stale sort order is a smaller wrong than that, and the next delete or
-reconnection recomputes it. The delete itself is still translated: a record
-removed between the pre-check and the delete is the documented 404, not a P2025
-escaping as a 500.
+`externalParticipants` (`google/participants.ts`) is the one gate, discarding **us**
+(allow-list domains, `User` table), **rep decisions** (`SuppressedContact`,
+`SuppressedDomain`), and **addresses no human reads**.
+
+- **`isMachineDomain` (`companies/domain.ts`) sits beside `FREE_EMAIL_DOMAINS`**;
+ `domainFromEmail` returns null for both, and `companyForEmail` is the only path from
+ address to company — so a caller ignorant of the rule still cannot create one.
+ `.calendar.google.com` covers shared calendars, rooms and ICS feeds.
+- **Matches the host, never a substring** — `calendar.acme.com` is a real company.
+- **`isMachineAddress` also catches opaque local parts** (24 hex chars, UUIDs),
+ deliberately narrow: a false positive is a real customer never filed.
+- **It leaves no row** — a rep may still type these into quick-add; only the *inbox*
+ is barred from deciding. `syncAttendees` filters the same addresses beside
+ `attendee.resource`.
+- **`isAutomatedAddress` is a separate list about the local part** (`sales@`,
+ `noreply@`), which is why `[email protected]` never becomes a lead.
+
+## Deleting a record
+
+`contacts.delete`, `companies.delete`, `deals.delete`. No soft delete, no archive.
+
+- **A deleted contact is suppressed by address**, or the sync recreates them from the
+ next thread. `ContactsService.delete` writes `SuppressedContact`, and
+ `externalParticipants` drops it like a `SuppressedDomain` — one filter covering
+ contact creation, company auto-creation and attribution.
+- **Keyed lower case.** `normalizeEmail` (`crm/values.ts`) is the one canonicaliser,
+ on `contacts.create`, `.update` and the suppression; conflict checks and `allowAgain`
+ match case-insensitively.
+- **The address comes from the delete itself**
+ (`tx.contact.delete({ select: { email: true } })`), not a read before it — and the
+ 404 is that statement's own `P2025` through `translate`.
+- **Adding them back lifts the suppression** via `allowAgain` **inside the write's
+ transaction**. Never automatic.
+- **Deleting a company does not suppress its domain** — its people survive with no
+ company, and domain suppression stays the explicit Settings → Connections control.
+- **Clear `AgentTask` and `AgentEvent` yourself** — they carry `contactId`/`companyId`
+ with no foreign key, so nothing cascades.
+- **Recompute `lastActivityAt` on exactly the records the delete reached.**
+ `ActivityStampService.targetsOf(where)` collects them *inside* the transaction (the
+ evidence is what gets deleted); `recomputeMany` restamps. A company's `where` must
+ follow its deals: `{ OR: [{ companyId }, { deal: { companyId } }] }`.
+ `recomputeAll()` is for a purge only.
+- **Recompute after commit, logging rather than throwing** — the row is already gone,
+ and a raised error makes the browser skip invalidation and retry into a 404.
## A deal is sold in one currency and reported in another
-A deal has always carried a `currency`, and every place that printed *one* deal
-honoured it. What did not was every place that printed a **total**: `_sum:
-{ amount: true }` added the decimals column across whatever currencies happened
-to be in the rows, and the dashboard then rendered the result through
-`formatMoneyCompact(cents)` with no currency argument at all — which defaults to
-`usd`. A €1M deal beside a $1M deal read **`$2.0M`**. Nothing errored, nothing
-logged, and the number was wrong in the one direction a sales dashboard is never
-questioned in.
-
-So there are now two amounts on a deal, and only one of them is ever summed.
-
-- **`amount` + `currency` is what the customer is paying.** It is what a rep
- types, what the deal sheet shows, and it is never converted in place.
-- **`baseAmount` is that figure in the workspace's reporting currency, and it is
- the only column any total, chart, average or sort may touch.** `fxRate` and
- `fxRateAt` sit beside it saying how it got there, so a quarter's number can be
- explained a year later.
-- **`baseCurrency` says which currency `baseAmount` is denominated in, and
- without it the invariant is unprovable.** Re-rating is a read of the distinct
- currencies followed by an `UPDATE` per currency — not one atomic statement — so
- a deal written concurrently with a reporting-currency change can commit a
- figure converted against the *old* base. Nothing about the row said so: a
- number with no currency attached cannot be told apart from a correct one, and
- it would have sat in the pipeline total forever.
- - **Every money aggregate filters on it**, through `countedWhere(base)`. A row
- whose `baseCurrency` is not the current one is excluded rather than summed,
- which is what stops the wrong figure being reported for the window before
- anything fixes it. Counts are deliberately *not* filtered — a deal with no
- amount is still an open deal — so the stage groups read their counts from one
- query and their sums from another.
- - **`pendingWhere(base)` is the other half**: null `baseAmount` *or* a
- `baseCurrency` that is not the current one. It is what `unconverted` reports
- and what `fillMissing()` repairs, so the daily cron heals a straggler and the
- disclosure and the totals never disagree about which rows were counted.
- - **It is composed with `AND`, never spread.** `pendingWhere` contains an `OR`,
- and the deals list's own `where` already carries one from the search filter —
- spreading the two would silently drop the caller's search.
- - **`pendingWhere` matches a null `baseCurrency` explicitly**, and leaving that
- clause out was a hole rather than a rounding error. `{ baseCurrency: { not:
- base } }` compiles to `baseCurrency <> 'USD'`, which is `NULL` — not true —
- for a row where the column is null. So a row carrying a `baseAmount` with no
- currency beside it was excluded from every total by `countedWhere` *and*
- invisible to the disclosure: it did not appear anywhere, and nothing would
- ever repair it.
- - **Anything that writes `baseAmount` writes `baseCurrency` in the same
- statement.** `ConversionService` is the only writer in the app, but
- `packages/db/prisma/seed.ts` is a second one, and it was setting the amount
- and not the currency — so a freshly seeded clone had twenty-three deals with
- converted figures and a pipeline of zero. The seed also converts at an
- identity rate when a deal is already in the reporting currency, which needs
- no rate table at all; only a genuine cross-currency deal under a non-USD base
- is left for the cron.
-
-**The rate is resolved once, at the moment the amount is set, and then frozen.**
-`DealsService.create` and `.update` call `ConversionService.dealFields` whenever
-`amount` *or* `currency` changes — and an update that changes only one of them
-reads the other back inside the same call, because converting a new amount
-against a stale currency is how you get a figure that matches neither. Freezing
-is the point: rates move daily, and a closed-won quarter that changes value
-every morning is not a report. Converting on read was the simpler schema and it
-is wrong for exactly that reason.
-
-- **A missing rate is a null, and a null is disclosed rather than counted as
- zero.** `baseAmount` stays null when nothing can convert the currency, which
- keeps it out of every `_sum` automatically — and `ConversionService.unconverted`
- counts those rows so the dashboard, the deals list and the company sheet can
- say *3 deals in CHF are not included*. A total that silently drops rows is the
- same class of bug as the one above, wearing a nicer hat.
-- **The work is recovered from the record, not held in a queue.** A deal written
- with no rate is not retried by anything; it is simply a row with a null
- `baseAmount`, which is what `fillMissing()` looks for the moment a rate
- arrives — from the cron or from somebody typing one in. Same shape as a
- `PENDING` company waiting on a research key.
-- **`fillMissing()` never touches a deal that already converted**, which is what
- keeps the freeze true when the daily cron brings in new rates.
- `rerateAll()` is the one thing that overwrites a locked rate, and it runs only
- when the reporting currency changes — because at that point every stored
- `baseAmount` is denominated in a currency the workspace no longer reports in,
- so leaving them would be worse than moving them. Settings says so before you
- change it.
-
-**Rates live in `ExchangeRate`, and `rate` means one thing only: how many units
-of `baseCurrency` one unit of `quoteCurrency` buys.** So `baseAmount = amount ×
-rate`, in that direction, everywhere. The public feed quotes the opposite way (1
-USD = 0.8655 EUR), so `RatesService` inverts on ingest rather than at every
-call site — one place to be wrong instead of six.
-
-- **Two sources, and by-hand wins.** The unique key is
- `(baseCurrency, quoteCurrency, source)`, so a `FETCHED` row and a `MANUAL` row
- coexist and `resolveRate` prefers the manual one. That is what makes the
- fetcher optional rather than load-bearing: an install behind a firewall, or
- one dealing in a currency the ECB does not publish, types its own rates on
- **Settings → Currencies** and everything downstream is identical.
-- **`resolveRate` refuses a rate of zero or less** instead of converting with
- it. A `baseAmount` of 0 is indistinguishable from a free deal.
-- **Re-rating groups by the raw column and then works in normalised codes.**
- `currency` was free text once, so ` usd ` and `USD` are two groups that mean
- one currency — and each pass matches on `upper(btrim(...))`, so every pass
- updated every variant. The counts came back multiples too high (80 rows
- reported for 28) and the same rows were written repeatedly. The codes are
- deduplicated through a `Set` before any rate is resolved.
-- **An amount has an upper bound, and it is the column's.** `MAX_AMOUNT_CENTS`
- in `deals.contracts.ts` is what `Decimal(14, 2)` can hold; without it a large
- enough amount failed as a Postgres numeric overflow — a 500 on input that
- passed validation. `baseAmount` is `Decimal(24, 4)` rather than `(18, 4)` for
- the same reason from the other direction: the *product* of a legal amount and
- a legal rate has to fit.
-- **The reporting currency is a row, not a variable** —
- `AppSetting.reportingCurrency`, read through `readReportingCurrency` in
- [`@crm/db/settings`](../packages/db/src/settings.ts), which is the only reader
- and falls back to `DEFAULT_REPORTING_CURRENCY`. Same reasoning as the agent's
- model and the Context key: an admin who cannot redeploy has to be able to
- change it.
-- **A currency code is validated against a list, not a regex.**
- `isCurrencyCode` in [`@crm/db/currency`](../packages/db/src/currency.ts) is the
- gate, and it is what `deals.contracts.ts` refines on. `z.string().length(3)`
- accepted `ZZZ`, which is well-formed enough that `Intl` renders it happily as
- `ZZZ 1,234.50` and nothing can ever convert it. Shape and membership are two
- different questions and the module answers both separately —
- `isWellFormedCurrency` exists because `Intl.NumberFormat` throws a
- `RangeError` on anything that is not three letters, so a *formatter* has to
- check shape even where membership is not its business.
-- **`CURRENCIES` is ten currencies, and that is the whole of what this CRM
- supports.** The world's ten most-traded — USD, EUR, JPY, GBP, CNY, AUD, CAD,
- CHF, HKD, SGD — in that order, and the pickers render it in array order rather
- than alphabetically so the answer is usually the first or second row. It
- started as fifty-three, which is a scroll bar in front of a decision that is
- `USD` nine times out of ten.
- - **Supported means supported everywhere**, and `isCurrencyCode` is the single
- gate: it is what `deals.contracts.ts` refines on, what `RatesService` filters
- the feed through, and what `readReportingCurrency` requires of a stored
- value. Offering ten and converting a hundred and sixty-five was two answers
- to one question — the picker said one thing and the rate table another.
- - **Everything offered is therefore convertible.** The feed covers all ten, so
- choosing from a picker cannot produce the unconverted deal the disclosure
- above exists to explain. That disclosure stays, because two things can still
- reach it: a row written before the list shrank, and a reporting-currency
- change made while the feed is unreachable.
- - **A refresh prunes as well as writes**, deleting `FETCHED` rows for the
- current base whose quote currency is not in the ten. Without that, an install
- that ran the old code keeps a hundred and fifty-six rates nothing will ever
- refresh, and a legacy deal stays convertible at a frozen number — which is
- the split this rule just removed, surviving in the data. It leaves `MANUAL`
- rows alone: a rate a person typed is not ours to delete, and the form can no
- longer create one outside the ten anyway.
- - **A deal in an unsupported currency is disclosed, not hidden.** Its
- `baseAmount` goes null on the next re-rate, which takes it out of every total
- and puts it in `unconverted` — so the dashboard says *N deals in SEK are not
- included* rather than quietly counting or quietly dropping them. Editing such
- a deal's currency is the fix, and the picker offers only the ten.
- - **There is no three-decimal currency left in the ten**, so the KWD caveat
- below is now only about a legacy row rather than anything a rep can enter.
-- **`minorUnitsOf` is why conversion rounds correctly.** JPY has no decimal
- places and KWD has three; `applyRate` rounds to the *reporting* currency's
- own units rather than to two. The `×100` cents transport across tRPC is
- untouched and still round-trips, because it is a scaling convention and not a
- claim about decimals — but note it cannot represent a three-decimal currency's
- minor unit, and neither can `Decimal(14, 2)`. A KWD deal is stored to the
- fils, not the fils-tenth.
-
-**One feed, keyless: `open.er-api.com`.** It answers
-`GET /v6/latest/{BASE}` with `{ result, base_code, time_last_update_unix, rates }`
-and needs no account, which is what keeps it out of `.env` entirely.
-
-- **It replaced `api.frankfurter.dev`, for coverage as much as uptime.**
- Frankfurter is ECB-backed and publishes 29 currencies and — the part that
- actually bit — could not be asked for a base outside its own set, so a
- workspace reporting in a currency it does not quote got nothing at all. It was
- also timing out intermittently on an 8-second budget. The replacement quotes
- 166 and accepts any of them as the base, which covers all ten of ours with
- room for the list to grow.
-- **`result` is checked, not just the status code.** An unsupported base comes
- back **HTTP 200** with `{"result":"error","error-type":"unsupported-code"}`, so
- `response.ok` alone would read a refusal as success, find no `rates`, and log
- the misleading "carried no usable rates" instead of the reason the provider
- gave.
-- **Two attempts, 6 seconds each.** The failure that prompted this was a
- transient timeout on a single try, and one retry costs a few hundred
- milliseconds against a request that normally answers in under 150ms. The
- ceiling stays low enough for the interactive Refresh button on the settings
- page to be worth pressing.
-
-**Changing how money is reported is an owner-or-admin action.** `canManageCurrency`
-in [`@crm/auth`](../packages/auth/src/organization.ts) sits beside
-`canRenameWorkspace` and `canConfigureSso` and answers the same way, and
-`CurrencyService` enforces it on every mutation while `settings` returns
-`canManage` so the page disables the controls it would refuse — the button and
-the 403 cannot disagree. `AuthMiddleware` alone was not enough here: it proves
-who is asking, and this router can re-rate every deal in the CRM, which is not
-something any member should be able to do to everyone else's numbers.
-
-**The fetcher is in the API, and that is a deliberate exception to the rule at
-the top of this file.** A daily rate is not intelligence: it decides nothing
-about a person or a company, there is no confidence model, no identity to match
-and no judgement to drift. It is the same category as `FaviconService`, which
-also makes an outbound request from Nest. The load-bearing reason is timing —
-`DealsService` needs a rate *synchronously* to write `baseAmount` in the same
-transaction as the amount, and routing that through the agent's task queue would
-make a rep's pipeline total wrong for the seconds it took a session to start. If
-this ever grows a judgement — deciding *which* provider to trust, or whether a
-rate looks wrong — that part belongs in `apps/agent`.
-
-- **`POST /internal/sync/rates`** is the cron entry, guarded by `CRON_SECRET`
- through the same `timingSafeEquals` check as the Google sync, and it **fails
- closed when the secret is unset**. It refreshes and then calls
- `fillMissing()`, so one daily hit both updates the rates and rescues the deals
- that were waiting on them.
-- **A route is not a schedule.** `apps/api/vercel.json` is what actually makes
- either cron run, and it had been deleted — so the Gmail and Calendar sync had
- not been firing on Vercel either, while this file went on documenting a
- `*/5 * * * *` entry that no longer existed. Adding an internal route means
- adding it there in the same change; nothing else in the repo will tell you it
- is dead.
-- **An unreachable provider is not an error.** `RatesService.refresh` warns and
- returns `{ ok: false }`; nothing throws, no deal changes, and the manual rates
- keep working. Only the *interactive* refresh on the settings page turns that
- into a `BadRequestException`, because there a person is standing there waiting
- to be told.
+Two amounts, and only one is ever summed. (`_sum: { amount: true }` once added euros
+to dollars and printed `$2.0M`, silently.)
+
+- **`amount` + `currency`** is what the customer pays. Never converted in place.
+- **`baseAmount` is the only column any total, chart, average or sort may touch**;
+ `fxRate`/`fxRateAt` record how it got there.
+- **`baseCurrency` says what `baseAmount` is denominated in** — without it a figure
+ converted against a stale base is indistinguishable from a correct one.
+ - **`countedWhere(base)` filters every money aggregate.** Counts are deliberately
+ *not* filtered, so stage groups read counts and sums from separate queries.
+ - **`pendingWhere(base)`** = null `baseAmount` *or* wrong `baseCurrency`, and it
+ **matches null explicitly** — `{ not: base }` is `NULL`, not true, for a null
+ column, so such rows were invisible everywhere.
+ - **Compose with `AND`, never spread** — it contains an `OR`, and so does the deals
+ list's own `where`.
+ - **Every writer of `baseAmount` writes `baseCurrency` in the same statement**:
+ `ConversionService` and `prisma/seed.ts`.
+- **The rate is resolved once and frozen.** `create`/`update` call
+ `ConversionService.dealFields` when `amount` *or* `currency` changes, reading the
+ unchanged one back in the same call. Converting on read makes a closed quarter change
+ value every morning.
+- **A missing rate is a null, disclosed not zeroed** — it falls out of `_sum`
+ automatically, and `unconverted` counts those rows so the UI can say *3 deals in CHF
+ are not included*.
+- **`fillMissing()` never touches a converted deal**; `rerateAll()` is the only thing
+ that overwrites a frozen rate, and only on a reporting-currency change.
+
+**`ExchangeRate.rate` = units of `baseCurrency` per unit of `quoteCurrency`**, so
+`baseAmount = amount × rate` everywhere. The feed quotes the other way; `RatesService`
+inverts on ingest.
+
+- **`MANUAL` beats `FETCHED`** (unique on `(base, quote, source)`), which makes the
+ fetcher optional — Settings → Currencies is the manual path. `resolveRate` refuses a
+ rate ≤ 0.
+- **Re-rating deduplicates codes through a `Set`** — `currency` was free text, so
+ ` usd ` and `USD` were two groups each updating every variant.
+- **`MAX_AMOUNT_CENTS`** (`deals.contracts.ts`) is what `Decimal(14, 2)` holds;
+ `baseAmount` is `Decimal(24, 4)` so amount × rate still fits.
+- **Reporting currency is `AppSetting.reportingCurrency`**, read only through
+ `readReportingCurrency`.
+- **Codes are validated against `isCurrencyCode` (`@crm/db/currency`), not a regex** —
+ `z.string().length(3)` accepted `ZZZ`. `isWellFormedCurrency` is separate because
+ `Intl` throws on non-three-letter input.
+- **`CURRENCIES` is ten currencies and that is all this CRM supports** — USD, EUR, JPY,
+ GBP, CNY, AUD, CAD, CHF, HKD, SGD, in array order. `isCurrencyCode` is the single
+ gate for the picker, the feed filter and the stored setting. A refresh **prunes**
+ `FETCHED` rows outside the ten and leaves `MANUAL` alone.
+- **`applyRate` rounds to the *reporting* currency's `minorUnitsOf`**, not to two. The
+ ×100 cents transport cannot represent a three-decimal minor unit; nor can
+ `Decimal(14, 2)`.
+
+**Feed: `open.er-api.com`, keyless**, two attempts at 6s. **Check `result`, not just
+the status** — an unsupported base returns HTTP 200 with `{"result":"error"}`. An
+unreachable provider warns and returns `{ ok: false }`; only the interactive refresh
+throws.
+
+**The fetcher is in the API deliberately**: a daily rate decides nothing, and
+`DealsService` needs it *synchronously* to write `baseAmount` in the same transaction.
+Any judgement about it belongs in `apps/agent`.
+
+`POST /internal/sync/rates` is guarded by `CRON_SECRET` (`timingSafeEquals`) and
+**fails closed when unset**. **A route is not a schedule** — add it to
+`apps/api/vercel.json` in the same change or nothing runs it.
## Freshness: invalidate the query, don't disable the cache
-There is no HTTP response cache in front of tRPC. Freshness is TanStack Query's
-job: a mutation invalidates the query keys it affected, and the list refetches.
-
-- **Invalidate on the client, in the mutation's `onSuccess`** — but **through
- `useCrmCache()`** (`apps/app/lib/trpc/cache.ts`), not by listing keys at the
- call site. Say *what changed* (`cache.deal(id)`, `cache.company(id)`,
- `cache.contact(id)`, `cache.activity()`) and the module owns the fan-out. Twelve
- hand-written key lists is how they drifted: a stage change did not refresh the
- timeline entry it writes, creating a deal did not refresh the board, and nothing
- refreshed the overview, so a rep could close a deal and watch their own numbers
- not move. **A new mutation adds a call there, not a new list of keys.**
-- **A deletion is `cache.removed(ref)`, and it is the one call that skips a
- key.** Everything a deletion can reach is refreshed together — the lists, the
- timeline, the dashboard, and the other records that named this one, since a
- colleague list and a deal's attendees both go stale the moment a contact goes.
- The deleted record's *own* `byId` entry is invalidated with
- `refetchType: "none"`, which is the one place that option is right: its query
- is still mounted for the moment it takes the sheet to animate shut, so a
- refetch asks the API for a row that no longer exists and the sheet reads the
- 404 as "this record could not be loaded" on its way out. Marking it stale
- without refetching keeps the closing sheet quiet *and* stops the entry being
- served from cache — `staleTime` is 30 seconds, so leaving it untouched meant a
- rep who reopened the record from a stale link or the back button read half a
- minute of a record that no longer exists. One wide fan-out is right here
- because deleting is rare and touches more than any edit does.
-- **Pass `{ settle: "record" }`** when the caller is an inline editor. The
- default waits for every affected view to refetch, which is right when the point
- of the action *is* the view changing (a card moving between board columns);
- `"record"` waits only for the edited record so the field's spinner clears as
- soon as the value under it is right, and lets the table behind the sheet catch
- up on its own.
-- **An infinite query needs `pathKey()`, not `queryKey()`.** tRPC stamps the
- query type into the key, so `queryKey()` yields `{ type: "query" }` and
- `infiniteQueryOptions` caches under `{ type: "infinite" }` — the two cannot
- partially match, and invalidating with the wrong one is silent: it reports
- success, refetches the sibling non-infinite queries, and leaves the infinite
- one stale until a reload. `pathKey()` carries no type and matches both, which
- is what you want whenever a procedure is read both ways (`activities.timeline`
- is, as a paged history and as a pinned top-ten).
-- **`cache-manager` is still there** (`apps/api/src/cache`, Redis when
- `REDIS_URL` is set) but it is used deliberately, per value, by services that
- want it — `AuthService.getProfile` is the model: read through, write on miss,
- and an explicit `invalidateProfile` on change. It is not a global interceptor,
- so nothing is cached unless a service asks for it.
-- **Background writes the browser cannot see** — enrichment finishing, most
- obviously — are not invalidations at all, because no client action caused
- them. Poll for those: `refetchInterval` while the record's status is
- `PENDING`/`RUNNING`, and stop once it settles. Use `isEnriching()` and
- `ENRICHMENT_POLL_MS` from `components/crm/enrichment-status` so the rule is one
- definition. **A list polls too, not just the record sheet** — the company sheet
- polled and the companies table did not, so a newly added company's logo and
- industry appeared in the sheet and stayed blank in the table behind it until a
- reload.
+- **Invalidate in `onSuccess` through `useCrmCache()`** (`lib/trpc/cache.ts`), never by
+ listing keys at the call site. Say what changed — `cache.deal(id)`,
+ `cache.company(id)`, `cache.contact(id)`, `cache.activity()`. **A new mutation adds a
+ call there, not a new list of keys.**
+- **A deletion is `cache.removed(ref)`** — one wide fan-out, and the only place
+ `refetchType: "none"` is right: the deleted record's `byId` query is still mounted
+ while the sheet animates shut, so refetching reads a 404 into the closing sheet,
+ while leaving it alone serves 30s of a dead record from cache.
+- **`{ settle: "record" }`** for inline editors, so the field's spinner clears without
+ waiting for the table.
+- **Infinite queries need `pathKey()`, not `queryKey()`** — the latter stamps
+ `{ type: "query" }` and silently cannot match `{ type: "infinite" }`.
+ `activities.timeline` is read both ways.
+- **`cache-manager` is per-value and opt-in**, not an interceptor;
+ `AuthService.getProfile` is the model.
+- **Background writes need polling, not invalidation** — `refetchInterval` while
+ `PENDING`/`RUNNING`, via `isEnriching()` and `ENRICHMENT_POLL_MS`. **Lists poll too,
+ not just the sheet.**
diff --git a/docs/environment.md b/docs/environment.md
index 9fecc019..df3c0ad9 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -1,446 +1,147 @@
# Environment
-## One `.env`, at the root of the repo
+Setup, local dev and the `vercel env pull` hazard are in `docs/setup.md`.
-Copy [`.env.example`](../.env.example) to `.env` and fill in the five required
-values. That file is the documentation — every variable the repo reads is in it,
-with a note on what it does, and nothing that is not read is in it.
+## One `.env`, at the repo root
-```sh
-cp .env.example .env
-```
+`.env.example` **is the documentation** — every variable the repo reads, with a note,
+and nothing that is not read. `packages/env` walks up to the workspace root and reads
+`.env`, then `.env.local` on top.
-It is loaded by [`packages/env`](../packages/env), which walks up from the
-process's working directory to the workspace root and reads `.env`, then
-`.env.local` on top. Every process gets there:
+- **Real environment variables always win** — the loader never overwrites
+ `process.env`, so Vercel/Docker/CI takes precedence.
+- **Never add a per-package `.env`.** Four once existed with duplicate
+ `DATABASE_URL`/`BETTER_AUTH_SECRET`; when they drifted the API minted a cookie the
+ app could not verify and the browser bounced between `/sign-in` and `/` forever.
+- **The root marker is a `package.json` declaring `workspaces`** — stopping at the
+ first `turbo.json` resolves the API's root to `apps/api`.
-| Process | How it picks the file up |
-| --- | --- |
-| The NestJS API | `@crm/db` and `@crm/auth` both `import "@crm/env/load"` before reading anything |
-| The Next.js app | `next.config.ts` calls `loadRootEnv()`, then republishes `API_URL` as `NEXT_PUBLIC_API_URL` |
-| The agent | `agent/agent.ts` and `@crm/db` |
-| The Prisma CLI | `packages/db/prisma.config.ts` |
-
-**Real environment variables always win.** The loader never overwrites a value
-already present in `process.env`, so a platform's own configuration — Vercel,
-Docker, systemd, CI — takes precedence and the file is purely a local
-convenience. With no `.env` at all the loader is a no-op and each consumer
-reports by name what it is missing.
-
-There used to be four files (`apps/api/.env`, `apps/app/.env`,
-`packages/db/.env`, `apps/agent/.env`), three of which had to hold identical
-copies of `DATABASE_URL` and `BETTER_AUTH_SECRET`. Files that must agree are
-files that can disagree, and the failure was not an error: the API would mint a
-session cookie the app could not verify, so the browser bounced between
-`/sign-in` and `/` forever. If you still have those files from an older
-checkout, delete them.
-
-### Finding the root
-
-The marker is a `package.json` that declares `workspaces` — the one thing only
-the root has. Neither obvious alternative works: every package has a
-`package.json`, and `apps/api` and `apps/agent` have their own `turbo.json`. A
-walk that stops at the first `turbo.json` resolves the API's root to
-`apps/api`, reads a file that is not there, and the symptom surfaces three
-frames away as a missing variable. `packages/env/test/root.spec.ts` pins this.
-
-## What is required
-
-Three values, and the API refuses to start without them.
-
-| Variable | Why it has no default |
-| --- | --- |
-| `DATABASE_URL` | `docker compose up -d` starts a Postgres that matches `.env.example` exactly |
-| `BETTER_AUTH_SECRET` | Signs session cookies. `openssl rand -base64 32` |
-| `ALLOWED_SIGN_IN` | The entire authorisation model — see below |
-
-Everything else has a working localhost default or is genuinely optional. That
-is the difference between a clone that runs and a clone that makes you read a
-table of variables first.
-
-### Google is the fourth value, and it is a pair
-
-`GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are what a clone starts with, and
-almost every install wants them: they are both the sign-in button and the Gmail
-and Calendar sync. They are nonetheless **optional**, because an install that
-signs in through [its own identity provider](./api.md#sso-is-a-row-not-a-deployment)
-should not have to create a Google Cloud project to do it.
-
-- **They are set together or not at all.** `packages/auth/src/env.ts` throws on
- one without the other, because half a client is a sign-in button that fails at
- Google with an error the reader cannot act on.
-- **Neither Google nor a provider is a state the sign-in page reports**, naming
- the two variables — see [the SSO rules](./api.md#sso-is-a-row-not-a-deployment).
- It is the one configuration mistake whose audience is the person who can fix
- it, so it must not present as a blank page.
-- **Without them, Gmail sync is a capability the install does not have**, and
- Settings → Connections says so rather than offering a button that cannot work.
-
-### `ALLOWED_SIGN_IN`
-
-Who may sign in, comma-separated, each entry either a whole email domain or a
-single address:
-
-```sh
-ALLOWED_SIGN_IN="acme.com" # everyone at a workspace
-ALLOWED_SIGN_IN="acme.com,[email protected]" # …plus one outsider
-ALLOWED_SIGN_IN="[email protected]" # a one-person install
-```
-
-Bare addresses exist for the third case: a solo self-hoster on a consumer
-mailbox has no domain to name, and `gmail.com` would be an open door.
-
-One list, read by two things that must never disagree — the sign-in guard and
-the sync's decision about which side of a conversation is external. If they
-drifted, a colleague's address would either be refused at the door or filed as
-a sales lead.
-
-**An empty list fails closed**: nobody signs in until it is set. The other
-choice would be a CRM full of real customer data that any Google account can
-read, and it would look like it was working. It is parsed on demand rather than
-at import, so the Better Auth CLI — which loads `auth.ts` in a process with no
-`.env` — and the tests can both set it themselves.
-
-Live in `packages/auth/src/workspace.ts`.
-
-## The landing page is a flag, and it is off
-
-`IS_MARKETING="true"` serves the landing page in `app/(landing)` at `/`.
-Anything else — unset, empty, `false`, `1` — and a signed-out visitor to the
-root is redirected to `/sign-in`.
-
-It defaults to off because the page markets *this* product. A clone serving it
-is telling a stranger about a CRM that stranger is already running, under
-somebody else's name; and on an internal install there is no stranger to tell,
-only a rep who signed out and wants the sign-in box.
-
-- **Only the literal `true` turns it on**, which is the same shape as
- `PRISMA_LOG_QUERIES`. A flag with several truthy spellings is a flag that is
- set and not working.
-- **It decides one thing: what a stranger at `/` is shown.** Anyone signed in is
- sent to their workspace by the proxy either way, and no other route changes —
- the landing page's own components are still built and still reachable from a
- deploy that sets the flag.
-- **The read is live.** `isMarketing()` in `apps/app/lib/env.ts` reads
- `process.env` per request rather than at import: `proxy.ts` runs in Next's
- Node runtime, so the value comes from the environment the server is running
- in, not from the one it was built in. Declared in `apps/app/turbo.json` under
- `passThroughEnv` for both `dev` and `build`, because Turbo runs in strict env
- mode.
-
-See [the proxy rules](./api.md#there-is-exactly-one-organization-and-it-is-not-a-tenancy-boundary)
-for where it sits among the other gates.
+## Required
+
+`DATABASE_URL`, `BETTER_AUTH_SECRET`, `ALLOWED_SIGN_IN`. Everything else has a
+localhost default or is genuinely optional.
+
+**`GOOGLE_CLIENT_ID` + `GOOGLE_CLIENT_SECRET`** are the sign-in button *and* the
+Gmail/Calendar sync — optional, so an SSO-only install needn't create a Google project,
+but **set together or not at all** (`packages/auth/src/env.ts` throws on one).
+
+**`ALLOWED_SIGN_IN`** — comma-separated whole domains or single addresses. Bare
+addresses exist for a solo self-hoster where `gmail.com` would be an open door. **One
+list, read by the sign-in guard *and* the sync's "which side is external" decision** —
+if they drifted a colleague would be refused at the door or filed as a lead. **An empty
+list fails closed.** Parsed on demand, not at import.
+`packages/auth/src/workspace.ts`.
## Where things are
-`API_URL` and `APP_URL` default to `http://localhost:3001` and
-`http://localhost:3000`. Set them for any real deployment.
-
-- **`API_URL`** is the origin that mints session cookies and serves
- `/api/auth/*`. `next.config.ts` republishes it as `NEXT_PUBLIC_API_URL`, which
- is what the browser's auth client and tRPC proxy use — so one variable
- configures both sides. `BETTER_AUTH_URL` is still read as a fallback because
- Better Auth's own tooling looks for it, but `API_URL` is the name to use.
-- **`APP_URL`** is where the browser is, and it is also the trusted-origin
- allow-list: the set of origins allowed to call the API with credentials, and
- the list Better Auth validates post-sign-in `callbackURL`s against.
- Comma-separate if the app is genuinely served from more than one origin; the
- first is canonical. This replaced a separate `AUTH_TRUSTED_ORIGINS`, which
- could only ever disagree with it.
-- **`AUTH_COOKIE_DOMAIN`** only when the API and the app are on different
- subdomains of one parent — then `.example.com`, so one cookie covers both. On
- localhost the shared cookie already works, because cookies ignore ports.
-
-### The session cookie is named after this app, not after the library
-
-`AUTH_COOKIE_PREFIX` in [`@crm/auth/cookies`](../packages/auth/src/cookies.ts)
-is the literal string `crm`, so the session cookie is
-`__Secure-crm.session_token` rather than Better Auth's default
-`__Secure-better-auth.session_token`.
-
-The default is a hazard for any install whose app shares a parent domain with
-something else — `crm.example.com` beside an existing `app.example.com`. A
-cookie set with `Domain=.example.com` by the neighbour is sent to *us* too,
-under a name identical to ours, and `parseCookies` keeps one value per name. The
-failure is silent and reads as a deployment problem rather than a naming one:
-sign-in completes, the `session` row is written with a week's expiry, the
-browser holds a cookie, and then every reader — the API that minted it and the
-app alike — resolves it to `null` and bounces to `/sign-in`. Nothing logs an
-error, because nothing has errored.
-
-Two things follow. It is set on the **server config and the proxy's read**
-together: `advanced.cookiePrefix` in `auth.ts` names the cookie and
-`getSessionCookie(request, { cookiePrefix: AUTH_COOKIE_PREFIX })` in
-`apps/app/proxy.ts` looks for it, and a prefix changed in one place only is a
-gate that redirects every signed-in request. And **changing it signs everybody
-out** — the old cookies stop matching. That is a one-time cost paid on deploy,
-not a loop: a stale `better-auth`-prefixed cookie no longer matches, so the
-proxy sends the reader to `/sign-in`, which is where they need to be.
-- **`AGENT_URL`** is the research agent, which is its own deployment. The app
- reads it to proxy the bridge and the API reads it to poke the dispatcher, both
- server-side only: the browser never learns the agent has an origin of its own.
- It must be a whole URL including the scheme, and the API validates that at
- boot — `new URL("/internal/crm/dispatch", base)` throws on `127.0.0.1:2000`,
- and it would throw at the moment a task is queued rather than at startup. See
- [the agent bridge](./agent.md#the-bridge).
+- **`API_URL`** (`:3001`) mints session cookies and serves `/api/auth/*`;
+ `next.config.ts` republishes it as `NEXT_PUBLIC_API_URL`, so one variable does both
+ sides. `BETTER_AUTH_URL` is a legacy fallback.
+- **`APP_URL`** (`:3000`) is also the trusted-origin and `callbackURL` allow-list;
+ comma-separate if multi-origin, first is canonical.
+- **`AUTH_COOKIE_DOMAIN`** only for API and app on different subdomains of one parent.
+- **`AGENT_URL`** is the agent's deployment, server-side only, and **must include the
+ scheme** — validated at boot, or it throws when a task is queued instead.
+- **`AUTH_COOKIE_PREFIX` is `crm`** (`@crm/auth/cookies`), set on **both**
+ `advanced.cookiePrefix` in `auth.ts` and `getSessionCookie(request, { cookiePrefix })`
+ in `proxy.ts` — one alone redirects every signed-in request. Better Auth's default
+ collides with any neighbour on a shared parent domain, and the failure is silent:
+ sign-in completes, the row is written, every reader resolves `null`. **Changing it
+ signs everybody out**, once.
+
+## `IS_MARKETING` — landing page flag, off by default
+
+`"true"` serves `app/(landing)` at `/`; anything else sends a signed-out visitor to
+`/sign-in`, because the page markets *this* product.
+
+- **Only the literal `true`** (same shape as `PRISMA_LOG_QUERIES`).
+- **It decides one thing**: what a stranger at `/` sees.
+- **`isMarketing()` (`apps/app/lib/env.ts`) reads per request**, so a config change
+ needs no rebuild. Declared in `apps/app/turbo.json` `passThroughEnv`.
## Typed, validated env
-`apps/api/src/config/env.validation.ts` is a `class-validator` schema run by
-`ConfigModule.forRoot({ validate })`, so the API fails at boot with a named
-error rather than at three in the morning with `undefined`. It lists every
-variable the API reads and nothing else — a variable that exists but is never
-read is a question a self-hoster has to answer for no reason.
-
-Two sharp edges:
+`apps/api/src/config/env.validation.ts` runs via `ConfigModule.forRoot({ validate })`.
+It lists every variable the API reads and nothing else.
-- **Validation runs while `AppModule` is being evaluated.** A test that needs to
- set a variable has to do it before importing that module — see the dynamic
- `import()` in `apps/api/test/auth.e2e.spec.ts`.
-- **The schema is the API's, not the repo's.** `@crm/auth` and the agent read
- their own values directly, because they run in processes Nest does not own.
+- **Validation runs while `AppModule` is evaluated** — a test must set variables before
+ importing it (see the dynamic `import()` in `test/auth.e2e.spec.ts`).
+- **The schema is the API's, not the repo's** — `@crm/auth` and the agent read their own
+ values.
## Optional: what the agent can do
-Every outside source the agent can reach is optional, and it is designed to run
-with none of them. A missing key removes a place to look; it is never an error.
-
-The company research key is the exception and it is **not in this table**,
-because it is not a variable at all — see
-[the next section](#the-context-key-is-asked-for-not-configured).
+Every outside source is optional and the agent runs with none. A missing key removes a
+place to look; **never an error, never throws**.
+`apps/agent/agent/lib/capabilities.ts` is the single place that knows what is set.
| Variable | What it adds |
| --- | --- |
-| `PERPLEXITY_API_KEY` | Open-web research with citations, and the search that finds a LinkedIn slug |
-| `RAPIDAPI_KEY` | LinkedIn profiles via LinkDAPI — name, title, employer, tenure |
-| `GITHUB_TOKEN` | Raises the GitHub rate limit from 60/hour when matching profiles |
-| `BLOB_READ_WRITE_TOKEN` | Mirrors every logo and profile picture into Vercel Blob rather than linking them. Read by the API and the seed too — see below |
-| `AI_GATEWAY_API_KEY` | The model. Not needed on Vercel, where OIDC handles it |
-| `AGENT_BRIDGE_SECRET` | Lets a rep talk to the agent from the contact sheet — [the bridge](./agent.md#the-bridge) |
-
-`apps/agent/agent/lib/capabilities.ts` is the single place that knows which are
-set. It prints the list at startup, states it in the session instructions so the
-agent plans around what it actually has, and gives the tools a shared
-"not configured, and retrying will not help" result — checked *before* the
-research budget is charged, so an install without a key does not pay for the
-discovery on every contact.
+| `PERPLEXITY_API_KEY` | Open-web research with citations; finds a LinkedIn slug |
+| `RAPIDAPI_KEY` | LinkedIn profiles via LinkDAPI |
+| `GITHUB_TOKEN` | Raises the GitHub rate limit from 60/hour |
+| `BLOB_READ_WRITE_TOKEN` | Mirrors logos and photos into Blob |
+| `AI_GATEWAY_API_KEY` | The model. Not needed on Vercel (OIDC) |
+| `AGENT_BRIDGE_SECRET` | The rep-facing Agent panel — see `agent.md` |
+
+`BLOB_READ_WRITE_TOKEN` is also in `env.validation.ts` and `apps/api/turbo.json`
+because the API and the seed write pictures too. The Next.js app is deliberately
+excluded — recognising our URL for the image optimizer needs no token.
### The Context key is asked for, not configured
-**`CONTEXT_DEV_API_KEY` is not a variable in this repo, and adding one back
-would be a second answer to a question that already has one.** Nothing reads it
-— not `.env.example`, not `env.validation.ts`, not any `turbo.json`. The key
-lives in `AppSetting` beside the agent's model, it is asked for at
-`/onboarding/research`, and **Settings → General** changes it afterwards.
-
-Same reason as [SSO](./api.md#sso-is-a-row-not-a-deployment): an admin who
-cannot redeploy cannot set an environment variable. It goes further than SSO
-does, because this is not a key an install can sensibly do without — it decides
-whether a company arrives as itself or as a grey square with its initials in
-it — so [the proxy asks for it](./api.md#the-gate-is-proxyts-and-it-is-answered-once-per-browser)
-rather than leaving it to be discovered on a settings page nobody visits.
-
-- **An install that had the variable set is asked for the key again, and that
- is the intended upgrade.** Nothing adopts the old value — no boot-time
- migration, no fallback — so the first navigation after deploying lands
- everyone on `/onboarding/research`, where they paste the key they already
- have. It is one interruption, once, in exchange for the answer living in one
- place rather than two — and it cannot be dismissed, because a dismissed gate
- is an install quietly filling up with companies that have no logo.
-- **Nothing is lost in the meantime, and the wait is not a queue.** A `brand`
- task with nowhere to look is consumed and marked done — but it settles
- `SKIPPED` *before* anything marks the row `RUNNING`, and `settle` only writes
- over a `RUNNING` row, so the company stays `PENDING`. `PENDING` is exactly
- what the sign-in sweep re-queues, so the work is recovered from the record
- rather than held in the queue. `test/keyless-brand.integration.spec.ts` pins
- it, because a `settle` that wrote unconditionally would strand every company
- added before the key with nothing to say so.
-- **Saving the key picks that work up immediately.**
- `settings.setResearchKey` runs the company sweep itself rather than leaving it
- to the next sign-in, because the person who just fixed it is standing there.
- It is fire-and-forget: a sweep that fails logs and the sign-in one still
- catches up. Contacts are not swept here — only one of the three portrait
- sources is Context — and they are picked up on the next sign-in as before.
-- **`readContextDevKey` in [`@crm/db/settings`](../packages/db/src/settings.ts)
- is the only reader**, and it reads one column. Everything downstream —
- `contextDevKey()` in the agent's `capabilities.ts`, the client in
- `lib/context-dev.ts`, the API's `settings.researchKey` — goes through it, so
- there is exactly one place that knows where the key is kept.
-- **It is read live, not at boot.** There is no cache in front of it, so a key
- pasted into the settings page applies to the very next vendor call rather than
- to the next deployment. Each read is one indexed row in front of a lookup that
- is about to make an HTTP request anyway.
-- **A database that cannot be read is a capability that is off**, not an
- exception. `contextDevKey()` logs and returns null, because a missing source
- must never throw — the rule at the top of this section, and the reason the
- agent keeps running against everything else it has.
-- **The key is never read back.** The API returns whether one is set and its
- last four characters, and nothing returns the key itself. Same rule as an SSO
- client secret.
-- **A wrong key is refused at the point it is typed, and the agent is what
- checks it.** Checking means calling Context, and [a vendor client in the API
- is a bug](./api.md#intelligence-never-lives-in-the-api) — so
- `settings.setResearchKey` asks the agent over the bridge
- (`POST /internal/crm/verify-key`) and only writes the row if the answer is not
- *invalid*. The agent already owns the client, the error classification and the
- key, so nothing about Context.dev is learned twice.
- - **The probe costs nothing.** A brand lookup only bills when it resolves a
- brand, and a free-provider address is refused with a documented `422`
- before any resolution — so `[email protected]` reaches Context, proves
- the key authenticates, and is never billed. Measured at about half a second.
- - **`401` is the only answer that means the key is wrong.** A `403` about the
- plan, a `422` refusing the probe, a `429`, a `500` — all of those were
- served *after* the key authenticated, so the key is good and only the probe
- was refused. `classifyKey` in `lib/context-dev.ts` holds that rule and
- `test/verify-key.spec.ts` pins every branch of it.
- - **A check that cannot be made is not a failed check.** No
- `AGENT_BRIDGE_SECRET`, an agent that is down, a timeout — all return
- `unknown`, and an unknown answer *saves the key* and logs that it went in
- unverified. The alternative is an install whose agent is not up yet being
- unable to finish onboarding, which is a worse failure than an unchecked
- key: the key is still checked by the first task that uses it.
-
-`BLOB_READ_WRITE_TOKEN` is the one entry in that table the agent does not own
-alone, which is why it is also declared in `apps/api/src/config/env.validation.ts`
-and in `apps/api/turbo.json`. The API writes two pictures of its own — the
-favicon a domain serves, and the Google avatar of anyone who signs in — and
-`packages/db/prisma/seed.ts` writes fifteen. The Next.js app is deliberately
-*not* on that list: it only has to recognise one of our URLs to route it through
-the image optimizer, and recognising one needs no token. See
-[the agent's picture rules](./agent.md#pictures-are-copied-never-linked).
+**`CONTEXT_DEV_API_KEY` is not a variable here and must not become one.** The key lives
+in `AppSetting`, is asked for at `/onboarding/research`, and is changed on Settings →
+General — an admin who cannot redeploy cannot set a variable.
+
+- **An install that had the variable is asked again**: no migration, no fallback, and
+ **the gate cannot be dismissed**.
+- **Nothing is lost while waiting.** A keyless `brand` task settles `SKIPPED` *before*
+ anything marks the row `RUNNING`, and `settle` only overwrites `RUNNING` — so the
+ company stays `PENDING`, which the sweep re-queues
+ (`test/keyless-brand.integration.spec.ts`).
+- **Saving the key runs the company sweep immediately** (fire-and-forget). Contacts wait
+ for the next sign-in — only one of three portrait sources is Context.
+- **`readContextDevKey` (`@crm/db/settings`) is the only reader**, read live with no
+ cache. An unreadable database is a capability that is off, not an exception.
+- **The key is never read back** — only whether one is set, and its last four.
+- **The agent checks it, not the API** (a vendor client in the API is a bug):
+ `settings.setResearchKey` calls `POST /internal/crm/verify-key` and writes unless the
+ answer is *invalid*. **`401` is the only answer meaning the key is wrong.** **A check
+ that cannot be made is not a failed check** — agent down or timeout → `unknown` →
+ save anyway and log it unverified.
## Gmail and Calendar sync
-Always on. Same OAuth client, same callback — the two read-only scopes are added
-to the existing Google provider rather than to a second one, so there is no
-extra redirect URI to register.
-
-The scopes are requested **at sign-in** and are a condition of using the CRM
-*for the person who signed in with Google*: `requireGoogleAccess()` gates the
-app shell on what Google actually granted, because granular consent lets a user
-untick a scope and still complete sign-in. Anyone missing either scope is sent
-to `/grant-access` to re-consent.
-
-**Someone who signed in through an identity provider is not gated**, and the
-distinction is the whole of `needsGoogleGrant` in
-[`@crm/auth`](../packages/auth/src/scopes.ts): the wall applies to an account
-whose only sign-in row is `google`. Two reasons it cannot be "does this person
-have the scopes".
-
-- **An SSO rep has no Google account to grant them on.** Sending them to
- `/grant-access` is sending them to a page whose only other button is *sign
- out* — a locked door with a sign on it, on an install that may have no Google
- client at all.
-- **Linking Gmail must not become a trap.** An SSO rep who connects Google and
- later revokes it would, under a scopes-only rule, be locked out of the CRM by
- having tried the optional feature. `revoke()` clears the tokens and keeps the
- `account` row, so that row is exactly what a scopes-only rule would trip over.
-
-They connect it from **Settings → Connections** instead, which posts the same
-`linkSocial` call `/grant-access` does — one write path, two doors. The card
-tells the three states apart, because they need three different sentences: no
-Google client on the install, a client but no linked account, and a linked
-account that has stopped working.
-
-**Sync is forward-only.** Nothing from before a mailbox was first seen is
-imported: Gmail records the current `historyId` on its first pass and imports
-nothing, and Calendar reads from `now` onwards.
-
-| Variable | Required | Notes |
-| --- | --- | --- |
-| `CRON_SECRET` | in deployed environments | Bearer guard on `POST /internal/sync/google` **and `POST /internal/sync/rates`**. Vercel sends it automatically as `Authorization: Bearer $CRON_SECRET`. Minimum 16 characters; both routes **fail closed** if unset, so locally the crons simply never run. |
-
-The absences are deliberate:
-
-- **No `GOOGLE_SYNC_ENABLED`.** A feature flag earns its keep when it gates
- something that can genuinely be absent — `PERPLEXITY_API_KEY` does, because
- without a key there is no call to make. Sync has everything it needs the
- moment the app boots. A switch that can turn off a mandatory feature,
- defaulting to off, is a switch that is only ever wrong.
-- **No `GOOGLE_WORKSPACE_DOMAIN`.** `ALLOWED_SIGN_IN` already says who is
- internal, and it is seeded into the sync's "us" set alongside the `User`
- table. Two sources for one fact is how a colleague becomes a lead.
-- **No `GMAIL_BACKFILL_DAYS`.** There is no backfill.
-- **No exchange-rate provider variable.** The rate feed is `open.er-api.com`, a
- constant in `apps/api/src/currency/rates.service.ts`, and it needs no account;
- an install that cannot reach it types its own rates on Settings → Currencies
- instead. See
- [the currency rules](./api.md#a-deal-is-sold-in-one-currency-and-reported-in-another).
- `POST /internal/sync/rates` wants a **daily** schedule beside the five-minute
- Google one.
-
-Two things to do in Google Cloud before this works:
-
-- **Enable the Gmail API and the Google Calendar API** on the project.
-- **Set the consent screen to User type: Internal** if you are on Google
- Workspace. `gmail.readonly` is a *restricted* scope; an External app using it
- needs OAuth verification plus an annual CASA security assessment, while an
- Internal app needs no further review. Going External later means the full
- review, so this is a decision, not a checkbox.
-
-The cron is declared in `apps/api/vercel.json` at `*/5 * * * *`. Minute-level
-schedules need a Pro plan; on Hobby it silently becomes daily.
-
-## Database
-
-Prisma is driven through turbo from the repo root: `db:generate`, `db:migrate`,
-`db:push`, `db:reset`, `db:seed`, `db:studio`, `db:deploy`. Config lives in
-`packages/db/prisma.config.ts`, which loads the root `.env` itself, so the CLI
-works without any app running.
-
-## What is not an env var
-
-- **Cache TTL default** — `DEFAULT_TTL_MS` (60s) is a constant in
- `apps/api/src/cache/cache.module.ts`. `CACHE_TTL_MS` only overrides it.
-- **Redis** — optional. Without `REDIS_URL` the cache falls back to a
- per-instance in-memory store, which is fine for local work and wrong for any
- multi-instance deploy (see `docs/api.md`).
-- **Sign-in method** — Google is the built-in one and it is in code. An
- install that wants its own identity provider adds one on the SSO settings
- page, and that is a row rather than a variable — see
- [SSO](./api.md#sso-is-a-row-not-a-deployment).
-
-## `vercel env pull` writes to `.env.local`, which wins
-
-The two conventions collide, and the collision is quiet:
-
-- `.env.local` is the *local override* file, so the loader reads it **after**
- `.env` and it wins.
-- `vercel env pull` writes **production** credentials into that same file by
- default — database, auth secret, OAuth client, Blob, Redis, the lot.
-
-Pull once and every process in the repo silently points at production. The
-symptom is not an error; it is `bun run dev` working perfectly against the live
-database, and `prisma migrate dev` in `packages/db` applying migrations to it.
-That happened here on 2026-08-01: eleven migrations landed on Neon from a
-laptop, and only the backfill in `20260801140000_contact_intelligence` kept it
-from dropping three columns of real data.
-
-Two defences, and you want both:
-
-1. **Pull somewhere inert.** `vercel env pull .env.vercel` — the loader does not
- read it, so it is reference material rather than configuration.
-2. **The destructive `db:*` scripts refuse a non-local host.**
- `packages/db/scripts/require-local-db.ts` guards `db:migrate`, `db:push`,
- `db:reset` and `db:seed`, prints which file the URL came from, and takes
- `ALLOW_REMOTE_DB=1` when you mean it. `db:deploy` is deliberately unguarded —
- pointing that at a remote database is what it is for.
-
-The guard resolves the URL by reading the root files directly, in the loader's
-order, rather than trusting `process.env`. That is not fussiness: Bun
-auto-loads the `.env` in the *working directory* before running a script, while
-Prisma's CLI is a Node process that only sees `@crm/env/load`. The first version
-of the guard read `process.env`, saw the `packages/db/.env` copy, and waved the
-Neon case through. A guard that is wrong in that direction is worse than none.
-
-## Secrets hygiene
-
-The root `.gitignore` ignores `.env` and `.env.*` with a single negation for
-`.env.example`, so a backup like `.env.bak` or `.env.old` is ignored too rather
-than committed by a stray `git add -A`. `.env.example` is the only env file in
-the repository, and it ships no value that is a secret — the placeholders are
-empty strings, and `packages/env/test/root.spec.ts` asserts that they stay that
-way.
-
-Generate your own secret. Never reuse one from an example file, a tutorial, or
-another environment: `openssl rand -base64 32`.
+Always on. Same OAuth client and callback — the two read-only scopes go on the existing
+Google provider, so there is no extra redirect URI.
+
+Scopes are requested at sign-in and gated by `requireGoogleAccess()`, because granular
+consent lets a user untick one and still sign in. Missing either → `/grant-access`.
+
+**An SSO rep is not gated** — `needsGoogleGrant` (`@crm/auth`) walls only an account
+whose *sole* sign-in row is Google. It cannot be "has the scopes": an SSO rep has no
+Google account to grant on, and `revoke()` keeps the `account` row, so trying the
+optional feature and revoking would lock them out. They connect from **Settings →
+Connections**, posting the same `linkSocial` call.
+
+**Sync is forward-only.** Gmail records the current `historyId` on its first pass and
+imports nothing; Calendar reads from `now`.
+
+**`CRON_SECRET`** (min 16 chars) guards `POST /internal/sync/google` and
+`POST /internal/sync/rates`; both **fail closed when unset**. **Crons live in
+`apps/api/vercel.json`** — Google `*/5 * * * *`, rates daily. Minute-level schedules
+need a Pro plan; on Hobby it silently becomes daily.
+
+Deliberate absences: **no `GOOGLE_SYNC_ENABLED`** (a switch that can disable a mandatory
+feature is only ever wrong), **no `GOOGLE_WORKSPACE_DOMAIN`** (`ALLOWED_SIGN_IN` already
+says who is internal — two sources is how a colleague becomes a lead), **no
+`GMAIL_BACKFILL_DAYS`**, **no rate provider variable** (`open.er-api.com` is a keyless
+constant).
+
+## Not env vars
+
+- **Cache TTL** — `DEFAULT_TTL_MS` (60s) in `cache.module.ts`; `CACHE_TTL_MS` overrides.
+- **Redis** — optional. Without `REDIS_URL` the cache is per-instance in-memory: fine
+ locally, wrong for multi-instance.
+- **Sign-in method** — Google is in code; an IdP is a row (SSO, in `api.md`).
diff --git a/docs/setup.md b/docs/setup.md
new file mode 100644
index 00000000..d329e438
--- /dev/null
+++ b/docs/setup.md
@@ -0,0 +1,101 @@
+# Setup and local development
+
+Operational detail moved out of the rule docs. `api.md`, `agent.md` and
+`environment.md` are what agents read before changing code; this is what a person
+reads once.
+
+## First run
+
+```sh
+cp .env.example .env # fill DATABASE_URL, BETTER_AUTH_SECRET, ALLOWED_SIGN_IN
+docker compose up -d # Postgres, matching .env.example
+bun run db:migrate && bun run db:seed
+bun run dev # app :3000, api :3001, agent :2000
+```
+
+Prisma from the repo root: `db:generate`, `db:migrate`, `db:push`, `db:reset`,
+`db:seed`, `db:studio`, `db:deploy`.
+
+## Google Cloud
+
+- **Enable the Gmail API and the Google Calendar API** on the project.
+- **Set the consent screen to User type: Internal** if you are on Workspace.
+ `gmail.readonly` is a *restricted* scope, so an External app needs OAuth
+ verification plus an annual CASA assessment. Going External later means the full
+ review — a decision, not a checkbox.
+
+## The agent bridge
+
+```sh
+AGENT_URL="http://127.0.0.1:2000" # 127.0.0.1, not localhost: eve dev is IPv4-only
+AGENT_BRIDGE_SECRET="$(openssl rand -base64 32)"
+```
+
+| Agent tab error | Cause |
+| --- | --- |
+| `503` | `AGENT_BRIDGE_SECRET` unset in the app's process |
+| `401` | The two processes hold different secrets, **or** `passThroughEnv` in `apps/app/turbo.json` / `apps/agent/turbo.json` is missing the pair (Turbo is strict-env) |
+| `502` | Agent not running, or `AGENT_URL` wrong |
+
+`localDev()` accepts any loopback request, so `curl 127.0.0.1` proves nothing about
+the bridge — send `-H 'Host: agent.example.com'`. `GET /eve/v1/info` is the whole
+inventory, including a `diagnostics` count that finds files eve silently ignored.
+
+## Running the agent
+
+**`bun run dev` is `eve dev --no-ui`** — turbo gives each task a pty, so the
+interactive TUI and turbo redraw over each other. `dev:tui` keeps the interactive one,
+and only that writes `.eve/logs/` for `eve logs`; under `--no-ui` the turbo pane is
+the record.
+
+`hooks/activity.ts` is the replacement narration, **to stderr** (the TUI hides
+stdout), printing shape everywhere and argument contents outside production only. It
+is **not the audit trail** — `hooks/audit.ts` writes `AgentEvent` regardless.
+
+- A second `bun run dev` fails the whole turbo run.
+- An orphaned agent holds the port: `lsof -nP -iTCP:2000 -sTCP:LISTEN`.
+
+### Nothing is researching, and the queue only grows
+
+**`eve dev` never fires schedules on their cron cadence**, and everything visible
+still works — the row is written, the sheet says *Queued*, and `dispatch.ts` is never
+called. The poke covers this **only when `AGENT_BRIDGE_SECRET` is set**; unset,
+`poke()` returns silently and the queue looks exactly like a slow agent.
+
+Tasks the API did not write (`schedule_recheck`) and anything queued while the agent
+was down still need a manual run:
+
+```sh
+bun run --filter=agent dispatch # exact production path, both lanes, real credits
+```
+
+Its printed `sessionIds` are research rows only, so a run that resolved forty logos
+prints an empty list and was not idle. `eve start` and Vercel do run the schedule.
+
+## `vercel env pull` writes `.env.local`, which wins
+
+`.env.local` is the override the loader reads *last*, and `vercel env pull` writes
+**production** credentials there by default. Pull once and every process silently
+points at production — not as an error, but as `bun run dev` working perfectly against
+the live database. On 2026-08-01 eleven migrations landed on Neon from a laptop.
+
+1. **Pull somewhere inert**: `vercel env pull .env.vercel`.
+2. **`packages/db/scripts/require-local-db.ts` guards `db:migrate`, `db:push`,
+ `db:reset`, `db:seed`** and takes `ALLOW_REMOTE_DB=1`. `db:deploy` is unguarded on
+ purpose. It reads the root files directly rather than `process.env`, because Bun
+ auto-loads the working directory's `.env` while Prisma's CLI only sees
+ `@crm/env/load`.
+
+## Secrets hygiene
+
+`.gitignore` ignores `.env` and `.env.*` with one negation for `.env.example`, so
+`.env.bak` is ignored too. `.env.example` ships no secret — placeholders are empty
+strings, asserted by `packages/env/test/root.spec.ts`. **Generate your own secret**;
+never reuse one from an example, a tutorial, or another environment.
+
+## Tests
+
+```sh
+bun run --filter=api test
+bun run --filter=agent test # integration specs need DATABASE_URL + real Postgres
+```
diff --git a/packages/db/prisma/seed.ts b/packages/db/prisma/seed.ts
index 45df8d7f..6ad15c6a 100644
--- a/packages/db/prisma/seed.ts
+++ b/packages/db/prisma/seed.ts
@@ -1,11 +1,13 @@
import { mirror } from "../src/blob";
import { db } from "../src/client";
+import { DEFAULT_REPORTING_CURRENCY } from "../src/currency";
import { resolveFavicon } from "../src/favicon";
import {
ActivityType,
DealStage,
RateSource,
} from "../src/generated/prisma/enums";
+import { readReportingCurrency, SETTINGS_ID } from "../src/settings";
function makeRandom(seed: number): () => number {
let a = seed;
@@ -489,14 +491,17 @@ let seedBase = "USD";
async function seedRates(): Promise<number> {
const asOf = daysFromNow(-1);
- const setting = await db.appSetting.upsert({
- where: { id: "app" },
- create: { id: "app", reportingCurrency: "USD" },
+ await db.appSetting.upsert({
+ where: { id: SETTINGS_ID },
+ create: {
+ id: SETTINGS_ID,
+ reportingCurrency: DEFAULT_REPORTING_CURRENCY,
+ },
update: {},
- select: { reportingCurrency: true },
+ select: { id: true },
});
- seedBase = (setting.reportingCurrency ?? "USD").trim().toUpperCase() || "USD";
+ seedBase = await readReportingCurrency(db);
if (seedBase !== "USD") {
console.log(