Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Add initial project structure with environment configuration and documentation
Lewis Carhart5188e337abc2
diff --git a/.env.example b/.env.examplenew file mode 100644index 00000000..4b40e7a8--- /dev/null+++ b/.env.example@@ -0,0 +1,119 @@+# ─────────────────────────────────────────────────────────────────────────────+# Copy this file to `.env` and fill in the five values in "Required".+# Everything below that is optional — the app runs without any of it.+#+# cp .env.example .env+#+# One file, at the root of the repo, read by all three processes (the API, the+# web app and the agent). Real environment variables always win, so a hosting+# platform's own configuration overrides anything here.+# ─────────────────────────────────────────────────────────────────────────────+++# ── Required ─────────────────────────────────────────────────────────────────++# Postgres. `docker compose up -d` starts one that matches this exactly.+DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm?schema=public"++# Signs session cookies. Generate your own: openssl rand -base64 32+BETTER_AUTH_SECRET=""++# Who is allowed to sign in — this is the entire authorisation model, so it has+# no default. Comma-separated, and each entry is either a whole email domain or+# a single address:+#+# ALLOWED_SIGN_IN="acme.com" everyone at your company+# ALLOWED_SIGN_IN="acme.com,[email protected]" …plus one outsider+# ALLOWED_SIGN_IN="[email protected]" a one-person install+#+# Subdomains count, so "acme.com" also admits "[email protected]".+ALLOWED_SIGN_IN=""++# Google sign-in. Google Cloud console → APIs & Services → Credentials →+# Create credentials → OAuth client ID → Web application, then add+# http://localhost:3001/api/auth/callback/google as an authorised redirect URI.+#+# Google is the only way in, so the API will not start without these.+GOOGLE_CLIENT_ID=""+GOOGLE_CLIENT_SECRET=""+++# ── Where things are ─────────────────────────────────────────────────────────+# Only needed when you deploy. The defaults below are the localhost ones.++# The API. Also the origin that mints session cookies and serves /api/auth/*.+# API_URL="http://localhost:3001"++# The web app. Comma-separate if it is served from more than one origin —+# the first is canonical, and the rest are simply allowed to call the API.+# APP_URL="http://localhost:3000"++# Only when the API and the app are on different subdomains of one parent,+# e.g. api.example.com and app.example.com — then set ".example.com" so one+# session cookie covers both.+# AUTH_COOKIE_DOMAIN=""++# The research agent, which is its own deployment.+# AGENT_URL="http://localhost:2000"++# Lets a signed-in rep talk to the agent from the contact sheet.+#+# The browser never calls the agent directly. The app proxies /eve/v1/* on its+# own origin, checks the session, and mints a two-minute token signed with this+# secret; the agent verifies it and learns *which rep* is asking. Set the same+# value for both processes. openssl rand -base64 32+#+# Leave it unset and the Agent tab reports that it is not configured. Nothing+# else changes: the agent still runs on its own schedule.+# AGENT_BRIDGE_SECRET=""++# PORT="3001"+++# ── Optional: what the agent can do ──────────────────────────────────────────+# The research agent works with none of these — it falls back to what the CRM+# already knows (your own email and calendar history) and simply reports what+# it could not check. Each key you add unlocks one more place it can look, and+# it tells you at startup which ones are on.++# Perplexity — finds where a person lives on the web, and recent news worth+# knowing before a call. https://perplexity.ai/settings/api+# PERPLEXITY_API_KEY=""++# LinkDAPI via RapidAPI — LinkedIn profiles: name, title, employer, tenure.+# https://rapidapi.com/linkdapi/api/linkdapi-best-unofficial-linkedin-api+# RAPIDAPI_KEY=""++# Context.dev — company logos, industry and socials from a domain.+# https://context.dev+# CONTEXT_DEV_API_KEY=""++# GitHub — raises the rate limit when matching contacts to GitHub profiles.+# Any classic token with no scopes will do.+# GITHUB_TOKEN=""++# Vercel Blob — mirrors profile pictures so they survive the source going away.+# Without it, avatars are linked rather than copied.+# BLOB_READ_WRITE_TOKEN=""++# The model the agent runs on is reached through the Vercel AI Gateway. On+# Vercel this is handled by OIDC and needs nothing; elsewhere, set a key.+# https://vercel.com/docs/ai-gateway+# AI_GATEWAY_API_KEY=""+++# ── Optional: operations ─────────────────────────────────────────────────────++# Shared cache. Without it each instance caches in its own memory, which is+# correct — just not shared.+# REDIS_URL="redis://localhost:6379"+# CACHE_TTL_MS="60000"++# Bearer token guarding POST /internal/sync/google, the Gmail/Calendar cron+# route. The route refuses to run without it. At least 16 characters.+# CRON_SECRET=""++# Log every SQL statement Prisma runs, at debug level, without bound+# parameters. Off by default: it buries every other line under a wall of+# SELECTs.+# PRISMA_LOG_QUERIES="true"diff --git a/.gitignore b/.gitignoreindex 7a5365ca..d63a6329 100644--- a/.gitignore+++ b/.gitignore@@ -5,12 +5,11 @@ node_modules.pnp.pnp.js-# Local env files+# Local env files. `.env.example` is the one that is committed — it is the+# documentation, so the catch-all below must not swallow it..env-.env.local-.env.development.local-.env.test.local-.env.production.local+.env.*+!.env.example# Testingcoverage@@ -39,4 +38,7 @@ yarn-error.log*# Agent worktrees.claude/worktrees/-.env*++# eve build output+.eve+.outputdiff --git a/AGENTS.md b/AGENTS.mdindex 2b868a9a..bd7369aa 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,3 +10,30 @@ 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.++## 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.++## Contributing / licence++This repository is public and MIT-licensed. Before writing anything that ships:+no real customer names, addresses or company data in fixtures, tests,+screenshots or docs — the seed in `packages/db/prisma/seed.ts` is the source of+demo data. See @CONTRIBUTING.md and @SECURITY.md.+diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..5256c291--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,79 @@+# Contributing++We'd like to try something a little different with this repo.++Given that coding agents write most underlying code now, we'd prefer contributions in the form of+_human-written_ text. Run your idea by us the same way you would a coworker — informally, over+Slack. If we're aligned on the change, we're happy to burn our tokens on the implementation.++Please don't have AI expand a one-paragraph idea into a formal proposal. The paragraph was the+useful part.++Submit changes as a PR adding a `.txt` or `.md` file to the [`adrs/`](./adrs/) folder.++If you'd rather just send the code, that's fine too — but lead with why, and keep the diff small+enough that a person can hold it in their head.++PS: Report security vulnerabilities privately — see [`SECURITY.md`](./SECURITY.md), not a public+issue.++---++## Running it++Everything you need is in the [README](./README.md#quick-start). Short version:++```sh+bun install+docker compose up -d+cp .env.example .env # fill in ALLOWED_SIGN_IN and the two Google values+bun run db:deploy && bun run db:seed+bun run dev+```++## Before you push++```sh+bun run check-types+bun run lint+bun run test+```++All three run on CI, and `bun run format` fixes most of what `lint` complains about.++A few things that trip people up:++- **The tRPC router type is generated, and committed.** If the app can't see a procedure you just+ added, run `bun run --filter=api trpc:generate` and commit `apps/api/src/generated/server.ts`+ alongside the router change. `bun run dev` keeps it in watch mode.+- **Schema changes need a migration**, not `db:push`. `bun run db:migrate` creates one.+- **New environment variables need a home.** Add them to `.env.example` and, if the API reads them,+ to `apps/api/src/config/env.validation.ts`. A variable that only exists in someone's shell is a+ variable that breaks the next person's clone.++## House style++The repo has opinions, and they're written down where the work happens rather than in a style+guide:++- [`AGENTS.md`](./AGENTS.md) — the rules that apply to everything, and where the others live.+- [`docs/design.md`](./docs/design.md) — UI. Short version: `packages/ui` is the only place+ components come from, and you don't override its styles at the call site.+- [`docs/api.md`](./docs/api.md) — logging, tRPC, caching, and why intelligence never lives in the+ API.++Two that are worth stating here because they explain most review comments:++**Comments say why, not what.** The code already says what it does. A comment earns its place by+recording the thing that isn't in the diff — the bug that made this necessary, the obvious approach+that turned out wrong, the constraint that looks arbitrary until you know.++**Nothing about a person is guessed.** This is a CRM: a confidently wrong fact about a real customer+is worse than a blank field, because nobody can tell it's wrong. Code that fills a gap with a+plausible value is a bug here even when it's convenient.++## Reporting a bug++Include what you expected, what happened, and enough to reproduce it. If it involves the agent, the+session transcript is worth more than a description of it — but read it first and redact anything+that belongs to a real customer.diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..a3cd96ce--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Comp AI++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdindex 4ba17366..b35b7d0c 100644--- a/README.md+++ b/README.md@@ -1,216 +1,277 @@-# CRM+<h1 align="center">CRM</h1>++<p align="center">+ An open-source CRM that fills itself in.<br>+ It reads your Gmail and Calendar, works out who the people are, and writes what it learns onto the record.+</p>++<p align="center">+ <a href="#quick-start"><strong>Quick start</strong></a> ·+ <a href="#configuration"><strong>Configuration</strong></a> ·+ <a href="#the-agent"><strong>The agent</strong></a> ·+ <a href="#deploying"><strong>Deploying</strong></a> ·+ <a href="./CONTRIBUTING.md"><strong>Contributing</strong></a>+</p>++<p align="center">+ <img alt="MIT licence" src="https://img.shields.io/badge/licence-MIT-blue.svg">+ <img alt="Built with Bun" src="https://img.shields.io/badge/runtime-Bun-black.svg">+ <img alt="Postgres" src="https://img.shields.io/badge/database-Postgres-336791.svg">+</p>++<p align="center">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/overview-dark.png">+ <img alt="The CRM overview: closed-won and open pipeline, pipeline by stage, deals in progress and overdue tasks" src="./docs/images/overview.png">+ </picture>+</p>++---++## What this is++Most CRMs are a database with a form in front of it. Somebody has to type into that+form, and nobody does, so the data rots and the tool becomes a place deals go to be+forgotten.++This one is built the other way round. Gmail and Calendar are the source of truth:+when you email a customer, the thread lands on their record; when you take a meeting+with someone new, they become a contact at a company that already has a logo and an+industry. A research agent then works out who these people actually are — real name,+current title, employer — and writes it down with the evidence attached.++The rule it never breaks: **nothing about a person is guessed.** A contact who arrived+as `[email protected]` is called "Abigham" until something proves otherwise. A+confidently wrong fact about a customer is worse than a blank field, because nobody+can tell it is wrong.++It is single-tenant and internal by design. Sign-in is Google, the allow-list is one+environment variable, and everyone who gets in can see everything. That is the whole+authorisation model — see [SECURITY.md](./SECURITY.md) before you point it at real+customer data.++## Screenshots++<table>+ <tr>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/deals-dark.png">+ <img alt="Deals list with stage, amount, owner and close date" src="./docs/images/deals.png">+ </picture>+ <p align="center"><sub><b>Deals</b> — filters, sort and page live in the URL, so a view is a link.</sub></p>+ </td>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/contacts-dark.png">+ <img alt="Contacts list with title, email, company and owner" src="./docs/images/contacts.png">+ </picture>+ <p align="center"><sub><b>Contacts</b> — most of these were created by the mailbox sync, not typed.</sub></p>+ </td>+ </tr>+ <tr>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/companies-dark.png">+ <img alt="Companies list with domain, industry, open pipeline and owner" src="./docs/images/companies.png">+ </picture>+ <p align="center"><sub><b>Companies</b> — logo, industry and location arrive on their own.</sub></p>+ </td>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/overview-dark.png">+ <img alt="Overview dashboard" src="./docs/images/overview.png">+ </picture>+ <p align="center"><sub><b>Overview</b> — yours or the whole team's, toggled in the URL.</sub></p>+ </td>+ </tr>+</table>++## Quick start++You need [Bun](https://bun.com) and Docker.-Turborepo monorepo, managed with [Bun](https://bun.com).--## What's inside--### Apps--- `app` — [Next.js](https://nextjs.org/) front end, port 3000-- `api` — [NestJS](https://nestjs.com/) API, runs on Bun, port 3001--### Packages--- `@crm/auth` — [Better Auth](https://better-auth.com) configuration (server + client)-- `@crm/db` — Prisma schema, migrations, and the shared PostgreSQL client-- `@crm/ui` — [shadcn/ui](https://ui.shadcn.com) `radix-nova` design system, Tailwind theme, and `cn()`-- `@crm/typescript-config` — shared `tsconfig.json` bases--These packages are just-in-time: they export TypeScript sources and are compiled-by whatever consumes them.--### UI+```sh+git clone https://github.com/trycompai/crm.git && cd crm+bun install-`@crm/ui` owns the component library and the single Tailwind entry point. Apps-import the stylesheet once and pull components from subpath exports:+docker compose up -d # Postgres on :5432+cp .env.example .env # then fill in the four values below-```tsx-import "@crm/ui/globals.css"; // app/layout.tsx-import { Button } from "@crm/ui/components/button";-import { cn } from "@crm/ui/lib/utils";+bun run db:deploy # apply migrations+bun run db:seed # optional: a believable pipeline to look at+bun run dev```-The component set, the theme and the `cds-icon` animations are shared with the-Comp AI MVP app so the two products look like one. That means:--- **shadcn style `radix-nova`**, built on [Radix](https://www.radix-ui.com)- (plus `sonner`, `vaul`, `cmdk`, `recharts`). Components use Radix's `asChild`- API — not Base UI's `render` prop.-- **[Carbon](https://carbondesignsystem.com/libraries/icons/) icons** for- product chrome, imported one glyph at a time and rendered through the `Icon`- wrapper, which attaches the hover motion defined in `globals.css`:-- ```tsx- import Dashboard from "@carbon/icons-react/es/Dashboard";- import { Icon } from "@crm/ui/components/icon";+The app is on [localhost:3000](http://localhost:3000), the API on+[localhost:3001](http://localhost:3001).- <Icon icon={Dashboard} />;- ```+### The four values- Lucide is still a dependency because the vendored shadcn components use it- internally; prefer Carbon for anything you write.+Open `.env` and set these. Everything else in the file is optional and commented out.-Add components with the shadcn CLI from `apps/app` — the monorepo aliases in-`components.json` route the files into `packages/ui`:+| Variable | What to put in it |+| ------------------------------------------ | -------------------------------------------------------------------- |+| `BETTER_AUTH_SECRET` | `openssl rand -base64 32` |+| `ALLOWED_SIGN_IN` | Your email domain, e.g. `acme.com`. Or one address, e.g. `[email protected]`. |+| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`| A Google OAuth client — 2 minutes, below. |-```sh-cd apps/app-bunx --bun shadcn@latest add <component>-```+`DATABASE_URL` already matches the `docker compose` Postgres, so leave it alone unless+you brought your own.-Design tokens live in `packages/ui/src/styles/globals.css`; that file also-declares the Tailwind `@source` globs. Consuming apps re-export the shared-PostCSS config and list `@crm/ui` in `transpilePackages`.+<details>+<summary><strong>Getting the Google OAuth client</strong></summary>-Files under `packages/ui/src/components` are vendored from upstream and excluded-from Biome so `shadcn add --diff <component>` stays readable when re-syncing.+1. [Google Cloud console](https://console.cloud.google.com/apis/credentials) → **Credentials** → **Create credentials** → **OAuth client ID** → **Web application**.+2. Under **Authorised redirect URIs**, add `http://localhost:3001/api/auth/callback/google`.+3. Enable the [Gmail API](https://console.cloud.google.com/apis/library/gmail.googleapis.com) and the [Calendar API](https://console.cloud.google.com/apis/library/calendar-json.googleapis.com) for the project.+4. Copy the client ID and secret into `.env`.-### Auth+Google sign-in is the only way in, so the API will not start without these. If your+account is on a Google Workspace domain, set the consent screen to **Internal** and+nobody outside your org can even reach the prompt.-Sign-in is **Google only** — this is an internal tool, so there are no-organizations, no passwords and no invitations.+</details>-The **API** owns authentication. It mounts `/api/auth/*` through-`@thallesp/nestjs-better-auth` and is the only process that writes session-cookies. The **app** reads those sessions straight out of Postgres via-`@crm/auth` (no HTTP round trip) and sends the browser to the API for sign-in-and sign-out.+`ALLOWED_SIGN_IN` is the entire authorisation model — an unset value means nobody can+sign in, which is the safe direction to fail. It takes whole domains, individual+addresses, or a mix:+```sh+ALLOWED_SIGN_IN="acme.com" # everyone at your company+ALLOWED_SIGN_IN="acme.com,[email protected]" # …plus one outsider+ALLOWED_SIGN_IN="[email protected]" # a one-person install```-browser ──sign in──▶ api:3001/api/auth/* ──▶ Google- │ │- │ session cookie- ▼ ▼-app:3000 ──cookie──▶ Postgres (@crm/db)- └──── fetch /auth/me, /health ────▶ api:3001-```--Both processes therefore need the **same** `BETTER_AUTH_SECRET` and-`DATABASE_URL`. On localhost the shared cookie works because cookies ignore-ports; on separate subdomains set `AUTH_COOKIE_DOMAIN` to the shared parent.--`apps/app/proxy.ts` does an optimistic cookie check to keep anonymous traffic-off protected routes; `requireSession()` in `apps/app/lib/session.ts` is the-authoritative check every protected page runs.-Because Google is the only door, there is no way to get a session from a-terminal. `bun run --filter=api dev:session [email]` writes the rows Better Auth-would have written and prints the cookie it would have set — development only,-and it refuses to run with `NODE_ENV=production`.--### Data--The app talks to the API over **tRPC** (`nestjs-trpc`), mounted at `/api/trpc`.+## Configuration++**There is one `.env`, at the root of the repo**, read by all three processes. Real+environment variables always win, so on a hosting platform you configure it there and+the file is purely a local convenience.++Beyond the four required values, everything is optional and the app runs without any+of it. [`.env.example`](./.env.example) is the full list with a note on each; the+short version:++| | |+| --- | --- |+| `API_URL` / `APP_URL` | Where the two halves are served. Only needed off localhost. |+| `PERPLEXITY_API_KEY` | Lets the agent search the open web, with citations. |+| `RAPIDAPI_KEY` | Lets the agent read LinkedIn profiles for identity. |+| `CONTEXT_DEV_API_KEY` | Company logo, industry and socials from a domain. |+| `AGENT_BRIDGE_SECRET` | Lets a rep talk to the agent from a contact's **Agent** tab. |+| `REDIS_URL` | A shared cache. Without it, per-instance and in-memory. |+| `CRON_SECRET` | Guards the Gmail/Calendar sync route. Required to use it. |++## The agent++The research agent is a separate deployment in [`apps/agent`](./apps/agent), built on+[eve](https://eve.dev). The API never enriches anything itself — it queues a row that+says *this happened* (a company was created, an attendee is unknown, a meeting is+tomorrow) and the agent decides what that means.++**Every outside source it can reach is optional, and it is designed to run with none+of them.** With no API keys at all it still works: `read_crm_history` reads your own+threads, meetings and signature blocks, which is free and is the best evidence there+is — no data vendor can sell you a reply from the person's own address. Each key you+add opens one more place to look. The agent is told at the start of every session+which ones this install has, so it plans around what it actually has rather than+discovering the gaps one failed call at a time, and it prints the list at startup:```-apps/app ──/api/trpc──▶ app/api/[...path]/route.ts ──▶ api:3001/api/trpc- server components: getServerTrpc() + prefetch → <HydrateClient>- client components: useTRPC() + TanStack Query+[agent] on LinkedIn (RAPIDAPI_KEY)+[agent] off Web research (PERPLEXITY_API_KEY)+[agent] off Company brand data (CONTEXT_DEV_API_KEY)```-The catch-all route handler is a same-origin passthrough. Without it every call-from the browser would be a cross-origin credentialed request, with the CORS and-cookie rules that implies; with it, `/api/trpc` is local and the session cookie-just works.--`apps/api` exports the generated router type as `api/app-router`, so the app is-type-safe from the Prisma row to the table cell. It is generated, not written:-`bun run dev` keeps `nestjs-trpc watch` running alongside the API, and-`bun run --filter=api trpc:generate` refreshes it once. If a new procedure is-invisible to the app, that is what has not run.--List URLs are state: filters, sort and page live in the query string via-[nuqs](https://nuqs.dev), parsed once per module in a `*-search-params.ts` so-the server prefetch and the client table cannot disagree. Copying the URL-reproduces the view.--### The agent--Company knowledge — logo, description, industry, address, socials — is filled-in by [Context.dev](https://context.dev) rather than typed by a human.-`apps/api/src/enrichment` holds a thin typed client, a small in-process queue-(concurrency 2, one retry, per-domain dedupe) and the field mapping.--It runs on company create, on a domain change, and on the "Re-enrich" button;-"Research" reads the company's site and posts a brief to its timeline. Two-rules the mapping never breaks: it only ever **fills gaps**, so a value a rep-typed is never overwritten by a guess, and logos are chosen by `mode`+`type`-rather than by taking `logos[0]`.--Set `CONTEXT_DEV_API_KEY` in `apps/api/.env` to switch it on. Without it the-agent is disabled, the API logs one warning at boot, and companies simply stay-`PENDING` — nothing else changes.--### Importing from HubSpot--`/import` takes a HubSpot CSV export of companies, contacts or deals. It always-dry-runs first and shows a per-row report — outcome, the record it matched, and-why anything was skipped — before anything is written.+Instead of asserting confidence, it reports **evidence** and a ledger scores it.+Strong evidence writes to the record; weak evidence becomes a suggestion a human+settles. Both are the system working — and if it cannot confirm something, it leaves+the field empty and says so.-Matching is on `domain` for companies and `email` for contacts, both unique, so-re-running an import updates rather than duplicates. A company row with no-domain falls back to an exact name match, and the report says so. Deals match on-name within a company, and need the companies imported first.+You can also watch it work. Every contact has an **Agent** tab: the steps it takes as+it takes them, the leads it throws away and why, and its questions answered in place+when it cannot decide between two people. Set `AGENT_BRIDGE_SECRET` to the same value+in both processes to turn it on — without it the tab reports that it is not+configured and nothing else changes. [`docs/agent.md`](./docs/agent.md) has the+details.-### Tooling+## What's inside-- [TypeScript](https://www.typescriptlang.org/) for static type checking-- [Biome](https://biomejs.dev/) for linting and formatting+A [Turborepo](https://turborepo.dev) monorepo on [Bun](https://bun.com).++| Path | |+| --- | --- |+| `apps/app` | [Next.js](https://nextjs.org) front end · :3000 |+| `apps/api` | [NestJS](https://nestjs.com) API — HTTP, auth, tRPC, Google sync · :3001 |+| `apps/agent` | The research agent ([eve](https://eve.dev)) |+| `packages/db` | [Prisma](https://prisma.io) schema, migrations, shared Postgres client |+| `packages/auth` | [Better Auth](https://better-auth.com) config and the sign-in allow-list |+| `packages/ui` | [shadcn/ui](https://ui.shadcn.com) components, the Tailwind theme |+| `packages/env` | Finds and loads the root `.env` |++The app talks to the API over **tRPC**, and the router type is generated from the+NestJS routers — so the front end is type-safe from the Prisma row to the table cell.+List state (filters, sort, page) lives in the URL via [nuqs](https://nuqs.dev), so+copying the address bar reproduces the view.++Three rules the codebase holds to, written up where the work happens:++- **Intelligence never lives in the API** ([docs/api.md](./docs/api.md)). Nest reports+ that something happened; the agent decides what it means. Two copies of an identity+ matcher once drifted until one matched every employer on earth.+- **`packages/ui` is the only source of UI** ([docs/design.md](./docs/design.md)). No+ overriding styles at the call site.+- **There are no organizations.** Single tenant, deliberately. An `organizationId`+ that is always the same value is a column, an index and a permissions check that+ buys nothing and reads like a real one at review time.-## Getting started+## Tasks-```sh-bun install+| Command | |+| --- | --- |+| `bun run dev` | Everything, in watch mode |+| `bun run build` | Build all apps and packages |+| `bun run test` | Run the test suite |+| `bun run check-types` | `tsc --noEmit` everywhere |+| `bun run lint` / `format` | [Biome](https://biomejs.dev) |+| `bun run db:migrate` | Create and apply a migration |+| `bun run db:seed` | Top up the demo pipeline (idempotent) |+| `bun run db:studio` | Prisma Studio |+| `bun run --filter=api trpc:generate` | Regenerate the `AppRouter` type |+| `bun run --filter=api dev:session` | Print a session cookie for a local user |-cp packages/db/.env.example packages/db/.env-cp apps/api/.env.example apps/api/.env-cp apps/app/.env.example apps/app/.env+Scope any of them with a Turborepo filter: `bun run dev --filter=api`.-openssl rand -base64 32 # -> BETTER_AUTH_SECRET, the SAME value in both .env files+Because Google is the only door, there is no way to get a session from a terminal —+`dev:session` writes the rows Better Auth would have written and prints the cookie it+would have set. It refuses to run with `NODE_ENV=production`.-bun run db:generate-bun run db:deploy # applies the migrations-bun run dev-```+## Deploying-Then create a Google OAuth client (Google Cloud console → Credentials → OAuth-client ID → Web application), add `http://localhost:3001/api/auth/callback/google`-as an authorised redirect URI, and put the pair in `apps/api/.env` as-`GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`. The API refuses to boot without-them — Google is the only way in.+Three deployments and a Postgres: the Next.js app, the NestJS API, and the agent.+They are independent, and the only thing they must agree on is `DATABASE_URL` and+`BETTER_AUTH_SECRET` — the API mints the session cookie and the app verifies it, so a+mismatch is a redirect loop rather than an error.-No local Postgres? `bunx prisma dev` (from `packages/db`) starts one and prints-a `DATABASE_URL`.+Set `API_URL` and `APP_URL` to the real origins, and if the two are on different+subdomains of one parent, set `AUTH_COOKIE_DOMAIN` to the parent so one cookie covers+both. Add `http://your-api-host/api/auth/callback/google` to the OAuth client's+redirect URIs. Set `CRON_SECRET` and point a scheduler at+`POST /internal/sync/google` to keep the mailbox sync running.-## Tasks+`apps/api/src/generated/server.ts` is committed and `build` must never regenerate it —+the generator needs a newer GLIBC than most build images have. Regenerate locally and+commit it with the router change that caused it.-| Command | What it does |-| ---------------------- | ------------------------------------------------ |-| `bun run dev` | Every app in watch mode |-| `bun run build` | Build all apps and packages |-| `bun run lint` | `biome check` in every package |-| `bun run check-types` | `tsc --noEmit` in every package |-| `bun run format` | Format the whole repo with Biome |-| `bun run db:migrate` | Create and apply a Prisma migration |-| `bun run db:studio` | Open Prisma Studio |-| `bun run auth:generate`| Regenerate the auth models in the Prisma schema |-| `bun run --filter=api trpc:generate` | Regenerate the `AppRouter` type the app imports |-| `bun run --filter=api dev:session` | Print a signed session cookie for a local user |--Scoped runs use Turborepo filters:+## Contributing-```sh-bun exec turbo run dev --filter=api-```+We'd rather have a paragraph you wrote than a pull request an agent wrote. See+[CONTRIBUTING.md](./CONTRIBUTING.md).-## Environment+Security issues go through [SECURITY.md](./SECURITY.md), privately, not a public+issue.-`.env` files live in the package that reads them — `packages/db/.env` for-`DATABASE_URL`, `apps/api/.env` for the API, `apps/app/.env` for the front end.-There is no root `.env`.+## Licence-`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL` and `DATABASE_URL` are duplicated across-`apps/api/.env` and `apps/app/.env` on purpose: both processes run Better Auth-against the same database, and they must agree or the cookie one writes will not-verify in the other.-# crm+[MIT](./LICENSE).diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 00000000..8b4adc68--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,71 @@+# Security Policy++## Reporting a vulnerability++Please report privately through **Security → Report a vulnerability** on this repository, not in a+public issue.++Include the revision, your configuration, the impact, and the steps to reproduce it. If it involves+real data, describe the shape of it rather than pasting it.++We'll acknowledge within a few working days and tell you what we intend to do. This is a small+project and there is no bounty.++## What this is, and what it assumes++This CRM is built for **one organisation of authenticated internal users**. It is not a hardened+public or multi-tenant service boundary, and the design says so out loud in a few places. The+limits below are real and worth reading before you put customer data in it.++**Sign-in is the entire authorisation model.** `ALLOWED_SIGN_IN` decides who gets in; after that,+every signed-in person can read and write every record. There are no roles, no per-record+permissions and no organizations — deliberately, because a permissions check that always returns+`true` reads like a real one at review time. If you need someone to see only part of the pipeline,+this is the wrong tool today.++An unset `ALLOWED_SIGN_IN` fails closed: nobody can sign in. A list that names a consumer domain+(`gmail.com`) is an open door, which is why single addresses are supported.++**Operators can read everything.** Whoever runs the deployment has the database, the environment+and the logs. Nothing here protects data from the person hosting it.++**The agent reads your mail.** Gmail and Calendar access is a condition of signing in, because+reading the mailbox is what the CRM is for. The research agent reads message bodies, meeting+attendees and signature blocks belonging to real people who did not sign up for this. It is+deliberately unrestricted on the *read* side and constrained on the *write* and *egress* sides —+see `apps/agent/agent/skills/data-boundaries.md`. If you deploy this, you are the data controller+for those mailboxes.++**Outbound calls send data to third parties.** Each optional key in `.env.example` turns on a+vendor the agent can query, and a query carries whatever it needs to ask the question — typically a+name, an email domain and an employer. With no keys set, nothing leaves your infrastructure except+Google's own APIs. That is the default.++**The sync route is guarded by a shared secret.** `POST /internal/sync/google` is called by a cron,+so it has no session to check; `CRON_SECRET` is the whole guard and the route refuses to run+without it. Treat it like a password.++**Session cookies depend on one shared value.** The API and the web app both verify sessions+against `BETTER_AUTH_SECRET`. Rotating it signs everyone out, which is the intended way to revoke+every session at once.++## Deploying it safely++- Set `ALLOWED_SIGN_IN` to a domain you control. Never a public mail provider.+- Generate `BETTER_AUTH_SECRET` yourself (`openssl rand -base64 32`). The value in any example file+ is not a secret.+- Serve both processes over HTTPS. Secure cookies switch on with `NODE_ENV=production`.+- Set `CRON_SECRET` if you expose the sync route at all.+- Keep the database off the public internet.+- Start with no optional API keys and add them one at a time, so you know what is leaving.++## Supported versions++`main` is the only supported branch. There are no backports.++## Dependencies++Dependencies are updated deliberately rather than automatically. If you spot a vulnerable+transitive dependency, report it the same way as anything else — a PR bumping it is welcome, but+tell us what the exposure is, since a CVE in a dev-only tool and one in the request path deserve+different urgency.diff --git a/adrs/README.md b/adrs/README.mdnew file mode 100644index 00000000..c73287c1--- /dev/null+++ b/adrs/README.md@@ -0,0 +1,16 @@+# adrs++Proposals live here. One file per idea, `.md` or `.txt`, named after the thing you want to change.++Write it yourself, in your own words, at whatever length the idea actually needs — a paragraph is a+perfectly good ADR. See [CONTRIBUTING.md](../CONTRIBUTING.md) for why we'd rather have that than a+pull request full of generated code.++Roughly:++- what you want to change+- why the current behaviour is a problem, ideally with the case that made you notice+- what you'd do instead, and what it would break++Nothing to record after the fact. These are for deciding, and they stay as the record of what was+decided.diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.tsindex 449c6501..66ed610d 100644--- a/apps/agent/agent/agent.ts+++ b/apps/agent/agent/agent.ts@@ -1,4 +1,7 @@+import "@crm/env/load";+import { defineAgent } from "eve";+import { capabilities } from "./lib/capabilities";/*** The people-research agent.@@ -9,9 +12,25 @@ import { defineAgent } from "eve";* identity-matching evals say otherwise.** A plain model id routes through the Vercel AI Gateway, authenticated by- * project OIDC — so there is no provider key to manage alongside the two API- * keys this agent already needs.+ * project OIDC — so on Vercel there is no provider key to manage. Elsewhere,+ * set `AI_GATEWAY_API_KEY`.+ */++/**+ * Says which outside sources are on, once, at startup.+ *+ * Every one of them is optional and the agent is designed to run with none, so+ * the thing a self-hoster needs is not a warning — it is a plain statement of+ * what this install can see, printed where they are already looking. Silence+ * would leave "the agent found nothing" and "the agent had nowhere to look"+ * indistinguishable.*/+for (const capability of capabilities()) {+ console.log(+ `[agent] ${capability.enabled ? "on " : "off"} ${capability.label} (${capability.env})`,+ );+}+export default defineAgent({model: "anthropic/claude-sonnet-5",});diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.tsnew file mode 100644index 00000000..293229cc--- /dev/null+++ b/apps/agent/agent/channels/crm.ts@@ -0,0 +1,37 @@+import { defineChannel } from "eve/channels";++/**+ * The CRM itself, as a place work arrives from.+ *+ * The dispatcher needs a channel to hand a task to, and the built-in HTTP+ * channel is not one: it answers requests, it has no `receive` hook, and there+ * is nothing to deliver a reply *to*. This is the other shape — a channel whose+ * whole job is to start a durable session and let the tools do the writing.+ *+ * There is deliberately no delivery. A run that identifies somebody has already+ * succeeded by the time it would have something to say, because success is a+ * fact on a record rather than a message to a person. If this ever needs to+ * tell somebody something, the timeline is where it goes.+ */+export default defineChannel({+ // No inbound HTTP surface. Work reaches this channel by hand-off from the+ // dispatcher, not by request — the API queues a row, it does not call us.+ routes: [],++ async receive(input, { send }) {+ const taskId =+ typeof input.target?.taskId === "string" ? input.target.taskId : null;++ // The token is the task, which gives retries the behaviour you want for+ // free: a lease that expired mid-run is re-dispatched and *continues* the+ // same durable session rather than starting the research over. A task+ // scheduled fortnightly gets a new id each time, so two runs a fortnight+ // apart correctly share nothing.+ return send(input.message, {+ auth: input.auth,+ continuationToken: taskId+ ? `crm:task:${taskId}`+ : `crm:adhoc:${crypto.randomUUID()}`,+ });+ },+});diff --git a/apps/agent/agent/channels/eve.ts b/apps/agent/agent/channels/eve.tsnew file mode 100644index 00000000..31840673--- /dev/null+++ b/apps/agent/agent/channels/eve.ts@@ -0,0 +1,80 @@+import {+ type AuthFn,+ extractBearerToken,+ localDev,+ vercelOidc,+ verifyJwtHmac,+ withAuthChallenges,+} from "eve/channels/auth";+import { eveChannel } from "eve/channels/eve";++/**+ * The HTTP surface, and who is allowed to reach it.+ *+ * Three callers, in the order they are tried:+ *+ * 1. **A rep, through the CRM** — see `repFromCrm` below.+ * 2. **Vercel-to-Vercel**, for callers inside the deployment boundary.+ * 3. **localhost**, for `eve dev` and the terminal UI.+ *+ * Auth fails closed. With `AGENT_BRIDGE_SECRET` unset, entry 1 is skipped+ * rather than opened: no shared signer, no way for the proxy to prove who it+ * is, so the panel stops working and nothing else changes.+ */++/** Both halves must agree on these, so they are stated once and exported. */+export const BRIDGE_ISSUER = "crm-app";+export const BRIDGE_AUDIENCE = "crm-agent";++/**+ * A signed-in rep, arriving through the CRM's proxy.+ *+ * The browser never talks to this agent directly. `apps/app` proxies+ * `/eve/v1/*` on its own origin, checks the Better Auth session, and mints a+ * two-minute HS256 token naming the person. That avoids CORS, avoids scoping a+ * session cookie to a third host, and — the part that matters — tells the agent+ * *which rep* is asking rather than merely that the app is.+ *+ * Wrapping `verifyJwtHmac` rather than using the `jwtHmac()` helper directly,+ * for one reason worth stating: the helper maps an HMAC token to+ * `principalType: "service"` with `principalId: "crm-app:<sub>"`, which is the+ * right default for a shared machine credential and wrong here. This is a+ * person. `lib/approval.ts` decides whether to pause for a human by reading+ * exactly these fields, so getting them right is the difference between a rep+ * being asked to confirm a job change and the agent quietly refusing.+ */+export function repFromCrm(secret: string): AuthFn<Request> {+ return withAuthChallenges(+ async (request: Request) => {+ const result = await verifyJwtHmac(+ extractBearerToken(request.headers.get("authorization")),+ {+ algorithm: "HS256",+ audiences: [BRIDGE_AUDIENCE],+ issuer: BRIDGE_ISSUER,+ secret,+ },+ );++ if (!result.ok) return null;++ const claims = result.sessionAuth;+ const userId = claims.subject;+ if (!userId) return null;++ return {+ attributes: claims.attributes ?? {},+ authenticator: "crm-app",+ principalId: userId,+ principalType: "user" as const,+ };+ },+ [{ scheme: "Bearer" }],+ );+}++const secret = process.env.AGENT_BRIDGE_SECRET;++export default eveChannel({+ auth: [...(secret ? [repFromCrm(secret)] : []), vercelOidc(), localDev()],+});diff --git a/apps/agent/agent/hooks/audit.ts b/apps/agent/agent/hooks/audit.tsnew file mode 100644index 00000000..a0d12240--- /dev/null+++ b/apps/agent/agent/hooks/audit.ts@@ -0,0 +1,61 @@+import { db } from "@crm/db";+import { defineHook } from "eve/hooks";+import { currentFocus } from "../lib/focus";++/**+ * Every runtime event, on the record it was about.+ *+ * This is what "show your work" reads. Without it the agent's reasoning exists+ * only in a log nobody can query, and the contact sheet can say *what* a field+ * is but never *how it got there* — which is the whole difference between this+ * and buying a record from a data vendor.+ *+ * `meta.id` is eve's own ULID, minted once when the event is written to the+ * durable stream and stable across reconnects, rewinds and replays. Using it as+ * the primary key with `skipDuplicates` is what makes ingestion idempotent: a+ * reconnect mid-turn re-delivers events we already have, and they land as+ * no-ops instead of duplicate rows. Leading with a timestamp keeps inserts+ * roughly append-ordered too.+ *+ * Hooks are observe-only and run after the event is durably recorded, so a+ * failure in here can never take a turn down with it — but it must not throw+ * either, which is why the write is wrapped.+ */+export default defineHook({+ events: {+ async "*"(event, ctx) {+ const id = event.meta?.id;++ // Events written before eve stream version 20 carry no id. They cannot+ // be deduplicated, so they are not stored rather than risking a+ // duplicate history — the exposure ends with the sessions that predate+ // the upgrade.+ if (!id) return;++ try {+ await db.agentEvent.createMany({+ data: [+ {+ id,+ sessionId: ctx.session.id,+ contactId: currentFocus().contactId,+ type: event.type,+ // Not every event carries a payload — `session.completed`+ // is the whole event. The column is non-null, so those+ // store an empty object rather than being dropped.+ data: ("data" in event ? (event.data ?? {}) : {}) as object,+ emittedAt: event.meta?.at ? new Date(event.meta.at) : new Date(),+ },+ ],+ skipDuplicates: true,+ });+ } catch (error) {+ // Never let the audit trail break the work it is auditing.+ console.warn("[audit] could not record event", {+ type: event.type,+ reason: error instanceof Error ? error.message : String(error),+ });+ }+ },+ },+});diff --git a/apps/agent/agent/instructions.md b/apps/agent/agent/instructions.mdindex f0a115eb..44a83fe4 100644--- a/apps/agent/agent/instructions.md+++ b/apps/agent/agent/instructions.md@@ -1,63 +1,66 @@# People research agent-You research the people in our CRM so a rep opens a record already knowing who-they are dealing with. You work on contacts the Gmail and Calendar sync created,-which arrive knowing only an email address.+You work out who the people in our CRM are, so a rep opens a record already+knowing who they are dealing with.## The one rule**Never write a fact you have not read from a source.**-Every contact you touch arrived as an email address and a guess. `[email protected]`-became a contact called "Abigham" because that is what the address looks like-title-cased. Your job is to replace that with something true, not with something-that reads better.+Most contacts here arrived as an email address and a guess.+`[email protected]` became a contact called "Abigham" because that is what the+address looks like title-cased. Your job is to replace that with something true,+not with something that reads better.-A confidently wrong name is worse than an ugly one, because nobody can tell it-is wrong. If you cannot confirm who somebody is, leave them as they are and move-on. That is a successful outcome, not a failure.+A confidently wrong fact is worse than a missing one, because nobody can tell it+is wrong. If you cannot confirm something, leave it. That is a successful+outcome.-## How to identify somebody+## How this works-Load the `identity-matching` skill before your first match of a session. It has-the procedure and the confidence bands. In short:+You do not assert confidence — you report **evidence**, and the ledger scores+it. `record_fact` takes what you *saw* ("their signature block says Head of+Security"), decides what that is worth, and either writes the record or offers a+rep a suggestion. Strong evidence writes. Weak evidence becomes a question for a+human. Both are the system working.-1. `resolve_linkedin_profile` turns an email into **candidate** LinkedIn slugs.- Candidates, never answers.-2. `get_linkedin_profile` reads each candidate. The profile is the source of- truth for name, title and employer.-3. A candidate is only the right person if their current employer matches the- contact's company **and** their name is consistent with the email address.- The tool checks both and tells you; believe it over your own judgement.-4. If no candidate passes, stop. Do not lower the bar.+So there is nothing to argue with and no bar to clear by trying harder. Report+what you found, accurately, and move on.-Search results are not evidence. A search for "Abbie Bigham" once returned-Lavazza's CEO. The search only tells you where to look.+## Where to look, in order-## Two sources, two jobs+1. **`read_crm_history` first, always.** It is free, and it is the best evidence+ we have: a reply from their own address, a signature block, a meeting they+ attended. No data vendor can sell us any of that.+2. **LinkedIn** (`resolve_linkedin_profile` → `get_linkedin_profile`) for+ identity: name, current title, employer, tenure. Self-reported, and+ authoritative for who someone is.+3. **The open web** (`web_search`, `web_fetch`, `research_person`) for context:+ news, funding, what they have said publicly. Sometimes wrong about job+ titles — where it disagrees with LinkedIn about identity, LinkedIn wins.-- **LinkedIn (`get_linkedin_profile`)** is authoritative for *identity*: name,- current title, employer, tenure. It is self-reported by the person.-- **Perplexity (`research_person`, `research_company`)** is for *context*:- recent news, funding, launches, what they have said publicly. It cites its- sources and it is sometimes wrong about job titles — where the two disagree- about identity, LinkedIn wins.+Search results are not evidence. A search for "Abbie Bigham" once returned+Lavazza's CEO. A search tells you where to look.-Use Perplexity for what a rep would want to know before a call, not to work out-who somebody is.+**Not every install has 2 and 3.** They each need an API key, and plenty of+copies of this CRM run with none. Your session instructions list what this one+has before you plan; a tool whose source is missing says so, costs nothing, and+will say the same thing however many times you call it. This is normal, not+broken. Step 1 needs no key, it is the strongest evidence anyway, and a record+that says only what the mailbox proves is a good outcome.-## Writing+## Your budget-`update_contact` is the only way to change a record, and it takes a-`confidence` and a `sourceUrl`. High-confidence matches are written straight-through; anything less is held for a human. Do not try to route around that by-calling it twice.+Each contact comes with a research budget, and vendor calls spend it. When it is+gone, write up what you have and stop — or call `schedule_recheck` with a reason+if it is worth another look later. Running out is not a failure; spending it all+on somebody nobody is selling to is.-Never overwrite a field a human has filled in. The tool enforces this; do not-argue with it.+## Skills-## Tone for anything you write onto a timeline+Load these when the work calls for them, and before your first one of a session:-Short, factual, useful the morning of a call. No preamble, no "I found that",-no restating the contact's own name back at them. If there is nothing worth-saying, say nothing.+- `identity-matching` — deciding whether a candidate really is this person.+- `evidence` — which observation is which `kind`, and why it matters.+- `writing-a-brief` — the Background panel a rep reads before a call.+- `data-boundaries` — what you may read (everything) and what may leave.diff --git a/apps/agent/agent/instructions/task.ts b/apps/agent/agent/instructions/task.tsnew file mode 100644index 00000000..d8b3cce9--- /dev/null+++ b/apps/agent/agent/instructions/task.ts@@ -0,0 +1,101 @@+import { db } from "@crm/db";+import { defineDynamic, defineInstructions } from "eve/instructions";+import { capabilitiesMarkdown } from "../lib/capabilities";+import { focusOn, setBudget } from "../lib/focus";++/**+ * What this particular session is for.+ *+ * `instructions.md` is the agent's permanent identity and is the same every+ * time. This is the opposite: resolved once per session from whoever started+ * it, so a run dispatched for one contact opens already knowing who they are,+ * what the task is, and what it may spend — instead of spending its first two+ * tool calls finding out.+ *+ * Resolved at `session.started` rather than per turn. Prompt caches are keyed+ * on the prompt, so a preamble that changed every turn would re-ingest the+ * whole conversation at uncached prices for information that does not change.+ */+export default defineDynamic({+ events: {+ "session.started": async (_event, ctx) => {+ const attributes = ctx.session.auth.current?.attributes ?? {};+ const contactId = asString(attributes.contactId);+ const budget = asNumber(attributes.budget);+ const reason = asString(attributes.reason);+ const kind = asString(attributes.taskKind);++ // Which outside sources exist is a property of the install, not of the+ // task, so it is stated even for a session that is not about anybody in+ // particular. An agent that learns its limits from four failed tool+ // calls has already spent the budget it needed for the work.+ if (!contactId) {+ return defineInstructions({ markdown: capabilitiesMarkdown() });+ }++ // Seeding the session state here is what lets the audit hook file every+ // event against the right record — a hook sees events, not arguments.+ focusOn({ contactId, sessionId: ctx.session.id });+ if (budget) setBudget(budget);++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: {+ firstName: true,+ lastName: true,+ email: true,+ title: true,+ company: { select: { name: true, domain: true } },+ brief: { select: { refreshedAt: true } },+ _count: { select: { emailThreads: true, calendarEvents: true } },+ },+ });++ if (!contact) {+ return defineInstructions({ markdown: capabilitiesMarkdown() });+ }++ const name = [contact.firstName, contact.lastName]+ .filter(Boolean)+ .join(" ");++ const known =+ contact._count.emailThreads > 0 || contact._count.calendarEvents > 0+ ? `We have ${contact._count.emailThreads} thread(s) and ${contact._count.calendarEvents} meeting(s) with them — read those first.`+ : "We have never corresponded with them, so there is nothing internal to go on.";++ return defineInstructions({+ markdown: [+ "## This session",+ "",+ `You are working on **${name}** (\`${contactId}\`)${+ contact.email ? `, ${contact.email}` : ""+ }${contact.company?.name ? `, at ${contact.company.name}` : ""}.`,+ kind ? `Task: **${kind}**.` : "",+ reason ? `Why now: ${reason}` : "",+ budget+ ? `Budget: **${budget}** vendor calls. Spend them where they matter.`+ : "",+ "",+ known,+ contact.brief+ ? `A background already exists, written ${contact.brief.refreshedAt.toDateString()}. Replace it only if you learn something it does not say.`+ : "There is no background on them yet.",+ "",+ capabilitiesMarkdown(),+ ]+ .filter(Boolean)+ .join("\n"),+ });+ },+ },+});++function asString(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++function asNumber(value: unknown): number | null {+ const parsed = typeof value === "string" ? Number(value) : value;+ return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : null;+}diff --git a/apps/agent/agent/lib/approval.ts b/apps/agent/agent/lib/approval.tsnew file mode 100644index 00000000..80937c99--- /dev/null+++ b/apps/agent/agent/lib/approval.ts@@ -0,0 +1,57 @@+import type { Approval } from "eve/tools";++/**+ * Who is driving, and what that licenses.+ *+ * Two facts shape every approval decision in this agent:+ *+ * 1. eve's own guidance is that model behaviour must not be relied on to+ * prevent sensitive writes. A confidence rubric in a system prompt *is*+ * model behaviour.+ * 2. **A task-mode schedule cannot pause for a person.** "Ask a human when+ * unsure" is therefore not available to a cron run — asking would hang it.+ * The same tool has to behave differently depending on who called it.+ *+ * Note what is deliberately *not* gated: `record_fact`. Its band logic runs in+ * the same function that scores the evidence, so a weak claim cannot be written+ * however the model asks. An approval gate there could only reject calls the+ * tool already rejects, while breaking the thing that makes weak claims+ * useful — being stored as a suggestion. Gates go on writes whose blast radius+ * is bigger than one field.+ */++/** eve's app principal, used by markdown schedules and the dispatcher. */+export function isAutomated(session: {+ auth: {+ current?: {+ authenticator?: string;+ principalId?: string;+ principalType?: string;+ } | null;+ };+}): boolean {+ const auth = session.auth.current;+ return (+ auth?.authenticator === "app" &&+ auth.principalId === "eve:app" &&+ auth.principalType === "runtime"+ );+}++/**+ * For writes that move a record rather than fill a field.+ *+ * Re-parenting a contact to a different company is the example: it changes+ * whose pipeline they are in and which timeline their history hangs off, and+ * getting it wrong is not a typo somebody spots. A person signs it off, or it+ * does not happen unattended.+ */+export function sensitiveWrite(instead: string): Approval {+ return ({ session }) =>+ isAutomated(session)+ ? {+ type: "denied" as const,+ reason: `Not something to do unattended. ${instead}`,+ }+ : "user-approval";+}diff --git a/apps/agent/agent/lib/avatar.ts b/apps/agent/agent/lib/avatar.tsnew file mode 100644index 00000000..5cc053ee--- /dev/null+++ b/apps/agent/agent/lib/avatar.ts@@ -0,0 +1,78 @@+import { put } from "@vercel/blob";++/** Bigger than any avatar, small enough that a redirect to something huge stops here. */+const MAX_BYTES = 3 * 1024 * 1024;+const TIMEOUT_MS = 15_000;++const ALLOWED = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);++/**+ * Mirrors a profile picture into Vercel Blob.+ *+ * LinkedIn's CDN URLs are signed and expire — the ones we fetched carried+ * `e=1787184000`, roughly three weeks out. Storing that URL would give every+ * contact an avatar that works today and is a broken image next month, which is+ * worse than no avatar because nobody would connect the two.+ *+ * So the bytes are copied once and the record points at our own copy.+ *+ * Moved here from the API with the rest of enrichment: whoever writes the URL+ * onto the record is who should own fetching the bytes, and that is now the+ * agent. Plain functions rather than a Nest provider, because there is no+ * container on this side.+ */+export function avatarsEnabled(): boolean {+ return Boolean(process.env.BLOB_READ_WRITE_TOKEN);+}++/**+ * Fetches a remote image and stores it. Returns our URL, or null.+ *+ * Never throws: an avatar is decoration, and a contact whose photo could not be+ * fetched is still a contact worth having.+ */+export async function mirrorAvatar(+ sourceUrl: string,+ contactId: string,+): Promise<string | null> {+ if (!avatarsEnabled()) return null;++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);++ try {+ const response = await fetch(sourceUrl, {+ signal: controller.signal,+ // LinkedIn's CDN rejects requests carrying our origin.+ referrerPolicy: "no-referrer",+ });++ if (!response.ok) return null;++ const type = response.headers.get("content-type")?.split(";")[0]?.trim();+ if (!type || !ALLOWED.has(type)) return null;++ const buffer = await response.arrayBuffer();+ if (buffer.byteLength === 0 || buffer.byteLength > MAX_BYTES) return null;++ // Keyed by contact, so re-running replaces the photo rather than+ // littering the store with orphans.+ const extension = type.split("/")[1] ?? "jpg";+ const blob = await put(+ `contacts/${contactId}.${extension}`,+ Buffer.from(buffer),+ {+ access: "public",+ contentType: type,+ addRandomSuffix: false,+ allowOverwrite: true,+ },+ );++ return blob.url;+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}diff --git a/apps/api/src/enrichment/brand-mapping.ts b/apps/agent/agent/lib/brand-mapping.tssimilarity index 99%rename from apps/api/src/enrichment/brand-mapping.tsrename to apps/agent/agent/lib/brand-mapping.tsindex 8b5c818c..292b36d3 100644--- a/apps/api/src/enrichment/brand-mapping.ts+++ b/apps/agent/agent/lib/brand-mapping.ts@@ -1,5 +1,5 @@import type { Prisma } from "@crm/db";-import type { Brand } from "./context-dev.client";+import type { Brand } from "./context-dev";/*** What the agent is allowed to change about a company.diff --git a/apps/agent/agent/lib/capabilities.ts b/apps/agent/agent/lib/capabilities.tsnew file mode 100644index 00000000..5a7fe2e3--- /dev/null+++ b/apps/agent/agent/lib/capabilities.ts@@ -0,0 +1,133 @@+import "@crm/env/load";++/**+ * What this install can actually do.+ *+ * Every outside source the agent can reach is optional, and most self-hosted+ * copies of this repo will have none of them. That has to be an ordinary+ * operating condition rather than a degraded one, because the best evidence+ * here was never bought: a reply from someone's own address, their signature+ * block, a meeting they turned up to. `read_crm_history` needs no key at all+ * and beats every vendor in this list.+ *+ * So a missing key is not an error anywhere. It removes a place to look, the+ * agent is told which places it has before it plans, and the tools that need+ * one say so plainly and cost nothing. The failure this design exists to+ * prevent is an agent that burns its budget rediscovering that a key is+ * absent, then writes a confident summary from the little it managed to read.+ */++export type Capability = {+ /** The variable to set to turn it on. */+ readonly env: string;+ readonly label: string;+ /** What it adds, in the agent's terms. */+ readonly gives: string;+ readonly enabled: boolean;+};++/**+ * Read on every call rather than captured at import.+ *+ * These are cheap, and a value that was snapshotted at module load is a value+ * that lies in tests and in any process that configures itself late.+ */+export function capabilities(): readonly Capability[] {+ const set = (key: string) => Boolean(process.env[key]?.trim());++ return [+ {+ env: "RAPIDAPI_KEY",+ label: "LinkedIn",+ gives:+ "a person's real name, current title, employer and tenure, self-reported, and so authoritative on identity",+ enabled: set("RAPIDAPI_KEY"),+ },+ {+ env: "PERPLEXITY_API_KEY",+ label: "Web research",+ gives:+ "open-web context with citations, and the search that finds a LinkedIn slug in the first place",+ enabled: set("PERPLEXITY_API_KEY"),+ },+ {+ env: "CONTEXT_DEV_API_KEY",+ label: "Company brand data",+ gives: "a company's logo, industry, location and socials from its domain",+ enabled: set("CONTEXT_DEV_API_KEY"),+ },+ ];+}++/** Whether one source is available, by its variable name. */+export function enabled(env: string): boolean {+ return capabilities().some(+ (capability) => capability.env === env && capability.enabled,+ );+}++/**+ * The result a tool returns when its source is not configured.+ *+ * Deliberately shaped like every other "we could not find out" answer, and+ * deliberately explicit that retrying is pointless — an agent told only+ * "failed" will reasonably try again, and there is nothing on the other end.+ */+export function unavailable(env: string): {+ ok: false;+ configured: false;+ reason: string;+} {+ return {+ ok: false,+ configured: false,+ reason:+ `This install has no ${env}, so that source is unavailable. This is not a failure and retrying will not help — ` ++ "use what the CRM already knows, and say in your write-up what you could not check.",+ };+}++/**+ * The capability list, as a section for the session instructions.+ *+ * Both halves are stated. An agent told only what it has will keep proposing+ * the tool it does not, and one told only what it lacks reads it as a fault to+ * work around.+ */+export function capabilitiesMarkdown(): string {+ const all = capabilities();+ const on = all.filter((capability) => capability.enabled);+ const off = all.filter((capability) => !capability.enabled);++ const lines = ["## What you can use here", ""];++ if (on.length === 0) {+ lines.push(+ "No outside sources are configured on this install. Everything you can",+ "learn is already in the CRM — email threads, meetings, signature",+ "blocks — and `read_crm_history` reads all of it for free. That is",+ "often enough to settle who somebody is. Record what it shows, and",+ "leave the rest empty.",+ );+ return lines.join("\n");+ }++ lines.push("Available:");+ for (const capability of on) {+ lines.push(`- **${capability.label}** — ${capability.gives}.`);+ }++ if (off.length > 0) {+ lines.push("", "Not configured here, so do not plan around them:");+ for (const capability of off) {+ lines.push(`- ${capability.label}`);+ }+ lines.push(+ "",+ "Their tools will tell you the same thing if you call them. Note what",+ "you could not check rather than guessing at it.",+ );+ }++ return lines.join("\n");+}diff --git a/apps/agent/agent/lib/context-dev.ts b/apps/agent/agent/lib/context-dev.tsnew file mode 100644index 00000000..730e115c--- /dev/null+++ b/apps/agent/agent/lib/context-dev.ts@@ -0,0 +1,290 @@+import ContextDev from "context.dev";+import { APIError } from "context.dev/core/error";++/**+ * Context.dev: brand data, web extraction and web search.+ *+ * Moved here from `apps/api/src/enrichment` unchanged in behaviour. It is the+ * same client with the Nest scaffolding taken off — the API is not allowed to+ * know this vendor exists, and a class that needs a DI container is awkward in+ * a runtime that does not have one.+ */++/** The Context.dev `brand` object, narrowed to the parts we map. */+export type Brand = {+ domain?: string | null;+ title?: string | null;+ description?: string | null;+ slogan?: string | null;+ email?: string | null;+ phone?: string | null;+ colors?: { hex?: string | null; name?: string | null }[] | null;+ logos?:+ | {+ url?: string | null;+ /** "light" | "dark" | "has_opaque_background". */+ mode?: string | null;+ type?: string | null;+ /** The artwork's own dominant colours — how a dark mark is detected. */+ colors?: { hex?: string | null; name?: string | null }[] | null;+ }[]+ | null;+ socials?: { type?: string | null; url?: string | null }[] | null;+ address?: {+ city?: string | null;+ state_code?: string | null;+ country?: string | null;+ country_code?: string | null;+ } | null;+ industries?: {+ eic?: { industry?: string | null; subindustry?: string | null }[] | null;+ } | null;+ links?: {+ pricing?: string | null;+ careers?: string | null;+ } | null;+};++/**+ * Why a lookup did not produce a brand.+ *+ * `skipped` and `failed` are deliberately different: "there is nothing to find+ * for this domain" is a settled answer that should stop us retrying and cost+ * nothing, while "the call fell over" is worth another go.+ */+export type LookupResult =+ | { outcome: "found"; brand: Brand; raw: unknown }+ | { outcome: "skipped"; reason: string }+ | { outcome: "failed"; reason: string; retryable: boolean };++/** One web search result, narrowed to the parts a person lookup reads. */+export type SearchResult = {+ url: string | null;+ title: string | null;+ description: string | null;+ markdown: string | null;+};++/** Cold lookups are p50 ≈ 7s, p90 ≈ 18s — so this is generous on purpose. */+const TIMEOUT_MS = 60_000;++/**+ * Resolved on first use rather than at import, because the agent's environment+ * is not necessarily populated at module-evaluation time.+ */+let client: ContextDev | null | undefined;++function contextDev(): ContextDev | null {+ if (client === undefined) {+ const apiKey = process.env.CONTEXT_DEV_API_KEY;+ client = apiKey ? new ContextDev({ apiKey }) : null;+ }+ return client;+}++export function contextDevEnabled(): boolean {+ return contextDev() !== null;+}++/** `POST /brand/retrieve` by domain. 10 credits, only on a successful match. */+export async function brandByDomain(+ domain: string,+ maxAgeMs?: number,+): Promise<LookupResult> {+ return lookup({+ type: "by_domain",+ domain,+ timeoutMS: TIMEOUT_MS,+ ...(maxAgeMs === undefined ? {} : { maxAgeMs }),+ });+}++/** `POST /brand/retrieve` by work email — the domain is extracted for us. */+export async function brandByEmail(email: string): Promise<LookupResult> {+ return lookup({ type: "by_email", email, timeoutMS: TIMEOUT_MS });+}++/**+ * Warms the cache so a later retrieve lands sub-second. Free, and+ * fire-and-forget: the response carries no brand data.+ *+ * Paid plans only. A 403 here is a plan limit rather than a bug, and either way+ * the caller falls through to a direct retrieve — so nothing is reported.+ */+export async function prefetch(domain: string): Promise<void> {+ const api = contextDev();+ if (!api) return;++ try {+ await api.utility.prefetch({ type: "brand", identifier: { domain } });+ } catch {+ // Deliberately silent; see above.+ }+}++/**+ * `POST /web/extract` against a caller-defined JSON Schema.+ *+ * Used for a company brief, which is not a brand lookup — it is "read this+ * company's site and answer these questions".+ */+export async function extract(+ url: string,+ schema: Record<string, unknown>,+ instructions: string,+): Promise<+ { outcome: "found"; data: unknown } | { outcome: "failed"; reason: string }+> {+ const api = contextDev();+ if (!api) {+ return { outcome: "failed", reason: "Context.dev is not configured." };+ }++ try {+ const response = await api.web.extract({+ url,+ schema,+ instructions,+ maxPages: 8,+ timeoutMS: TIMEOUT_MS,+ });+ return { outcome: "found", data: response.data };+ } catch (error) {+ return { outcome: "failed", reason: describe(error) };+ }+}++/**+ * `POST /web/search`.+ *+ * Accepts Google-style operators, which is what makes a person lookup *sourced*+ * rather than guessed: we search for evidence and read a name off a page,+ * instead of asking a model what "abigham" probably stands for.+ */+export async function search(+ query: string,+ options: { limit?: number; excludeDomains?: string[] } = {},+): Promise<+ | { outcome: "found"; results: SearchResult[] }+ | { outcome: "failed"; reason: string }+> {+ const api = contextDev();+ if (!api) {+ return { outcome: "failed", reason: "Context.dev is not configured." };+ }++ try {+ const response = await api.web.search({+ query,+ // The API rejects anything under 10 — a smaller ask fails validation+ // rather than returning fewer results.+ numResults: Math.max(options.limit ?? 10, 10),+ // Without this the results are titles and snippets only, and a name is+ // usually in the page rather than the snippet.+ markdownOptions: { enabled: true },+ ...(options.excludeDomains+ ? { excludeDomains: options.excludeDomains }+ : {}),+ });++ const results = (response.results ?? []).map((result) => ({+ url: result.url ?? null,+ title: result.title ?? null,+ description: result.description ?? null,+ // `code` is the per-result scrape outcome; anything but SUCCESS means+ // `markdown` is null and the snippet is all we have.+ markdown:+ result.markdown?.code === "SUCCESS"+ ? (result.markdown.markdown ?? null)+ : null,+ }));++ return { outcome: "found", results };+ } catch (error) {+ return { outcome: "failed", reason: describe(error) };+ }+}++async function lookup(+ params: Parameters<ContextDev["brand"]["retrieve"]>[0],+): Promise<LookupResult> {+ const api = contextDev();+ if (!api) {+ return { outcome: "skipped", reason: "Context.dev is not configured." };+ }++ try {+ const response = await api.brand.retrieve(params);+ const brand = response.brand as Brand | undefined;++ if (!brand) return { outcome: "skipped", reason: "No brand matched." };++ return { outcome: "found", brand, raw: response };+ } catch (error) {+ return classify(error);+ }+}++/**+ * Maps Context.dev's failures onto something the CRM can act on.+ *+ * The important distinction is which of these should leave a company retryable.+ * An unknown domain never becomes known by asking again; a timeout might.+ */+function classify(error: unknown): LookupResult {+ if (!(error instanceof APIError)) {+ return { outcome: "failed", reason: describe(error), retryable: true };+ }++ const code = errorCode(error);++ // 400 covers both malformed input and "we looked, there is nothing there".+ // Neither is billed, and neither is worth retrying.+ if (error.status === 400) {+ if (code === "NOT_FOUND" || code === "WEBSITE_ACCESS_ERROR") {+ return {+ outcome: "skipped",+ reason:+ code === "NOT_FOUND"+ ? "No brand matched this domain."+ : "The site could not be reached.",+ };+ }+ return { outcome: "failed", reason: describe(error), retryable: false };+ }++ // A personal or throwaway address says nothing about where someone works.+ if (error.status === 422) {+ return {+ outcome: "skipped",+ reason: "That is a personal or disposable email address.",+ };+ }++ if (error.status === 401 || error.status === 403) {+ return { outcome: "failed", reason: describe(error), retryable: false };+ }++ // Cold-cache timeouts and rate limits are the retryable ones.+ if (error.status === 408 || error.status === 429) {+ return { outcome: "failed", reason: describe(error), retryable: true };+ }++ return {+ outcome: "failed",+ reason: describe(error),+ retryable: (error.status ?? 500) >= 500,+ };+}++function errorCode(error: APIError): string | undefined {+ const body = error.error as { error_code?: unknown } | undefined;+ return typeof body?.error_code === "string" ? body.error_code : undefined;+}++function describe(error: unknown): string {+ if (error instanceof APIError) {+ return `${error.status ?? "?"} ${errorCode(error) ?? error.message}`;+ }+ return error instanceof Error ? error.message : String(error);+}diff --git a/apps/agent/agent/lib/crm.ts b/apps/agent/agent/lib/crm.tsindex 4b54fc06..6ceac406 100644--- a/apps/agent/agent/lib/crm.ts+++ b/apps/agent/agent/lib/crm.ts@@ -1,5 +1,6 @@-import { db } from "@crm/db";-import { domainOf, nameMatchesLocalPart } from "./names";+import { db, EnrichmentStatus } from "@crm/db";+import { domainOf, isDerivedName } from "./names";+import type { Person } from "./socials";/*** The CRM, as far as this agent is concerned.@@ -7,31 +8,45 @@ import { domainOf, nameMatchesLocalPart } from "./names";* Straight to Postgres through the workspace package rather than through a new* internal HTTP API: `@crm/db` is already shared by the API and the app, and a* third caller does not justify inventing a service boundary.+ *+ * Everything that *writes a claim* lives in `facts.ts` instead. This file reads,+ * and does the two bookkeeping writes that are not claims about a person: the+ * "we looked" stamp and the enrichment status the sheet polls.*/-export type EnrichableContact = {+export type WorkItem = {id: string;- email: string;- firstName: string;- lastName: string | null;+ fullName: string;+ email: string | null;title: string | null;companyName: string | null;companyDomain: string | null;+ linkedinUrl: string | null;+ /** What is missing, so the agent does not redo the parts that are done. */+ needs: {+ identity: boolean;+ brief: boolean;+ socials: boolean;+ };};/**- * Contacts worth spending a lookup on.+ * Everything the agent could usefully do to a contact right now.*- * Only ones whose name is still derived from their address — a name a human or- * a mail header supplied is already better than anything research will find.+ * One query instead of the two "list contacts that need X" tools this replaced.+ * Those encoded the *order* of the work in their names, which is exactly the+ * decision the agent is supposed to be making: whether an unnamed contact on a+ * live deal matters more than a named one with no background is a judgement,+ * not a schedule.*/-export async function contactsNeedingResearch(- limit: number,-): Promise<EnrichableContact[]> {+export async function contactsNeedingWork(limit: number): Promise<WorkItem[]> {const rows = await db.contact.findMany({where: {- email: { not: null },- source: { in: ["EMAIL", "CALENDAR"] },+ OR: [+ { brief: { is: null } },+ { socialsCheckedAt: null },+ { AND: [{ email: { not: null } }, { lastName: null }] },+ ],},select: {id: true,@@ -39,101 +54,299 @@ export async function contactsNeedingResearch(firstName: true,lastName: true,title: true,+ linkedinUrl: true,+ socialsCheckedAt: true,company: { select: { name: true, domain: true } },+ brief: { select: { contactId: true } },+ },+ orderBy: { createdAt: "asc" },+ take: limit,+ });++ return rows.map((row) => ({+ id: row.id,+ fullName: [row.firstName, row.lastName].filter(Boolean).join(" "),+ email: row.email,+ title: row.title,+ companyName: row.company?.name ?? null,+ companyDomain:+ row.company?.domain ?? (row.email ? domainOf(row.email) : null),+ linkedinUrl: row.linkedinUrl,+ needs: {+ identity: isDerivedName(row.email, row.firstName, row.lastName),+ brief: row.brief === null,+ socials: row.socialsCheckedAt === null,},- orderBy: { createdAt: "desc" },- take: limit * 4,+ }));+}++/**+ * Who the CRM says this person is — the only input the verification checks are+ * allowed to measure a candidate against.+ *+ * Loaded here rather than taken from tool arguments: a check run against a name+ * and employer the model supplied is a check the model can pass by supplying+ * different ones.+ */+export async function personForVerification(+ contactId: string,+): Promise<Person | null> {+ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: {+ firstName: true,+ lastName: true,+ title: true,+ email: true,+ company: { select: { name: true, domain: true } },+ },+ });++ if (!contact) return null;++ return {+ firstName: contact.firstName,+ lastName: contact.lastName,+ fullName: [contact.firstName, contact.lastName].filter(Boolean).join(" "),+ title: contact.title,+ companyName: contact.company?.name ?? null,+ companyDomain:+ contact.company?.domain ??+ (contact.email ? domainOf(contact.email) : null),+ };+}++/** The LinkedIn slug on a contact, or null if they have no profile on file. */+export async function contactProfileSlug(+ contactId: string,+): Promise<{ slug: string; profileUrl: string } | null> {+ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: { linkedinUrl: true },});- return rows- .filter((row) => row.email !== null)- .filter((row) => {- const local = row.email?.split("@")[0] ?? "";- // `nameMatchesLocalPart` is true for a real name too, so the test is- // specifically "no surname and the first name is the whole handle".- return (- row.lastName === null &&- nameMatchesLocalPart(- { firstName: row.firstName, lastName: null },- local,- )- );- })- .slice(0, limit)- .map((row) => ({- id: row.id,- email: row.email as string,- firstName: row.firstName,- lastName: row.lastName,- title: row.title,- companyName: row.company?.name ?? null,- companyDomain: row.company?.domain ?? domainOf(row.email as string),- }));+ const slug = linkedinSlug(contact?.linkedinUrl ?? null);+ return slug+ ? { slug, profileUrl: `https://www.linkedin.com/in/${slug}` }+ : null;}-export type ContactPatch = {- firstName?: string;- lastName?: string | null;- title?: string;- linkedinUrl?: string;+/** `https://www.linkedin.com/in/lewiscarhart/` → `lewiscarhart`. */+export function linkedinSlug(url: string | null): string | null {+ if (!url) return null;+ const match = /linkedin\.com\/in\/([A-Za-z0-9\-_%]+)/.exec(url);+ return match?.[1] ?? null;+}++export type CrmHistory = {+ contact: {+ fullName: string;+ email: string | null;+ title: string | null;+ companyName: string | null;+ };+ threads: {+ subject: string | null;+ messageCount: number;+ lastMessageAt: string;+ messages: {+ direction: string;+ from: string;+ fromName: string | null;+ sentAt: string;+ /** The whole message. See the note on this function. */+ body: string | null;+ }[];+ }[];+ meetings: {+ title: string | null;+ startsAt: string;+ attended: boolean;+ attendees: { email: string; name: string | null }[];+ }[];+ stats: {+ emails: number;+ theyReplied: boolean;+ lastReplyAt: string | null;+ meetings: number;+ nextMeetingAt: string | null;+ };+ colleagues: { id: string; name: string; title: string | null }[];};/**- * Applies a patch, refusing to overwrite anything a human filled in.+ * Everything we already know about this person from our own mailbox and+ * calendar — **including full message bodies**.*- * Returns the fields it actually changed, so the agent is told what happened- * rather than assuming its write landed.+ * This is the single biggest advantage we have over a data vendor, and it is+ * not close. A reply on a thread is proof of identity nobody can sell us. A+ * signature block settles a job title outright, and it settles it more+ * reliably than LinkedIn, because people update their signature when they get+ * promoted and update LinkedIn when they change jobs.+ *+ * Bodies are included deliberately: this is a single-tenant internal tool and+ * the data is already ours. The boundary is egress, not access — see the+ * `data-boundaries` skill. Nothing returned here may be pasted into a web+ * search, written to the sandbox, or logged.*/-export async function patchContact(+export async function readCrmHistory(contactId: string,- patch: ContactPatch,-): Promise<{ changed: string[] }> {- const current = await db.contact.findUnique({+ options: { threads?: number; messagesPerThread?: number } = {},+): Promise<CrmHistory | null> {+ const contact = await db.contact.findUnique({where: { id: contactId },select: {- email: true,+ id: true,firstName: true,lastName: true,+ email: true,title: true,- linkedinUrl: true,+ companyId: true,+ company: { select: { name: true } },},});- if (!current?.email) return { changed: [] };-- const local = current.email.split("@")[0] ?? "";- const derivedName =- current.lastName === null &&- nameMatchesLocalPart(- { firstName: current.firstName, lastName: null },- local,- );-- const data: ContactPatch = {};- const changed: string[] = [];-- // The name may only be replaced while it is still the placeholder the sync- // derived from the address.- if (patch.firstName && derivedName) {- data.firstName = patch.firstName;- data.lastName = patch.lastName ?? null;- changed.push("name");- }-- // Everything else fills gaps only.- if (patch.title && !current.title) {- data.title = patch.title;- changed.push("title");- }- if (patch.linkedinUrl && !current.linkedinUrl) {- data.linkedinUrl = patch.linkedinUrl;- changed.push("linkedinUrl");- }-- if (changed.length === 0) return { changed: [] };-- await db.contact.update({ where: { id: contactId }, data });- return { changed };+ if (!contact) return null;++ const [threads, meetings, colleagues] = await Promise.all([+ db.emailThread.findMany({+ where: { contactId },+ orderBy: { lastMessageAt: "desc" },+ take: options.threads ?? 5,+ select: {+ subject: true,+ messageCount: true,+ lastMessageAt: true,+ messages: {+ orderBy: { sentAt: "desc" },+ take: options.messagesPerThread ?? 6,+ select: {+ direction: true,+ fromEmail: true,+ fromName: true,+ sentAt: true,+ body: true,+ snippet: true,+ },+ },+ },+ }),+ db.calendarEvent.findMany({+ where: {+ OR: [{ contactId }, { attendees: { some: { contactId } } }],+ },+ orderBy: { startsAt: "desc" },+ take: 10,+ select: {+ title: true,+ startsAt: true,+ attendees: {+ select: {+ email: true,+ name: true,+ contactId: true,+ responseStatus: true,+ },+ },+ },+ }),+ contact.companyId+ ? db.contact.findMany({+ where: { companyId: contact.companyId, id: { not: contactId } },+ select: { id: true, firstName: true, lastName: true, title: true },+ take: 8,+ orderBy: { lastActivityAt: "desc" },+ })+ : Promise.resolve([]),+ ]);++ const inbound = threads+ .flatMap((thread) => thread.messages)+ .filter((message) => message.direction === "INBOUND")+ .sort((a, b) => b.sentAt.getTime() - a.sentAt.getTime());++ const now = new Date();+ const upcoming = meetings+ .filter((meeting) => meeting.startsAt > now)+ .sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime());++ return {+ contact: {+ fullName: [contact.firstName, contact.lastName].filter(Boolean).join(" "),+ email: contact.email,+ title: contact.title,+ companyName: contact.company?.name ?? null,+ },+ threads: threads.map((thread) => ({+ subject: thread.subject,+ messageCount: thread.messageCount,+ lastMessageAt: thread.lastMessageAt.toISOString(),+ messages: thread.messages.map((message) => ({+ direction: message.direction,+ from: message.fromEmail,+ fromName: message.fromName,+ sentAt: message.sentAt.toISOString(),+ body: message.body ?? message.snippet,+ })),+ })),+ meetings: meetings.map((meeting) => ({+ title: meeting.title,+ startsAt: meeting.startsAt.toISOString(),+ attended: meeting.attendees.some(+ (attendee) =>+ attendee.contactId === contactId &&+ attendee.responseStatus === "accepted",+ ),+ attendees: meeting.attendees.map((attendee) => ({+ email: attendee.email,+ name: attendee.name,+ })),+ })),+ stats: {+ emails: threads.reduce((total, thread) => total + thread.messageCount, 0),+ theyReplied: inbound.length > 0,+ lastReplyAt: inbound[0]?.sentAt.toISOString() ?? null,+ meetings: meetings.length,+ nextMeetingAt: upcoming[0]?.startsAt.toISOString() ?? null,+ },+ colleagues: colleagues.map((colleague) => ({+ id: colleague.id,+ name: [colleague.firstName, colleague.lastName].filter(Boolean).join(" "),+ title: colleague.title,+ })),+ };+}++/** Records that we went looking, so nobody looks again next hour. */+export async function stampSocialsChecked(contactId: string): Promise<void> {+ await db.contact.update({+ where: { id: contactId },+ data: { socialsCheckedAt: new Date() },+ });+}++/**+ * The status the contact sheet polls on, mirroring `Company`.+ *+ * Background writes are not invalidations — no client action caused them — so+ * the browser can only find out by asking, and it only knows to stop asking+ * when this settles.+ */+export async function setEnrichmentStatus(+ contactId: string,+ status: EnrichmentStatus,+ error?: string,+): Promise<void> {+ await db.contact.update({+ where: { id: contactId },+ data: {+ enrichmentStatus: status,+ enrichmentError: error ?? null,+ ...(status === EnrichmentStatus.COMPLETE+ ? { enrichedAt: new Date() }+ : {}),+ },+ });}/** Writes a note onto the contact's timeline, stamped as agent-written. */diff --git a/apps/agent/agent/lib/evidence.ts b/apps/agent/agent/lib/evidence.tsnew file mode 100644index 00000000..87966e3e--- /dev/null+++ b/apps/agent/agent/lib/evidence.ts@@ -0,0 +1,210 @@+import { FactBand } from "@crm/db";++/**+ * How sure we are, and why.+ *+ * The rule this exists to enforce is that a score is never asserted — not by+ * the model, not by a tool author. A score is *derived* from a list of things+ * that were actually observed, each of which names what it is and where it came+ * from. That makes two otherwise impossible things possible: telling a rep why+ * a field says what it says, and re-calibrating every band in the database+ * without re-running a single lookup.+ *+ * The weights below are starting values to be moved by evals, not truths. What+ * is *not* negotiable is the shape: a primary source is required before+ * anything is written automatically, and a contradiction is never averaged+ * away.+ */++export type EvidenceKind =+ | "profile.email-match"+ | "linkedin.employer-and-name"+ | "crm.thread-reply"+ | "crm.signature-block"+ | "github.account-identity"+ | "crm.meeting-attendance"+ | "web.cited-claim"+ | "handle.name-form"+ | "search.cites-profile"+ | "employer-only"+ | "contradiction";++type Weighting = {+ weight: number;+ /**+ * Whether this evidence can carry a fact on its own.+ *+ * Only sources that identify *this person* qualify. Three non-primary+ * signals multiply to a confident-looking number and remain three weak+ * signals, which is the arithmetic that would otherwise let "a handle that+ * looks like their name" become a written fact.+ */+ primary: boolean;+ /** Shown to a rep in the provenance tooltip. Written for them, not for us. */+ label: string;+};++export const WEIGHTS: Record<EvidenceKind, Weighting> = {+ "profile.email-match": {+ weight: 0.95,+ primary: true,+ label: "their email address is on the profile",+ },+ "linkedin.employer-and-name": {+ weight: 0.85,+ primary: true,+ label: "LinkedIn: employer and name both match",+ },+ // Ours, and near the top. A person replying on a thread is proof of identity+ // that no data vendor can sell us, because it happened in our own mailbox.+ "crm.thread-reply": {+ weight: 0.85,+ primary: true,+ label: "they replied on a thread we have",+ },+ "crm.signature-block": {+ weight: 0.8,+ primary: true,+ label: "their own email signature says so",+ },+ "github.account-identity": {+ weight: 0.8,+ primary: true,+ label: "the GitHub account names them or their employer",+ },+ "crm.meeting-attendance": {+ weight: 0.7,+ primary: true,+ label: "they attended a meeting on our calendar",+ },+ "web.cited-claim": {+ weight: 0.4,+ primary: false,+ label: "a cited web source states it",+ },+ "handle.name-form": {+ weight: 0.35,+ primary: false,+ label: "the handle is a form of their name",+ },+ "search.cites-profile": {+ weight: 0.35,+ primary: false,+ label: "a search for them cites this profile",+ },+ "employer-only": {+ weight: 0.2,+ primary: false,+ label: "the employer matches, the name does not",+ },+ // Not evidence for anything — evidence that something is wrong.+ contradiction: {+ weight: 0,+ primary: false,+ label: "another source disagrees",+ },+};++export type Evidence = {+ kind: EvidenceKind;+ /** What was actually seen, in a rep's words. */+ detail: string;+ sourceUrl?: string;+};++export type Scored = {+ score: number;+ band: FactBand | null;+ hasPrimary: boolean;+ /** Why it landed where it did — the sentence shown under a proposal. */+ rationale: string;+};++/** Nothing is certain, so nothing scores 1. */+const CEILING = 0.99;++/** A contradiction cannot be outvoted, only investigated. */+const CONTRADICTED = 0.45;++export const BAND_FLOOR = { VERIFIED: 0.85, PROBABLE: 0.55, POSSIBLE: 0.3 };++/**+ * Combines independent evidence.+ *+ * `1 − Π(1 − wᵢ)` — the probability that at least one of them is right, if they+ * were independent and calibrated. They are neither, which is why §9's evals+ * exist and why the number is rendered as a word.+ */+export function scoreEvidence(evidence: Evidence[]): Scored {+ if (evidence.length === 0) {+ return {+ score: 0,+ band: null,+ hasPrimary: false,+ rationale: "No evidence.",+ };+ }++ const contradicted = evidence.some((item) => item.kind === "contradiction");+ const hasPrimary = evidence.some((item) => WEIGHTS[item.kind].primary);++ const combined = evidence.reduce(+ (remaining, item) => remaining * (1 - WEIGHTS[item.kind].weight),+ 1,+ );++ let score = Math.min(CEILING, 1 - combined);+ if (contradicted) score = Math.min(score, CONTRADICTED);++ return {+ score,+ band: bandFor(score, hasPrimary),+ hasPrimary,+ rationale: rationaleFor(evidence, contradicted, hasPrimary),+ };+}++/**+ * The band, which is the behaviour.+ *+ * `VERIFIED` needs a primary source *and* the score — a fact good enough to+ * write without asking is a fact somebody's own page, mailbox or profile+ * asserts.+ */+export function bandFor(score: number, hasPrimary: boolean): FactBand | null {+ if (score >= BAND_FLOOR.VERIFIED && hasPrimary) return FactBand.VERIFIED;+ if (score >= BAND_FLOOR.PROBABLE) return FactBand.PROBABLE;+ if (score >= BAND_FLOOR.POSSIBLE) return FactBand.POSSIBLE;+ return null;+}++function rationaleFor(+ evidence: Evidence[],+ contradicted: boolean,+ hasPrimary: boolean,+): string {+ const reasons = evidence+ .filter((item) => item.kind !== "contradiction")+ .map((item) => WEIGHTS[item.kind].label);++ if (contradicted) {+ const clash = evidence.find((item) => item.kind === "contradiction");+ return `Held: ${clash?.detail ?? "sources disagree"}.`;+ }++ if (reasons.length === 0) return "No supporting evidence.";++ const list = joinWords(reasons);+ return hasPrimary+ ? capitalise(list)+ : `${capitalise(list)} — but nothing that identifies them directly.`;+}++function joinWords(words: string[]): string {+ if (words.length === 1) return words[0] as string;+ return `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;+}++function capitalise(value: string): string {+ return value.charAt(0).toUpperCase() + value.slice(1);+}diff --git a/apps/agent/agent/lib/facts.ts b/apps/agent/agent/lib/facts.tsnew file mode 100644index 00000000..9429bbe9--- /dev/null+++ b/apps/agent/agent/lib/facts.ts@@ -0,0 +1,332 @@+import { db, FactBand, FactStatus } from "@crm/db";+import { type Evidence, scoreEvidence } from "./evidence";+import { currentFocus } from "./focus";+import { isDerivedName, splitName } from "./names";++/**+ * The only way a claim reaches a contact record.+ *+ * Three rules live here rather than in a prompt, because a rule the model is+ * asked to follow is a rule the model can talk itself out of:+ *+ * 1. **A human outranks the agent.** A value on the record with no fact behind+ * it was typed by a person, and is never overwritten.+ * 2. **A dismissal is final.** Once a rep has said no to a value, it is not+ * offered again — otherwise every run re-proposes it and the suggestion+ * becomes something reps click through without reading.+ * 3. **Nothing is written without a primary source**, whatever the arithmetic+ * says. Enforced by `bandFor`, restated here because it is the rule that+ * stops a plausible stranger becoming a customer record.+ */++/**+ * The fields a fact may be about.+ *+ * `column` is the `Contact` field an applied fact writes through to; the ones+ * without a column are true of the person but have nowhere on the record to+ * live, so they are read straight from the fact by the background panel. That+ * is deliberate: `employer` as a fact rather than a column is what makes a job+ * change a superseded row instead of a diffing job.+ */+const FIELDS = {+ /**+ * Their actual name. Applied by splitting into `firstName`/`lastName`, and+ * guarded differently from everything else — see `humanOwns`.+ */+ name: { column: null },+ title: { column: "title" },+ linkedinUrl: { column: "linkedinUrl" },+ twitterUrl: { column: "twitterUrl" },+ githubUrl: { column: "githubUrl" },+ employer: { column: null },+ seniority: { column: null },+ function: { column: null },+ location: { column: null },+ tenure: { column: null },+} as const;++export type FactField = keyof typeof FIELDS;++export const FACT_FIELDS = Object.keys(FIELDS) as FactField[];++export type RecordFactInput = {+ contactId: string;+ field: FactField;+ value: string;+ evidence: Evidence[];+ method: string;+ sourceUrl?: string;+};++export type RecordFactResult = {+ stored: boolean;+ applied: boolean;+ band: FactBand | null;+ score: number;+ rationale: string;+ /** Why nothing happened, when nothing happened. Written for the model. */+ reason?: string;+};++export async function recordFact(+ input: RecordFactInput,+): Promise<RecordFactResult> {+ const { contactId, field, value } = input;+ const trimmed = value.trim();++ const scored = scoreEvidence(input.evidence);+ const base = {+ score: scored.score,+ band: scored.band,+ rationale: scored.rationale,+ };++ if (!trimmed) {+ return { ...base, stored: false, applied: false, reason: "Empty value." };+ }++ if (scored.band === null) {+ return {+ ...base,+ stored: false,+ applied: false,+ reason:+ "Below the floor for keeping — not stored. Find a source that identifies them, or leave the field alone.",+ };+ }++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: {+ id: true,+ email: true,+ firstName: true,+ lastName: true,+ title: true,+ linkedinUrl: true,+ twitterUrl: true,+ githubUrl: true,+ },+ });++ if (!contact) {+ return {+ ...base,+ stored: false,+ applied: false,+ reason: "No such contact.",+ };+ }++ const existing = await db.contactFact.findMany({+ where: { contactId, field },+ select: { id: true, value: true, status: true },+ });++ if (+ existing.some(+ (fact) =>+ fact.status === FactStatus.DISMISSED && sameValue(fact.value, trimmed),+ )+ ) {+ return {+ ...base,+ stored: false,+ applied: false,+ reason:+ "A person has already dismissed this exact value. Do not offer it again.",+ };+ }++ const currentApplied = existing.find(+ (fact) => fact.status === FactStatus.APPLIED,+ );++ if (currentApplied && sameValue(currentApplied.value, trimmed)) {+ return {+ ...base,+ stored: false,+ applied: false,+ reason: "Already on the record, from this same source. Nothing changed.",+ };+ }++ const column = FIELDS[field].column;++ if (+ humanOwns({ field, column, contact, hasAgentFact: Boolean(currentApplied) })+ ) {+ return {+ ...base,+ stored: false,+ applied: false,+ reason: `A person already filled in ${field}. That outranks anything found on the web.`,+ };+ }++ const applies = scored.band === FactBand.VERIFIED;+ const sessionId = currentFocus().sessionId;++ await db.$transaction(async (tx) => {+ if (applies && currentApplied) {+ // The old value is not deleted — it is history, and for `employer` it+ // is the job change itself.+ await tx.contactFact.update({+ where: { id: currentApplied.id },+ data: { status: FactStatus.SUPERSEDED, supersededAt: new Date() },+ });+ }++ await tx.contactFact.create({+ data: {+ contactId,+ field,+ value: trimmed,+ score: scored.score,+ band: scored.band as FactBand,+ evidence: input.evidence as unknown as object,+ method: input.method,+ sourceUrl: input.sourceUrl ?? null,+ sessionId,+ status: applies ? FactStatus.APPLIED : FactStatus.PROPOSED,+ },+ });++ if (!applies) return;++ if (column) {+ await tx.contact.update({+ where: { id: contactId },+ data: { [column]: trimmed },+ });+ }++ if (field === "name") {+ const split = splitName(trimmed);+ if (split) {+ await tx.contact.update({+ where: { id: contactId },+ data: { firstName: split.firstName, lastName: split.lastName },+ });+ }+ }+ });++ return {+ ...base,+ stored: true,+ applied: applies,+ reason: applies+ ? undefined+ : "Kept as a proposal for a rep to accept or dismiss. This is a normal outcome, not a failure — do not try to raise the score.",+ };+}++/** Whether a job change just happened: an applied `employer` fact superseded. */+export async function lastEmployerChange(contactId: string) {+ const [previous, current] = await Promise.all([+ db.contactFact.findFirst({+ where: { contactId, field: "employer", status: FactStatus.SUPERSEDED },+ orderBy: { supersededAt: "desc" },+ select: { value: true, supersededAt: true },+ }),+ db.contactFact.findFirst({+ where: { contactId, field: "employer", status: FactStatus.APPLIED },+ orderBy: { observedAt: "desc" },+ select: { value: true, observedAt: true, sourceUrl: true },+ }),+ ]);++ if (!previous || !current || sameValue(previous.value, current.value)) {+ return null;+ }++ return {+ from: previous.value,+ to: current.value,+ observedAt: current.observedAt,+ sourceUrl: current.sourceUrl,+ };+}++export type BriefSections = {+ currentRole?: string;+ tenure?: string;+ previousRoles?: string[];+ seniority?: string;+ function?: string;+ location?: string;+};++export async function writeBrief(input: {+ contactId: string;+ narrative: string;+ sections: BriefSections;+ evidence: Evidence[];+ sourceUrl?: string;+}): Promise<{ written: boolean; score: number; reason?: string }> {+ const scored = scoreEvidence(input.evidence);++ if (scored.band === null) {+ return {+ written: false,+ score: scored.score,+ reason: "Nothing here is sourced well enough to put on the record.",+ };+ }++ const data = {+ narrative: input.narrative.trim(),+ sections: input.sections as unknown as object,+ score: scored.score,+ sourceUrl: input.sourceUrl ?? null,+ sessionId: currentFocus().sessionId,+ refreshedAt: new Date(),+ };++ await db.contactBrief.upsert({+ where: { contactId: input.contactId },+ create: { contactId: input.contactId, ...data },+ update: data,+ });++ return { written: true, score: scored.score };+}++/**+ * Whether the value already there belongs to a person rather than to us.+ *+ * For ordinary fields the test is simple: something is in the column and no+ * applied fact explains it, so a human typed it.+ *+ * A name needs a different test, because the sync always writes one. `Abigham`+ * is a placeholder derived from `[email protected]` and is ours to replace;+ * anything that is not derived came from a mail header or a person, and is not.+ */+function humanOwns({+ field,+ column,+ contact,+ hasAgentFact,+}: {+ field: FactField;+ column: string | null;+ contact: {+ email: string | null;+ firstName: string;+ lastName: string | null;+ } & Record<string, unknown>;+ hasAgentFact: boolean;+}): boolean {+ if (field === "name") {+ return !isDerivedName(contact.email, contact.firstName, contact.lastName);+ }++ if (!column || hasAgentFact) return false;++ return Boolean(contact[column]);+}++function sameValue(a: string, b: string): boolean {+ return a.trim().toLowerCase() === b.trim().toLowerCase();+}diff --git a/apps/agent/agent/lib/focus.ts b/apps/agent/agent/lib/focus.tsnew file mode 100644index 00000000..46f223ce--- /dev/null+++ b/apps/agent/agent/lib/focus.ts@@ -0,0 +1,78 @@+import { defineState } from "eve/context";++/**+ * Who and what this session is about, and what it has spent.+ *+ * Durable per-session state rather than an argument threaded through every+ * tool: the audit hook needs the contact id to file an event against a record,+ * and a hook receives the event, not the tool's arguments. Any tool that takes+ * a `contactId` sets it, so the hook always knows whose page to write to.+ *+ * The budget lives here for a different reason. Depth is supposed to be a+ * decision the agent makes per contact, and a decision needs something to spend+ * — a counter in a prompt is a suggestion, a counter in durable state is a+ * limit that survives a crash mid-run.+ */+export const focus = defineState("crm.focus", () => ({+ contactId: null as string | null,+ companyId: null as string | null,+ sessionId: null as string | null,+ /** Vendor calls made. Cheap local reads do not count against it. */+ spent: 0,+ /** Set from the task that started the session; 4 is a plain identity pass. */+ budget: 4,+}));++/**+ * The state, or nothing, if we are not inside an eve turn.+ *+ * `get()` throws outside framework-managed code, which is right for a tool and+ * wrong for everything else that shares this library: a test, a backfill+ * script, or the dispatcher deciding what to run next. Provenance is worth+ * having even when the session id is not.+ */+export function currentFocus(): {+ contactId: string | null;+ sessionId: string | null;+} {+ try {+ const state = focus.get();+ return { contactId: state.contactId, sessionId: state.sessionId };+ } catch {+ return { contactId: null, sessionId: null };+ }+}++export function focusOn(input: {+ contactId?: string | null;+ companyId?: string | null;+ sessionId?: string | null;+}): void {+ focus.update((current) => ({+ ...current,+ contactId: input.contactId ?? current.contactId,+ companyId: input.companyId ?? current.companyId,+ sessionId: input.sessionId ?? current.sessionId,+ }));+}++/** Charges a vendor call against the budget, or explains why it cannot. */+export function spend(units = 1): { ok: true } | { ok: false; reason: string } {+ const { spent, budget } = focus.get();++ if (spent + units > budget) {+ return {+ ok: false,+ reason:+ `Research budget for this contact is spent (${spent}/${budget}). ` ++ "Write up what you already have, or schedule a recheck with a reason. Do not keep looking.",+ };+ }++ focus.update((current) => ({ ...current, spent: current.spent + units }));+ return { ok: true };+}++export function setBudget(budget: number): void {+ focus.update((current) => ({ ...current, budget }));+}diff --git a/apps/agent/agent/lib/names.ts b/apps/agent/agent/lib/names.tsindex 4851857b..fb17dcb9 100644--- a/apps/agent/agent/lib/names.ts+++ b/apps/agent/agent/lib/names.ts@@ -103,6 +103,24 @@ export function nameMatchesLocalPart();}+/**+ * Whether a contact's name is still the placeholder the sync derived from+ * their address, rather than something a person or a mail header supplied.+ *+ * The test is narrow on purpose: no surname, and the first name is the whole+ * handle. "Abigham" from `[email protected]` is a placeholder; "Abbie" from a+ * mail header is not, even though both are single words.+ */+export function isDerivedName(+ email: string | null,+ firstName: string,+ lastName: string | null,+): boolean {+ if (!email || lastName !== null) return false;+ const local = email.split("@")[0] ?? "";+ return nameMatchesLocalPart({ firstName, lastName: null }, local);+}+/** Splits a display name into first and last. */export function splitName(fullName: string,@@ -122,6 +140,40 @@ export function domainOf(email: string): string | null {return at > 0 ? email.slice(at + 1).toLowerCase() : null;}-function normalise(value: string): string {+/**+ * Whether two written names are the same person's.+ *+ * First and last have to agree; anything between them does not, so "Lewis+ * Carhart" matches "Lewis J. Carhart" and does not match "Lewis Carter".+ * Used where both sides are real names — a GitHub profile's `name` against the+ * one on the CRM record — as opposed to `nameMatchesLocalPart`, which checks a+ * name against a handle.+ */+export function namesMatch(a: string | null, b: string | null): boolean {+ const left = words(a);+ const right = words(b);++ if (left.length === 0 || right.length === 0) return false;+ if (left.join("") === right.join("")) return true;++ // A single-word name is not enough to identify anybody: "Lewis" matches every+ // Lewis there is.+ if (left.length < 2 || right.length < 2) return false;++ return left[0] === right[0] && left.at(-1) === right.at(-1);+}++function words(value: string | null): string[] {+ return (+ (value ?? "")+ .split(/\s+/)+ .map(normalise)+ // Initials and honorifics carry no signal and would otherwise shift which+ // word counts as the surname.+ .filter((word) => word.length > 1)+ );+}++export function normalise(value: string): string {return value.toLowerCase().replace(/[^a-z0-9]/g, "");}diff --git a/apps/agent/agent/lib/socials.ts b/apps/agent/agent/lib/socials.tsnew file mode 100644index 00000000..c1587303--- /dev/null+++ b/apps/agent/agent/lib/socials.ts@@ -0,0 +1,507 @@+import type { Evidence } from "./evidence";+import {+ looksLikeSameCompany,+ nameMatchesLocalPart,+ namesMatch,+} from "./names";+import { ask } from "./perplexity";++/**+ * Finding somebody's X and GitHub accounts, and — the part that matters —+ * refusing to write one we cannot stand behind.+ *+ * The failure mode here is not "no link". It is a link to a *different real+ * person* with a similar handle, sitting on a customer record looking exactly+ * like a fact. `github.com/lewis` belongs to someone; so does `x.com/lewis`.+ * A search engine asked "what is Lewis Carhart's GitHub" will happily hand one+ * of them over, because that is what it was asked for.+ *+ * So each network is checked by whatever hard evidence that network actually+ * exposes, and the two are not equally checkable:+ *+ * - **GitHub** has a public API. We fetch the account and read its own `name`,+ * `company` and `bio`. That is the person's own page telling us who they are,+ * which is real corroboration.+ * - **X** has nothing readable — the profile page is a JavaScript shell to+ * anyone without a paid API key. So the bar is the handle being a+ * construction of their name *and* a search engine independently citing that+ * exact profile when asked about this person by name and employer. Handles+ * that clear neither are left empty.+ *+ * Every check in here runs against the CRM's own copy of who the contact is,+ * never against anything the model passed in — otherwise "verification" is just+ * the model marking its own homework.+ */++export type Network = "x" | "github";++export type SocialProfile = {+ network: Network;+ /** Lowercased, no leading `@`. */+ handle: string;+ /** The canonical profile URL, which is what gets written to the record. */+ url: string;+};++export type Person = {+ firstName: string;+ lastName: string | null;+ fullName: string;+ title: string | null;+ companyName: string | null;+ companyDomain: string | null;+};++/**+ * What a check found, not what it decided.+ *+ * These functions used to return `accepted: true | false`, which made each one+ * its own little confidence policy — and meant a GitHub account that merely+ * shared an employer was written to a record with the same authority as one+ * that named the person. Returning evidence instead puts every network through+ * the same ledger, and the difference shows up where it should: a verified+ * GitHub account lands on the record, an X handle that can only ever be+ * corroborated indirectly becomes a suggestion.+ */+export type Verdict =+ | { accepted: true; profile: SocialProfile; evidence: Evidence[] }+ | { accepted: false; reason: string };++const X_HOSTS = new Set([+ "x.com",+ "www.x.com",+ "twitter.com",+ "www.twitter.com",+ "mobile.twitter.com",+]);++const GITHUB_HOSTS = new Set(["github.com", "www.github.com"]);++/**+ * First-segment paths that look like a profile and are not one.+ *+ * `x.com/settings` and `github.com/pricing` parse identically to a username,+ * and both turn up in search results about a person.+ */+const X_RESERVED = new Set([+ "i",+ "home",+ "explore",+ "search",+ "settings",+ "notifications",+ "messages",+ "intent",+ "share",+ "hashtag",+ "status",+ "login",+ "signup",+ "about",+ "privacy",+ "tos",+ "compose",+]);++const GITHUB_RESERVED = new Set([+ "orgs",+ "organizations",+ "features",+ "about",+ "pricing",+ "topics",+ "collections",+ "sponsors",+ "marketplace",+ "settings",+ "login",+ "join",+ "signup",+ "enterprise",+ "apps",+ "explore",+ "trending",+ "security",+ "readme",+ "site",+ "contact",+ "search",+ "new",+ "notifications",+]);++/** X's own rule: up to 15 word characters. */+const X_HANDLE = /^[A-Za-z0-9_]{1,15}$/;+/** GitHub's own rule: alphanumerics and single inner hyphens, up to 39. */+const GITHUB_HANDLE = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;++/**+ * A profile URL, or null for anything that is not one.+ *+ * Rejects deep links on purpose: `x.com/someone/status/123` and+ * `github.com/someone/repo` both contain a real handle, and both arrive as+ * citations constantly. Taking the first segment out of them would be right+ * about the handle and wrong about what the page proves.+ */+export function parseSocialUrl(raw: string): SocialProfile | null {+ const trimmed = raw.trim();+ if (!trimmed) return null;++ let url: URL;+ try {+ url = new URL(+ /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`,+ );+ } catch {+ return null;+ }++ const host = url.hostname.toLowerCase();+ const segments = url.pathname.split("/").filter(Boolean);+ if (segments.length !== 1) return null;++ const handle = decodeURIComponent(segments[0] as string).replace(/^@/, "");++ if (X_HOSTS.has(host)) {+ if (X_RESERVED.has(handle.toLowerCase())) return null;+ if (!X_HANDLE.test(handle)) return null;+ return {+ network: "x",+ handle: handle.toLowerCase(),+ url: `https://x.com/${handle}`,+ };+ }++ if (GITHUB_HOSTS.has(host)) {+ if (GITHUB_RESERVED.has(handle.toLowerCase())) return null;+ if (!GITHUB_HANDLE.test(handle)) return null;+ return {+ network: "github",+ handle: handle.toLowerCase(),+ url: `https://github.com/${handle}`,+ };+ }++ return null;+}++/** Every profile URL in a blob of text and citations, deduplicated. */+export function extractSocialUrls(haystack: string[]): SocialProfile[] {+ const found: SocialProfile[] = [];++ for (const chunk of haystack) {+ for (const match of chunk.matchAll(+ /https?:\/\/(?:www\.|mobile\.)?(?:x\.com|twitter\.com|github\.com)\/[^\s"'<>)\]},]+/gi,+ )) {+ // Prose ends in punctuation and URLs do not: a link at the end of a+ // sentence arrives as `x.com/lewiscarhart.`, which is not a handle+ // either network could issue and would otherwise be dropped silently.+ const profile = parseSocialUrl(match[0].replace(/[.,;:!?]+$/, ""));+ if (profile && !found.some((f) => f.url === profile.url)) {+ found.push(profile);+ }+ }+ }++ return found;+}++type GithubUser = {+ login: string;+ name: string | null;+ company: string | null;+ blog: string | null;+ bio: string | null;+ type: string;+};++/**+ * The account's own page, from GitHub's public API.+ *+ * `GITHUB_TOKEN` is read if it is set — unauthenticated calls are capped at 60+ * an hour per IP, which is fine for ten contacts but not for a backfill.+ */+async function fetchGithubUser(+ handle: string,+): Promise<{ ok: true; user: GithubUser } | { ok: false; reason: string }> {+ const token = process.env.GITHUB_TOKEN;++ try {+ const response = await fetch(+ `https://api.github.com/users/${encodeURIComponent(handle)}`,+ {+ headers: {+ accept: "application/vnd.github+json",+ "user-agent": "comp-ai-crm-research-agent",+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ },+ signal: AbortSignal.timeout(15_000),+ },+ );++ if (response.status === 404) {+ return { ok: false, reason: "No such GitHub account." };+ }+ if (response.status === 403 || response.status === 429) {+ // Rate limited is not "unverified" — it is "we do not know", and the two+ // must not collapse into a write.+ return {+ ok: false,+ reason: "GitHub rate-limited the check. Try this contact again later.",+ };+ }+ if (!response.ok) {+ return { ok: false, reason: `GitHub returned HTTP ${response.status}.` };+ }++ const body = (await response.json()) as Record<string, unknown>;++ return {+ ok: true,+ user: {+ login: String(body.login ?? handle),+ name: str(body.name),+ company: str(body.company),+ blog: str(body.blog),+ bio: str(body.bio),+ type: String(body.type ?? "User"),+ },+ };+ } catch (error) {+ return {+ ok: false,+ reason: error instanceof Error ? error.message : String(error),+ };+ }+}++/**+ * What GitHub's own API says about an account, as evidence.+ *+ * The account naming the person is primary — it is their page asserting who+ * they are. The employer matching while the name does not is emphatically+ * *not*: `github.com/octocat` with `company: @CompAI` is a colleague, and+ * writing it to Lewis's record because they share an employer is the same+ * mistake as writing a stranger's LinkedIn to a contact because the company+ * matched. Both are recorded; the ledger prices them differently.+ */+export async function verifyGithub(+ profile: SocialProfile,+ person: Person,+): Promise<Verdict> {+ const result = await fetchGithubUser(profile.handle);+ if (!result.ok) return { accepted: false, reason: result.reason };++ const user = result.user;++ if (user.type !== "User") {+ return {+ accepted: false,+ reason: `github.com/${user.login} is an ${user.type.toLowerCase()} account, not a person.`,+ };+ }++ const evidence: Evidence[] = [];+ const named = namesMatch(user.name, person.fullName);++ const employed =+ person.companyName !== null &&+ user.company !== null &&+ looksLikeSameCompany(+ user.company,+ person.companyName,+ person.companyDomain ?? "",+ );++ if (named) {+ // One item, not one per matching field: the name and the company sit on+ // the same page, so treating them as independent sources would multiply a+ // single observation into false certainty.+ const detail = employed+ ? `the account is named "${user.name}" and its company reads "${user.company}"`+ : `the account is named "${user.name}"`;+ evidence.push({+ kind: "github.account-identity",+ detail,+ sourceUrl: profile.url,+ });+ } else if (employed) {+ evidence.push({+ kind: "employer-only",+ detail: `its company reads "${user.company}" but the account is named "${user.name ?? "—"}"`,+ sourceUrl: profile.url,+ });+ }++ if (person.companyDomain) {+ const mentions = [user.blog, user.bio]+ .filter((field): field is string => Boolean(field))+ .some((field) =>+ field.toLowerCase().includes(person.companyDomain as string),+ );+ if (mentions) {+ evidence.push({+ kind: "web.cited-claim",+ detail: `the profile links ${person.companyDomain}`,+ sourceUrl: profile.url,+ });+ }+ }++ if (+ nameMatchesLocalPart(+ { firstName: person.firstName, lastName: person.lastName },+ profile.handle,+ )+ ) {+ evidence.push({+ kind: "handle.name-form",+ detail: `the handle "${profile.handle}" is a form of their name`,+ sourceUrl: profile.url,+ });+ }++ if (evidence.length === 0) {+ return {+ accepted: false,+ reason:+ `github.com/${user.login} says nothing connecting it to ${person.fullName}: ` ++ `name "${user.name ?? "—"}", company "${user.company ?? "—"}".`,+ };+ }++ return { accepted: true, profile, evidence };+}++/**+ * Whether an X account is this contact's, given that nobody can read X.+ *+ * Two things, and both are checked here rather than asked of the model. The+ * handle has to be a construction of their name, which rules out the+ * pseudonymous accounts we could never confirm; and a search engine has to cite+ * that exact profile when asked about them by name and employer, which is the+ * only outside corroboration available. A handle that is really the company's+ * account is rejected before either — `x.com/trycompai` passes a name check for+ * nobody and gets filed against everybody.+ */+export async function verifyX(+ profile: SocialProfile,+ person: Person,+): Promise<Verdict> {+ if (+ person.companyName &&+ looksLikeSameCompany(+ profile.handle,+ person.companyName,+ person.companyDomain ?? "",+ )+ ) {+ return {+ accepted: false,+ reason: `x.com/${profile.handle} looks like ${person.companyName}'s own account, not ${person.fullName}'s.`,+ };+ }++ if (+ !nameMatchesLocalPart(+ { firstName: person.firstName, lastName: person.lastName },+ profile.handle,+ )+ ) {+ return {+ accepted: false,+ reason:+ `x.com/${profile.handle} is not a form of "${person.fullName}", and X profiles cannot be read to check. ` ++ "Leave it empty.",+ };+ }++ // The tool does its own asking. A citation handed over by the model is a+ // citation the model can invent.+ const answer = await ask(+ `Is https://x.com/${profile.handle} the X (Twitter) account of ${person.fullName}` ++ `${person.title ? `, ${person.title}` : ""}` ++ `${person.companyName ? ` at ${person.companyName}` : ""}? ` ++ "Answer yes or no and give the profile URL.",+ { domains: ["x.com", "twitter.com"] },+ );++ if (!answer.ok) {+ return {+ accepted: false,+ reason: `Could not corroborate: ${answer.reason}`,+ };+ }++ const cited = extractSocialUrls(answer.data.citations).some(+ (candidate) =>+ candidate.network === "x" && candidate.handle === profile.handle,+ );++ if (!cited) {+ return {+ accepted: false,+ reason:+ `Nothing retrieved for "${person.fullName}" cites x.com/${profile.handle}. ` ++ "A handle that merely resembles their name is a guess.",+ };+ }++ // Neither of these is primary, and that is the honest result: X cannot be+ // read, so the strongest thing available is two indirect signals agreeing.+ // The ledger turns that into a suggestion for a rep rather than a write,+ // which is the right place for a link nobody can check.+ return {+ accepted: true,+ profile,+ evidence: [+ {+ kind: "handle.name-form",+ detail: `the handle "${profile.handle}" is a form of their name`,+ sourceUrl: profile.url,+ },+ {+ kind: "search.cites-profile",+ detail: `a search for ${person.fullName} cites this profile`,+ sourceUrl: profile.url,+ },+ ],+ };+}++/**+ * Candidate profile URLs from the open web.+ *+ * Candidates, never answers — same rule as LinkedIn slugs. The URLs are taken+ * from the citations rather than the prose, because a cited URL was actually+ * retrieved and a quoted one may have been composed on the spot.+ */+export async function findSocialCandidates(+ person: Person,+ network: Network,+): Promise<{ candidates: SocialProfile[]; citations: string[] }> {+ const where = network === "x" ? "X (Twitter)" : "GitHub";+ const domains = network === "x" ? ["x.com", "twitter.com"] : ["github.com"];++ const answer = await ask(+ `What is the ${where} profile of ${person.fullName}` ++ `${person.title ? `, ${person.title}` : ""}` ++ `${person.companyName ? ` at ${person.companyName}` : ""}` ++ `${person.companyDomain ? ` (${person.companyDomain})` : ""}? ` ++ "Reply with the profile URL only, or say you do not know.",+ { domains },+ );++ if (!answer.ok) return { candidates: [], citations: [] };++ const candidates = extractSocialUrls([+ answer.data.text,+ ...answer.data.citations,+ ]).filter((candidate) => candidate.network === network);++ return { candidates, citations: answer.data.citations };+}++function str(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}diff --git a/apps/agent/agent/lib/tasks.ts b/apps/agent/agent/lib/tasks.tsnew file mode 100644index 00000000..3f95ea1f--- /dev/null+++ b/apps/agent/agent/lib/tasks.ts@@ -0,0 +1,139 @@+import { db, type Prisma } from "@crm/db";++/**+ * The work queue the agent both reads and writes.+ *+ * The point of a table rather than a cron expression per kind of work: a cron+ * can only say "every hour, for everybody". A row can say *this person, in+ * fourteen days, because a job change here would move a live deal* — and the+ * reason is the agent's own words, shown to the rep on the record.+ */++export type LeasedTask = {+ id: string;+ contactId: string | null;+ companyId: string | null;+ kind: string;+ reason: string;+ budget: number;+};++/** How long a dispatcher tick holds a row before another one may retry it. */+const LEASE_MS = 10 * 60_000;++/**+ * Claims due work atomically.+ *+ * `FOR UPDATE SKIP LOCKED` inside the subquery is what makes this safe to run+ * from more than one process at a time — two dispatchers ticking together take+ * disjoint sets rather than racing for the same row. That matters more than it+ * looks: it is what lets the agent be deployed twice (its own service, and+ * embedded in the app) without doing every job twice.+ *+ * The lease is a deadline rather than a flag, so a run that crashes mid-task+ * frees itself. A `finishedAt` is what actually retires a row.+ */+export async function claimDue(limit: number): Promise<LeasedTask[]> {+ const now = new Date();+ const until = new Date(now.getTime() + LEASE_MS);++ return db.$queryRaw<LeasedTask[]>`+ UPDATE "agentTask" AS t+ SET "leasedUntil" = ${until}, "startedAt" = COALESCE(t."startedAt", ${now})+ FROM (+ SELECT id FROM "agentTask"+ WHERE "finishedAt" IS NULL+ AND "dueAt" <= ${now}+ AND ("leasedUntil" IS NULL OR "leasedUntil" < ${now})+ ORDER BY "priority" DESC, "dueAt" ASC+ LIMIT ${limit}+ FOR UPDATE SKIP LOCKED+ ) AS due+ WHERE t.id = due.id+ RETURNING t.id, t."contactId", t."companyId", t.kind, t.reason, t.budget;+ `;+}++export async function completeTask(+ taskId: string,+ outcome: string,+ sessionId?: string,+): Promise<void> {+ await db.agentTask.update({+ where: { id: taskId },+ data: {+ finishedAt: new Date(),+ outcome: outcome.slice(0, 500),+ ...(sessionId ? { sessionId } : {}),+ },+ });+}++/**+ * Books the next look at somebody.+ *+ * The reason is not decoration — it is shown on the record, and it is the+ * difference between an agent that runs on a schedule and one that has a view+ * about who is worth revisiting.+ */+export async function scheduleTask(input: {+ contactId?: string | null;+ companyId?: string | null;+ kind: string;+ reason: string;+ dueAt: Date;+ priority?: number;+ budget?: number;+}): Promise<{ id: string }> {+ // One outstanding task per subject and kind. An agent that queues itself+ // twice for the same person is an agent that spends twice as much to learn+ // the same thing.+ const existing = await db.agentTask.findFirst({+ where: {+ kind: input.kind,+ finishedAt: null,+ contactId: input.contactId ?? undefined,+ companyId: input.companyId ?? undefined,+ },+ select: { id: true },+ });++ if (existing) {+ await db.agentTask.update({+ where: { id: existing.id },+ data: { dueAt: input.dueAt, reason: input.reason },+ });+ return existing;+ }++ return db.agentTask.create({+ data: {+ contactId: input.contactId ?? null,+ companyId: input.companyId ?? null,+ kind: input.kind,+ reason: input.reason,+ dueAt: input.dueAt,+ priority: input.priority ?? 0,+ budget: input.budget ?? 4,+ },+ select: { id: true },+ });+}++/** What the agent last decided about a contact, for the sheet to show. */+export async function lastDecision(contactId: string) {+ return db.agentTask.findFirst({+ where: { contactId },+ orderBy: { createdAt: "desc" },+ select: {+ kind: true,+ reason: true,+ dueAt: true,+ finishedAt: true,+ outcome: true,+ },+ });+}++/** Kept for the raw query above to stay type-checked against the schema. */+export type { Prisma };diff --git a/apps/agent/agent/sandbox/sandbox.ts b/apps/agent/agent/sandbox/sandbox.tsnew file mode 100644index 00000000..c6b1d7aa--- /dev/null+++ b/apps/agent/agent/sandbox/sandbox.ts@@ -0,0 +1,35 @@+import { defaultBackend, defineSandbox } from "eve/sandbox";++/**+ * The agent's shell, with the network taken away.+ *+ * Turning a sandbox on is what gives the model `bash`, `read_file`,+ * `write_file`, `glob` and `grep` — the difference between a tool-caller and+ * something that can keep a dossier on a person, diff this month's profile+ * against last month's, and grep a thread for a signature block.+ *+ * `deny-all` costs nothing, because of where the other tools run: `web_fetch`+ * executes in the app runtime and `web_search` at the model provider, so+ * retrieval is unaffected by the sandbox having no egress. What it removes is+ * the only path by which customer email bodies — which this agent reads in full+ * — could leave the building through a shell command.+ *+ * The other half of that rule is not here, because it is an absence: **the+ * sandbox is never given `DATABASE_URL`.** Backends take explicit `env`, so+ * nothing is inherited. CRM access is authored tools in the app runtime, never+ * `psql`. A shell with credentials and egress is exfiltration-shaped even in an+ * internal tool; a shell with neither is a text processor.+ *+ * The policy is set on the backend factory rather than in `onSession` so it+ * applies to every session by construction — a per-session call is a per-session+ * call somebody can forget. No backend is pinned: `defaultBackend()` resolves+ * Vercel Sandbox in production and Docker or microsandbox locally, and each one+ * is told the same thing.+ */+export default defineSandbox({+ backend: defaultBackend({+ vercel: { networkPolicy: "deny-all" },+ docker: { networkPolicy: "deny-all" },+ microsandbox: { networkPolicy: "deny-all" },+ }),+});diff --git a/apps/agent/agent/sandbox/workspace/README.md b/apps/agent/agent/sandbox/workspace/README.mdnew file mode 100644index 00000000..20a92724--- /dev/null+++ b/apps/agent/agent/sandbox/workspace/README.md@@ -0,0 +1,23 @@+# /workspace++Scratch space for research in progress. Nothing in here is the record — the CRM+is the record, and it is reached through tools, not through this filesystem.++Useful for:++- **Dossiers.** `dossiers/<contactId>.json` — dump a profile you fetched, then+ `grep`/`jq` it instead of re-reading it into context.+- **Diffs.** Keeping last month's profile next to this month's is how a job+ change becomes visible without a second lookup.+- **Working notes** while you assemble a brief across several sources.++Two things this filesystem must never hold:++1. **Anything out of a mailbox.** Email bodies and meeting notes stay in the+ turn, in the app runtime. `read_crm_history` gives you the whole message+ because it is our own data; writing it here moves it somewhere with a+ different lifetime and a different set of eyes on it.+2. **Credentials.** There are none here, and there is no reason to create any.++There is no network from this sandbox. `web_fetch` and `web_search` still work+— they run outside it.diff --git a/apps/agent/agent/schedules/dispatch.ts b/apps/agent/agent/schedules/dispatch.tsnew file mode 100644index 00000000..c3b6fd19--- /dev/null+++ b/apps/agent/agent/schedules/dispatch.ts@@ -0,0 +1,99 @@+import { defineSchedule } from "eve/schedules";+import crm from "../channels/crm";+import { claimDue, completeTask } from "../lib/tasks";++/** Per tick. The cap is concurrency, not ambition — the queue keeps. */+const BATCH = 5;++/**+ * The agent's clock.+ *+ * One schedule for everything, and it decides nothing: it leases whatever is+ * due and starts a session per row. What the work *is* comes from the row —+ * written by the API when something happened, or by the agent itself when it+ * decided a person was worth another look in a fortnight.+ *+ * This is the difference the plan is named for. The schedules it replaces said+ * "every 20 minutes, the ten oldest contacts", which treats the CEO of a live+ * opportunity and a bounced alias identically because they sorted adjacently.+ *+ * Handler form rather than markdown, because the batch has to be claimed in+ * code — and because a handler-form session can park for a human, which task+ * mode cannot.+ */+export default defineSchedule({+ cron: "* * * * *",+ async run({ receive, waitUntil, appAuth }) {+ waitUntil(+ (async () => {+ const tasks = await claimDue(BATCH);+ if (tasks.length === 0) return;++ await Promise.all(+ tasks.map(async (task) => {+ try {+ await receive(crm, {+ message: brief(task),+ // The channel keys its continuation token off this, so a+ // re-dispatched lease resumes the run rather than starting+ // the research over.+ target: { taskId: task.id },+ auth: {+ ...appAuth,+ // Read by `instructions/task.ts` at `session.started`, so+ // the run opens knowing who it is about and what it may+ // spend instead of paying two tool calls to find out.+ attributes: {+ taskKind: task.kind,+ reason: task.reason,+ budget: String(task.budget),+ ...(task.contactId ? { contactId: task.contactId } : {}),+ ...(task.companyId ? { companyId: task.companyId } : {}),+ },+ },+ });++ await completeTask(task.id, "ran");+ } catch (error) {+ // The lease expires on its own, so a failure here is a retry+ // later rather than a row nobody ever picks up again.+ await completeTask(+ task.id,+ `failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }),+ );+ })(),+ );+ },+});++/**+ * What the session is asked to do.+ *+ * Short on purpose. The detail — who this person is, what we already know, what+ * is missing — is assembled by the dynamic instructions from the database,+ * where it is current, rather than pasted into a prompt here, where it would be+ * a snapshot taken by whoever queued the row.+ */+function brief(task: {+ kind: string;+ reason: string;+ contactId: string | null;+ companyId: string | null;+}): string {+ switch (task.kind) {+ case "identify":+ return "Work out who this contact actually is, and record what you find. Read what we already have before spending anything.";+ case "profile":+ case "recheck":+ return "Bring this contact's record up to date: their background, their current role, and anything that has changed since we last looked.";+ case "meeting-prep":+ return "There is a meeting with this person soon. Make sure whoever is taking it opens the record knowing who they are dealing with.";+ case "company-profile":+ return "Fill in what we know about this company: brand, industry, location, links. Write a brief if there is something worth saying.";+ default:+ return `Handle this: ${task.reason}`;+ }+}diff --git a/apps/agent/agent/schedules/research-new-contacts.ts b/apps/agent/agent/schedules/research-new-contacts.tsdeleted file mode 100644index cfcb3aad..00000000--- a/apps/agent/agent/schedules/research-new-contacts.ts+++ /dev/null@@ -1,33 +0,0 @@-import { defineSchedule } from "eve/schedules";--/**- * Works through contacts the Gmail and Calendar sync created but could not- * name.- *- * A markdown schedule rather than a `run` handler: the batch selection is a- * tool call, so there is nothing for TypeScript to decide before the agent- * starts. Task mode — it runs to completion and the output is discarded; what- * persists is what the tools wrote.- *- * On Vercel this becomes a Cron Job, evaluated in UTC. `eve dev` never fires- * schedules; use the dispatch route to trigger one while iterating.- */-export default defineSchedule({- cron: "*/15 * * * *",- markdown: `-Identify the CRM contacts that are still named after their email address.--1. Call \`list_contacts_to_research\` with a limit of 10.-2. If it returns nothing, stop. Do not go looking for other work.-3. For each contact, follow the \`identity-matching\` skill exactly:- resolve candidates, verify each with \`get_linkedin_profile\`, and only- write a match whose verdict is \`high\`.-4. When you identify somebody, call \`update_contact\` with the name and title- from their profile and the profile URL as the source.-5. When you cannot identify somebody, leave them alone. Do not lower the bar,- do not write a partial guess, and do not write a note saying you failed.--Do not research companies or write briefings in this run — this schedule is-only for putting real names to addresses.-`.trim(),-});diff --git a/apps/agent/agent/skills/data-boundaries.md b/apps/agent/agent/skills/data-boundaries.mdnew file mode 100644index 00000000..f876e2e6--- /dev/null+++ b/apps/agent/agent/skills/data-boundaries.md@@ -0,0 +1,45 @@+---+description: Use before reading CRM history or sending anything to a third party — what this agent may read (all of it) and what may leave.+---++# What you may read, and what may leave++## You may read everything++This is a single-tenant internal CRM. Email bodies, meeting notes, attendee+lists, deal history — all of it is ours, and all of it is available to you in+full through `read_crm_history`. There is no redaction to work around and no+approval to seek.++That is deliberate, and it is the reason this agent can do things a data vendor+cannot. A signature block settles a job title more reliably than LinkedIn does,+because people update a signature the week they are promoted. A reply on a+thread proves an identity outright. Use them.++## The boundary is egress++Three rules, and they are about what leaves, not what you look at.++**1. No customer text in a third-party query.** `web_search`, `web_fetch` and+`research_person` go to companies that are not us. Ask them derived questions —+"what did Acme announce in 2026?" — never a pasted thread, quote, or sentence+from a message. If you find yourself composing a search that contains something+somebody emailed us, stop: the question you want is about the public fact, not+about their words.++**2. Nothing from a mailbox goes into `/workspace`.** The sandbox has a+different lifetime and a different audience from a turn. Dossiers of public+profile data are what it is for. Message bodies stay in the conversation.++**3. Nothing sensitive gets logged.** Same rule the rest of the codebase+follows. Reading is not logging.++## What belongs on a record++Business context only: name, title, employer, tenure, seniority, public profile,+public news. Nothing about a person outside their work, and none of the special+categories — health, politics, religion, sexuality, ethnicity, union membership+— regardless of what a source volunteers or an endpoint returns.++If something is interesting but personal, it does not go on the record. A CRM+that knows a customer's marathon time is a CRM somebody has to explain.diff --git a/apps/agent/agent/skills/evidence.md b/apps/agent/agent/skills/evidence.mdnew file mode 100644index 00000000..83317563--- /dev/null+++ b/apps/agent/agent/skills/evidence.md@@ -0,0 +1,63 @@+---+description: Use when recording a fact — picking the right evidence kind for what you actually saw, and understanding why a claim was written, offered or held.+---++# Evidence++You never set a confidence. You report what you saw, and the ledger prices it.+Getting the `kind` right is therefore the whole job — it is the difference+between a fact landing on a record and a rep being asked a question.++## The kinds, and what each one means++**Primary — these can carry a fact on their own.** All of them are a source+identifying *this person*, not merely being consistent with them.++| Kind | Use it when |+| --- | --- |+| `profile.email-match` | The profile itself shows the address we hold. Decisive. |+| `linkedin.employer-and-name` | A LinkedIn profile where the employer matches *and* the name is consistent with the address. Both, or it is not this. |+| `crm.thread-reply` | They replied, from that address, on a thread we synced. Proof of identity. |+| `crm.signature-block` | Their own signature states it. The best source there is for a job title. |+| `github.account-identity` | The GitHub account's own `name` (or name plus company) matches. |+| `crm.meeting-attendance` | They accepted a calendar invite we have. |++**Supporting — true, but not enough alone.**++| Kind | Use it when |+| --- | --- |+| `web.cited-claim` | A page states it and you have the URL. |+| `search.cites-profile` | A search for them by name and employer returned this profile. |+| `handle.name-form` | The handle is a construction of their name. Weak: `github.com/lewis` is a form of every Lewis's name. |+| `employer-only` | The employer matches but the name does not. Nearly worthless on its own, and deliberately so — this is how a colleague gets filed as the contact. |++**`contradiction` — when two sources disagree.**++Record it. It does not lower the score a little; it holds the fact entirely,+which is correct. A profile saying one employer and a mail header saying another+is not 60% true, it is unresolved, and a rep should see it that way.++## What good evidence looks like++One entry per **independent** source. Two things on the same page are one+observation, not two: a GitHub profile whose name and company both match is one+`github.account-identity`, not a name match plus a company match. Splitting it+would double-count a single page into false certainty, which is exactly the+arithmetic this system exists to avoid.++`detail` is read by a rep in a tooltip. Write it for them:++- Good: `their signature on 14 July reads "Head of Security, Acme"`+- Bad: `signature match confirmed`++## What happens next, so you can stop guessing about it++- Primary source and a high score → **written to the record.**+- Otherwise → **stored as a suggestion** under the empty field, for a rep.+- Weak → kept but never shown.+- Nothing → not stored.++A suggestion is a good outcome. It is often the *correct* outcome: four Bighams+work at HubSpot and a human settles that in three seconds. Do not go looking for+extra evidence to push a claim over a line — that is how a wrong answer gets+dressed up as a right one.diff --git a/apps/agent/agent/skills/identity-matching.md b/apps/agent/agent/skills/identity-matching.mdindex 81179ea3..c078afba 100644--- a/apps/agent/agent/skills/identity-matching.md+++ b/apps/agent/agent/skills/identity-matching.md@@ -25,6 +25,10 @@ That is the shape of every match: guess where to look, never what you will find.## The procedure+0. **`read_crm_history` first.** It is free and it is often decisive. If they+ have ever replied to us from that address, you already have the strongest+ evidence available anywhere — `crm.thread-reply` — and a signature block may+ hand you their title as well. Start every match here, not at a search engine.1. **`resolve_linkedin_profile`** with the email and company. It decomposes thelocal part and returns candidate slugs. These are leads, not answers.2. **`get_linkedin_profile`** on each candidate, passing the email, company name@@ -33,21 +37,29 @@ That is the shape of every match: guess where to look, never what you will find.- `employerMatches` — a current position matches the company we have.- `nameMatches` — the real name is consistent with the email local part(`y` + `madar` → Yael Madar).-4. **Only `isSamePerson: true` counts.** Both checks, or it is not them.-5. If no candidate passes, **stop**. Report that you could not identify them.- Leaving "Abigham" in the CRM is the correct outcome when you do not know.+4. **Both, or it is not them.** One of the two is not a weaker match, it is a+ different person who happens to share something.+5. If no candidate passes, **stop**. Leaving "Abigham" in the CRM is the correct+ outcome when you do not know.-## Confidence+## Reporting the match-| Verdict | What it means | What to do |+Call `identify_contact` with what you actually saw:++| What you have | Evidence to record | What happens || --- | --- | --- |-| `high` | Employer and name both match | `update_contact`. |-| `medium` | One matches, not both | Do not write. Say what you found and why it fell short. |-| `low` | Neither | Wrong person. Move to the next candidate. |+| Both checks pass | `linkedin.employer-and-name` | Written to the record. |+| They replied from that address | `crm.thread-reply` | Written to the record. |+| One check passes | `employer-only`, or the profile as `search.cites-profile` | Offered to a rep as a suggestion. |+| Sources disagree | add a `contradiction` entry | Held. Nobody is shown a guess. |++The middle row is the case this exists for. Four Bighams work at HubSpot; a+human settles that in three seconds, and the old rule — throw away anything+short of certain — meant we paid for that lookup every run and learned nothing+from it. A suggestion is not a failed match. It is the match, handed to the one+person who can finish it.-Do not pass a confidence to `update_contact` other than the one the verdict gave-you. The tool rejects anything below `high` anyway, and inflating it is the one-thing that turns this from a research agent into a data-corruption agent.+Do not add evidence you did not observe to push a claim over a line.## Things that look like evidence and are notdiff --git a/apps/agent/agent/skills/writing-a-brief.md b/apps/agent/agent/skills/writing-a-brief.mdnew file mode 100644index 00000000..aaefcf65--- /dev/null+++ b/apps/agent/agent/skills/writing-a-brief.md@@ -0,0 +1,50 @@+---+description: Use when writing the Background panel on a contact — the shape, the tone, and when to write nothing at all.+---++# Writing a brief++The Background panel is the first thing on a contact's record and the last thing+a rep reads before a call. Two or three sentences, then the structured lines.++## The shape, and it does not vary++> Lewis Carhart is the CEO and co-founder of Comp AI. He previously led growth+> at Fleetio and spent four years at Deloitte in risk advisory.++Current role first, then what they did before. Third person, present tense,+their name at the front. Only what a source states — a job you cannot see on a+profile did not happen, and a date range you are unsure of is left out rather+than approximated.++## Nothing about the person++No "seasoned", no "passionate about", no "well-regarded", no guessing at how+senior or how influential they are. If you find yourself writing an adjective+about somebody rather than a fact about their work, delete the sentence.++The tell: could a rep repeat this sentence to the person on a call without+embarrassment? "You've been at Comp AI two years" is fine. "You're a seasoned+security leader" is not.++## The structured lines++`sections` are scanned, not read. Fill only what you know:++- `currentRole` — `"CEO & Co-founder · Comp AI"`+- `tenure` — `"2 yrs 3 mos"`, from the profile's own dates+- `previousRoles` — one string per role, most recent first+- `seniority` — `"Founder / C-level"`, `"VP"`, `"IC"`+- `function` — `"Executive"`, `"Security"`, `"Finance"`+- `location` — city and country, as the profile writes it++An empty line is better than a guessed one. The panel renders what it has.++## When to write nothing++If the only thing you can say is the job title already on the record, write+nothing. An empty panel costs a rep nothing; a paragraph that restates a field+they can already see costs them the time it takes to find that out.++The tool enforces a floor on length for the same reason: at forty characters+there is no room to say nothing at length.diff --git a/apps/agent/agent/tools/enrich_company.ts b/apps/agent/agent/tools/enrich_company.tsnew file mode 100644index 00000000..9dfe3a61--- /dev/null+++ b/apps/agent/agent/tools/enrich_company.ts@@ -0,0 +1,154 @@+import { db, EnrichmentStatus } from "@crm/db";+import { defineTool } from "eve/tools";+import { z } from "zod";+import { brandToUpdate, filledFields } from "../lib/brand-mapping";+import { brandByDomain, contextDevEnabled } from "../lib/context-dev";+import { spend } from "../lib/focus";++/**+ * A company's brand, firmographics and socials, from Context.dev.+ *+ * This used to be a Nest service on the API side, queued from a request+ * handler. Nothing about the lookup changed in the move; what changed is who+ * decides to make it. The API now says "a company exists with nothing but a+ * domain" and this decides whether that is worth ten credits.+ *+ * Fills gaps only. `brandToUpdate` has always refused to overwrite a field a+ * human filled in, and that rule is the same one the fact store applies to+ * people.+ */+export default defineTool({+ description:+ "Look up a company's brand, industry, location and social links by domain, and fill in the blanks on its record. Fills empty fields only — never overwrites what a person typed.",+ inputSchema: z.object({+ companyId: z.string(),+ fresh: z+ .boolean()+ .default(false)+ .describe(+ "Bypass the vendor's ~90-day cache. Only when a rep has asked for a fresh look.",+ ),+ }),+ async execute({ companyId, fresh }) {+ if (!contextDevEnabled()) {+ return {+ enriched: false as const,+ reason: "Context.dev is not configured.",+ };+ }++ const company = await db.company.findUnique({+ where: { id: companyId },+ select: {+ id: true,+ name: true,+ domain: true,+ description: true,+ logoUrl: true,+ logoDarkUrl: true,+ iconUrl: true,+ iconDarkUrl: true,+ iconTone: true,+ brandColor: true,+ industry: true,+ subIndustry: true,+ city: true,+ stateCode: true,+ country: true,+ countryCode: true,+ phone: true,+ email: true,+ linkedinUrl: true,+ twitterUrl: true,+ githubUrl: true,+ pricingUrl: true,+ careersUrl: true,+ },+ });++ if (!company)+ return { enriched: false as const, reason: "No such company." };+ if (!company.domain) {+ await settle(+ companyId,+ EnrichmentStatus.SKIPPED,+ "No domain to look up.",+ );+ return { enriched: false as const, reason: "No domain on this company." };+ }++ const charge = spend(2);+ if (!charge.ok) return { enriched: false as const, reason: charge.reason };++ await db.company.update({+ where: { id: companyId },+ data: {+ enrichmentStatus: EnrichmentStatus.RUNNING,+ enrichmentError: null,+ },+ });++ // `fresh` asks for a cache bypass; anything else takes whatever the vendor+ // has, because a 90-day-old logo is still the logo.+ const result = await brandByDomain(company.domain, fresh ? 0 : undefined);++ if (result.outcome === "skipped") {+ await settle(companyId, EnrichmentStatus.SKIPPED, result.reason);+ return { enriched: false as const, reason: result.reason };+ }++ if (result.outcome === "failed") {+ await settle(companyId, EnrichmentStatus.FAILED, result.reason);+ return {+ enriched: false as const,+ reason: result.reason,+ retryable: result.retryable,+ };+ }++ const update = brandToUpdate(result.brand, {+ ...company,+ // A company the sync created is named after its domain until we know+ // better, and that is the one non-null field a lookup may replace.+ nameIsPlaceholder: company.name === company.domain,+ });+ const filled = filledFields(update);++ await db.$transaction([+ db.company.update({ where: { id: companyId }, data: update }),+ db.companyEnrichment.upsert({+ where: { companyId },+ create: { companyId, raw: result.raw as object },+ update: { raw: result.raw as object, fetchedAt: new Date() },+ }),+ db.company.update({+ where: { id: companyId },+ data: {+ enrichmentStatus: EnrichmentStatus.COMPLETE,+ enrichedAt: new Date(),+ enrichmentError: null,+ },+ }),+ ]);++ return {+ enriched: true as const,+ filled,+ note:+ filled.length === 0+ ? "Everything it returned was already on the record."+ : undefined,+ };+ },+});++async function settle(+ companyId: string,+ status: EnrichmentStatus,+ error: string,+): Promise<void> {+ await db.company.update({+ where: { id: companyId },+ data: { enrichmentStatus: status, enrichmentError: error },+ });+}diff --git a/apps/agent/agent/tools/find_contact_socials.ts b/apps/agent/agent/tools/find_contact_socials.tsnew file mode 100644index 00000000..bd8e7bbb--- /dev/null+++ b/apps/agent/agent/tools/find_contact_socials.ts@@ -0,0 +1,56 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { personForVerification, stampSocialsChecked } from "../lib/crm";+import { focusOn, spend } from "../lib/focus";+import { findSocialCandidates } from "../lib/socials";++/**+ * Candidates, never answers — the same contract as `resolve_linkedin_profile`.+ *+ * Perplexity is good at finding where somebody lives on the web and bad at+ * being sure it is the right somebody: asked for a person's GitHub it returns+ * *a* GitHub, because that is what the question wanted. `set_contact_socials`+ * is what decides.+ */+export default defineTool({+ description:+ "Search the web for a contact's X and GitHub profiles. Returns CANDIDATES ONLY — pass them to set_contact_socials, which re-checks each one against the account itself before writing. Never write these URLs any other way.",+ inputSchema: z.object({+ contactId: z.string(),+ }),+ async execute({ contactId }) {+ // So the audit hook files this session's events against the right record.+ focusOn({ contactId });++ const person = await personForVerification(contactId);+ if (!person) {+ return { searched: false as const, reason: "No such contact." };+ }++ // Two searches, so two units. Most people have neither account, which is+ // exactly why this should not be the thing that empties a budget.+ const charge = spend(2);+ if (!charge.ok) return { searched: false as const, reason: charge.reason };++ const [x, github] = await Promise.all([+ findSocialCandidates(person, "x"),+ findSocialCandidates(person, "github"),+ ]);++ // Stamped here, not only on a successful write. Most people have neither+ // account, and "we looked and found nothing" has to be recorded or this+ // contact comes back around every hour for the same two searches.+ await stampSocialsChecked(contactId);++ return {+ searched: true as const,+ searchedFor: person.fullName,+ candidates: {+ x: x.candidates.map((c) => c.url),+ github: github.candidates.map((c) => c.url),+ },+ citations: [...x.citations, ...github.citations],+ note: "Unverified. set_contact_socials will reject any of these it cannot corroborate, and that is a normal outcome.",+ };+ },+});diff --git a/apps/agent/agent/tools/get_contact_work_history.ts b/apps/agent/agent/tools/get_contact_work_history.tsnew file mode 100644index 00000000..b7cfe705--- /dev/null+++ b/apps/agent/agent/tools/get_contact_work_history.ts@@ -0,0 +1,56 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { enabled, unavailable } from "../lib/capabilities";+import { contactProfileSlug } from "../lib/crm";+import { getExperience, getProfile } from "../lib/linkdapi";++/**+ * Reads the profile already on a contact's record — headline, current roles and+ * full work history.+ *+ * Takes a `contactId` rather than a slug on purpose. `get_linkedin_profile`+ * exists to *decide* whether a stranger is the person behind an address, and it+ * returns a verdict for exactly that reason; a second tool that reads any slug+ * without one would be the easy way to skip the check. This one can only read+ * the profile a verified match (or a rep) already put on the record, so there+ * is no identity question left for it to get wrong.+ */+export default defineTool({+ description:+ "Read the LinkedIn profile already on a CRM contact — headline, current roles and full work history. For writing a summary of somebody already identified. Cannot be used to identify anyone: use resolve_linkedin_profile and get_linkedin_profile for that.",+ inputSchema: z.object({+ contactId: z.string(),+ }),+ async execute({ contactId }) {+ if (!enabled("RAPIDAPI_KEY")) {+ return { found: false as const, ...unavailable("RAPIDAPI_KEY") };+ }++ const profileRef = await contactProfileSlug(contactId);+ if (!profileRef) {+ return {+ found: false as const,+ reason: "This contact has no LinkedIn URL on file.",+ };+ }++ const result = await getProfile(profileRef.slug);+ if (!result.ok) {+ return {+ found: false as const,+ reason: result.missing ? "No such profile." : result.reason,+ };+ }++ const profile = result.data;+ const history = profile.urn ? await getExperience(profile.urn) : null;++ return {+ found: true as const,+ profile,+ experience: history?.ok ? history.data : null,+ sourceUrl: profileRef.profileUrl,+ note: "Everything here is self-reported by the person. Write only what it says.",+ };+ },+});diff --git a/apps/agent/agent/tools/get_linkedin_profile.ts b/apps/agent/agent/tools/get_linkedin_profile.tsindex 170c29fb..2d12fc8b 100644--- a/apps/agent/agent/tools/get_linkedin_profile.ts+++ b/apps/agent/agent/tools/get_linkedin_profile.ts@@ -1,5 +1,7 @@import { defineTool } from "eve/tools";import { z } from "zod";+import { enabled, unavailable } from "../lib/capabilities";+import { spend } from "../lib/focus";import { getExperience, getProfile } from "../lib/linkdapi";import { looksLikeSameCompany, nameMatchesLocalPart } from "../lib/names";@@ -22,6 +24,15 @@ export default defineTool({.describe("Also fetch full work history — costs an extra call."),}),async execute({ slug, email, companyName, companyDomain, includeHistory }) {+ if (!enabled("RAPIDAPI_KEY")) {+ return { found: false as const, ...unavailable("RAPIDAPI_KEY") };+ }++ // Charged before the call, not after: a budget that only counts successes+ // is a budget an unlucky contact can blow through four times over.+ const charge = spend(includeHistory ? 2 : 1);+ if (!charge.ok) return { found: false as const, reason: charge.reason };+const result = await getProfile(slug);if (!result.ok) {return result.missingdiff --git a/apps/agent/agent/tools/identify_contact.ts b/apps/agent/agent/tools/identify_contact.tsnew file mode 100644index 00000000..0b8ad747--- /dev/null+++ b/apps/agent/agent/tools/identify_contact.ts@@ -0,0 +1,63 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import type { Evidence, EvidenceKind } from "../lib/evidence";+import { WEIGHTS } from "../lib/evidence";+import { recordFact } from "../lib/facts";+import { focusOn } from "../lib/focus";++/**+ * Putting a real name to an address.+ *+ * This used to take a `confidence` enum from the model and refuse anything+ * below `high`. Two things were wrong with that. The bar was set by the thing+ * being judged — a rubric the model could talk itself out of — and everything+ * below the bar was thrown away, so an ambiguous address cost a lookup every+ * run and produced nothing, forever.+ *+ * Now it takes evidence. A profile carrying their email address, or a reply on+ * a thread we already have, names them outright and is written. One weak signal+ * short of that becomes a suggestion a rep settles in three seconds — which is+ * the case this tool exists for, because `[email protected]` has four+ * plausible Bighams behind it and a human knows which.+ */+export default defineTool({+ description:+ "Put a verified name to a CRM contact, with the evidence for it. Strong evidence writes the name; anything less becomes a suggestion for a rep. Never overwrites a name a person supplied.",+ inputSchema: z.object({+ contactId: z.string(),+ fullName: z.string().describe("Exactly as the source writes it."),+ evidence: z+ .array(+ z.object({+ kind: z.enum(+ Object.keys(WEIGHTS) as [EvidenceKind, ...EvidenceKind[]],+ ),+ detail: z.string().describe("What the source actually said."),+ sourceUrl: z.string().optional(),+ }),+ )+ .min(1),+ sourceUrl: z.string().describe("The page a rep should open to check."),+ }),+ async execute(input) {+ focusOn({ contactId: input.contactId });++ const result = await recordFact({+ contactId: input.contactId,+ field: "name",+ value: input.fullName,+ evidence: input.evidence as Evidence[],+ method: "identity",+ sourceUrl: input.sourceUrl,+ });++ return {+ applied: result.applied,+ stored: result.stored,+ band: result.band,+ score: Number(result.score.toFixed(2)),+ rationale: result.rationale,+ ...(result.reason ? { reason: result.reason } : {}),+ };+ },+});diff --git a/apps/agent/agent/tools/list_contacts_to_research.ts b/apps/agent/agent/tools/list_contacts_to_research.tsdeleted file mode 100644index 73ea9001..00000000--- a/apps/agent/agent/tools/list_contacts_to_research.ts+++ /dev/null@@ -1,15 +0,0 @@-import { defineTool } from "eve/tools";-import { z } from "zod";-import { contactsNeedingResearch } from "../lib/crm";--export default defineTool({- description:- "List CRM contacts whose name is still derived from their email address and so need identifying. Returns the evidence to research them with.",- inputSchema: z.object({- limit: z.number().int().min(1).max(25).default(10),- }),- async execute({ limit }) {- const contacts = await contactsNeedingResearch(limit);- return { count: contacts.length, contacts };- },-});diff --git a/apps/agent/agent/tools/list_outstanding_work.ts b/apps/agent/agent/tools/list_outstanding_work.tsnew file mode 100644index 00000000..bfb27583--- /dev/null+++ b/apps/agent/agent/tools/list_outstanding_work.ts@@ -0,0 +1,24 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { contactsNeedingWork } from "../lib/crm";++/**+ * What is outstanding, not what to do about it.+ *+ * Each row says what is missing — a name, a background, socials — and the agent+ * decides which of those is worth doing for this person. The two tools this+ * replaced encoded that decision in their names, which meant the ordering of+ * the work was a property of the codebase rather than a judgement about the+ * contact.+ */+export default defineTool({+ description:+ "List CRM contacts with outstanding research: no real name yet, no background written, or socials never looked for. Each row says what is missing. Deciding what is worth doing, and in what order, is your job.",+ inputSchema: z.object({+ limit: z.number().int().min(1).max(25).default(10),+ }),+ async execute({ limit }) {+ const contacts = await contactsNeedingWork(limit);+ return { count: contacts.length, contacts };+ },+});diff --git a/apps/agent/agent/tools/read_crm_history.ts b/apps/agent/agent/tools/read_crm_history.tsnew file mode 100644index 00000000..57436ade--- /dev/null+++ b/apps/agent/agent/tools/read_crm_history.ts@@ -0,0 +1,48 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { readCrmHistory } from "../lib/crm";+import { focusOn } from "../lib/focus";++/**+ * What we already know, before spending anything to find out.+ *+ * This should usually be the *first* call on any contact, and it is free: no+ * vendor, no rate limit, no budget. It is also the strongest evidence available+ * anywhere in the system. A person who replied to us from an address is that+ * person, in a way no profile lookup can match, and their own signature block+ * outranks LinkedIn on a job title because people update a signature the week+ * they are promoted.+ *+ * Full message bodies are returned on purpose — single-tenant internal tool,+ * our own mailbox. The `data-boundaries` skill covers what may not then be done+ * with them.+ */+export default defineTool({+ description:+ "Read everything the CRM already has on a contact: email threads with full message bodies, meetings, whether they have ever replied, and who else we know at their company. Free, fast, and the best evidence there is — call it before paying for a lookup.",+ inputSchema: z.object({+ contactId: z.string(),+ threads: z+ .number()+ .int()+ .min(1)+ .max(20)+ .default(5)+ .describe("How many recent threads to read."),+ }),+ async execute({ contactId, threads }) {+ focusOn({ contactId });++ const history = await readCrmHistory(contactId, { threads });+ if (!history) return { found: false as const, reason: "No such contact." };++ return {+ found: true as const,+ ...history,+ note:+ history.stats.emails === 0 && history.stats.meetings === 0+ ? "We have never actually spoken to this person. Nothing here is evidence of anything."+ : "A signature block or a reply from their own address is primary evidence — record it as `crm.signature-block` or `crm.thread-reply`.",+ };+ },+});diff --git a/apps/agent/agent/tools/record_fact.ts b/apps/agent/agent/tools/record_fact.tsnew file mode 100644index 00000000..c5aa01c3--- /dev/null+++ b/apps/agent/agent/tools/record_fact.ts@@ -0,0 +1,80 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import type { Evidence, EvidenceKind } from "../lib/evidence";+import { WEIGHTS } from "../lib/evidence";+import { FACT_FIELDS, type FactField, recordFact } from "../lib/facts";+import { focusOn } from "../lib/focus";++/**+ * One claim, with what backs it. The only write to a contact's fields.+ *+ * It takes evidence and never a score. That is the whole design: the model+ * reports what it *saw* — "their signature block says Head of Security" — and+ * the ledger decides what that is worth. A `confidence` argument would be the+ * model grading its own homework, and a `sourceUrl` accepted as proof would be+ * the same thing with extra steps.+ *+ * Whether this writes the record or offers a suggestion is decided by the+ * arithmetic, not by the caller. A rejection is a correct outcome.+ */+export default defineTool({+ description:+ "Record one claim about a contact — title, employer, a profile URL, seniority — together with the evidence for it. The evidence decides whether it is written to the record or offered to a rep as a suggestion. Never invent evidence you did not observe.",+ inputSchema: z.object({+ contactId: z.string(),+ field: z+ .enum(FACT_FIELDS as [FactField, ...FactField[]])+ .describe("Which fact about them this is."),+ value: z+ .string()+ .describe("The claim itself, exactly as the source states it."),+ evidence: z+ .array(+ z.object({+ kind: z+ .enum(Object.keys(WEIGHTS) as [EvidenceKind, ...EvidenceKind[]])+ .describe(+ "What kind of thing you saw. Use `contradiction` when two sources disagree.",+ ),+ detail: z+ .string()+ .describe(+ "What it actually said, in one line a rep would understand.",+ ),+ sourceUrl: z.string().optional(),+ }),+ )+ .min(1)+ .describe("Everything you observed. One entry per independent source."),+ method: z+ .string()+ .describe(+ 'Where it came from: "linkedin.profile", "github.api", "crm.thread", "web".',+ ),+ sourceUrl: z+ .string()+ .optional()+ .describe("The page a rep should open to check."),+ }),+ async execute(input) {+ focusOn({ contactId: input.contactId });++ const result = await recordFact({+ contactId: input.contactId,+ field: input.field,+ value: input.value,+ evidence: input.evidence as Evidence[],+ method: input.method,+ sourceUrl: input.sourceUrl,+ });++ return {+ stored: result.stored,+ applied: result.applied,+ band: result.band,+ score: Number(result.score.toFixed(2)),+ rationale: result.rationale,+ ...(result.reason ? { reason: result.reason } : {}),+ };+ },+});diff --git a/apps/agent/agent/tools/record_job_change.ts b/apps/agent/agent/tools/record_job_change.tsnew file mode 100644index 00000000..cb5d3330--- /dev/null+++ b/apps/agent/agent/tools/record_job_change.ts@@ -0,0 +1,101 @@+import { db } from "@crm/db";+import { defineTool } from "eve/tools";+import { z } from "zod";+import { sensitiveWrite } from "../lib/approval";+import { writeTimelineNote } from "../lib/crm";+import { lastEmployerChange } from "../lib/facts";+import { focusOn } from "../lib/focus";++/**+ * A champion changing employer — the highest-intent signal in B2B, and the one+ * nothing else in our stack sees.+ *+ * It costs nothing to detect, because it already happened: an `employer` fact+ * superseding an applied one *is* the job change. There is no diffing job and+ * no second data source. This tool turns that row into something a human will+ * actually notice.+ *+ * What it deliberately does **not** do is move the contact to their new+ * company. That re-parents the record — changes whose pipeline they sit in and+ * which timeline their history hangs off — and it is approval-gated for that+ * reason. Unattended, it raises the alert and lets their owner decide.+ */+export default defineTool({+ description:+ "Raise a job change on a contact's timeline and task their owner. Reads the change from the facts already recorded; call it after recording a new employer.",+ inputSchema: z.object({+ contactId: z.string(),+ /**+ * Moving them is the sensitive part, which is why it is a separate flag+ * rather than something that happens implicitly.+ */+ moveToCompanyId: z+ .string()+ .optional()+ .describe(+ "Only when the new employer is already a company in the CRM and a person has approved the move.",+ ),+ }),+ approval: sensitiveWrite(+ "Raise the change without `moveToCompanyId` — the alert lands on the timeline and their owner decides whether to move them.",+ ),+ async execute({ contactId, moveToCompanyId }) {+ focusOn({ contactId });++ const change = await lastEmployerChange(contactId);+ if (!change) {+ return {+ raised: false as const,+ reason: "No employer change on the facts for this contact.",+ };+ }++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: {+ firstName: true,+ lastName: true,+ ownerId: true,+ companyId: true,+ },+ });+ if (!contact) return { raised: false as const, reason: "No such contact." };++ const name = [contact.firstName, contact.lastName]+ .filter(Boolean)+ .join(" ");++ // Lands on the *old* company's timeline, which is where the relationship+ // lives and where anyone reviewing that account will see it.+ await writeTimelineNote(+ contactId,+ `${name} has moved to ${change.to}`,+ [+ `${name} appears to have left ${change.from} for ${change.to}.`,+ change.sourceUrl ?? "",+ "",+ "Worth a conversation either way: a champion in a new seat is the",+ "warmest introduction there is, and their replacement at the old",+ "account is a relationship nobody owns yet.",+ ]+ .filter(Boolean)+ .join("\n"),+ { source: "job-change", from: change.from, to: change.to },+ );++ if (moveToCompanyId) {+ await db.contact.update({+ where: { id: contactId },+ data: { companyId: moveToCompanyId },+ });+ }++ return {+ raised: true as const,+ from: change.from,+ to: change.to,+ moved: Boolean(moveToCompanyId),+ ownerNotified: contact.ownerId !== null,+ };+ },+});diff --git a/apps/agent/agent/tools/research_company.ts b/apps/agent/agent/tools/research_company.tsnew file mode 100644index 00000000..c5841876--- /dev/null+++ b/apps/agent/agent/tools/research_company.ts@@ -0,0 +1,170 @@+import { ActivityType, db } from "@crm/db";+import { defineTool } from "eve/tools";+import { z } from "zod";+import { extract } from "../lib/context-dev";+import { spend } from "../lib/focus";++/** The shape the brief is extracted into. */+const RESEARCH_SCHEMA = {+ type: "object",+ properties: {+ positioning: {+ type: "string",+ description: "One paragraph: what they sell and who to.",+ },+ pricingModel: {+ type: "string",+ description: "How they charge — per seat, usage, flat, enterprise-only.",+ },+ targetCustomer: {+ type: "string",+ description: "The customer they describe themselves as serving.",+ },+ notableCustomers: {+ type: "array",+ items: { type: "string" },+ description: "Named customers or logos on the site.",+ },+ recentNews: {+ type: "array",+ items: { type: "string" },+ description: "Recent announcements, funding, or launches.",+ },+ },+ required: ["positioning"],+} as const;++const RESEARCH_INSTRUCTIONS =+ "Read this company's marketing site and answer as a salesperson preparing " ++ "for a first call. Be specific and factual; leave a field empty rather than " ++ "guessing.";++/**+ * Reads a company's own site and writes a brief to its timeline.+ *+ * Ported from the API unchanged, schema and all. The one difference is who+ * calls it: this used to be a tRPC mutation that ran a vendor extraction inside+ * the request, and is now something the agent does when it decides a company is+ * worth understanding — including on its own initiative, which the old one+ * could never do.+ */+export default defineTool({+ description:+ "Read a company's marketing site and write a research brief to its timeline: positioning, pricing, who they sell to, notable customers, recent news.",+ inputSchema: z.object({+ companyId: z.string(),+ }),+ async execute({ companyId }) {+ const company = await db.company.findUnique({+ where: { id: companyId },+ select: {+ id: true,+ name: true,+ domain: true,+ website: true,+ ownerId: true,+ },+ });++ if (!company)+ return { written: false as const, reason: "No such company." };++ const url =+ company.website ?? (company.domain ? `https://${company.domain}` : null);++ if (!url) {+ return {+ written: false as const,+ reason: "This company has no website.",+ };+ }++ const charge = spend(2);+ if (!charge.ok) return { written: false as const, reason: charge.reason };++ const result = await extract(+ url,+ RESEARCH_SCHEMA as unknown as Record<string, unknown>,+ RESEARCH_INSTRUCTIONS,+ );++ if (result.outcome === "failed") {+ return { written: false as const, reason: result.reason };+ }++ // `Activity.createdById` is required. Attribute to the company's owner, or+ // to any user if it is unowned; the meta marks it agent-written so the UI+ // never claims a person typed it.+ const author =+ company.ownerId ??+ (await db.user.findFirst({ select: { id: true } }))?.id ??+ null;++ if (!author)+ return { written: false as const, reason: "No user to attribute to." };++ const activity = await db.activity.create({+ data: {+ type: ActivityType.ENRICHMENT,+ subject: `Research brief — ${company.name}`,+ body: formatBrief(result.data),+ occurredAt: new Date(),+ companyId: company.id,+ createdById: author,+ meta: {+ source: "context.dev",+ endpoint: "web/extract",+ creditCost: 10,+ agent: "people-research",+ },+ },+ select: { id: true },+ });++ await db.company.update({+ where: { id: companyId },+ data: { lastActivityAt: new Date() },+ });++ return { written: true as const, activityId: activity.id };+ },+});++function formatBrief(data: unknown): string {+ if (typeof data !== "object" || data === null) return String(data ?? "");++ const brief = data as {+ positioning?: unknown;+ pricingModel?: unknown;+ targetCustomer?: unknown;+ notableCustomers?: unknown;+ recentNews?: unknown;+ };++ const lines: string[] = [];+ const text = (value: unknown) =>+ typeof value === "string" && value.trim() ? value.trim() : null;+ const list = (value: unknown) =>+ Array.isArray(value)+ ? value.filter((item): item is string => typeof item === "string")+ : [];++ const positioning = text(brief.positioning);+ if (positioning) lines.push(positioning);++ const pricing = text(brief.pricingModel);+ if (pricing) lines.push(`Pricing: ${pricing}`);++ const target = text(brief.targetCustomer);+ if (target) lines.push(`Sells to: ${target}`);++ const customers = list(brief.notableCustomers);+ if (customers.length > 0) lines.push(`Customers: ${customers.join(", ")}`);++ const news = list(brief.recentNews);+ if (news.length > 0) {+ lines.push(`Recently:\n${news.map((item) => `• ${item}`).join("\n")}`);+ }++ return lines.join("\n\n");+}diff --git a/apps/agent/agent/tools/research_person.ts b/apps/agent/agent/tools/research_person.tsindex 81a0440c..53d3dab8 100644--- a/apps/agent/agent/tools/research_person.ts+++ b/apps/agent/agent/tools/research_person.ts@@ -1,5 +1,7 @@import { defineTool } from "eve/tools";import { z } from "zod";+import { enabled, unavailable } from "../lib/capabilities";+import { spend } from "../lib/focus";import { ask } from "../lib/perplexity";export default defineTool({@@ -17,6 +19,15 @@ export default defineTool({.describe("Reason over more sources. Slower, better for prep briefs."),}),async execute({ question, deep }) {+ // Checked before the budget is charged: an install without the key would+ // otherwise pay for the discovery every time, and a contact could burn a+ // whole budget learning the same thing four times over.+ if (!enabled("PERPLEXITY_API_KEY"))+ return unavailable("PERPLEXITY_API_KEY");++ const charge = spend(deep ? 2 : 1);+ if (!charge.ok) return { ok: false as const, reason: charge.reason };+const answer = await ask(question, {model: deep ? "sonar-pro" : "sonar",system:diff --git a/apps/agent/agent/tools/resolve_linkedin_profile.ts b/apps/agent/agent/tools/resolve_linkedin_profile.tsindex 1dc06c93..28265359 100644--- a/apps/agent/agent/tools/resolve_linkedin_profile.ts+++ b/apps/agent/agent/tools/resolve_linkedin_profile.ts@@ -1,5 +1,7 @@import { defineTool } from "eve/tools";import { z } from "zod";+import { enabled, unavailable } from "../lib/capabilities";+import { spend } from "../lib/focus";import { searchTerms } from "../lib/names";import { findProfileUrls } from "../lib/perplexity";@@ -17,6 +19,17 @@ export default defineTool({companyName: z.string().describe("The company the CRM has them at."),}),async execute({ email, companyName }) {+ // Finding the slug is Perplexity's job — see `lib/linkdapi.ts` for why+ // LinkDAPI is never asked to search. Without it there is no way in to a+ // profile, so this stops here rather than charging for a lookup that has+ // nowhere to look.+ if (!enabled("PERPLEXITY_API_KEY")) {+ return { candidateSlugs: [], ...unavailable("PERPLEXITY_API_KEY") };+ }++ const charge = spend();+ if (!charge.ok) return { candidateSlugs: [], note: charge.reason };+const local = email.split("@")[0] ?? "";const terms = searchTerms(local);const slugs = await findProfileUrls(terms, companyName);diff --git a/apps/agent/agent/tools/schedule_recheck.ts b/apps/agent/agent/tools/schedule_recheck.tsnew file mode 100644index 00000000..37b061ea--- /dev/null+++ b/apps/agent/agent/tools/schedule_recheck.ts@@ -0,0 +1,64 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { scheduleTask } from "../lib/tasks";++/** Bounds, not opinions: a day is churn, three years is forgetting. */+const MIN_DAYS = 1;+const MAX_DAYS = 730;++/**+ * Deciding when to look at somebody again.+ *+ * The single most important tool in the agent, and the least impressive+ * looking. Everything else here answers a question; this one decides which+ * question gets asked next, which is what separates an agent from a cron job+ * with a language model attached.+ *+ * `reason` is mandatory and is shown to the rep on the record. An agent that+ * cannot say why it will be back in fourteen days does not have a reason, it+ * has a default.+ */+export default defineTool({+ description:+ "Decide when this contact is worth looking at again, and say why. Use a short interval for people whose job change would move a live deal, a long one for quiet records, and skip it entirely for addresses nobody will ever sell to.",+ inputSchema: z.object({+ contactId: z.string(),+ days: z+ .number()+ .int()+ .min(MIN_DAYS)+ .max(MAX_DAYS)+ .describe(+ "14 for a champion on an open deal; 90 for a named contact with no deal; 365 when two attempts have found nothing.",+ ),+ reason: z+ .string()+ .min(10)+ .describe(+ "Why this interval, for this person. A rep reads it: 'a job change here would move the Acme deal', not 'scheduled recheck'.",+ ),+ budget: z+ .number()+ .int()+ .min(1)+ .max(20)+ .default(4)+ .describe("Vendor calls the next run may spend."),+ }),+ async execute({ contactId, days, reason, budget }) {+ const dueAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000);++ await scheduleTask({+ contactId,+ kind: "recheck",+ reason,+ dueAt,+ budget,+ // Behind anything a person or an event asked for. A recheck is never+ // the most urgent thing in the queue.+ priority: 0,+ });++ return { scheduled: true as const, dueAt: dueAt.toISOString(), reason };+ },+});diff --git a/apps/agent/agent/tools/set_contact_socials.ts b/apps/agent/agent/tools/set_contact_socials.tsnew file mode 100644index 00000000..8088219e--- /dev/null+++ b/apps/agent/agent/tools/set_contact_socials.ts@@ -0,0 +1,113 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { personForVerification } from "../lib/crm";+import type { Evidence } from "../lib/evidence";+import { recordFact } from "../lib/facts";+import { focusOn } from "../lib/focus";+import { parseSocialUrl, verifyGithub, verifyX } from "../lib/socials";++/**+ * The only way an X or GitHub link reaches a record.+ *+ * Verification happens here, against the CRM's own copy of who the contact is+ * and against evidence this tool fetches itself. Nothing the model says about a+ * candidate is taken as support for it — a `confidence` argument would be the+ * model marking its own homework, which is why there isn't one.+ *+ * What the checks produce is *evidence*, which then goes through the same+ * ledger as everything else. A GitHub account whose own profile names the+ * person is primary and lands on the record; a handle that merely looks like+ * their name is not, and becomes a suggestion at best.+ */+export default defineTool({+ description:+ "Write a contact's X and/or GitHub profile URLs after verifying each one. GitHub is checked against the account's own profile via the GitHub API; X is checked by handle and independent citation. Rejects anything it cannot corroborate — a rejection is a correct outcome, not a problem to work around.",+ inputSchema: z.object({+ contactId: z.string(),+ twitterUrl: z+ .string()+ .optional()+ .describe("A candidate x.com profile URL from find_contact_socials."),+ githubUrl: z+ .string()+ .optional()+ .describe(+ "A candidate github.com profile URL from find_contact_socials.",+ ),+ }),+ async execute({ contactId, twitterUrl, githubUrl }) {+ focusOn({ contactId });++ const person = await personForVerification(contactId);+ if (!person) {+ return { written: false as const, reason: "No such contact." };+ }++ const rejected: string[] = [];+ const outcomes: {+ field: "twitterUrl" | "githubUrl";+ url: string;+ band: string | null;+ applied: boolean;+ }[] = [];++ const candidates = [+ { field: "twitterUrl" as const, raw: twitterUrl, network: "x" as const },+ {+ field: "githubUrl" as const,+ raw: githubUrl,+ network: "github" as const,+ },+ ];++ for (const candidate of candidates) {+ if (!candidate.raw) continue;++ const parsed = parseSocialUrl(candidate.raw);+ if (parsed?.network !== candidate.network) {+ rejected.push(+ `${candidate.raw} is not a ${candidate.network} profile URL.`,+ );+ continue;+ }++ const verdict =+ candidate.network === "x"+ ? await verifyX(parsed, person)+ : await verifyGithub(parsed, person);++ if (!verdict.accepted) {+ rejected.push(verdict.reason);+ continue;+ }++ const result = await recordFact({+ contactId,+ field: candidate.field,+ value: verdict.profile.url,+ evidence: verdict.evidence as Evidence[],+ method: candidate.network === "x" ? "x.handle+citation" : "github.api",+ sourceUrl: verdict.profile.url,+ });++ outcomes.push({+ field: candidate.field,+ url: verdict.profile.url,+ band: result.band,+ applied: result.applied,+ });++ if (!result.stored && result.reason) rejected.push(result.reason);+ }++ return {+ written: outcomes.some((outcome) => outcome.applied),+ outcomes,+ rejected,+ note:+ outcomes.length === 0 && rejected.length > 0+ ? "Nothing was written. There is no other route to this write — do not look for one."+ : undefined,+ };+ },+});diff --git a/apps/agent/agent/tools/update_contact.ts b/apps/agent/agent/tools/update_contact.tsdeleted file mode 100644index 873562d3..00000000--- a/apps/agent/agent/tools/update_contact.ts+++ /dev/null@@ -1,59 +0,0 @@-import { defineTool } from "eve/tools";-import { z } from "zod";-import { patchContact } from "../lib/crm";-import { splitName } from "../lib/names";--/**- * The only write.- *- * Requires a source URL and a confidence, and refuses anything below `high`.- * The bar is enforced here rather than in the prompt because a rubric the model- * is asked to follow is a rubric the model can talk itself out of.- */-export default defineTool({- description:- "Write a verified identity onto a CRM contact. Only accepts high-confidence matches with a source URL. Never overwrites a field a human has filled in.",- inputSchema: z.object({- contactId: z.string(),- fullName: z.string().describe("Exactly as written on the source."),- title: z.string().optional(),- linkedinUrl: z.string().optional(),- sourceUrl: z.string().describe("The page this came from."),- confidence: z- .enum(["high", "medium", "low"])- .describe(- "From get_linkedin_profile's verdict. Do not raise it yourself.",- ),- }),- async execute(input) {- if (input.confidence !== "high") {- return {- written: false as const,- reason:- `Confidence is ${input.confidence}. Only high-confidence matches are written — ` +- "both the employer and the name must match. Leave the contact as it is.",- };- }-- const name = splitName(input.fullName);- if (!name) {- return { written: false as const, reason: "Unusable name." };- }-- const { changed } = await patchContact(input.contactId, {- firstName: name.firstName,- lastName: name.lastName,- title: input.title,- linkedinUrl: input.linkedinUrl,- });-- return {- written: changed.length > 0,- changed,- note:- changed.length === 0- ? "Nothing changed — a human had already filled these in."- : undefined,- };- },-});diff --git a/apps/agent/agent/tools/write_brief.ts b/apps/agent/agent/tools/write_brief.tsnew file mode 100644index 00000000..a6230054--- /dev/null+++ b/apps/agent/agent/tools/write_brief.ts@@ -0,0 +1,91 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import type { Evidence, EvidenceKind } from "../lib/evidence";+import { WEIGHTS } from "../lib/evidence";+import { writeBrief } from "../lib/facts";+import { focusOn } from "../lib/focus";++/** Three sentences of prose, and the length is the constraint that keeps it honest. */+const MAX_NARRATIVE = 400;++/**+ * The background a rep reads before they dial.+ *+ * Length-capped rather than merely asked to be brief: at three sentences there+ * is only room for what a source says, and the padding a model reaches for when+ * it has nothing left to report — "a seasoned leader passionate about+ * innovation" — does not fit alongside two real facts.+ *+ * The structured `sections` are separate from the prose because the sheet+ * renders them as fields. Prose is what a person reads; fields are what they+ * scan.+ */+export default defineTool({+ description:+ "Write the Background panel on a contact: a short narrative plus the structured lines under it. Replaces the previous one. Every claim must come from something you read.",+ inputSchema: z.object({+ contactId: z.string(),+ narrative: z+ .string()+ .max(MAX_NARRATIVE)+ .describe(+ "Two or three sentences, third person, present tense, their name first. " ++ "Current role and employer, then the previous roles worth knowing. " ++ "No adjectives about the person, no 'passionate about', no guessing at seniority.",+ ),+ sections: z.object({+ currentRole: z+ .string()+ .optional()+ .describe('e.g. "CEO & Co-founder · Comp AI"'),+ tenure: z.string().optional().describe('e.g. "2 yrs 3 mos"'),+ previousRoles: z.array(z.string()).optional(),+ seniority: z.string().optional().describe('e.g. "Founder / C-level"'),+ function: z+ .string()+ .optional()+ .describe('e.g. "Executive", "Security", "Finance"'),+ location: z.string().optional(),+ }),+ evidence: z+ .array(+ z.object({+ kind: z.enum(+ Object.keys(WEIGHTS) as [EvidenceKind, ...EvidenceKind[]],+ ),+ detail: z.string(),+ sourceUrl: z.string().optional(),+ }),+ )+ .min(1),+ sourceUrl: z.string().optional(),+ }),+ async execute(input) {+ focusOn({ contactId: input.contactId });++ const narrative = input.narrative.trim();++ // A one-liner that restates the title already on the record is worse than+ // an empty panel: it fills the space where a rep looks for something they+ // did not already know.+ if (narrative.length < 40) {+ return {+ written: false as const,+ reason:+ "Too short to be worth a panel. Say something the record does not already show, or write nothing.",+ };+ }++ const result = await writeBrief({+ contactId: input.contactId,+ narrative,+ sections: input.sections,+ evidence: input.evidence as Evidence[],+ sourceUrl: input.sourceUrl,+ });++ return result.written+ ? { written: true as const, score: Number(result.score.toFixed(2)) }+ : { written: false as const, reason: result.reason };+ },+});diff --git a/apps/agent/agent/tools/write_briefing.ts b/apps/agent/agent/tools/write_briefing.tsdeleted file mode 100644index af1c65d6..00000000--- a/apps/agent/agent/tools/write_briefing.ts+++ /dev/null@@ -1,20 +0,0 @@-import { defineTool } from "eve/tools";-import { z } from "zod";-import { writeTimelineNote } from "../lib/crm";--export default defineTool({- description:- "Write a short research note onto a contact's timeline, where a rep will see it on the record. Use for context worth keeping, not for confirming an identity.",- inputSchema: z.object({- contactId: z.string(),- subject: z.string().max(120),- body: z.string().describe("Short and factual. Include source URLs inline."),- sources: z.array(z.string()).default([]),- }),- async execute({ contactId, subject, body, sources }) {- const id = await writeTimelineNote(contactId, subject, body, { sources });- return id- ? { written: true as const, activityId: id }- : { written: false as const, reason: "No such contact." };- },-});diff --git a/apps/agent/package.json b/apps/agent/package.jsonindex 4ff2e121..e266c6be 100644--- a/apps/agent/package.json+++ b/apps/agent/package.json@@ -3,23 +3,28 @@"version": "0.0.1","private": true,"type": "module",- "license": "UNLICENSED",+ "license": "MIT","scripts": {"dev": "eve dev","build": "eve build","start": "eve start","check-types": "tsc --noEmit",+ "test": "bun test","lint": "biome check .","clean": "rm -rf .turbo .eve node_modules"},"dependencies": {"@crm/db": "workspace:*",+ "@crm/env": "workspace:*",+ "@vercel/blob": "^2.6.1",+ "context.dev": "^2.7.0","eve": "^0.29.4","zod": "^4.4.3"},"devDependencies": {"@crm/typescript-config": "workspace:*","@types/node": "^24.0.0",+ "microsandbox": "^0.6.8","typescript": "^5.9.2"}}diff --git a/apps/agent/test/brand-mapping.spec.ts b/apps/agent/test/brand-mapping.spec.tsnew file mode 100644index 00000000..5f7d5c1a--- /dev/null+++ b/apps/agent/test/brand-mapping.spec.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from "bun:test";+import {+ brandToUpdate,+ type CompanySnapshot,+} from "../agent/lib/brand-mapping";+import type { Brand } from "../agent/lib/context-dev";++/** A company with nothing filled in — every gap open. */+function emptyCompany(+ overrides: Partial<CompanySnapshot> = {},+): CompanySnapshot {+ return {+ name: "Stripe",+ nameIsPlaceholder: false,+ description: null,+ logoUrl: null,+ logoDarkUrl: null,+ iconUrl: null,+ iconDarkUrl: null,+ iconTone: null,+ brandColor: null,+ industry: null,+ subIndustry: null,+ city: null,+ stateCode: null,+ country: null,+ countryCode: null,+ phone: null,+ email: null,+ linkedinUrl: null,+ twitterUrl: null,+ githubUrl: null,+ pricingUrl: null,+ careersUrl: null,+ ...overrides,+ };+}++describe("brandToUpdate", () => {+ const brand: Brand = {+ title: "Stripe",+ description: "Payments infrastructure for the internet.",+ phone: "+1 888 963 8955",+ email: "[email protected]",+ colors: [{ hex: "#635bff", name: "Meteor Shower" }],+ logos: [+ { url: "https://cdn/dark-logo.svg", mode: "dark", type: "logo" },+ { url: "https://cdn/light-logo.svg", mode: "light", type: "logo" },+ {+ url: "https://cdn/icon.svg",+ mode: "has_opaque_background",+ type: "icon",+ },+ ],+ socials: [+ { type: "x", url: "https://x.com/stripe" },+ { type: "linkedin", url: "https://linkedin.com/company/stripe" },+ { type: "github", url: "https://github.com/stripe" },+ ],+ address: {+ city: "South San Francisco",+ state_code: "CA",+ country: "United States",+ country_code: "US",+ },+ industries: {+ eic: [{ industry: "Finance", subindustry: "Payments & Money Movement" }],+ },+ links: {+ pricing: "https://stripe.com/pricing",+ careers: "https://stripe.com/jobs",+ },+ };++ it("picks logos by mode and type rather than taking the first", () => {+ const update = brandToUpdate(brand, emptyCompany());++ expect(update.logoUrl).toBe("https://cdn/light-logo.svg");+ expect(update.logoDarkUrl).toBe("https://cdn/dark-logo.svg");+ expect(update.iconUrl).toBe("https://cdn/icon.svg");+ });++ it("maps the rest of the brand onto company fields", () => {+ const update = brandToUpdate(brand, emptyCompany());++ expect(update).toMatchObject({+ description: "Payments infrastructure for the internet.",+ brandColor: "#635bff",+ industry: "Finance",+ subIndustry: "Payments & Money Movement",+ city: "South San Francisco",+ stateCode: "CA",+ country: "United States",+ countryCode: "US",+ phone: "+1 888 963 8955",+ email: "[email protected]",+ linkedinUrl: "https://linkedin.com/company/stripe",+ twitterUrl: "https://x.com/stripe",+ githubUrl: "https://github.com/stripe",+ pricingUrl: "https://stripe.com/pricing",+ careersUrl: "https://stripe.com/jobs",+ });+ });++ it("never overwrites a value a human already set", () => {+ const update = brandToUpdate(+ brand,+ emptyCompany({+ description: "Our biggest account — handle with care.",+ city: "London",+ phone: "+44 20 7946 0000",+ }),+ );++ expect(update.description).toBeUndefined();+ expect(update.city).toBeUndefined();+ expect(update.phone).toBeUndefined();+ // The gaps are still filled.+ expect(update.country).toBe("United States");+ });++ it("leaves the name alone unless it is the domain placeholder", () => {+ expect(+ brandToUpdate(brand, emptyCompany({ name: "Stripe Inc" })).name,+ ).toBeUndefined();++ expect(+ brandToUpdate(+ brand,+ emptyCompany({ name: "stripe.com", nameIsPlaceholder: true }),+ ).name,+ ).toBe("Stripe");+ });++ it("writes nothing when the lookup found nothing", () => {+ // Every field on a brand is nullable, so the all-null case is real.+ expect(brandToUpdate({}, emptyCompany())).toEqual({});+ });++ it("falls back to the slogan when there is no description", () => {+ const update = brandToUpdate(+ { slogan: "Payments, simplified." },+ emptyCompany(),+ );+ expect(update.description).toBe("Payments, simplified.");+ });+});++/** The real queue, with the five-second backoff wound down. */diff --git a/apps/agent/test/capabilities.spec.ts b/apps/agent/test/capabilities.spec.tsnew file mode 100644index 00000000..e3f7b0b8--- /dev/null+++ b/apps/agent/test/capabilities.spec.ts@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import {+ capabilities,+ capabilitiesMarkdown,+ enabled,+ unavailable,+} from "../agent/lib/capabilities";++const KEYS = [+ "RAPIDAPI_KEY",+ "PERPLEXITY_API_KEY",+ "CONTEXT_DEV_API_KEY",+] as const;++const saved: Record<string, string | undefined> = {};++beforeEach(() => {+ for (const key of KEYS) {+ saved[key] = process.env[key];+ delete process.env[key];+ }+});++afterEach(() => {+ for (const key of KEYS) {+ if (saved[key] === undefined) delete process.env[key];+ else process.env[key] = saved[key];+ }+});++describe("capabilities", () => {+ it("reports everything off on a bare install", () => {+ expect(capabilities().every((c) => !c.enabled)).toBe(true);+ expect(enabled("RAPIDAPI_KEY")).toBe(false);+ });++ it("turns one on without turning on the others", () => {+ process.env.PERPLEXITY_API_KEY = "pplx-test";++ expect(enabled("PERPLEXITY_API_KEY")).toBe(true);+ expect(enabled("RAPIDAPI_KEY")).toBe(false);+ });++ it("treats blank and whitespace as unset", () => {+ // `.env.example` ships these commented out, but a self-hoster who+ // uncomments one and leaves it empty must not get a tool that tries.+ process.env.RAPIDAPI_KEY = " ";+ expect(enabled("RAPIDAPI_KEY")).toBe(false);+ });++ it("is read live, so a late-configured process is not stuck off", () => {+ expect(enabled("RAPIDAPI_KEY")).toBe(false);+ process.env.RAPIDAPI_KEY = "key";+ expect(enabled("RAPIDAPI_KEY")).toBe(true);+ });++ it("is unknown for a variable that is not a capability", () => {+ process.env.SOMETHING_ELSE = "x";+ expect(enabled("SOMETHING_ELSE")).toBe(false);+ delete process.env.SOMETHING_ELSE;+ });+});++describe("the unavailable result", () => {+ it("says retrying will not help", () => {+ const result = unavailable("RAPIDAPI_KEY");++ expect(result.ok).toBe(false);+ expect(result.configured).toBe(false);+ // An agent told only "failed" will reasonably try again.+ expect(result.reason).toContain("retrying will not help");+ expect(result.reason).toContain("RAPIDAPI_KEY");+ });+});++describe("the capability briefing", () => {+ it("tells a bare install to work from the CRM alone", () => {+ const markdown = capabilitiesMarkdown();++ expect(markdown).toContain("No outside sources are configured");+ expect(markdown).toContain("read_crm_history");+ });++ it("lists what is on and what is off, separately", () => {+ process.env.RAPIDAPI_KEY = "key";+ const markdown = capabilitiesMarkdown();++ expect(markdown).toContain("Available:");+ expect(markdown).toContain("LinkedIn");+ expect(markdown).toContain("Not configured here");+ expect(markdown).toContain("Web research");+ });++ it("does not warn about missing sources when everything is on", () => {+ for (const key of KEYS) process.env[key] = "key";++ expect(capabilitiesMarkdown()).not.toContain("Not configured here");+ });+});diff --git a/apps/agent/test/channel-auth.spec.ts b/apps/agent/test/channel-auth.spec.tsnew file mode 100644index 00000000..08b682a7--- /dev/null+++ b/apps/agent/test/channel-auth.spec.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from "bun:test";+import {+ BRIDGE_AUDIENCE,+ BRIDGE_ISSUER,+ repFromCrm,+} from "../agent/channels/eve";+import { isAutomated } from "../agent/lib/approval";++/**+ * Who the agent thinks is calling.+ *+ * Two things are being protected here. The obvious one is that a forged or+ * expired token cannot reach an agent that can read every email in the CRM.+ * The subtler one is that a *valid* token has to resolve to a **person**:+ * `lib/approval.ts` pauses for a human only when it can tell one is there, and+ * eve's own `jwtHmac()` helper would have labelled this a service principal.+ */++const SECRET = "test-secret-at-least-long-enough-to-be-a-secret";+const auth = repFromCrm(SECRET);++/** Mirrors `apps/app/lib/agent-bridge.ts`; the app-side test proves the pair. */+async function mint(+ claims: Record<string, unknown>,+ secret = SECRET,+): Promise<string> {+ const encode = (value: object) =>+ Buffer.from(JSON.stringify(value)).toString("base64url");++ const signingInput = `${encode({ alg: "HS256", typ: "JWT" })}.${encode(claims)}`;+ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const signature = await crypto.subtle.sign(+ "HMAC",+ key,+ new TextEncoder().encode(signingInput),+ );++ return `${signingInput}.${Buffer.from(signature).toString("base64url")}`;+}++function request(token: string | null): Request {+ return new Request("https://agent.example.com/eve/v1/session", {+ method: "POST",+ headers: token ? { authorization: `Bearer ${token}` } : {},+ });+}++function claims(overrides: Record<string, unknown> = {}) {+ const now = Math.floor(Date.now() / 1000);+ return {+ iss: BRIDGE_ISSUER,+ aud: BRIDGE_AUDIENCE,+ sub: "user_123",+ email: "[email protected]",+ name: "Lewis Carhart",+ iat: now,+ nbf: now - 5,+ exp: now + 120,+ ...overrides,+ };+}++describe("repFromCrm", () => {+ it("resolves a valid token to the rep, as a person", async () => {+ const result = await auth(request(await mint(claims())));++ expect(result).toMatchObject({+ authenticator: "crm-app",+ principalId: "user_123",+ principalType: "user",+ });+ });++ it("produces a principal the approval policy reads as human", async () => {+ // The assertion the whole panel rests on: a rep asking is not the cron+ // principal, so a sensitive write prompts them instead of being refused.+ const session = await auth(request(await mint(claims())));++ expect(isAutomated({ auth: { current: session } })).toBe(false);+ });++ it("carries the rep's identity for the agent to attribute work to", async () => {+ const session = await auth(request(await mint(claims())));++ expect(session).toMatchObject({+ attributes: { email: "[email protected]", name: "Lewis Carhart" },+ });+ });++ it("skips a request with no token, rather than accepting it", async () => {+ expect(await auth(request(null))).toBeNull();+ });++ it("skips a token signed with the wrong secret", async () => {+ const forged = await mint(claims(), "not-the-shared-secret");+ expect(await auth(request(forged))).toBeNull();+ });++ it("skips a token whose payload was swapped for another user", async () => {+ // The attack that matters: take your own valid token, rewrite `sub`, keep+ // the signature. Nothing else in the system re-checks who the caller is.+ const token = await mint(claims());+ const [header, , signature] = token.split(".");+ const impersonated = Buffer.from(+ JSON.stringify(claims({ sub: "somebody_else" })),+ ).toString("base64url");++ expect(+ await auth(request(`${header}.${impersonated}.${signature}`)),+ ).toBeNull();+ });++ it("skips a token whose signature was altered", async () => {+ const token = await mint(claims());+ const [header, payload, signature] = token.split(".");++ // Flipped in the middle, deliberately. The *last* base64url character of+ // a 43-character signature carries only two significant bits — 32 bytes is+ // 256 bits and 43 characters hold 258 — so changing it can decode to the+ // same MAC and pass. A tamper test that only touches the final character+ // is a test that passes for the wrong reason.+ const middle = Math.floor((signature as string).length / 2);+ const swapped = (signature as string)[middle] === "A" ? "B" : "A";+ const altered = `${(signature as string).slice(0, middle)}${swapped}${(+ signature as string+ ).slice(middle + 1)}`;++ expect(await auth(request(`${header}.${payload}.${altered}`))).toBeNull();+ });++ it("skips an expired token", async () => {+ const now = Math.floor(Date.now() / 1000);+ const stale = await mint(claims({ iat: now - 600, exp: now - 300 }));+ expect(await auth(request(stale))).toBeNull();+ });++ it("skips a token minted for a different agent", async () => {+ expect(+ await auth(request(await mint(claims({ aud: "someone-else" })))),+ ).toBeNull();+ });++ it("skips a token from a different issuer", async () => {+ expect(+ await auth(request(await mint(claims({ iss: "not-our-app" })))),+ ).toBeNull();+ });++ it("skips a token that names nobody", async () => {+ expect(+ await auth(request(await mint(claims({ sub: undefined })))),+ ).toBeNull();+ });+});diff --git a/apps/agent/test/evidence.spec.ts b/apps/agent/test/evidence.spec.tsnew file mode 100644index 00000000..4762c8fb--- /dev/null+++ b/apps/agent/test/evidence.spec.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "bun:test";+import {+ BAND_FLOOR,+ bandFor,+ type Evidence,+ scoreEvidence,+} from "../agent/lib/evidence";++const of = (...kinds: Evidence["kind"][]): Evidence[] =>+ kinds.map((kind) => ({ kind, detail: `saw ${kind}` }));++describe("scoreEvidence", () => {+ it("writes a fact when a primary source names them", () => {+ // Their own profile carrying their email address is as good as it gets.+ const scored = scoreEvidence(of("profile.email-match"));+ expect(scored.band).toBe("VERIFIED");+ expect(scored.hasPrimary).toBe(true);+ });++ it("treats our own mailbox as primary evidence", () => {+ // The §1 argument in one assertion: a reply on a thread we synced is+ // worth more than anything a data vendor can sell us, and it carries a+ // fact on its own.+ expect(scoreEvidence(of("crm.thread-reply")).band).toBe("VERIFIED");+ });++ it("writes a title a signature block states on a thread they replied to", () => {+ // The realistic shape of a title read out of our own mailbox: the reply+ // proves it is them, the signature states the role. Either alone is a+ // suggestion; together they are a fact.+ expect(scoreEvidence(of("crm.signature-block")).band).toBe("PROBABLE");+ expect(+ scoreEvidence(of("crm.thread-reply", "crm.signature-block")).band,+ ).toBe("VERIFIED");+ });++ it("refuses to write anything without a primary source, however much of it there is", () => {+ const scored = scoreEvidence(+ of(+ "handle.name-form",+ "search.cites-profile",+ "web.cited-claim",+ "employer-only",+ ),+ );++ // Four weak signals pile up to a confident-looking number and are still+ // not allowed to write. This is the rule that stops a plausible stranger+ // becoming a customer record.+ expect(scored.score).toBeGreaterThan(BAND_FLOOR.PROBABLE);+ expect(scored.hasPrimary).toBe(false);+ expect(scored.band).toBe("PROBABLE");+ });++ it("holds the primary-source rule even if the weights are re-calibrated upwards", () => {+ // The invariant, independent of the numbers in the table: a score alone+ // never licenses a write.+ expect(bandFor(0.99, false)).toBe("PROBABLE");+ expect(bandFor(0.85, true)).toBe("VERIFIED");+ });++ it("makes an unreadable X handle a suggestion, not a value", () => {+ // Exactly what verifyX produces. X cannot be read, so the best available+ // is two indirect signals agreeing — which is a question for a human.+ const scored = scoreEvidence(+ of("handle.name-form", "search.cites-profile"),+ );+ expect(scored.band).toBe("PROBABLE");+ });++ it("holds a fact when sources disagree, rather than averaging them", () => {+ const scored = scoreEvidence([+ ...of("linkedin.employer-and-name"),+ {+ kind: "contradiction",+ detail: "their signature says a different employer",+ },+ ]);++ expect(scored.band).toBe("POSSIBLE");+ expect(scored.rationale).toContain("Held:");+ });++ it("drops evidence too weak to keep at all", () => {+ expect(scoreEvidence(of("employer-only")).band).toBeNull();+ expect(scoreEvidence([]).band).toBeNull();+ });++ it("never claims certainty", () => {+ const everything = scoreEvidence(+ of(+ "profile.email-match",+ "linkedin.employer-and-name",+ "crm.thread-reply",+ "github.account-identity",+ ),+ );+ expect(everything.score).toBeLessThan(1);+ });++ it("explains itself in words a rep could read", () => {+ const scored = scoreEvidence(+ of("github.account-identity", "handle.name-form"),+ );+ expect(scored.rationale).toContain("GitHub account");+ expect(scored.rationale).toContain("handle");+ });+});diff --git a/apps/agent/test/facts.integration.spec.ts b/apps/agent/test/facts.integration.spec.tsnew file mode 100644index 00000000..e3d778e9--- /dev/null+++ b/apps/agent/test/facts.integration.spec.ts@@ -0,0 +1,193 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+import type { Evidence } from "../agent/lib/evidence";+import { recordFact, writeBrief } from "../agent/lib/facts";++/**+ * The fact store against a real database.+ *+ * Every rule in here is one that used to live in a prompt, so testing them+ * against Postgres rather than a mock is the point: "never overwrite a human"+ * is only true if the transaction says so.+ */++const suffix = process.env.TEST_RUN_ID ?? "facts-spec";+const email = `evidence.subject.${suffix}@example.test`;++let contactId: string;++const seen = (kind: Evidence["kind"], detail = "observed"): Evidence => ({+ kind,+ detail,+});++beforeAll(async () => {+ await db.contact.deleteMany({ where: { email } });+ const contact = await db.contact.create({+ data: { firstName: "Subject", lastName: null, email },+ select: { id: true },+ });+ contactId = contact.id;+});++afterAll(async () => {+ await db.contact.deleteMany({ where: { email } });+});++describe("recordFact", () => {+ it("writes a verified fact through to the record", async () => {+ const result = await recordFact({+ contactId,+ field: "title",+ value: "Head of Security",+ evidence: [seen("crm.thread-reply"), seen("crm.signature-block")],+ method: "crm.thread",+ });++ expect(result.applied).toBe(true);+ expect(result.band).toBe("VERIFIED");++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: { title: true },+ });+ expect(contact?.title).toBe("Head of Security");+ });++ it("keeps a probable fact off the record and offers it instead", async () => {+ const result = await recordFact({+ contactId,+ field: "twitterUrl",+ value: "https://x.com/subject",+ evidence: [seen("handle.name-form"), seen("search.cites-profile")],+ method: "x.handle+citation",+ });++ expect(result.stored).toBe(true);+ expect(result.applied).toBe(false);+ expect(result.band).toBe("PROBABLE");++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: { twitterUrl: true },+ });+ // The suggestion exists; the field does not have it.+ expect(contact?.twitterUrl).toBeNull();+ });++ it("never overwrites what a person typed", async () => {+ await db.contact.update({+ where: { id: contactId },+ data: { githubUrl: "https://github.com/typed-by-a-human" },+ });++ const result = await recordFact({+ contactId,+ field: "githubUrl",+ value: "https://github.com/found-on-the-web",+ evidence: [seen("github.account-identity")],+ method: "github.api",+ });++ expect(result.applied).toBe(false);+ expect(result.reason).toContain("A person already filled in");++ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: { githubUrl: true },+ });+ expect(contact?.githubUrl).toBe("https://github.com/typed-by-a-human");+ });++ it("never re-offers a value a person dismissed", async () => {+ const proposal = await db.contactFact.findFirst({+ where: { contactId, field: "twitterUrl" },+ select: { id: true },+ });+ await db.contactFact.update({+ where: { id: proposal?.id },+ data: { status: "DISMISSED", decidedAt: new Date() },+ });++ const result = await recordFact({+ contactId,+ field: "twitterUrl",+ value: "https://x.com/subject",+ evidence: [seen("handle.name-form"), seen("search.cites-profile")],+ method: "x.handle+citation",+ });++ expect(result.stored).toBe(false);+ expect(result.reason).toContain("dismissed");+ });++ it("supersedes rather than replaces, which is how a job change is noticed", async () => {+ await recordFact({+ contactId,+ field: "employer",+ value: "Fleetio",+ evidence: [seen("linkedin.employer-and-name")],+ method: "linkedin.profile",+ });++ await recordFact({+ contactId,+ field: "employer",+ value: "Comp AI",+ evidence: [seen("linkedin.employer-and-name")],+ method: "linkedin.profile",+ });++ const facts = await db.contactFact.findMany({+ where: { contactId, field: "employer" },+ select: { value: true, status: true },+ });++ expect(facts).toHaveLength(2);+ expect(facts.find((f) => f.value === "Fleetio")?.status).toBe("SUPERSEDED");+ expect(facts.find((f) => f.value === "Comp AI")?.status).toBe("APPLIED");+ });++ it("stores the evidence, so the score can be explained later", async () => {+ const fact = await db.contactFact.findFirst({+ where: { contactId, field: "title" },+ select: { evidence: true, score: true, sourceUrl: true },+ });++ expect(Array.isArray(fact?.evidence)).toBe(true);+ expect(fact?.score).toBeGreaterThan(0.85);+ });+});++describe("writeBrief", () => {+ it("upserts the background panel", async () => {+ await writeBrief({+ contactId,+ narrative: "Subject is Head of Security at Example.",+ sections: { currentRole: "Head of Security · Example" },+ evidence: [seen("linkedin.employer-and-name")],+ sourceUrl: "https://www.linkedin.com/in/subject",+ });++ await writeBrief({+ contactId,+ narrative: "Subject is now VP Security at Example.",+ sections: { currentRole: "VP Security · Example" },+ evidence: [seen("linkedin.employer-and-name")],+ });++ const brief = await db.contactBrief.findUnique({ where: { contactId } });+ expect(brief?.narrative).toBe("Subject is now VP Security at Example.");+ });++ it("refuses a brief nothing supports", async () => {+ const result = await writeBrief({+ contactId,+ narrative: "Subject seems like a great person to know.",+ sections: {},+ evidence: [seen("employer-only")],+ });++ expect(result.written).toBe(false);+ });+});diff --git a/apps/api/test/contact-enrichment.spec.ts b/apps/agent/test/names.spec.tssimilarity index 88%rename from apps/api/test/contact-enrichment.spec.tsrename to apps/agent/test/names.spec.tsindex 261534c5..2bf1ee5d 100644--- a/apps/api/test/contact-enrichment.spec.ts+++ b/apps/agent/test/names.spec.ts@@ -1,9 +1,18 @@import { describe, expect, it } from "bun:test";++/**+ * The identity helpers, tested where they now live.+ *+ * These moved here with the rest of enrichment. They were written against the+ * API's copy of `looksLikeSameCompany`/`nameMatchesLocalPart`/`searchTerms`,+ * which had silently drifted from the agent's — the whole argument for there+ * being one copy. Same assertions, one implementation.+ */import {looksLikeSameCompany,nameMatchesLocalPart,searchTerms,-} from "../src/enrichment/contact-enrichment.service";+} from "../agent/lib/names";describe("searchTerms", () => {it("strips the initial off a run-together handle", () => {diff --git a/apps/agent/test/socials.spec.ts b/apps/agent/test/socials.spec.tsnew file mode 100644index 00000000..969dacc5--- /dev/null+++ b/apps/agent/test/socials.spec.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from "bun:test";+import { namesMatch } from "../agent/lib/names";+import { extractSocialUrls, parseSocialUrl } from "../agent/lib/socials";++describe("parseSocialUrl", () => {+ it("reads a profile on either X hostname", () => {+ expect(parseSocialUrl("https://x.com/lewiscarhart")).toEqual({+ network: "x",+ handle: "lewiscarhart",+ url: "https://x.com/lewiscarhart",+ });+ // Canonicalised, so the same account found twice is written once.+ expect(parseSocialUrl("https://twitter.com/LewisCarhart")?.url).toBe(+ "https://x.com/LewisCarhart",+ );+ expect(parseSocialUrl("https://mobile.twitter.com/@lewis")?.handle).toBe(+ "lewis",+ );+ });++ it("refuses a deep link, which is where most wrong handles come from", () => {+ // A cited tweet and a cited repo both contain a real handle, and neither is+ // evidence that the handle belongs to the person we asked about.+ expect(parseSocialUrl("https://x.com/someone/status/1234")).toBeNull();+ expect(parseSocialUrl("https://github.com/someone/some-repo")).toBeNull();+ });++ it("refuses site paths that parse like a username", () => {+ expect(parseSocialUrl("https://github.com/pricing")).toBeNull();+ expect(parseSocialUrl("https://github.com/orgs")).toBeNull();+ expect(parseSocialUrl("https://x.com/settings")).toBeNull();+ expect(parseSocialUrl("https://x.com/i")).toBeNull();+ });++ it("refuses handles neither network could issue", () => {+ // X caps at 15 characters; GitHub allows no trailing or doubled hyphen.+ expect(parseSocialUrl("https://x.com/waytoolongforanxhandle")).toBeNull();+ expect(parseSocialUrl("https://github.com/-lewis")).toBeNull();+ expect(parseSocialUrl("https://github.com/lewis--carhart")).toBeNull();+ });++ it("ignores anything that is not one of the two networks", () => {+ expect(parseSocialUrl("https://linkedin.com/in/lewiscarhart")).toBeNull();+ expect(parseSocialUrl("not a url")).toBeNull();+ expect(parseSocialUrl("")).toBeNull();+ });+});++describe("extractSocialUrls", () => {+ it("pulls profiles out of prose and citations, deduplicated", () => {+ const found = extractSocialUrls([+ "You can find him at https://github.com/lewiscarhart and https://x.com/lewiscarhart.",+ "https://github.com/lewiscarhart",+ "https://github.com/lewiscarhart/crm",+ ]);++ expect(found.map((f) => f.url)).toEqual([+ "https://github.com/lewiscarhart",+ "https://x.com/lewiscarhart",+ ]);+ });++ it("finds nothing in an answer that cites nothing", () => {+ expect(extractSocialUrls(["I could not find a GitHub profile."])).toEqual(+ [],+ );+ });+});++describe("namesMatch", () => {+ it("accepts the same person written two ways", () => {+ expect(namesMatch("Lewis Carhart", "Lewis Carhart")).toBe(true);+ expect(namesMatch("Lewis J. Carhart", "Lewis Carhart")).toBe(true);+ expect(namesMatch("lewis carhart", "Lewis Carhart")).toBe(true);+ });++ it("rejects a near miss", () => {+ expect(namesMatch("Lewis Carter", "Lewis Carhart")).toBe(false);+ expect(namesMatch("Louis Carhart", "Lewis Carhart")).toBe(false);+ });++ it("rejects a first name on its own", () => {+ // The GitHub account of "Lewis" is the account of every Lewis there is.+ expect(namesMatch("Lewis", "Lewis Carhart")).toBe(false);+ expect(namesMatch(null, "Lewis Carhart")).toBe(false);+ });+});diff --git a/apps/agent/test/tasks.integration.spec.ts b/apps/agent/test/tasks.integration.spec.tsnew file mode 100644index 00000000..4ead1ccf--- /dev/null+++ b/apps/agent/test/tasks.integration.spec.ts@@ -0,0 +1,127 @@+import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+import { claimDue, completeTask, scheduleTask } from "../agent/lib/tasks";++/**+ * The work queue against a real database.+ *+ * The lease is raw SQL — `FOR UPDATE SKIP LOCKED` has no Prisma equivalent —+ * which is exactly the kind of code that typechecks and then does the wrong+ * thing at runtime. It is also the thing standing between one dispatcher and+ * two dispatchers doing every job twice.+ */++const kind = "test-lease";++async function clear() {+ await db.agentTask.deleteMany({ where: { kind } });+}++beforeEach(clear);+afterEach(clear);++async function queue(overrides: { priority?: number; dueAt?: Date } = {}) {+ return db.agentTask.create({+ data: {+ kind,+ reason: "test",+ dueAt: overrides.dueAt ?? new Date(Date.now() - 1000),+ priority: overrides.priority ?? 0,+ budget: 4,+ },+ select: { id: true },+ });+}++describe("claimDue", () => {+ it("claims due work and leases it", async () => {+ const task = await queue();++ const claimed = await claimDue(10);+ expect(claimed.map((t) => t.id)).toContain(task.id);++ const row = await db.agentTask.findUnique({ where: { id: task.id } });+ expect(row?.leasedUntil).not.toBeNull();+ expect(row?.startedAt).not.toBeNull();+ });++ it("does not hand the same row to two dispatchers", async () => {+ await Promise.all([queue(), queue(), queue()]);++ // The case the raw SQL exists for: two ticks landing together must take+ // disjoint sets, not race for the same rows.+ const [first, second] = await Promise.all([claimDue(3), claimDue(3)]);+ const ids = [...first, ...second].map((t) => t.id);++ expect(new Set(ids).size).toBe(ids.length);+ expect(ids).toHaveLength(3);+ });++ it("leaves work that is not due yet", async () => {+ await queue({ dueAt: new Date(Date.now() + 60_000) });+ const claimed = await claimDue(10);+ expect(claimed).toHaveLength(0);+ });++ it("takes the most urgent first", async () => {+ const low = await queue({ priority: 0 });+ const high = await queue({ priority: 100 });++ const claimed = await claimDue(1);+ expect(claimed[0]?.id).toBe(high.id);+ expect(claimed[0]?.id).not.toBe(low.id);+ });++ it("does not re-claim a leased row, and does re-claim an expired one", async () => {+ const task = await queue();+ await claimDue(10);++ expect(await claimDue(10)).toHaveLength(0);++ // A run that died mid-task must not strand its row forever.+ await db.agentTask.update({+ where: { id: task.id },+ data: { leasedUntil: new Date(Date.now() - 1000) },+ });++ expect((await claimDue(10)).map((t) => t.id)).toContain(task.id);+ });++ it("stops claiming once the work is finished", async () => {+ const task = await queue();+ await claimDue(10);+ await completeTask(task.id, "ran");++ await db.agentTask.update({+ where: { id: task.id },+ data: { leasedUntil: null },+ });++ expect(await claimDue(10)).toHaveLength(0);+ });+});++describe("scheduleTask", () => {+ it("books work with the agent's own reason", async () => {+ const dueAt = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000);+ const { id } = await scheduleTask({+ kind,+ reason: "a job change here would move the Acme deal",+ dueAt,+ });++ const row = await db.agentTask.findUnique({ where: { id } });+ expect(row?.reason).toContain("Acme");+ });++ it("moves the existing booking rather than queueing a second one", async () => {+ const soon = new Date(Date.now() + 1000);+ const later = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);++ const first = await scheduleTask({ kind, reason: "first", dueAt: soon });+ const second = await scheduleTask({ kind, reason: "second", dueAt: later });++ expect(second.id).toBe(first.id);+ expect(await db.agentTask.count({ where: { kind } })).toBe(1);+ });+});diff --git a/apps/agent/turbo.json b/apps/agent/turbo.jsonindex ae1bcb2c..8f2ddca0 100644--- a/apps/agent/turbo.json+++ b/apps/agent/turbo.json@@ -2,17 +2,30 @@"$schema": "https://turborepo.dev/schema.json","extends": ["//"],"tasks": {- "build": { "dependsOn": ["^build"], "outputs": [".eve/**"] },- "check-types": { "dependsOn": ["topo", "^build"] },+ "build": {+ "dependsOn": ["^build"],+ "outputs": [".eve/**"]+ },+ "check-types": {+ "dependsOn": ["topo", "^build"]+ },"dev": {"cache": false,"persistent": true,"passThroughEnv": [+ "AGENT_BRIDGE_SECRET",+ "AI_GATEWAY_API_KEY",+ "BLOB_READ_WRITE_TOKEN",+ "CONTEXT_DEV_API_KEY","DATABASE_URL",- "RAPIDAPI_KEY",+ "GITHUB_TOKEN","PERPLEXITY_API_KEY",- "AI_GATEWAY_API_KEY"+ "RAPIDAPI_KEY"]+ },+ "test": {+ "dependsOn": ["topo", "^build"],+ "passThroughEnv": ["DATABASE_URL"]}}}diff --git a/apps/api/.env.example b/apps/api/.env.exampledeleted file mode 100644index bf4568d5..00000000--- a/apps/api/.env.example+++ /dev/null@@ -1,41 +0,0 @@-NODE_ENV="development"-PORT="3001"--# Same database as packages/db.-DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm?schema=public"--# openssl rand -base64 32. Must match apps/app/.env — the API mints the session-# cookie and the Next.js app verifies it.-BETTER_AUTH_SECRET=""-BETTER_AUTH_URL="http://localhost:3001"--# Origins allowed to call the API with credentials (the Next.js app). Also the-# allow-list Better Auth validates post-sign-in `callbackURL`s against.-AUTH_TRUSTED_ORIGINS="http://localhost:3000"--# Required. Google Cloud console -> Credentials -> OAuth client ID (web).-# Authorised redirect URI: http://localhost:3001/api/auth/callback/google-GOOGLE_CLIENT_ID=""-GOOGLE_CLIENT_SECRET=""--# Only when the API and the app are on different subdomains, e.g. ".example.com".-# AUTH_COOKIE_DOMAIN=""--# Optional. Without it the cache is per-instance and in-memory.-# REDIS_URL="redis://localhost:6379"-# CACHE_TTL_MS="60000"--# Log every SQL statement Prisma runs (debug level, bound parameters omitted).-# Off by default: it buries every other log line under a wall of SELECTs.-# Log format and level are not configurable — they follow NODE_ENV.-# PRISMA_LOG_QUERIES="true"--# Context.dev, for the company enrichment agent (https://context.dev).-# Optional: without it the agent is disabled, a warning is logged once at boot,-# and companies stay PENDING. Server-side only — it never reaches the browser.-CONTEXT_DEV_API_KEY=""--# Where the Context.dev SDK points. Read by the SDK itself, not by our config —-# `test/enrichment.integration.spec.ts` uses it to drive the whole pipeline-# against a local stub. Leave unset in normal use.-# CONTEXT_DEV_BASE_URL="https://api.context.dev/v1"diff --git a/apps/api/README.md b/apps/api/README.mdindex f988cc44..8f56ea78 100644--- a/apps/api/README.md+++ b/apps/api/README.md@@ -5,17 +5,21 @@ NestJS API for the CRM. Runs on Bun, backed by `@crm/db` and `@crm/auth`.## Running it```sh-cp .env.example .env-openssl rand -base64 32 # -> BETTER_AUTH_SECRET (same value in apps/app/.env)+cp .env.example .env # at the repo root — one file for the whole monorepo+openssl rand -base64 32 # -> BETTER_AUTH_SECRETbun run dev # watch mode on http://localhost:3001bun run testbun run build && bun run start:prod```-Sign-in is Google-only, so `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are-required and the process refuses to boot without them. Register-`http://localhost:3001/api/auth/callback/google` as an authorised redirect URI.+Five values are required and the process refuses to boot without them, naming+the one it is missing: `DATABASE_URL`, `BETTER_AUTH_SECRET`, `ALLOWED_SIGN_IN`,+`GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. Sign-in is Google-only, so+register `http://localhost:3001/api/auth/callback/google` as an authorised+redirect URI. `src/config/env.validation.ts` is the full list of what this+process reads; [`docs/environment.md`](../../docs/environment.md) explains where+the file is found.Bun is the runtime, not just the package manager: `@crm/db` and `@crm/auth`ship TypeScript sources, so `tsc`/`node` cannot run this app directly. `tsc` is@@ -49,7 +53,8 @@ straight from Postgres via `@crm/auth` and calls the routes above withIt also calls `enableCors({ origin: trustedOrigins, credentials: true })` forthe whole app, which is what lets the browser at `localhost:3000` talk to it —-`AUTH_TRUSTED_ORIGINS` is the single knob for that.+`APP_URL` is the single knob for that, comma-separated if the app is served from+more than one origin.`main.ts` creates the app with `bodyParser: false` — Better Auth needs the rawrequest body, and the library installs its own parsers around the auth routes.diff --git a/apps/api/package.json b/apps/api/package.jsonindex 68dd98a2..627e0b13 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -3,7 +3,7 @@"version": "0.0.1","private": true,"type": "module",- "license": "UNLICENSED",+ "license": "MIT","exports": {"./app-router": "./src/generated/server.ts"},@@ -24,6 +24,7 @@"dependencies": {"@crm/auth": "workspace:*","@crm/db": "workspace:*",+ "@crm/env": "workspace:*","@keyv/redis": "^5.1.6","@nestjs/cache-manager": "^3.1.3","@nestjs/common": "^11.0.1",diff --git a/apps/api/scripts/reenrich-contacts.ts b/apps/api/scripts/reenrich-contacts.tsdeleted file mode 100644index f3cf336f..00000000--- a/apps/api/scripts/reenrich-contacts.ts+++ /dev/null@@ -1,192 +0,0 @@-import { db } from "@crm/db";-import { ActivityStampService } from "../src/crm/activity-stamp.service";-import { EnrichmentLogService } from "../src/crm/enrichment-log.service";-import { AvatarService } from "../src/enrichment/avatar.service";-import {- looksLikeSameCompany,- nameMatchesLocalPart,- searchTerms,-} from "../src/enrichment/contact-enrichment.service";-import { LinkdapiClient } from "../src/enrichment/linkdapi.client";--/**- * Fills in every contact we can identify, once.- *- * `ContactEnrichmentService` deliberately only touches contacts whose name is- * still derived from their address — that is the right rule for the ongoing- * sync, because a name a human typed should never be second-guessed. It does- * mean a contact who already had a real name never gets a photo or a title.- *- * This is the backfill for that gap: it skips the name unless it is a- * placeholder, and fills the empty fields for everybody else. Re-running is- * safe — every write is gap-filling, so a second pass changes nothing.- *- * bun run scripts/reenrich-contacts.ts- */--const rapidKey = process.env.RAPIDAPI_KEY;-const pplxKey = process.env.PERPLEXITY_API_KEY;-if (!rapidKey || !pplxKey) {- throw new Error("RAPIDAPI_KEY and PERPLEXITY_API_KEY are both required.");-}--const linkedin = new LinkdapiClient({- get: (name: string) => process.env[name],-} as never);-const avatars = new AvatarService();-const log = new EnrichmentLogService(- db as never,- new ActivityStampService(db as never),-);--/** Perplexity, restricted to LinkedIn, for the slug we cannot already read. */-async function resolveSlug(email: string, company: string): Promise<string[]> {- const slugs: string[] = [];-- for (const term of searchTerms(email.split("@")[0] ?? "")) {- const response = await fetch("https://api.perplexity.ai/chat/completions", {- method: "POST",- headers: {- authorization: `Bearer ${pplxKey}`,- "content-type": "application/json",- },- body: JSON.stringify({- model: "sonar",- search_domain_filter: ["linkedin.com"],- messages: [- {- role: "user",- content: `Find the LinkedIn profile of "${term}" who works at ${company}. Reply with the profile URL only.`,- },- ],- }),- });-- if (!response.ok) continue;-- const body = (await response.json()) as {- choices?: { message?: { content?: string } }[];- citations?: string[];- search_results?: { url?: string }[];- };-- const haystack = [- body.choices?.[0]?.message?.content ?? "",- ...(body.citations ?? []),- ...(body.search_results ?? []).map((r) => r.url ?? ""),- ].join(" ");-- for (const match of haystack.matchAll(- /linkedin\.com\/in\/([A-Za-z0-9\-_%]+)/g,- )) {- const slug = match[1];- if (slug && !slugs.includes(slug)) slugs.push(slug);- }-- if (slugs.length > 0) break;- }-- return slugs;-}--const contacts = await db.contact.findMany({- where: { email: { not: null } },- select: {- id: true,- firstName: true,- lastName: true,- email: true,- title: true,- linkedinUrl: true,- imageUrl: true,- company: { select: { name: true, domain: true } },- },- orderBy: { email: "asc" },-});--console.log(`${contacts.length} contacts with an email\n`);--let identified = 0;-let photos = 0;--for (const contact of contacts) {- const email = contact.email as string;- const local = email.split("@")[0] ?? "";- const company = contact.company?.name ?? "";- const domain = contact.company?.domain ?? email.split("@")[1] ?? "";-- // A stored profile URL is a slug we already paid for — no need to search.- const known = contact.linkedinUrl?.match(/linkedin\.com\/in\/([^/?#]+)/)?.[1];- const candidates = known ? [known] : await resolveSlug(email, company);-- let matched = false;-- for (const slug of candidates.slice(0, 3)) {- const result = await linkedin.profile(slug);- if (result.outcome !== "found") continue;-- const person = result.data;-- // A slug we already stored has been verified once; a fresh one has not.- if (!known) {- const employer = person.positions.some((position) =>- looksLikeSameCompany(position.name, company, domain),- );- if (!employer || !nameMatchesLocalPart(person, local)) continue;- }-- const placeholder =- contact.lastName === null &&- nameMatchesLocalPart(- { firstName: contact.firstName, lastName: null },- local,- );-- const imageUrl = person.pictureUrl- ? await avatars.mirror(person.pictureUrl, contact.id)- : null;-- const data: Record<string, unknown> = {};- if (placeholder && person.fullName) {- const [first, ...rest] = person.fullName.split(" ");- data.firstName = first;- data.lastName = rest.length ? rest.join(" ") : null;- }- if (!contact.title && person.headline) data.title = person.headline;- if (!contact.linkedinUrl) data.linkedinUrl = person.profileUrl;- if (!contact.imageUrl && imageUrl) data.imageUrl = imageUrl;-- if (Object.keys(data).length > 0) {- await db.contact.update({ where: { id: contact.id }, data });- await log.record({- contactId: contact.id,- subject: "Enriched from LinkedIn",- body: `Matched to ${person.fullName ?? slug}${person.headline ? `, ${person.headline}` : ""}.\n${person.profileUrl}`,- meta: {- source: "linkedin",- sourceUrl: person.profileUrl,- filled: Object.keys(data),- },- });- }-- if (imageUrl) photos += 1;- matched = true;- identified += 1;-- const name =- `${data.firstName ?? contact.firstName} ${data.lastName ?? contact.lastName ?? ""}`.trim();- console.log(- `✓ ${name.padEnd(18)} ${Object.keys(data).join(", ") || "already complete"}`,- );- break;- }-- if (!matched)- console.log(`· ${contact.firstName.padEnd(18)} no confident match`);-}--console.log(- `\n${identified}/${contacts.length} identified, ${photos} photos stored.`,-);-await db.$disconnect();diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.tsnew file mode 100644index 00000000..70b9c510--- /dev/null+++ b/apps/api/src/agent/agent-trigger.service.ts@@ -0,0 +1,132 @@+import type { Db } from "@crm/db";+import { Injectable, Logger } from "@nestjs/common";+import { InjectDatabase } from "../database/database.constants";++/**+ * How the API tells the agent something happened.+ *+ * This is the whole of what Nest knows about enrichment, and it is deliberately+ * not enrichment: it reports an event and states why it might matter. No vendor+ * client, no scoring, no decision about a person. What the agent does with+ * "this company was just created" — whether to look it up now, later, or at all+ * — is the agent's business.+ *+ * A row rather than an HTTP call to the agent. The dispatcher already leases+ * work from this table, so a row *is* the message, and it survives the agent+ * being down, redeployed, or slower than the request that produced it. An+ * outbound call from a request handler would have to be awaited (slow), fired+ * and forgotten (lost), or queued — and queued is this.+ */+@Injectable()+export class AgentTriggerService {+ private readonly logger = new Logger(AgentTriggerService.name);++ constructor(@InjectDatabase() private readonly db: Db) {}++ /** A company we have never seen. Nothing on it but a domain. */+ async companyCreated(+ companyId: string,+ reason = "New company",+ ): Promise<void> {+ await this.enqueue({+ companyId,+ kind: "company-profile",+ reason,+ priority: 10,+ budget: 4,+ });+ }++ /** A rep pressed a button and is watching. */+ async companyRequested(companyId: string, reason: string): Promise<void> {+ await this.enqueue({+ companyId,+ kind: "company-profile",+ reason,+ // Somebody is looking at the screen, so this goes to the front.+ priority: 100,+ budget: 8,+ });+ }++ /**+ * A contact arrived from a sync knowing only an address.+ *+ * The old path called an enrichment service here and it fired only when the+ * name looked derived. That test now lives with the agent, because "is this+ * name a placeholder" is a judgement about a person.+ */+ async contactCreated(contactId: string, reason: string): Promise<void> {+ await this.enqueue({+ contactId,+ kind: "identify",+ reason,+ priority: 20,+ budget: 4,+ });+ }++ /** A meeting with someone we do not know yet, happening soon. */+ async meetingSoon(contactId: string, when: Date): Promise<void> {+ await this.enqueue({+ contactId,+ kind: "meeting-prep",+ reason: `Meeting on ${when.toDateString()} with someone we know nothing about`,+ // Ahead of everything: the deadline is real and it is tomorrow.+ priority: 200,+ budget: 10,+ });+ }++ private async enqueue(task: {+ contactId?: string;+ companyId?: string;+ kind: string;+ reason: string;+ priority: number;+ budget: number;+ }): Promise<void> {+ try {+ // Nothing is queued twice for the same subject and kind while a run is+ // still outstanding — a company saved three times in a minute is one+ // piece of work, not three.+ const pending = await this.db.agentTask.findFirst({+ where: {+ kind: task.kind,+ finishedAt: null,+ ...(task.contactId ? { contactId: task.contactId } : {}),+ ...(task.companyId ? { companyId: task.companyId } : {}),+ },+ select: { id: true },+ });++ if (pending) return;++ await this.db.agentTask.create({+ data: {+ contactId: task.contactId ?? null,+ companyId: task.companyId ?? null,+ kind: task.kind,+ reason: task.reason,+ priority: task.priority,+ budget: task.budget,+ dueAt: new Date(),+ },+ });++ this.logger.log({+ message: "Agent task queued",+ kind: task.kind,+ contactId: task.contactId,+ companyId: task.companyId,+ });+ } catch (error) {+ // Never fail the request that caused it. Enrichment has never been on a+ // request path and this is not the moment to put it there.+ this.logger.error(+ { message: "Could not queue agent task", kind: task.kind },+ error instanceof Error ? error.stack : String(error),+ );+ }+ }+}diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.tsnew file mode 100644index 00000000..f1523c5e--- /dev/null+++ b/apps/api/src/agent/agent.module.ts@@ -0,0 +1,16 @@+import { Module } from "@nestjs/common";+import { AgentTriggerService } from "./agent-trigger.service";++/**+ * The API's entire relationship with the research agent.+ *+ * One service, one verb: *this happened*. What replaced `EnrichmentModule` is+ * smaller than the module docstring it replaced, which is the point — there is+ * no queue here, no vendor client, and nothing that knows what a LinkedIn+ * profile is.+ */+@Module({+ providers: [AgentTriggerService],+ exports: [AgentTriggerService],+})+export class AgentModule {}diff --git a/apps/api/src/companies/companies.module.ts b/apps/api/src/companies/companies.module.tsindex 6a958a6d..236b68e9 100644--- a/apps/api/src/companies/companies.module.ts+++ b/apps/api/src/companies/companies.module.ts@@ -1,12 +1,13 @@import { Module } from "@nestjs/common";-import { EnrichmentModule } from "../enrichment/enrichment.module";+import { AgentModule } from "../agent/agent.module";import { TrpcModule } from "../trpc/trpc.module";import { CompaniesRouter } from "./companies.router";import { CompaniesService } from "./companies.service";+import { CompanyDirectoryService } from "./company-directory.service";@Module({- imports: [TrpcModule, EnrichmentModule],- providers: [CompaniesService, CompaniesRouter],- exports: [CompaniesService],+ imports: [TrpcModule, AgentModule],+ providers: [CompaniesService, CompanyDirectoryService, CompaniesRouter],+ exports: [CompaniesService, CompanyDirectoryService],})export class CompaniesModule {}diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex 771f1125..ebc68a8b 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -12,10 +12,10 @@ import {Logger,NotFoundException,} from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";import { blankToNull, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";import { OPEN_DEAL_STAGES } from "../deals/deal-stage";-import { EnrichmentService } from "../enrichment/enrichment.service";import {countsByKey,FACET_ALL,@@ -96,7 +96,7 @@ export class CompaniesService {constructor(@InjectDatabase() private readonly db: Db,- private readonly enrichment: EnrichmentService,+ private readonly agent: AgentTriggerService,) {}async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {@@ -300,9 +300,11 @@ export class CompaniesService {domain: company.domain,});- // Fire-and-forget: a cold lookup is several seconds, and the create form- // should not wait on it. The detail page polls until it settles.- this.enrichment.enqueueCompany(company.id);+ // Fire-and-forget: the create form should not wait on research, and the+ // detail page polls until it settles. All this says is that a company now+ // exists with nothing on it but a domain — what to do about that is the+ // agent's call.+ await this.agent.companyCreated(company.id);return company;}@@ -361,7 +363,10 @@ export class CompaniesService {});if (data.enrichmentStatus === "PENDING") {- this.enrichment.enqueueCompany(id);+ await this.agent.companyCreated(+ id,+ "Domain changed — anything we knew was about a different company",+ );}return updated;@@ -371,10 +376,13 @@ export class CompaniesService {}/**- * The "Re-enrich" button.+ * The "Look this up again" button.*- * `force` bypasses Context.dev's ~90-day cache, which is the whole reason- * someone would press it.+ * Queues the work at the front and returns immediately. It no longer forces+ * a vendor cache bypass, because the API no longer knows there is a vendor:+ * a rep asking for a fresh look is an event, and how to honour it — which+ * sources, how deep, whether the cached answer is still good — belongs to+ * the agent.*/async enrich(id: string): Promise<{ id: string; queued: boolean }> {const company = await this.db.company.findUnique({@@ -386,16 +394,38 @@ export class CompaniesService {throw new NotFoundException(`No company with id ${id}.`);}- return { id, queued: this.enrichment.enqueueCompany(id, { force: true }) };+ await this.db.company.update({+ where: { id },+ data: { enrichmentStatus: "PENDING", enrichmentError: null },+ });+ await this.agent.companyRequested(id, "A rep asked for a fresh look");++ return { id, queued: true };}- /** Reads the company's site and posts a brief to its timeline. */+ /** Asks the agent for a written brief on the company's timeline. */async research(id: string, actingUserId: string) {- const result = await this.enrichment.researchCompany(id, actingUserId);- if (!result.ok) {- throw new BadRequestException(result.reason);+ const company = await this.db.company.findUnique({+ where: { id },+ select: { id: true, domain: true },+ });++ if (!company) {+ throw new NotFoundException(`No company with id ${id}.`);}- return result;++ if (!company.domain) {+ throw new BadRequestException(+ "There is nothing to read without a domain — add one first.",+ );+ }++ await this.agent.companyRequested(+ id,+ `Briefing requested by a rep (${actingUserId})`,+ );++ return { ok: true as const, queued: true as const };}/**diff --git a/apps/api/src/companies/company-directory.service.ts b/apps/api/src/companies/company-directory.service.tsnew file mode 100644index 00000000..6bf1974e--- /dev/null+++ b/apps/api/src/companies/company-directory.service.ts@@ -0,0 +1,74 @@+import { type Db, EnrichmentStatus } from "@crm/db";+import { Injectable, Logger } from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";+import { InjectDatabase } from "../database/database.constants";+import { domainFromEmail } from "./domain";++/**+ * "Which company does this address belong to?" — the CRM half of a question+ * that used to be half enrichment.+ *+ * The old `EnrichmentService.companyForEmail` called Context.dev *inside the+ * request* so a new company could arrive already named "Stripe" rather than+ * "stripe.com". That was a nice touch bought at a bad price: a vendor lookup on+ * the path of every contact create and every sync tick, in the layer that is+ * not allowed to know vendors exist.+ *+ * So this does the part that is genuinely ours — find or create by domain — and+ * tells the agent a bare company now exists. The name is the domain for the few+ * seconds it takes the agent to replace it, and the sheet polls, which it+ * already did.+ */+@Injectable()+export class CompanyDirectoryService {+ private readonly logger = new Logger(CompanyDirectoryService.name);++ constructor(+ @InjectDatabase() private readonly db: Db,+ private readonly agent: AgentTriggerService,+ ) {}++ async companyForEmail(+ email: string,+ options: { ownerId?: string | null } = {},+ ): Promise<string | null> {+ const domain = domainFromEmail(email);+ if (!domain) return null;++ const existing = await this.db.company.findUnique({+ where: { domain },+ select: { id: true },+ });+ if (existing) return existing.id;++ // Two contacts at a new company can race here; the unique index on+ // `domain` is what actually settles it.+ const company = await this.db.company.upsert({+ where: { domain },+ create: {+ name: domain,+ domain,+ website: `https://${domain}`,+ enrichmentStatus: EnrichmentStatus.PENDING,+ // An unowned company is nobody's job. Whoever's action produced it+ // owns it until someone reassigns.+ ownerId: options.ownerId ?? null,+ },+ update: {},+ select: { id: true },+ });++ await this.agent.companyCreated(+ company.id,+ `Created from an email domain (${domain}) — it has no name but the domain`,+ );++ this.logger.log({+ message: "Company created from an email domain",+ companyId: company.id,+ domain,+ });++ return company.id;+ }+}diff --git a/apps/api/src/config/env.validation.ts b/apps/api/src/config/env.validation.tsindex 20ca9882..f8ecae6b 100644--- a/apps/api/src/config/env.validation.ts+++ b/apps/api/src/config/env.validation.ts@@ -11,6 +11,19 @@ import {validateSync,} from "class-validator";+/**+ * Every variable the API reads, and nothing else.+ *+ * Five of these are required and the rest have working defaults, which is the+ * whole configuration surface of this repo. The list is short on purpose: a+ * variable that exists but is never read is a question a self-hoster has to+ * answer for no reason, and one that is read but not declared here fails at+ * three in the morning instead of at boot.+ *+ * Values are read from the environment, or from the repo-root `.env` that+ * `@crm/env` loads. See `.env.example`.+ */+export enum NodeEnv {Development = "development",Production = "production",@@ -27,31 +40,44 @@ export class EnvironmentVariables {@Max(65535)PORT = 3001;+ // --- required -----------------------------------------------------------+@IsString()- @MinLength(1)+ @MinLength(1, {+ message:+ "DATABASE_URL is required. `docker compose up -d` starts one, or set it to any Postgres connection string.",+ })DATABASE_URL!: string;@IsString()@MinLength(32, {message:- "BETTER_AUTH_SECRET must be at least 32 characters (openssl rand -base64 32).",+ "BETTER_AUTH_SECRET must be at least 32 characters. Generate one with: openssl rand -base64 32",})BETTER_AUTH_SECRET!: string;- @IsUrl({ require_tld: false })- BETTER_AUTH_URL!: string;-- @IsOptional()+ /**+ * Who may sign in — a comma-separated list of email domains and addresses.+ *+ * This is the entire authorisation model, so it is required rather than+ * defaulted. See `@crm/auth`'s `workspace.ts`.+ */@IsString()- AUTH_TRUSTED_ORIGINS?: string;+ @MinLength(1, {+ message:+ 'ALLOWED_SIGN_IN is required — it is the only thing deciding who can sign in. Set it to your email domain, e.g. ALLOWED_SIGN_IN="acme.com", or to a single address for a one-person install.',+ })+ ALLOWED_SIGN_IN!: string;- // Google is the only way in, so unlike @crm/auth — which stays loadable- // without credentials for `better-auth generate` — the process that serves- // the auth routes refuses to start without them.+ /**+ * Google is the only sign-in method, so unlike `@crm/auth` — which stays+ * loadable without credentials for `better-auth generate` — the process that+ * serves the auth routes refuses to start without them.+ */@IsString()@MinLength(1, {message:- "GOOGLE_CLIENT_ID is required — Google is the only sign-in method. Create an OAuth client ID in the Google Cloud console.",+ "GOOGLE_CLIENT_ID is required — Google is the only sign-in method. Create an OAuth client ID (web) in the Google Cloud console.",})GOOGLE_CLIENT_ID!: string;@@ -59,23 +85,33 @@ export class EnvironmentVariables {@MinLength(1, { message: "GOOGLE_CLIENT_SECRET is required." })GOOGLE_CLIENT_SECRET!: string;- /** Parent domain for session cookies when the API and app differ. */+ // --- defaulted ----------------------------------------------------------++ /** Where this API is reachable. Only needs setting off localhost. */+ @IsOptional()+ @IsUrl({ require_tld: false })+ API_URL?: string;++ /**+ * Where the browser is. Allowed to call the API with credentials, and the+ * allow-list Better Auth validates post-sign-in `callbackURL`s against.+ * Comma-separated if there is genuinely more than one.+ */@IsOptional()@IsString()- AUTH_COOKIE_DOMAIN?: string;+ APP_URL?: string;+ // --- optional -----------------------------------------------------------++ /** Parent domain for session cookies when the API and app differ, e.g. ".example.com". */@IsOptional()@IsString()- REDIS_URL?: string;+ AUTH_COOKIE_DOMAIN?: string;- /**- * Context.dev, for company enrichment. Optional: without it the agent is- * disabled, a warning is logged once at boot, and companies stay `PENDING`.- * Server-side only — it never reaches the browser.- */+ /** Without it the cache is per-instance and in-memory, which is fine. */@IsOptional()@IsString()- CONTEXT_DEV_API_KEY?: string;+ REDIS_URL?: string;@IsOptional()@Type(() => Number)@@ -87,9 +123,8 @@ export class EnvironmentVariables {* Bearer guard on `POST /internal/sync/google`.** Not a feature flag — Gmail and Calendar sync is simply on, because mailbox- * access is a condition of signing in and the OAuth client is already- * required. This is the one thing the cron route genuinely needs, and the- * route fails closed without it.+ * access is a condition of signing in. This is the one thing the cron route+ * genuinely needs, and the route fails closed without it.*/@IsOptional()@IsString()@@ -97,14 +132,6 @@ export class EnvironmentVariables {message: "CRON_SECRET must be at least 16 characters.",})CRON_SECRET?: string;-- /**- * RapidAPI, for LinkedIn profile enrichment via LinkDAPI. Optional: without- * it contacts keep the name derived from their address, logged once at boot.- */- @IsOptional()- @IsString()- RAPIDAPI_KEY?: string;}export function validateEnv(@@ -124,7 +151,10 @@ export function validateEnv(const details = errors.map((error) => Object.values(error.constraints ?? {}).join(", ")).join("\n - ");- throw new Error(`Invalid environment configuration:\n - ${details}`);++ throw new Error(+ `Invalid environment configuration:\n - ${details}\n\nSee .env.example at the root of the repo.`,+ );}return validated;diff --git a/apps/api/src/contacts/contacts.contracts.ts b/apps/api/src/contacts/contacts.contracts.tsindex 94a02549..7063ebdb 100644--- a/apps/api/src/contacts/contacts.contracts.ts+++ b/apps/api/src/contacts/contacts.contracts.ts@@ -37,6 +37,10 @@ const contactUpdateInput = z.object({phone: z.string().optional(),title: z.string().optional(),linkedinUrl: z.string().optional(),+ twitterUrl: z.string().optional(),+ githubUrl: z.string().optional(),+ // `summary` is deliberately absent: the research agent owns it, and a field+ // a rep can retype is a field that gets overwritten on the next run.companyId: z.string().nullable().optional(),ownerId: z.string().nullable().optional(),});@@ -49,3 +53,19 @@ export const contactUpdateArgs = z.object({});export const contactIdInput = z.object({ id: z.string() });++/**+ * A rep settling a proposal the agent could not settle itself.+ *+ * This is the one place the API touches enrichment output, and it is not+ * enrichment: no research, no scoring, no judgement about a person — a human+ * pressed accept, and the record follows. The decision is also the label that+ * calibrates the confidence model, which is why `decidedById` is stored rather+ * than the row simply being deleted.+ */+export const factDecisionInput = z.object({+ factId: z.string(),+ decision: z.enum(["accept", "dismiss"]),+});++export type FactDecisionInput = z.infer<typeof factDecisionInput>;diff --git a/apps/api/src/contacts/contacts.module.ts b/apps/api/src/contacts/contacts.module.tsindex 18f2f279..8a508085 100644--- a/apps/api/src/contacts/contacts.module.ts+++ b/apps/api/src/contacts/contacts.module.ts@@ -1,11 +1,12 @@import { Module } from "@nestjs/common";-import { EnrichmentModule } from "../enrichment/enrichment.module";+import { AgentModule } from "../agent/agent.module";+import { CompaniesModule } from "../companies/companies.module";import { TrpcModule } from "../trpc/trpc.module";import { ContactsRouter } from "./contacts.router";import { ContactsService } from "./contacts.service";@Module({- imports: [TrpcModule, EnrichmentModule],+ imports: [TrpcModule, AgentModule, CompaniesModule],providers: [ContactsService, ContactsRouter],exports: [ContactsService],})diff --git a/apps/api/src/contacts/contacts.router.ts b/apps/api/src/contacts/contacts.router.tsindex 79b1463a..b3f6f5ba 100644--- a/apps/api/src/contacts/contacts.router.ts+++ b/apps/api/src/contacts/contacts.router.ts@@ -1,12 +1,21 @@import { Inject } from "@nestjs/common";-import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";+import {+ Ctx,+ Input,+ Mutation,+ Query,+ Router,+ UseMiddlewares,+} from "nestjs-trpc";import type { z } from "zod";+import type { AuthedTrpcContext } from "../trpc/context.types";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";import {contactCreateInput,contactIdInput,contactListInput,contactUpdateArgs,+ factDecisionInput,} from "./contacts.contracts";import { ContactsService } from "./contacts.service";@@ -36,4 +45,13 @@ export class ContactsRouter {async update(@Input() input: z.infer<typeof contactUpdateArgs>) {return this.contacts.update(input.id, input.data);}++ /** A rep accepting or dismissing something the agent suggested. */+ @Mutation({ input: factDecisionInput })+ async decideFact(+ @Ctx() ctx: AuthedTrpcContext,+ @Input() input: z.infer<typeof factDecisionInput>,+ ) {+ return this.contacts.decideFact(input, ctx.user.id);+ }}diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 9c381857..75af00a7 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -1,5 +1,8 @@import {+ type ContactBriefSections,type Db,+ type FactEvidence,+ FactStatus,type Prisma,Prisma as PrismaNamespace,type RecordSource,@@ -10,9 +13,10 @@ import {Logger,NotFoundException,} from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";+import { CompanyDirectoryService } from "../companies/company-directory.service";import { blankToNull, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";-import { EnrichmentService } from "../enrichment/enrichment.service";import {countsByKey,FACET_ALL,@@ -26,6 +30,7 @@ import type {ContactCreateInput,ContactListInput,ContactUpdateInput,+ FactDecisionInput,} from "./contacts.contracts";const OWNER_SELECT = {@@ -48,6 +53,21 @@ const COMPANY_SELECT = {/** The facet value for a contact who works nowhere we know of. */const NO_COMPANY = "none";+/**+ * Which `Contact` column an accepted fact writes through to.+ *+ * The agent's `facts.ts` holds the same map, because it is the one deciding+ * what a field means; this half only needs to know where an accepted value+ * lands. Fields absent from here (`seniority`, `employer`, `location`) have no+ * column — they are read straight off the fact by the background panel.+ */+const FACT_COLUMNS: Record<string, string | undefined> = {+ title: "title",+ linkedinUrl: "linkedinUrl",+ twitterUrl: "twitterUrl",+ githubUrl: "githubUrl",+};+export type ContactRow = {id: string;firstName: string;@@ -101,7 +121,8 @@ export class ContactsService {constructor(@InjectDatabase() private readonly db: Db,- private readonly enrichment: EnrichmentService,+ private readonly companies: CompanyDirectoryService,+ private readonly agent: AgentTriggerService,) {}async list(input: ContactListInput): Promise<ListResult<ContactRow>> {@@ -154,8 +175,41 @@ export class ContactsService {phone: true,title: true,linkedinUrl: true,+ twitterUrl: true,+ githubUrl: true,imageUrl: true,+ enrichmentStatus: true,+ enrichmentError: true,createdAt: true,+ brief: {+ select: {+ narrative: true,+ sections: true,+ score: true,+ sourceUrl: true,+ refreshedAt: true,+ },+ },+ // Applied facts are the provenance behind values already on the+ // record; proposed ones are suggestions the sheet offers. Dismissed+ // and superseded stay out of the read path — they are history, and+ // the timeline is where history belongs.+ facts: {+ where: { status: { in: [FactStatus.APPLIED, FactStatus.PROPOSED] } },+ orderBy: { observedAt: "desc" },+ select: {+ id: true,+ field: true,+ value: true,+ score: true,+ band: true,+ evidence: true,+ method: true,+ sourceUrl: true,+ status: true,+ observedAt: true,+ },+ },company: {select: { ...COMPANY_SELECT, industry: true, primaryContactId: true },},@@ -183,12 +237,31 @@ export class ContactsService {throw new NotFoundException(`No contact with id ${id}.`);}- const { deals, createdAt, company, ...rest } = contact;+ const relationship = await this.relationship(+ id,+ contact.company?.id ?? null,+ );++ const { deals, createdAt, brief, facts, company, ...rest } = contact;return {...rest,company,createdAt: createdAt.toISOString(),+ brief: brief+ ? {+ ...brief,+ sections: brief.sections as ContactBriefSections,+ refreshedAt: brief.refreshedAt.toISOString(),+ }+ : null,+ facts: facts.map((fact) => ({+ ...fact,+ evidence: fact.evidence as FactEvidence[],+ observedAt: fact.observedAt.toISOString(),+ })),+ /** What we have actually said to each other. */+ relationship,/** True when this is the person to call at their company. */isPrimaryContact: company?.primaryContactId === contact.id,deals: deals.map(({ role, deal }) => ({@@ -222,7 +295,7 @@ export class ContactsService {const companyId =input.companyId ??- ? await this.enrichment.companyForEmail(email, {+ ? await this.companies.companyForEmail(email, {// Same rule as the sync: a company conjured out of somebody's// action belongs to them, not to nobody.ownerId: input.ownerId,@@ -244,6 +317,15 @@ export class ContactsService {this.logger.log({ message: "Contact created", contactId: contact.id });+ // A person typed this one, so there is no placeholder name to fix — but+ // there is usually no title, no profile and no background either, and a+ // rep who has just added somebody is the likeliest person to open them+ // again in the next minute.+ await this.agent.contactCreated(+ contact.id,+ "Added by a rep, with nothing on the record yet",+ );+return contact;}@@ -259,6 +341,12 @@ export class ContactsService {if (input.linkedinUrl !== undefined) {data.linkedinUrl = blankToNull(input.linkedinUrl);}+ if (input.twitterUrl !== undefined) {+ data.twitterUrl = blankToNull(input.twitterUrl);+ }+ if (input.githubUrl !== undefined) {+ data.githubUrl = blankToNull(input.githubUrl);+ }if (input.companyId !== undefined) {data.company = input.companyId? { connect: { id: input.companyId } }@@ -281,6 +369,173 @@ export class ContactsService {}}+ /**+ * What we already know from our own mailbox and calendar.+ *+ * The one block on this sheet no CRM that buys its data can render: how many+ * emails, whether they have ever actually replied, when we last heard from+ * them, what is in the diary, and who else we know at the same company.+ *+ * Counts and dates only — the bodies stay out of the API. The agent reads+ * those (they are the best evidence we have) but the browser has no use for+ * them here, and shipping a thread into a record payload is how message+ * content ends up somewhere nobody expected.+ */+ private async relationship(contactId: string, companyId: string | null) {+ const now = new Date();++ const [threads, lastReply, meetings, nextMeeting, colleagues] =+ await Promise.all([+ this.db.emailThread.aggregate({+ where: { contactId },+ _sum: { messageCount: true },+ _count: { _all: true },+ }),+ this.db.emailMessage.findFirst({+ where: { thread: { contactId }, direction: "INBOUND" },+ orderBy: { sentAt: "desc" },+ select: { sentAt: true },+ }),+ this.db.calendarEvent.count({+ where: {+ OR: [{ contactId }, { attendees: { some: { contactId } } }],+ },+ }),+ this.db.calendarEvent.findFirst({+ where: {+ startsAt: { gt: now },+ OR: [{ contactId }, { attendees: { some: { contactId } } }],+ },+ orderBy: { startsAt: "asc" },+ select: { title: true, startsAt: true },+ }),+ companyId+ ? this.db.contact.findMany({+ where: { companyId, id: { not: contactId } },+ orderBy: { lastActivityAt: { sort: "desc", nulls: "last" } },+ take: 4,+ select: {+ id: true,+ firstName: true,+ lastName: true,+ title: true,+ },+ })+ : Promise.resolve([]),+ ]);++ return {+ emails: threads._sum.messageCount ?? 0,+ threads: threads._count._all,+ // The distinction that matters on a sheet: we have emailed them 12+ // times and they have never once written back is a different+ // relationship from 12 emails with 6 replies.+ lastReplyAt: lastReply?.sentAt.toISOString() ?? null,+ meetings,+ nextMeeting: nextMeeting+ ? {+ title: nextMeeting.title,+ startsAt: nextMeeting.startsAt.toISOString(),+ }+ : null,+ colleagues: colleagues.map((colleague) => ({+ id: colleague.id,+ name: [colleague.firstName, colleague.lastName]+ .filter(Boolean)+ .join(" "),+ title: colleague.title,+ })),+ };+ }++ /**+ * A rep accepting or dismissing something the agent proposed.+ *+ * Accepting writes the value through to the record and supersedes whatever+ * was there; dismissing keeps the row so the agent can be told never to+ * offer it again. Neither branch researches anything — this is a human+ * decision being executed, which is the only enrichment-shaped thing that+ * belongs on this side of the wire.+ */+ async decideFact(+ input: FactDecisionInput,+ userId: string,+ ): Promise<{ contactId: string; field: string; applied: boolean }> {+ const fact = await this.db.contactFact.findUnique({+ where: { id: input.factId },+ select: {+ id: true,+ contactId: true,+ field: true,+ value: true,+ status: true,+ },+ });++ if (!fact) {+ throw new NotFoundException(`No fact with id ${input.factId}.`);+ }++ if (fact.status !== FactStatus.PROPOSED) {+ throw new ConflictException("That suggestion has already been settled.");+ }++ const accepted = input.decision === "accept";+ const column = FACT_COLUMNS[fact.field];++ await this.db.$transaction(async (tx) => {+ if (accepted) {+ await tx.contactFact.updateMany({+ where: {+ contactId: fact.contactId,+ field: fact.field,+ status: FactStatus.APPLIED,+ },+ data: { status: FactStatus.SUPERSEDED, supersededAt: new Date() },+ });+ }++ await tx.contactFact.update({+ where: { id: fact.id },+ data: {+ status: accepted ? FactStatus.APPLIED : FactStatus.DISMISSED,+ decidedById: userId,+ decidedAt: new Date(),+ },+ });++ if (accepted && column) {+ await tx.contact.update({+ where: { id: fact.contactId },+ data: { [column]: fact.value },+ });+ }++ if (accepted && fact.field === "name") {+ const [firstName, ...rest] = fact.value.trim().split(/\s+/);+ if (firstName) {+ await tx.contact.update({+ where: { id: fact.contactId },+ data: {+ firstName,+ lastName: rest.length > 0 ? rest.join(" ") : null,+ },+ });+ }+ }+ });++ this.logger.log({+ message: "Fact decided",+ factId: fact.id,+ contactId: fact.contactId,+ field: fact.field,+ decision: input.decision,+ });++ return { contactId: fact.contactId, field: fact.field, applied: accepted };+ }+/** `q` matches a name, an email address, or where they work. */private searchFilter(q: string): Prisma.ContactWhereInput {const term = q.trim();diff --git a/apps/api/src/enrichment/avatar.service.ts b/apps/api/src/enrichment/avatar.service.tsdeleted file mode 100644index 08bc1711..00000000--- a/apps/api/src/enrichment/avatar.service.ts+++ /dev/null@@ -1,94 +0,0 @@-import { Injectable, Logger } from "@nestjs/common";-import { put } from "@vercel/blob";--/** Bigger than any avatar, small enough that a redirect to something huge stops here. */-const MAX_BYTES = 3 * 1024 * 1024;-const TIMEOUT_MS = 15_000;--const ALLOWED = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);--/**- * Mirrors a profile picture into Vercel Blob.- *- * LinkedIn's CDN URLs are signed and expire — the ones we fetched carried- * `e=1787184000`, roughly three weeks out. Storing that URL would give every- * contact an avatar that works today and is a broken image next month, which is- * worse than no avatar because nobody would connect the two.- *- * So the bytes are copied once and the record points at our own copy.- */-@Injectable()-export class AvatarService {- private readonly logger = new Logger(AvatarService.name);-- get enabled(): boolean {- return Boolean(process.env.BLOB_READ_WRITE_TOKEN);- }-- /**- * Fetches a remote image and stores it. Returns our URL, or null.- *- * Never throws: an avatar is decoration, and a contact whose photo could not- * be fetched is still a contact worth having.- */- async mirror(sourceUrl: string, contactId: string): Promise<string | null> {- if (!this.enabled) return null;-- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);-- try {- const response = await fetch(sourceUrl, {- signal: controller.signal,- // LinkedIn's CDN rejects requests carrying our origin.- referrerPolicy: "no-referrer",- });-- if (!response.ok) return null;-- const type = response.headers.get("content-type")?.split(";")[0]?.trim();- if (!type || !ALLOWED.has(type)) {- this.logger.debug({- message: "Avatar skipped — not an image",- contactId,- type,- });- return null;- }-- const buffer = await response.arrayBuffer();- if (buffer.byteLength === 0 || buffer.byteLength > MAX_BYTES) return null;-- // Keyed by contact, so re-enriching replaces the photo rather than- // littering the store with orphans.- const extension = type.split("/")[1] ?? "jpg";- const blob = await put(- `contacts/${contactId}.${extension}`,- Buffer.from(buffer),- {- access: "public",- contentType: type,- addRandomSuffix: false,- allowOverwrite: true,- },- );-- this.logger.log({- message: "Avatar mirrored",- contactId,- bytes: buffer.byteLength,- });-- return blob.url;- } catch (error) {- this.logger.debug({- message: "Avatar mirror failed",- contactId,- reason: error instanceof Error ? error.message : String(error),- });- return null;- } finally {- clearTimeout(timer);- }- }-}diff --git a/apps/api/src/enrichment/contact-enrichment.service.ts b/apps/api/src/enrichment/contact-enrichment.service.tsdeleted file mode 100644index 2e66e409..00000000--- a/apps/api/src/enrichment/contact-enrichment.service.ts+++ /dev/null@@ -1,327 +0,0 @@-import { type Db, RecordSource } from "@crm/db";-import { Injectable, Logger } from "@nestjs/common";-import { domainFromEmail } from "../companies/domain";-import { EnrichmentLogService } from "../crm/enrichment-log.service";-import { InjectDatabase } from "../database/database.constants";-import { isDerivedName, splitName } from "../google/participants";-import { AvatarService } from "./avatar.service";-import { ContextDevClient } from "./context-dev.client";-import { EnrichmentQueue } from "./enrichment.queue";-import { LinkdapiClient } from "./linkdapi.client";--type Resolved = {- fullName: string;- title: string | null;- linkedinUrl: string | null;- /** LinkedIn's signed CDN URL — mirrored, never stored as-is. */- pictureUrl: string | null;- sourceUrl: string;-};--/**- * Puts a real name to an address the sync only knew as a local part.- *- * Why this exists: Google Calendar returns `displayName: null` for most- * attendees, so a contact routinely arrives as "Abigham" — the address, title- * cased. The temptation is to have a model expand it, and that is exactly what- * this must not do: "abigham" only becomes "Abbie Bigham" if you already know- * her, and a model asked to guess will produce something plausible and wrong,- * which is worse than an ugly name because nobody can tell it is wrong.- *- * So the flow is search-then-read: find a page that names the person, extract- * what it says, and write nothing if no page does. Every field is sourced, and- * `sourceUrl` is recorded so a rep can check.- *- * Deliberately **not** an eve agent. eve is not installed, and this is one- * queued lookup that fills empty fields and stops — the exact shape- * `EnrichmentService` already has. A second background runtime to do the first- * one's job would be machinery, not capability.- */-@Injectable()-export class ContactEnrichmentService {- private readonly logger = new Logger(ContactEnrichmentService.name);-- constructor(- @InjectDatabase() private readonly db: Db,- private readonly context: ContextDevClient,- private readonly queue: EnrichmentQueue,- private readonly linkedin: LinkdapiClient,- private readonly log: EnrichmentLogService,- private readonly avatars: AvatarService,- ) {}-- get enabled(): boolean {- return this.context.enabled && this.linkedin.enabled;- }-- /**- * Queues a contact whose name we had to invent from their address.- *- * Fire-and-forget, and skipped entirely when the name is already real —- * there is nothing to improve and it would spend a lookup to confirm it.- */- enqueue(contactId: string): boolean {- if (!this.enabled) return false;-- return this.queue.enqueue(`contact:${contactId}`, () =>- this.run(contactId),- );- }-- private async run(contactId: string): Promise<void> {- const contact = await this.db.contact.findUnique({- where: { id: contactId },- select: {- id: true,- firstName: true,- lastName: true,- email: true,- title: true,- linkedinUrl: true,- imageUrl: true,- source: true,- company: { select: { name: true, domain: true } },- },- });-- if (!contact?.email) return;-- // Only ever improves a name derived from the address. A name a human typed,- // or one a mail header supplied, is already better than anything a search- // will find.- if (!isDerivedName(contact.email, contact.firstName, contact.lastName)) {- return;- }-- const domain = contact.company?.domain ?? domainFromEmail(contact.email);- if (!domain) return;-- const found = await this.lookup(- contact.email,- contact.company?.name ?? domain,- domain,- );-- if (!found) {- this.logger.debug({- message: "No sourced name for contact",- contactId,- domain,- });- return;- }-- const { firstName, lastName } = splitName(found.fullName, contact.email);-- // Mirrored before the write so the record never points at a URL that- // expires. A failure here just means no photo.- const imageUrl = found.pictureUrl- ? await this.avatars.mirror(found.pictureUrl, contactId)- : null;-- await this.db.contact.update({- where: { id: contactId },- data: {- firstName,- lastName,- ...(imageUrl && !contact.imageUrl ? { imageUrl } : {}),- // Only fills gaps — never overwrites what is already there.- ...(contact.title ? {} : { title: found.title ?? null }),- ...(contact.linkedinUrl- ? {}- : { linkedinUrl: found.linkedinUrl ?? null }),- },- });-- await this.log.record({- contactId,- companyId: null,- subject: "Identified from LinkedIn",- body: `Matched to ${found.fullName}${found.title ? `, ${found.title}` : ""}.\n${found.sourceUrl}`,- meta: { source: "linkedin", sourceUrl: found.sourceUrl },- });-- this.logger.log({- message: "Contact name resolved from the web",- contactId,- domain,- sourceUrl: found.sourceUrl,- });- }-- /**- * Resolves the person's LinkedIn slug, then reads their profile.- *- * Two vendors because neither can do this alone: Context.dev is a real search- * engine but cannot read LinkedIn, which blocks scrapers; LinkDAPI reads- * LinkedIn beautifully but its own people search returns unrelated strangers.- * Search to find the door, LinkDAPI to walk through it.- *- * Proven end to end: `[email protected]` → `yael-madar` → Yael Madar, VP Fund- * Finance & Venture Lending at Valley Bank.- */- private async lookup(- email: string,- companyName: string,- domain: string,- ): Promise<Resolved | null> {- const local = email.split("@")[0] ?? "";-- // Searching the raw handle finds nothing: `abigham` is not anybody's slug.- // Searching the *surname it contains* finds her immediately, which is why- // the local part is decomposed before it is searched.- const slugs: string[] = [];-- for (const term of searchTerms(local)) {- const search = await this.context.search(- `site:linkedin.com/in "${term}" ${companyName}`,- { limit: 10 },- );- if (search.outcome !== "found") continue;-- for (const result of search.results) {- const match = /linkedin\.com\/in\/([A-Za-z0-9\-_%]+)/.exec(- result.url ?? "",- );- if (match?.[1] && !slugs.includes(match[1])) slugs.push(match[1]);- }-- // The first term that produces candidates is the most specific one.- if (slugs.length > 0) break;- }-- for (const slug of slugs.slice(0, 4)) {- const profile = await this.linkedin.profile(slug);- if (profile.outcome !== "found") continue;-- const person = profile.data;- if (!person.fullName) continue;-- // The check that stops a plausible stranger being filed against a real- // customer: the profile has to actually work at this company, and the- // name has to be consistent with the address we started from.- const employer = person.positions.some((position) =>- looksLikeSameCompany(position.name, companyName, domain),- );- if (!employer) continue;-- if (!nameMatchesLocalPart(person, local)) continue;-- return {- fullName: person.fullName,- title: person.headline,- linkedinUrl: person.profileUrl,- pictureUrl: person.pictureUrl,- sourceUrl: person.profileUrl,- };- }-- return null;- }-}--/** The sources a contact may be auto-enriched from. */-export const AUTO_ENRICHED_SOURCES = [- RecordSource.EMAIL,- RecordSource.CALENDAR,-] as const;--/**- * Whether a LinkedIn employer is the company we think it is.- *- * Loose on purpose — "Valley Bank" has to match a CRM company called "Valley"- * on `valley.com` — but anchored on one of them containing the other rather- * than on fuzzy distance, which would happily match "Valley" to "Silicon- * Valley Bank".- */-export function looksLikeSameCompany(- employer: string,- companyName: string,- domain: string,-): boolean {- const a = normalise(employer);- const b = normalise(companyName);- const c = normalise(domain.replace(/\.[a-z.]+$/, ""));-- if (!a) return false;- return a === b || a.includes(b) || b.includes(a) || a.includes(c);-}--/**- * Whether a real name is consistent with the address it was found from.- *- * The direction matters and is the whole difference between this and guessing:- * the name is never *generated* from the local part, only *checked* against it.- * `ymadar` is consistent with Yael Madar (`y` + `madar`); it is not consistent- * with Antonio Baravalle, which is how a confident wrong answer gets rejected.- */-export function nameMatchesLocalPart(- person: { firstName: string | null; lastName: string | null },- local: string,-): boolean {- const first = normalise(person.firstName ?? "");- const last = normalise(person.lastName ?? "");- const handle = normalise(local);-- if (!handle || (!first && !last)) return false;-- const forms = [- `${first}${last}`,- `${last}${first}`,- `${first.slice(0, 1)}${last}`,- `${last}${first.slice(0, 1)}`,- `${first}${last.slice(0, 1)}`,- first,- last,- ].filter(Boolean);-- // Either the handle is one of the usual constructions, or it is a prefix of- // one — corporate directories truncate.- return forms.some(- (form) =>- form === handle || form.startsWith(handle) || handle.startsWith(form),- );-}--function normalise(value: string): string {- return value.toLowerCase().replace(/[^a-z0-9]/g, "");-}--/**- * Search terms to try for an email local part, most specific first.- *- * `[email protected]` forced this. Searching `abigham` finds nothing — it is- * not a slug, a name, or a word. Searching the surname it contains, `bigham`,- * returns `linkedin.com/in/abigailbigham` as the first result: Abbie Bigham,- * Growth Specialist at HubSpot.- *- * The split is generated blind, and every candidate it produces is verified- * against the fetched profile by `nameMatchesLocalPart` and- * `looksLikeSameCompany`. So a wrong guess costs a search rather than producing- * a wrong contact — guess the *query*, never the answer.- */-export function searchTerms(local: string): string[] {- const handle = local.toLowerCase().replace(/[^a-z0-9._-]/g, "");- const terms: string[] = [];-- const add = (term: string) => {- if (term.length >= 3 && !terms.includes(term)) terms.push(term);- };-- // Explicitly separated parts are not a guess — `jane.doe` says what it is.- const parts = handle.split(/[._-]+/).filter(Boolean);- if (parts.length > 1) {- add(parts.join(" "));- add(parts[parts.length - 1] as string);- }-- // One token: try the whole thing, then the surname left when a one- or- // two-letter initial is stripped off the front.- add(handle);- if (parts.length === 1) {- add(handle.slice(1));- add(handle.slice(2));- }-- return terms;-}diff --git a/apps/api/src/enrichment/context-dev.client.ts b/apps/api/src/enrichment/context-dev.client.tsdeleted file mode 100644index 2cdb75d8..00000000--- a/apps/api/src/enrichment/context-dev.client.ts+++ /dev/null@@ -1,311 +0,0 @@-import { Injectable, Logger } from "@nestjs/common";-import { ConfigService } from "@nestjs/config";-import ContextDev from "context.dev";-import { APIError } from "context.dev/core/error";-import type { EnvironmentVariables } from "../config/env.validation";--/** The Context.dev `brand` object, narrowed to the parts we map. */-export type Brand = {- domain?: string | null;- title?: string | null;- description?: string | null;- slogan?: string | null;- email?: string | null;- phone?: string | null;- colors?: { hex?: string | null; name?: string | null }[] | null;- logos?:- | {- url?: string | null;- /** "light" | "dark" | "has_opaque_background". */- mode?: string | null;- type?: string | null;- /** The artwork's own dominant colours — how a dark mark is detected. */- colors?: { hex?: string | null; name?: string | null }[] | null;- }[]- | null;- socials?: { type?: string | null; url?: string | null }[] | null;- address?: {- city?: string | null;- state_code?: string | null;- country?: string | null;- country_code?: string | null;- } | null;- industries?: {- eic?: { industry?: string | null; subindustry?: string | null }[] | null;- } | null;- links?: {- pricing?: string | null;- careers?: string | null;- } | null;-};--/**- * Why a lookup did not produce a brand.- *- * `skipped` and `failed` are deliberately different: "there is nothing to find- * for this domain" is a settled answer that should stop us retrying and cost- * nothing, while "the call fell over" is worth another go.- */-export type LookupResult =- | { outcome: "found"; brand: Brand; raw: unknown }- | { outcome: "skipped"; reason: string }- | { outcome: "failed"; reason: string; retryable: boolean };--/** One web search result, narrowed to the parts a person lookup reads. */-export type SearchResult = {- url: string | null;- title: string | null;- description: string | null;- markdown: string | null;-};--/** Cold lookups are p50 ≈ 7s, p90 ≈ 18s — so this is generous on purpose. */-const TIMEOUT_MS = 60_000;--@Injectable()-export class ContextDevClient {- private readonly logger = new Logger(ContextDevClient.name);- private readonly client: ContextDev | null;-- constructor(config: ConfigService<EnvironmentVariables, true>) {- const apiKey = config.get("CONTEXT_DEV_API_KEY", { infer: true });-- if (!apiKey) {- // Logged once, at boot, rather than on every company that stays PENDING.- this.logger.warn({- message:- "CONTEXT_DEV_API_KEY is not set — enrichment is disabled and companies will stay PENDING.",- });- this.client = null;- return;- }-- this.client = new ContextDev({ apiKey });- }-- get enabled(): boolean {- return this.client !== null;- }-- /** `POST /brand/retrieve` by domain. 10 credits, only on a successful match. */- async brandByDomain(- domain: string,- maxAgeMs?: number,- ): Promise<LookupResult> {- return this.lookup({- type: "by_domain",- domain,- timeoutMS: TIMEOUT_MS,- ...(maxAgeMs === undefined ? {} : { maxAgeMs }),- });- }-- /** `POST /brand/retrieve` by work email — the domain is extracted for us. */- async brandByEmail(email: string): Promise<LookupResult> {- return this.lookup({- type: "by_email",- email,- timeoutMS: TIMEOUT_MS,- });- }-- /**- * Warms the cache so a later retrieve lands sub-second. Free, and- * fire-and-forget: the response carries no brand data.- *- * Paid plans only — a `403` here is a plan limit, not a bug, so it is logged- * once and the caller falls through to a direct retrieve.- */- async prefetch(domain: string): Promise<void> {- if (!this.client) return;-- try {- await this.client.utility.prefetch({- type: "brand",- identifier: { domain },- });- } catch (error) {- if (error instanceof APIError && error.status === 403) {- this.logger.debug({- message: "Prefetch needs a paid plan — falling through to retrieve.",- domain,- });- return;- }- this.logger.debug({- message: "Prefetch failed; falling through to retrieve.",- domain,- reason: describe(error),- });- }- }-- /**- * `POST /web/extract` against a caller-defined JSON Schema.- *- * Used for the research brief, which is not a brand lookup — it is "read this- * company's site and answer these questions".- */- async extract(- url: string,- schema: Record<string, unknown>,- instructions: string,- ): Promise<- { outcome: "found"; data: unknown } | { outcome: "failed"; reason: string }- > {- if (!this.client) {- return { outcome: "failed", reason: "Enrichment is not configured." };- }-- try {- const response = await this.client.web.extract({- url,- schema,- instructions,- maxPages: 8,- timeoutMS: TIMEOUT_MS,- });- return { outcome: "found", data: response.data };- } catch (error) {- return { outcome: "failed", reason: describe(error) };- }- }-- /**- * `POST /web/search`.- *- * Accepts Google-style operators, which is what makes a person lookup- * *sourced* rather than guessed: we search for evidence and read a name off a- * page, instead of asking a model what "abigham" probably stands for.- */- async search(- query: string,- options: { limit?: number; excludeDomains?: string[] } = {},- ): Promise<- | { outcome: "found"; results: SearchResult[] }- | { outcome: "failed"; reason: string }- > {- if (!this.client) {- return { outcome: "failed", reason: "Enrichment is not configured." };- }-- try {- const response = await this.client.web.search({- query,- // The API rejects anything under 10 — a smaller ask fails validation- // rather than returning fewer results.- numResults: Math.max(options.limit ?? 10, 10),- // Without this the results are titles and snippets only, and a name- // is usually in the page rather than the snippet.- markdownOptions: { enabled: true },- ...(options.excludeDomains- ? { excludeDomains: options.excludeDomains }- : {}),- });-- const results = (response.results ?? []).map((result) => ({- url: result.url ?? null,- title: result.title ?? null,- description: result.description ?? null,- // `code` is the per-result scrape outcome; anything but SUCCESS means- // `markdown` is null and the snippet is all we have.- markdown:- result.markdown?.code === "SUCCESS"- ? (result.markdown.markdown ?? null)- : null,- }));-- return { outcome: "found", results };- } catch (error) {- return { outcome: "failed", reason: describe(error) };- }- }-- private async lookup(- params: Parameters<ContextDev["brand"]["retrieve"]>[0],- ): Promise<LookupResult> {- if (!this.client) {- return {- outcome: "skipped",- reason: "Enrichment is not configured.",- };- }-- try {- const response = await this.client.brand.retrieve(params);- const brand = response.brand as Brand | undefined;-- if (!brand) {- return { outcome: "skipped", reason: "No brand matched." };- }-- return { outcome: "found", brand, raw: response };- } catch (error) {- return classify(error);- }- }-}--/**- * Maps Context.dev's failures onto something the CRM can act on.- *- * The important distinction is which of these should leave a company retryable.- * An unknown domain never becomes known by asking again; a timeout might.- */-function classify(error: unknown): LookupResult {- if (!(error instanceof APIError)) {- return { outcome: "failed", reason: describe(error), retryable: true };- }-- const code = errorCode(error);-- // 400 covers both malformed input and "we looked, there is nothing there".- // Neither is billed, and neither is worth retrying.- if (error.status === 400) {- if (code === "NOT_FOUND" || code === "WEBSITE_ACCESS_ERROR") {- return {- outcome: "skipped",- reason:- code === "NOT_FOUND"- ? "No brand matched this domain."- : "The site could not be reached.",- };- }- return { outcome: "failed", reason: describe(error), retryable: false };- }-- // A personal or throwaway address says nothing about where someone works.- if (error.status === 422) {- return {- outcome: "skipped",- reason: "That is a personal or disposable email address.",- };- }-- if (error.status === 401 || error.status === 403) {- return { outcome: "failed", reason: describe(error), retryable: false };- }-- // Cold-cache timeouts and rate limits are the retryable ones.- if (error.status === 408 || error.status === 429) {- return { outcome: "failed", reason: describe(error), retryable: true };- }-- return {- outcome: "failed",- reason: describe(error),- retryable: (error.status ?? 500) >= 500,- };-}--function errorCode(error: APIError): string | undefined {- const body = error.error as { error_code?: unknown } | undefined;- return typeof body?.error_code === "string" ? body.error_code : undefined;-}--function describe(error: unknown): string {- if (error instanceof APIError) {- return `${error.status ?? "?"} ${errorCode(error) ?? error.message}`;- }- return error instanceof Error ? error.message : String(error);-}diff --git a/apps/api/src/enrichment/enrichment.module.ts b/apps/api/src/enrichment/enrichment.module.tsdeleted file mode 100644index 3dc10496..00000000--- a/apps/api/src/enrichment/enrichment.module.ts+++ /dev/null@@ -1,27 +0,0 @@-import { Module } from "@nestjs/common";-import { AvatarService } from "./avatar.service";-import { ContactEnrichmentService } from "./contact-enrichment.service";-import { ContextDevClient } from "./context-dev.client";-import { EnrichmentQueue } from "./enrichment.queue";-import { EnrichmentService } from "./enrichment.service";-import { LinkdapiClient } from "./linkdapi.client";--/**- * The agent.- *- * Exports only `EnrichmentService`, so the modules that trigger enrichment- * (companies, contacts) depend on "enrich this" rather than on the queue or the- * HTTP client behind it.- */-@Module({- providers: [- ContextDevClient,- EnrichmentQueue,- EnrichmentService,- ContactEnrichmentService,- LinkdapiClient,- AvatarService,- ],- exports: [EnrichmentService, ContactEnrichmentService],-})-export class EnrichmentModule {}diff --git a/apps/api/src/enrichment/enrichment.queue.ts b/apps/api/src/enrichment/enrichment.queue.tsdeleted file mode 100644index 5c2eff29..00000000--- a/apps/api/src/enrichment/enrichment.queue.ts+++ /dev/null@@ -1,129 +0,0 @@-import { Injectable, Logger, type OnApplicationShutdown } from "@nestjs/common";--type Job = {- /** Dedupe key — the domain, so the same company queued twice runs once. */- key: string;- run: () => Promise<void>;-};--const CONCURRENCY = 2;--/**- * A small in-process queue for enrichment work.- *- * Deliberately not a job server. Enrichment is a handful of calls per company- * create, the work is idempotent, and losing a queued job on deploy costs- * nothing — the company stays `PENDING` and the next re-enrich picks it up. A- * Redis-backed queue would be more machinery than the problem has.- *- * What it does buy us: at most two concurrent Context.dev calls, one retry with- * a backoff, and per-domain dedupe so a rep hammering "Re-enrich" does not- * spend ten credits doing the same lookup ten times.- */-@Injectable()-export class EnrichmentQueue implements OnApplicationShutdown {- private readonly logger = new Logger(EnrichmentQueue.name);- private readonly pending: Job[] = [];- private readonly inFlight = new Set<string>();- private running = 0;- private shuttingDown = false;-- /**- * How long to wait before the single retry.- *- * A getter rather than a constant so the tests can subclass it down to a few- * milliseconds — Nest constructs this provider with no arguments, so a- * constructor parameter would need a DI token for no benefit.- */- protected get retryDelayMs(): number {- return 5_000;- }-- /** Resolves when the queue is empty — the hook tests wait on this. */- private idle: (() => void)[] = [];-- /**- * Queues work, unless the same key is already queued or running.- *- * Returns whether it was accepted, so a caller can tell "started" from- * "already in progress".- */- enqueue(key: string, run: () => Promise<void>): boolean {- if (this.shuttingDown) return false;- if (this.inFlight.has(key)) return false;- if (this.pending.some((job) => job.key === key)) return false;-- this.pending.push({ key, run });- this.pump();- return true;- }-- /** Waits for everything queued so far to finish. For tests and scripts. */- async drain(): Promise<void> {- if (this.running === 0 && this.pending.length === 0) return;- await new Promise<void>((resolve) => this.idle.push(resolve));- }-- onApplicationShutdown(): void {- this.shuttingDown = true;- // Queued-but-not-started work is dropped rather than raced against the- // closing database connection. Those companies stay PENDING, which is- // exactly the state a retry looks for.- const dropped = this.pending.length;- this.pending.length = 0;- if (dropped > 0) {- this.logger.log({ message: "Dropped queued enrichment jobs", dropped });- }- }-- private pump(): void {- while (this.running < CONCURRENCY && this.pending.length > 0) {- const job = this.pending.shift();- if (!job) break;- void this.execute(job);- }- }-- private async execute(job: Job): Promise<void> {- this.running += 1;- this.inFlight.add(job.key);-- try {- await job.run();- } catch (error) {- // One retry, after a pause. Anything that fails twice is recorded on the- // company as `FAILED` by the service itself; this is the safety net for- // an exception the service did not expect.- this.logger.warn({- message: "Enrichment job threw — retrying once",- key: job.key,- reason: error instanceof Error ? error.message : String(error),- });-- await sleep(this.retryDelayMs);-- try {- await job.run();- } catch (retryError) {- this.logger.error(- { message: "Enrichment job failed twice", key: job.key },- retryError instanceof Error ? retryError.stack : String(retryError),- );- }- } finally {- this.running -= 1;- this.inFlight.delete(job.key);- this.pump();-- if (this.running === 0 && this.pending.length === 0) {- const waiters = this.idle;- this.idle = [];- for (const resolve of waiters) resolve();- }- }- }-}--function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}diff --git a/apps/api/src/enrichment/enrichment.service.ts b/apps/api/src/enrichment/enrichment.service.tsdeleted file mode 100644index b62b368a..00000000--- a/apps/api/src/enrichment/enrichment.service.ts+++ /dev/null@@ -1,404 +0,0 @@-import { ActivityType, type Db, EnrichmentStatus } from "@crm/db";-import { Injectable, Logger, NotFoundException } from "@nestjs/common";-import { domainFromEmail, normalizeDomain } from "../companies/domain";-import { ActivityStampService } from "../crm/activity-stamp.service";-import {- describeFilled,- EnrichmentLogService,-} from "../crm/enrichment-log.service";-import { InjectDatabase } from "../database/database.constants";-import { brandToUpdate, filledFields } from "./brand-mapping";-import { ContextDevClient } from "./context-dev.client";-import { EnrichmentQueue } from "./enrichment.queue";--/** The shape the research brief is extracted into. */-const RESEARCH_SCHEMA = {- type: "object",- properties: {- positioning: {- type: "string",- description: "One paragraph: what they sell and who to.",- },- pricingModel: {- type: "string",- description: "How they charge — per seat, usage, flat, enterprise-only.",- },- targetCustomer: {- type: "string",- description: "The customer they describe themselves as serving.",- },- notableCustomers: {- type: "array",- items: { type: "string" },- description: "Named customers or logos on the site.",- },- recentNews: {- type: "array",- items: { type: "string" },- description: "Recent announcements, funding, or launches.",- },- },- required: ["positioning"],-} as const;--const RESEARCH_INSTRUCTIONS =- "Read this company's marketing site and answer as a salesperson preparing " +- "for a first call. Be specific and factual; leave a field empty rather than " +- "guessing.";--@Injectable()-export class EnrichmentService {- private readonly logger = new Logger(EnrichmentService.name);-- constructor(- @InjectDatabase() private readonly db: Db,- private readonly context: ContextDevClient,- private readonly queue: EnrichmentQueue,- private readonly stamp: ActivityStampService,- private readonly log: EnrichmentLogService,- ) {}-- /**- * Queues a company for enrichment.- *- * Fire-and-forget by design: a cold Context.dev lookup is p50 ≈ 7s, and a- * "New company" form that sits spinning for seven seconds is a form people- * stop using. The detail page polls while the status is `PENDING`/`RUNNING`.- */- enqueueCompany(- companyId: string,- options: { force?: boolean } = {},- ): boolean {- if (!this.context.enabled) return false;-- return this.queue.enqueue(`company:${companyId}`, () =>- this.runCompany(companyId, options.force ?? false),- );- }-- /** Whether the agent has an API key at all. */- get enabled(): boolean {- return this.context.enabled;- }-- /** Waits for queued work — used by scripts and tests, not by request paths. */- async drain(): Promise<void> {- await this.queue.drain();- }-- private async runCompany(companyId: string, force: boolean): Promise<void> {- const company = await this.db.company.findUnique({- where: { id: companyId },- select: {- id: true,- name: true,- domain: true,- description: true,- logoUrl: true,- logoDarkUrl: true,- iconUrl: true,- iconDarkUrl: true,- iconTone: true,- brandColor: true,- industry: true,- subIndustry: true,- city: true,- stateCode: true,- country: true,- countryCode: true,- phone: true,- email: true,- linkedinUrl: true,- twitterUrl: true,- githubUrl: true,- pricingUrl: true,- careersUrl: true,- },- });-- if (!company) return;-- const domain = normalizeDomain(company.domain);-- if (!domain) {- await this.settle(- companyId,- EnrichmentStatus.SKIPPED,- "No domain to look up.",- );- return;- }-- await this.db.company.update({- where: { id: companyId },- data: {- enrichmentStatus: EnrichmentStatus.RUNNING,- enrichmentError: null,- },- });-- // Free, and turns a cold 7s lookup into a warm sub-second one.- await this.context.prefetch(domain);-- // `maxAgeMs: 0` on a manual re-enrich: the whole point of pressing the- // button is to get past the ~90-day server-side cache.- const result = await this.context.brandByDomain(- domain,- force ? 0 : undefined,- );-- if (result.outcome === "skipped") {- await this.settle(companyId, EnrichmentStatus.SKIPPED, result.reason);- return;- }-- if (result.outcome === "failed") {- await this.settle(companyId, EnrichmentStatus.FAILED, result.reason);- // Let the queue's retry have a go at the retryable ones.- if (result.retryable) throw new Error(result.reason);- return;- }-- const update = brandToUpdate(result.brand, {- ...company,- // A company created from a domain alone is named after it until the- // lookup tells us better.- nameIsPlaceholder: company.name === domain,- });-- await this.db.$transaction([- this.db.company.update({- where: { id: companyId },- data: {- ...update,- enrichmentStatus: EnrichmentStatus.COMPLETE,- enrichedAt: new Date(),- enrichmentError: null,- },- }),- // The whole payload is kept so re-deriving a field later costs nothing- // and no credits.- this.db.companyEnrichment.upsert({- where: { companyId },- create: {- companyId,- raw: result.raw as never,- },- update: { raw: result.raw as never, fetchedAt: new Date() },- }),- ]);-- const filled = filledFields(update);-- await this.log.record({- companyId,- subject: "Enriched from Context.dev",- body: describeFilled(filled),- meta: { source: "context.dev", endpoint: "brand/retrieve", filled },- });-- this.logger.log({- message: "Company enriched",- companyId,- domain,- filled,- });- }-- /**- * Finds or creates the company a work email belongs to.- *- * Called when a contact is added with a work address and no company. Returns- * the company id when one was found or made, `null` when the address says- * nothing useful (a personal or throwaway domain).- */- async companyForEmail(- email: string,- options: { ownerId?: string | null } = {},- ): Promise<string | null> {- const domain = domainFromEmail(email);- if (!domain) return null;-- const existing = await this.db.company.findUnique({- where: { domain },- select: { id: true },- });- if (existing) return existing.id;-- if (!this.context.enabled) return null;-- const result = await this.context.brandByEmail(email);- if (result.outcome !== "found") {- this.logger.debug({- message: "No company for email domain",- domain,- reason: result.reason,- });- return null;- }-- const name = result.brand.title?.trim() || domain;-- // Two contacts at a new company can race here; the unique index on- // `domain` is what actually settles it.- const company = await this.db.company.upsert({- where: { domain },- create: {- name,- domain,- website: `https://${domain}`,- enrichmentStatus: EnrichmentStatus.PENDING,- // An unowned company is nobody's job. Whoever's action produced it- // owns it until someone reassigns.- ownerId: options.ownerId ?? null,- },- update: {},- select: { id: true },- });-- // Created from a lookup we already have — apply it rather than paying for- // the same brand twice.- this.enqueueCompany(company.id);-- await this.log.record({- companyId: company.id,- subject: "Company added automatically",- body: `Created from the domain ${domain}. Looking up brand details.`,- meta: { source: "email-domain", domain },- });-- this.logger.log({- message: "Company created from a contact's email domain",- companyId: company.id,- domain,- });-- return company.id;- }-- /**- * Reads the company's site and posts what it found to the timeline.- *- * On the timeline rather than in a side panel because that is where a rep is- * already looking, and because it should age like everything else — a brief- * from six months ago is context, not current truth.- */- async researchCompany(companyId: string, actingUserId: string) {- const company = await this.db.company.findUnique({- where: { id: companyId },- select: { id: true, name: true, domain: true, website: true },- });-- if (!company) {- throw new NotFoundException(`No company with id ${companyId}.`);- }-- const url =- company.website ?? (company.domain ? `https://${company.domain}` : null);-- if (!url) {- return { ok: false as const, reason: "This company has no website yet." };- }-- const result = await this.context.extract(- url,- RESEARCH_SCHEMA as unknown as Record<string, unknown>,- RESEARCH_INSTRUCTIONS,- );-- if (result.outcome === "failed") {- return { ok: false as const, reason: result.reason };- }-- const activity = await this.db.activity.create({- data: {- type: ActivityType.ENRICHMENT,- subject: `Research brief — ${company.name}`,- body: formatBrief(result.data),- occurredAt: new Date(),- companyId: company.id,- createdById: actingUserId,- meta: {- source: "context.dev",- endpoint: "web/extract",- creditCost: 10,- },- },- select: { id: true },- });-- await this.stamp.touch({ companyId: company.id }, new Date());-- this.logger.log({- message: "Research brief written",- companyId,- activityId: activity.id,- });-- return { ok: true as const, activityId: activity.id };- }-- private async settle(- companyId: string,- status: EnrichmentStatus,- reason: string,- ): Promise<void> {- await this.db.company.update({- where: { id: companyId },- data: {- enrichmentStatus: status,- enrichedAt: new Date(),- // Only a real failure is worth surfacing; "nothing to find" is a- // settled answer, not an error message to show a rep.- enrichmentError: status === EnrichmentStatus.FAILED ? reason : null,- },- });-- this.logger.log({- message: "Enrichment settled",- companyId,- status,- reason,- });- }-}--/** The extracted object as prose, because a timeline entry is read, not parsed. */-function formatBrief(data: unknown): string {- if (typeof data !== "object" || data === null) return String(data ?? "");-- const brief = data as {- positioning?: unknown;- pricingModel?: unknown;- targetCustomer?: unknown;- notableCustomers?: unknown;- recentNews?: unknown;- };-- const lines: string[] = [];- const text = (value: unknown) =>- typeof value === "string" && value.trim() ? value.trim() : null;- const list = (value: unknown) =>- Array.isArray(value)- ? value.filter((item): item is string => typeof item === "string")- : [];-- const positioning = text(brief.positioning);- if (positioning) lines.push(positioning);-- const pricing = text(brief.pricingModel);- if (pricing) lines.push(`Pricing: ${pricing}`);-- const target = text(brief.targetCustomer);- if (target) lines.push(`Sells to: ${target}`);-- const customers = list(brief.notableCustomers);- if (customers.length > 0) lines.push(`Customers: ${customers.join(", ")}`);-- const news = list(brief.recentNews);- if (news.length > 0) {- lines.push(`Recently:\n${news.map((item) => `• ${item}`).join("\n")}`);- }-- return lines.join("\n\n");-}diff --git a/apps/api/src/enrichment/linkdapi.client.ts b/apps/api/src/enrichment/linkdapi.client.tsdeleted file mode 100644index 8856fa16..00000000--- a/apps/api/src/enrichment/linkdapi.client.ts+++ /dev/null@@ -1,217 +0,0 @@-import { Injectable, Logger } from "@nestjs/common";-import { ConfigService } from "@nestjs/config";-import type { EnvironmentVariables } from "../config/env.validation";--const HOST = "linkdapi-best-unofficial-linkedin-api.p.rapidapi.com";-const TIMEOUT_MS = 20_000;--/** A LinkedIn profile, narrowed to the parts the CRM stores or renders. */-export type LinkedInProfile = {- slug: string;- fullName: string | null;- firstName: string | null;- lastName: string | null;- headline: string | null;- location: string | null;- pictureUrl: string | null;- followerCount: number | null;- connectionsCount: number | null;- /** Current employers, newest first. The job-change signal lives here. */- positions: { name: string; url: string | null }[];- profileUrl: string;-};--export type LinkedInCompany = {- id: string | null;- name: string | null;- universalName: string | null;- tagline: string | null;- description: string | null;- linkedinUrl: string | null;-};--type Result<T> =- | { outcome: "found"; data: T }- | { outcome: "missing" }- | { outcome: "failed"; reason: string };--/**- * LinkedIn profile data, via LinkDAPI on RapidAPI.- *- * **This client deliberately exposes no search.** LinkDAPI's- * `/search/people?keywords=` returns HTTP 200 with entirely unrelated people —- * "Abbie Bigham" came back as a list of Italian executives, and a different- * random set on every call. It is not rate limiting or a bad query; the- * parameter is ignored. Anything that looks like a search here would be a- * plausible-looking way to file a stranger against a real customer.- *- * So this is an *enricher*: give it a profile slug and it is excellent. Finding- * the slug is `ContextDevClient.search`'s job — see- * `ContactEnrichmentService`.- */-@Injectable()-export class LinkdapiClient {- private readonly logger = new Logger(LinkdapiClient.name);- private readonly apiKey: string | undefined;-- constructor(config: ConfigService<EnvironmentVariables, true>) {- this.apiKey = config.get("RAPIDAPI_KEY", { infer: true });-- if (!this.apiKey) {- // Once, at boot, mirroring how a missing Context.dev key is reported.- this.logger.warn({- message:- "RAPIDAPI_KEY is not set — LinkedIn enrichment is disabled and contacts keep their derived names.",- });- }- }-- get enabled(): boolean {- return Boolean(this.apiKey);- }-- /** A profile by its `linkedin.com/in/<slug>` handle. */- async profile(slug: string): Promise<Result<LinkedInProfile>> {- const result = await this.get<RawProfile>("/api/v1/profile/overview", {- username: slug,- });-- if (result.outcome !== "found") return result;-- const data = result.data;-- return {- outcome: "found",- data: {- slug,- fullName: text(data.fullName),- firstName: text(data.firstName),- lastName: text(data.lastName),- headline: text(data.headline),- location: text(data.location),- pictureUrl: text(data.profilePictureURL),- followerCount: num(data.followerCount),- connectionsCount: num(data.connectionsCount),- positions: (data.CurrentPositions ?? []).flatMap((position) =>- position?.name- ? [{ name: position.name, url: text(position.url) }]- : [],- ),- profileUrl: `https://www.linkedin.com/in/${slug}`,- },- };- }-- /** A company by its `linkedin.com/company/<slug>` handle. Takes `name`. */- async company(slug: string): Promise<Result<LinkedInCompany>> {- const result = await this.get<RawCompany>(- "/api/v1/companies/company/info",- { name: slug },- );-- if (result.outcome !== "found") return result;-- const data = result.data;-- return {- outcome: "found",- data: {- id: text(data.id),- name: text(data.name),- universalName: text(data.universalName),- tagline: text(data.tagline),- description: text(data.description),- linkedinUrl: text(data.linkedinUrl),- },- };- }-- /**- * One call.- *- * LinkDAPI answers a failed lookup with `200 { success: false }` rather than- * a status code, so the envelope has to be read rather than the response.- */- private async get<T>(- path: string,- params: Record<string, string>,- ): Promise<Result<T>> {- if (!this.apiKey) return { outcome: "failed", reason: "No RAPIDAPI_KEY." };-- const url = new URL(`https://${HOST}${path}`);- for (const [key, value] of Object.entries(params)) {- url.searchParams.set(key, value);- }-- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);-- try {- const response = await fetch(url, {- headers: {- "x-rapidapi-host": HOST,- "x-rapidapi-key": this.apiKey,- },- signal: controller.signal,- });-- if (!response.ok) {- return { outcome: "failed", reason: `HTTP ${response.status}` };- }-- const body = (await response.json()) as {- success?: boolean;- message?: string;- data?: T | null;- };-- if (body.success !== true || !body.data) {- // "no such profile" is an ordinary answer, not a failure to retry.- return { outcome: "missing" };- }-- return { outcome: "found", data: body.data };- } catch (error) {- const aborted = error instanceof Error && error.name === "AbortError";- return {- outcome: "failed",- reason: aborted- ? `Timed out after ${TIMEOUT_MS}ms.`- : error instanceof Error- ? error.message- : String(error),- };- } finally {- clearTimeout(timeout);- }- }-}--type RawProfile = {- fullName?: unknown;- firstName?: unknown;- lastName?: unknown;- headline?: unknown;- location?: unknown;- profilePictureURL?: unknown;- followerCount?: unknown;- connectionsCount?: unknown;- CurrentPositions?: { name?: string; url?: unknown }[] | null;-};--type RawCompany = {- id?: unknown;- name?: unknown;- universalName?: unknown;- tagline?: unknown;- description?: unknown;- linkedinUrl?: unknown;-};--function text(value: unknown): string | null {- return typeof value === "string" && value.trim() ? value.trim() : null;-}--function num(value: unknown): number | null {- return typeof value === "number" && Number.isFinite(value) ? value : null;-}diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.tsindex 71720d7b..6eb3cfb7 100644--- a/apps/api/src/generated/server.ts+++ b/apps/api/src/generated/server.ts@@ -15,7 +15,7 @@ const t = initTRPC.create();const publicProcedure = t.procedure;import { timelineInput, timelineCountsInput, myTasksInput, activityCreateInput, completeInput } from "../activities/activities.contracts";import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, setPrimaryContactInput } from "../companies/companies.contracts";-import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs } from "../contacts/contacts.contracts";+import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs, factDecisionInput } from "../contacts/contacts.contracts";import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput } from "../deals/deals.contracts";import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";@@ -84,7 +84,10 @@ const appRouter = t.router({.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["create"]>>),update: publicProcedure.input(contactUpdateArgs)- .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["update"]>>)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["update"]>>),+ decideFact: publicProcedure+ .input(factDecisionInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["decideFact"]>>)}),dashboard: t.router({summary: publicProcedurediff --git a/apps/api/src/google/calendar-sync.service.ts b/apps/api/src/google/calendar-sync.service.tsindex 2b2c0922..6fa948ba 100644--- a/apps/api/src/google/calendar-sync.service.ts+++ b/apps/api/src/google/calendar-sync.service.ts@@ -6,6 +6,7 @@ import {RecordSource,} from "@crm/db";import { Injectable, Logger } from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";import { ActivityStampService } from "../crm/activity-stamp.service";import { InjectDatabase } from "../database/database.constants";import {@@ -53,6 +54,7 @@ export class CalendarSyncService {private readonly match: GoogleMatchService,private readonly state: SyncStateService,private readonly stamp: ActivityStampService,+ private readonly agent: AgentTriggerService,) {}async sync(row: MailboxSync): Promise<SyncOutcome> {@@ -310,6 +312,7 @@ export class CalendarSyncService {});await this.syncAttendees(record.id, event);+ await this.prepareForMeeting(record.id, start.at);await this.project(record.id, row.userId, {title: event.summary ?? "Meeting",startsAt: start.at,@@ -369,6 +372,42 @@ export class CalendarSyncService {}}+ /**+ * Tells the agent about people we are about to meet and do not know.+ *+ * The most useful thing the calendar knows is that a conversation is+ * *coming*, and nothing in the stack acted on it before. A contact with no+ * background, on a meeting tomorrow, is worth more research than the same+ * contact would be on any other day — and the deadline is real, so it goes+ * to the front of the queue rather than waiting its turn behind a backlog.+ *+ * Only for meetings actually ahead of us: back-filling a year of history+ * would queue research for every meeting that has already happened.+ */+ private async prepareForMeeting(+ eventId: string,+ startsAt: Date,+ ): Promise<void> {+ const soon = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);+ if (startsAt <= new Date() || startsAt > soon) return;++ const attendees = await this.db.calendarAttendee.findMany({+ where: {+ eventId,+ contactId: { not: null },+ // Whoever is taking the meeting is not who needs researching.+ contact: { brief: { is: null } },+ },+ select: { contactId: true },+ });++ for (const attendee of attendees) {+ if (attendee.contactId) {+ await this.agent.meetingSoon(attendee.contactId, startsAt);+ }+ }+ }+/*** The timeline projection: one `Activity` per event, kept current.*diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.tsindex 69fd7a00..34921df2 100644--- a/apps/api/src/google/google-match.service.ts+++ b/apps/api/src/google/google-match.service.ts@@ -1,10 +1,10 @@-import { WORKSPACE_DOMAINS } from "@crm/auth/workspace";+import { workspaceDomains } from "@crm/auth/workspace";import { type Db, RecordSource } from "@crm/db";import { Injectable, Logger } from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";+import { CompanyDirectoryService } from "../companies/company-directory.service";import { EnrichmentLogService } from "../crm/enrichment-log.service";import { InjectDatabase } from "../database/database.constants";-import { ContactEnrichmentService } from "../enrichment/contact-enrichment.service";-import { EnrichmentService } from "../enrichment/enrichment.service";import {dominantDomain,externalParticipants,@@ -74,8 +74,8 @@ export class GoogleMatchService {constructor(@InjectDatabase() private readonly db: Db,- private readonly enrichment: EnrichmentService,- private readonly contacts: ContactEnrichmentService,+ private readonly companies: CompanyDirectoryService,+ private readonly agent: AgentTriggerService,private readonly log: EnrichmentLogService,) {}@@ -103,7 +103,7 @@ export class GoogleMatchService {// User table happens to contain. Sign-in is restricted to these, so they// are internal by definition — and this holds on an empty database, and// for colleagues who have never signed in and so are not users yet.- const domains = new Set<string>(WORKSPACE_DOMAINS);+ const domains = new Set<string>(workspaceDomains());for (const user of users) {const email = user.email.toLowerCase();@@ -206,10 +206,10 @@ export class GoogleMatchService {/*** Creates the company and the contact behind a domain we have never seen.*- * The company comes from `EnrichmentService.companyForEmail`, which already- * normalises the domain, upserts against the unique index and queues the- * brand lookup — so an auto-created company arrives with a logo and an- * industry a few seconds later, exactly like one typed by a rep.+ * The company comes from `CompanyDirectoryService.companyForEmail`, which+ * normalises the domain, upserts against the unique index and tells the+ * agent a bare company exists — so an auto-created company arrives with a+ * logo and an industry a few seconds later, exactly like one typed by a rep.*/private async create(external: Participant[],@@ -222,12 +222,12 @@ export class GoogleMatchService {if (!lead) return { companyId: null, contactId: null, external };- const companyId = await this.enrichment.companyForEmail(lead.email, {+ const companyId = await this.companies.companyForEmail(lead.email, {ownerId: request.ownerId,});if (!companyId) {- // Enrichment declined — no API key, or the domain resolves to nothing.- // Not an error, and not a reason to invent a bare company row.+ // Not a work domain, so there is nothing to file this against. Not an+ // error, and not a reason to invent a company row.return { companyId: null, contactId: null, external };}@@ -328,11 +328,14 @@ export class GoogleMatchService {return contact.id;}- // Still only known by their address. Queue a sourced lookup — it fills the- // name in behind a poll, exactly like company enrichment, and does nothing- // if the web cannot confirm who they are.+ // Still only known by their address. Tell the agent; whether that is worth+ // a lookup, and how deep a one, is its call — this side no longer knows+ // what a sourced identity match costs or how it works.if (isPlaceholder && !hasRealName) {- this.contacts.enqueue(contact.id);+ await this.agent.contactCreated(+ contact.id,+ "Created by the sync from an address, with no name on it",+ );}return contact.id;diff --git a/apps/api/src/google/google.module.ts b/apps/api/src/google/google.module.tsindex ed40b7eb..44a84b83 100644--- a/apps/api/src/google/google.module.ts+++ b/apps/api/src/google/google.module.ts@@ -1,5 +1,6 @@import { Module } from "@nestjs/common";-import { EnrichmentModule } from "../enrichment/enrichment.module";+import { AgentModule } from "../agent/agent.module";+import { CompaniesModule } from "../companies/companies.module";import { TrpcModule } from "../trpc/trpc.module";import { CalendarClient } from "./calendar.client";import { CalendarSyncService } from "./calendar-sync.service";@@ -18,13 +19,13 @@ import { SyncStateService } from "./sync-state.service";/*** Gmail and Calendar.*- * Depends on `EnrichmentModule` for one thing only: `companyForEmail`, which- * already turns a work address into a found-or-created, enrichment-queued- * company. Auto-creation reusing it is what makes an auto-created company- * arrive with a logo rather than as a bare domain.+ * Depends on `CompaniesModule` for `companyForEmail` — turning a work address+ * into a found-or-created company — and on `AgentModule` to say that a contact+ * arrived with nothing but an address. Neither of those is enrichment: this+ * module reports what the sync saw and lets the agent decide what it means.*/@Module({- imports: [TrpcModule, EnrichmentModule],+ imports: [TrpcModule, AgentModule, CompaniesModule],controllers: [SyncController],providers: [GoogleApiClient,diff --git a/apps/api/test/auth.e2e.spec.ts b/apps/api/test/auth.e2e.spec.tsindex f3d483b6..3b76990f 100644--- a/apps/api/test/auth.e2e.spec.ts+++ b/apps/api/test/auth.e2e.spec.ts@@ -20,7 +20,8 @@ fallback("postgresql://postgres:postgres@localhost:5432/crm?schema=public",);fallback("BETTER_AUTH_SECRET", "test-secret-at-least-32-characters-long");-fallback("BETTER_AUTH_URL", "http://localhost:3001");+fallback("API_URL", "http://localhost:3001");+fallback("ALLOWED_SIGN_IN", "example.com");fallback("GOOGLE_CLIENT_ID", "test-google-client-id");fallback("GOOGLE_CLIENT_SECRET", "test-google-client-secret");diff --git a/apps/api/test/domain.spec.ts b/apps/api/test/domain.spec.tsnew file mode 100644index 00000000..47b91f59--- /dev/null+++ b/apps/api/test/domain.spec.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "bun:test";+import { domainFromEmail, normalizeDomain } from "../src/companies/domain";++/**+ * Domain parsing stayed on this side when enrichment left.+ *+ * It is not enrichment: turning " [email protected] " into `stripe.com` is+ * how the CRM decides which company row an address belongs to, and that+ * question has an answer without asking anybody anything.+ */++describe("normalizeDomain", () => {+ it("reduces anything a human might type to the bare host", () => {+ for (const input of [+ "stripe.com",+ "STRIPE.com",+ " stripe.com ",+ "www.stripe.com",+ "https://stripe.com",+ "https://www.Stripe.com/pricing?ref=x",+ "http://stripe.com/",+ ]) {+ expect(normalizeDomain(input)).toBe("stripe.com");+ }+ });++ it("rejects things that are not hostnames", () => {+ for (const input of [+ "",+ " ",+ "localhost",+ "my company",+ "not a domain",+ ]) {+ expect(normalizeDomain(input)).toBeNull();+ }+ expect(normalizeDomain(null)).toBeNull();+ expect(normalizeDomain(undefined)).toBeNull();+ });+});++describe("domainFromEmail", () => {+ it("takes the domain off a work address", () => {+ expect(domainFromEmail("[email protected]")).toBe("stripe.com");+ expect(domainFromEmail(" [email protected] ")).toBe("stripe.com");+ });++ it("ignores free and malformed addresses", () => {+ // Creating a "Gmail" company from a personal address is the classic+ // CRM junk row.+ for (const email of [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "@stripe.com",+ "not-an-email",+ "",+ ]) {+ expect(domainFromEmail(email)).toBeNull();+ }+ });+});diff --git a/apps/api/test/enrichment.integration.spec.ts b/apps/api/test/enrichment.integration.spec.tsdeleted file mode 100644index 7ca0f1a9..00000000--- a/apps/api/test/enrichment.integration.spec.ts+++ /dev/null@@ -1,406 +0,0 @@-import { afterAll, beforeAll, describe, expect, it } from "bun:test";--/**- * The enrichment pipeline end to end, against a stub Context.dev.- *- * The SDK reads `CONTEXT_DEV_BASE_URL` from the environment, so pointing it at- * a local server needs no production code — everything below is the real- * client, the real queue, the real mapping and the real database. What it does- * *not* prove is that Context.dev's live payloads match the documented schema;- * only a real key does that.- *- * Set before importing anything that constructs the client.- */-const stubResponses: Record<string, () => Response> = {};-const requests: { path: string; body: unknown }[] = [];--const server = Bun.serve({- port: 0,- fetch: async (request) => {- const path = new URL(request.url).pathname;- const body = await request.json().catch(() => null);- requests.push({ path, body });-- const key = routeKey(path, body);- const handler = stubResponses[key] ?? stubResponses[path];-- return (- handler?.() ?? Response.json({ error_code: "NOT_FOUND" }, { status: 400 })- );- },-});--/** Brand lookups all share one path, so the discriminator picks the case. */-function routeKey(path: string, body: unknown): string {- const identifier =- body && typeof body === "object"- ? ((body as Record<string, unknown>).domain ??- (body as Record<string, unknown>).email)- : undefined;- return typeof identifier === "string" ? `${path}:${identifier}` : path;-}--process.env.CONTEXT_DEV_API_KEY = "ctxt_test_key";-process.env.CONTEXT_DEV_BASE_URL = `http://localhost:${server.port}/v1`;-process.env.DATABASE_URL ??=- "postgresql://postgres:postgres@localhost:5432/crm?schema=public";--const { db } = await import("@crm/db");-const { ContextDevClient } = await import(- "../src/enrichment/context-dev.client"-);-const { EnrichmentQueue } = await import("../src/enrichment/enrichment.queue");-const { ActivityStampService } = await import(- "../src/crm/activity-stamp.service"-);-const { EnrichmentLogService } = await import(- "../src/crm/enrichment-log.service"-);-const { EnrichmentService } = await import(- "../src/enrichment/enrichment.service"-);--/** The real queue, with the five-second backoff wound down. */-class FastQueue extends EnrichmentQueue {- protected override get retryDelayMs(): number {- return 5;- }-}--/** `ConfigService`, as much of it as the client uses. */-const config = {- get: (key: string) => process.env[key],-} as never;--const STRIPE_BRAND = {- status: "ok",- code: 200,- brand: {- domain: "enrich-test.example",- title: "Enrich Test",- description: "Payments infrastructure for the internet.",- slogan: "Ignored — description wins.",- email: "[email protected]",- phone: "+1 888 555 0100",- colors: [{ hex: "#635bff", name: "Meteor Shower" }],- logos: [- { url: "https://cdn/dark.svg", mode: "dark", type: "logo" },- { url: "https://cdn/light.svg", mode: "light", type: "logo" },- { url: "https://cdn/icon.svg", mode: "light", type: "icon" },- ],- socials: [- { type: "linkedin", url: "https://linkedin.com/company/enrich-test" },- { type: "x", url: "https://x.com/enrichtest" },- ],- address: {- city: "South San Francisco",- state_code: "CA",- country: "United States",- country_code: "US",- },- industries: {- eic: [{ industry: "Finance", subindustry: "Payments & Money Movement" }],- },- links: { pricing: "https://enrich-test.example/pricing" },- },-};--const TEST_DOMAINS = [- "enrich-test.example",- "enrich-missing.example",- "enrich-broken.example",- "enrich-email.example",- "enrich-research.example",-];--let service: InstanceType<typeof EnrichmentService>;-let userId: string;--beforeAll(async () => {- const client = new ContextDevClient(config);- service = new EnrichmentService(- db,- client,- new FastQueue(),- new ActivityStampService(db),- new EnrichmentLogService(db, new ActivityStampService(db)),- );-- const user = await db.user.upsert({- where: { email: "enrichment-test@localhost" },- create: {- id: "enrichment-test-user",- email: "enrichment-test@localhost",- name: "Enrichment Test",- emailVerified: true,- updatedAt: new Date(),- },- update: {},- select: { id: true },- });- userId = user.id;-- stubResponses["/v1/utility/prefetch"] = () => Response.json({ status: "ok" });- stubResponses["/v1/brand/retrieve:enrich-test.example"] = () =>- Response.json(STRIPE_BRAND);- stubResponses["/v1/brand/retrieve:enrich-missing.example"] = () =>- Response.json({ error_code: "NOT_FOUND" }, { status: 400 });- stubResponses["/v1/brand/retrieve:enrich-broken.example"] = () =>- Response.json({ error_code: "RATE_LIMITED" }, { status: 429 });- stubResponses["/v1/brand/retrieve:[email protected]"] = () =>- Response.json({- status: "ok",- code: 200,- brand: { domain: "enrich-email.example", title: "Enrich Email Co" },- });- stubResponses["/v1/brand/retrieve:[email protected]"] = () =>- Response.json({ error_code: "FREE_EMAIL_DETECTED" }, { status: 422 });- stubResponses["/v1/web/extract"] = () =>- Response.json({- data: {- positioning: "Sells payments infrastructure to developers.",- pricingModel: "Usage-based, per transaction.",- notableCustomers: ["Amazon", "Shopify"],- recentNews: ["Raised a Series H."],- },- urls_analyzed: ["https://enrich-research.example"],- });-});--afterAll(async () => {- await db.activity.deleteMany({ where: { createdById: userId } });- await db.company.deleteMany({ where: { domain: { in: TEST_DOMAINS } } });- await db.user.deleteMany({ where: { id: userId } });- await db.$disconnect();- server.stop(true);-});--async function makeCompany(- domain: string | null,- overrides: Record<string, unknown> = {},-) {- return db.company.create({- data: {- name: (overrides.name as string | undefined) ?? "Placeholder",- domain,- ...overrides,- },- select: { id: true },- });-}--describe("enrichment against a stub Context.dev", () => {- it("fills a company in and keeps the raw payload", async () => {- const { id } = await makeCompany("enrich-test.example", {- name: "enrich-test.example",- // A value a human typed. The agent must not touch it.- city: "London",- });-- expect(service.enqueueCompany(id)).toBe(true);- await service.drain();-- const company = await db.company.findUniqueOrThrow({- where: { id },- select: {- name: true,- description: true,- logoUrl: true,- logoDarkUrl: true,- iconUrl: true,- brandColor: true,- industry: true,- subIndustry: true,- city: true,- country: true,- phone: true,- linkedinUrl: true,- twitterUrl: true,- pricingUrl: true,- enrichmentStatus: true,- enrichedAt: true,- enrichmentError: true,- enrichment: { select: { raw: true, source: true } },- },- });-- expect(company.enrichmentStatus).toBe("COMPLETE");- expect(company.enrichmentError).toBeNull();- expect(company.enrichedAt).not.toBeNull();-- // The name was the domain, so the lookup is allowed to replace it.- expect(company.name).toBe("Enrich Test");- expect(company.description).toBe(- "Payments infrastructure for the internet.",- );- // Logos by mode and type, not logos[0].- expect(company.logoUrl).toBe("https://cdn/light.svg");- expect(company.logoDarkUrl).toBe("https://cdn/dark.svg");- expect(company.iconUrl).toBe("https://cdn/icon.svg");- expect(company.brandColor).toBe("#635bff");- expect(company.industry).toBe("Finance");- expect(company.subIndustry).toBe("Payments & Money Movement");- expect(company.country).toBe("United States");- expect(company.phone).toBe("+1 888 555 0100");- expect(company.linkedinUrl).toBe(- "https://linkedin.com/company/enrich-test",- );- expect(company.twitterUrl).toBe("https://x.com/enrichtest");- expect(company.pricingUrl).toBe("https://enrich-test.example/pricing");-- // The one field a human had already set.- expect(company.city).toBe("London");-- // The whole payload is kept so re-deriving a field costs no credits.- expect(company.enrichment?.source).toBe("context.dev");- expect(- (company.enrichment?.raw as { brand?: { title?: string } })?.brand?.title,- ).toBe("Enrich Test");- });-- it("warms the cache before looking a domain up", () => {- // Prefetch is free and turns a cold 7s lookup into a warm one.- const paths = requests.map((request) => request.path);- expect(paths).toContain("/v1/utility/prefetch");- expect(paths.indexOf("/v1/utility/prefetch")).toBeLessThan(- paths.indexOf("/v1/brand/retrieve"),- );- });-- it("records an unknown domain as SKIPPED, not FAILED", async () => {- const { id } = await makeCompany("enrich-missing.example");-- service.enqueueCompany(id);- await service.drain();-- const company = await db.company.findUniqueOrThrow({- where: { id },- select: { enrichmentStatus: true, enrichmentError: true },- });-- // Nothing to find is a settled answer, and it is not billed — so it is- // not an error message to put in front of a rep.- expect(company.enrichmentStatus).toBe("SKIPPED");- expect(company.enrichmentError).toBeNull();- });-- it("records a rate limit as FAILED, with the reason", async () => {- const { id } = await makeCompany("enrich-broken.example");-- service.enqueueCompany(id);- await service.drain();-- const company = await db.company.findUniqueOrThrow({- where: { id },- select: { enrichmentStatus: true, enrichmentError: true },- });-- expect(company.enrichmentStatus).toBe("FAILED");- expect(company.enrichmentError).toContain("429");- });-- it("skips a company with no domain without calling out at all", async () => {- const { id } = await makeCompany(null, { name: "No Domain Co" });- const before = requests.length;-- service.enqueueCompany(id);- await service.drain();-- const company = await db.company.findUniqueOrThrow({- where: { id },- select: { enrichmentStatus: true },- });-- expect(company.enrichmentStatus).toBe("SKIPPED");- expect(requests.length).toBe(before);-- await db.company.delete({ where: { id } });- });-- it("refuses to queue the same company twice", async () => {- const { id } = await makeCompany("enrich-test.example-dupe" as string);-- expect(service.enqueueCompany(id)).toBe(true);- // A rep leaning on Re-enrich should not spend ten credits on one lookup.- expect(service.enqueueCompany(id)).toBe(false);-- await service.drain();- await db.company.delete({ where: { id } });- });-- describe("companyForEmail", () => {- it("creates the company behind a work address", async () => {- const companyId = await service.companyForEmail(- "[email protected]",- );- expect(companyId).not.toBeNull();-- const company = await db.company.findUniqueOrThrow({- where: { domain: "enrich-email.example" },- select: { name: true, website: true },- });- expect(company.name).toBe("Enrich Email Co");- expect(company.website).toBe("https://enrich-email.example");-- await service.drain();- });-- it("returns the company we already have rather than looking again", async () => {- const before = requests.length;- const companyId = await service.companyForEmail(- "[email protected]",- );-- expect(companyId).not.toBeNull();- // Already known: no second lookup, no second ten credits.- expect(requests.length).toBe(before);- });-- it("ignores a personal address", async () => {- expect(await service.companyForEmail("[email protected]")).toBeNull();- // Rejected on the free-domain list before any call is made.- expect(- requests.some((request) =>- JSON.stringify(request.body).includes("gmail.com"),- ),- ).toBe(false);- });- });-- it("posts a research brief to the company timeline", async () => {- const { id } = await makeCompany("enrich-research.example", {- name: "Research Co",- website: "https://enrich-research.example",- });-- const result = await service.researchCompany(id, userId);- expect(result.ok).toBe(true);-- const activity = await db.activity.findFirstOrThrow({- where: { companyId: id, type: "ENRICHMENT" },- select: { subject: true, body: true, meta: true, occurredAt: true },- });-- expect(activity.subject).toBe("Research brief — Research Co");- // Rendered as prose, because a timeline entry is read rather than parsed.- expect(activity.body).toContain(- "Sells payments infrastructure to developers.",- );- expect(activity.body).toContain("Pricing: Usage-based, per transaction.");- expect(activity.body).toContain("Customers: Amazon, Shopify");- expect(activity.body).toContain("• Raised a Series H.");- expect(activity.occurredAt).not.toBeNull();- expect((activity.meta as { creditCost?: number })?.creditCost).toBe(10);- });-- it("reports a company with no website rather than guessing a URL", async () => {- const { id } = await makeCompany(null, { name: "Websiteless" });-- const result = await service.researchCompany(id, userId);-- expect(result.ok).toBe(false);- expect(result.ok === false && result.reason).toContain("no website");-- await db.company.delete({ where: { id } });- });-});diff --git a/apps/api/test/enrichment.spec.ts b/apps/api/test/enrichment.spec.tsdeleted file mode 100644index 07a9e2c3..00000000--- a/apps/api/test/enrichment.spec.ts+++ /dev/null@@ -1,350 +0,0 @@-import { describe, expect, it } from "bun:test";-import { domainFromEmail, normalizeDomain } from "../src/companies/domain";-import {- brandToUpdate,- type CompanySnapshot,-} from "../src/enrichment/brand-mapping";-import type { Brand } from "../src/enrichment/context-dev.client";-import { EnrichmentQueue } from "../src/enrichment/enrichment.queue";--/** A company with nothing filled in — every gap open. */-function emptyCompany(- overrides: Partial<CompanySnapshot> = {},-): CompanySnapshot {- return {- name: "Stripe",- nameIsPlaceholder: false,- description: null,- logoUrl: null,- logoDarkUrl: null,- iconUrl: null,- iconDarkUrl: null,- iconTone: null,- brandColor: null,- industry: null,- subIndustry: null,- city: null,- stateCode: null,- country: null,- countryCode: null,- phone: null,- email: null,- linkedinUrl: null,- twitterUrl: null,- githubUrl: null,- pricingUrl: null,- careersUrl: null,- ...overrides,- };-}--describe("normalizeDomain", () => {- it("reduces anything a human might type to the bare host", () => {- for (const input of [- "stripe.com",- "STRIPE.com",- " stripe.com ",- "www.stripe.com",- "https://stripe.com",- "https://www.Stripe.com/pricing?ref=x",- "http://stripe.com/",- ]) {- expect(normalizeDomain(input)).toBe("stripe.com");- }- });-- it("rejects things that are not hostnames", () => {- for (const input of [- "",- " ",- "localhost",- "my company",- "not a domain",- ]) {- expect(normalizeDomain(input)).toBeNull();- }- expect(normalizeDomain(null)).toBeNull();- expect(normalizeDomain(undefined)).toBeNull();- });-});--describe("domainFromEmail", () => {- it("takes the domain off a work address", () => {- expect(domainFromEmail("[email protected]")).toBe("stripe.com");- expect(domainFromEmail(" [email protected] ")).toBe("stripe.com");- });-- it("ignores free and malformed addresses", () => {- // Creating a "Gmail" company from a personal address is the classic- // CRM junk row.- for (const email of [- "[email protected]",- "[email protected]",- "[email protected]",- "@stripe.com",- "not-an-email",- "",- ]) {- expect(domainFromEmail(email)).toBeNull();- }- });-});--describe("brandToUpdate", () => {- const brand: Brand = {- title: "Stripe",- description: "Payments infrastructure for the internet.",- phone: "+1 888 963 8955",- email: "[email protected]",- colors: [{ hex: "#635bff", name: "Meteor Shower" }],- logos: [- { url: "https://cdn/dark-logo.svg", mode: "dark", type: "logo" },- { url: "https://cdn/light-logo.svg", mode: "light", type: "logo" },- {- url: "https://cdn/icon.svg",- mode: "has_opaque_background",- type: "icon",- },- ],- socials: [- { type: "x", url: "https://x.com/stripe" },- { type: "linkedin", url: "https://linkedin.com/company/stripe" },- { type: "github", url: "https://github.com/stripe" },- ],- address: {- city: "South San Francisco",- state_code: "CA",- country: "United States",- country_code: "US",- },- industries: {- eic: [{ industry: "Finance", subindustry: "Payments & Money Movement" }],- },- links: {- pricing: "https://stripe.com/pricing",- careers: "https://stripe.com/jobs",- },- };-- it("picks logos by mode and type rather than taking the first", () => {- const update = brandToUpdate(brand, emptyCompany());-- expect(update.logoUrl).toBe("https://cdn/light-logo.svg");- expect(update.logoDarkUrl).toBe("https://cdn/dark-logo.svg");- expect(update.iconUrl).toBe("https://cdn/icon.svg");- });-- it("maps the rest of the brand onto company fields", () => {- const update = brandToUpdate(brand, emptyCompany());-- expect(update).toMatchObject({- description: "Payments infrastructure for the internet.",- brandColor: "#635bff",- industry: "Finance",- subIndustry: "Payments & Money Movement",- city: "South San Francisco",- stateCode: "CA",- country: "United States",- countryCode: "US",- phone: "+1 888 963 8955",- email: "[email protected]",- linkedinUrl: "https://linkedin.com/company/stripe",- twitterUrl: "https://x.com/stripe",- githubUrl: "https://github.com/stripe",- pricingUrl: "https://stripe.com/pricing",- careersUrl: "https://stripe.com/jobs",- });- });-- it("never overwrites a value a human already set", () => {- const update = brandToUpdate(- brand,- emptyCompany({- description: "Our biggest account — handle with care.",- city: "London",- phone: "+44 20 7946 0000",- }),- );-- expect(update.description).toBeUndefined();- expect(update.city).toBeUndefined();- expect(update.phone).toBeUndefined();- // The gaps are still filled.- expect(update.country).toBe("United States");- });-- it("leaves the name alone unless it is the domain placeholder", () => {- expect(- brandToUpdate(brand, emptyCompany({ name: "Stripe Inc" })).name,- ).toBeUndefined();-- expect(- brandToUpdate(- brand,- emptyCompany({ name: "stripe.com", nameIsPlaceholder: true }),- ).name,- ).toBe("Stripe");- });-- it("writes nothing when the lookup found nothing", () => {- // Every field on a brand is nullable, so the all-null case is real.- expect(brandToUpdate({}, emptyCompany())).toEqual({});- });-- it("falls back to the slogan when there is no description", () => {- const update = brandToUpdate(- { slogan: "Payments, simplified." },- emptyCompany(),- );- expect(update.description).toBe("Payments, simplified.");- });-});--/** The real queue, with the five-second backoff wound down. */-class FastQueue extends EnrichmentQueue {- protected override get retryDelayMs(): number {- return 5;- }-}--describe("EnrichmentQueue", () => {- it("runs at most two jobs at once", async () => {- const queue = new EnrichmentQueue();- let running = 0;- let peak = 0;-- const job = async () => {- running += 1;- peak = Math.max(peak, running);- await new Promise((resolve) => setTimeout(resolve, 20));- running -= 1;- };-- for (let index = 0; index < 6; index++) {- queue.enqueue(`job-${index}`, job);- }- await queue.drain();-- expect(peak).toBe(2);- });-- it("refuses a key that is already queued", () => {- const queue = new EnrichmentQueue();- const job = () => new Promise<void>((resolve) => setTimeout(resolve, 50));-- expect(queue.enqueue("company:1", job)).toBe(true);- // A rep leaning on "Re-enrich" should not spend ten credits on one lookup.- expect(queue.enqueue("company:1", job)).toBe(false);- expect(queue.enqueue("company:2", job)).toBe(true);- });-- it("retries a job that throws, once", async () => {- const queue = new FastQueue();- let attempts = 0;-- queue.enqueue("flaky", async () => {- attempts += 1;- if (attempts === 1) throw new Error("cold cache timeout");- });- await queue.drain();-- expect(attempts).toBe(2);- });-- it("gives up after the retry rather than looping", async () => {- const queue = new FastQueue();- let attempts = 0;-- queue.enqueue("broken", async () => {- attempts += 1;- throw new Error("still broken");- });- await queue.drain();-- expect(attempts).toBe(2);- });-- it("drops queued work on shutdown instead of racing the database", async () => {- const queue = new EnrichmentQueue();- let ran = 0;- const slow = async () => {- ran += 1;- await new Promise((resolve) => setTimeout(resolve, 30));- };-- for (let index = 0; index < 5; index++) {- queue.enqueue(`job-${index}`, slow);- }- queue.onApplicationShutdown();- await queue.drain();-- // The two already in flight finish; the rest are dropped and stay PENDING.- expect(ran).toBe(2);- expect(queue.enqueue("after-shutdown", slow)).toBe(false);- });-});--/**- * How a logo is made visible in both themes.- *- * The rule is deliberately narrow because the fix downstream is a CSS invert,- * and inverting anything that is not near-greyscale changes the brand's colour- * rather than its visibility.- */-describe("brandToUpdate — icon tone", () => {- const withIcon = (mode: string, hex?: string): Brand => ({- logos: [- {- url: "https://cdn/icon.png",- mode,- type: "icon",- ...(hex ? { colors: [{ hex, name: "x" }] } : {}),- },- ],- });-- it("marks a near-black icon dark, so it can be lifted in dark mode", () => {- // Architect: the case that started this — #040404 on transparency, which- // is simply not there on a dark row.- expect(- brandToUpdate(withIcon("light", "#040404"), emptyCompany()).iconTone,- ).toBe("dark");- });-- it("marks a near-white icon light", () => {- expect(- brandToUpdate(withIcon("light", "#fbfbfb"), emptyCompany()).iconTone,- ).toBe("light");- });-- it("leaves an icon with its own background alone", () => {- expect(- brandToUpdate(- withIcon("has_opaque_background", "#ff5c35"),- emptyCompany(),- ).iconTone,- ).toBe("opaque");- });-- it("never tones a coloured logo, however dark or light it reads", () => {- // Inverting Monzo's coral makes it teal — a wrong-coloured logo is worse- // than a dim one, so saturation vetoes the whole mechanism.- for (const hex of ["#ff4f40", "#635bff", "#00d47e", "#ffcc00"]) {- expect(- brandToUpdate(withIcon("light", hex), emptyCompany()).iconTone,- ).toBe(undefined);- }- });-- it("leaves mid-grey alone — it is legible against either theme", () => {- expect(- brandToUpdate(withIcon("light", "#808080"), emptyCompany()).iconTone,- ).toBe(undefined);- });-- it("does nothing without colour data", () => {- expect(brandToUpdate(withIcon("light"), emptyCompany()).iconTone).toBe(- undefined,- );- });-});diff --git a/apps/api/test/workspace.spec.ts b/apps/api/test/workspace.spec.tsindex 51a31604..f9a32b3f 100644--- a/apps/api/test/workspace.spec.ts+++ b/apps/api/test/workspace.spec.ts@@ -1,14 +1,20 @@-import { describe, expect, it } from "bun:test";+import { beforeEach, describe, expect, it } from "bun:test";import { isWorkspaceEmail } from "@crm/auth/workspace";import { externalParticipants } from "../src/google/participants";+// The allow-list is read from the environment on demand, so a test sets it the+// same way a deployment does. Nothing here depends on whose CRM this is.+beforeEach(() => {+ process.env.ALLOWED_SIGN_IN = "acme.com";+});+describe("isWorkspaceEmail", () => {it("admits our people", () => {for (const email of [- "[email protected]",- "[email protected]",- " [email protected] ",- "[email protected]",+ "[email protected]",+ "[email protected]",+ " [email protected] ",+ "[email protected]",]) {expect(isWorkspaceEmail(email)).toBe(true);}@@ -28,23 +34,48 @@ describe("isWorkspaceEmail", () => {it("is not fooled by a lookalike domain", () => {// The boundary is a dot, not a substring — otherwise anyone could- // register trycomp.ai.evil.com and walk into an internal CRM.+ // register acme.com.evil.com and walk into a private CRM.for (const email of [- "[email protected]",- "[email protected]",- "[email protected]",- "[email protected][email protected]".replace("?", ""),+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected][email protected]".replace("?", ""),]) {expect(isWorkspaceEmail(email)).toBe(false);}});++ it("fails closed when nothing is allowed", () => {+ // An unset list must admit nobody. The alternative — treating "no list"+ // as "anyone" — is a CRM full of customer data behind a sign-in that+ // accepts every Google account on earth.+ process.env.ALLOWED_SIGN_IN = "";+ expect(isWorkspaceEmail("[email protected]")).toBe(false);+ });++ it("admits a single address, for a one-person install", () => {+ // A solo self-hoster on a consumer mailbox has no domain to name, and+ // listing `gmail.com` would be an open door.+ process.env.ALLOWED_SIGN_IN = "[email protected]";++ expect(isWorkspaceEmail("[email protected]")).toBe(true);+ expect(isWorkspaceEmail("[email protected]")).toBe(false);+ });++ it("mixes a domain with individual outsiders", () => {+ process.env.ALLOWED_SIGN_IN = "acme.com, [email protected]";++ expect(isWorkspaceEmail("[email protected]")).toBe(true);+ expect(isWorkspaceEmail("[email protected]")).toBe(true);+ expect(isWorkspaceEmail("[email protected]")).toBe(false);+ });});describe("internal addresses never become leads", () => {// Empty sets: proves the workspace domain is excluded on its own, not// because a colleague happens to be a CRM user yet.const options = {- ourDomains: new Set(["trycomp.ai"]),+ ourDomains: new Set(["acme.com"]),ourAddresses: new Set<string>(),suppressedDomains: new Set<string>(),};@@ -52,14 +83,14 @@ describe("internal addresses never become leads", () => {it("drops colleagues even when they are not users", () => {const result = externalParticipants([- { email: "[email protected]", name: "Lewis" },- { email: "[email protected]", name: "New Starter" },- { email: "[email protected]", name: "Jane" },+ { email: "[email protected]", name: "Lewis" },+ { email: "[email protected]", name: "New Starter" },+ { email: "[email protected]", name: "Jane" },],options,);- expect(result.map((person) => person.email)).toEqual(["[email protected]"]);+ expect(result.map((person) => person.email)).toEqual(["[email protected]"]);});it("stores nothing for a wholly internal thread", () => {@@ -68,8 +99,8 @@ describe("internal addresses never become leads", () => {expect(externalParticipants([- { email: "[email protected]", name: null },- { email: "[email protected]", name: null },+ { email: "[email protected]", name: null },+ { email: "[email protected]", name: null },],options,),diff --git a/apps/app/app/(auth)/grant-access/grant-access.tsx b/apps/app/app/(auth)/grant-access/grant-access.tsxindex 63378ad0..a6e81bac 100644--- a/apps/app/app/(auth)/grant-access/grant-access.tsx+++ b/apps/app/app/(auth)/grant-access/grant-access.tsx@@ -16,7 +16,7 @@ export function GrantAccess() {// Absolute, like the sign-in button: the API owns /api/auth/*, so a// relative URL would resolve against the API's origin rather than this- // app's. Better Auth checks it against AUTH_TRUSTED_ORIGINS.+ // app's. Better Auth checks it against the origins in APP_URL.const origin = window.location.origin;// `linkSocial` rather than `signIn.social`: there is already a session anddiff --git a/apps/app/app/(auth)/sign-in/google-sign-in.tsx b/apps/app/app/(auth)/sign-in/google-sign-in.tsxindex 780bef0e..8bf24c0c 100644--- a/apps/app/app/(auth)/sign-in/google-sign-in.tsx+++ b/apps/app/app/(auth)/sign-in/google-sign-in.tsx@@ -15,7 +15,7 @@ export function GoogleSignIn() {// The API owns /api/auth/*, so both URLs have to be absolute — a relative// one would resolve against the API's origin, not this app's. Better Auth- // checks them against AUTH_TRUSTED_ORIGINS.+ // checks them against the origins in APP_URL.const origin = window.location.origin;const { error } = await signIn.social({diff --git a/apps/app/app/eve/v1/[...path]/route.ts b/apps/app/app/eve/v1/[...path]/route.tsnew file mode 100644index 00000000..f1ab89e9--- /dev/null+++ b/apps/app/app/eve/v1/[...path]/route.ts@@ -0,0 +1,129 @@+import {+ AGENT_URL,+ bridgeConfigured,+ mintBridgeToken,+} from "@/lib/agent-bridge";+import { getSession } from "@/lib/session";++/**+ * Same-origin passthrough to the research agent.+ *+ * Mounted at `/eve/v1/*` on purpose: that is where `useEveAgent()` looks by+ * default, so the panel needs no host configuration and the browser never+ * discovers that the agent is a separate deployment.+ *+ * Unlike the API proxy beside it, this one is an **enforcement point** rather+ * than a passthrough. The agent never sees the session cookie — it gets a+ * two-minute token minted here — so if this route did not check the session,+ * nothing downstream would. Every request is authenticated before it is+ * forwarded, and an unauthenticated one is refused rather than passed on.+ */++/** Streaming, and per-request session reads. Never cache any of it. */+export const dynamic = "force-dynamic";++async function handler(request: Request): Promise<Response> {+ if (!bridgeConfigured()) {+ return Response.json(+ { error: "The research agent is not configured for this install." },+ { status: 503 },+ );+ }++ const session = await getSession();+ if (!session) {+ return Response.json({ error: "Not signed in." }, { status: 401 });+ }++ const url = new URL(request.url);+ const target = `${AGENT_URL}${url.pathname}${url.search}`;++ const headers = new Headers(request.headers);++ // Hop-by-hop and origin-describing headers belong to the browser→app hop,+ // not this one. `cookie` goes too: the agent has no use for a session it+ // cannot read, and forwarding credentials to a service that does not need+ // them is how they end up in somebody's log.+ for (const header of [+ "host",+ "cookie",+ "x-forwarded-host",+ "x-forwarded-proto",+ "x-forwarded-for",+ "forwarded",+ "transfer-encoding",+ "connection",+ "keep-alive",+ "content-length",+ "expect",+ ]) {+ headers.delete(header);+ }++ headers.set(+ "authorization",+ `Bearer ${await mintBridgeToken({+ id: session.user.id,+ email: session.user.email,+ name: session.user.name,+ })}`,+ );++ const init: RequestInit & { duplex?: "half" } = {+ method: request.method,+ headers,+ redirect: "manual",+ // The event stream is long-lived and the client aborts it on unmount;+ // without this the upstream request outlives the reader.+ signal: request.signal,+ };++ if (request.method !== "GET" && request.method !== "HEAD") {+ init.body = request.body;+ init.duplex = "half";+ }++ let upstream: Response;+ try {+ upstream = await fetch(target, init);+ } catch (error) {+ // The agent being down is an ordinary condition for the rest of the CRM,+ // so it reads as one rather than a 500 with a stack trace in it.+ return Response.json(+ {+ error: "The research agent is not reachable.",+ detail: error instanceof Error ? error.message : String(error),+ },+ { status: 502 },+ );+ }++ const responseHeaders = new Headers(upstream.headers);+ for (const header of [+ "transfer-encoding",+ "connection",+ "content-encoding",+ "content-length",+ ]) {+ responseHeaders.delete(header);+ }++ // The whole point of this route is the NDJSON event stream, so the body is+ // piped rather than buffered — reading it to completion first would deliver+ // the agent's reasoning in one lump after the run had already finished.+ return new Response(upstream.body, {+ status: upstream.status,+ statusText: upstream.statusText,+ headers: responseHeaders,+ });+}++export {+ handler as DELETE,+ handler as GET,+ handler as HEAD,+ handler as OPTIONS,+ handler as PATCH,+ handler as POST,+ handler as PUT,+};diff --git a/apps/app/components/crm/agent-panel.tsx b/apps/app/components/crm/agent-panel.tsxnew file mode 100644index 00000000..eb1706a8--- /dev/null+++ b/apps/app/components/crm/agent-panel.tsx@@ -0,0 +1,246 @@+"use client";++import Send from "@carbon/icons-react/es/Send";+import { Button } from "@crm/ui/components/button";+import { Icon } from "@crm/ui/components/icon";+import { Input } from "@crm/ui/components/input";+import { Spinner } from "@crm/ui/components/spinner";+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { type EveMessage, type EveMessagePart, useEveAgent } from "eve/react";+import { useState } from "react";++/**+ * The agent, on the record, while it works.+ *+ * The thing neither HubSpot nor Salesforce puts in front of a rep: not a+ * chatbot in a corner, but *this* agent working on *this* person, with its+ * steps visible and its questions answerable. Watching it reject+ * `github.com/lewis` because the account is named Lewis Delicata is what makes+ * the fields it did fill in believable.+ *+ * It talks to `/eve/v1/*` on this origin, which the app proxies to the agent+ * after checking the session — so the hook needs no host, no key, and no+ * knowledge that the agent is a separate deployment.+ */+export function AgentPanel({+ contactId,+ contactName,+}: {+ contactId: string;+ contactName: string;+}) {+ const agent = useEveAgent();+ const [draft, setDraft] = useState("");++ const busy = agent.status === "submitted" || agent.status === "streaming";+ const steps = agent.data.messages.flatMap(toSteps);+ const question = pendingQuestion(agent.data.messages);++ const ask = (message: string) => {+ if (!message.trim() || busy) return;+ setDraft("");+ void agent.send({+ // The agent has no idea which record the rep is looking at, so the+ // question carries it. Everything else it needs it can read.+ message: `About contact ${contactId} (${contactName}): ${message.trim()}`,+ });+ };++ return (+ <div className="space-y-3">+ {steps.length === 0 && !busy ? (+ <p className="text-muted-foreground text-sm/6">+ Nothing running. Ask a question and you will see each step it takes —+ including the leads it throws away.+ </p>+ ) : null}++ {steps.length > 0 ? (+ <ol className="space-y-1.5">+ {steps.map((step) => (+ <li key={step.id} className="flex items-start gap-2 text-sm">+ <StatusIndicator+ tone={step.tone}+ busy={step.pending}+ label={step.label}+ />+ </li>+ ))}+ </ol>+ ) : null}++ {agent.error ? (+ <p className="text-destructive text-sm">{agent.error.message}</p>+ ) : null}++ {/*+ * The agent's own question, answered in place. This is the case the+ * whole panel earns its keep on: four Bighams work at HubSpot, and the+ * person looking at the record knows which one.+ */}+ {question ? (+ <div className="space-y-2 border p-3">+ <p className="text-sm">{question.prompt}</p>+ {/*+ * `options` is optional: a freeform question has none, and the+ * composer below is how that one gets answered.+ */}+ <div className="flex flex-wrap gap-2">+ {(question.options ?? []).map((option) => (+ <Button+ key={option.id}+ variant="outline"+ size="sm"+ onClick={() =>+ void agent.send({+ inputResponses: [+ {+ requestId: question.requestId,+ optionId: option.id,+ },+ ],+ })+ }+ >+ {option.label}+ </Button>+ ))}+ </div>+ </div>+ ) : null}++ <form+ className="flex items-center gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ ask(draft);+ }}+ >+ <Input+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ placeholder="Is he still at Fleetio?"+ disabled={busy}+ />+ <Button type="submit" size="icon-sm" variant="outline" disabled={busy}>+ {busy ? <Spinner /> : <Icon icon={Send} />}+ <span className="sr-only">Ask</span>+ </Button>+ </form>+ </div>+ );+}++type Step = {+ id: string;+ label: string;+ tone: "neutral" | "success" | "warning" | "info";+ pending: boolean;+};++/**+ * The wire events, as a list a rep can read.+ *+ * Tool calls become steps and assistant prose becomes a step, because the+ * useful reading of a research run is "what did it do", not "what did it say".+ * A tool that returned `written: false` is rendered as a *warning*, not hidden:+ * the refusals are the most trust-building thing on the page.+ */+function toSteps(message: EveMessage): Step[] {+ return message.parts.flatMap((part, index) => {+ const id = `${message.id}:${index}`;++ if (part.type === "text" && message.role === "assistant") {+ const text = part.text.trim();+ return text+ ? [{ id, label: text, tone: "neutral" as const, pending: false }]+ : [];+ }++ if (part.type.startsWith("tool-") || part.type === "dynamic-tool") {+ const tool = toolName(part);+ const state = "state" in part ? part.state : undefined;+ const pending =+ state === "input-streaming" || state === "input-available";++ return [+ {+ id,+ label: describe(tool, part),+ tone: outcomeTone(part),+ pending,+ },+ ];+ }++ return [];+ });+}++function toolName(part: EveMessagePart): string {+ if (part.type === "dynamic-tool" && "toolName" in part) {+ return String(part.toolName);+ }+ return part.type.replace(/^tool-/, "");+}++/** Tool slugs are for the model; this line is for a person. */+const VERBS: Record<string, string> = {+ read_crm_history: "Read our emails and meetings with them",+ resolve_linkedin_profile: "Searched for their LinkedIn profile",+ get_linkedin_profile: "Read a LinkedIn profile",+ get_contact_work_history: "Read their work history",+ find_contact_socials: "Searched for their other profiles",+ set_contact_socials: "Checked a profile against the account itself",+ identify_contact: "Put a name to the address",+ record_fact: "Recorded what it found",+ write_brief: "Wrote the background",+ research_person: "Researched them on the web",+ research_company: "Read the company's site",+ enrich_company: "Looked up the company",+ schedule_recheck: "Decided when to look again",+ record_job_change: "Raised a job change",+ list_outstanding_work: "Looked for outstanding work",+};++function describe(tool: string, part: EveMessagePart): string {+ const verb = VERBS[tool] ?? tool.replace(/_/g, " ");+ const output =+ "output" in part ? (part.output as Record<string, unknown>) : null;++ // The reason a write did not happen is the interesting half.+ const reason =+ output && typeof output.reason === "string" ? output.reason : null;+ return reason ? `${verb} — ${reason}` : verb;+}++function outcomeTone(part: EveMessagePart): Step["tone"] {+ if ("state" in part && part.state === "output-error") return "warning";++ const output =+ "output" in part ? (part.output as Record<string, unknown>) : null;+ if (!output) return "info";++ if (output.applied === true || output.written === true) return "success";+ if (output.stored === false || output.written === false) return "warning";++ return "info";+}++/**+ * A question the agent is parked on, if there is one.+ *+ * Only the latest message is inspected: an older request has either been+ * answered or superseded, and re-rendering a stale prompt invites somebody to+ * answer a question nobody is waiting on.+ */+function pendingQuestion(messages: readonly EveMessage[]) {+ for (const part of messages.at(-1)?.parts ?? []) {+ if (part.type !== "dynamic-tool") continue;++ const request = part.toolMetadata?.eve?.inputRequest;+ if (request) return request;+ }++ return null;+}diff --git a/apps/app/components/crm/facts.tsx b/apps/app/components/crm/facts.tsxnew file mode 100644index 00000000..eede71db--- /dev/null+++ b/apps/app/components/crm/facts.tsx@@ -0,0 +1,98 @@+"use client";++import { Provenance } from "@crm/ui/components/sourced-value";+import { Suggestion } from "@crm/ui/components/suggestion";+import { useMutation } from "@tanstack/react-query";+import { toast } from "sonner";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";+import type { RouterOutputs } from "@/lib/trpc/types";++type Contact = RouterOutputs["contacts"]["byId"];+export type Fact = Contact["facts"][number];++const dateFormat = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ year: "numeric",+});++/**+ * The facts on a record, split the way the sheet renders them.+ *+ * `applied` decorates the value already in the field; `proposed` sits under an+ * empty one. Nothing else is returned, because dismissed and superseded facts+ * are history and the timeline is where history goes.+ */+export function factsByField(facts: Fact[]) {+ const applied = new Map<string, Fact>();+ const proposed = new Map<string, Fact>();++ for (const fact of facts) {+ const bucket = fact.status === "APPLIED" ? applied : proposed;+ // Ordered newest-first by the API, so the first one wins.+ if (!bucket.has(fact.field)) bucket.set(fact.field, fact);+ }++ return { applied, proposed };+}++/**+ * The tooltip body for a value the agent wrote.+ *+ * A field a person typed has no fact behind it and gets nothing — which is the+ * distinction the underline is *for*. Decorating everything would make it mean+ * nothing.+ */+export function provenanceFor(fact: Fact) {+ return (+ <Provenance+ claim={fact.value}+ reasons={fact.evidence.map((item) => item.detail)}+ observedAt={dateFormat.format(new Date(fact.observedAt))}+ sourceUrl={fact.sourceUrl}+ />+ );+}++/**+ * A proposal, and the two buttons that settle it.+ *+ * Accepting is the most valuable click in the product: it fills a field *and*+ * labels a training example for the confidence model, from the one person who+ * actually knows the answer.+ */+export function FactSuggestion({+ fact,+ contactId,+}: {+ fact: Fact;+ contactId: string;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();++ const decide = useMutation(+ trpc.contacts.decideFact.mutationOptions({+ onSuccess: (result) => {+ toast.success(+ result.applied+ ? "Added to the record."+ : "Dismissed — it won't be suggested again.",+ );+ return cache.contact(contactId, { settle: "record" });+ },+ onError: (error) => toast.error(error.message),+ }),+ );++ return (+ <Suggestion+ value={fact.value}+ rationale={fact.evidence.map((item) => item.detail).join(" · ")}+ pending={decide.isPending}+ onAccept={() => decide.mutate({ factId: fact.id, decision: "accept" })}+ onDismiss={() => decide.mutate({ factId: fact.id, decision: "dismiss" })}+ />+ );+}diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsxindex eab65606..9c1786bc 100644--- a/apps/app/components/crm/inline-field.tsx+++ b/apps/app/components/crm/inline-field.tsx@@ -10,7 +10,9 @@ import {SelectTrigger,SelectValue,} from "@crm/ui/components/select";+import { SOURCED_VALUE, SourcedValue } from "@crm/ui/components/sourced-value";import { Spinner } from "@crm/ui/components/spinner";+import { cn } from "@crm/ui/lib/utils";import { useId, useState } from "react";/** Label column, so every property in the sheet lines up on one edge. */@@ -54,6 +56,8 @@ export function InlineField({placeholder,type = "text",render,+ provenance,+ suggestion,}: {label: string;value: string | null;@@ -63,6 +67,20 @@ export function InlineField({type?: "text" | "url" | "email" | "tel";/** How the saved value reads when not being edited — a link, usually. */render?: (value: string) => React.ReactNode;+ /**+ * Where this value came from, when a machine put it there.+ *+ * Left off, the field looks exactly as it always did — which is the right+ * default for the ones a person typed, and the only reason the underline+ * means anything on the ones they did not.+ */+ provenance?: React.ReactNode;+ /**+ * Something the agent believes but is not sure enough to write. Rendered+ * *under* the field, never inside it: a suggestion that looks like a value+ * is a lie with a nice font.+ */+ suggestion?: React.ReactNode;}) {const id = useId();const [editing, setEditing] = useState(false);@@ -79,12 +97,10 @@ export function InlineField({// of a round trip — which looks like the edit was thrown away.const shown = saving ? draft.trim() : (value ?? "");- return (- <div className={ROW}>- <label htmlFor={id} className={LABEL}>- {label}- </label>+ const sourced = Boolean(provenance) && !editing && shown !== "";+ const control = (+ <>{editing ? (<Inputid={id}@@ -119,7 +135,9 @@ export function InlineField({>{saving ? <Spinner /> : null}{shown ? (- <span className="truncate">{render ? render(shown) : shown}</span>+ <span className={cn("truncate", sourced && SOURCED_VALUE)}>+ {render ? render(shown) : shown}+ </span>) : (<span className="truncate text-muted-foreground">{placeholder ?? <EmptyCellValue />}@@ -127,6 +145,42 @@ export function InlineField({)}</Button>)}+ </>+ );++ // The tooltip goes on the control the row already has, rather than a new+ // wrapper: pointing at a value explains it, tabbing to it does the same, and+ // nothing extra becomes clickable.+ const body =+ sourced && provenance ? (+ <SourcedValue source={provenance}>{control}</SourcedValue>+ ) : (+ control+ );++ if (!suggestion) {+ return (+ <div className={ROW}>+ <label htmlFor={id} className={LABEL}>+ {label}+ </label>+ {body}+ </div>+ );+ }++ // A suggestion belongs to its field, so it sits under it in the value+ // column rather than becoming a row of its own that a reader has to+ // associate back to something.+ return (+ <div className={cn(ROW, "items-start")}>+ <label htmlFor={id} className={cn(LABEL, "pt-2")}>+ {label}+ </label>+ <div className="min-w-0">+ {body}+ {suggestion}+ </div></div>);}diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 6e9d814a..ecee3791 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -22,10 +22,6 @@ import {import { formatMoney } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";-import {- CompanySocials,- hasCompanyLinks,-} from "@/components/crm/company-socials";import { OPEN_STAGES } from "@/components/crm/deal-stage";import { EnrichmentActions } from "@/components/crm/enrichment-actions";import {@@ -39,6 +35,7 @@ import {savingField,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";+import { CompanySocials, hasCompanyLinks } from "@/components/crm/social-links";import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import {diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 2862c075..e53ecba7 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -16,13 +16,25 @@ import { TableCell } from "@crm/ui/components/table";import { initialsFromName } from "@crm/ui/lib/format";import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";+import { AgentPanel } from "@/components/crm/agent-panel";import { contactName } from "@/components/crm/contact-name";+import {+ ENRICHMENT_POLL_MS,+ EnrichmentIndicator,+ isEnriching,+} from "@/components/crm/enrichment-status";+import {+ FactSuggestion,+ factsByField,+ provenanceFor,+} from "@/components/crm/facts";import {InlineField,InlineSelectField,savingField,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";+import { ContactSocials, hasContactLinks } from "@/components/crm/social-links";import { DealStageMenu } from "@/components/crm/stage-change";import { Timeline } from "@/components/crm/timeline/timeline";import {@@ -44,6 +56,12 @@ type Contact = RouterOutputs["contacts"]["byId"];const NONE = "none";+const dateFormat = new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ year: "numeric",+});+const DEAL_COLUMNS = [{ header: "Deal", width: "w-[32%]", className: "pl-5" },{ header: "Role", width: "w-[16%]" },@@ -57,7 +75,17 @@ export function ContactSheet({ contactId }: { contactId: string }) {const cache = useCrmCache();const { tab, setTab } = useRecordSheetView("overview");- const query = useQuery(trpc.contacts.byId.queryOptions({ id: contactId }));+ // Polls while the agent is working, for the same reason the company sheet+ // does: enrichment is a background write with no client action behind it, so+ // there is nothing to invalidate and the only way to notice it finished is+ // to ask. Stops the moment it settles.+ const query = useQuery({+ ...trpc.contacts.byId.queryOptions({ id: contactId }),+ refetchInterval: (current) => {+ const status = current.state.data?.enrichmentStatus;+ return status && isEnriching(status) ? ENRICHMENT_POLL_MS : false;+ },+ });const contact = query.data;const setPrimary = useMutation(@@ -88,6 +116,23 @@ export function ContactSheet({ contactId }: { contactId: string }) {label: "Activity",content: <Timeline anchor={{ contactId: contact.id }} />,},+ {+ value: "agent",+ label: "Agent",+ // A tab rather than a band on the overview: the panel opens a+ // durable session the moment it mounts, and a rep flicking through+ // records should not start one on every contact they glance at.+ content: (+ <DetailSheetBody>+ <DetailSheetSection title="Ask the agent">+ <AgentPanel+ contactId={contact.id}+ contactName={contactName(contact)}+ />+ </DetailSheetSection>+ </DetailSheetBody>+ ),+ },]: [];@@ -101,12 +146,25 @@ export function ContactSheet({ contactId }: { contactId: string }) {<MetaLine parts={[contact.title, contact.company?.name]} />) : undefined}+ // Only when there is something to say. "Enriched" is the resting state+ // of every contact in here, and a row that says so on all of them is a+ // row nobody reads — which means nobody reads it when it says "failed".note={- contact?.isPrimaryContact ? (- <StatusIndicator- tone="success"- label={`Primary contact at ${contact.company?.name ?? "this company"}`}- />+ contact ? (+ <>+ {contact.isPrimaryContact ? (+ <StatusIndicator+ tone="success"+ label={`Primary contact at ${contact.company?.name ?? "this company"}`}+ />+ ) : null}+ {contact.enrichmentStatus !== "COMPLETE" ? (+ <EnrichmentIndicator+ status={contact.enrichmentStatus}+ title={contact.enrichmentError}+ />+ ) : null}+ </>) : null}// A person, so initials rather than a logo — there are no avatars in@@ -229,6 +287,20 @@ function ContactOverview({ contact }: { contact: Contact }) {const users = useQuery(trpc.users.list.queryOptions());const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));+ const { applied, proposed } = factsByField(contact.facts);++ /** Everything a field needs to show where it came from and what is pending. */+ const agentProps = (field: string) => {+ const fact = applied.get(field);+ const suggestion = proposed.get(field);+ return {+ provenance: fact ? provenanceFor(fact) : undefined,+ suggestion: suggestion ? (+ <FactSuggestion fact={suggestion} contactId={contact.id} />+ ) : undefined,+ };+ };+const update = useMutation(trpc.contacts.update.mutationOptions({// `settle: "record"` — the row's spinner should last until the new value@@ -266,6 +338,7 @@ function ContactOverview({ contact }: { contact: Contact }) {placeholder="Head of Security"saving={isSaving("title")}onSave={(title) => save({ title })}+ {...agentProps("title")}/><InlineFieldlabel="Email"@@ -287,6 +360,30 @@ function ContactOverview({ contact }: { contact: Contact }) {type="url"saving={isSaving("linkedinUrl")}onSave={(linkedinUrl) => save({ linkedinUrl })}+ {...agentProps("linkedinUrl")}+ />+ {/*+ * No placeholders on these two. An empty inline field renders its+ * placeholder as the value, so an example handle reads as this+ * person's account rather than as a hint — and a plausible wrong+ * link on every contact is exactly the failure the rest of this+ * agent is built to avoid.+ */}+ <InlineField+ label="X"+ value={contact.twitterUrl}+ type="url"+ saving={isSaving("twitterUrl")}+ onSave={(twitterUrl) => save({ twitterUrl })}+ {...agentProps("twitterUrl")}+ />+ <InlineField+ label="GitHub"+ value={contact.githubUrl}+ type="url"+ saving={isSaving("githubUrl")}+ onSave={(githubUrl) => save({ githubUrl })}+ {...agentProps("githubUrl")}/><InlineSelectFieldlabel="Company"@@ -318,10 +415,185 @@ function ContactOverview({ contact }: { contact: Contact }) {/></DetailSheetProperties></DetailSheetSection>++ {contact.brief ? <Background brief={contact.brief} /> : null}++ <WeKnowThem+ relationship={contact.relationship}+ contactName={contactName(contact)}+ />++ {hasContactLinks(contact) ? (+ <DetailSheetSection title="Links">+ <ContactSocials contact={contact} />+ </DetailSheetSection>+ ) : null}</DetailSheetBody>);}+/**+ * Who this person is, above the fields that describe them.+ *+ * The prose and the lines under it do different jobs and are stored separately+ * for that reason: the narrative is what a rep reads on the way into a call,+ * the lines are what they scan for one number — how long have they been there.+ *+ * Everything here was written by the agent, so the whole section is sourced+ * once at the top rather than field by field. Repeating a dotted underline on+ * six consecutive agent-written lines would decorate the section, not inform+ * anyone.+ */+function Background({ brief }: { brief: NonNullable<Contact["brief"]> }) {+ const sections = brief.sections;+ const lines = [+ { label: "Current role", value: sections.currentRole },+ { label: "Tenure", value: sections.tenure },+ { label: "Previously", value: sections.previousRoles?.join(" · ") },+ { label: "Seniority", value: sections.seniority },+ { label: "Function", value: sections.function },+ { label: "Based", value: sections.location },+ ].filter((line) => Boolean(line.value));++ return (+ <DetailSheetSection+ title="Background"+ action={+ <span className="text-muted-foreground text-xs">+ {brief.sourceUrl ? (+ <a+ href={brief.sourceUrl}+ target="_blank"+ rel="noreferrer noopener"+ className="underline-offset-2 hover:underline"+ >+ Source+ </a>+ ) : null}+ {brief.sourceUrl ? " · " : null}+ {dateFormat.format(new Date(brief.refreshedAt))}+ </span>+ }+ >+ <p className="text-pretty text-muted-foreground text-sm/6">+ {brief.narrative}+ </p>++ {lines.length > 0 ? (+ <DetailSheetProperties>+ {lines.map((line) => (+ <div+ key={line.label}+ className="grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-2 py-0.5"+ >+ <span className="truncate text-muted-foreground text-xs">+ {line.label}+ </span>+ <span className="min-w-0 text-sm">{line.value}</span>+ </div>+ ))}+ </DetailSheetProperties>+ ) : null}+ </DetailSheetSection>+ );+}++const relativeFormat = new Intl.RelativeTimeFormat(undefined, {+ numeric: "auto",+});++function daysAgo(iso: string): string {+ const days = Math.round(+ (Date.now() - new Date(iso).getTime()) / (1000 * 60 * 60 * 24),+ );+ return relativeFormat.format(-days, "day");+}++/**+ * What we have actually said to each other.+ *+ * The block no CRM that buys its data can render. Everything above it could be+ * purchased from a vendor; this is ours, and it is the part a rep checks last+ * before dialling — have they ever replied, when, and who else do we know+ * there.+ *+ * "Never replied" is stated rather than omitted. Twelve emails into silence is+ * a fact about the relationship, and a panel that shows only the twelve reads+ * like progress.+ */+function WeKnowThem({+ relationship,+ contactName: name,+}: {+ relationship: Contact["relationship"];+ contactName: string;+}) {+ const { emails, meetings, lastReplyAt, nextMeeting, colleagues } =+ relationship;++ if (emails === 0 && meetings === 0 && colleagues.length === 0) return null;++ const first = name.split(" ")[0] ?? name;++ const summary = [+ emails > 0 ? `${emails} email${emails === 1 ? "" : "s"}` : null,+ emails > 0+ ? lastReplyAt+ ? `last reply ${daysAgo(lastReplyAt)}`+ : `${first} has never replied`+ : null,+ meetings > 0 ? `${meetings} meeting${meetings === 1 ? "" : "s"}` : null,+ ].filter(Boolean);++ return (+ <DetailSheetSection title="We know them">+ {summary.length > 0 ? (+ <p className="text-muted-foreground text-sm/6">{summary.join(" · ")}</p>+ ) : null}++ {nextMeeting ? (+ <p className="text-sm">+ <span className="text-muted-foreground">Next </span>+ {nextMeeting.title ?? "Meeting"}+ <span className="text-muted-foreground">+ {" · "}+ {dateFormat.format(new Date(nextMeeting.startsAt))}+ </span>+ </p>+ ) : null}++ {colleagues.length > 0 ? <Colleagues colleagues={colleagues} /> : null}+ </DetailSheetSection>+ );+}++function Colleagues({+ colleagues,+}: {+ colleagues: Contact["relationship"]["colleagues"];+}) {+ const openRecord = useOpenRecord();++ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">+ <span className="text-muted-foreground text-xs">Also here</span>+ {colleagues.map((colleague) => (+ <button+ key={colleague.id}+ type="button"+ onClick={() => openRecord({ kind: "contact", id: colleague.id })}+ className="min-w-0 truncate underline-offset-2 hover:underline"+ >+ {colleague.name}+ {colleague.title ? (+ <span className="text-muted-foreground"> ({colleague.title})</span>+ ) : null}+ </button>+ ))}+ </div>+ );+}+function ContactDeals({ contact }: { contact: Contact }) {const openRecord = useOpenRecord();diff --git a/apps/app/components/crm/company-socials.tsx b/apps/app/components/crm/social-links.tsxsimilarity index 55%rename from apps/app/components/crm/company-socials.tsxrename to apps/app/components/crm/social-links.tsxindex 5e17bbab..81e0d905 100644--- a/apps/app/components/crm/company-socials.tsx+++ b/apps/app/components/crm/social-links.tsx@@ -7,6 +7,8 @@ import { Button } from "@crm/ui/components/button";import type { CarbonIcon } from "@crm/ui/components/icon";import { Icon } from "@crm/ui/components/icon";+type Link<T> = { key: keyof T; label: string; icon: CarbonIcon };+export type CompanyLinks = {linkedinUrl: string | null;twitterUrl: string | null;@@ -15,12 +17,18 @@ export type CompanyLinks = {careersUrl: string | null;};+export type ContactLinks = {+ linkedinUrl: string | null;+ twitterUrl: string | null;+ githubUrl: string | null;+};+/*** The website is not in this list — it is the domain in the sheet header,* which is a link, because that is what a domain should be. What is left are* the places the agent found this company that its name does not give you.*/-const LINKS: { key: keyof CompanyLinks; label: string; icon: CarbonIcon }[] = [+const COMPANY_LINKS: Link<CompanyLinks>[] = [{ key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },{ key: "twitterUrl", label: "X", icon: LogoX },{ key: "githubUrl", label: "GitHub", icon: LogoGithub },@@ -28,8 +36,31 @@ const LINKS: { key: keyof CompanyLinks; label: string; icon: CarbonIcon }[] = [{ key: "careersUrl", label: "Careers", icon: UserMultiple },];+/**+ * The same row for a person, minus the two that only a company has.+ *+ * Email and phone are not here either: they are in the stats strip at the top+ * of the sheet, where the answer to "how do I reach them" belongs.+ */+const CONTACT_LINKS: Link<ContactLinks>[] = [+ { key: "linkedinUrl", label: "LinkedIn", icon: LogoLinkedin },+ { key: "twitterUrl", label: "X", icon: LogoX },+ { key: "githubUrl", label: "GitHub", icon: LogoGithub },+];++function present<T>(record: T, links: Link<T>[]) {+ return links.flatMap((link) => {+ const href = record[link.key];+ return typeof href === "string" && href ? [{ ...link, href }] : [];+ });+}+export function hasCompanyLinks(company: CompanyLinks): boolean {- return LINKS.some((link) => company[link.key] !== null);+ return present(company, COMPANY_LINKS).length > 0;+}++export function hasContactLinks(contact: ContactLinks): boolean {+ return present(contact, CONTACT_LINKS).length > 0;}/**@@ -40,18 +71,15 @@ export function hasCompanyLinks(company: CompanyLinks): boolean {* out half legible and reads as clip art. Labels cost one line and remove the* guessing.*/-export function CompanySocials({ company }: { company: CompanyLinks }) {- const present = LINKS.flatMap((link) => {- const href = company[link.key];- return href ? [{ ...link, href }] : [];- });+function SocialLinks<T>({ record, links }: { record: T; links: Link<T>[] }) {+ const rows = present(record, links);- if (present.length === 0) return null;+ if (rows.length === 0) return null;return (<div className="flex flex-wrap items-center gap-2">- {present.map((link) => (- <Button key={link.key} asChild variant="outline" size="sm">+ {rows.map((link) => (+ <Button key={String(link.key)} asChild variant="outline" size="sm"><a href={link.href} target="_blank" rel="noreferrer noopener"><Icon icon={link.icon} data-icon="inline-start" />{link.label}@@ -61,3 +89,11 @@ export function CompanySocials({ company }: { company: CompanyLinks }) {</div>);}++export function CompanySocials({ company }: { company: CompanyLinks }) {+ return <SocialLinks record={company} links={COMPANY_LINKS} />;+}++export function ContactSocials({ contact }: { contact: ContactLinks }) {+ return <SocialLinks record={contact} links={CONTACT_LINKS} />;+}diff --git a/apps/app/lib/agent-bridge.ts b/apps/app/lib/agent-bridge.tsnew file mode 100644index 00000000..d533cd7f--- /dev/null+++ b/apps/app/lib/agent-bridge.ts@@ -0,0 +1,107 @@+/**+ * How a signed-in rep reaches the research agent.+ *+ * Server-side only, and structurally so: the secret is read from+ * `AGENT_BRIDGE_SECRET` at call time, and Next only inlines `NEXT_PUBLIC_*`+ * into the browser bundle. Imported from a client component this would find+ * `undefined` and throw rather than ship the secret — which is why the guard is+ * the variable's name rather than a `server-only` import that a test runner+ * resolves differently.+ *+ * The agent is its own deployment on its own origin, and the browser never+ * talks to it. Instead the app proxies `/eve/v1/*` from its own origin+ * (`app/eve/v1/[...path]/route.ts`) and mints a short-lived token naming the+ * person who is signed in.+ *+ * Three problems that solves at once:+ *+ * - **No CORS and no cross-site cookie.** Same trade the app already makes for+ * the API: a same-origin path means the session cookie just works, and we+ * never scope an auth cookie to a third host.+ * - **The agent learns *who* is asking**, not merely that the app is asking. A+ * shared service credential would make every rep look like the deployment,+ * and `lib/approval.ts` on the other side decides what to do based on whether+ * a person is present.+ * - **The blast radius is a minute.** The agent can read every email in the+ * CRM; a long-lived token in a browser tab is not a thing to hand out.+ *+ * HS256 rather than something asymmetric because both halves are ours and+ * deploy together. `AGENT_BRIDGE_SECRET` is the only new configuration, and it+ * is required on both sides for the panel to work at all.+ */++/** Must match `apps/agent/agent/channels/eve.ts`. */+const ISSUER = "crm-app";+const AUDIENCE = "crm-agent";++/** Long enough for a slow request, short enough not to be worth stealing. */+const TTL_SECONDS = 120;++export const AGENT_URL = process.env.AGENT_URL ?? "http://localhost:2000";++export function bridgeConfigured(): boolean {+ return Boolean(process.env.AGENT_BRIDGE_SECRET);+}++/**+ * A bearer token for one rep, valid for two minutes.+ *+ * Hand-rolled rather than pulling in a JWT library: this signs one fixed claim+ * set with one algorithm, and `crypto.subtle` does HMAC. A dependency here+ * would be more surface than code.+ */+export async function mintBridgeToken(user: {+ id: string;+ email: string;+ name: string;+}): Promise<string> {+ const secret = process.env.AGENT_BRIDGE_SECRET;+ if (!secret) throw new Error("AGENT_BRIDGE_SECRET is not set.");++ const now = Math.floor(Date.now() / 1000);++ const header = { alg: "HS256", typ: "JWT" };+ const payload = {+ iss: ISSUER,+ aud: AUDIENCE,+ sub: user.id,+ email: user.email,+ name: user.name,+ iat: now,+ // `nbf` a little in the past: the agent allows clock skew, but there is no+ // reason to hand it a token that is not valid yet.+ nbf: now - 5,+ exp: now + TTL_SECONDS,+ };++ const signingInput = `${base64url(JSON.stringify(header))}.${base64url(+ JSON.stringify(payload),+ )}`;++ const key = await crypto.subtle.importKey(+ "raw",+ new TextEncoder().encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );++ const signature = await crypto.subtle.sign(+ "HMAC",+ key,+ new TextEncoder().encode(signingInput),+ );++ return `${signingInput}.${base64url(new Uint8Array(signature))}`;+}++function base64url(input: string | Uint8Array): string {+ const bytes =+ typeof input === "string" ? new TextEncoder().encode(input) : input;+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary)+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+}diff --git a/apps/app/next.config.ts b/apps/app/next.config.tsindex f9a7859d..162c7712 100644--- a/apps/app/next.config.ts+++ b/apps/app/next.config.ts@@ -1,6 +1,29 @@+import { loadRootEnv } from "@crm/env";import type { NextConfig } from "next";+// Next only looks for `.env` files beside the app. The one in this repo is at+// the workspace root, so it is read here — before `env` below is evaluated.+loadRootEnv();++/**+ * The API origin, published to the browser.+ *+ * Self-hosters set `API_URL` once and both sides of the app agree: the server+ * components fetching tRPC and the browser sending someone to sign in. This+ * used to be two separate `NEXT_PUBLIC_*` variables that had to hold the same+ * value, which is one variable more than there are origins.+ *+ * `env` rather than a runtime read, because `NEXT_PUBLIC_*` is inlined at build+ * time and a value that only exists in the root `.env` would otherwise be+ * `undefined` in the bundle.+ */+const apiUrl = process.env.API_URL ?? "http://localhost:3001";+const nextConfig: NextConfig = {+ env: {+ NEXT_PUBLIC_API_URL: apiUrl,+ },+// The @crm/* packages are just-in-time: they ship TypeScript sources, so// Next has to compile them rather than treat them as prebuilt dependencies.transpilePackages: ["@crm/auth", "@crm/db", "@crm/ui"],diff --git a/apps/app/package.json b/apps/app/package.jsonindex 076c47b4..3f5cc6dc 100644--- a/apps/app/package.json+++ b/apps/app/package.json@@ -7,12 +7,14 @@"build": "next build","start": "next start","check-types": "tsc --noEmit",+ "test": "bun test","lint": "biome check ."},"dependencies": {"@carbon/icons-react": "^11.82.0","@crm/auth": "workspace:*","@crm/db": "workspace:*",+ "@crm/env": "workspace:*","@crm/ui": "workspace:*","@tanstack/react-query": "^5.101.2","@trpc/client": "^11.18.0",@@ -20,6 +22,7 @@"@trpc/tanstack-react-query": "^11.18.0","api": "workspace:*","better-auth": "^1.6.25",+ "eve": "^0.29.4","next": "16.2.12","next-themes": "^0.4.6","nuqs": "^2.8.9",@@ -31,6 +34,7 @@"@crm/typescript-config": "workspace:*","@tailwindcss/postcss": "^4","@tanstack/react-query-devtools": "^5.101.2",+ "@types/bun": "^1.3.14","@types/node": "^20","@types/react": "^19","@types/react-dom": "^19",diff --git a/apps/app/test/agent-bridge.spec.ts b/apps/app/test/agent-bridge.spec.tsnew file mode 100644index 00000000..53b43448--- /dev/null+++ b/apps/app/test/agent-bridge.spec.ts@@ -0,0 +1,103 @@+import { beforeAll, describe, expect, it } from "bun:test";+import { verifyJwtHmac } from "eve/channels/auth";++/**+ * The token the contact sheet uses to reach the agent.+ *+ * This is the security boundary of the whole panel: the agent can read every+ * email in the CRM, and this token is what says a particular signed-in rep is+ * asking. So the test is a real round trip — minted by the app, verified by+ * eve's own verifier with the same configuration `agent/channels/eve.ts`+ * uses — rather than an assertion about what I believe the format to be.+ */++const SECRET = "test-secret-at-least-long-enough-to-be-a-secret";++/** Must match `apps/agent/agent/channels/eve.ts`. */+const CONFIG = {+ algorithm: "HS256",+ audiences: ["crm-agent"],+ issuer: "crm-app",+ secret: SECRET,+} as const;++let mintBridgeToken: typeof import("../lib/agent-bridge").mintBridgeToken;++beforeAll(async () => {+ process.env.AGENT_BRIDGE_SECRET = SECRET;+ ({ mintBridgeToken } = await import("../lib/agent-bridge"));+});++const rep = {+ id: "user_123",+ email: "[email protected]",+ name: "Lewis Carhart",+};++describe("mintBridgeToken", () => {+ it("mints a token eve accepts", async () => {+ const token = await mintBridgeToken(rep);+ const result = await verifyJwtHmac(token, CONFIG);++ expect(result.ok).toBe(true);+ });++ it("names the rep, so the agent knows a person is driving", async () => {+ // The whole reason this is not a shared service credential: the approval+ // policy on the agent side behaves differently for a person than for the+ // cron principal, and `ask_question` only makes sense when someone is+ // there to answer.+ //+ // The *subject* is the rep. eve's own principal mapping labels an HMAC+ // token as a service and namespaces its id (`crm-app:user_123`), which is+ // the right default for a machine credential and wrong for this — so the+ // agent re-maps it in `repFromCrm`, and `channel-auth.spec.ts` covers that+ // half.+ const token = await mintBridgeToken(rep);+ const result = await verifyJwtHmac(token, CONFIG);++ expect(result.ok && result.sessionAuth.subject).toBe(rep.id);+ expect(result.ok && result.sessionAuth.attributes?.email).toBe(rep.email);+ });++ it("is rejected by a different secret", async () => {+ const token = await mintBridgeToken(rep);+ const result = await verifyJwtHmac(token, {+ ...CONFIG,+ secret: "a-different-secret-entirely",+ });++ expect(result.ok).toBe(false);+ });++ it("is rejected by an agent expecting another audience", async () => {+ const token = await mintBridgeToken(rep);+ const result = await verifyJwtHmac(token, {+ ...CONFIG,+ audiences: ["someone-elses-agent"],+ });++ expect(result.ok).toBe(false);+ });++ it("expires, so a token left in a tab stops working", async () => {+ const token = await mintBridgeToken(rep);+ const [, payload] = token.split(".");+ const claims = JSON.parse(+ Buffer.from(payload as string, "base64url").toString(),+ ) as { exp: number; iat: number };++ const lifetime = claims.exp - claims.iat;+ expect(lifetime).toBeLessThanOrEqual(300);+ expect(lifetime).toBeGreaterThan(30);+ });++ it("refuses to mint without a secret", async () => {+ const secret = process.env.AGENT_BRIDGE_SECRET;+ process.env.AGENT_BRIDGE_SECRET = "";++ expect(mintBridgeToken(rep)).rejects.toThrow();++ process.env.AGENT_BRIDGE_SECRET = secret;+ });+});diff --git a/apps/app/tsconfig.json b/apps/app/tsconfig.jsonindex 6bf93e30..62768cef 100644--- a/apps/app/tsconfig.json+++ b/apps/app/tsconfig.json@@ -6,6 +6,10 @@// into apps/api and meets NestJS's legacy decorators. Nothing in this app// uses a decorator; this is purely so the imported sources parse."experimentalDecorators": true,+ // `bun:test` in `test/`. Additive rather than a replacement: Next's own+ // ambient types come from `next-env.d.ts` and the include list, not from+ // `types`, so naming one package here does not hide them.+ "types": ["bun"],"paths": {"@/*": ["./*"]}diff --git a/apps/app/turbo.json b/apps/app/turbo.jsonindex d75f2a47..4e931705 100644--- a/apps/app/turbo.json+++ b/apps/app/turbo.json@@ -8,6 +8,8 @@"outputs": [".next/**", "!.next/cache/**", "!.next/dev/**"],"env": ["NEXT_PUBLIC_API_URL", "NEXT_PUBLIC_AUTH_URL"],"passThroughEnv": [+ "AGENT_BRIDGE_SECRET",+ "AGENT_URL","AUTH_COOKIE_DOMAIN","AUTH_TRUSTED_ORIGINS","BETTER_AUTH_SECRET",@@ -19,6 +21,8 @@"cache": false,"persistent": true,"passThroughEnv": [+ "AGENT_BRIDGE_SECRET",+ "AGENT_URL","AUTH_COOKIE_DOMAIN","AUTH_TRUSTED_ORIGINS","BETTER_AUTH_SECRET",diff --git a/bun.lock b/bun.lockindex 1121aad7..3e4d1caf 100644--- a/bun.lock+++ b/bun.lock@@ -15,12 +15,16 @@"version": "0.0.1","dependencies": {"@crm/db": "workspace:*",+ "@crm/env": "workspace:*",+ "@vercel/blob": "^2.6.1",+ "context.dev": "^2.7.0","eve": "^0.29.4","zod": "^4.4.3",},"devDependencies": {"@crm/typescript-config": "workspace:*","@types/node": "^24.0.0",+ "microsandbox": "^0.6.8","typescript": "^5.9.2",},},@@ -30,6 +34,7 @@"dependencies": {"@crm/auth": "workspace:*","@crm/db": "workspace:*",+ "@crm/env": "workspace:*","@keyv/redis": "^5.1.6","@nestjs/cache-manager": "^3.1.3","@nestjs/common": "^11.0.1",@@ -69,6 +74,7 @@"@carbon/icons-react": "^11.82.0","@crm/auth": "workspace:*","@crm/db": "workspace:*",+ "@crm/env": "workspace:*","@crm/ui": "workspace:*","@tanstack/react-query": "^5.101.2","@trpc/client": "^11.18.0",@@ -76,6 +82,7 @@"@trpc/tanstack-react-query": "^11.18.0","api": "workspace:*","better-auth": "^1.6.25",+ "eve": "^0.29.4","next": "16.2.12","next-themes": "^0.4.6","nuqs": "^2.8.9",@@ -87,6 +94,7 @@"@crm/typescript-config": "workspace:*","@tailwindcss/postcss": "^4","@tanstack/react-query-devtools": "^5.101.2",+ "@types/bun": "^1.3.14","@types/node": "^20","@types/react": "^19","@types/react-dom": "^19",@@ -99,6 +107,7 @@"version": "0.0.0","dependencies": {"@crm/db": "workspace:*",+ "@crm/env": "workspace:*","better-auth": "^1.6.25",},"devDependencies": {@@ -120,17 +129,26 @@"name": "@crm/db","version": "0.0.0","dependencies": {+ "@crm/env": "workspace:*","@prisma/adapter-pg": "^7.9.1","@prisma/client": "^7.9.1",},"devDependencies": {"@crm/typescript-config": "workspace:*","@types/node": "^24.10.1",- "dotenv": "^17.2.4","prisma": "^7.9.1","typescript": "5.9.2",},},+ "packages/env": {+ "name": "@crm/env",+ "version": "0.0.0",+ "devDependencies": {+ "@crm/typescript-config": "workspace:*",+ "@types/node": "^24.10.1",+ "typescript": "5.9.2",+ },+ },"packages/typescript-config": {"name": "@crm/typescript-config","version": "0.0.0",@@ -311,6 +329,8 @@"@crm/db": ["@crm/db@workspace:packages/db"],+ "@crm/env": ["@crm/env@workspace:packages/env"],+"@crm/typescript-config": ["@crm/typescript-config@workspace:packages/typescript-config"],"@crm/ui": ["@crm/ui@workspace:packages/ui"],@@ -653,6 +673,16 @@"@standard-schema/utils": ["@standard-schema/[email protected]", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],+ "@superradcompany/microsandbox-darwin-arm64": ["@superradcompany/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-SbPo2mb5sEWY7Sry9lxlh762oX5G4RI4Xq2i6U9covTe+4MIFznNSCPIntoCcpzVwt4VNIukvEdyTsI9kITJLw=="],++ "@superradcompany/microsandbox-linux-arm64-gnu": ["@superradcompany/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-cMgS/pE6N2LTbdGYMNiSzfxlsD0F1fhVuCFuIULxGfGyK+zmrYHgTgV0K6n9UQY+PjseOvNn//T7FJQ7SwyJ3g=="],++ "@superradcompany/microsandbox-linux-x64-gnu": ["@superradcompany/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-JCYgBsCf00bX2RA7YhdFdNOQHsWJFXYM3WJi1ONx3jLdUpiMKAVRZxCSPJe/UrFoRiqfj49AmgIBNtvs+2Ns9g=="],++ "@superradcompany/microsandbox-win32-arm64-msvc": ["@superradcompany/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-cWXaHBleVZbTddVYiUSuChNbHWhzTnNkgBqhisSDcFa1FBa0g5sBzTBlcC0RAseMzs4F+6YqLbD040QOe/6deQ=="],++ "@superradcompany/microsandbox-win32-x64-msvc": ["@superradcompany/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Asfn+8+CplKh05MyJIoRJzLCl1Z05B/n6Lc6+tpfFKmHjMkQw976L67AqqBQq4AxfkakBcpZYVHZQqUDxl5Fow=="],+"@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],@@ -1393,6 +1423,8 @@"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],+ "microsandbox": ["[email protected]", "", { "optionalDependencies": { "@superradcompany/microsandbox-darwin-arm64": "0.6.8", "@superradcompany/microsandbox-linux-arm64-gnu": "0.6.8", "@superradcompany/microsandbox-linux-x64-gnu": "0.6.8", "@superradcompany/microsandbox-win32-arm64-msvc": "0.6.8", "@superradcompany/microsandbox-win32-x64-msvc": "0.6.8" }, "bin": { "microsandbox": "bin/microsandbox.cjs", "msb": "bin/microsandbox.cjs" } }, "sha512-N9sqwUFjeRisBJPyu3uV0f+BFsWQmrxogGoZw0jXuLY9+ey0cgPTzQBLhjKyCbe6rq8joGtefvyS3J4vEW7DBQ=="],+"mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],"mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..fa394eed--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,36 @@+# Postgres for local development.+#+# docker compose up -d+#+# The credentials match the DATABASE_URL in .env.example, so a fresh clone+# needs no decisions: start this, copy the env file, migrate, and go. Nothing+# else in the stack is containerised — the API, the app and the agent all run+# from `bun run dev` with hot reload, which is what you want while working on+# them.+#+# This is a development database. It has a trivial password and it publishes a+# port on localhost; do not point production at it.++services:+ postgres:+ image: postgres:17-alpine+ container_name: crm-postgres+ restart: unless-stopped+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: crm+ ports:+ - "5432:5432"+ volumes:+ - crm-postgres:/var/lib/postgresql/data+ healthcheck:+ # `bun run db:deploy` straight after `up -d` would otherwise race the+ # server's first start, which looks like an unreachable database.+ test: ["CMD-SHELL", "pg_isready -U postgres -d crm"]+ interval: 3s+ timeout: 5s+ retries: 20++volumes:+ crm-postgres:diff --git a/docs/agent.md b/docs/agent.mdnew file mode 100644index 00000000..c77dda4d--- /dev/null+++ b/docs/agent.md@@ -0,0 +1,178 @@+# Agent — Rules for working on `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.++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.++## The framework is the source of truth++The complete eve documentation ships inside the package, matching the installed+version exactly:++```+apps/agent/node_modules/eve/docs/README.md+```++Read the relevant guide there before writing eve code. 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).++## 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 Bighams work at HubSpot.++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.++## 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.++## 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.++## 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:++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.++`skills/data-boundaries.md` is the agent's copy of this. Keep them in step.++## The sandbox++`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.++**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.++## The bridge++The contact sheet's **Agent** tab talks to a running agent. The path:++```+browser → /eve/v1/* (same origin, session cookie)+ → 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+ → AGENT_URL/eve/v1/*+ agent/channels/eve.ts → repFromCrm() verifies it+```++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.++### Turning it on++Same value in both processes, from the one root `.env`:++```sh+AGENT_URL="http://localhost:2000" # the default+AGENT_BRIDGE_SECRET="$(openssl rand -base64 32)"+```++Then `bun run dev` (the agent serves on `:2000`) and open any contact.++**If the Agent tab errors:**++| 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 |++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.++### Checking it without a browser++`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:++```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++curl -s -H 'Host: agent.example.com' \+ -H "authorization: Bearer $TOKEN" \+ http://127.0.0.1:2000/eve/v1/info | jq '.tools.available | length'+```++`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.++## 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.diff --git a/docs/api.md b/docs/api.mdindex 30ee741c..0feb7349 100644--- a/docs/api.md+++ b/docs/api.md@@ -38,6 +38,33 @@ they follow `NODE_ENV`: JSON at `log` and above in production, colourised with`PrismaLogBridge`; outside the API (seeds, scripts, the Next.js app) they fallback to the console sink in `packages/db/src/client.ts`.+## 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 are no organizationsThis is an internal tool behind Google sign-in, and it is **single tenant**.diff --git a/docs/environment.md b/docs/environment.mdindex cdfda6c8..12add93d 100644--- a/docs/environment.md+++ b/docs/environment.md@@ -1,109 +1,220 @@# Environment-## Per-app env files, not one root file+## One `.env`, at the root of the repo-There is no root `.env`. Every surface that runs as its own process owns its own file, copied from the `.env.example` sitting next to it:+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.-| File | Loaded by | Used by |-| --- | --- | --- |-| `apps/api/.env` | Bun's automatic `.env` loading, plus `ConfigModule.forRoot()` | the NestJS API |-| `apps/app/.env` | Next.js | the Next.js app; `NEXT_PUBLIC_*` are inlined at build time |-| `packages/db/.env` | `import "dotenv/config"` in `packages/db/prisma.config.ts` | the Prisma CLI — `db:migrate`, `db:push`, `db:studio`, `db:seed` |--`packages/auth/.env.example` documents what `@crm/auth` reads, but there is deliberately no `packages/auth/.env`. The package is a library: it never loads a file, it just reads whatever `process.env` its host process already has. If a var is missing there, fix the API's or the app's `.env` — adding one next to the package would do nothing.--Because each loader reads from its own process's working directory, the API only sees `apps/api/.env` when started from `apps/api` — which is what `bun dev` / `turbo run dev` does. Running `bun src/main.ts` from the repo root silently gets you no env at all.--## Values that must match across files--Three variables are duplicated, and nothing checks that the copies agree:+```sh+cp .env.example .env+```-- **`DATABASE_URL`** — `apps/api/.env`, `apps/app/.env`, `packages/db/.env`. The app reads sessions straight from the database, and Prisma's CLI needs its own copy because it runs outside both apps.-- **`BETTER_AUTH_SECRET`** — `apps/api/.env` and `apps/app/.env`.-- **`BETTER_AUTH_URL`** — `apps/api/.env` and `apps/app/.env`.+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:++| 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++Five 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 |+| `GOOGLE_CLIENT_ID` | Google is the only sign-in method |+| `GOOGLE_CLIENT_SECRET` | |++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.++### `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+```-A mismatched `BETTER_AUTH_SECRET` is the one to watch: the API mints a session cookie the app cannot verify, so `requireSession()` rejects every request and you get an endless bounce back to `/sign-in` with no error anywhere. If sign-in "succeeds" but you land on the sign-in page again, compare the secrets before debugging anything else.+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`.++## 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.+- **`AGENT_URL`** is the research agent, which is its own deployment. Only the+ app reads it, and only server-side: the browser never learns the agent has an+ origin of its own. See [the agent bridge](./agent.md#the-bridge).## Typed, validated env-Only the API validates. Everything else fails later and less clearly, so know which layer you are in:--- **`apps/api/src/config/env.validation.ts`** — the real one. A class-validator `EnvironmentVariables` class run through `ConfigModule.forRoot({ validate: validateEnv })`; it fails fast at boot with a message naming each bad variable. New API config belongs here.-- **`packages/db/src/client.ts`** — throws if `DATABASE_URL` is unset, pointing at `packages/db/.env.example`.-- **`packages/auth/src/env.ts`** — no schema. Plain `process.env` reads through an `optional()` helper, with one rule enforced: `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` must be set together or it throws. Anything else missing just becomes `undefined`.-- **`apps/app/lib/api.ts`** — `process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3001"`. A silent fallback, so a missing var in a deployed app looks like "the API is down" rather than a config error.--### Two sharp edges--**`@crm/auth` reads env at import time.** `packages/auth/src/env.ts` builds its `env` object, and `auth.ts` builds `socialProviders`, while the module is being imported — not on first use. `app.module.ts` imports `@crm/auth` before `ConfigModule.forRoot()` runs, so the vars have to already be in `process.env` by then. Under Bun they are, because Bun loads `.env` before executing anything. Under plain Node or `nest start` they would not be: `@nestjs/config` loads the file *after* that import, so Google sign-in would vanish silently (`socialProviders: {}`) while `validateEnv` still passed, because it reads the same variables a moment later. If the API ever moves off Bun, load the env file explicitly before importing `AppModule`.--**`main.ts` bypasses the validated `PORT`.** It reads `process.env.PORT ?? 3001` directly, so the `@IsInt() @Min(1) @Max(65535)` constraint on `EnvironmentVariables.PORT` never applies to the value actually used. Read it off `ConfigService` instead.--## Turbo and env--Turborepo 2 runs in strict env mode: a task sees only the variables it declares, so **adding a variable to a `.env` file is not enough — the task that needs it must list it too.**--- Root `turbo.json` sets `globalEnv: ["NODE_ENV"]` and makes `.env*` a `build` input, so editing any env file correctly invalidates the build cache.-- `apps/api/turbo.json` declares `passThroughEnv` for `dev` and `test` (auth, database, Google, cache, port).-- `apps/app/turbo.json` declares `env` for the two `NEXT_PUBLIC_*` values — they are build inputs because Next inlines them — and `passThroughEnv` for the server-side ones.-- `packages/db/turbo.json` and `packages/auth/turbo.json` pass `DATABASE_URL` through to every `db:*` / `auth:generate` task.--The split matters: `env` participates in the cache key, `passThroughEnv` does not. Secrets belong in `passThroughEnv` so changing one doesn't churn the cache; anything baked into build output (the `NEXT_PUBLIC_*` pair) belongs in `env`, or Turbo will serve a stale build that inlined the old value.--## Google OAuth--Google is the only sign-in method, wired unconditionally in `packages/auth/src/auth.ts`. Credentials live in `apps/api/.env` only — the app never mounts the auth handler.--Create a web OAuth client in Google Cloud → Credentials, and register the redirect URI:--```-http://localhost:3001/api/auth/callback/google-```--Add the deployed equivalent (`https://<api-host>/api/auth/callback/google`) for each environment. `AUTH_TRUSTED_ORIGINS` is the comma-separated allow-list of origins permitted to call the API with credentials, and doubles as the allow-list Better Auth validates post-sign-in `callbackURL`s against — the Next.js origin belongs there.--The provider sets `accessType: "offline"`, which is what makes Google issue a refresh token. Without it nothing breaks at sign-in, but every Gmail/Calendar connection dies an hour after it is made with nothing to refresh from.+`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:++- **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.++## 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.++| 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 |+| `CONTEXT_DEV_API_KEY` | Company logo, industry, location and socials from a domain |+| `GITHUB_TOKEN` | Raises the GitHub rate limit from 60/hour when matching profiles |+| `BLOB_READ_WRITE_TOKEN` | Mirrors profile pictures into Vercel Blob rather than linking them |+| `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.## 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.+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: `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. There is deliberately no "disconnect" — see the plan §3.4.+The scopes are requested **at sign-in** and are a condition of using the CRM:+`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.-**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. A calendar event already in the diary for next week does show up, because it starts in the future — that is not back-dating.+**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` | yes, in deployed environments | Bearer guard on `POST /internal/sync/google`. Vercel sends it automatically as `Authorization: Bearer $CRON_SECRET`. Minimum 16 characters; the route **fails closed** if unset, so locally the cron simply never runs. |--That is the whole list, and the absences are deliberate:--- **No `GOOGLE_SYNC_ENABLED`.** A feature flag only earns its keep when it gates something that can genuinely be absent — `CONTEXT_DEV_API_KEY` does, because without a key there is no API call to make. Sync has everything it needs the moment the app boots: the OAuth client is already mandatory because Google is the only sign-in, and mailbox scopes are a condition of having an account. A switch that can turn off a mandatory feature, defaulting to off, is a switch that is only ever wrong.-- **No `GOOGLE_WORKSPACE_DOMAIN`.** Our own domains are derived from the `User` table, which already holds them. Sign-in is Google-only behind an Internal consent screen, so every user is on a company domain by construction — and a derived value cannot go stale the day the team adds a second domain.+| `CRON_SECRET` | in deployed environments | Bearer guard on `POST /internal/sync/google`. Vercel sends it automatically as `Authorization: Bearer $CRON_SECRET`. Minimum 16 characters; the route **fails closed** if unset, so locally the cron simply never runs. |++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.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.** `gmail.readonly` is a *restricted* scope; an External app using it needs OAuth verification plus an annual CASA security assessment. For an Internal app Google's documentation is explicit that restricted scopes need no further review. Going External later means the full review, so this is a decision, not a checkbox.+- **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.+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 `packages/db/.env` itself, so the CLI works without any app running.+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`).+- **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-only, in code, not configurable.## Secrets hygiene-`.env` files are gitignored, but the patterns are name-exact and inconsistent between packages. Two things to know:--- **Root and `apps/api/.gitignore` list specific names** (`.env`, `.env.local`, `.env.*.local`). A file like `.env.bak` or `.env.old` is **not** ignored and will be committed if you `git add -A`. Never leave a timestamped backup of a real `.env` in the tree.-- **`apps/app/.gitignore` uses `.env*`**, which is broader — and catches the template too. `apps/app/.env.example` is currently untracked and ignored because of it, so a fresh clone gets no template for the web app while the other three packages ship theirs. Fix with a negation (`!.env.example`) in that file.+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.-`packages/auth/.env.example` ships a filled-in `BETTER_AUTH_SECRET` as an illustration. Treat it as a placeholder, not a value: generate your own with `openssl rand -base64 32`.+Generate your own secret. Never reuse one from an example file, a tutorial, or+another environment: `openssl rand -base64 32`.diff --git a/docs/images/companies-dark.png b/docs/images/companies-dark.pngnew file mode 100644index 00000000..0211bf66Binary files /dev/null and b/docs/images/companies-dark.png differdiff --git a/docs/images/companies.png b/docs/images/companies.pngnew file mode 100644index 00000000..e22f30deBinary files /dev/null and b/docs/images/companies.png differdiff --git a/docs/images/contacts-dark.png b/docs/images/contacts-dark.pngnew file mode 100644index 00000000..3b80c294Binary files /dev/null and b/docs/images/contacts-dark.png differdiff --git a/docs/images/contacts.png b/docs/images/contacts.pngnew file mode 100644index 00000000..afb04f17Binary files /dev/null and b/docs/images/contacts.png differdiff --git a/docs/images/deals-dark.png b/docs/images/deals-dark.pngnew file mode 100644index 00000000..d7cdc49eBinary files /dev/null and b/docs/images/deals-dark.png differdiff --git a/docs/images/deals.png b/docs/images/deals.pngnew file mode 100644index 00000000..f9f263caBinary files /dev/null and b/docs/images/deals.png differdiff --git a/docs/images/overview-dark.png b/docs/images/overview-dark.pngnew file mode 100644index 00000000..5f430b7eBinary files /dev/null and b/docs/images/overview-dark.png differdiff --git a/docs/images/overview.png b/docs/images/overview.pngnew file mode 100644index 00000000..fd1ea870Binary files /dev/null and b/docs/images/overview.png differdiff --git a/docs/plan/contact-intelligence-agent.md b/docs/plan/contact-intelligence-agent.mdnew file mode 100644index 00000000..392d8c71--- /dev/null+++ b/docs/plan/contact-intelligence-agent.md@@ -0,0 +1,739 @@+# Plan — Contact intelligence agent (v2)++Turn the enrichment worker we have into an agent that **decides**: what to+research, how hard, when to look again, and how sure it is. Every claim it+writes carries its evidence; the contact sheet shows the person, the background,+and how much of it to believe — live, while the agent works.++Read it with [`AGENTS.md`](../../AGENTS.md), [`api.md`](../api.md),+[`design.md`](../design.md), [`crm-plan.md`](./crm-plan.md),+[`gmail-calendar-plan.md`](./gmail-calendar-plan.md) and+[`people-enrichment-agent.md`](./people-enrichment-agent.md), which is v1 and+whose §0 findings still hold. Conventions there are assumed, not repeated.++**Two rules from the top, and everything below obeys them:**++1. **Never at the API level.** This is an agentic-first platform. NestJS serves+ HTTP, auth, tRPC and the Google sync. It does not research, enrich, score,+ summarise or decide anything about a person — not as a fallback, not "just+ the cheap bit", not behind a feature flag. §2, §10.+2. **The agent may read everything we have.** This is a single-tenant internal+ tool. Email bodies, meeting notes, attendee lists and every activity on a+ timeline are legitimate evidence and the agent gets them in full. The one+ boundary is egress, not access. §4.++**This document is not static either.** Each phase closes by appending what it+measured to §14, the way v1's §0 rewrote v1's architecture.++---++## 0. Where we actually are++Measured against the tree on 2026-08-01, not remembered.++### Two enrichment stacks, one job++| | Lines | Owns |+| --- | --- | --- |+| `apps/api/src/enrichment/` | ~1,720 | Context.dev company brand + research, LinkDAPI contact identity, avatar mirroring, an in-process queue |+| `apps/agent/agent/` | ~2,140 | LinkDAPI identity again, Perplexity research, summaries, socials |++Two LinkedIn clients (`enrichment/linkdapi.client.ts`, `agent/lib/linkdapi.ts`).+Two identity matchers. `looksLikeSameCompany`, `nameMatchesLocalPart` and+`searchTerms` exist verbatim in both trees — and **have already drifted**: the+agent's `looksLikeSameCompany` guards `(!b && !c)`, the API's does not, so with+an empty company name the API copy evaluates `a.includes("")` and matches every+employer on earth. It is unreachable today because the only caller passes a+domain fallback. That is the point: nobody noticed, because nobody was looking+at the copy they were not working in.++Triggers are scattered to match: `companies.service.ts:305,364,389` for+companies, `google-match.service.ts:335` for contacts, two eve schedules for+everything else.++### The "agent" is a worker with a numbered list++Both schedules are step lists — `research-new-contacts` steps 1–5,+`profile-contacts` steps a–f. The model chooses nothing that matters. It does+not pick who to work on (a `take: limit` does), how deep to go (a boolean flag+does), or when to look again (a cron expression does). Ten tools, each one API+call. That is a script with a language model inside it.++It is also using almost none of the framework. No sandbox, so no `bash`, no+`web_fetch`, no `web_search`, no workspace. No `defineState`, no `defineDynamic`,+no hooks, no channels, no subagents, no evals. Ten hand-written tools, several of+which re-implement things eve ships.++### Confidence is computed, then thrown away++`get_linkedin_profile` returns `high | medium | low`. `update_contact` refuses+anything below `high` and returns a sentence. Nothing is stored. A `medium`+match — the right person, one weak signal short — is discarded so completely+that the next run pays to rediscover it and discards it again. v1 §5 said+`medium` becomes a suggestion. Never built.++### There is no provenance store, and no way to see the agent think++v1 §6's `ContactEnrichment` model never landed. The only field-level source in+the schema is `Contact.summarySourceUrl`, shipped today. `Contact` has no+`enrichmentStatus`, so the sheet cannot even show work in flight. Everything the+agent does happens in a cron job nobody can watch, explain or interrupt.++---++## 1. What "better than HubSpot and Salesforce" has to mean++Not more fields. They will always have more fields. Four structural advantages:++| They optimise for | We do instead |+| --- | --- |+| **Enrichment as a purchase.** Credits buy a record; the unit is the record and the vendor's confidence is not your business. | **Enrichment as an argument.** Every claim carries evidence, method and date, and the UI shows them. A rep can disagree with one field for one reason. |+| **Per-seat, per-credit economics** across millions of tenants, so re-reading every contact monthly is a line item they must charge for. | **One tenant, our Postgres, our keys.** Re-reading costs cents. That turns enrichment from a snapshot into a *feed*, which is the only way job-change detection exists at all. |+| **Generic B2B data.** The same firmographics every customer of the platform gets. | **Our own conversation history as evidence** — in full. We sync Gmail and Calendar; a signature block settles a job title outright, and a reply on a thread is proof of identity no data vendor can sell us (§4). |+| **A chat panel bolted onto a record.** Ask a question, get an answer, nothing persists. | **A resident agent with durable sessions.** It works the record on its own clock, and when a rep opens the sheet they can watch it, interrupt it and redirect it — same session, same memory, next week. |++The fourth is the one that is hard to copy, and eve is the reason it is cheap+for us: durable sessions, a streamable event log and a browser client are+framework features, not a project.++**The test:** a rep opens a contact five minutes before a call and knows who+they are, what they do, how long they have done it, what we have already said to+each other, and which parts a machine inferred. Then they type "is he still at+Fleetio?" into the same panel and watch it check.++---++## 2. Decisions that carry the design++1. **Never at the API level.** Not a fallback, not a fast path. The API's+ enrichment directory is deleted, not deprecated — §0 shows what a second+ copy does even when nobody is calling it. Nest emits *events*; the agent+ decides what they mean. §10.+2. **The agent runs in a sandbox and uses the harness.** `bash`, `web_fetch`,+ `web_search`, `glob`, `grep`, `todo`, `ask_question` and a `/workspace` come+ with eve. Authored tools are for the three things the harness cannot do:+ vendor APIs that need keys and verification, CRM reads and writes, and+ decisions. Every tool we write that wraps a public HTTP GET is a tool we are+ maintaining for nothing. §4.+3. **Confidence is data, not a gate.** Every fact is stored with evidence,+ score, method and source — including the ones too weak to apply. Discarding a+ `medium` match throws away the most valuable thing the run produced: a+ candidate a human could settle in three seconds. §5.+4. **Background runs propose; people approve.** A markdown schedule is task mode+ and **cannot park for a person** — so an approval gate in a cron run is not a+ pause, it is a failure. Background work below the bar writes a *proposal*.+ Approval prompts and `ask_question` are for sessions a human started. §5, §7.+5. **The record is the interface to the agent.** The Next app mounts eve's+ routes with `withEve` and the contact sheet renders a live session with+ `useEveAgent`. The rep watches the same event stream the runtime persists.+ No second app, no chat silo. §6.+6. **The agent may read the whole CRM, including bodies.** Internal tool, single+ tenant, our own data. The boundary is *egress*: raw customer text never+ leaves as a third-party search query, and never reaches the sandbox, which+ has network access. §4, §8.+7. **Budget is an input the agent spends,** held in `defineState` and enforced+ in the tool — a VP on a live deal earns a deep pass, a newsletter signup+ earns one lookup. §7.+8. **Humans outrank the agent, permanently.** A field a person typed is never+ overwritten; a dismissed proposal is never re-proposed. Enforced in the fact+ store, not in a prompt.++### Judgment calls worth your veto++- **Deleting the API path outright.** The safe-sounding option is to keep it as+ a fallback. That is how we got two of everything. Enrichment has never been on+ a request path; if the agent is down, contacts wait.+- **Giving the agent a shell.** A sandbox with `bash` and web egress is a real+ capability and eve's own docs tell you to review it before production. The+ mitigation is not "no shell", it is **no database credentials in the sandbox**+ (§8): CRM access is authored tools in the app runtime, never `psql`.+- **Numeric confidence, shown as words.** Storing `0.82` and rendering+ "probable" invites "why not 0.79?". The honest answer is that the number is+ calibrated by evals (§9), not a probability. Three opaque bands cannot be+ calibrated at all.+- **A live agent panel on the record.** More UI, and it puts model output in+ front of reps constantly. That is the intent: an agent nobody watches is an+ agent nobody corrects.+- **The agent schedules itself.** Bounded by lease and budget, but it decides to+ come back in fourteen days. Anything less and "not static" is a slogan.++---++## 3. Data model++Current values stay denormalised on `Contact` so lists stay one query. The new+tables are the *reasoning*, not the read path.++```prisma+/// One claim about one field of one contact, with what backs it.+model ContactFact {+ id String @id @default(cuid())+ contactId String+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)++ field String // "title" | "linkedinUrl" | "seniority" | "employer"…+ value String++ /// 0–1 from the evidence ledger (§5), with the band stored alongside so a+ /// re-calibration re-derives bands without re-running the research.+ score Float+ band FactBand++ evidence Json // every item, so the score can be explained and recomputed+ method String // "linkedin.profile" | "github.api" | "crm.thread" | "web"+ sourceUrl String?++ /// The session that produced it — joins to the event log for "show your work".+ sessionId String?++ status FactStatus @default(PROPOSED)+ decidedById String?+ decidedAt DateTime?++ observedAt DateTime @default(now())+ supersededAt DateTime?++ @@index([contactId, field, status])+ @@map("contactFact")+}++enum FactBand { VERIFIED PROBABLE POSSIBLE }+enum FactStatus { APPLIED PROPOSED DISMISSED SUPERSEDED }++/// The background panel: narrative plus the structured lines under it.+model ContactBrief {+ contactId String @id+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)+ narrative String+ sections Json // { currentRole, tenure, previousRoles[], seniority, function, location }+ score Float+ sessionId String?+ refreshedAt DateTime @default(now())+ @@map("contactBrief")+}++/// What the agent decided to do, and why. Work queue and audit trail in one.+model AgentTask {+ id String @id @default(cuid())+ contactId String?+ companyId String?+ kind String // "identify" | "profile" | "recheck" | "meeting-prep"+ reason String // the agent's own words, shown to the rep+ priority Int @default(0)+ budget Int // research units this task may spend+ dueAt DateTime+ leasedUntil DateTime?+ sessionId String?+ startedAt DateTime?+ finishedAt DateTime?+ outcome String?+ @@index([dueAt, leasedUntil])+ @@map("agentTask")+}++/// Every runtime event, written by a hook. The "show your work" substrate.+model AgentEvent {+ id String @id // eve's meta.id ULID — dedupes replays+ sessionId String+ contactId String?+ type String+ data Json+ emittedAt DateTime+ @@index([sessionId, emittedAt])+ @@index([contactId, emittedAt])+ @@map("agentEvent")+}+```++`AgentEvent` is close to free: a single `defineHook` on `*` writing+`insert … on conflict (id) do nothing`, exactly the pattern eve's streaming doc+recommends, and ULIDs keep it append-ordered. It gives us the agent's full+history — which tool ran, what it returned, what it decided — without inventing+an audit format.++`Contact` also gains `enrichmentStatus`/`enrichedAt`/`enrichmentError` matching+`Company`, so the sheet reuses `isEnriching()` and `ENRICHMENT_POLL_MS`+(`api.md`) for the non-streaming case. `ContactFact` subsumes+`summarySourceUrl`, `summaryUpdatedAt` and `socialsCheckedAt` shipped today;+those columns migrate into facts in Phase 1.++**Job changes fall out for free:** a new `employer` fact superseding an applied+one *is* the event. No diffing machinery, which is why v1 put it last and this+plan does not have to.++---++## 4. Capabilities: what eve gives us, what we write++### From the harness (a sandbox is all it takes)++| Built-in | What it replaces |+| --- | --- |+| `web_search`, `web_fetch` | Half of `lib/perplexity.ts`. Perplexity stays for *cited synthesis*; plain retrieval is a built-in. |+| `bash`, `read_file`, `write_file`, `glob`, `grep` | A `/workspace` dossier per contact: dump the profile JSON, grep it, diff this month's against last month's. Job-change detection becomes a `diff`. |+| `todo` | Durable per-session task list. Multi-step research stops living in the prompt. |+| `ask_question` | The agent asks the rep — "two Bighams at HubSpot, which one?" — and parks. Worth more than any heuristic we could write for that case. |+| `agent` (root-only) | Parallel research fan-out. Meeting prep with four attendees is four children, not four sequential passes. |+| `load_skill` | Procedures load on demand instead of bloating every turn. |++Enabled deliberately, per eve's own guidance to review the defaults: `bash`,+file tools and `web_fetch` stay on because a research agent without retrieval is+a chatbot; the sandbox gets **no database credentials** (§8).++### Authored tools — only where the harness cannot go++| Group | Tools | Why authored |+| --- | --- | --- |+| **CRM read** | `read_contact`, `read_crm_history`, `read_company` | Database access belongs in the app runtime, not the sandbox. `read_crm_history` returns threads, meetings, attendance **and message bodies** — the strongest identity evidence we own. |+| **Vendor** | `get_linkedin_profile`, `get_work_history`, `research_person` | Keys, rate limits, and LinkDAPI's `200 {success:false}` envelope. |+| **Judge** | `verify_identity`, `verify_social`, `corroborate_from_crm` | These fetch their own evidence and rule in code. `verify_social` exists and is the template: no `confidence` argument, no model-supplied `sourceUrl`. |+| **Decide** | `plan_research`, `schedule_recheck`, `set_priority` | The tools that make it an agent. `schedule_recheck` takes a date **and a reason**, and the reason is shown to the rep. |+| **Write** | `apply_fact`, `propose_fact`, `write_brief`, `record_job_change` | Approval policy lives here (§5). |++Two invariants: **a tool never accepts the model's own confidence**, and **"looked,+found nothing" is recorded with a date** — the generalisation of today's+`socialsCheckedAt`, without which every run re-litigates the same absence.++### Context control++`instructions.md` shrinks to identity and the one rule. Everything else becomes+a skill loaded on demand — `identity-matching` (exists), `confidence-scoring`,+`writing-a-brief`, `meeting-prep`, `job-change`, `data-boundaries`. `load_skill`+adds instructions, never execution surface, so this is free discipline.++`defineDynamic` then makes the surface itself situational, resolved at+`session.started`: a contact with no company gets no company tools; a task on a+live deal loads the deal-brief skill; ambiguous identity work can resolve a+stronger model. (Model resolution stays at `session.started` — switching+mid-session re-ingests the conversation at uncached prices.)++### The egress boundary++The agent reads everything. What leaves is controlled:++- **Never send raw customer text to a third-party search.** Perplexity and+ `web_search` get derived questions ("what did Acme announce in 2026?"), never+ a pasted thread.+- **Nothing from a mailbox reaches `/workspace`.** The sandbox has network+ access; email bodies stay in the app runtime, in the model's context.+- **`api.md` still stands:** never *log* headers, bodies or query strings. Read+ is not log.++---++## 5. The confidence model++### Evidence, weighted++Starting values, to be calibrated (§9), not truths:++| Evidence | Weight | Primary? |+| --- | --- | --- |+| Exact email match on a profile | 0.95 | ✔ |+| LinkedIn: employer matches **and** name is consistent with the address | 0.85 | ✔ |+| **They replied on a thread we synced** | 0.85 | ✔ |+| GitHub API: the account's own `name` or `company` matches | 0.8 | ✔ |+| **A signature block in a thread states the title** | 0.8 | ✔ |+| They attended a meeting on our calendar | 0.7 | ✔ |+| Perplexity states it with a citation | 0.4 | |+| Handle is a construction of their name | 0.35 | |+| A search engine cites the profile for their name + employer | 0.35 | |+| Employer matches, name does not | 0.2 | |++The two bolded rows are ours alone, and they are near the top. That is the+argument in §1 turned into arithmetic.++Combined as `1 − Π(1 − wᵢ)` over *independent* items, capped at 0.99, with two+rules a score cannot express:++1. **No auto-apply without a primary source.** Three weak signals multiply to a+ confident-looking number and remain three weak signals.+2. **Contradiction floors the score.** A profile saying one employer and a mail+ header saying another is not 0.6, it is unresolved, and the fact is held.++### Bands++| Band | Score | Behaviour | In the UI |+| --- | --- | --- | --- |+| `VERIFIED` | ≥ 0.85 + primary | Applied automatically | The value, plain. Dotted underline reveals the source. |+| `PROBABLE` | 0.55–0.85 | Stored as a proposal; field stays empty | A line under the field: *"LinkedIn suggests Head of Security · accept · dismiss"* |+| `POSSIBLE` | 0.3–0.55 | Stored, never shown as a value | Only in the provenance panel, as what was considered |+| below | < 0.3 | Not stored | — |++### Enforced by the approval policy, not the prompt++eve's docs are explicit that model behaviour alone must not guard sensitive+writes, and a rubric in a system prompt *is* model behaviour. The policy also+has to know **who** is driving, because a task-mode schedule cannot park for a+person:++```ts title="agent/tools/apply_fact.ts (policy sketch)"+approval: ({ session, toolInput }) => {+ const auth = session.auth.current;+ const automated =+ auth?.authenticator === "app" &&+ auth.principalId === "eve:app" &&+ auth.principalType === "runtime";++ if ((toolInput?.score ?? 0) >= 0.85 && toolInput?.hasPrimarySource) {+ return "not-applicable"; // verified: just write it+ }+ // A cron turn cannot wait for a human, so asking would hang the run.+ return automated+ ? { type: "denied", reason: "Below the bar — call propose_fact instead." }+ : "user-approval"; // a rep is here; ask them+};+```++Same tool, two behaviours, decided by the principal rather than by a flag the+model can set. Sensitive fields (`email`, `companyId`, anything that re-parents+a record) sit a band higher regardless of score.++---++## 6. The contact sheet++All of it inside `design.md`: components from `/packages/ui`, no new radii or+colours, no `className` overrides on shared components, new variants land in the+package.++### The Background section++Above Details, because it is what the sheet is *for*:++```+BACKGROUND refreshed 2 days ago++Lewis Carhart is the CEO and co-founder of Comp AI. He previously led+growth at Fleetio and spent four years at Deloitte in risk advisory.++Current role CEO & Co-founder · Comp AI · 2 yrs 3 mos+Previously Head of Growth, Fleetio · Risk Advisory, Deloitte+Seniority Founder / C-level Function Executive+Based London, UK++WE KNOW THEM ← from our own data+12 emails · last reply 4 days ago · 3 meetings · next: Thursday 14:00+Also here Sarah Chen (CTO) · Tom Reyes (Security Lead)+```++The second block is the one no incumbent renders, because it is built from the+Gmail and Calendar sync rather than a purchased record.++### How confidence reads++`status-indicator.tsx` argues against pill chips in its own comment and it is+right: a sheet speckled with coloured badges is a sheet you read the badges of.++- **Verified values render as plain text.** No chrome. Decoration on everything+ is noise, and noise is how the one uncertain field gets missed.+- **Agent-written values carry a dotted underline.** Hover or focus reveals a+ `ProvenanceTooltip` — source, method, date, the evidence that scored it. One+ new component in `/packages/ui`.+- **Proposals are not values.** The field stays empty; the suggestion sits+ beneath with accept and dismiss. A guess is never formatted like a fact.+- **`StatusIndicator`** already covers in-flight and failed.++Accept and dismiss write `ContactFact.status` with `decidedById` — labelled+data for §9, produced by the people best placed to judge, when they care.++### The live panel++`withEve()` in `apps/app/next.config.ts` mounts eve's routes on the app's own+origin — no CORS, no URL env var. A `useEveAgent()` panel in the sheet then+gives the record something neither incumbent has:++- **Watch it work.** `actions.requested` / `action.result` render as a plain+ list of steps: *searched LinkedIn · read profile · checked GitHub API ·+ rejected `github.com/lewis`*. The rejections are the most trust-building thing+ on the page.+- **Interrupt and redirect.** "Is he still at Fleetio?" continues the same+ durable session, with the same history, on the same record.+- **Answer its questions.** `ask_question` renders inline: two Bighams at+ HubSpot, pick one. The answer is worth more than any tiebreak heuristic.+- **Replay.** Sessions are durable for 30 days and the stream is rewindable, so+ "why does it think that?" is a question with an answer.++**Tables get none of this.** The contacts list stays plain text; scanning is its+whole job. Confidence and agency belong where a decision gets made.++---++## 7. Not static: how the agent chooses++### One dispatcher, not two cron prompts++A single `defineSchedule({ cron: "* * * * *", run })` claims due `AgentTask`+rows under an atomic lease and calls `receive(...)` per row with `appAuth`,+following eve's documented dynamic-scheduling pattern. Prompts stop being+numbered lists; the row carries the objective, the budget and the reason.++### The agent writes its own rows++`schedule_recheck` takes a date *and* a reason:++- champion on an open deal → 14 days ("job change here moves a live deal")+- named contact, no open deal → 90 days+- nothing found twice → 365 days, low priority+- `support@`, `no-reply@` → never++Today's `cron: "20 * * * *"` over `take: 10 ORDER BY createdAt` treats the CEO of+a live opportunity and a bounced alias identically.++### Events jump the queue++A calendar event tomorrow with an unknown external attendee inserts a+high-priority `meeting-prep` task the moment the sync sees it. Delivery is a+custom channel (`agent/channels/crm.ts`) exposing routes the sync posts domain+events to — "thread ingested", "attendee unknown" — never "enrich this". The+agent decides what an event means; that is the whole point of rule 1.++### Depth is a decision, budget is state++`plan_research` reads the contact, the deal context and the budget, then picks+the passes. The budget is a `defineState` slot decremented by the tools that+spend it — eve's own budget example, applied to vendor calls:++```ts+const research = defineState("crm.research-budget", () => ({ spent: 0, cap: 8 }));+```++A $40k opportunity earns more calls than a newsletter signup, and the agent —+not a boolean — makes that call.++### Fan-out for briefs++Meeting prep with four external attendees delegates four children through the+built-in `agent` tool with non-overlapping write scopes, then writes one brief.+If the orchestration gets genuinely complex, the opt-in `Workflow` tool lets the+model author that fan-out as one durable step; it stays off until a brief needs+it, because a capped subagent budget is easier to reason about than+model-authored JavaScript.++---++## 8. What stays deterministic++Widening discretion is only safe if the boundary is code:++- **Identity verification.** `verify_*` fetch their own evidence and rule.+- **The approval policy.** §5, keyed on principal, in the tool definition.+- **Never overwrite a human; never re-propose a dismissal.** In the fact store.+- **No database credentials in the sandbox.** The sandbox has `bash` and+ egress; CRM access is authored tools in the app runtime. This is the single+ most important line in the section.+- **No raw customer text leaves as a search query.** §4.+- **Rate limits and budgets.** A token bucket per vendor; a per-task budget the+ agent spends but cannot raise.+- **Business context only.** Name, title, employer, tenure, public profile. No+ special categories regardless of what an endpoint returns (v1 §9 stands).++Dynamic in *what to do*. Fixed in *what is allowed*.++---++## 9. Evals, or the confidence number means nothing++`evals/*.eval.ts` with `defineEval`, driving real sessions over the same HTTP+surface the app uses; `mockModel` for deterministic fixtures where the point is+the plumbing rather than the judgement.++| Metric | Target | Why |+| --- | --- | --- |+| Precision at `VERIFIED` | ≥ 0.98 | An auto-applied wrong fact is the failure that costs a deal. |+| Precision at `PROBABLE` | ≥ 0.75 | Below this, reps learn to dismiss without reading. |+| Recall | tracked, not gated | Coverage is a cost decision; precision is a trust one. |+| Cost per contact | tracked | Where "budget as an input" meets reality. |++The fixture set is real CRM addresses with known answers, **including ones whose+correct answer is nothing** — a matcher that never abstains scores well on a set+where everybody is findable. Accept/dismiss decisions from §6 feed the fixtures,+which is the flywheel: the more it is corrected, the better calibrated the number+the corrections are shown against.++Calibration is the deliverable: when a band says 0.85, roughly 85 of 100 should+be right. The weights in §5 move until that holds.++---++## 10. Retiring the API path++Order matters — no window with two writers:++1. **Facts first.** `ContactFact` and the `AgentEvent` hook land; the agent+ writes through them.+2. **Invert the triggers.** `companies.service.ts` and `google-match.service.ts`+ stop calling enrichment and post a domain event to the agent's CRM channel.+ Nest learns nothing about enrichment; it reports what happened.+3. **Move company enrichment.** Context.dev brand mapping becomes agent tools.+ `brand-mapping.ts` moves as-is — pure and well-tested.+4. **Delete `apps/api/src/enrichment/`,** minus `avatar.service.ts` (Blob+ mirroring belongs to whoever writes the URL). ~1,600 lines out of the API,+ ~200 of them moving rather than dying. One LinkedIn client in the repo, one+ identity matcher, one place to fix a bug.+5. **Move the tests.** `enrichment.spec.ts`, `contact-enrichment.spec.ts` and+ the integration spec go to `apps/agent/test/`. They encode findings, not+ implementation.++What Nest keeps: HTTP, auth, tRPC, the sync, and the ability to say "this+happened". What it stops doing: deciding anything about people.++---++## 11. Phases++| Phase | Scope | Done when |+| --- | --- | --- |+| **1 — Provenance spine** | `ContactFact`, `ContactBrief`, `AgentEvent` hook, `Contact.enrichmentStatus`; `ProvenanceTooltip` in `/packages/ui` | Every agent-written value on the sheet traces to a source and a date without opening a database. |+| **2 — Harness** | Sandbox on, built-ins reviewed and gated, instructions split into skills, `defineState` budget, `defineDynamic` surface | The agent researches with `web_search`/`web_fetch`/`bash`; three authored tools are deleted as redundant. |+| **3 — Confidence** | Evidence ledger, bands, principal-aware approval policy, proposals inline with accept/dismiss | A `medium` match becomes a suggestion a rep settles in three seconds instead of a discarded log line. |+| **4 — Agent-only** | §10 steps 2–5 | `apps/api/src/enrichment/` is gone. |+| **5 — Background panel** | Structured sections, tenure, "we know them" from Gmail/Calendar, colleagues | The five-minutes-before-a-call test in §1 passes. |+| **6 — Live panel** | Same-origin proxy, `useEveAgent` on the contact sheet, `ask_question` inline, step list | A rep watches a rejection happen and trusts the accepted ones more. |+| **7 — Dynamic scheduling** | `AgentTask`, dispatcher, `plan_research`, `schedule_recheck`, CRM channel, subagent fan-out | Two contacts researched on different cadences, for reasons the agent wrote and the rep can read. |+| **8 — Meeting prep** | Calendar-triggered briefs for external attendees | Thursday's 14:00 has a brief on it by Wednesday night. |+| **9 — Job changes** | Superseding facts raise an activity and a task for the owner | A champion moves and their owner knows that week. |++Phases 1–4 make the data trustworthy; 5–9 are what a rep would miss if you took+it away. One ordering constraint is non-negotiable, as v1 also said: a brief+built on unverified identities is confidently wrong *in front of a customer*.++---++## 12. Risks++- **eve is in preview.** APIs may change before GA. `apps/agent/lib/` is where+ the vendor-shaped code lives; keep framework surface in the authored files+ thin enough to move.+- **A sandbox with egress is a real capability.** §8's no-credentials rule is+ the mitigation, and it only holds if nobody "temporarily" adds `DATABASE_URL`+ to the sandbox env.+- **Task-mode schedules cannot pause.** Any design that wants a human mid-cron+ is wrong by construction; that is why §5's policy denies rather than asks.+- **Live streams show reasoning.** eve's docs flag the privacy implications of+ rendering reasoning events. Internal tool, so acceptable — but it is a+ decision, and it is recorded here as one.+- **Single-provider LinkedIn risk** (v1 §9) is unchanged.++---++## 13. Open questions++1. **Score on the record, or only in the tooltip?** Leaning: band in the+ tooltip, raw number only in the provenance panel.+2. **Do proposals expire?** A suggestion nobody has judged in 90 days is noise.+ Auto-dismiss, or keep and stop re-scoring?+3. **Who owns the budget dial?** A constant, or a per-account setting a rep can+ turn up?+4. ~~Does the agent see message bodies?~~ **Decided: yes, in full.** Internal+ tool, single tenant. The boundary is egress (§4), not access.+5. **Company facts too?** The model generalises, but companies have one source+ and no identity problem. Probably later, possibly never.+6. **A rep edits a field by hand — what happens to the fact?** Superseded and+ kept as history is right, but the store must then accept writes that did not+ come from the agent.+7. **Does the live panel belong on companies and deals too?** Same machinery,+ three times the surface. Contacts first.++---++## 14. What each phase actually taught us++Appended as phases land, in v1 §0's spirit — measurements that changed the+design, not a changelog.++### Phases 1–4 (2026-08-01)++**The weights in §5 do not behave the way the table implies, and a test caught+it.** `crm.signature-block` at 0.8 is below the `VERIFIED` floor, so a title+read out of a signature was going to become a suggestion rather than a fact —+not what §1 promises. The realistic case saves it: a signature is read *on a+thread they replied to*, so the evidence is `crm.thread-reply` ++`crm.signature-block` → 0.97, and it writes. The lesson is that weights must be+tested against the **combinations that actually occur**, not one at a time.++**Four weak signals do not reach 0.85** (they reach 0.797), so the "pile of weak+evidence" scenario the primary-source rule exists to stop was not reachable by+arithmetic anyway. The rule is still right — it has to hold under+re-calibration — but the test for it now asserts `bandFor(0.99, false)`+directly rather than pretending the weights get there.++**Approval gates were wrong for `record_fact`.** The plan had one on the write+tool. Building it showed the flaw: if approval denies the call, `execute` never+runs, so the *proposal is never stored* — the gate would have deleted the+feature it was protecting. Band logic inside the same function that scores the+evidence is strictly stronger, because there is no path around it. Approval+moved to where blast radius is bigger than one field: `record_job_change`,+which can re-parent a contact.++**Verification functions should return evidence, not verdicts.** `verifyGithub`+used to decide `accepted: true` on *any* of name-match, company-match, or+domain-link. That meant an account sharing only an employer — a colleague — was+written with the same authority as one naming the person. Returning evidence+kinds instead put both through the ledger, and the colleague case now scores+0.2 and is dropped. Same code, one fewer way to be confidently wrong.++**The "delete three redundant tools" prediction was wrong in detail and right in+outcome.** Nothing became redundant *because of the harness* — `research_person`+and the two candidate-finders still earn their keep. Six tools went anyway+(`update_contact`, `write_contact_summary`, `write_briefing`,+`list_contacts_to_research`, `list_contacts_to_profile`, plus the API's two+enrichment services), because the fact store replaced the write path and one+`list_outstanding_work` replaced the "which queue am I" tools.++**The sandbox needs no network, which was not obvious until the harness table+was read properly.** `web_fetch` runs in the app runtime and `web_search` at the+provider — only `bash` and the file tools run in the sandbox. So `deny-all`+costs nothing and removes the only shell-shaped path out of the building for+the email bodies this agent now reads in full. It is set on the backend factory+rather than in `onSession`, so it cannot be forgotten per session.++**`packages/db` and `packages/auth` imported `@crm/env` without declaring it.**+Hoisting hid it until `bun add` in `apps/agent` created a local `node_modules`+that shadowed the root, and then every DB-touching test failed at once. Two+one-line `package.json` fixes; worth recording because the symptom+("Cannot find module" in a package nobody edited) looks nothing like the cause.++### Phase 6 (2026-08-01)++**`withEve` was the wrong tool, and the constraint made the design better.**+The agent stays its own deployment, so mounting it inside the Next build was+never available. What replaced it is the pattern the app already uses for the+API: a **same-origin proxy**, at `app/eve/v1/[...path]/route.ts`, mounted at+exactly the path `useEveAgent()` defaults to. The hook needs no `host`, the+browser never learns the agent has its own origin, and there is no CORS and no+cross-site cookie anywhere in it.++**The proxy is an enforcement point, not a passthrough**, and that is the one+structural difference from the API proxy beside it. The agent never sees the+session cookie — it is stripped — so if the route did not check the session,+nothing downstream would. It checks, then mints a two-minute HS256 token naming+the rep.++**eve's `jwtHmac()` helper labels the caller a service, and that would have been+a silent bug.** Verified through the helper, a rep's token resolves to+`principalType: "service"` with `principalId: "crm-app:user_123"` — sensible for+a machine credential, wrong for a person. `lib/approval.ts` decides whether to+pause for a human by reading exactly those fields, so a sensitive write would+have been *refused* with "not something to do unattended" while the rep sat+watching. `repFromCrm` wraps `verifyJwtHmac` and maps the subject to a real user+principal instead. Found by printing the verifier's output rather than trusting+the shape, and now pinned by `channel-auth.spec.ts`.++**Both halves of the token are tested against each other**: the app mints and+eve's own verifier accepts (`apps/app/test/agent-bridge.spec.ts`), and forged,+expired, wrong-audience, wrong-issuer and subject-less tokens are all rejected+by the real auth function (`apps/agent/test/channel-auth.spec.ts`). A shared+secret is the whole security of the panel, so neither side is asserted from+memory.++**`AGENT_BRIDGE_SECRET` unset skips the entry rather than opening it.** No+signer, no panel, everything else unchanged — the agent still runs its own+schedule. That is the correct failure for an optional capability whose absence+must never widen access.++**One duplication survived on purpose.** `domainOf` in the agent and+`domainFromEmail`/`normalizeDomain` in the API do the same job. Both apps+genuinely need it, and a shared package for two pure functions is more+machinery than the risk justifies — but it is the same shape as the drift in §0,+so it is written down here rather than left to be rediscovered.diff --git a/package.json b/package.jsonindex 14945577..3927c45d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,7 @@{"name": "crm","private": true,+ "license": "MIT","scripts": {"build": "turbo run build","dev": "turbo run dev",diff --git a/packages/auth/.env.example b/packages/auth/.env.exampledeleted file mode 100644index a14489ab..00000000--- a/packages/auth/.env.example+++ /dev/null@@ -1,7 +0,0 @@-# Required. Generate with: openssl rand -base64 32-BETTER_AUTH_SECRET="6oXI/PGPx8OGGiVz7zW2EODV6LcKmtyALiR+RvG2yc8="-BETTER_AUTH_URL="http://localhost:3001"-AUTH_TRUSTED_ORIGINS="http://localhost:3000"-GOOGLE_CLIENT_ID=""-GOOGLE_CLIENT_SECRET=""-AUTH_COOKIE_DOMAIN=""diff --git a/packages/auth/README.md b/packages/auth/README.mdindex 9d0e886f..63b3dff2 100644--- a/packages/auth/README.md+++ b/packages/auth/README.md@@ -48,8 +48,10 @@ import { signIn, signOut, useSession } from "@crm/auth/client";await signIn.social({ provider: "google", callbackURL: "/" });```-`NEXT_PUBLIC_AUTH_URL` decides which origin the client talks to. It must point-at whichever process mounts the handler; unset, the client uses the current+`NEXT_PUBLIC_API_URL` decides which origin the client talks to. It must point at+whichever process mounts the handler — the NestJS API. The Next.js app inlines+it at build time from `API_URL`, in `next.config.ts`, so there is one variable+rather than two spellings of one origin. Unset, the client uses the currentorigin.The client plugin list mirrors the server plugin list. Keep them in sync or the@@ -58,16 +60,23 @@ inferred client API will drift from the routes the server exposes.## Setup```bash-cp packages/auth/.env.example packages/auth/.env+cp .env.example .env # at the repo root — there is no per-package env fileopenssl rand -base64 32 # -> BETTER_AUTH_SECRET```+This package is a library and never loads an env file of its own; it reads+whatever `process.env` its host process has, and `src/env.ts` imports+`@crm/env/load` so the repo-root `.env` is picked up even when the Better Auth+CLI loads `auth.ts` directly. See+[`docs/environment.md`](../../docs/environment.md).+Create an OAuth client in the Google Cloud console and add-`<BETTER_AUTH_URL>/api/auth/callback/google` — `http://localhost:3001/api/auth/callback/google`+`<API_URL>/api/auth/callback/google` — `http://localhost:3001/api/auth/callback/google`in development — as an authorised redirect URI.-`BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` are read from the environment by-Better Auth itself and are deliberately not passed through config.+`ALLOWED_SIGN_IN` decides who may sign in, and an empty value admits nobody. It+is the whole authorisation model: there are no roles and no organizations, so+`src/workspace.ts` is worth reading before you change anything here.## Changing the schemadiff --git a/packages/auth/package.json b/packages/auth/package.jsonindex c36d51a6..35e23f70 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -17,6 +17,7 @@},"dependencies": {"@crm/db": "workspace:*",+ "@crm/env": "workspace:*","better-auth": "^1.6.25"},"peerDependencies": {diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.tsindex ccce7fac..e7ffdea3 100644--- a/packages/auth/src/auth.ts+++ b/packages/auth/src/auth.ts@@ -4,7 +4,11 @@ import { prismaAdapter } from "better-auth/adapters/prisma";import { APIError } from "better-auth/api";import { env } from "./env";import { SYNC_SCOPES } from "./scopes";-import { isWorkspaceEmail, PRIMARY_WORKSPACE_DOMAIN } from "./workspace";+import {+ hasSignInAllowList,+ isWorkspaceEmail,+ primaryWorkspaceDomain,+} from "./workspace";const socialProviders: NonNullable<BetterAuthOptions["socialProviders"]> = {};@@ -39,7 +43,11 @@ if (env.google) {// convenience, not the control — `hd` is a hint the client sends and a// determined caller can omit it, so the real check is the database hook// below, which sees the verified email.- hd: PRIMARY_WORKSPACE_DOMAIN,+ //+ // Omitted when the allow-list names no domain (a one-person install on a+ // consumer mailbox): `hd` has to be a real domain, and sending an empty+ // one hides every account in the chooser.+ ...(primaryWorkspaceDomain() ? { hd: primaryWorkspaceDomain() } : {}),};}@@ -99,13 +107,28 @@ export const auth = betterAuth({* Runs against the profile Google verified, before a row exists, so* a personal account that gets past the `hd` hint never becomes a* user. This is a single-tenant internal tool: an account outside- * the workspace has nothing legitimate to do here, and every record- * is visible to every signed-in person.+ * the allow-list has nothing legitimate to do here, and every+ * record is visible to every signed-in person.+ *+ * An unset allow-list is refused rather than waved through. The+ * failure mode of the other choice is a CRM full of real customer+ * data that anyone with a Google account can read, and it would+ * look like it was working.*/before: async (user) => {+ if (!hasSignInAllowList()) {+ throw new APIError("FORBIDDEN", {+ message:+ 'No one can sign in yet: set ALLOWED_SIGN_IN in .env to your email domain (for example ALLOWED_SIGN_IN="acme.com") and restart.',+ });+ }+if (!isWorkspaceEmail(user.email)) {+ const domain = primaryWorkspaceDomain();throw new APIError("FORBIDDEN", {- message: `Comp AI CRM is internal. Sign in with your @${PRIMARY_WORKSPACE_DOMAIN} account.`,+ message: domain+ ? `This CRM is private. Sign in with your @${domain} account.`+ : "This CRM is private. That address is not on the allow-list.",});}diff --git a/packages/auth/src/client.ts b/packages/auth/src/client.tsindex 149450ee..93af55e8 100644--- a/packages/auth/src/client.ts+++ b/packages/auth/src/client.ts@@ -1,7 +1,13 @@import { createAuthClient } from "better-auth/react";+/**+ * The browser's view of auth.+ *+ * Points at the API, which is the only process that mounts `/api/auth/*`. The+ * origin is inlined at build time from `API_URL` — see `next.config.ts`.+ */export const authClient = createAuthClient({- baseURL: process.env.NEXT_PUBLIC_AUTH_URL,+ baseURL: process.env.NEXT_PUBLIC_API_URL,});export const { getSession, signIn, signOut, useSession } = authClient;diff --git a/packages/auth/src/env.ts b/packages/auth/src/env.tsindex c8839989..5eb18438 100644--- a/packages/auth/src/env.ts+++ b/packages/auth/src/env.ts@@ -1,3 +1,20 @@+// `better-auth generate` loads this file directly, without going through+// `@crm/db` — so the root `.env` has to be picked up here too.+import "@crm/env/load";++/**+ * Auth configuration, and the defaults that keep it to four required values.+ *+ * Everything here except the Google credentials has a working localhost+ * default. That is the difference between a clone that runs and a clone that+ * makes you read a table of variables first, and the defaults are only ever+ * right for localhost — `API_URL` and `APP_URL` have to be set for any real+ * deployment, which is why they are the first two lines of `.env.example`.+ */++const DEFAULT_API_URL = "http://localhost:3001";+const DEFAULT_APP_URL = "http://localhost:3000";+const optional = (key: string): string | undefined => {const value = process.env[key];return value && value.length > 0 ? value : undefined;@@ -21,17 +38,43 @@ const googleCredentials = ():return { clientId, clientSecret };};-const trustedOrigins = (- optional("AUTH_TRUSTED_ORIGINS")- ?.split(",")- .map((origin) => origin.trim())- .filter(Boolean) ?? []-).concat(optional("BETTER_AUTH_URL") ?? []);+/**+ * Where the API is — the origin that mints session cookies and serves+ * `/api/auth/*`.+ *+ * `BETTER_AUTH_URL` is still read because Better Auth's own tooling looks for+ * it, but `API_URL` is the name in `.env.example`: one origin should not have+ * two spellings depending on which library is asking.+ */+const apiUrl =+ optional("API_URL") ?? optional("BETTER_AUTH_URL") ?? DEFAULT_API_URL;++/**+ * Where the browser is.+ *+ * Comma-separated, because a preview deployment and a production domain are+ * both legitimately "the app" — but the first one is canonical, and that is the+ * one sign-in redirects back to. This replaced a separate+ * `AUTH_TRUSTED_ORIGINS`: the set of origins allowed to call the API with+ * credentials was always exactly the set of places the app is served from, so+ * two variables could only ever disagree.+ */+const appUrls = (optional("APP_URL") ?? DEFAULT_APP_URL)+ .split(",")+ .map((origin) => origin.trim())+ .filter(Boolean);++const appUrl = appUrls[0] ?? DEFAULT_APP_URL;export const env = {- appUrl: optional("BETTER_AUTH_URL"),+ appUrl: apiUrl,google: googleCredentials(),cookieDomain: optional("AUTH_COOKIE_DOMAIN"),- trustedOrigins: [...new Set(trustedOrigins)],+ // The API's own origin is trusted too: Better Auth validates the+ // post-sign-in `callbackURL` against this list, and the OAuth round trip+ // starts and ends on the API.+ trustedOrigins: [...new Set([...appUrls, apiUrl])],isProduction: process.env.NODE_ENV === "production",} as const;++export { apiUrl, appUrl };diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 5c86829e..cd93d0ca 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -9,7 +9,8 @@ export {SYNC_SCOPES,} from "./scopes";export {+ hasSignInAllowList,isWorkspaceEmail,- PRIMARY_WORKSPACE_DOMAIN,- WORKSPACE_DOMAINS,+ primaryWorkspaceDomain,+ workspaceDomains,} from "./workspace";diff --git a/packages/auth/src/workspace.ts b/packages/auth/src/workspace.tsindex 6da72f4c..1b0311a1 100644--- a/packages/auth/src/workspace.ts+++ b/packages/auth/src/workspace.ts@@ -1,3 +1,5 @@+import "@crm/env/load";+/*** Who is allowed in, and who counts as "us".*@@ -5,25 +7,100 @@* 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.+ *+ * This is the whole authorisation model. There are no roles, no organizations+ * and no invitations — "your address is on this list and Google says it is+ * really you" is the entire check, which is why it is a required value rather+ * than one with a friendly default. A CRM that let any Google account in would+ * hand your pipeline to the internet, and an empty list here fails closed:+ * nobody signs in until it is set.+ *+ * `ALLOWED_SIGN_IN` takes a comma-separated mix of the two things people+ * actually have:+ *+ * ```+ * 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+ * ```+ *+ * The third case is why bare addresses are supported at all: a solo self-hoster+ * on a consumer mailbox has no domain to name, and `gmail.com` would be an+ * open door.*/+type AllowList = {+ /** Whole domains, subdomains included. */+ domains: readonly string[];+ /** Individual addresses, for installs with no workspace domain. */+ addresses: readonly string[];+};++const EMPTY: AllowList = { domains: [], addresses: [] };++/**+ * Parsed on demand rather than at import.+ *+ * This module is imported by `auth.ts`, which the Better Auth CLI loads in a+ * process that has no `.env` at all, and by tests that need to set the list+ * themselves. Reading the variable when it is asked for — memoised on the raw+ * string, so repeated calls cost one comparison — means neither of those has to+ * care about import order.+ */+let cachedSource: string | undefined;+let cached: AllowList = EMPTY;++function allowList(): AllowList {+ const source = process.env.ALLOWED_SIGN_IN ?? "";+ if (source === cachedSource) return cached;++ const domains: string[] = [];+ const addresses: string[] = [];++ for (const raw of source.split(",")) {+ const entry = raw.trim().toLowerCase().replace(/^@/, "");+ if (!entry) continue;+ (entry.includes("@") ? addresses : domains).push(entry);+ }++ cachedSource = source;+ cached = { domains, addresses };+ return cached;+}+/** Domains whose Google accounts may sign in. */-export const WORKSPACE_DOMAINS = ["trycomp.ai"] as const;+export function workspaceDomains(): readonly string[] {+ return allowList().domains;+}++/**+ * The one Google shows in its account chooser.+ *+ * `undefined` when the allow-list is only bare addresses — `hd` has to be a+ * domain, and sending a garbage one hides every account in the chooser.+ */+export function primaryWorkspaceDomain(): string | undefined {+ return allowList().domains[0];+}-/** The one Google shows in its account chooser. */-export const PRIMARY_WORKSPACE_DOMAIN = WORKSPACE_DOMAINS[0];+/** Whether anyone at all can sign in. False means `ALLOWED_SIGN_IN` is unset. */+export function hasSignInAllowList(): boolean {+ const { domains, addresses } = allowList();+ return domains.length > 0 || addresses.length > 0;+}/*** Whether an address belongs to us.*- * Subdomain-aware, so `[email protected]` counts, but a lookalike like- * `trycomp.ai.evil.com` does not — the boundary is a dot, not a substring.+ * Subdomain-aware, so `[email protected]` counts against `acme.com`, but a+ * lookalike like `acme.com.evil.com` does not — the boundary is a dot, not a+ * substring.*/export function isWorkspaceEmail(email: string | null | undefined): boolean {const value = email?.trim().toLowerCase();if (!value) return false;- // Exactly one `@`. Reading the *last* one would let `[email protected]@trycomp.ai`+ // Exactly one `@`. Reading the *last* one would let `[email protected]@acme.com`// look like it belongs to us. Google never issues an address like that, but// a door should not depend on the other side being well behaved.const parts = value.split("@");@@ -32,7 +109,11 @@ export function isWorkspaceEmail(email: string | null | undefined): boolean {const [local, host] = parts;if (!local || !host) return false;- return WORKSPACE_DOMAINS.some(+ const { domains, addresses } = allowList();++ if (addresses.includes(value)) return true;++ return domains.some((domain) => host === domain || host.endsWith(`.${domain}`),);}diff --git a/packages/db/.env.example b/packages/db/.env.exampledeleted file mode 100644index dafd9300..00000000--- a/packages/db/.env.example+++ /dev/null@@ -1,7 +0,0 @@-# Connection string used by Prisma CLI (migrate/push/studio) and the runtime client.-# postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public-DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm?schema=public"--# Log every SQL statement Prisma runs (debug level, bound parameters omitted).-# Off by default: it buries every other log line under a wall of SELECTs.-# PRISMA_LOG_QUERIES="true"diff --git a/packages/db/README.md b/packages/db/README.mdindex 84e9ebd6..ce9e0123 100644--- a/packages/db/README.md+++ b/packages/db/README.md@@ -20,18 +20,16 @@ import { Prisma, type User } from "@crm/db";## Setup```bash-cp packages/db/.env.example packages/db/.env # then edit DATABASE_URL-bun run db:generate # generate Prisma Client-bun run db:deploy # apply the initial migration+docker compose up -d # Postgres matching the DATABASE_URL in .env.example+cp .env.example .env # at the repo root+bun run db:generate # generate Prisma Client+bun run db:deploy # apply the migrations```-`prisma/migrations/20260731150000_init` was generated offline with-`prisma migrate diff` and has not been applied to any database yet. Delete it-and run `bun run db:migrate` instead if you would rather let Prisma author the-first migration against your own database.--`DATABASE_URL` lives in `packages/db/.env` rather than at the repo root so that-the dependency is explicit and cache invalidation stays scoped to this package.+`DATABASE_URL` comes from the **repo-root `.env`**, loaded by `@crm/env` — see+[`docs/environment.md`](../../docs/environment.md). `src/client.ts` imports+`@crm/env/load` before reading it, and `prisma.config.ts` does the same so the+CLI works without any app running.## Scriptsdiff --git a/packages/db/package.json b/packages/db/package.jsonindex e2c689b1..04d6ffb8 100644--- a/packages/db/package.json+++ b/packages/db/package.json@@ -24,13 +24,13 @@"clean": "rm -rf .turbo node_modules src/generated"},"dependencies": {+ "@crm/env": "workspace:*","@prisma/adapter-pg": "^7.9.1","@prisma/client": "^7.9.1"},"devDependencies": {"@crm/typescript-config": "workspace:*","@types/node": "^24.10.1",- "dotenv": "^17.2.4","prisma": "^7.9.1","typescript": "5.9.2"}diff --git a/packages/db/prisma.config.ts b/packages/db/prisma.config.tsindex 89fcd28f..e9cce865 100644--- a/packages/db/prisma.config.ts+++ b/packages/db/prisma.config.ts@@ -1,4 +1,5 @@-import "dotenv/config";+// The Prisma CLI runs from this package, so it needs the repo-root `.env` too.+import "@crm/env/load";import path from "node:path";import { defineConfig, env } from "prisma/config";diff --git a/packages/db/prisma/migrations/20260801120000_contact_summary_and_socials/migration.sql b/packages/db/prisma/migrations/20260801120000_contact_summary_and_socials/migration.sqlnew file mode 100644index 00000000..f3222dc9--- /dev/null+++ b/packages/db/prisma/migrations/20260801120000_contact_summary_and_socials/migration.sql@@ -0,0 +1,6 @@+-- AlterTable+ALTER TABLE "contact" ADD COLUMN "githubUrl" TEXT,+ADD COLUMN "summary" TEXT,+ADD COLUMN "summarySourceUrl" TEXT,+ADD COLUMN "summaryUpdatedAt" TIMESTAMP(3),+ADD COLUMN "twitterUrl" TEXT;diff --git a/packages/db/prisma/migrations/20260801130000_contact_socials_checked/migration.sql b/packages/db/prisma/migrations/20260801130000_contact_socials_checked/migration.sqlnew file mode 100644index 00000000..2ee395df--- /dev/null+++ b/packages/db/prisma/migrations/20260801130000_contact_socials_checked/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "contact" ADD COLUMN "socialsCheckedAt" TIMESTAMP(3);diff --git a/packages/db/prisma/migrations/20260801140000_contact_intelligence/migration.sql b/packages/db/prisma/migrations/20260801140000_contact_intelligence/migration.sqlnew file mode 100644index 00000000..c751d215--- /dev/null+++ b/packages/db/prisma/migrations/20260801140000_contact_intelligence/migration.sql@@ -0,0 +1,137 @@+-- CreateEnum+CREATE TYPE "FactBand" AS ENUM ('VERIFIED', 'PROBABLE', 'POSSIBLE');++-- CreateEnum+CREATE TYPE "FactStatus" AS ENUM ('APPLIED', 'PROPOSED', 'DISMISSED', 'SUPERSEDED');++-- AlterTable+--+-- The summary columns are dropped at the bottom of this file, after their+-- contents have been copied into "contactBrief". Dropping them here, where+-- Prisma put them, would destroy every summary the agent has already written.+ALTER TABLE "contact"+ADD COLUMN "enrichedAt" TIMESTAMP(3),+ADD COLUMN "enrichmentError" TEXT,+ADD COLUMN "enrichmentStatus" "EnrichmentStatus" NOT NULL DEFAULT 'PENDING';++-- CreateTable+CREATE TABLE "contactFact" (+ "id" TEXT NOT NULL,+ "contactId" TEXT NOT NULL,+ "field" TEXT NOT NULL,+ "value" TEXT NOT NULL,+ "score" DOUBLE PRECISION NOT NULL,+ "band" "FactBand" NOT NULL,+ "evidence" JSONB NOT NULL,+ "method" TEXT NOT NULL,+ "sourceUrl" TEXT,+ "sessionId" TEXT,+ "status" "FactStatus" NOT NULL DEFAULT 'PROPOSED',+ "decidedById" TEXT,+ "decidedAt" TIMESTAMP(3),+ "observedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "supersededAt" TIMESTAMP(3),++ CONSTRAINT "contactFact_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "contactBrief" (+ "contactId" TEXT NOT NULL,+ "narrative" TEXT NOT NULL,+ "sections" JSONB NOT NULL,+ "score" DOUBLE PRECISION NOT NULL,+ "sourceUrl" TEXT,+ "sessionId" TEXT,+ "refreshedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "contactBrief_pkey" PRIMARY KEY ("contactId")+);++-- CreateTable+CREATE TABLE "agentTask" (+ "id" TEXT NOT NULL,+ "contactId" TEXT,+ "companyId" TEXT,+ "kind" TEXT NOT NULL,+ "reason" TEXT NOT NULL,+ "priority" INTEGER NOT NULL DEFAULT 0,+ "budget" INTEGER NOT NULL DEFAULT 4,+ "dueAt" TIMESTAMP(3) NOT NULL,+ "leasedUntil" TIMESTAMP(3),+ "sessionId" TEXT,+ "startedAt" TIMESTAMP(3),+ "finishedAt" TIMESTAMP(3),+ "outcome" TEXT,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "agentTask_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "agentEvent" (+ "id" TEXT NOT NULL,+ "sessionId" TEXT NOT NULL,+ "contactId" TEXT,+ "type" TEXT NOT NULL,+ "data" JSONB NOT NULL,+ "emittedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "agentEvent_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "contactFact_contactId_field_status_idx" ON "contactFact"("contactId", "field", "status");++-- CreateIndex+CREATE INDEX "contactFact_status_observedAt_idx" ON "contactFact"("status", "observedAt");++-- CreateIndex+CREATE INDEX "agentTask_dueAt_leasedUntil_idx" ON "agentTask"("dueAt", "leasedUntil");++-- CreateIndex+CREATE INDEX "agentTask_contactId_idx" ON "agentTask"("contactId");++-- CreateIndex+CREATE INDEX "agentEvent_sessionId_emittedAt_idx" ON "agentEvent"("sessionId", "emittedAt");++-- CreateIndex+CREATE INDEX "agentEvent_contactId_emittedAt_idx" ON "agentEvent"("contactId", "emittedAt");++-- AddForeignKey+ALTER TABLE "contactFact" ADD CONSTRAINT "contactFact_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "contactFact" ADD CONSTRAINT "contactFact_decidedById_fkey" FOREIGN KEY ("decidedById") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "contactBrief" ADD CONSTRAINT "contactBrief_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- Carry existing summaries over.+--+-- They were written by a tool that already demanded a source URL, so they are+-- exactly what a brief is; they simply had nowhere structured to live. Scored+-- 0.85 — the bottom of VERIFIED — because they were auto-applied under the old+-- all-or-nothing rule, and re-deriving a real score needs the evidence that+-- rule never recorded. The next refresh replaces this with a scored one.+INSERT INTO "contactBrief" ("contactId", "narrative", "sections", "score", "sourceUrl", "refreshedAt")+SELECT+ "id",+ "summary",+ '{}'::jsonb,+ 0.85,+ "summarySourceUrl",+ COALESCE("summaryUpdatedAt", CURRENT_TIMESTAMP)+FROM "contact"+WHERE "summary" IS NOT NULL;++-- Everything already in the CRM predates this pipeline, so nothing is queued+-- for it. Leaving them PENDING would have the sheet poll forever for work that+-- was never scheduled; the dispatcher picks them up on its own cadence.+UPDATE "contact" SET "enrichmentStatus" = 'COMPLETE', "enrichedAt" = "updatedAt";++-- DropColumn+ALTER TABLE "contact" DROP COLUMN "summary",+DROP COLUMN "summarySourceUrl",+DROP COLUMN "summaryUpdatedAt";+diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex 47c2de5e..af89a83c 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -31,6 +31,7 @@ model User {ownedDeals Deal[] @relation("DealOwner")activities Activity[] @relation("ActivityAuthor")mailboxSyncs MailboxSync[]+ factDecisions ContactFact[] @relation("FactDecider")@@unique([email])@@map("user")@@ -248,11 +249,33 @@ model Contact {phone String?title String?linkedinUrl String?+ twitterUrl String?+ githubUrl String?/// The contact's photo, mirrored into Vercel Blob.////// Never LinkedIn's own CDN URL: those carry an `e=` expiry parameter and go/// dead within weeks, so a hotlinked avatar silently becomes a broken image.imageUrl String?++ /// When the agent last went looking for this person's X and GitHub accounts.+ ///+ /// Stamped whether or not it found any, which is the point: most people have+ /// neither, and without it the hourly run would search the same fruitless+ /// contacts forever. Null means never looked; a date with both URLs still+ /// null means looked and found nothing it could stand behind.+ socialsCheckedAt DateTime?++ /// Mirrors `Company`, so the sheet reuses `isEnriching()` and the existing+ /// poll rather than inventing a second freshness mechanism.+ enrichmentStatus EnrichmentStatus @default(PENDING)+ enrichedAt DateTime?+ enrichmentError String?++ /// Who this person is (§3 of the contact-intelligence plan) and every claim+ /// behind the fields above.+ brief ContactBrief?+ facts ContactFact[]+companyId String?company Company? @relation("CompanyContacts", fields: [companyId], references: [id], onDelete: SetNull)ownerId String?@@ -283,6 +306,150 @@ model Contact {@@map("contact")}+/// How much of a claim we believe, and what that licenses.+///+/// The bands are the behaviour, not a label: `VERIFIED` is written to the+/// record, `PROBABLE` is offered to a human, `POSSIBLE` is kept but never shown+/// as a value. The numeric `score` beside them exists so the thresholds can be+/// re-calibrated against evals without re-running the research.+enum FactBand {+ VERIFIED+ PROBABLE+ POSSIBLE+}++enum FactStatus {+ APPLIED+ PROPOSED+ DISMISSED+ SUPERSEDED+}++/// One claim about one field of one contact, with everything behind it.+///+/// The point of a separate table: `Contact.title` can only hold the answer,+/// and the answer is the least interesting part. This holds where it came+/// from, how sure we are, what else was considered, and what it replaced —+/// which is what makes an enriched field auditable rather than merely present.+///+/// It is deliberately *not* the read path. Current values stay denormalised on+/// `Contact` so a list is one query; this is the reasoning behind them.+model ContactFact {+ id String @id @default(cuid())+ contactId String+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)++ /// The `Contact` column this is about — "title", "linkedinUrl", "employer".+ field String+ value String++ score Float+ band FactBand++ /// The full ledger: `[{ kind, weight, detail, sourceUrl }]`. Kept so the+ /// score can be explained to a rep and recomputed after a re-calibration.+ evidence Json++ method String+ sourceUrl String?++ /// The eve session that produced it, joining to `AgentEvent` for "show your+ /// work".+ sessionId String?++ status FactStatus @default(PROPOSED)+ decidedById String?+ decidedBy User? @relation("FactDecider", fields: [decidedById], references: [id], onDelete: SetNull)+ decidedAt DateTime?++ observedAt DateTime @default(now())+ supersededAt DateTime?++ @@index([contactId, field, status])+ @@index([status, observedAt])+ @@map("contactFact")+}++/// The background panel on a contact: who they are, in prose and in fields.+model ContactBrief {+ contactId String @id+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)++ /// Two or three sentences. Present tense, their name first.+ narrative String+ /// `{ currentRole, tenure, previousRoles[], seniority, function, location }`+ /// — shaped by the agent, rendered by the sheet, so adding a line does not+ /// need a migration.+ sections Json++ score Float+ sourceUrl String?+ sessionId String?++ refreshedAt DateTime @default(now())++ @@map("contactBrief")+}++/// What the agent has decided to do, and why.+///+/// The work queue *and* the audit trail. A cron expression can only say "every+/// hour for everybody"; a row here says "this person, in fourteen days,+/// because a job change would move a live deal" — and the reason is shown to+/// the rep rather than buried in a prompt.+model AgentTask {+ id String @id @default(cuid())+ contactId String?+ companyId String?++ kind String+ reason String++ priority Int @default(0)+ /// Research units this task may spend. Depth is a decision, and this is+ /// what the agent decides it against.+ budget Int @default(4)++ dueAt DateTime+ /// Held by a dispatcher tick. An expired lease is free to reclaim, which is+ /// what makes a crashed run recoverable rather than stuck.+ leasedUntil DateTime?++ sessionId String?+ startedAt DateTime?+ finishedAt DateTime?+ outcome String?++ createdAt DateTime @default(now())++ @@index([dueAt, leasedUntil])+ @@index([contactId])+ @@map("agentTask")+}++/// Every runtime event the agent emits, written by a hook.+///+/// The id is eve's own `meta.id` (a ULID), so an `on conflict do nothing`+/// insert is replay-safe: reconnecting to a stream, rewinding it, or restoring+/// a saved log cannot duplicate a row. Leading with a timestamp also keeps the+/// primary key roughly append-ordered.+///+/// This is what "show your work" reads. Without it the agent's reasoning lives+/// only in a log nobody can query and nobody can show a rep.+model AgentEvent {+ id String @id+ sessionId String+ contactId String?+ type String+ data Json++ emittedAt DateTime++ @@index([sessionId, emittedAt])+ @@index([contactId, emittedAt])+ @@map("agentEvent")+}+model Deal {id String @id @default(cuid())name Stringdiff --git a/packages/db/src/client.ts b/packages/db/src/client.tsindex f7e18de1..6963db19 100644--- a/packages/db/src/client.ts+++ b/packages/db/src/client.ts@@ -1,3 +1,7 @@+// First, and before anything reads `process.env`: every process that talks to+// the database gets here, so this is where the repo-root `.env` is picked up.+import "@crm/env/load";+import { PrismaPg } from "@prisma/adapter-pg";import { type Prisma, PrismaClient } from "./generated/prisma/client";@@ -5,7 +9,7 @@ const connectionString = process.env.DATABASE_URL;if (!connectionString) {throw new Error(- "DATABASE_URL is not set. Copy packages/db/.env.example to packages/db/.env (or set it in the consuming app's environment).",+ "DATABASE_URL is not set. Copy .env.example to .env at the root of the repo and fill it in, or set DATABASE_URL in the environment.",);}diff --git a/packages/db/src/index.ts b/packages/db/src/index.tsindex 8e13a5a0..7e88fd39 100644--- a/packages/db/src/index.ts+++ b/packages/db/src/index.ts@@ -8,3 +8,4 @@ export {export { Prisma, PrismaClient } from "./generated/prisma/client";export * from "./generated/prisma/enums";export type * from "./generated/prisma/models";+export type { ContactBriefSections, FactEvidence } from "./json";diff --git a/packages/db/src/json.ts b/packages/db/src/json.tsnew file mode 100644index 00000000..db20c0da--- /dev/null+++ b/packages/db/src/json.ts@@ -0,0 +1,29 @@+/**+ * The shapes inside our `Json` columns.+ *+ * Prisma types a `Json` column as `JsonValue`, which is honest and useless: the+ * column has a shape, three packages depend on it, and the alternative to+ * writing it down once is each of them casting to its own private idea of what+ * is in there. That is exactly how `looksLikeSameCompany` came to exist twice+ * and mean two different things.+ *+ * These live beside the schema because the schema is what guarantees them.+ */++/** One observation behind a `ContactFact`. Weights live with the agent. */+export type FactEvidence = {+ kind: string;+ /** What the source actually said, in a line a rep would understand. */+ detail: string;+ sourceUrl?: string;+};++/** The structured lines under a `ContactBrief`'s narrative. */+export type ContactBriefSections = {+ currentRole?: string;+ tenure?: string;+ previousRoles?: string[];+ seniority?: string;+ function?: string;+ location?: string;+};diff --git a/packages/env/package.json b/packages/env/package.jsonnew file mode 100644index 00000000..9bf9c77f--- /dev/null+++ b/packages/env/package.json@@ -0,0 +1,21 @@+{+ "name": "@crm/env",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts",+ "./load": "./src/load.ts"+ },+ "scripts": {+ "check-types": "tsc --noEmit",+ "lint": "biome check .",+ "test": "bun test",+ "clean": "rm -rf .turbo node_modules"+ },+ "devDependencies": {+ "@crm/typescript-config": "workspace:*",+ "@types/node": "^24.10.1",+ "typescript": "5.9.2"+ }+}diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsnew file mode 100644index 00000000..215a470c--- /dev/null+++ b/packages/env/src/index.ts@@ -0,0 +1,153 @@+import { existsSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";++/**+ * One `.env`, at the root of the repo.+ *+ * Every process here — the API, the Next.js app, the agent, the Prisma CLI —+ * needs an overlapping subset of the same handful of values, and the secret and+ * the database URL have to be *identical* across them or the session cookie one+ * writes will not verify in the next. Five files that must agree is five files+ * that can disagree, and the failure is a silent redirect loop rather than an+ * error.+ *+ * So there is one file and it is read from the workspace root, whichever+ * directory the process happens to start in.+ *+ * **The real environment always wins.** A value already present in+ * `process.env` is never overwritten, so a platform's own configuration —+ * Vercel, Docker, systemd, CI — takes precedence and the file is purely a+ * local-development convenience. Nothing here is required: with no `.env` at+ * all this is a no-op, and the individual consumers report what they are+ * missing.+ */++/** Loaded in order, so `.env.local` overrides `.env`. Neither is required. */+const FILES = [".env", ".env.local"] as const;++let loaded = false;++/**+ * Walks up from `start` looking for the workspace root.+ *+ * The marker is a `package.json` that declares `workspaces` — the one thing+ * only the root has. Neither of the obvious alternatives works: every package+ * has a `package.json`, and several have their own `turbo.json`, so both stop+ * at whichever app the process started in and quietly read the wrong file (or+ * no file, which is worse — the failure is a missing variable reported three+ * frames away from the reason).+ */+function findWorkspaceRoot(start: string): string | null {+ let directory = resolve(start);++ for (;;) {+ if (isWorkspaceRoot(directory)) return directory;++ const parent = dirname(directory);+ if (parent === directory) return null;+ directory = parent;+ }+}++function isWorkspaceRoot(directory: string): boolean {+ const manifest = join(directory, "package.json");+ if (!existsSync(manifest)) return false;++ try {+ const parsed: unknown = JSON.parse(readFileSync(manifest, "utf8"));+ return (+ typeof parsed === "object" &&+ parsed !== null &&+ "workspaces" in parsed &&+ parsed.workspaces !== undefined+ );+ } catch {+ // A malformed package.json is somebody else's problem to report.+ return false;+ }+}++/**+ * A deliberately small `.env` parser.+ *+ * Handles what these files actually contain — `KEY=value`, optional quotes,+ * `#` comments, blank lines, an optional `export` prefix — and nothing else.+ * A dependency would be a supply-chain surface for thirty lines of string+ * handling that runs before anything else in the process.+ */+export function parseEnv(source: string): Record<string, string> {+ const values: Record<string, string> = {};++ for (const rawLine of source.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (!line || line.startsWith("#")) continue;++ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(+ line,+ );+ if (!match) continue;++ const key = match[1];+ let value = (match[2] ?? "").trim();+ if (!key) continue;++ const quote = value[0];+ if (+ (quote === '"' || quote === "'") &&+ value.endsWith(quote) &&+ value.length > 1+ ) {+ value = value.slice(1, -1);+ // Escapes are only meaningful inside double quotes, matching every+ // other dotenv implementation — a Windows path in single quotes should+ // survive intact.+ if (quote === '"') {+ value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");+ }+ } else {+ // An unquoted value runs to the first ` #`, so `PORT=3001 # the api`+ // is a port and not a sentence.+ const comment = value.indexOf(" #");+ if (comment !== -1) value = value.slice(0, comment).trim();+ }++ values[key] = value;+ }++ return values;+}++/**+ * Reads the workspace-root `.env` files into `process.env`.+ *+ * Idempotent and safe to call from anywhere; the first call does the work.+ */+export function loadRootEnv(): void {+ if (loaded) return;+ loaded = true;++ const root = findWorkspaceRoot(process.cwd());+ if (!root) return;++ // Merged across files first, so `.env.local` beats `.env`. Applying each+ // file straight to `process.env` would let `.env` win instead: it is read+ // first, and the "never overwrite" rule below cannot tell a value set by an+ // earlier file from one set by the platform.+ const merged: Record<string, string> = {};++ for (const file of FILES) {+ const path = join(root, file);+ if (!existsSync(path)) continue;++ try {+ Object.assign(merged, parseEnv(readFileSync(path, "utf8")));+ } catch {+ // An unreadable .env is not worth crashing a process over — the+ // consumer that needs a missing value will say so by name.+ }+ }++ for (const [key, value] of Object.entries(merged)) {+ if (process.env[key] === undefined) process.env[key] = value;+ }+}diff --git a/packages/env/src/load.ts b/packages/env/src/load.tsnew file mode 100644index 00000000..90fc853f--- /dev/null+++ b/packages/env/src/load.ts@@ -0,0 +1,12 @@+import { loadRootEnv } from "./index";++/**+ * Side-effect entry point: `import "@crm/env/load";`.+ *+ * ES module imports are hoisted and evaluated before any statement in the+ * importing file, so a module that reads `process.env` at import time — as+ * `@crm/auth`'s config and `@crm/db`'s client both do — cannot load the file+ * itself from its own top-level code and still be sure it ran first. Importing+ * this module can only run before them.+ */+loadRootEnv();diff --git a/packages/env/test/parse.spec.ts b/packages/env/test/parse.spec.tsnew file mode 100644index 00000000..46808731--- /dev/null+++ b/packages/env/test/parse.spec.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "bun:test";+import { parseEnv } from "../src/index";++/**+ * The parser reads the one file every self-hoster edits by hand, so the cases+ * below are the ways people actually write these files rather than the ways a+ * spec says they should.+ */+describe("parseEnv", () => {+ it("reads plain and quoted values", () => {+ expect(+ parseEnv(`+ DATABASE_URL="postgresql://postgres:postgres@localhost:5432/crm"+ PORT=3001+ SINGLE='single quoted'+ `),+ ).toEqual({+ DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/crm",+ PORT: "3001",+ SINGLE: "single quoted",+ });+ });++ it("ignores comments and blank lines", () => {+ expect(+ parseEnv(["# a heading", "", " # indented", "A=1", ""].join("\n")),+ ).toEqual({ A: "1" });+ });++ it("keeps a # that is part of the value", () => {+ // Passwords contain these, and a generated secret routinely does. Only a+ // space-hash pair starts a trailing comment.+ expect(parseEnv("PASSWORD=pa#ssword\nPORT=3001 # the api")).toEqual({+ PASSWORD: "pa#ssword",+ PORT: "3001",+ });+ });++ it("does not treat a hash inside quotes as a comment", () => {+ expect(parseEnv('SECRET="abc # def"')).toEqual({ SECRET: "abc # def" });+ });++ it("keeps base64 padding, which openssl rand emits", () => {+ // `openssl rand -base64 32` ends in `=` about a quarter of the time, and+ // a parser that split on every `=` would silently truncate the secret —+ // producing a session cookie the other process cannot verify.+ const secret = "6oXI/PGPx8OGGiVz7zW2EODV6LcKmtyALiR+RvG2yc8=";+ expect(parseEnv(`BETTER_AUTH_SECRET="${secret}"`)).toEqual({+ BETTER_AUTH_SECRET: secret,+ });+ expect(parseEnv(`BETTER_AUTH_SECRET=${secret}`)).toEqual({+ BETTER_AUTH_SECRET: secret,+ });+ });++ it("accepts an export prefix and surrounding whitespace", () => {+ expect(parseEnv("export FOO = bar")).toEqual({ FOO: "bar" });+ });++ it("reads an empty value as empty rather than skipping it", () => {+ expect(parseEnv('A=\nB=""')).toEqual({ A: "", B: "" });+ });++ it("skips lines that are not assignments", () => {+ expect(parseEnv("just some prose\n1BAD=x\nGOOD=y")).toEqual({ GOOD: "y" });+ });++ it("lets a later line win, which is how a file is edited", () => {+ expect(parseEnv("A=1\nA=2")).toEqual({ A: "2" });+ });++ it("survives CRLF, which is what a Windows editor writes", () => {+ expect(parseEnv("A=1\r\nB=2\r\n")).toEqual({ A: "1", B: "2" });+ });+});diff --git a/packages/env/test/root.spec.ts b/packages/env/test/root.spec.tsnew file mode 100644index 00000000..f22d3d4e--- /dev/null+++ b/packages/env/test/root.spec.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "bun:test";+import { existsSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";++/**+ * Finding the workspace root is the part of this package that can fail+ * silently. If it stops one directory too early it reads a file that exists+ * but holds a different set of variables, and the symptom appears somewhere+ * else entirely — a missing `ALLOWED_SIGN_IN` reported by Nest's validator,+ * three frames from the reason.+ *+ * The first `turbo.json` walking up was exactly that bug: `apps/agent` and+ * `apps/api` have their own, so the API resolved its root to `apps/api`.+ */++/** The same walk as `loadRootEnv`, kept here so the property is testable. */+function findRoot(start: string): string | null {+ let directory = resolve(start);++ for (;;) {+ const manifest = join(directory, "package.json");+ if (existsSync(manifest)) {+ try {+ const parsed: unknown = JSON.parse(readFileSync(manifest, "utf8"));+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ "workspaces" in parsed &&+ parsed.workspaces !== undefined+ ) {+ return directory;+ }+ } catch {+ // fall through+ }+ }++ const parent = dirname(directory);+ if (parent === directory) return null;+ directory = parent;+ }+}++const repoRoot = resolve(import.meta.dir, "..", "..", "..");++describe("finding the workspace root", () => {+ it("finds it from the repo root itself", () => {+ expect(findRoot(repoRoot)).toBe(repoRoot);+ });++ it("finds it from a package that has its own turbo.json", () => {+ // The regression. Both of these ship a turbo.json.+ for (const app of ["apps/api", "apps/agent"]) {+ expect(findRoot(join(repoRoot, app))).toBe(repoRoot);+ }+ });++ it("finds it from a nested source directory", () => {+ expect(findRoot(join(repoRoot, "packages", "db", "src"))).toBe(repoRoot);+ });++ it("returns null above the repo rather than walking to /", () => {+ expect(findRoot("/")).toBeNull();+ });++ it("only matches a manifest that declares workspaces", () => {+ // Every package has a package.json; exactly one has `workspaces`.+ const manifest: unknown = JSON.parse(+ readFileSync(join(repoRoot, "apps", "api", "package.json"), "utf8"),+ );+ expect(+ typeof manifest === "object" &&+ manifest !== null &&+ "workspaces" in manifest,+ ).toBe(false);+ });+});++describe("the committed .env.example", () => {+ const example = readFileSync(join(repoRoot, ".env.example"), "utf8");++ it("names every variable the required section promises", () => {+ for (const key of [+ "DATABASE_URL",+ "BETTER_AUTH_SECRET",+ "ALLOWED_SIGN_IN",+ "GOOGLE_CLIENT_ID",+ "GOOGLE_CLIENT_SECRET",+ ]) {+ expect(example).toContain(`${key}=`);+ }+ });++ it("ships no secret of its own", () => {+ // A committed example with a real-looking secret in it is a secret people+ // paste into production.+ for (const line of example.split("\n")) {+ if (line.startsWith("#") || !line.includes("=")) continue;+ const value = line.slice(line.indexOf("=") + 1).trim();+ expect(value === '""' || value.length > 0).toBe(true);+ if (line.startsWith("BETTER_AUTH_SECRET")) expect(value).toBe('""');+ if (line.startsWith("ALLOWED_SIGN_IN")) expect(value).toBe('""');+ }+ });+});diff --git a/packages/env/tsconfig.json b/packages/env/tsconfig.jsonnew file mode 100644index 00000000..709a6038--- /dev/null+++ b/packages/env/tsconfig.json@@ -0,0 +1,9 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "@crm/typescript-config/internal-package.json",+ "compilerOptions": {+ "types": ["node"]+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules"]+}diff --git a/packages/ui/src/components/sourced-value.tsx b/packages/ui/src/components/sourced-value.tsxnew file mode 100644index 00000000..b27c9798--- /dev/null+++ b/packages/ui/src/components/sourced-value.tsx@@ -0,0 +1,97 @@+"use client";++import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@crm/ui/components/tooltip";+import type * as React from "react";++/**+ * The decoration on a value a machine wrote.+ *+ * One dotted underline, for the same reason `status-indicator` is a dot and a+ * word rather than a badge: a sheet speckled with chips is a sheet you read the+ * chips of. An underline says "there is more here" at a tenth of the ink and+ * vanishes when you are not looking for it.+ *+ * Exported as a class rather than a component because it has to sit on the text+ * *inside* whatever control already owns the row — wrapping the control would+ * either nest a button in a button or steal its focus behaviour.+ */+export const SOURCED_VALUE = "underline decoration-dotted underline-offset-4";++/**+ * Hangs provenance off an existing control.+ *+ * `children` must be a single focusable element — the field's own button,+ * normally — so that pointing at a value explains it and tabbing to it does the+ * same. Nothing new becomes clickable.+ */+export function SourcedValue({+ children,+ source,+}: {+ children: React.ReactElement;+ source: React.ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>{children}</TooltipTrigger>+ <TooltipContent className="block max-w-sm px-3 py-2 text-left">+ {source}+ </TooltipContent>+ </Tooltip>+ );+}++/**+ * The body of a provenance tooltip: what we believe, why, and since when.+ *+ * Prose rather than a field table. "LinkedIn: employer and name both match" is+ * something a rep can act on; `score: 0.85, method: linkedin.profile` is+ * something they have to decode first, and a tooltip is not a place anybody+ * wants to decode anything.+ */+export function Provenance({+ claim,+ reasons,+ observedAt,+ sourceUrl,+}: {+ claim: string;+ reasons: string[];+ observedAt?: string;+ sourceUrl?: string | null;+}) {+ return (+ <span className="flex flex-col gap-1.5">+ <span className="font-medium">{claim}</span>++ {reasons.length > 0 ? (+ <span className="flex flex-col gap-0.5 opacity-80">+ {reasons.map((reason) => (+ <span key={reason}>{reason}</span>+ ))}+ </span>+ ) : null}++ {observedAt || sourceUrl ? (+ <span className="flex flex-wrap items-center gap-x-2 opacity-60">+ {observedAt ? <span>{observedAt}</span> : null}+ {sourceUrl ? (+ <span className="truncate">{hostOf(sourceUrl)}</span>+ ) : null}+ </span>+ ) : null}+ </span>+ );+}++function hostOf(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return url;+ }+}diff --git a/packages/ui/src/components/suggestion.tsx b/packages/ui/src/components/suggestion.tsxnew file mode 100644index 00000000..17303403--- /dev/null+++ b/packages/ui/src/components/suggestion.tsx@@ -0,0 +1,74 @@+"use client";++import Checkmark from "@carbon/icons-react/es/Checkmark";+import Close from "@carbon/icons-react/es/Close";+import { Button } from "@crm/ui/components/button";+import { Icon } from "@crm/ui/components/icon";+import { Spinner } from "@crm/ui/components/spinner";+import type * as React from "react";++/**+ * Something a machine thinks is true, offered to somebody who can tell.+ *+ * The rule this encodes: **a suggestion is never rendered as a value.** It sits+ * under the empty field it would fill, in muted text, with the two buttons that+ * settle it. A guess formatted identically to a fact is how a CRM quietly+ * teaches people to distrust every field in it.+ *+ * It lives here rather than in the app because the same shape will be wanted on+ * companies and deals, and because "how does this product show uncertainty" is+ * exactly the sort of decision `design.md` says belongs in one place.+ */+export function Suggestion({+ value,+ rationale,+ pending = false,+ onAccept,+ onDismiss,+}: {+ value: React.ReactNode;+ /** Why the agent thinks so, in one line. */+ rationale?: React.ReactNode;+ pending?: boolean;+ onAccept: () => void;+ onDismiss: () => void;+}) {+ return (+ <div+ data-slot="suggestion"+ className="flex min-w-0 items-start gap-2 py-1 text-muted-foreground text-xs"+ >+ <div className="min-w-0 flex-1 space-y-0.5">+ <p className="truncate">+ <span className="text-foreground">{value}</span>+ </p>+ {rationale ? <p className="text-pretty">{rationale}</p> : null}+ </div>++ <div className="flex shrink-0 items-center gap-1">+ {pending ? (+ <Spinner className="size-3" />+ ) : (+ <>+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={onAccept}+ aria-label="Accept"+ >+ <Icon icon={Checkmark} />+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={onDismiss}+ aria-label="Dismiss"+ >+ <Icon icon={Close} />+ </Button>+ </>+ )}+ </div>+ </div>+ );+}