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

Enhance documentation and introduce new currency handling guidelines

Lewis Carhartde682cb3216c
diff --git a/AGENTS.md b/AGENTS.md
index 3eb88c93..947f5532 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,10 +6,13 @@ 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` |
+| Anything in `apps/api` — tRPC, auth, logging, sync, deletes, caching | `docs/api.md` |
+| `apps/agent` — the eve research agent, tools, tasks, dispatch | `docs/agent.md` |
+| `.env`, configuration, which variables exist and why | `docs/environment.md` |
| UI in `apps/app` or `packages/ui` | `docs/design.md` (below) |
+| Deal amounts, totals, charts, exchange rates | `docs/currency.md` |
+| The record sheet's Agent tab | `docs/agent-panel.md` |
+| Running it locally, Google Cloud, DB commands, secrets | `docs/setup.md` |
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
diff --git a/docs/agent-panel.md b/docs/agent-panel.md
new file mode 100644
index 00000000..7eb2538c
--- /dev/null
+++ b/docs/agent-panel.md
@@ -0,0 +1,31 @@
+# The Agent panel — read when touching the record sheet's Agent tab
+
+
+`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.
+
+This lives in the API and is not a breach of rule one: listing history decides nothing.
+
diff --git a/docs/agent.md b/docs/agent.md
index 7f0536a9..8a86ea8d 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -2,7 +2,8 @@
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.
+may move into the API. Local dev, the bridge env vars and the manual dispatch command
+are in `docs/setup.md`.
**Read the eve guide before writing eve code** —
`apps/agent/node_modules/eve/docs/README.md` matches the installed version;
@@ -17,8 +18,7 @@ agent and the API both need it.
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.
+- **The chooser offers only `tool-use` models** (`ModelCatalogService`).
- **Not a frontier model, deliberately** — refusing wrong answers is enforced by the
tools and evidence model, not model strength.
@@ -35,14 +35,13 @@ agent and the API both need it.
- **`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.
+- **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`.
+ `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.**
## Two lanes
@@ -54,40 +53,39 @@ agent and the API both need it.
| **Research** | everything else | One eve session per row | 12 |
**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.**
+behind sixty LLM runs for 25 minutes (`test/lanes.integration.spec.ts`). **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.
+**Priority**: `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`.
+`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`.
+- **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.
+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.
+- **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.
- **`classifyKey` rejects on `401` and nothing else.**
- **The candidate key, never the stored one.**
@@ -99,22 +97,22 @@ Sign-in sweep covers records never looked up (10 credits/company);
- **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.
+- **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.
+- **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.** 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.
+`lib/evidence.ts` prices it. A model asked to grade its own certainty will, and will be
+wrong in the direction that looks useful.
- **`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
@@ -131,9 +129,8 @@ retrying will not help" result — **checked before the research budget is charg
missing key removes a place to look. **Never an error, never throws.**
**`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.
+`capabilitiesFrom()`/`markdownFor()` are the pure halves. `contextDevKey()` is the only
+resolver, and `lib/context-dev.ts` memoises its client on the key string.
## Budget and scheduling
@@ -145,8 +142,8 @@ cache in front of the read.
## Three records, no dead ends
-**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.
+**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.
| Read (all free) | Hands back |
| --- | --- |
@@ -157,8 +154,8 @@ agent ask a rep who had a company open, contacts on screen, to paste an email.
**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.
+titles. **`search_crm` does no fuzzy matching** — "Marchetti" reaching "Marchetta" is a
+wrong record about a real person.
### Preambles
@@ -167,10 +164,8 @@ points at the read to start from) and **who opened it** — a dispatched task is
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.
-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.
+`task.ts` is the resolver and owns one side effect: seeding `lib/focus.ts`, without
+which the audit hook files events against nothing.
**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`).
@@ -185,14 +180,14 @@ preamble; `lib/workspace.ts` is the only renderer.
- **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.
+- **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`.
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.**
+`write_workspace_profile`, queued by `WorkspaceService.update` on a website change. **A
+finished attempt stands the sweep down for seven days.**
## What may be read, and what may leave
@@ -239,69 +234,12 @@ browser → /eve/v1/* (same origin, session cookie, x-crm-contact header)
### 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
-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)"
-```
+`lib/agent-record.ts` maps a record kind to everything downstream. The panel's own
+rules — snapshot loading, composer state, thread capture, scrolling — are in
+**`docs/agent-panel.md`**. It lives in the API and is not a breach of rule one:
+listing history decides nothing.
-`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
+## 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
@@ -313,8 +251,3 @@ sat on "Researching" forever. Hidden because the archived event's
**`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`. 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 024c0a13..2f6517e2 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -185,71 +185,13 @@ self-hoster's admin cannot redeploy.
- **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
-
-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.
+## Money
+
+A deal is sold in one currency and reported in another, and **only `baseAmount` may
+ever be summed**. The rules — `baseCurrency`, `countedWhere`/`pendingWhere`, frozen
+rates, the ten supported currencies, the keyless feed, and why the fetcher is the one
+documented exception to *no intelligence in the API* — are in **`docs/currency.md`**.
+Read it before touching any amount, total, chart or rate.
## Freshness: invalidate the query, don't disable the cache
diff --git a/docs/currency.md b/docs/currency.md
new file mode 100644
index 00000000..2917b73a
--- /dev/null
+++ b/docs/currency.md
@@ -0,0 +1,67 @@
+# Currency — read when touching deal amounts, totals, or rates
+
+
+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.
+
diff --git a/docs/environment.md b/docs/environment.md
index df3c0ad9..1aad230a 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -1,6 +1,6 @@
# Environment
-Setup, local dev and the `vercel env pull` hazard are in `docs/setup.md`.
+Setup, DB commands, Google Cloud and the `vercel env pull` hazard: `docs/setup.md`.
## One `.env`, at the repo root
@@ -25,29 +25,26 @@ localhost default or is genuinely optional.
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
+**`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`.
+list fails closed.** Parsed on demand. `packages/auth/src/workspace.ts`.
## Where things are
- **`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.
+- **`APP_URL`** (`:3000`) is also the trusted-origin and `callbackURL` allow-list.
- **`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.
+ collides with any neighbour on a shared parent domain, silently: sign-in completes,
+ the row is written, every reader resolves `null`. **Changing it signs everybody out.**
## `IS_MARKETING` — landing page flag, off by default
@@ -61,19 +58,18 @@ list fails closed.** Parsed on demand, not at import.
## Typed, validated env
-`apps/api/src/config/env.validation.ts` runs via `ConfigModule.forRoot({ validate })`.
-It lists every variable the API reads and nothing else.
+`apps/api/src/config/env.validation.ts` runs via `ConfigModule.forRoot({ validate })`,
+and lists every variable the API reads and nothing else.
- **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.
+- **The schema is the API's, not the repo's** — `@crm/auth` and the agent read their own.
## Optional: what the agent can do
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.
+place to look; **never an error, never throws**. `agent/lib/capabilities.ts` is the
+single place that knows what is set.
| Variable | What it adds |
| --- | --- |
@@ -91,7 +87,7 @@ 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 here and must not become one.** The key lives
-in `AppSetting`, is asked for at `/onboarding/research`, and is changed on Settings →
+in `AppSetting`, is asked for at `/onboarding/research`, and changes 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
@@ -100,48 +96,44 @@ General — an admin who cannot redeploy cannot set a variable.
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.
+- **Saving the key runs the company sweep immediately** (fire-and-forget).
- **`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.
+ answer is *invalid*. **`401` is the only answer meaning the key is wrong**, and **a
+ check that cannot be made is not a failed check** — `unknown` saves anyway and logs it
+ unverified.
## Gmail and Calendar sync
-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`.
+Always on, 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.
**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.
+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
+**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
+`/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).
+`GMAIL_BACKFILL_DAYS`**, **no rate provider variable**.
## 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.
+- **Redis** — optional; without `REDIS_URL` the cache is per-instance in-memory, which
+ is wrong for multi-instance.
- **Sign-in method** — Google is in code; an IdP is a row (SSO, in `api.md`).