Skip to content

armgit / crm

Public Imported from GitHub
0

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

TypeScript

Add Gmail/Calendar sync, LinkedIn enrichment, and a research agent

Lewis Carhart9328239f7fb8
diff --git a/apps/agent/.gitignore b/apps/agent/.gitignore
new file mode 100644
index 00000000..4a559273
--- /dev/null
+++ b/apps/agent/.gitignore
@@ -0,0 +1,5 @@
+.eve/
+node_modules/
+.env
+.env.local
+.vercel
diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.ts
new file mode 100644
index 00000000..449c6501
--- /dev/null
+++ b/apps/agent/agent/agent.ts
@@ -0,0 +1,17 @@
+import { defineAgent } from "eve";
+
+/**
+ * The people-research agent.
+ *
+ * Sonnet rather than a frontier model: the hard part here is not reasoning, it
+ * is refusing to accept a plausible-looking wrong answer, and that is enforced
+ * by the tools and the skill rather than by model strength. Revisit if the
+ * 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.
+ */
+export default defineAgent({
+ model: "anthropic/claude-sonnet-5",
+});
diff --git a/apps/agent/agent/instructions.md b/apps/agent/agent/instructions.md
new file mode 100644
index 00000000..f0a115eb
--- /dev/null
+++ b/apps/agent/agent/instructions.md
@@ -0,0 +1,63 @@
+# 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.
+
+## 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.
+
+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.
+
+## How to identify somebody
+
+Load the `identity-matching` skill before your first match of a session. It has
+the procedure and the confidence bands. In short:
+
+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.
+
+Search results are not evidence. A search for "Abbie Bigham" once returned
+Lavazza's CEO. The search only tells you where to look.
+
+## Two sources, two jobs
+
+- **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.
+
+Use Perplexity for what a rep would want to know before a call, not to work out
+who somebody is.
+
+## Writing
+
+`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.
+
+Never overwrite a field a human has filled in. The tool enforces this; do not
+argue with it.
+
+## Tone for anything you write onto a timeline
+
+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.
diff --git a/apps/agent/agent/lib/crm.ts b/apps/agent/agent/lib/crm.ts
new file mode 100644
index 00000000..4b54fc06
--- /dev/null
+++ b/apps/agent/agent/lib/crm.ts
@@ -0,0 +1,176 @@
+import { db } from "@crm/db";
+import { domainOf, nameMatchesLocalPart } from "./names";
+
+/**
+ * The CRM, as far as this agent is concerned.
+ *
+ * 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.
+ */
+
+export type EnrichableContact = {
+ id: string;
+ email: string;
+ firstName: string;
+ lastName: string | null;
+ title: string | null;
+ companyName: string | null;
+ companyDomain: string | null;
+};
+
+/**
+ * Contacts worth spending a lookup on.
+ *
+ * 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.
+ */
+export async function contactsNeedingResearch(
+ limit: number,
+): Promise<EnrichableContact[]> {
+ const rows = await db.contact.findMany({
+ where: {
+ email: { not: null },
+ source: { in: ["EMAIL", "CALENDAR"] },
+ },
+ select: {
+ id: true,
+ email: true,
+ firstName: true,
+ lastName: true,
+ title: true,
+ company: { select: { name: true, domain: true } },
+ },
+ orderBy: { createdAt: "desc" },
+ take: limit * 4,
+ });
+
+ 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),
+ }));
+}
+
+export type ContactPatch = {
+ firstName?: string;
+ lastName?: string | null;
+ title?: string;
+ linkedinUrl?: string;
+};
+
+/**
+ * Applies a patch, refusing to overwrite anything a human filled in.
+ *
+ * Returns the fields it actually changed, so the agent is told what happened
+ * rather than assuming its write landed.
+ */
+export async function patchContact(
+ contactId: string,
+ patch: ContactPatch,
+): Promise<{ changed: string[] }> {
+ const current = await db.contact.findUnique({
+ where: { id: contactId },
+ select: {
+ email: true,
+ firstName: true,
+ lastName: true,
+ title: true,
+ linkedinUrl: 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 };
+}
+
+/** Writes a note onto the contact's timeline, stamped as agent-written. */
+export async function writeTimelineNote(
+ contactId: string,
+ subject: string,
+ body: string,
+ meta: Record<string, unknown> = {},
+): Promise<string | null> {
+ const contact = await db.contact.findUnique({
+ where: { id: contactId },
+ select: { companyId: true, ownerId: true },
+ });
+ if (!contact) return null;
+
+ // Activity.createdById is required. Attribute to the contact's owner, or to
+ // any user if the contact is unowned — the meta marks it as agent-written so
+ // the UI never claims a person typed it.
+ const author =
+ contact.ownerId ??
+ (await db.user.findFirst({ select: { id: true } }))?.id ??
+ null;
+ if (!author) return null;
+
+ const activity = await db.activity.create({
+ data: {
+ type: "NOTE",
+ subject,
+ body,
+ occurredAt: new Date(),
+ contactId,
+ companyId: contact.companyId,
+ createdById: author,
+ meta: { ...meta, agent: "people-research" },
+ },
+ select: { id: true },
+ });
+
+ return activity.id;
+}
diff --git a/apps/agent/agent/lib/linkdapi.ts b/apps/agent/agent/lib/linkdapi.ts
new file mode 100644
index 00000000..fdff05e9
--- /dev/null
+++ b/apps/agent/agent/lib/linkdapi.ts
@@ -0,0 +1,254 @@
+const HOST = "linkdapi-best-unofficial-linkedin-api.p.rapidapi.com";
+const TIMEOUT_MS = 20_000;
+
+/**
+ * LinkedIn data via LinkDAPI on RapidAPI.
+ *
+ * **There is deliberately no search function here.** LinkDAPI publishes no
+ * people-search endpoint, and the undocumented `/search/people?keywords=` path
+ * answers `HTTP 200` with entirely unrelated people — a query for "Abbie Bigham"
+ * returned Lavazza's CEO, and a different random set on the next call. Anything
+ * that looked like search here would be a well-typed way to file a stranger
+ * against a real customer. Finding the slug is Perplexity's job.
+ *
+ * Given a slug this API is excellent, so that is all it is asked to do.
+ */
+
+export type Profile = {
+ slug: string;
+ profileUrl: string;
+ fullName: string | null;
+ firstName: string | null;
+ lastName: string | null;
+ headline: string | null;
+ location: string | null;
+ /** Needed by every detail endpoint — they take `urn`, not `username`. */
+ urn: string | null;
+ followerCount: number | null;
+ connectionsCount: number | null;
+ /** Current employers. The job-change signal lives here. */
+ positions: { name: string; url: string | null }[];
+};
+
+export type Company = {
+ id: string | null;
+ name: string | null;
+ universalName: string | null;
+ tagline: string | null;
+ description: string | null;
+ linkedinUrl: string | null;
+};
+
+export type Experience = {
+ title: string | null;
+ company: string | null;
+ dateRange: string | null;
+ location: string | null;
+};
+
+type Outcome<T> =
+ | { ok: true; data: T }
+ | { ok: false; missing: true }
+ | { ok: false; missing: false; reason: string };
+
+function key(): string | null {
+ return process.env.RAPIDAPI_KEY ?? null;
+}
+
+export function linkedinEnabled(): boolean {
+ return key() !== null;
+}
+
+/** A profile by its `linkedin.com/in/<slug>` handle. */
+export async function getProfile(slug: string): Promise<Outcome<Profile>> {
+ const result = await call<RawProfile>("/api/v1/profile/overview", {
+ username: slug,
+ });
+ if (!result.ok) return result;
+
+ const d = result.data;
+ return {
+ ok: true,
+ data: {
+ slug,
+ profileUrl: `https://www.linkedin.com/in/${slug}`,
+ fullName: str(d.fullName),
+ firstName: str(d.firstName),
+ lastName: str(d.lastName),
+ headline: str(d.headline),
+ location: str(d.location),
+ urn: str(d.urn),
+ followerCount: int(d.followerCount),
+ connectionsCount: int(d.connectionsCount),
+ positions: (d.CurrentPositions ?? []).flatMap((p) =>
+ p?.name ? [{ name: p.name, url: str(p.url) }] : [],
+ ),
+ },
+ };
+}
+
+/** Full work history. Takes the `urn` from a profile, not the slug. */
+export async function getExperience(
+ urn: string,
+): Promise<Outcome<Experience[]>> {
+ const result = await call<RawExperience>("/api/v1/profile/full-experience", {
+ urn,
+ });
+ if (!result.ok) return result;
+
+ // The endpoint has been seen returning both a bare array and an object
+ // wrapping one, so both are accepted rather than trusting either.
+ const payload = result.data;
+ const rows: RawExperienceRow[] = Array.isArray(payload)
+ ? payload
+ : (payload.experience ?? payload.experiences ?? []);
+
+ return {
+ ok: true,
+ data: rows.map(
+ (row): Experience => ({
+ title: str(row?.title),
+ company: str(row?.companyName ?? row?.company),
+ dateRange: str(row?.dateRange ?? row?.duration),
+ location: str(row?.location),
+ }),
+ ),
+ };
+}
+
+/** Resolves a company name to LinkedIn's id. */
+export async function lookupCompany(
+ query: string,
+): Promise<Outcome<{ id: string; displayName: string }[]>> {
+ const result = await call<RawLookup>("/api/v1/companies/name-lookup", {
+ query,
+ });
+ if (!result.ok) return result;
+
+ return {
+ ok: true,
+ data: (result.data.companies ?? []).flatMap((c) =>
+ c?.id ? [{ id: c.id, displayName: c.displayName ?? c.id }] : [],
+ ),
+ };
+}
+
+/** Company detail. Takes `name` (the universal name) or `id`. */
+export async function getCompany(nameOrId: string): Promise<Outcome<Company>> {
+ const numeric = /^\d+$/.test(nameOrId);
+ const result = await call<RawCompany>("/api/v1/companies/company/info", {
+ [numeric ? "id" : "name"]: nameOrId,
+ });
+ if (!result.ok) return result;
+
+ const d = result.data;
+ return {
+ ok: true,
+ data: {
+ id: str(d.id),
+ name: str(d.name),
+ universalName: str(d.universalName),
+ tagline: str(d.tagline),
+ description: str(d.description),
+ linkedinUrl: str(d.linkedinUrl),
+ },
+ };
+}
+
+/**
+ * One call.
+ *
+ * LinkDAPI reports a failed lookup as `200 { success: false }` rather than a
+ * status code, so the envelope is what has to be read.
+ */
+async function call<T>(
+ path: string,
+ params: Record<string, string>,
+): Promise<Outcome<T>> {
+ const apiKey = key();
+ if (!apiKey) return { ok: false, missing: false, reason: "No RAPIDAPI_KEY." };
+
+ const url = new URL(`https://${HOST}${path}`);
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
+
+ try {
+ const response = await fetch(url, {
+ headers: { "x-rapidapi-host": HOST, "x-rapidapi-key": apiKey },
+ signal: controller.signal,
+ });
+
+ if (!response.ok) {
+ return { ok: false, missing: false, reason: `HTTP ${response.status}` };
+ }
+
+ const body = (await response.json()) as {
+ success?: boolean;
+ data?: T | null;
+ };
+
+ // "no such profile" is an ordinary answer, not something to retry.
+ if (body.success !== true || body.data == null) {
+ return { ok: false, missing: true };
+ }
+
+ return { ok: true, data: body.data };
+ } catch (error) {
+ const aborted = error instanceof Error && error.name === "AbortError";
+ return {
+ ok: false,
+ missing: false,
+ reason: aborted
+ ? `Timed out after ${TIMEOUT_MS}ms.`
+ : error instanceof Error
+ ? error.message
+ : String(error),
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+type RawProfile = {
+ fullName?: unknown;
+ firstName?: unknown;
+ lastName?: unknown;
+ headline?: unknown;
+ location?: unknown;
+ urn?: unknown;
+ followerCount?: unknown;
+ connectionsCount?: unknown;
+ CurrentPositions?: { name?: string; url?: unknown }[] | null;
+};
+
+type RawExperienceRow = {
+ title?: unknown;
+ companyName?: unknown;
+ company?: unknown;
+ dateRange?: unknown;
+ duration?: unknown;
+ location?: unknown;
+};
+
+type RawExperience =
+ | RawExperienceRow[]
+ | { experience?: RawExperienceRow[]; experiences?: RawExperienceRow[] };
+type RawLookup = { companies?: { id?: string; displayName?: string }[] | null };
+type RawCompany = {
+ id?: unknown;
+ name?: unknown;
+ universalName?: unknown;
+ tagline?: unknown;
+ description?: unknown;
+ linkedinUrl?: unknown;
+};
+
+function str(value: unknown): string | null {
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+function int(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
diff --git a/apps/agent/agent/lib/names.ts b/apps/agent/agent/lib/names.ts
new file mode 100644
index 00000000..4851857b
--- /dev/null
+++ b/apps/agent/agent/lib/names.ts
@@ -0,0 +1,127 @@
+/**
+ * Turning an email local part into something searchable, and checking the
+ * answer that comes back.
+ *
+ * All pure, and all verified against real CRM addresses rather than reasoned
+ * about: `[email protected]` → `bigham` → `linkedin.com/in/abigailbigham` →
+ * Abbie Bigham, Growth Specialist at HubSpot.
+ */
+
+/**
+ * Search terms for an email local part, most specific first.
+ *
+ * Searching the raw handle finds nothing — `abigham` is not a slug, a name or a
+ * word. Searching the surname it contains finds her on the first result.
+ *
+ * The split is generated blind and every candidate it produces is verified
+ * afterwards, 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);
+ };
+
+ // An explicit separator is 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);
+ }
+
+ add(handle);
+
+ // One token: try the surname left when a one- or two-letter initial comes off
+ // the front. This is the `abigham` → `bigham` step.
+ if (parts.length === 1) {
+ add(handle.slice(1));
+ add(handle.slice(2));
+ }
+
+ return terms;
+}
+
+/**
+ * Whether a LinkedIn employer is the company we think it is.
+ *
+ * Loose enough that "Valley Bank" matches a CRM company called "Valley", but
+ * anchored on containment rather than fuzzy distance — which would cheerfully
+ * 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 || (!b && !c)) return false;
+ return (
+ (b !== "" && (a === b || a.includes(b) || b.includes(a))) ||
+ (c !== "" && a.includes(c))
+ );
+}
+
+/**
+ * Whether a name is consistent with the address it was found from.
+ *
+ * The direction is the whole point: the name is checked against the local part,
+ * never derived from it. `ymadar` is consistent with Yael Madar (`y` + `madar`).
+ * It is not consistent with Antonio Baravalle, which is how a confident wrong
+ * answer from a search engine 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 a prefix of one —
+ // corporate directories truncate.
+ return forms.some(
+ (form) =>
+ form === handle || form.startsWith(handle) || handle.startsWith(form),
+ );
+}
+
+/** Splits a display name into first and last. */
+export function splitName(
+ fullName: string,
+): { firstName: string; lastName: string | null } | null {
+ const cleaned = fullName.trim().replace(/\s+/g, " ");
+ if (!cleaned) return null;
+
+ const [first, ...rest] = cleaned.split(" ");
+ if (!first) return null;
+
+ return { firstName: first, lastName: rest.length ? rest.join(" ") : null };
+}
+
+/** The domain part of an email, lowercased. */
+export function domainOf(email: string): string | null {
+ const at = email.lastIndexOf("@");
+ return at > 0 ? email.slice(at + 1).toLowerCase() : null;
+}
+
+function normalise(value: string): string {
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
+}
diff --git a/apps/agent/agent/lib/perplexity.ts b/apps/agent/agent/lib/perplexity.ts
new file mode 100644
index 00000000..38419772
--- /dev/null
+++ b/apps/agent/agent/lib/perplexity.ts
@@ -0,0 +1,137 @@
+const ENDPOINT = "https://api.perplexity.ai/chat/completions";
+const TIMEOUT_MS = 45_000;
+
+/**
+ * Perplexity, for the two things it is better at than anything else here:
+ * finding where a person lives on the web, and saying what has happened
+ * recently that a rep should know before a call.
+ *
+ * It is **not** the source of truth for identity. Asked for Abbie Bigham's job
+ * title it answered "Account Executive L3" while her own LinkedIn profile says
+ * "Growth Specialist at HubSpot" — an aggregator reconciling stale sources.
+ * LinkedIn is self-reported and wins on identity; Perplexity wins on context.
+ *
+ * Every answer carries its citations, and a claim without one does not get
+ * written to a record.
+ */
+
+export type Answer = {
+ text: string;
+ citations: string[];
+};
+
+type Outcome<T> = { ok: true; data: T } | { ok: false; reason: string };
+
+export function perplexityEnabled(): boolean {
+ return Boolean(process.env.PERPLEXITY_API_KEY);
+}
+
+export type AskOptions = {
+ /** `sonar` is fast and cited; `sonar-pro` reasons harder over more sources. */
+ model?: "sonar" | "sonar-pro";
+ /** Narrow the search, e.g. `["linkedin.com"]`. */
+ domains?: string[];
+ system?: string;
+};
+
+/** One grounded question. */
+export async function ask(
+ question: string,
+ options: AskOptions = {},
+): Promise<Outcome<Answer>> {
+ const apiKey = process.env.PERPLEXITY_API_KEY;
+ if (!apiKey) return { ok: false, reason: "No PERPLEXITY_API_KEY." };
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
+
+ try {
+ const response = await fetch(ENDPOINT, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ "content-type": "application/json",
+ },
+ signal: controller.signal,
+ body: JSON.stringify({
+ model: options.model ?? "sonar",
+ messages: [
+ ...(options.system
+ ? [{ role: "system", content: options.system }]
+ : []),
+ { role: "user", content: question },
+ ],
+ ...(options.domains ? { search_domain_filter: options.domains } : {}),
+ }),
+ });
+
+ if (!response.ok) {
+ return { ok: false, reason: `HTTP ${response.status}` };
+ }
+
+ const body = (await response.json()) as {
+ choices?: { message?: { content?: string } }[];
+ citations?: string[];
+ search_results?: { url?: string }[];
+ };
+
+ const text = body.choices?.[0]?.message?.content?.trim() ?? "";
+ if (!text) return { ok: false, reason: "Empty answer." };
+
+ // The field moved between API versions; read whichever is present rather
+ // than dropping citations on a version bump.
+ const citations =
+ body.citations ??
+ (body.search_results ?? []).flatMap((r) => (r.url ? [r.url] : []));
+
+ return { ok: true, data: { text, citations } };
+ } catch (error) {
+ const aborted = error instanceof Error && error.name === "AbortError";
+ return {
+ ok: false,
+ reason: aborted
+ ? `Timed out after ${TIMEOUT_MS}ms.`
+ : error instanceof Error
+ ? error.message
+ : String(error),
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * LinkedIn profile URLs for a person, from their email and employer.
+ *
+ * Restricted to linkedin.com so the answer is a set of URLs rather than prose,
+ * and the slugs are pulled out of the citations rather than out of the model's
+ * text — a cited URL was actually retrieved, a quoted one may not have been.
+ */
+export async function findProfileUrls(
+ terms: string[],
+ companyName: string,
+): Promise<string[]> {
+ const slugs: string[] = [];
+
+ for (const term of terms) {
+ const answer = await ask(
+ `Find the LinkedIn profile of the person called "${term}" who works at ${companyName}. Reply with their profile URL only.`,
+ { domains: ["linkedin.com"] },
+ );
+
+ if (!answer.ok) continue;
+
+ const haystack = [answer.data.text, ...answer.data.citations].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);
+ }
+
+ // The first term that produces anything is the most specific one.
+ if (slugs.length > 0) break;
+ }
+
+ return slugs;
+}
diff --git a/apps/agent/agent/schedules/research-new-contacts.ts b/apps/agent/agent/schedules/research-new-contacts.ts
new file mode 100644
index 00000000..cfcb3aad
--- /dev/null
+++ b/apps/agent/agent/schedules/research-new-contacts.ts
@@ -0,0 +1,33 @@
+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/identity-matching.md b/apps/agent/agent/skills/identity-matching.md
new file mode 100644
index 00000000..81179ea3
--- /dev/null
+++ b/apps/agent/agent/skills/identity-matching.md
@@ -0,0 +1,70 @@
+---
+name: identity-matching
+description: How to decide that a LinkedIn profile is the person behind a CRM email address, and when to refuse.
+---
+
+# Identity matching
+
+You are given an email address and a company. You need the person. Getting this
+wrong writes a stranger's career onto a customer's record, so the procedure is
+built to fail closed.
+
+## Why the obvious approach does not work
+
+`[email protected]` is not a name. Searching for it directly returns nothing.
+Asking a model what it stands for produces "Abbie Bigham" — which happens to be
+right, and would have been just as confident had it been wrong. You cannot tell
+the difference afterwards, which is why guessing is banned outright.
+
+What works is decomposition: `abigham` contains the surname `bigham`, and
+searching *that* alongside the company returns `linkedin.com/in/abigailbigham`
+as the first result. The guess went into the **query**, and the answer came from
+the profile.
+
+That is the shape of every match: guess where to look, never what you will find.
+
+## The procedure
+
+1. **`resolve_linkedin_profile`** with the email and company. It decomposes the
+ local part and returns candidate slugs. These are leads, not answers.
+2. **`get_linkedin_profile`** on each candidate, passing the email, company name
+ and domain. It returns the profile *and a verdict*.
+3. **Read the verdict, not the profile.** It checks two things:
+ - `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.
+
+## Confidence
+
+| Verdict | What it means | What to do |
+| --- | --- | --- |
+| `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. |
+
+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.
+
+## Things that look like evidence and are not
+
+- **A search result.** Search says where to look. A query for "Abbie Bigham"
+ once returned Lavazza's CEO, an HR lead at Reply, and a data engineer in
+ Seattle — all with total confidence.
+- **A matching first name.** Half the Chrises at a company are not your Chris.
+ The surname or the employer has to carry it.
+- **Perplexity's view of somebody's job title.** It aggregates stale sources; it
+ said "Account Executive L3" for a profile that reads "Growth Specialist at
+ HubSpot". For identity, the person's own profile wins.
+- **A very plausible expansion.** `jsmith` is probably J. Smith. Probably is not
+ a source.
+
+## When the person genuinely is not findable
+
+Some people have no profile, or a profile with no employer, or a name that
+cannot be reconciled with their address. Say so plainly and move on. A contact
+that keeps its placeholder name is a contact a human can fix in five seconds; a
+contact with the wrong person's job history is one nobody knows to fix.
diff --git a/apps/agent/agent/tools/get_linkedin_profile.ts b/apps/agent/agent/tools/get_linkedin_profile.ts
new file mode 100644
index 00000000..170c29fb
--- /dev/null
+++ b/apps/agent/agent/tools/get_linkedin_profile.ts
@@ -0,0 +1,62 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { getExperience, getProfile } from "../lib/linkdapi";
+import { looksLikeSameCompany, nameMatchesLocalPart } from "../lib/names";
+
+/**
+ * Reads a candidate and judges it, rather than handing the model a profile and
+ * hoping. The two checks are the thing standing between a search result and a
+ * customer record.
+ */
+export default defineTool({
+ description:
+ "Read a LinkedIn profile by slug and check whether it is really the person behind an email address. Returns the profile plus an explicit verdict.",
+ inputSchema: z.object({
+ slug: z.string().describe("The linkedin.com/in/<slug> handle."),
+ email: z.string().describe("The address we are trying to identify."),
+ companyName: z.string(),
+ companyDomain: z.string(),
+ includeHistory: z
+ .boolean()
+ .default(false)
+ .describe("Also fetch full work history — costs an extra call."),
+ }),
+ async execute({ slug, email, companyName, companyDomain, includeHistory }) {
+ const result = await getProfile(slug);
+ if (!result.ok) {
+ return result.missing
+ ? { found: false as const, reason: "No such profile." }
+ : { found: false as const, reason: result.reason };
+ }
+
+ const profile = result.data;
+ const local = email.split("@")[0] ?? "";
+
+ const employerMatches = profile.positions.some((position) =>
+ looksLikeSameCompany(position.name, companyName, companyDomain),
+ );
+ const nameMatches = nameMatchesLocalPart(profile, local);
+
+ const history =
+ includeHistory && profile.urn ? await getExperience(profile.urn) : null;
+
+ return {
+ found: true as const,
+ profile,
+ experience: history?.ok ? history.data : null,
+ verdict: {
+ employerMatches,
+ nameMatches,
+ // Both, or it is not them. Stated as a decision rather than as two
+ // facts so there is nothing to reinterpret.
+ isSamePerson: employerMatches && nameMatches,
+ confidence:
+ employerMatches && nameMatches
+ ? ("high" as const)
+ : employerMatches || nameMatches
+ ? ("medium" as const)
+ : ("low" as const),
+ },
+ };
+ },
+});
diff --git a/apps/agent/agent/tools/list_contacts_to_research.ts b/apps/agent/agent/tools/list_contacts_to_research.ts
new file mode 100644
index 00000000..73ea9001
--- /dev/null
+++ b/apps/agent/agent/tools/list_contacts_to_research.ts
@@ -0,0 +1,15 @@
+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/research_person.ts b/apps/agent/agent/tools/research_person.ts
new file mode 100644
index 00000000..81a0440c
--- /dev/null
+++ b/apps/agent/agent/tools/research_person.ts
@@ -0,0 +1,37 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { ask } from "../lib/perplexity";
+
+export default defineTool({
+ description:
+ "Research a person or company on the open web for sales context — recent news, funding, launches, public statements. Returns cited claims. NOT a source of truth for someone's identity or job title; use get_linkedin_profile for that.",
+ inputSchema: z.object({
+ question: z
+ .string()
+ .describe(
+ "A specific question, e.g. 'What has Acme announced in the last 6 months?'",
+ ),
+ deep: z
+ .boolean()
+ .default(false)
+ .describe("Reason over more sources. Slower, better for prep briefs."),
+ }),
+ async execute({ question, deep }) {
+ const answer = await ask(question, {
+ model: deep ? "sonar-pro" : "sonar",
+ system:
+ "You are researching for a B2B sales rep. Be specific and factual. " +
+ "State only what your sources support, prefer recent information, and " +
+ "say plainly when you do not know. Never speculate about a person.",
+ });
+
+ if (!answer.ok) return { ok: false as const, reason: answer.reason };
+
+ return {
+ ok: true as const,
+ answer: answer.data.text,
+ citations: answer.data.citations,
+ note: "Only write claims that have a citation.",
+ };
+ },
+});
diff --git a/apps/agent/agent/tools/resolve_linkedin_profile.ts b/apps/agent/agent/tools/resolve_linkedin_profile.ts
new file mode 100644
index 00000000..1dc06c93
--- /dev/null
+++ b/apps/agent/agent/tools/resolve_linkedin_profile.ts
@@ -0,0 +1,30 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { searchTerms } from "../lib/names";
+import { findProfileUrls } from "../lib/perplexity";
+
+/**
+ * Candidates, never an answer.
+ *
+ * The name is never taken from here — only the slug, which `get_linkedin_profile`
+ * then verifies. A search for "Abbie Bigham" has returned Lavazza's CEO.
+ */
+export default defineTool({
+ description:
+ "Find candidate LinkedIn profile slugs for a work email address. Returns CANDIDATES ONLY — you must verify each with get_linkedin_profile before believing any of them.",
+ inputSchema: z.object({
+ email: z.string().describe("The contact's work email address."),
+ companyName: z.string().describe("The company the CRM has them at."),
+ }),
+ async execute({ email, companyName }) {
+ const local = email.split("@")[0] ?? "";
+ const terms = searchTerms(local);
+ const slugs = await findProfileUrls(terms, companyName);
+
+ return {
+ searchedFor: terms,
+ candidateSlugs: slugs.slice(0, 5),
+ note: "Unverified. Each slug must be checked with get_linkedin_profile.",
+ };
+ },
+});
diff --git a/apps/agent/agent/tools/update_contact.ts b/apps/agent/agent/tools/update_contact.ts
new file mode 100644
index 00000000..873562d3
--- /dev/null
+++ b/apps/agent/agent/tools/update_contact.ts
@@ -0,0 +1,59 @@
+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_briefing.ts b/apps/agent/agent/tools/write_briefing.ts
new file mode 100644
index 00000000..af1c65d6
--- /dev/null
+++ b/apps/agent/agent/tools/write_briefing.ts
@@ -0,0 +1,20 @@
+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.json
new file mode 100644
index 00000000..4ff2e121
--- /dev/null
+++ b/apps/agent/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "agent",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "license": "UNLICENSED",
+ "scripts": {
+ "dev": "eve dev",
+ "build": "eve build",
+ "start": "eve start",
+ "check-types": "tsc --noEmit",
+ "lint": "biome check .",
+ "clean": "rm -rf .turbo .eve node_modules"
+ },
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "eve": "^0.29.4",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.0.0",
+ "typescript": "^5.9.2"
+ }
+}
diff --git a/apps/agent/tsconfig.json b/apps/agent/tsconfig.json
new file mode 100644
index 00000000..14ff6177
--- /dev/null
+++ b/apps/agent/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "extends": "@crm/typescript-config/base.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "module": "preserve",
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "types": ["node"]
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts"],
+ "exclude": ["node_modules", ".eve"]
+}
diff --git a/apps/agent/turbo.json b/apps/agent/turbo.json
new file mode 100644
index 00000000..ae1bcb2c
--- /dev/null
+++ b/apps/agent/turbo.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://turborepo.dev/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ "build": { "dependsOn": ["^build"], "outputs": [".eve/**"] },
+ "check-types": { "dependsOn": ["topo", "^build"] },
+ "dev": {
+ "cache": false,
+ "persistent": true,
+ "passThroughEnv": [
+ "DATABASE_URL",
+ "RAPIDAPI_KEY",
+ "PERPLEXITY_API_KEY",
+ "AI_GATEWAY_API_KEY"
+ ]
+ }
+ }
+}
diff --git a/apps/api/README.md b/apps/api/README.md
index 0895253b..f988cc44 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -29,6 +29,7 @@ used for type checking only (`bun run check-types`).
| `/auth/me` | required | Cached profile of the signed-in user |
| `/auth/session` | optional | Whether the caller is signed in |
| `/health` | anonymous | 200 with a database round-trip, 503 otherwise |
+| `/internal/sync/google` | `CRON_SECRET` bearer | Vercel Cron entrypoint for Gmail/Calendar sync. Fails closed when the secret is unset. |
## How auth is wired
diff --git a/apps/api/scripts/backfill-icon-tone.ts b/apps/api/scripts/backfill-icon-tone.ts
new file mode 100644
index 00000000..ecd43096
--- /dev/null
+++ b/apps/api/scripts/backfill-icon-tone.ts
@@ -0,0 +1,72 @@
+import { db } from "@crm/db";
+import { brandToUpdate } from "../src/enrichment/brand-mapping";
+
+/**
+ * Fills `iconDarkUrl` and `iconTone` from the Context.dev payloads we already
+ * stored.
+ *
+ * The whole point of keeping `CompanyEnrichment.raw` was that deriving a new
+ * field later should cost nothing and no credits — this is that promise being
+ * collected. Re-running is safe: `brandToUpdate` only fills fields that are
+ * currently empty, so a value a human has since corrected is left alone.
+ *
+ * bun run scripts/backfill-icon-tone.ts
+ */
+const rows = await db.companyEnrichment.findMany({
+ select: {
+ companyId: true,
+ raw: true,
+ company: {
+ select: {
+ name: 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,
+ },
+ },
+ },
+});
+
+let updated = 0;
+
+for (const row of rows) {
+ const brand = (row.raw as { brand?: unknown } | null)?.brand;
+ if (!brand) continue;
+
+ const update = brandToUpdate(brand as never, {
+ ...row.company,
+ nameIsPlaceholder: false,
+ });
+
+ // Only the two new fields — this script is not a re-enrichment.
+ const patch = {
+ ...(update.iconDarkUrl ? { iconDarkUrl: update.iconDarkUrl } : {}),
+ ...(update.iconTone ? { iconTone: update.iconTone } : {}),
+ };
+
+ if (Object.keys(patch).length === 0) continue;
+
+ await db.company.update({ where: { id: row.companyId }, data: patch });
+ updated += 1;
+ console.log(`${row.company.name}: ${JSON.stringify(patch)}`);
+}
+
+console.log(`\nUpdated ${updated} of ${rows.length} enriched companies.`);
+await db.$disconnect();
diff --git a/apps/api/scripts/build-func.mjs b/apps/api/scripts/build-func.mjs
index 3dc90569..972a63a1 100644
--- a/apps/api/scripts/build-func.mjs
+++ b/apps/api/scripts/build-func.mjs
@@ -76,7 +76,11 @@ execSync(
// bundle as a literal. Built without this, it folds to `false`, Better Auth
// drops the `__Secure-` cookie prefix, the app's proxy looks for the
// prefixed name over HTTPS and bounces every signed-in user to /sign-in.
- { cwd: apiDir, stdio: "inherit", env: { ...process.env, NODE_ENV: "production" } },
+ {
+ cwd: apiDir,
+ stdio: "inherit",
+ env: { ...process.env, NODE_ENV: "production" },
+ },
);
/**
@@ -183,7 +187,10 @@ for (const root of VENDOR_ROOTS) {
}
console.log(` vendored ${vendorCount} packages`);
-writeFileSync(join(funcDir, "package.json"), JSON.stringify({ type: "module" }));
+writeFileSync(
+ join(funcDir, "package.json"),
+ JSON.stringify({ type: "module" }),
+);
writeFileSync(
join(funcDir, ".vc-config.json"),
JSON.stringify({
diff --git a/apps/api/src/activities/activities.contracts.ts b/apps/api/src/activities/activities.contracts.ts
index bbd8dae2..f7b2fbd7 100644
--- a/apps/api/src/activities/activities.contracts.ts
+++ b/apps/api/src/activities/activities.contracts.ts
@@ -26,6 +26,10 @@ const TIMELINE_FILTERS = [
"notes",
"upcoming",
"done",
+ /** Synced Gmail threads and logged emails. */
+ "email",
+ /** Synced calendar events and logged meetings. */
+ "meetings",
] as const;
export type TimelineFilter = (typeof TIMELINE_FILTERS)[number];
diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts
index 22cfc406..4bef31a3 100644
--- a/apps/api/src/activities/activities.service.ts
+++ b/apps/api/src/activities/activities.service.ts
@@ -5,6 +5,7 @@ import {
Logger,
NotFoundException,
} from "@nestjs/common";
+import { ActivityStampService } from "../crm/activity-stamp.service";
import { blankToNull } from "../crm/values";
import { InjectDatabase } from "../database/database.constants";
import type {
@@ -35,6 +36,27 @@ const ENTRY_SELECT = {
company: { select: { id: true, name: true } },
contact: { select: { id: true, firstName: true, lastName: true } },
deal: { select: { id: true, name: true } },
+
+ // Summaries only. An email body never rides on a list payload — the row
+ // carries a snippet, and the accordion fetches `google.thread` on expand.
+ emailThread: {
+ select: {
+ id: true,
+ messageCount: true,
+ lastMessageAt: true,
+ },
+ },
+ calendarEvent: {
+ select: {
+ id: true,
+ startsAt: true,
+ endsAt: true,
+ isAllDay: true,
+ location: true,
+ conferenceUrl: true,
+ _count: { select: { attendees: true } },
+ },
+ },
} as const;
/** Entries a `NOTE`-ish filter should keep — what someone wrote down. */
@@ -49,7 +71,10 @@ const NOTE_TYPES = [
export class ActivitiesService {
private readonly logger = new Logger(ActivitiesService.name);
- constructor(@InjectDatabase() private readonly db: Db) {}
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly stamp: ActivityStampService,
+ ) {}
/**
* A record's timeline, newest first, paged by cursor.
@@ -68,7 +93,16 @@ export class ActivitiesService {
// without a second count query.
take: input.limit + 1,
...(input.cursor ? { cursor: { id: input.cursor }, skip: 1 } : {}),
- orderBy: [{ createdAt: "desc" }, { id: "desc" }],
+ // By when it *happened*, not when the row was written. Those were the
+ // same thing while a human logged everything by hand, and stopped being
+ // the same thing the moment a sync started writing: a first sync stamps
+ // every thread and meeting with roughly one `createdAt`, so ordering by
+ // it would jumble a year of history into one arbitrary block. `id` breaks
+ // ties so the cursor stays deterministic.
+ orderBy: [
+ { occurredAt: { sort: "desc", nulls: "last" } },
+ { id: "desc" },
+ ],
select: ENTRY_SELECT,
});
@@ -91,7 +125,7 @@ export class ActivitiesService {
) {
const anchor = this.anchor(input);
- const [all, notes, upcoming, done] = await Promise.all([
+ const [all, notes, upcoming, done, email, meetings] = await Promise.all([
this.db.activity.count({ where: anchor }),
this.db.activity.count({
where: { ...anchor, ...filterClause("notes") },
@@ -100,9 +134,15 @@ export class ActivitiesService {
where: { ...anchor, ...filterClause("upcoming") },
}),
this.db.activity.count({ where: { ...anchor, ...filterClause("done") } }),
+ this.db.activity.count({
+ where: { ...anchor, ...filterClause("email") },
+ }),
+ this.db.activity.count({
+ where: { ...anchor, ...filterClause("meetings") },
+ }),
]);
- return { all, notes, upcoming, done };
+ return { all, notes, upcoming, done, email, meetings };
}
async create(input: ActivityCreateInput, actingUserId: string) {
@@ -129,6 +169,11 @@ export class ActivitiesService {
select: ENTRY_SELECT,
});
+ await this.stamp.touch(
+ { companyId, contactId: input.contactId, dealId: input.dealId },
+ activity.createdAt,
+ );
+
this.logger.log({
message: "Activity logged",
activityId: activity.id,
@@ -252,6 +297,13 @@ function filterClause(filter: TimelineFilter): Prisma.ActivityWhereInput {
return { type: ActivityType.TASK, completedAt: { not: null } };
case "history":
return { NOT: { type: ActivityType.TASK, completedAt: null } };
+ // Both cover what a rep logged by hand *and* what the Google sync
+ // projected — from the timeline's point of view they are the same event,
+ // and splitting them would make "did we email them?" two questions.
+ case "email":
+ return { type: ActivityType.EMAIL };
+ case "meetings":
+ return { type: ActivityType.MEETING };
case "all":
return {};
}
@@ -268,6 +320,26 @@ function serializeEntry(entry: Entry) {
completedAt: entry.completedAt?.toISOString() ?? null,
createdAt: entry.createdAt.toISOString(),
meta: entry.meta as Record<string, unknown> | null,
+
+ emailThread: entry.emailThread
+ ? {
+ id: entry.emailThread.id,
+ messageCount: entry.emailThread.messageCount,
+ lastMessageAt: entry.emailThread.lastMessageAt.toISOString(),
+ }
+ : null,
+
+ calendarEvent: entry.calendarEvent
+ ? {
+ id: entry.calendarEvent.id,
+ startsAt: entry.calendarEvent.startsAt.toISOString(),
+ endsAt: entry.calendarEvent.endsAt.toISOString(),
+ isAllDay: entry.calendarEvent.isAllDay,
+ location: entry.calendarEvent.location,
+ conferenceUrl: entry.calendarEvent.conferenceUrl,
+ attendeeCount: entry.calendarEvent._count.attendees,
+ }
+ : null,
};
}
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts
index 70b92541..3fdef409 100644
--- a/apps/api/src/app.module.ts
+++ b/apps/api/src/app.module.ts
@@ -8,9 +8,11 @@ import { AppCacheModule } from "./cache/cache.module";
import { CompaniesModule } from "./companies/companies.module";
import { validateEnv } from "./config/env.validation";
import { ContactsModule } from "./contacts/contacts.module";
+import { CrmModule } from "./crm/crm.module";
import { DashboardModule } from "./dashboard/dashboard.module";
import { DatabaseModule } from "./database/database.module";
import { DealsModule } from "./deals/deals.module";
+import { GoogleModule } from "./google/google.module";
import { HealthModule } from "./health/health.module";
import { LoggingModule } from "./logging/logging.module";
import { logAuthRoute } from "./logging/request-logger.middleware";
@@ -28,6 +30,7 @@ import { UsersModule } from "./users/users.module";
}),
AppCacheModule,
DatabaseModule,
+ CrmModule,
BetterAuthModule.forRoot({ auth, middleware: logAuthRoute }),
AuthModule,
HealthModule,
@@ -39,6 +42,7 @@ import { UsersModule } from "./users/users.module";
ActivitiesModule,
DashboardModule,
SearchModule,
+ GoogleModule,
],
})
export class AppModule {}
diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.ts
index 5ad00b5b..10876b89 100644
--- a/apps/api/src/companies/companies.contracts.ts
+++ b/apps/api/src/companies/companies.contracts.ts
@@ -13,6 +13,13 @@ export const companyListInput = listInput.extend({
industry: z.string().default("all"),
/** An `EnrichmentStatus`, or `"all"`. */
enrichment: z.string().default("all"),
+ /**
+ * A `RecordSource`, or `"all"`.
+ *
+ * What makes an auto-create rule reversible: filter to `EMAIL`, see exactly
+ * what the sync decided, and delete the lot if it got it wrong.
+ */
+ source: z.string().default("all"),
});
export type CompanyListInput = z.infer<typeof companyListInput>;
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 33b18612..771f1125 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -3,6 +3,7 @@ import {
type EnrichmentStatus,
type Prisma,
Prisma as PrismaNamespace,
+ type RecordSource,
} from "@crm/db";
import {
BadRequestException,
@@ -44,10 +45,13 @@ export type CompanyRow = {
name: string;
domain: string | null;
iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
logoUrl: string | null;
brandColor: string | null;
industry: string | null;
enrichmentStatus: EnrichmentStatus;
+ source: RecordSource;
owner: {
id: string;
name: string;
@@ -58,6 +62,7 @@ export type CompanyRow = {
openDealCount: number;
/** ISO-8601, or null when nothing has happened yet. */
lastActivityAt: string | null;
+ createdAt: string;
};
/**
@@ -66,10 +71,6 @@ export type CompanyRow = {
* Spelled out rather than derived from the column id so `?sort=` can never
* reach Prisma as an arbitrary field name — and because ordering by a relation
* count is not a flat `{ [id]: dir }`.
- *
- * Contacts and open deals sort by relation count, which Prisma can do. Last
- * activity cannot: ordering by `max(activity.createdAt)` is an aggregate over a
- * relation, which has no Prisma ordering, so that column is display-only.
*/
const SORTABLE: Record<
string,
@@ -81,6 +82,12 @@ const SORTABLE: Record<
createdAt: (dir) => ({ createdAt: dir }),
contacts: (dir) => ({ contacts: { _count: dir } }),
deals: (dir) => ({ deals: { _count: dir } }),
+ // By the owner's name, not their id — nobody scans a list of cuids.
+ // Unassigned rows sort last either way: they are the least interesting.
+ owner: (dir) => ({ owner: { name: dir } }),
+ // A real column, so this is an index scan. Never-touched rows sort last in
+ // both directions, because "no activity" is not "the oldest activity".
+ lastActivity: (dir) => ({ lastActivityAt: { sort: dir, nulls: "last" } }),
};
@Injectable()
@@ -101,16 +108,21 @@ export class CompaniesService {
where,
skip,
take,
- orderBy: resolveOrderBy(input, SORTABLE, { name: "asc" }),
+ orderBy: resolveOrderBy(input, SORTABLE, {
+ createdAt: "desc",
+ }),
select: {
id: true,
name: true,
domain: true,
iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
logoUrl: true,
brandColor: true,
industry: true,
enrichmentStatus: true,
+ source: true,
owner: { select: OWNER_SELECT },
_count: {
select: {
@@ -118,14 +130,8 @@ export class CompaniesService {
deals: { where: { stage: { in: [...OPEN_DEAL_STAGES] } } },
},
},
- // One row per company via a lateral join — cheap at a page of 25,
- // and the only way to get "last activity" without an aggregate
- // Prisma cannot express.
- activities: {
- take: 1,
- orderBy: { createdAt: "desc" },
- select: { createdAt: true },
- },
+ lastActivityAt: true,
+ createdAt: true,
},
}),
this.db.company.count({ where }),
@@ -138,14 +144,18 @@ export class CompaniesService {
name: row.name,
domain: row.domain,
iconUrl: row.iconUrl,
+ iconDarkUrl: row.iconDarkUrl,
+ iconTone: row.iconTone,
logoUrl: row.logoUrl,
brandColor: row.brandColor,
industry: row.industry,
enrichmentStatus: row.enrichmentStatus,
+ source: row.source,
owner: row.owner,
contactCount: row._count.contacts,
openDealCount: row._count.deals,
- lastActivityAt: row.activities[0]?.createdAt.toISOString() ?? null,
+ lastActivityAt: row.lastActivityAt?.toISOString() ?? null,
+ createdAt: row.createdAt.toISOString(),
})),
total,
facetCounts,
@@ -164,6 +174,8 @@ export class CompaniesService {
logoUrl: true,
logoDarkUrl: true,
iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
brandColor: true,
industry: true,
subIndustry: true,
@@ -181,6 +193,7 @@ export class CompaniesService {
enrichmentStatus: true,
enrichedAt: true,
enrichmentError: true,
+ source: true,
createdAt: true,
owner: { select: OWNER_SELECT },
primaryContact: {
@@ -445,6 +458,10 @@ export class CompaniesService {
where.enrichmentStatus = input.enrichment as EnrichmentStatus;
}
+ if (input.source !== FACET_ALL) {
+ where.source = input.source as RecordSource;
+ }
+
return where;
}
@@ -458,7 +475,7 @@ export class CompaniesService {
private async facetCounts(input: CompanyListInput) {
const where = this.searchFilter(input.q);
- const [owners, industries, enrichment] = await Promise.all([
+ const [owners, industries, enrichment, sources] = await Promise.all([
this.db.company.groupBy({
by: ["ownerId"],
where,
@@ -474,12 +491,18 @@ export class CompaniesService {
where,
_count: { _all: true },
}),
+ this.db.company.groupBy({
+ by: ["source"],
+ where,
+ _count: { _all: true },
+ }),
]);
return {
owner: countsByKey(owners, "ownerId", FACET_UNASSIGNED),
industry: countsByKey(industries, "industry"),
enrichment: countsByKey(enrichment, "enrichmentStatus"),
+ source: countsByKey(sources, "source"),
};
}
diff --git a/apps/api/src/config/env.validation.ts b/apps/api/src/config/env.validation.ts
index f5ed930d..20ca9882 100644
--- a/apps/api/src/config/env.validation.ts
+++ b/apps/api/src/config/env.validation.ts
@@ -82,6 +82,29 @@ export class EnvironmentVariables {
@IsInt()
@Min(0)
CACHE_TTL_MS?: number;
+
+ /**
+ * 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.
+ */
+ @IsOptional()
+ @IsString()
+ @MinLength(16, {
+ 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(
diff --git a/apps/api/src/contacts/contacts.contracts.ts b/apps/api/src/contacts/contacts.contracts.ts
index 098a484b..94a02549 100644
--- a/apps/api/src/contacts/contacts.contracts.ts
+++ b/apps/api/src/contacts/contacts.contracts.ts
@@ -6,6 +6,8 @@ export const contactListInput = listInput.extend({
owner: z.string().default("all"),
/** A company id, `"none"`, or `"all"`. */
company: z.string().default("all"),
+ /** A `RecordSource`, or `"all"` — how a bad auto-create rule gets undone. */
+ source: z.string().default("all"),
});
export type ContactListInput = z.infer<typeof contactListInput>;
diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.ts
index 693e03b8..674fcc7f 100644
--- a/apps/api/src/contacts/contacts.service.ts
+++ b/apps/api/src/contacts/contacts.service.ts
@@ -1,4 +1,9 @@
-import { type Db, type Prisma, Prisma as PrismaNamespace } from "@crm/db";
+import {
+ type Db,
+ type Prisma,
+ Prisma as PrismaNamespace,
+ type RecordSource,
+} from "@crm/db";
import {
ConflictException,
Injectable,
@@ -35,6 +40,8 @@ const COMPANY_SELECT = {
name: true,
domain: true,
iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
logoUrl: true,
} as const;
@@ -52,6 +59,8 @@ export type ContactRow = {
name: string;
domain: string | null;
iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
logoUrl: string | null;
} | null;
owner: {
@@ -61,6 +70,7 @@ export type ContactRow = {
image: string | null;
} | null;
lastActivityAt: string | null;
+ createdAt: string;
};
/**
@@ -79,6 +89,8 @@ const SORTABLE: Record<
title: (dir) => [{ title: dir }, { lastName: "asc" }],
company: (dir) => [{ company: { name: dir } }, { lastName: "asc" }],
createdAt: (dir) => [{ createdAt: dir }],
+ owner: (dir) => [{ owner: { name: dir } }, { lastName: "asc" }],
+ lastActivity: (dir) => [{ lastActivityAt: { sort: dir, nulls: "last" } }],
};
@Injectable()
@@ -99,23 +111,18 @@ export class ContactsService {
where,
skip,
take,
- orderBy: resolveOrderBy(input, SORTABLE, [
- { lastName: "asc" },
- { firstName: "asc" },
- ]),
+ orderBy: resolveOrderBy(input, SORTABLE, [{ createdAt: "desc" }]),
select: {
id: true,
firstName: true,
lastName: true,
email: true,
title: true,
+ source: true,
company: { select: COMPANY_SELECT },
owner: { select: OWNER_SELECT },
- activities: {
- take: 1,
- orderBy: { createdAt: "desc" },
- select: { createdAt: true },
- },
+ lastActivityAt: true,
+ createdAt: true,
},
}),
this.db.contact.count({ where }),
@@ -123,9 +130,10 @@ export class ContactsService {
]);
return {
- rows: rows.map(({ activities, ...row }) => ({
+ rows: rows.map((row) => ({
...row,
- lastActivityAt: activities[0]?.createdAt.toISOString() ?? null,
+ lastActivityAt: row.lastActivityAt?.toISOString() ?? null,
+ createdAt: row.createdAt.toISOString(),
})),
total,
facetCounts,
@@ -209,7 +217,13 @@ export class ContactsService {
// the right company, not attach itself a few seconds later.
const companyId =
input.companyId ??
- (email ? await this.enrichment.companyForEmail(email) : null);
+ (email
+ ? await this.enrichment.companyForEmail(email, {
+ // Same rule as the sync: a company conjured out of somebody's
+ // action belongs to them, not to nobody.
+ ownerId: input.ownerId,
+ })
+ : null);
const contact = await this.db.contact.create({
data: {
@@ -288,6 +302,10 @@ export class ContactsService {
where.companyId = input.company === NO_COMPANY ? null : input.company;
}
+ if (input.source !== FACET_ALL) {
+ where.source = input.source as RecordSource;
+ }
+
return where;
}
@@ -295,7 +313,7 @@ export class ContactsService {
private async facetCounts(input: ContactListInput) {
const where = this.searchFilter(input.q);
- const [owners, companies] = await Promise.all([
+ const [owners, companies, sources] = await Promise.all([
this.db.contact.groupBy({
by: ["ownerId"],
where,
@@ -306,11 +324,17 @@ export class ContactsService {
where,
_count: { _all: true },
}),
+ this.db.contact.groupBy({
+ by: ["source"],
+ where,
+ _count: { _all: true },
+ }),
]);
return {
owner: countsByKey(owners, "ownerId", FACET_UNASSIGNED),
company: countsByKey(companies, "companyId", NO_COMPANY),
+ source: countsByKey(sources, "source"),
};
}
diff --git a/apps/api/src/crm/activity-stamp.service.ts b/apps/api/src/crm/activity-stamp.service.ts
new file mode 100644
index 00000000..ca0e86a6
--- /dev/null
+++ b/apps/api/src/crm/activity-stamp.service.ts
@@ -0,0 +1,159 @@
+import type { Db } from "@crm/db";
+import { Injectable } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+/** The records one activity can belong to. All three are stamped. */
+export type ActivityTarget = {
+ companyId?: string | null;
+ contactId?: string | null;
+ dealId?: string | null;
+};
+
+/**
+ * Keeps `lastActivityAt` current on companies, contacts and deals.
+ *
+ * The column is denormalised because it is a **sortable** column on every list,
+ * and ordering by `max(activity.createdAt)` is an aggregate over a relation that
+ * Prisma cannot express — the alternative is a correlated subquery per row,
+ * which would be the slowest thing on the page.
+ *
+ * Denormalised means it can drift, so every activity write goes through here
+ * rather than each caller remembering to update three tables. There are five
+ * places that write activities (the composer, stage changes, the research
+ * agent, and both Google syncs); the fan-out belongs to the shape of the data,
+ * not to whichever feature happened to trigger it. **A new activity writer adds
+ * a `touch()` call here, not its own update.**
+ *
+ * Stamped with the activity's `createdAt`, not `occurredAt`: a meeting booked
+ * for next month must not make a company look like it was active in the future.
+ * That also matches the lateral join this replaced.
+ */
+@Injectable()
+export class ActivityStampService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /**
+ * Raises `lastActivityAt` to `at` wherever it is currently older or unset.
+ *
+ * A conditional update rather than a read-then-write: two syncs stamping the
+ * same company concurrently would otherwise race, and the older one could
+ * win. Guarding in the `where` makes the operation idempotent and
+ * order-independent, so replaying a window cannot move the value backwards.
+ */
+ async touch(target: ActivityTarget, at: Date): Promise<void> {
+ const stale = {
+ OR: [{ lastActivityAt: null }, { lastActivityAt: { lt: at } }],
+ };
+
+ await Promise.all([
+ target.companyId
+ ? this.db.company.updateMany({
+ where: { id: target.companyId, ...stale },
+ data: { lastActivityAt: at },
+ })
+ : null,
+ target.contactId
+ ? this.db.contact.updateMany({
+ where: { id: target.contactId, ...stale },
+ data: { lastActivityAt: at },
+ })
+ : null,
+ target.dealId
+ ? this.db.deal.updateMany({
+ where: { id: target.dealId, ...stale },
+ data: { lastActivityAt: at },
+ })
+ : null,
+ ]);
+ }
+
+ /**
+ * Recomputes from the activity table.
+ *
+ * For deletes, where the value can only go *down* and `touch` — which never
+ * lowers it — cannot help. Purging a mailbox is the case that needs it:
+ * without this a company keeps claiming activity whose rows are gone.
+ */
+ async recompute(target: ActivityTarget): Promise<void> {
+ if (target.companyId) {
+ const { _max } = await this.db.activity.aggregate({
+ where: { companyId: target.companyId },
+ _max: { createdAt: true },
+ });
+ await this.db.company.update({
+ where: { id: target.companyId },
+ data: { lastActivityAt: _max.createdAt },
+ });
+ }
+
+ if (target.contactId) {
+ const { _max } = await this.db.activity.aggregate({
+ where: { contactId: target.contactId },
+ _max: { createdAt: true },
+ });
+ await this.db.contact.update({
+ where: { id: target.contactId },
+ data: { lastActivityAt: _max.createdAt },
+ });
+ }
+
+ if (target.dealId) {
+ const { _max } = await this.db.activity.aggregate({
+ where: { dealId: target.dealId },
+ _max: { createdAt: true },
+ });
+ await this.db.deal.update({
+ where: { id: target.dealId },
+ data: { lastActivityAt: _max.createdAt },
+ });
+ }
+ }
+
+ /**
+ * Rebuilds every row's stamp in three statements.
+ *
+ * For bulk deletes, where naming the affected records would mean collecting
+ * ids across cascades. Set-based, so it stays a few hundred milliseconds on a
+ * table this size rather than one query per record.
+ */
+ async recomputeAll(): Promise<void> {
+ await this.db.$transaction([
+ this.db.$executeRaw`
+ UPDATE "company" c
+ SET "lastActivityAt" = a.max
+ FROM (
+ SELECT "companyId" AS id, MAX("createdAt") AS max
+ FROM "activity" WHERE "companyId" IS NOT NULL GROUP BY "companyId"
+ ) a
+ WHERE c.id = a.id AND c."lastActivityAt" IS DISTINCT FROM a.max`,
+ this.db.$executeRaw`
+ UPDATE "company" SET "lastActivityAt" = NULL
+ WHERE "lastActivityAt" IS NOT NULL
+ AND id NOT IN (SELECT "companyId" FROM "activity" WHERE "companyId" IS NOT NULL)`,
+ this.db.$executeRaw`
+ UPDATE "contact" c
+ SET "lastActivityAt" = a.max
+ FROM (
+ SELECT "contactId" AS id, MAX("createdAt") AS max
+ FROM "activity" WHERE "contactId" IS NOT NULL GROUP BY "contactId"
+ ) a
+ WHERE c.id = a.id AND c."lastActivityAt" IS DISTINCT FROM a.max`,
+ this.db.$executeRaw`
+ UPDATE "contact" SET "lastActivityAt" = NULL
+ WHERE "lastActivityAt" IS NOT NULL
+ AND id NOT IN (SELECT "contactId" FROM "activity" WHERE "contactId" IS NOT NULL)`,
+ this.db.$executeRaw`
+ UPDATE "deal" d
+ SET "lastActivityAt" = a.max
+ FROM (
+ SELECT "dealId" AS id, MAX("createdAt") AS max
+ FROM "activity" WHERE "dealId" IS NOT NULL GROUP BY "dealId"
+ ) a
+ WHERE d.id = a.id AND d."lastActivityAt" IS DISTINCT FROM a.max`,
+ this.db.$executeRaw`
+ UPDATE "deal" SET "lastActivityAt" = NULL
+ WHERE "lastActivityAt" IS NOT NULL
+ AND id NOT IN (SELECT "dealId" FROM "activity" WHERE "dealId" IS NOT NULL)`,
+ ]);
+ }
+}
diff --git a/apps/api/src/crm/crm.module.ts b/apps/api/src/crm/crm.module.ts
new file mode 100644
index 00000000..95a59709
--- /dev/null
+++ b/apps/api/src/crm/crm.module.ts
@@ -0,0 +1,17 @@
+import { Global, Module } from "@nestjs/common";
+import { ActivityStampService } from "./activity-stamp.service";
+
+/**
+ * Cross-cutting CRM concerns.
+ *
+ * `@Global()` for the same reason `DatabaseModule` is: every module that writes
+ * an activity needs the stamp, and threading it through four `imports` arrays
+ * would make the dependency graph say something about layering that is not
+ * true — the composer, deals, enrichment and both Google syncs are peers.
+ */
+@Global()
+@Module({
+ providers: [ActivityStampService],
+ exports: [ActivityStampService],
+})
+export class CrmModule {}
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index a0a0c353..f6454426 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -11,6 +11,7 @@ import {
Logger,
NotFoundException,
} from "@nestjs/common";
+import { ActivityStampService } from "../crm/activity-stamp.service";
import { fromCents, toCents } from "../crm/values";
import { InjectDatabase } from "../database/database.constants";
import {
@@ -48,6 +49,8 @@ const COMPANY_SELECT = {
name: true,
domain: true,
iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
} as const;
const LOSING = new Set<DealStage>(LOSING_DEAL_STAGES);
@@ -64,13 +67,18 @@ const SORTABLE: Record<
amount: (dir) => [{ amount: dir }],
expectedCloseDate: (dir) => [{ expectedCloseDate: dir }],
createdAt: (dir) => [{ createdAt: dir }],
+ owner: (dir) => [{ owner: { name: dir } }, { name: "asc" }],
+ lastActivity: (dir) => [{ lastActivityAt: { sort: dir, nulls: "last" } }],
};
@Injectable()
export class DealsService {
private readonly logger = new Logger(DealsService.name);
- constructor(@InjectDatabase() private readonly db: Db) {}
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly stamp: ActivityStampService,
+ ) {}
async list(input: DealListInput) {
const where = this.buildWhere(input);
@@ -81,10 +89,7 @@ export class DealsService {
where,
skip,
take,
- orderBy: resolveOrderBy(input, SORTABLE, [
- { stage: "asc" },
- { expectedCloseDate: "asc" },
- ]),
+ orderBy: resolveOrderBy(input, SORTABLE, [{ createdAt: "desc" }]),
select: {
id: true,
name: true,
@@ -95,11 +100,8 @@ export class DealsService {
closedAt: true,
company: { select: COMPANY_SELECT },
owner: { select: OWNER_SELECT },
- activities: {
- take: 1,
- orderBy: { createdAt: "desc" },
- select: { createdAt: true },
- },
+ lastActivityAt: true,
+ createdAt: true,
},
}),
this.db.deal.count({ where }),
@@ -115,12 +117,20 @@ export class DealsService {
return {
rows: rows.map(
- ({ activities, amount, expectedCloseDate, closedAt, ...row }) => ({
+ ({
+ amount,
+ expectedCloseDate,
+ closedAt,
+ lastActivityAt,
+ createdAt,
+ ...row
+ }) => ({
...row,
amountCents: toCents(amount),
expectedCloseDate: expectedCloseDate?.toISOString() ?? null,
closedAt: closedAt?.toISOString() ?? null,
- lastActivityAt: activities[0]?.createdAt.toISOString() ?? null,
+ lastActivityAt: lastActivityAt?.toISOString() ?? null,
+ createdAt: createdAt.toISOString(),
}),
),
total,
@@ -296,6 +306,11 @@ export class DealsService {
}),
]);
+ await this.stamp.touch(
+ { companyId: deal.companyId, dealId: deal.id },
+ new Date(),
+ );
+
this.logger.log({
message: "Deal stage changed",
dealId: deal.id,
diff --git a/apps/api/src/enrichment/brand-mapping.ts b/apps/api/src/enrichment/brand-mapping.ts
index 45ccdfc2..8b5c818c 100644
--- a/apps/api/src/enrichment/brand-mapping.ts
+++ b/apps/api/src/enrichment/brand-mapping.ts
@@ -20,6 +20,8 @@ export type CompanySnapshot = {
logoUrl: string | null;
logoDarkUrl: string | null;
iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
brandColor: string | null;
industry: string | null;
subIndustry: string | null;
@@ -42,18 +44,91 @@ export type CompanySnapshot = {
* The array is not ordered by usefulness: taking the first one is how you end
* up with a dark-mode wordmark on a white table row.
*/
-function pickLogo(
+type LogoMode = "light" | "dark" | "has_opaque_background";
+
+function pickEntry(
logos: Brand["logos"],
type: "logo" | "icon",
- mode?: "light" | "dark",
-): string | null {
- const candidates = (logos ?? []).filter(
+ mode?: LogoMode,
+) {
+ return (logos ?? []).find(
(logo) =>
logo?.url &&
logo.type === type &&
(mode === undefined || logo.mode === mode),
);
- return candidates[0]?.url ?? null;
+}
+
+function pickLogo(
+ logos: Brand["logos"],
+ type: "logo" | "icon",
+ mode?: LogoMode,
+): string | null {
+ return pickEntry(logos, type, mode)?.url ?? null;
+}
+
+/**
+ * The icon to render, preferring one that carries its own background.
+ *
+ * `has_opaque_background` is Context.dev saying the artwork is already composed
+ * on a tile, which is the only kind that needs no help from us in either theme.
+ */
+function pickIcon(logos: Brand["logos"]) {
+ return (
+ pickEntry(logos, "icon", "has_opaque_background") ??
+ pickEntry(logos, "icon", "light") ??
+ pickEntry(logos, "icon")
+ );
+}
+
+/**
+ * How the chosen icon behaves against a background.
+ *
+ * Most brands publish a light-mode logo and nothing else — of the companies
+ * enriched so far, every one had colour data and only two had a dark icon — so
+ * the artwork's own dominant colour, not a second URL, is what makes a black
+ * wordmark visible in dark mode.
+ */
+function iconTone(logos: Brand["logos"]): string | null {
+ const icon = pickIcon(logos);
+ if (!icon) return null;
+
+ if (icon.mode === "has_opaque_background") return "opaque";
+
+ const rgb = parseHex(icon.colors?.find((colour) => colour?.hex)?.hex);
+ if (!rgb) return null;
+
+ // Only near-greyscale artwork is a candidate. The fix downstream is a CSS
+ // invert, and inverting a coloured mark does not make it visible — it makes
+ // it the wrong brand: Monzo's coral comes out teal. A saturated logo is left
+ // alone even if it is dark, because a wrong-coloured logo is worse than a
+ // dim one.
+ const [r, g, b] = rgb;
+ const saturation = (Math.max(r, g, b) - Math.min(r, g, b)) / 255;
+ if (saturation > 0.12) return null;
+
+ // Rec. 601 weighting — enough to answer "is this light or dark", and cheaper
+ // than the sRGB-linearised version nobody would notice here.
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+
+ // Deliberately not a split at the midpoint. Only artwork close to pure black
+ // or pure white actually disappears against a theme background, and only
+ // that artwork survives an invert unchanged. Everything in between keeps its
+ // own colours.
+ if (luminance < 0.2) return "dark";
+ if (luminance > 0.8) return "light";
+ return null;
+}
+
+/** `#rrggbb` to a channel triple. */
+function parseHex(
+ hex: string | null | undefined,
+): [number, number, number] | null {
+ const match = /^#?([0-9a-f]{6})$/i.exec(hex?.trim() ?? "");
+ if (!match?.[1]) return null;
+
+ const value = Number.parseInt(match[1], 16);
+ return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff];
}
function social(socials: Brand["socials"], type: string): string | null {
@@ -98,8 +173,9 @@ export function brandToUpdate(
fill("logoUrl", pickLogo(brand.logos, "logo", "light"));
fill("logoDarkUrl", pickLogo(brand.logos, "logo", "dark"));
- // Icons rarely declare a mode, so this one is not filtered by it.
- fill("iconUrl", pickLogo(brand.logos, "icon"));
+ fill("iconUrl", pickIcon(brand.logos)?.url ?? null);
+ fill("iconDarkUrl", pickLogo(brand.logos, "icon", "dark"));
+ fill("iconTone", iconTone(brand.logos));
// `colors[].name` is generated rather than the brand's own name for it, so
// the hex is the only part worth storing.
diff --git a/apps/api/src/enrichment/contact-enrichment.service.ts b/apps/api/src/enrichment/contact-enrichment.service.ts
new file mode 100644
index 00000000..07e354a8
--- /dev/null
+++ b/apps/api/src/enrichment/contact-enrichment.service.ts
@@ -0,0 +1,304 @@
+import { type Db, RecordSource } from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { domainFromEmail } from "../companies/domain";
+import { InjectDatabase } from "../database/database.constants";
+import { isDerivedName, splitName } from "../google/participants";
+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;
+ 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,
+ ) {}
+
+ 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,
+ 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);
+
+ await this.db.contact.update({
+ where: { id: contactId },
+ data: {
+ firstName,
+ lastName,
+ // Only fills gaps — never overwrites what is already there.
+ ...(contact.title ? {} : { title: found.title ?? null }),
+ ...(contact.linkedinUrl
+ ? {}
+ : { linkedinUrl: found.linkedinUrl ?? null }),
+ },
+ });
+
+ 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,
+ 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.ts
index 2c342156..2cdb75d8 100644
--- a/apps/api/src/enrichment/context-dev.client.ts
+++ b/apps/api/src/enrichment/context-dev.client.ts
@@ -16,8 +16,11 @@ export type Brand = {
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;
@@ -48,6 +51,14 @@ export type LookupResult =
| { 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;
@@ -160,6 +171,56 @@ export class ContextDevClient {
}
}
+ /**
+ * `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> {
diff --git a/apps/api/src/enrichment/enrichment.module.ts b/apps/api/src/enrichment/enrichment.module.ts
index 2a438e5b..a026236a 100644
--- a/apps/api/src/enrichment/enrichment.module.ts
+++ b/apps/api/src/enrichment/enrichment.module.ts
@@ -1,7 +1,9 @@
import { Module } from "@nestjs/common";
+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.
@@ -11,7 +13,13 @@ import { EnrichmentService } from "./enrichment.service";
* HTTP client behind it.
*/
@Module({
- providers: [ContextDevClient, EnrichmentQueue, EnrichmentService],
- exports: [EnrichmentService],
+ providers: [
+ ContextDevClient,
+ EnrichmentQueue,
+ EnrichmentService,
+ ContactEnrichmentService,
+ LinkdapiClient,
+ ],
+ exports: [EnrichmentService, ContactEnrichmentService],
})
export class EnrichmentModule {}
diff --git a/apps/api/src/enrichment/enrichment.service.ts b/apps/api/src/enrichment/enrichment.service.ts
index ccba515f..1028f65a 100644
--- a/apps/api/src/enrichment/enrichment.service.ts
+++ b/apps/api/src/enrichment/enrichment.service.ts
@@ -1,6 +1,7 @@
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 { InjectDatabase } from "../database/database.constants";
import { brandToUpdate, filledFields } from "./brand-mapping";
import { ContextDevClient } from "./context-dev.client";
@@ -49,6 +50,7 @@ export class EnrichmentService {
@InjectDatabase() private readonly db: Db,
private readonly context: ContextDevClient,
private readonly queue: EnrichmentQueue,
+ private readonly stamp: ActivityStampService,
) {}
/**
@@ -90,6 +92,8 @@ export class EnrichmentService {
logoUrl: true,
logoDarkUrl: true,
iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
brandColor: true,
industry: true,
subIndustry: true,
@@ -194,7 +198,10 @@ export class EnrichmentService {
* 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): Promise<string | null> {
+ async companyForEmail(
+ email: string,
+ options: { ownerId?: string | null } = {},
+ ): Promise<string | null> {
const domain = domainFromEmail(email);
if (!domain) return null;
@@ -227,6 +234,9 @@ export class EnrichmentService {
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 },
@@ -296,6 +306,8 @@ export class EnrichmentService {
select: { id: true },
});
+ await this.stamp.touch({ companyId: company.id }, new Date());
+
this.logger.log({
message: "Research brief written",
companyId,
diff --git a/apps/api/src/enrichment/linkdapi.client.ts b/apps/api/src/enrichment/linkdapi.client.ts
new file mode 100644
index 00000000..8856fa16
--- /dev/null
+++ b/apps/api/src/enrichment/linkdapi.client.ts
@@ -0,0 +1,217 @@
+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.ts
index d9eae44c..71720d7b 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -18,11 +18,13 @@ import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInp
import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs } 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";
import type { ActivitiesRouter } from "../activities/activities.router";
import type { CompaniesRouter } from "../companies/companies.router";
import type { ContactsRouter } from "../contacts/contacts.router";
import type { DashboardRouter } from "../dashboard/dashboard.router";
import type { DealsRouter } from "../deals/deals.router";
+import type { GoogleRouter } from "../google/google.router";
import type { SearchRouter } from "../search/search.router";
import type { UsersRouter } from "../users/users.router";
@@ -106,6 +108,28 @@ const appRouter = t.router({
.input(setStageInput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setStage"]>>)
}),
+ google: t.router({
+ status: publicProcedure
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["status"]>>),
+ purgeSyncedData: publicProcedure
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["purgeSyncedData"]>>),
+ revokeAccess: publicProcedure
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["revokeAccess"]>>),
+ syncNow: publicProcedure
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["syncNow"]>>),
+ setAutoCreate: publicProcedure
+ .input(setAutoCreateInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["setAutoCreate"]>>),
+ suppressDomain: publicProcedure
+ .input(suppressDomainInput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["suppressDomain"]>>),
+ thread: publicProcedure
+ .input(threadInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["thread"]>>),
+ event: publicProcedure
+ .input(calendarEventInput)
+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<GoogleRouter["event"]>>)
+ }),
search: t.router({
quick: publicProcedure
.input(z.object({ q: z.string().default("") }))
diff --git a/apps/api/src/google/calendar-sync.service.ts b/apps/api/src/google/calendar-sync.service.ts
new file mode 100644
index 00000000..2b2c0922
--- /dev/null
+++ b/apps/api/src/google/calendar-sync.service.ts
@@ -0,0 +1,449 @@
+import {
+ ActivityType,
+ type Db,
+ GoogleSyncStatus,
+ type MailboxSyncModel as MailboxSync,
+ RecordSource,
+} from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { ActivityStampService } from "../crm/activity-stamp.service";
+import { InjectDatabase } from "../database/database.constants";
+import {
+ CalendarClient,
+ conferenceUrl,
+ eventTime,
+ type GoogleEvent,
+} from "./calendar.client";
+import { GoogleMatchService, type MatchContext } from "./google-match.service";
+import { GoogleTokenService } from "./google-token.service";
+import type { Participant } from "./participants";
+import { SyncStateService } from "./sync-state.service";
+
+/** How many pages one cron tick will pull before yielding. */
+const MAX_PAGES_PER_TICK = 5;
+
+/** How far forward to look. Meetings matter before they happen. */
+const HORIZON_DAYS = 180;
+
+export type SyncOutcome = {
+ source: "calendar";
+ userId: string;
+ status: "synced" | "skipped" | "reconnect" | "rate-limited" | "failed";
+ eventsWritten?: number;
+ eventsRemoved?: number;
+ reason?: string;
+};
+
+/**
+ * Google Calendar → `CalendarEvent` → a projected `Activity` on the timeline.
+ *
+ * Calendar is the simpler of the two syncs and was built first deliberately: the
+ * dedupe key is handed to us, there are no bodies to parse, and it proves the
+ * whole connect → cron → match → project → render path before Gmail adds its
+ * own problems.
+ */
+@Injectable()
+export class CalendarSyncService {
+ private readonly logger = new Logger(CalendarSyncService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly calendar: CalendarClient,
+ private readonly tokens: GoogleTokenService,
+ private readonly match: GoogleMatchService,
+ private readonly state: SyncStateService,
+ private readonly stamp: ActivityStampService,
+ ) {}
+
+ async sync(row: MailboxSync): Promise<SyncOutcome> {
+ const token = await this.tokens.accessTokenFor(row.userId, "calendar");
+
+ if (token.outcome === "not-connected") {
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "skipped",
+ reason: token.reason,
+ };
+ }
+
+ if (token.outcome === "needs-reconnect") {
+ await this.state.markNeedsReconnect(row.id, token.reason);
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "reconnect",
+ reason: token.reason,
+ };
+ }
+
+ await this.state.markRunning(row.id);
+
+ const [internal, suppressedDomains] = await Promise.all([
+ this.match.internalIdentity(),
+ this.match.suppressedDomains(),
+ ]);
+
+ const context = {
+ ourAddresses: internal.addresses,
+ ourDomains: internal.domains,
+ suppressedDomains,
+ };
+
+ let pageToken: string | undefined;
+ let syncToken = row.cursor ?? undefined;
+ let written = 0;
+ let removed = 0;
+
+ for (let page = 0; page < MAX_PAGES_PER_TICK; page += 1) {
+ const result = await this.calendar.listEvents(token.accessToken, {
+ syncToken,
+ pageToken,
+ // Only meaningful on a full pass; ignored when a syncToken is set.
+ //
+ // `now`, never earlier: past meetings are not imported. Events that
+ // *start* from now on are, though, including ones booked before the
+ // sync was switched on — a meeting in next Tuesday's diary is the
+ // point of the feature, and putting it on the timeline is not
+ // back-dating anything.
+ timeMin: new Date().toISOString(),
+ timeMax: this.horizon().toISOString(),
+ });
+
+ if (result.outcome === "cursor-invalid") {
+ await this.state.clearCursor(row.id, result.reason);
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "synced",
+ eventsWritten: written,
+ eventsRemoved: removed,
+ reason: "Cursor reset; the next tick re-runs the window.",
+ };
+ }
+
+ if (result.outcome === "unauthorized") {
+ await this.state.markNeedsReconnect(row.id, result.reason);
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "reconnect",
+ reason: result.reason,
+ };
+ }
+
+ if (result.outcome === "rate-limited") {
+ await this.state.markRateLimited(row.id, result.retryAfterMs);
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "rate-limited",
+ reason: result.reason,
+ };
+ }
+
+ if (result.outcome === "failed") {
+ await this.state.markFailed(row.id, result.reason);
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "failed",
+ reason: result.reason,
+ };
+ }
+
+ for (const event of result.data.items ?? []) {
+ const applied = await this.apply(event, row, context);
+ if (applied === "written") written += 1;
+ if (applied === "removed") removed += 1;
+ }
+
+ pageToken = result.data.nextPageToken;
+
+ if (!pageToken) {
+ // The sync token only appears on the final page; that is the signal
+ // the window is fully drained and steady-state can begin.
+ syncToken = result.data.nextSyncToken ?? syncToken;
+ await this.state.settle(row.id, {
+ cursor: syncToken ?? null,
+ status: GoogleSyncStatus.RUNNING,
+ });
+
+ this.logger.log({
+ message: "Calendar sync complete",
+ userId: row.userId,
+ eventsWritten: written,
+ eventsRemoved: removed,
+ });
+
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "synced",
+ eventsWritten: written,
+ eventsRemoved: removed,
+ };
+ }
+ }
+
+ // Ran out of page budget without reaching the last page, so there is no
+ // sync token to keep. The next tick re-runs the window, which is free
+ // because every write is an upsert on a natural key.
+ await this.state.settle(row.id, {
+ status: GoogleSyncStatus.IDLE,
+ });
+
+ return {
+ source: "calendar",
+ userId: row.userId,
+ status: "synced",
+ eventsWritten: written,
+ eventsRemoved: removed,
+ reason: "Page budget reached; continuing next tick.",
+ };
+ }
+
+ /**
+ * One event: store it, project it, or delete what we stored before.
+ *
+ * Returns what it did so the caller can count without a second pass.
+ */
+ private async apply(
+ event: GoogleEvent,
+ row: MailboxSync,
+ context: MatchContext,
+ ): Promise<"written" | "removed" | "ignored"> {
+ const iCalUid = event.iCalUID;
+ if (!iCalUid) return "ignored";
+
+ const start = eventTime(event.start);
+ const originalStart = eventTime(event.originalStartTime) ?? start;
+
+ // An instance keeps its original start even when moved, which is what
+ // identifies it within a recurring series.
+ if (!originalStart) return "ignored";
+
+ const key = {
+ iCalUid_originalStartTime: {
+ iCalUid,
+ originalStartTime: originalStart.at,
+ },
+ };
+
+ if (event.status === "cancelled") {
+ // Cancellations arrive as ordinary items because we ask for
+ // showDeleted. Deleting cascades to the projected activity.
+ const deleted = await this.db.calendarEvent.deleteMany({
+ where: {
+ iCalUid,
+ originalStartTime: originalStart.at,
+ },
+ });
+ return deleted.count > 0 ? "removed" : "ignored";
+ }
+
+ const end = eventTime(event.end);
+ if (!start || !end) return "ignored";
+
+ const participants = this.participantsOf(event);
+
+ // A meeting is two-way engagement on its own: somebody put time in a
+ // diary. So calendar may create, subject to the row's own toggle.
+ const declinedByUs = event.attendees?.some(
+ (attendee) => attendee.self && attendee.responseStatus === "declined",
+ );
+
+ const match = await this.match.resolve(
+ {
+ participants,
+ allowCreate: row.autoCreate && !declinedByUs,
+ source: RecordSource.CALENDAR,
+ // Whoever's calendar this is owns what it creates — they are the
+ // person with the relationship.
+ ownerId: row.userId,
+ },
+ context,
+ );
+
+ if (!match.companyId && !match.contactId) {
+ // Nothing we track, and nothing worth creating — a dentist appointment.
+ // Never stored, per the plan §5.
+ return "ignored";
+ }
+
+ const organizer = event.organizer?.email?.toLowerCase() ?? null;
+
+ const record = await this.db.calendarEvent.upsert({
+ where: key,
+ create: {
+ iCalUid,
+ originalStartTime: originalStart.at,
+ recurringEventId: event.recurringEventId ?? null,
+ title: event.summary ?? null,
+ description: event.description ?? null,
+ location: event.location ?? null,
+ conferenceUrl: conferenceUrl(event),
+ startsAt: start.at,
+ endsAt: end.at,
+ isAllDay: start.isAllDay,
+ status: event.status ?? "confirmed",
+ organizerEmail: organizer,
+ companyId: match.companyId,
+ contactId: match.contactId,
+ syncedByUserId: row.userId,
+ googleEventId: event.id ?? null,
+ },
+ update: {
+ title: event.summary ?? null,
+ description: event.description ?? null,
+ location: event.location ?? null,
+ conferenceUrl: conferenceUrl(event),
+ startsAt: start.at,
+ endsAt: end.at,
+ isAllDay: start.isAllDay,
+ status: event.status ?? "confirmed",
+ organizerEmail: organizer,
+ companyId: match.companyId,
+ contactId: match.contactId,
+ },
+ select: { id: true },
+ });
+
+ await this.syncAttendees(record.id, event);
+ await this.project(record.id, row.userId, {
+ title: event.summary ?? "Meeting",
+ startsAt: start.at,
+ companyId: match.companyId,
+ contactId: match.contactId,
+ location: event.location ?? null,
+ });
+
+ return "written";
+ }
+
+ /** Replaces the attendee list, linking anyone we already know as a contact. */
+ private async syncAttendees(
+ eventId: string,
+ event: GoogleEvent,
+ ): Promise<void> {
+ const attendees = (event.attendees ?? []).filter(
+ // Meeting rooms are attendees as far as Google is concerned.
+ (attendee) => attendee.email && !attendee.resource,
+ );
+
+ if (attendees.length === 0) return;
+
+ const emails = attendees.map((attendee) =>
+ (attendee.email as string).toLowerCase(),
+ );
+
+ const contacts = await this.db.contact.findMany({
+ where: { email: { in: emails } },
+ select: { id: true, email: true },
+ });
+
+ const contactByEmail = new Map(
+ contacts.map((contact) => [contact.email as string, contact.id]),
+ );
+
+ for (const attendee of attendees) {
+ const email = (attendee.email as string).toLowerCase();
+
+ await this.db.calendarAttendee.upsert({
+ where: { eventId_email: { eventId, email } },
+ create: {
+ eventId,
+ email,
+ name: attendee.displayName ?? null,
+ responseStatus: attendee.responseStatus ?? null,
+ isOrganizer: attendee.organizer ?? false,
+ contactId: contactByEmail.get(email) ?? null,
+ },
+ update: {
+ name: attendee.displayName ?? null,
+ responseStatus: attendee.responseStatus ?? null,
+ isOrganizer: attendee.organizer ?? false,
+ contactId: contactByEmail.get(email) ?? null,
+ },
+ });
+ }
+ }
+
+ /**
+ * The timeline projection: one `Activity` per event, kept current.
+ *
+ * `occurredAt` is the meeting's start even when that is in the future, so an
+ * upcoming meeting sorts where a rep expects to find it rather than at the
+ * moment the sync happened to run.
+ */
+ private async project(
+ calendarEventId: string,
+ userId: string,
+ summary: {
+ title: string;
+ startsAt: Date;
+ companyId: string | null;
+ contactId: string | null;
+ location: string | null;
+ },
+ ): Promise<void> {
+ const body = summary.location ? `Location: ${summary.location}` : null;
+
+ const activity = await this.db.activity.upsert({
+ where: { calendarEventId },
+ create: {
+ type: ActivityType.MEETING,
+ subject: summary.title,
+ body,
+ occurredAt: summary.startsAt,
+ companyId: summary.companyId,
+ contactId: summary.contactId,
+ createdById: userId,
+ calendarEventId,
+ meta: { synced: true, source: "calendar" },
+ },
+ update: {
+ subject: summary.title,
+ body,
+ occurredAt: summary.startsAt,
+ companyId: summary.companyId,
+ contactId: summary.contactId,
+ },
+ select: { createdAt: true },
+ });
+
+ await this.stamp.touch(
+ { companyId: summary.companyId, contactId: summary.contactId },
+ activity.createdAt,
+ );
+ }
+
+ private participantsOf(event: GoogleEvent): Participant[] {
+ const people: Participant[] = [];
+
+ for (const attendee of event.attendees ?? []) {
+ if (!attendee.email || attendee.resource) continue;
+ people.push({
+ email: attendee.email.toLowerCase(),
+ name: attendee.displayName ?? null,
+ });
+ }
+
+ // A one-to-one booked through a scheduling link often has the customer as
+ // organiser and nobody in `attendees`.
+ if (event.organizer?.email) {
+ people.push({
+ email: event.organizer.email.toLowerCase(),
+ name: event.organizer.displayName ?? null,
+ });
+ }
+
+ return people;
+ }
+
+ private horizon(): Date {
+ const to = new Date();
+ to.setDate(to.getDate() + HORIZON_DAYS);
+ return to;
+ }
+}
diff --git a/apps/api/src/google/calendar.client.ts b/apps/api/src/google/calendar.client.ts
new file mode 100644
index 00000000..ca576c57
--- /dev/null
+++ b/apps/api/src/google/calendar.client.ts
@@ -0,0 +1,119 @@
+import { Injectable } from "@nestjs/common";
+import { GoogleApiClient, type GoogleResult } from "./google-api.client";
+
+const EVENTS_URL =
+ "https://www.googleapis.com/calendar/v3/calendars/primary/events";
+
+/** The slice of Google's event resource we actually read. */
+export type GoogleEvent = {
+ id?: string;
+ iCalUID?: string;
+ status?: string;
+ summary?: string;
+ description?: string;
+ location?: string;
+ hangoutLink?: string;
+ htmlLink?: string;
+ recurringEventId?: string;
+ start?: GoogleEventTime;
+ end?: GoogleEventTime;
+ originalStartTime?: GoogleEventTime;
+ organizer?: { email?: string; displayName?: string; self?: boolean };
+ creator?: { email?: string; displayName?: string; self?: boolean };
+ attendees?: {
+ email?: string;
+ displayName?: string;
+ responseStatus?: string;
+ organizer?: boolean;
+ self?: boolean;
+ resource?: boolean;
+ }[];
+ conferenceData?: {
+ entryPoints?: { entryPointType?: string; uri?: string }[];
+ };
+};
+
+export type GoogleEventTime = {
+ /** Set on a timed event. */
+ dateTime?: string;
+ /** Set on an all-day event; a bare `YYYY-MM-DD`. */
+ date?: string;
+ timeZone?: string;
+};
+
+export type EventsPage = {
+ items?: GoogleEvent[];
+ nextPageToken?: string;
+ nextSyncToken?: string;
+};
+
+export type EventsQuery = {
+ /** Incremental. Mutually exclusive with the time window, per Google. */
+ syncToken?: string;
+ timeMin?: string;
+ timeMax?: string;
+ pageToken?: string;
+ maxResults?: number;
+};
+
+@Injectable()
+export class CalendarClient {
+ constructor(private readonly api: GoogleApiClient) {}
+
+ /**
+ * One page of events.
+ *
+ * `singleEvents: true` expands recurring series into instances, which is what
+ * makes `(iCalUID, originalStartTime)` a usable key — an unexpanded series
+ * would be one row for "every Tuesday forever" and could not sit on a
+ * timeline. `showDeleted: true` is how cancellations arrive at all.
+ */
+ async listEvents(
+ accessToken: string,
+ query: EventsQuery,
+ ): Promise<GoogleResult<EventsPage>> {
+ // Google rejects a request carrying both a syncToken and a time window.
+ const window = query.syncToken
+ ? {}
+ : { timeMin: query.timeMin, timeMax: query.timeMax };
+
+ return this.api.get<EventsPage>(EVENTS_URL, accessToken, {
+ singleEvents: true,
+ showDeleted: true,
+ maxResults: query.maxResults ?? 250,
+ syncToken: query.syncToken,
+ pageToken: query.pageToken,
+ ...window,
+ });
+ }
+}
+
+/** The best conference link on an event, if it has one. */
+export function conferenceUrl(event: GoogleEvent): string | null {
+ if (event.hangoutLink) return event.hangoutLink;
+
+ const entry = event.conferenceData?.entryPoints?.find(
+ (point) => point.entryPointType === "video" && point.uri,
+ );
+
+ return entry?.uri ?? null;
+}
+
+/** A Google event time as a Date, plus whether the event is all-day. */
+export function eventTime(
+ time: GoogleEventTime | undefined,
+): { at: Date; isAllDay: boolean } | null {
+ if (time?.dateTime) {
+ const at = new Date(time.dateTime);
+ return Number.isNaN(at.getTime()) ? null : { at, isAllDay: false };
+ }
+
+ if (time?.date) {
+ // A bare date is midnight local to the calendar; parsing it as UTC keeps
+ // the key stable regardless of where the server runs.
+ const at = new Date(`${time.date}T00:00:00Z`);
+ return Number.isNaN(at.getTime()) ? null : { at, isAllDay: true };
+ }
+
+ return null;
+}
diff --git a/apps/api/src/google/conversation.service.ts b/apps/api/src/google/conversation.service.ts
new file mode 100644
index 00000000..f15f3f48
--- /dev/null
+++ b/apps/api/src/google/conversation.service.ts
@@ -0,0 +1,127 @@
+import type { Db } from "@crm/db";
+import { Injectable, NotFoundException } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+
+/**
+ * Reading a synced thread or event back out.
+ *
+ * Separate from the sync services because this is the only path that returns
+ * message bodies, and keeping it in one file makes "where can an email body
+ * reach the browser" a question with one answer. The timeline never calls it —
+ * it carries a snippet, and the accordion fetches this on expand.
+ */
+@Injectable()
+export class ConversationService {
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async thread(threadId: string) {
+ const thread = await this.db.emailThread.findUnique({
+ where: { id: threadId },
+ select: {
+ id: true,
+ subject: true,
+ messageCount: true,
+ firstMessageAt: true,
+ lastMessageAt: true,
+ company: { select: { id: true, name: true } },
+ contact: { select: { id: true, firstName: true, lastName: true } },
+ messages: {
+ orderBy: { sentAt: "asc" },
+ select: {
+ id: true,
+ direction: true,
+ fromEmail: true,
+ fromName: true,
+ recipients: true,
+ subject: true,
+ body: true,
+ snippet: true,
+ sentAt: true,
+ gmailMessageId: true,
+ },
+ },
+ },
+ });
+
+ if (!thread) {
+ throw new NotFoundException(`No email thread with id ${threadId}.`);
+ }
+
+ return {
+ ...thread,
+ firstMessageAt: thread.firstMessageAt.toISOString(),
+ lastMessageAt: thread.lastMessageAt.toISOString(),
+ messages: thread.messages.map((message) => ({
+ ...message,
+ sentAt: message.sentAt.toISOString(),
+ recipients: recipientsOf(message.recipients),
+ /** Deep link back to Gmail, when we know which message it was. */
+ gmailUrl: message.gmailMessageId
+ ? `https://mail.google.com/mail/u/0/#all/${message.gmailMessageId}`
+ : null,
+ })),
+ };
+ }
+
+ async event(eventId: string) {
+ const event = await this.db.calendarEvent.findUnique({
+ where: { id: eventId },
+ select: {
+ id: true,
+ title: true,
+ description: true,
+ location: true,
+ conferenceUrl: true,
+ startsAt: true,
+ endsAt: true,
+ isAllDay: true,
+ status: true,
+ organizerEmail: true,
+ company: { select: { id: true, name: true } },
+ contact: { select: { id: true, firstName: true, lastName: true } },
+ attendees: {
+ orderBy: [{ isOrganizer: "desc" }, { email: "asc" }],
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ responseStatus: true,
+ isOrganizer: true,
+ contactId: true,
+ },
+ },
+ },
+ });
+
+ if (!event) {
+ throw new NotFoundException(`No calendar event with id ${eventId}.`);
+ }
+
+ return {
+ ...event,
+ startsAt: event.startsAt.toISOString(),
+ endsAt: event.endsAt.toISOString(),
+ };
+ }
+}
+
+/** `recipients` is `Json`, so it is read back defensively. */
+function recipientsOf(
+ value: unknown,
+): { email: string; name: string | null; kind: string }[] {
+ if (!Array.isArray(value)) return [];
+
+ return value.flatMap((entry) => {
+ if (typeof entry !== "object" || entry === null) return [];
+ const record = entry as Record<string, unknown>;
+ if (typeof record.email !== "string") return [];
+
+ return [
+ {
+ email: record.email,
+ name: typeof record.name === "string" ? record.name : null,
+ kind: typeof record.kind === "string" ? record.kind : "to",
+ },
+ ];
+ });
+}
diff --git a/apps/api/src/google/gmail-sync.service.ts b/apps/api/src/google/gmail-sync.service.ts
new file mode 100644
index 00000000..3e195290
--- /dev/null
+++ b/apps/api/src/google/gmail-sync.service.ts
@@ -0,0 +1,571 @@
+import {
+ ActivityType,
+ type Db,
+ EmailDirection,
+ GoogleSyncStatus,
+ type MailboxSyncModel as MailboxSync,
+ RecordSource,
+} from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { ActivityStampService } from "../crm/activity-stamp.service";
+import { InjectDatabase } from "../database/database.constants";
+import { GmailClient, type GmailMessage } from "./gmail.client";
+import { GoogleMatchService, type MatchContext } from "./google-match.service";
+import { GoogleTokenService } from "./google-token.service";
+import {
+ type GmailHeader,
+ header,
+ normaliseMessageId,
+ plainTextBody,
+ rootMessageId,
+ snippetOf,
+ stripQuotedHistory,
+} from "./mime";
+import {
+ type Participant,
+ parseAddress,
+ parseAddressList,
+} from "./participants";
+import { SyncStateService } from "./sync-state.service";
+
+/** Ceiling on one tick, so a burst of mail cannot stretch an invocation. */
+const MAX_MESSAGES_PER_TICK = 120;
+
+export type GmailSyncOutcome = {
+ source: "gmail";
+ userId: string;
+ status: "synced" | "skipped" | "reconnect" | "rate-limited" | "failed";
+ messagesWritten?: number;
+ threadsTouched?: number;
+ reason?: string;
+};
+
+/** A message parsed into the shape the database wants. */
+type ParsedMessage = {
+ rfcMessageId: string;
+ rootId: string;
+ subject: string | null;
+ from: Participant;
+ recipients: { email: string; name: string | null; kind: "to" | "cc" }[];
+ body: string;
+ sentAt: Date;
+ gmailMessageId: string | null;
+};
+
+/**
+ * Gmail → `EmailThread`/`EmailMessage` → one projected `Activity` per thread.
+ *
+ * The two things that make this harder than calendar: identity has to be
+ * derived from RFC headers rather than handed to us, and a reply carries the
+ * whole conversation in its body, so what gets stored needs pruning first.
+ */
+@Injectable()
+export class GmailSyncService {
+ private readonly logger = new Logger(GmailSyncService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly gmail: GmailClient,
+ private readonly tokens: GoogleTokenService,
+ private readonly match: GoogleMatchService,
+ private readonly state: SyncStateService,
+ private readonly stamp: ActivityStampService,
+ ) {}
+
+ async sync(row: MailboxSync): Promise<GmailSyncOutcome> {
+ const token = await this.tokens.accessTokenFor(row.userId, "gmail");
+
+ if (token.outcome === "not-connected") {
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "skipped",
+ reason: token.reason,
+ };
+ }
+
+ if (token.outcome === "needs-reconnect") {
+ await this.state.markNeedsReconnect(row.id, token.reason);
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "reconnect",
+ reason: token.reason,
+ };
+ }
+
+ await this.state.markRunning(row.id);
+
+ // Whose mailbox this is, so a message can be classed inbound or outbound
+ // and so "did the rep reply?" is answerable.
+ const profile = await this.gmail.profile(token.accessToken);
+ if (profile.outcome !== "ok") {
+ return this.handleFailure(row, profile, "gmail");
+ }
+
+ const mailbox = profile.data.emailAddress?.toLowerCase() ?? null;
+ if (!mailbox) {
+ await this.state.markFailed(row.id, "Gmail returned no mailbox address.");
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "failed",
+ reason: "No mailbox address.",
+ };
+ }
+
+ // No cursor means this mailbox has never been seen. Sync is forward-only,
+ // so the first pass imports nothing at all — it just records where "now"
+ // is, and everything after that point arrives through `incremental`.
+ if (!row.cursor) {
+ return this.start(row, profile.data.historyId ?? null);
+ }
+
+ return this.incremental(row, token.accessToken, mailbox, row.cursor);
+ }
+
+ /**
+ * Marks the starting line.
+ *
+ * Deliberately imports nothing. A CRM that suddenly fills with three months
+ * of a rep's old mail is noise nobody asked for, and the history is not what
+ * the feature is for — what matters is that from this moment on, the
+ * conversation shows up on the record.
+ */
+ private async start(
+ row: MailboxSync,
+ historyId: string | null,
+ ): Promise<GmailSyncOutcome> {
+ if (!historyId) {
+ await this.state.markFailed(row.id, "Gmail returned no historyId.");
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "failed",
+ reason: "No historyId to start from.",
+ };
+ }
+
+ await this.state.settle(row.id, {
+ cursor: historyId,
+ status: GoogleSyncStatus.RUNNING,
+ });
+
+ this.logger.log({
+ message: "Gmail sync started — watching for new mail",
+ userId: row.userId,
+ });
+
+ return { source: "gmail", userId: row.userId, status: "synced" };
+ }
+
+ /** Everything added since the stored historyId. */
+ private async incremental(
+ row: MailboxSync,
+ accessToken: string,
+ mailbox: string,
+ startHistoryId: string,
+ ): Promise<GmailSyncOutcome> {
+ const history = await this.gmail.listHistory(accessToken, {
+ startHistoryId,
+ });
+
+ if (history.outcome === "cursor-invalid") {
+ // The historyId fell out of Gmail's retention window — which takes about
+ // a week of the sync not running at all. Forward-only means we do not
+ // go back and fetch the gap: the cursor is re-pointed at now and the
+ // missed window is simply not imported. Logged, because a mailbox that
+ // keeps landing here is a sync that keeps failing.
+ await this.state.clearCursor(row.id, history.reason);
+
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "synced",
+ reason: "History expired; resuming from now.",
+ };
+ }
+
+ if (history.outcome !== "ok") {
+ return this.handleFailure(row, history, "gmail");
+ }
+
+ const ids = new Set<string>();
+ for (const entry of history.data.history ?? []) {
+ for (const added of entry.messagesAdded ?? []) {
+ if (added.message?.id) ids.add(added.message.id);
+ }
+ }
+
+ const { written, remaining } = await this.ingest(
+ row,
+ accessToken,
+ mailbox,
+ [...ids],
+ );
+
+ await this.state.settle(row.id, {
+ // Hold the cursor when the batch was capped. Advancing past messages we
+ // never read would drop them permanently; leaving it means the next tick
+ // re-lists the same window, finds this run's writes already stored, and
+ // works through the next hundred.
+ cursor:
+ remaining > 0
+ ? startHistoryId
+ : (history.data.historyId ?? startHistoryId),
+ status: GoogleSyncStatus.RUNNING,
+ });
+
+ if (written > 0 || remaining > 0) {
+ this.logger.log({
+ message: "Gmail incremental sync",
+ userId: row.userId,
+ messagesWritten: written,
+ remaining,
+ });
+ }
+
+ return {
+ source: "gmail",
+ userId: row.userId,
+ status: "synced",
+ messagesWritten: written,
+ };
+ }
+
+ /**
+ * Fetches and stores message ids, up to this tick's ceiling.
+ *
+ * Reports what it could not get to, so the caller knows whether it is safe to
+ * advance the cursor. Filtering the already-stored ids out *before* taking the
+ * batch is what makes a capped run make progress: otherwise every tick would
+ * re-take the same first hundred, find them all present, and write nothing.
+ */
+ private async ingest(
+ row: MailboxSync,
+ accessToken: string,
+ mailbox: string,
+ ids: readonly string[],
+ ): Promise<{ written: number; remaining: number }> {
+ if (ids.length === 0) return { written: 0, remaining: 0 };
+
+ // The unique index on `rfcMessageId` is the backstop, but checking Gmail's
+ // own id first avoids paying for a `messages.get` on something another
+ // rep's sync already ingested.
+ const alreadyHave = await this.db.emailMessage.findMany({
+ where: { gmailMessageId: { in: [...ids] } },
+ select: { gmailMessageId: true },
+ });
+ const seen = new Set(
+ alreadyHave.map((existing) => existing.gmailMessageId),
+ );
+
+ const pending = ids.filter((id) => !seen.has(id));
+ const batch = pending.slice(0, MAX_MESSAGES_PER_TICK);
+ const remaining = pending.length - batch.length;
+
+ if (batch.length === 0) return { written: 0, remaining };
+
+ const [internal, suppressedDomains] = await Promise.all([
+ this.match.internalIdentity(),
+ this.match.suppressedDomains(),
+ ]);
+
+ const context = {
+ ourAddresses: internal.addresses,
+ ourDomains: internal.domains,
+ suppressedDomains,
+ };
+
+ let written = 0;
+
+ for (const id of batch) {
+ const message = await this.gmail.getMessage(accessToken, id);
+ if (message.outcome !== "ok") continue;
+
+ const stored = await this.store(row, mailbox, message.data, context);
+ if (stored) written += 1;
+ }
+
+ return { written, remaining };
+ }
+
+ /** One message: match it, store it, keep its thread's projection current. */
+ private async store(
+ row: MailboxSync,
+ mailbox: string,
+ message: GmailMessage,
+ context: MatchContext,
+ ): Promise<boolean> {
+ const parsed = this.parse(message);
+ if (!parsed) return false;
+
+ // Already ingested from another mailbox. The unique index would catch this
+ // anyway; checking first keeps the log honest about what was written.
+ const existing = await this.db.emailMessage.findUnique({
+ where: { rfcMessageId: parsed.rfcMessageId },
+ select: { id: true },
+ });
+ if (existing) return false;
+
+ const participants = [parsed.from, ...parsed.recipients];
+ const outbound = parsed.from.email === mailbox;
+
+ // The thread may already exist from an earlier message, in which case its
+ // match is authoritative and the whole resolve step is skipped.
+ const thread = await this.db.emailThread.findUnique({
+ where: { rootMessageId: parsed.rootId },
+ select: { id: true, companyId: true, contactId: true },
+ });
+
+ let companyId = thread?.companyId ?? null;
+ let contactId = thread?.contactId ?? null;
+
+ if (!thread) {
+ // Two-way engagement: the rep has to have sent something. An inbound-only
+ // thread is a newsletter, a recruiter or spam, and creating a company
+ // from one is how a CRM fills with junk.
+ const repliedTo =
+ outbound || (await this.hasOutboundInThread(parsed.rootId, mailbox));
+
+ const match = await this.match.resolve(
+ {
+ participants,
+ allowCreate: row.autoCreate && repliedTo,
+ source: RecordSource.EMAIL,
+ // Whoever's mailbox this is owns what it creates.
+ ownerId: row.userId,
+ },
+ context,
+ );
+
+ companyId = match.companyId;
+ contactId = match.contactId;
+
+ if (!companyId && !contactId) {
+ // Not anybody we track and not worth creating. Dropped at ingest —
+ // never written, per the plan §5.
+ return false;
+ }
+ }
+
+ const record = await this.db.emailThread.upsert({
+ where: { rootMessageId: parsed.rootId },
+ create: {
+ rootMessageId: parsed.rootId,
+ subject: parsed.subject,
+ companyId,
+ contactId,
+ firstMessageAt: parsed.sentAt,
+ lastMessageAt: parsed.sentAt,
+ messageCount: 0,
+ },
+ update: {},
+ select: { id: true, firstMessageAt: true, lastMessageAt: true },
+ });
+
+ await this.db.emailMessage.create({
+ data: {
+ threadId: record.id,
+ rfcMessageId: parsed.rfcMessageId,
+ syncedByUserId: row.userId,
+ gmailMessageId: parsed.gmailMessageId,
+ direction: outbound ? EmailDirection.OUTBOUND : EmailDirection.INBOUND,
+ fromEmail: parsed.from.email,
+ fromName: parsed.from.name,
+ recipients: parsed.recipients,
+ subject: parsed.subject,
+ snippet: snippetOf(parsed.body),
+ body: parsed.body || null,
+ sentAt: parsed.sentAt,
+ },
+ });
+
+ // Recomputed rather than incremented: messages arriving out of order would
+ // otherwise leave `lastMessageAt` pointing at whichever message happened to
+ // arrive last, which is not the same as the latest one.
+ const stats = await this.db.emailMessage.aggregate({
+ where: { threadId: record.id },
+ _count: { _all: true },
+ _min: { sentAt: true },
+ _max: { sentAt: true },
+ });
+
+ const firstMessageAt = stats._min.sentAt ?? parsed.sentAt;
+ const lastMessageAt = stats._max.sentAt ?? parsed.sentAt;
+
+ await this.db.emailThread.update({
+ where: { id: record.id },
+ data: {
+ messageCount: stats._count._all,
+ firstMessageAt,
+ lastMessageAt,
+ // A thread's subject is the one it started with, not the "Re: Re: Fwd:"
+ // it acquired.
+ ...(parsed.sentAt <= firstMessageAt ? { subject: parsed.subject } : {}),
+ },
+ });
+
+ await this.project(record.id, row.userId, {
+ subject: parsed.subject ?? "(no subject)",
+ snippet: snippetOf(parsed.body),
+ lastMessageAt,
+ companyId,
+ contactId,
+ });
+
+ return true;
+ }
+
+ /** Whether the mailbox owner has sent anything into this thread already. */
+ private async hasOutboundInThread(
+ rootMessageId: string,
+ mailbox: string,
+ ): Promise<boolean> {
+ const found = await this.db.emailMessage.findFirst({
+ where: {
+ thread: { rootMessageId },
+ fromEmail: mailbox,
+ },
+ select: { id: true },
+ });
+
+ return found !== null;
+ }
+
+ /**
+ * One `Activity` per thread, updated as the thread grows.
+ *
+ * Not one per message: a forty-message thread would otherwise be forty
+ * timeline rows saying almost the same thing.
+ */
+ private async project(
+ emailThreadId: string,
+ userId: string,
+ summary: {
+ subject: string;
+ snippet: string | null;
+ lastMessageAt: Date;
+ companyId: string | null;
+ contactId: string | null;
+ },
+ ): Promise<void> {
+ const activity = await this.db.activity.upsert({
+ where: { emailThreadId },
+ create: {
+ type: ActivityType.EMAIL,
+ subject: summary.subject,
+ body: summary.snippet,
+ occurredAt: summary.lastMessageAt,
+ companyId: summary.companyId,
+ contactId: summary.contactId,
+ createdById: userId,
+ emailThreadId,
+ meta: { synced: true, source: "gmail" },
+ },
+ update: {
+ body: summary.snippet,
+ occurredAt: summary.lastMessageAt,
+ },
+ select: { createdAt: true },
+ });
+
+ await this.stamp.touch(
+ { companyId: summary.companyId, contactId: summary.contactId },
+ activity.createdAt,
+ );
+ }
+
+ /** Gmail's message resource → the fields we store. */
+ private parse(message: GmailMessage): ParsedMessage | null {
+ const headers = message.payload?.headers;
+
+ const rawMessageId = header(headers, "message-id");
+ if (!rawMessageId) return null;
+
+ const from = parseAddress(header(headers, "from") ?? "");
+ if (!from) return null;
+
+ const sentAt = this.sentAt(message, headers);
+ if (!sentAt) return null;
+
+ const rootId = rootMessageId(headers) ?? normaliseMessageId(rawMessageId);
+
+ const to = parseAddressList(header(headers, "to")).map((person) => ({
+ email: person.email,
+ name: person.name,
+ kind: "to" as const,
+ }));
+
+ const cc = parseAddressList(header(headers, "cc")).map((person) => ({
+ email: person.email,
+ name: person.name,
+ kind: "cc" as const,
+ }));
+
+ const body = stripQuotedHistory(plainTextBody(message.payload));
+
+ return {
+ rfcMessageId: normaliseMessageId(rawMessageId),
+ rootId,
+ subject: header(headers, "subject"),
+ from,
+ recipients: [...to, ...cc],
+ body,
+ sentAt,
+ gmailMessageId: message.id ?? null,
+ };
+ }
+
+ private sentAt(
+ message: GmailMessage,
+ headers: readonly GmailHeader[] | undefined,
+ ): Date | null {
+ // `internalDate` is Gmail's own receipt time in ms and is always present
+ // and always parseable; the `Date` header is neither.
+ if (message.internalDate) {
+ const at = new Date(Number(message.internalDate));
+ if (!Number.isNaN(at.getTime())) return at;
+ }
+
+ const raw = header(headers, "date");
+ if (!raw) return null;
+
+ const at = new Date(raw);
+ return Number.isNaN(at.getTime()) ? null : at;
+ }
+
+ private async handleFailure(
+ row: MailboxSync,
+ result: { outcome: string; reason: string; retryAfterMs?: number },
+ source: "gmail",
+ ): Promise<GmailSyncOutcome> {
+ if (result.outcome === "unauthorized") {
+ await this.state.markNeedsReconnect(row.id, result.reason);
+ return {
+ source,
+ userId: row.userId,
+ status: "reconnect",
+ reason: result.reason,
+ };
+ }
+
+ if (result.outcome === "rate-limited") {
+ await this.state.markRateLimited(row.id, result.retryAfterMs ?? 60_000);
+ return {
+ source,
+ userId: row.userId,
+ status: "rate-limited",
+ reason: result.reason,
+ };
+ }
+
+ await this.state.markFailed(row.id, result.reason);
+ return {
+ source,
+ userId: row.userId,
+ status: "failed",
+ reason: result.reason,
+ };
+ }
+}
diff --git a/apps/api/src/google/gmail.client.ts b/apps/api/src/google/gmail.client.ts
new file mode 100644
index 00000000..ff7d1b9d
--- /dev/null
+++ b/apps/api/src/google/gmail.client.ts
@@ -0,0 +1,106 @@
+import { Injectable } from "@nestjs/common";
+import { GoogleApiClient, type GoogleResult } from "./google-api.client";
+import type { GmailPart } from "./mime";
+
+const BASE = "https://gmail.googleapis.com/gmail/v1/users/me";
+
+export type GmailMessage = {
+ id?: string;
+ threadId?: string;
+ labelIds?: string[];
+ snippet?: string;
+ internalDate?: string;
+ historyId?: string;
+ payload?: GmailPart;
+};
+
+export type MessageList = {
+ messages?: { id?: string; threadId?: string }[];
+ nextPageToken?: string;
+ resultSizeEstimate?: number;
+};
+
+export type HistoryList = {
+ history?: {
+ id?: string;
+ messagesAdded?: { message?: { id?: string; threadId?: string } }[];
+ }[];
+ nextPageToken?: string;
+ historyId?: string;
+};
+
+export type Profile = {
+ emailAddress?: string;
+ historyId?: string;
+};
+
+/**
+ * The Gmail query used for every backfill page.
+ *
+ * Narrowing here rather than after fetching is the difference between reading a
+ * mailbox and reading the part of it that could possibly be work. Promotions,
+ * social and chats are never customer conversations, and each excluded message
+ * is a `messages.get` we do not pay for.
+ */
+export const WORK_MAIL_QUERY =
+ "-in:chats -category:promotions -category:social -category:forums";
+
+@Injectable()
+export class GmailClient {
+ constructor(private readonly api: GoogleApiClient) {}
+
+ /** The mailbox's own address and current historyId — the backfill anchor. */
+ async profile(accessToken: string): Promise<GoogleResult<Profile>> {
+ return this.api.get<Profile>(`${BASE}/profile`, accessToken);
+ }
+
+ /** Message ids in a time window, newest first. */
+ async listMessages(
+ accessToken: string,
+ options: {
+ after: Date;
+ before: Date;
+ pageToken?: string;
+ maxResults?: number;
+ },
+ ): Promise<GoogleResult<MessageList>> {
+ // Gmail's `after`/`before` take seconds since the epoch.
+ const after = Math.floor(options.after.getTime() / 1000);
+ const before = Math.ceil(options.before.getTime() / 1000);
+
+ return this.api.get<MessageList>(`${BASE}/messages`, accessToken, {
+ q: `${WORK_MAIL_QUERY} after:${after} before:${before}`,
+ maxResults: options.maxResults ?? 100,
+ pageToken: options.pageToken,
+ });
+ }
+
+ /**
+ * Changes since a historyId.
+ *
+ * A `startHistoryId` older than Gmail's retention window (documented as
+ * "typically at least one week") comes back as 404, which
+ * `GoogleApiClient` surfaces as `cursor-invalid`.
+ */
+ async listHistory(
+ accessToken: string,
+ options: { startHistoryId: string; pageToken?: string },
+ ): Promise<GoogleResult<HistoryList>> {
+ return this.api.get<HistoryList>(`${BASE}/history`, accessToken, {
+ startHistoryId: options.startHistoryId,
+ historyTypes: "messageAdded",
+ maxResults: 500,
+ pageToken: options.pageToken,
+ });
+ }
+
+ /** One message, with headers and body. */
+ async getMessage(
+ accessToken: string,
+ id: string,
+ ): Promise<GoogleResult<GmailMessage>> {
+ return this.api.get<GmailMessage>(`${BASE}/messages/${id}`, accessToken, {
+ format: "full",
+ });
+ }
+}
diff --git a/apps/api/src/google/google-api.client.ts b/apps/api/src/google/google-api.client.ts
new file mode 100644
index 00000000..686fe809
--- /dev/null
+++ b/apps/api/src/google/google-api.client.ts
@@ -0,0 +1,149 @@
+import { Injectable, Logger } from "@nestjs/common";
+
+/**
+ * What a Google API call did.
+ *
+ * The interesting cases are the two cursor invalidations, and they are separate
+ * variants rather than a status number because the whole sync design turns on
+ * them: Gmail answers an out-of-range `startHistoryId` with 404, Calendar
+ * answers a dead `syncToken` with 410, and both mean "your cursor is gone, fall
+ * back to a bounded resync" rather than "something broke".
+ */
+export type GoogleResult<T> =
+ | { outcome: "ok"; data: T }
+ | { outcome: "cursor-invalid"; reason: string }
+ | { outcome: "unauthorized"; reason: string }
+ | { outcome: "rate-limited"; reason: string; retryAfterMs: number }
+ | { outcome: "failed"; reason: string; retryable: boolean };
+
+const DEFAULT_TIMEOUT_MS = 20_000;
+
+/** Google's own suggestion when it rate limits us, with a sane floor. */
+const MIN_BACKOFF_MS = 30_000;
+const MAX_BACKOFF_MS = 15 * 60_000;
+
+@Injectable()
+export class GoogleApiClient {
+ private readonly logger = new Logger(GoogleApiClient.name);
+
+ /**
+ * A GET against a Google REST endpoint.
+ *
+ * Deliberately `fetch` rather than `googleapis`: we call four endpoints, the
+ * SDK is tens of megabytes of generated surface, and a serverless bundle pays
+ * for every byte on every cold start.
+ */
+ async get<T>(
+ url: string,
+ accessToken: string,
+ params: Record<string, string | number | boolean | undefined> = {},
+ ): Promise<GoogleResult<T>> {
+ const target = new URL(url);
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined) target.searchParams.set(key, String(value));
+ }
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
+
+ try {
+ const response = await fetch(target, {
+ headers: { authorization: `Bearer ${accessToken}` },
+ signal: controller.signal,
+ });
+
+ return await this.interpret<T>(response, target.pathname);
+ } catch (error) {
+ const aborted = error instanceof Error && error.name === "AbortError";
+ return {
+ outcome: "failed",
+ reason: aborted
+ ? `Timed out after ${DEFAULT_TIMEOUT_MS}ms.`
+ : error instanceof Error
+ ? error.message
+ : String(error),
+ retryable: true,
+ };
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+
+ private async interpret<T>(
+ response: Response,
+ path: string,
+ ): Promise<GoogleResult<T>> {
+ if (response.ok) {
+ return { outcome: "ok", data: (await response.json()) as T };
+ }
+
+ // Read the body for the reason, but never log it verbatim — Google echoes
+ // request parameters back in error messages, and those can carry addresses.
+ const detail = await this.reason(response);
+
+ switch (response.status) {
+ case 401:
+ return { outcome: "unauthorized", reason: detail };
+
+ // Gmail: `startHistoryId` is older than the retained history window.
+ case 404:
+ // Calendar: the `syncToken` expired or was invalidated by an ACL change.
+ case 410:
+ return { outcome: "cursor-invalid", reason: detail };
+
+ case 403:
+ // 403 is overloaded: quota exhaustion looks the same as a genuine
+ // permission failure until you read the reason. Only the quota flavour
+ // is worth backing off for; the rest is terminal.
+ if (/rate|quota|userRateLimitExceeded|limitExceeded/i.test(detail)) {
+ return {
+ outcome: "rate-limited",
+ reason: detail,
+ retryAfterMs: this.backoffFrom(response),
+ };
+ }
+ return { outcome: "failed", reason: detail, retryable: false };
+
+ case 429:
+ return {
+ outcome: "rate-limited",
+ reason: detail,
+ retryAfterMs: this.backoffFrom(response),
+ };
+
+ default: {
+ const retryable = response.status >= 500;
+ this.logger.warn({
+ message: "Google API call failed",
+ path,
+ status: response.status,
+ retryable,
+ });
+ return { outcome: "failed", reason: detail, retryable };
+ }
+ }
+ }
+
+ private backoffFrom(response: Response): number {
+ const header = response.headers.get("retry-after");
+ const seconds = header ? Number(header) : Number.NaN;
+ const suggested = Number.isFinite(seconds)
+ ? seconds * 1000
+ : MIN_BACKOFF_MS;
+
+ return Math.min(Math.max(suggested, MIN_BACKOFF_MS), MAX_BACKOFF_MS);
+ }
+
+ private async reason(response: Response): Promise<string> {
+ try {
+ const body = (await response.json()) as {
+ error?: { message?: string; status?: string };
+ };
+ return (
+ body.error?.message ?? body.error?.status ?? `HTTP ${response.status}`
+ );
+ } catch {
+ return `HTTP ${response.status}`;
+ }
+ }
+}
diff --git a/apps/api/src/google/google-connection.service.ts b/apps/api/src/google/google-connection.service.ts
new file mode 100644
index 00000000..2d0b1256
--- /dev/null
+++ b/apps/api/src/google/google-connection.service.ts
@@ -0,0 +1,244 @@
+import { type Db, GoogleSyncStatus } from "@crm/db";
+import { Injectable, Logger, NotFoundException } from "@nestjs/common";
+import { normalizeDomain } from "../companies/domain";
+import { ActivityStampService } from "../crm/activity-stamp.service";
+import { InjectDatabase } from "../database/database.constants";
+import {
+ SCOPE_FOR_SOURCE,
+ SYNC_SOURCES,
+ type SyncSource,
+} from "./google.constants";
+import { GoogleMatchService } from "./google-match.service";
+import { GoogleTokenService } from "./google-token.service";
+import { SyncStateService } from "./sync-state.service";
+
+export type SourceStatus = {
+ source: SyncSource;
+ connected: boolean;
+ status: GoogleSyncStatus | null;
+ lastSyncedAt: string | null;
+ lastError: string | null;
+ autoCreate: boolean;
+};
+
+export type ConnectionStatus = {
+ /** Whether Google issued a refresh token. False means reconnect. */
+ hasRefreshToken: boolean;
+ sources: SourceStatus[];
+};
+
+/**
+ * Everything the settings page asks about a rep's Google connection.
+ *
+ * Connection state is read from `Account.scope` rather than kept in a column of
+ * our own: the grant is the truth, and a boolean we maintain alongside it is a
+ * boolean that will eventually disagree with it.
+ */
+@Injectable()
+export class GoogleConnectionService {
+ private readonly logger = new Logger(GoogleConnectionService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly tokens: GoogleTokenService,
+ private readonly state: SyncStateService,
+ private readonly match: GoogleMatchService,
+ private readonly stamp: ActivityStampService,
+ ) {}
+
+ async status(userId: string): Promise<ConnectionStatus> {
+ // Reconcile first: the grant is the source of truth, and the sync rows are
+ // derived from it. Doing this here rather than in an OAuth-callback handler
+ // means the settings page is correct the moment it loads, with no
+ // coordination between the redirect and a mutation.
+ await this.onConnected(userId);
+
+ const [granted, rows, hasRefreshToken] = await Promise.all([
+ this.tokens.grantedScopes(userId),
+ this.state.listForUser(userId),
+ this.tokens.hasRefreshToken(userId),
+ ]);
+
+ const bySource = new Map(rows.map((row) => [row.source, row]));
+
+ const sources = SYNC_SOURCES.map((source): SourceStatus => {
+ const row = bySource.get(source);
+ const connected = granted.includes(SCOPE_FOR_SOURCE[source]);
+
+ return {
+ source,
+ connected,
+ status: row?.status ?? null,
+ lastSyncedAt: row?.lastSyncedAt?.toISOString() ?? null,
+ lastError: row?.lastError ?? null,
+ autoCreate: row?.autoCreate ?? false,
+ };
+ });
+
+ return { hasRefreshToken, sources };
+ }
+
+ /**
+ * Makes the sync rows match what Google has actually granted.
+ *
+ * Idempotent and safe to call repeatedly — `ensure` keeps the cursor of a
+ * mailbox already syncing. Called from `status` and from the cron\'s
+ * reconcile step, so a rep who grants the scopes and then closes the tab
+ * still gets synced without ever loading the settings page again.
+ */
+ async onConnected(userId: string): Promise<void> {
+ const [granted, existing] = await Promise.all([
+ this.tokens.grantedScopes(userId),
+ this.state.listForUser(userId),
+ ]);
+
+ const known = new Set(existing.map((row) => row.source));
+
+ const added: string[] = [];
+
+ for (const source of SYNC_SOURCES) {
+ if (!granted.includes(SCOPE_FOR_SOURCE[source])) continue;
+ if (known.has(source)) continue;
+
+ await this.state.ensure(userId, source, {
+ // Meetings are unambiguous, so calendar auto-creates from the start.
+ // Gmail is opt-in: the first week of mailbox auto-creation is where a
+ // bad rule shows up, and that should be a deliberate choice.
+ autoCreate: source === "calendar",
+ });
+
+ added.push(source);
+ }
+
+ if (added.length > 0) {
+ this.logger.log({ message: "Google connected", userId, sources: added });
+ }
+ }
+
+ /** Every user whose grant covers a source but who has no sync row yet. */
+ async reconcileAll(): Promise<void> {
+ const accounts = await this.db.account.findMany({
+ where: {
+ providerId: "google",
+ OR: SYNC_SOURCES.map((source) => ({
+ scope: { contains: SCOPE_FOR_SOURCE[source] },
+ })),
+ },
+ select: { userId: true },
+ });
+
+ for (const account of new Set(accounts.map((row) => row.userId))) {
+ await this.onConnected(account);
+ }
+ }
+
+ /**
+ * Deletes everything this user's mailbox put into the CRM, and re-imports
+ * from scratch.
+ *
+ * Deliberately *not* a "disconnect". Mailbox access is a condition of having
+ * an account here, so there is no supported state where a signed-in rep is
+ * not syncing — and a local disconnect could not create one anyway: the grant
+ * would still be there, and the next reconcile would rebuild the rows it had
+ * just deleted. Naming it for what it does avoids a button that appears to
+ * work and silently undoes itself.
+ *
+ * The real exit is `revoke`, which ends the grant and therefore the account's
+ * access to the CRM.
+ */
+ async purgeSyncedData(userId: string): Promise<{ purged: number }> {
+ // Cascades take the messages, attendees and projected activities with
+ // them, which is the point: "delete my mail from the CRM" should not need
+ // a migration to answer.
+ const [threads, events] = await this.db.$transaction([
+ this.db.emailThread.deleteMany({
+ where: { messages: { some: { syncedByUserId: userId } } },
+ }),
+ this.db.calendarEvent.deleteMany({ where: { syncedByUserId: userId } }),
+ ]);
+
+ // Those cascades took activities with them, so every stamp they were the
+ // high-water mark for is now overstated. `touch` cannot fix that — it only
+ // ever raises — so the stamps are rebuilt.
+ await this.stamp.recomputeAll();
+
+ const purged = threads.count + events.count;
+
+ this.logger.log({ message: "Synced data purged", userId, purged });
+
+ return { purged };
+ }
+
+ /** The explicit hard revoke. Kills sign-in access too — see the plan §3.4. */
+ async revoke(userId: string): Promise<{ revoked: boolean }> {
+ await this.state.remove(userId);
+ const revoked = await this.tokens.revoke(userId);
+ return { revoked };
+ }
+
+ async setAutoCreate(
+ userId: string,
+ source: SyncSource,
+ enabled: boolean,
+ ): Promise<void> {
+ const row = await this.state.get(userId, source);
+ if (!row) {
+ throw new NotFoundException(`${source} is not connected.`);
+ }
+
+ await this.state.setAutoCreate(userId, source, enabled);
+ }
+
+ /**
+ * Marks a domain as "not a customer".
+ *
+ * Optionally deletes what it already matched, because the reason someone
+ * presses this is that a vendor's domain is sitting on a timeline right now.
+ */
+ async suppressDomain(
+ domain: string,
+ options: { reason?: string; purge: boolean },
+ ): Promise<{ domain: string; purged: number }> {
+ const normalised = normalizeDomain(domain);
+ if (!normalised) {
+ throw new NotFoundException(`"${domain}" is not a domain.`);
+ }
+
+ const ours = await this.match.internalIdentity();
+ if (ours.domains.has(normalised)) {
+ throw new NotFoundException(
+ "That is our own domain — it is already excluded.",
+ );
+ }
+
+ await this.db.suppressedDomain.upsert({
+ where: { domain: normalised },
+ create: { domain: normalised, reason: options.reason ?? null },
+ update: { reason: options.reason ?? null },
+ });
+
+ if (!options.purge) return { domain: normalised, purged: 0 };
+
+ const company = await this.db.company.findUnique({
+ where: { domain: normalised },
+ select: { id: true },
+ });
+
+ if (!company) return { domain: normalised, purged: 0 };
+
+ const [threads, events] = await this.db.$transaction([
+ this.db.emailThread.deleteMany({ where: { companyId: company.id } }),
+ this.db.calendarEvent.deleteMany({ where: { companyId: company.id } }),
+ ]);
+
+ await this.stamp.recomputeAll();
+
+ this.logger.log({
+ message: "Domain suppressed",
+ domain: normalised,
+ purged: threads.count + events.count,
+ });
+
+ return { domain: normalised, purged: threads.count + events.count };
+ }
+}
diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.ts
new file mode 100644
index 00000000..64c56967
--- /dev/null
+++ b/apps/api/src/google/google-match.service.ts
@@ -0,0 +1,309 @@
+import { type Db, RecordSource } from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { ContactEnrichmentService } from "../enrichment/contact-enrichment.service";
+import { EnrichmentService } from "../enrichment/enrichment.service";
+import {
+ dominantDomain,
+ externalParticipants,
+ isDerivedName,
+ type Participant,
+ splitName,
+ workDomain,
+} from "./participants";
+
+/**
+ * The two sources that can create records.
+ *
+ * `RecordSource` is generated as a const object rather than a TS enum, so its
+ * members are values and this union is how you narrow to them in type position.
+ */
+export type SyncRecordSource =
+ | typeof RecordSource.EMAIL
+ | typeof RecordSource.CALENDAR;
+
+/** What a thread or an event resolved to. */
+export type MatchResult = {
+ companyId: string | null;
+ contactId: string | null;
+ /** The external participants that survived filtering, for the caller's log. */
+ external: Participant[];
+};
+
+/** Loaded once per sync pass and threaded through every item in it. */
+export type MatchContext = {
+ ourAddresses: ReadonlySet<string>;
+ ourDomains: ReadonlySet<string>;
+ suppressedDomains: ReadonlySet<string>;
+};
+
+export type MatchRequest = {
+ participants: readonly Participant[];
+ /**
+ * Whether this item is allowed to create records it cannot find.
+ *
+ * The caller decides, because the rule is per-source and per-item: a meeting
+ * qualifies on its own, an email thread only once the rep has replied. See
+ * the plan §6.
+ */
+ allowCreate: boolean;
+ source: SyncRecordSource;
+ /**
+ * Who ends up owning anything created.
+ *
+ * The rep whose mailbox produced the thread or the meeting — they are, by
+ * definition, the person with the relationship. Leaving it unassigned makes
+ * every auto-created record somebody else's problem, which is how a CRM ends
+ * up with a pile of ownerless rows nobody works.
+ */
+ ownerId: string;
+};
+
+/**
+ * Turns the people on a Google payload into a company and a contact.
+ *
+ * Used by both syncs, because the rule has to be identical: if calendar matched
+ * differently from Gmail, the same customer would land on two different company
+ * records depending on which arrived first.
+ */
+@Injectable()
+export class GoogleMatchService {
+ private readonly logger = new Logger(GoogleMatchService.name);
+
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly enrichment: EnrichmentService,
+ private readonly contacts: ContactEnrichmentService,
+ ) {}
+
+ /**
+ * Who counts as "us".
+ *
+ * Derived from the `User` table rather than configured: sign-in is Google-only
+ * behind an Internal consent screen, so every user is on a company domain by
+ * construction. That makes a `GOOGLE_WORKSPACE_DOMAIN` env var a second copy
+ * of a fact the database already holds — and one that is silently wrong the
+ * day the team adds a second domain. `workDomain` drops free hosts, so a
+ * stray personal address cannot poison the set.
+ *
+ * Loaded once per sync pass, not per item: it changes about once a quarter,
+ * and a thread-by-thread query would dominate the tick.
+ */
+ async internalIdentity(): Promise<{
+ addresses: Set<string>;
+ domains: Set<string>;
+ }> {
+ const users = await this.db.user.findMany({ select: { email: true } });
+
+ const addresses = new Set<string>();
+ const domains = new Set<string>();
+
+ for (const user of users) {
+ const email = user.email.toLowerCase();
+ addresses.add(email);
+
+ const domain = workDomain(email);
+ if (domain) domains.add(domain);
+ }
+
+ return { addresses, domains };
+ }
+
+ async suppressedDomains(): Promise<Set<string>> {
+ const rows = await this.db.suppressedDomain.findMany({
+ select: { domain: true },
+ });
+ return new Set(rows.map((row) => row.domain));
+ }
+
+ /**
+ * Resolves participants to a company and contact, creating them when the
+ * caller allows it and the guardrails pass.
+ *
+ * Returns `{ companyId: null, contactId: null }` when nothing matched and
+ * nothing was created — the caller's cue to drop the item entirely rather
+ * than store an unattached thread. Personal mail is never written.
+ */
+ async resolve(
+ request: MatchRequest,
+ context: MatchContext,
+ ): Promise<MatchResult> {
+ const external = externalParticipants(request.participants, {
+ ourDomains: context.ourDomains,
+ ourAddresses: context.ourAddresses,
+ suppressedDomains: context.suppressedDomains,
+ });
+
+ if (external.length === 0) {
+ return { companyId: null, contactId: null, external };
+ }
+
+ // An exact contact match is the strongest signal there is — `Contact.email`
+ // is unique, so this is the same person, not merely the same employer.
+ const contact = await this.db.contact.findFirst({
+ where: { email: { in: external.map((person) => person.email) } },
+ select: { id: true, companyId: true },
+ });
+
+ if (contact) {
+ return {
+ companyId: contact.companyId,
+ contactId: contact.id,
+ external,
+ };
+ }
+
+ const domains = [
+ ...new Set(
+ external
+ .map((person) => workDomain(person.email))
+ .filter((domain): domain is string => domain !== null),
+ ),
+ ];
+
+ const known = await this.db.company.findMany({
+ where: { domain: { in: domains } },
+ select: { id: true, domain: true },
+ });
+
+ const knownDomains = new Set(
+ known
+ .map((company) => company.domain)
+ .filter((domain): domain is string => domain !== null),
+ );
+
+ const domain = dominantDomain(external, knownDomains);
+ if (!domain) return { companyId: null, contactId: null, external };
+
+ const existing = known.find((company) => company.domain === domain);
+ if (existing) {
+ return {
+ companyId: existing.id,
+ // Known company, unknown person. Creating the contact is safe here
+ // even without `allowCreate`: we already sell to them, and a thread
+ // attributed to the company with no name against it is worse.
+ contactId: request.allowCreate
+ ? await this.createContact(external, domain, existing.id, request)
+ : null,
+ external,
+ };
+ }
+
+ if (!request.allowCreate) {
+ return { companyId: null, contactId: null, external };
+ }
+
+ return this.create(external, domain, request);
+ }
+
+ /**
+ * 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.
+ */
+ private async create(
+ external: Participant[],
+ domain: string,
+ request: MatchRequest,
+ ): Promise<MatchResult> {
+ const lead =
+ external.find((person) => workDomain(person.email) === domain) ??
+ external[0];
+
+ if (!lead) return { companyId: null, contactId: null, external };
+
+ const companyId = await this.enrichment.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.
+ return { companyId: null, contactId: null, external };
+ }
+
+ await this.db.company.update({
+ where: { id: companyId },
+ data: { source: request.source },
+ });
+
+ const contactId = await this.createContact(
+ external,
+ domain,
+ companyId,
+ request,
+ );
+
+ this.logger.log({
+ message: "Company auto-created from Google sync",
+ companyId,
+ domain,
+ source: request.source,
+ });
+
+ return { companyId, contactId, external };
+ }
+
+ /** Upserts the person on the domain, so a re-sync does not duplicate them. */
+ private async createContact(
+ external: Participant[],
+ domain: string,
+ companyId: string,
+ request: MatchRequest,
+ ): Promise<string | null> {
+ const person = external.find(
+ (candidate) => workDomain(candidate.email) === domain,
+ );
+ if (!person) return null;
+
+ const { firstName, lastName } = splitName(person.name, person.email);
+
+ // `Contact.email` is unique, so this is the race-safe form: two reps'
+ // syncs hitting the same new person resolve to one row.
+ const contact = await this.db.contact.upsert({
+ where: { email: person.email },
+ create: {
+ firstName,
+ lastName,
+ email: person.email,
+ companyId,
+ source: request.source,
+ ownerId: request.ownerId,
+ },
+ // Never overwrite a human's edits with a header's display name.
+ update: {},
+ select: { id: true, firstName: true, lastName: true },
+ });
+
+ // Google hands back an attendee with no `displayName` far more often than
+ // it hands back one with a name, so a contact is routinely created from the
+ // address alone and then met again later with a real name attached. Taking
+ // the better name when it arrives is the difference between "Abigham" and
+ // "Abbie Bigham" — but only over a name nobody has improved on.
+ const hasRealName = Boolean(person.name?.trim());
+ const isPlaceholder = isDerivedName(
+ person.email,
+ contact.firstName,
+ contact.lastName,
+ );
+
+ if (hasRealName && isPlaceholder) {
+ await this.db.contact.update({
+ where: { id: contact.id },
+ data: { firstName, lastName },
+ });
+ 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.
+ if (isPlaceholder && !hasRealName) {
+ this.contacts.enqueue(contact.id);
+ }
+
+ return contact.id;
+ }
+}
diff --git a/apps/api/src/google/google-sync.service.ts b/apps/api/src/google/google-sync.service.ts
new file mode 100644
index 00000000..781b3366
--- /dev/null
+++ b/apps/api/src/google/google-sync.service.ts
@@ -0,0 +1,135 @@
+import { Injectable, Logger } from "@nestjs/common";
+import { CalendarSyncService } from "./calendar-sync.service";
+import { GmailSyncService } from "./gmail-sync.service";
+import type { SyncSource } from "./google.constants";
+import { GoogleConnectionService } from "./google-connection.service";
+import { SyncStateService } from "./sync-state.service";
+
+/**
+ * How long a tick may run.
+ *
+ * Vercel's default function timeout is generous, but a cron that runs every five
+ * minutes must finish well inside five minutes or ticks overlap. The budget is
+ * checked between accounts, so one slow mailbox delays the next tick rather
+ * than being cut off mid-write.
+ */
+const TICK_BUDGET_MS = 60_000;
+
+export type TickSummary = {
+ attempted: number;
+ synced: number;
+ skipped: number;
+ failed: number;
+ durationMs: number;
+};
+
+/**
+ * Runs the due syncs.
+ *
+ * Deliberately not the in-process `EnrichmentQueue`: that queue drops queued
+ * work on shutdown, which is right for enrichment (the company stays PENDING
+ * and the next re-enrich picks it up) and wrong here, because a dropped sync
+ * silently leaves a gap in someone's timeline. State lives in Postgres and the
+ * cron is the scheduler.
+ */
+@Injectable()
+export class GoogleSyncService {
+ private readonly logger = new Logger(GoogleSyncService.name);
+
+ constructor(
+ private readonly state: SyncStateService,
+ private readonly calendar: CalendarSyncService,
+ private readonly gmail: GmailSyncService,
+ private readonly connections: GoogleConnectionService,
+ ) {}
+
+ /** One cron tick: every account that is due, until the budget runs out. */
+ async runDue(): Promise<TickSummary> {
+ const startedAt = Date.now();
+ const summary: TickSummary = {
+ attempted: 0,
+ synced: 0,
+ skipped: 0,
+ failed: 0,
+ durationMs: 0,
+ };
+
+ // Pick up anyone who granted the scopes but has no sync row yet — a rep who
+ // connected and closed the tab never triggers anything else.
+ await this.connections.reconcileAll();
+
+ const due = await this.state.due(new Date());
+
+ for (const row of due) {
+ if (Date.now() - startedAt > TICK_BUDGET_MS) {
+ this.logger.log({
+ message: "Sync tick budget reached",
+ remaining: due.length - summary.attempted,
+ });
+ break;
+ }
+
+ summary.attempted += 1;
+
+ try {
+ const outcome = await this.runOne(row.userId, row.source as SyncSource);
+
+ if (outcome === null || outcome.status === "skipped") {
+ summary.skipped += 1;
+ } else if (
+ outcome.status === "failed" ||
+ outcome.status === "reconnect"
+ ) {
+ summary.failed += 1;
+ } else {
+ summary.synced += 1;
+ }
+ } catch (error) {
+ summary.failed += 1;
+ // One account's crash must not abandon the rest of the tick.
+ await this.state.markFailed(
+ row.id,
+ error instanceof Error ? error.message : String(error),
+ );
+ this.logger.error(
+ {
+ message: "Sync threw",
+ userId: row.userId,
+ source: row.source,
+ },
+ error instanceof Error ? error.stack : String(error),
+ );
+ }
+ }
+
+ summary.durationMs = Date.now() - startedAt;
+
+ this.logger.log({
+ message: "Google sync tick",
+ attempted: summary.attempted,
+ synced: summary.synced,
+ skipped: summary.skipped,
+ failed: summary.failed,
+ durationMs: summary.durationMs,
+ });
+
+ return summary;
+ }
+
+ /** One account, one source. Also the path `google.syncNow` takes. */
+ async runOne(userId: string, source: SyncSource) {
+ const row = await this.state.get(userId, source);
+ if (!row) return null;
+
+ return source === "calendar"
+ ? this.calendar.sync(row)
+ : this.gmail.sync(row);
+ }
+
+ /** Every source for one user, for the "Sync now" button. */
+ async runForUser(userId: string): Promise<void> {
+ for (const source of ["calendar", "gmail"] as const) {
+ await this.runOne(userId, source);
+ }
+ }
+}
diff --git a/apps/api/src/google/google-token.service.ts b/apps/api/src/google/google-token.service.ts
new file mode 100644
index 00000000..b4b67714
--- /dev/null
+++ b/apps/api/src/google/google-token.service.ts
@@ -0,0 +1,166 @@
+import { auth } from "@crm/auth";
+import { type Db } from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import {
+ GOOGLE_PROVIDER_ID,
+ SCOPE_FOR_SOURCE,
+ type SyncSource,
+} from "./google.constants";
+
+/** Why a token could not be produced. Callers branch on this, not on a string. */
+export type TokenFailure =
+ /** No refresh token, or Google rejected it. The rep has to reconnect. */
+ | { outcome: "needs-reconnect"; reason: string }
+ /** The grant never included this scope. Not an error — just not connected. */
+ | { outcome: "not-connected"; reason: string };
+
+export type TokenResult = { outcome: "ok"; accessToken: string } | TokenFailure;
+
+/**
+ * The only place an access token is obtained.
+ *
+ * Nothing reads `Account.accessToken` directly: Better Auth's `getAccessToken`
+ * refreshes an expired token and persists the new one, so a hand-rolled refresh
+ * would be a second, worse implementation of the same thing racing the first.
+ */
+@Injectable()
+export class GoogleTokenService {
+ private readonly logger = new Logger(GoogleTokenService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ /** The scopes Google has actually granted this user, from the account row. */
+ async grantedScopes(userId: string): Promise<string[]> {
+ const account = await this.db.account.findFirst({
+ where: { userId, providerId: GOOGLE_PROVIDER_ID },
+ select: { scope: true },
+ });
+
+ return (
+ account?.scope
+ ?.split(",")
+ .map((scope) => scope.trim())
+ .filter(Boolean) ?? []
+ );
+ }
+
+ /** Whether the grant covers a source. The grant *is* the connection state. */
+ async isConnected(userId: string, source: SyncSource): Promise<boolean> {
+ const scopes = await this.grantedScopes(userId);
+ return scopes.includes(SCOPE_FOR_SOURCE[source]);
+ }
+
+ /**
+ * Whether Google issued a refresh token for this grant.
+ *
+ * Google only returns one when it re-prompts. If a reconnect slipped through
+ * without a prompt there is no refresh token, and everything works until the
+ * access token expires an hour later — so the connect flow checks this
+ * immediately rather than discovering it on the first cron tick.
+ */
+ async hasRefreshToken(userId: string): Promise<boolean> {
+ const account = await this.db.account.findFirst({
+ where: { userId, providerId: GOOGLE_PROVIDER_ID },
+ select: { refreshToken: true },
+ });
+
+ return Boolean(account?.refreshToken);
+ }
+
+ /**
+ * A valid access token for a source, or why there isn't one.
+ *
+ * Returns a result rather than throwing: "this rep never connected Gmail" is
+ * an ordinary state for a cron tick iterating every user, not an exception.
+ */
+ async accessTokenFor(
+ userId: string,
+ source: SyncSource,
+ ): Promise<TokenResult> {
+ if (!(await this.isConnected(userId, source))) {
+ return {
+ outcome: "not-connected",
+ reason: `The ${source} scope has not been granted.`,
+ };
+ }
+
+ try {
+ const { accessToken } = await auth.api.getAccessToken({
+ body: { providerId: GOOGLE_PROVIDER_ID, userId },
+ });
+
+ if (!accessToken) {
+ return {
+ outcome: "needs-reconnect",
+ reason: "Google returned no access token.",
+ };
+ }
+
+ return { outcome: "ok", accessToken };
+ } catch (error) {
+ // A refresh failure means the refresh token is gone — revoked, expired
+ // or never issued. Retrying cannot fix it, so this is terminal until
+ // the rep reconnects.
+ this.logger.warn({
+ message: "Google token refresh failed",
+ userId,
+ source,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+
+ return {
+ outcome: "needs-reconnect",
+ reason: "Google would not refresh the access token.",
+ };
+ }
+ }
+
+ /**
+ * Revokes the grant at Google.
+ *
+ * This kills the *whole* grant, sign-in included, because one OAuth client
+ * means one grant per user. It is deliberately not what the disconnect button
+ * calls — see `GoogleConnectionService.disconnect`.
+ */
+ async revoke(userId: string): Promise<boolean> {
+ const account = await this.db.account.findFirst({
+ where: { userId, providerId: GOOGLE_PROVIDER_ID },
+ select: { refreshToken: true, accessToken: true },
+ });
+
+ const token = account?.refreshToken ?? account?.accessToken;
+ if (!token) return false;
+
+ const response = await fetch("https://oauth2.googleapis.com/revoke", {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({ token }),
+ });
+
+ if (!response.ok) {
+ this.logger.warn({
+ message: "Google token revocation failed",
+ userId,
+ status: response.status,
+ });
+ return false;
+ }
+
+ // The stored tokens are dead now; clearing them stops every later call
+ // from trying to use them and getting a confusing 401.
+ await this.db.account.updateMany({
+ where: { userId, providerId: GOOGLE_PROVIDER_ID },
+ data: {
+ accessToken: null,
+ refreshToken: null,
+ scope: null,
+ accessTokenExpiresAt: null,
+ refreshTokenExpiresAt: null,
+ },
+ });
+
+ this.logger.log({ message: "Google access revoked", userId });
+ return true;
+ }
+}
diff --git a/apps/api/src/google/google.constants.ts b/apps/api/src/google/google.constants.ts
new file mode 100644
index 00000000..cdd3b688
--- /dev/null
+++ b/apps/api/src/google/google.constants.ts
@@ -0,0 +1,25 @@
+import { CALENDAR_SCOPE, GMAIL_SCOPE } from "@crm/auth";
+
+/**
+ * The scope strings come from `@crm/auth`, which is where the OAuth request is
+ * actually made. Re-declaring them here would be two lists that drift, and the
+ * failure is silent: the grant looks right and `isConnected()` says no.
+ */
+export { CALENDAR_SCOPE, GMAIL_SCOPE, SYNC_SCOPES } from "@crm/auth";
+
+/**
+ * The two sources sync independently: they have separate cursors, separate
+ * failure modes and separate auto-create rules, so they get separate
+ * `MailboxSync` rows rather than one row with two of everything.
+ */
+export const SYNC_SOURCES = ["calendar", "gmail"] as const;
+export type SyncSource = (typeof SYNC_SOURCES)[number];
+
+/** Which scope has to be granted for a source to be syncable. */
+export const SCOPE_FOR_SOURCE: Record<SyncSource, string> = {
+ calendar: CALENDAR_SCOPE,
+ gmail: GMAIL_SCOPE,
+};
+
+/** Better Auth's provider id. One provider, one grant — see the plan §3.4. */
+export const GOOGLE_PROVIDER_ID = "google";
diff --git a/apps/api/src/google/google.contracts.ts b/apps/api/src/google/google.contracts.ts
new file mode 100644
index 00000000..bcdc31c3
--- /dev/null
+++ b/apps/api/src/google/google.contracts.ts
@@ -0,0 +1,29 @@
+import { z } from "zod";
+import { SYNC_SOURCES } from "./google.constants";
+
+export const syncSourceInput = z.object({
+ source: z.enum(SYNC_SOURCES),
+});
+
+export const setAutoCreateInput = z.object({
+ source: z.enum(SYNC_SOURCES),
+ enabled: z.boolean(),
+});
+
+export const suppressDomainInput = z.object({
+ domain: z.string().trim().min(1),
+ reason: z.string().trim().max(200).optional(),
+ /** Also remove the threads and events this domain already produced. */
+ purge: z.boolean().default(true),
+});
+
+export const threadInput = z.object({
+ threadId: z.string(),
+});
+
+export const calendarEventInput = z.object({
+ eventId: z.string(),
+});
+
+export type SetAutoCreateInput = z.infer<typeof setAutoCreateInput>;
+export type SuppressDomainInput = z.infer<typeof suppressDomainInput>;
diff --git a/apps/api/src/google/google.module.ts b/apps/api/src/google/google.module.ts
new file mode 100644
index 00000000..ed40b7eb
--- /dev/null
+++ b/apps/api/src/google/google.module.ts
@@ -0,0 +1,45 @@
+import { Module } from "@nestjs/common";
+import { EnrichmentModule } from "../enrichment/enrichment.module";
+import { TrpcModule } from "../trpc/trpc.module";
+import { CalendarClient } from "./calendar.client";
+import { CalendarSyncService } from "./calendar-sync.service";
+import { ConversationService } from "./conversation.service";
+import { GmailClient } from "./gmail.client";
+import { GmailSyncService } from "./gmail-sync.service";
+import { GoogleRouter } from "./google.router";
+import { GoogleApiClient } from "./google-api.client";
+import { GoogleConnectionService } from "./google-connection.service";
+import { GoogleMatchService } from "./google-match.service";
+import { GoogleSyncService } from "./google-sync.service";
+import { GoogleTokenService } from "./google-token.service";
+import { SyncController } from "./sync.controller";
+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.
+ */
+@Module({
+ imports: [TrpcModule, EnrichmentModule],
+ controllers: [SyncController],
+ providers: [
+ GoogleApiClient,
+ GoogleTokenService,
+ SyncStateService,
+ GoogleMatchService,
+ CalendarClient,
+ CalendarSyncService,
+ GmailClient,
+ GmailSyncService,
+ GoogleSyncService,
+ GoogleConnectionService,
+ ConversationService,
+ GoogleRouter,
+ ],
+ exports: [GoogleSyncService, GoogleConnectionService],
+})
+export class GoogleModule {}
diff --git a/apps/api/src/google/google.router.ts b/apps/api/src/google/google.router.ts
new file mode 100644
index 00000000..b7061309
--- /dev/null
+++ b/apps/api/src/google/google.router.ts
@@ -0,0 +1,100 @@
+import { Inject } from "@nestjs/common";
+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 { ConversationService } from "./conversation.service";
+import {
+ calendarEventInput,
+ setAutoCreateInput,
+ suppressDomainInput,
+ threadInput,
+} from "./google.contracts";
+import { GoogleConnectionService } from "./google-connection.service";
+import { GoogleSyncService } from "./google-sync.service";
+
+/**
+ * The Google integration's data surface.
+ *
+ * Connecting is absent on purpose: the browser calls `authClient.linkSocial()`
+ * directly, and `status` reads the result off the granted scopes. A procedure
+ * here would only be a second way to describe the same grant.
+ */
+@Router({ alias: "google" })
+@UseMiddlewares(AuthMiddleware)
+export class GoogleRouter {
+ constructor(
+ @Inject(GoogleConnectionService)
+ private readonly connection: GoogleConnectionService,
+ @Inject(GoogleSyncService) private readonly sync: GoogleSyncService,
+ @Inject(ConversationService)
+ private readonly conversations: ConversationService,
+ ) {}
+
+ @Query()
+ async status(@Ctx() ctx: AuthedTrpcContext) {
+ return this.connection.status(ctx.user.id);
+ }
+
+ /**
+ * Deletes what this mailbox put into the CRM and re-imports it.
+ *
+ * Not a disconnect: syncing is a condition of having an account, so there is
+ * no state where a signed-in rep is not syncing. `revokeAccess` is the exit.
+ */
+ @Mutation()
+ async purgeSyncedData(@Ctx() ctx: AuthedTrpcContext) {
+ return this.connection.purgeSyncedData(ctx.user.id);
+ }
+
+ /** Hard revoke. Ends sign-in access too — the UI confirms before calling it. */
+ @Mutation()
+ async revokeAccess(@Ctx() ctx: AuthedTrpcContext) {
+ return this.connection.revoke(ctx.user.id);
+ }
+
+ @Mutation()
+ async syncNow(@Ctx() ctx: AuthedTrpcContext) {
+ await this.sync.runForUser(ctx.user.id);
+ return this.connection.status(ctx.user.id);
+ }
+
+ @Mutation({ input: setAutoCreateInput })
+ async setAutoCreate(
+ @Ctx() ctx: AuthedTrpcContext,
+ @Input() input: z.infer<typeof setAutoCreateInput>,
+ ) {
+ await this.connection.setAutoCreate(
+ ctx.user.id,
+ input.source,
+ input.enabled,
+ );
+ return this.connection.status(ctx.user.id);
+ }
+
+ @Mutation({ input: suppressDomainInput })
+ async suppressDomain(@Input() input: z.infer<typeof suppressDomainInput>) {
+ return this.connection.suppressDomain(input.domain, {
+ reason: input.reason,
+ purge: input.purge,
+ });
+ }
+
+ /** The messages behind a timeline entry. Only called when one is expanded. */
+ @Query({ input: threadInput })
+ async thread(@Input("threadId") threadId: string) {
+ return this.conversations.thread(threadId);
+ }
+
+ @Query({ input: calendarEventInput })
+ async event(@Input("eventId") eventId: string) {
+ return this.conversations.event(eventId);
+ }
+}
diff --git a/apps/api/src/google/mime.ts b/apps/api/src/google/mime.ts
new file mode 100644
index 00000000..ffa084c8
--- /dev/null
+++ b/apps/api/src/google/mime.ts
@@ -0,0 +1,179 @@
+/**
+ * Turning a Gmail payload into something readable.
+ *
+ * All pure: the awkward cases here (nested multiparts, quoted-printable, a
+ * forty-message quote trail) are exactly what wants table-driven tests without
+ * a network or a database.
+ */
+
+export type GmailHeader = { name?: string; value?: string };
+
+export type GmailPart = {
+ mimeType?: string;
+ filename?: string;
+ headers?: GmailHeader[];
+ body?: { data?: string; size?: number; attachmentId?: string };
+ parts?: GmailPart[];
+};
+
+/** Case-insensitive header lookup — Gmail is inconsistent about casing. */
+export function header(
+ headers: readonly GmailHeader[] | undefined,
+ name: string,
+): string | null {
+ const wanted = name.toLowerCase();
+ const found = headers?.find((entry) => entry.name?.toLowerCase() === wanted);
+ return found?.value?.trim() ?? null;
+}
+
+/** Gmail encodes every body as base64url, which `atob` will not accept. */
+export function decodeBase64Url(data: string): string {
+ const normalised = data.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalised.padEnd(
+ normalised.length + ((4 - (normalised.length % 4)) % 4),
+ "=",
+ );
+
+ try {
+ return Buffer.from(padded, "base64").toString("utf8");
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * The plain-text body.
+ *
+ * Prefers `text/plain`; falls back to stripping tags out of `text/html`,
+ * because plenty of senders ship HTML only and "(no body)" on the timeline is
+ * useless. Attachments are skipped — v1 stores no bytes.
+ */
+export function plainTextBody(payload: GmailPart | undefined): string {
+ if (!payload) return "";
+
+ const plain = findPart(payload, "text/plain");
+ if (plain?.body?.data) return decodeBase64Url(plain.body.data);
+
+ const html = findPart(payload, "text/html");
+ if (html?.body?.data) return stripHtml(decodeBase64Url(html.body.data));
+
+ if (payload.body?.data && !payload.filename) {
+ return decodeBase64Url(payload.body.data);
+ }
+
+ return "";
+}
+
+/** Depth-first search for a mime type, skipping attachment parts. */
+function findPart(part: GmailPart, mimeType: string): GmailPart | null {
+ if (part.mimeType === mimeType && !part.filename && part.body?.data) {
+ return part;
+ }
+
+ for (const child of part.parts ?? []) {
+ const found = findPart(child, mimeType);
+ if (found) return found;
+ }
+
+ return null;
+}
+
+export function stripHtml(html: string): string {
+ return html
+ .replace(/<style[\s\S]*?<\/style>/gi, "")
+ .replace(/<script[\s\S]*?<\/script>/gi, "")
+ .replace(/<br\s*\/?>/gi, "\n")
+ .replace(/<\/(p|div|tr|li|h[1-6])>/gi, "\n")
+ .replace(/<[^>]+>/g, "")
+ .replace(/&nbsp;/g, " ")
+ .replace(/&amp;/g, "&")
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+/**
+ * Where the quoted history starts.
+ *
+ * A reply carries the entire conversation beneath it, so storing the raw body
+ * would mean the same text N times over a thread and a timeline entry that is
+ * mostly `>`. Each pattern is a line that begins the quote; everything from the
+ * first match is dropped.
+ */
+const QUOTE_MARKERS: RegExp[] = [
+ // "On Tue, 5 Aug 2025 at 14:02, Jane <[email protected]> wrote:"
+ /^\s*On .+ wrote:\s*$/m,
+ // Outlook and most corporate clients.
+ /^\s*-{2,}\s*Original Message\s*-{2,}\s*$/im,
+ /^\s*_{5,}\s*$/m,
+ /^\s*From:\s.+$/m,
+ // Apple Mail.
+ /^\s*Begin forwarded message:\s*$/im,
+ // Gmail's own divider when the client collapses history.
+ /^\s*-{3,}\s*Forwarded message\s*-{3,}\s*$/im,
+];
+
+export function stripQuotedHistory(body: string): string {
+ let cut = body.length;
+
+ for (const marker of QUOTE_MARKERS) {
+ const match = marker.exec(body);
+ if (match && match.index < cut) cut = match.index;
+ }
+
+ let trimmed = body.slice(0, cut);
+
+ // Whatever survives, drop trailing lines that are pure quote — some clients
+ // interleave rather than appending.
+ const lines = trimmed.split("\n");
+ while (lines.length > 0 && /^\s*>/.test(lines[lines.length - 1] ?? "")) {
+ lines.pop();
+ }
+ trimmed = lines.join("\n");
+
+ return trimmed.replace(/\n{3,}/g, "\n\n").trim();
+}
+
+/**
+ * The id of the conversation root, from the reply chain.
+ *
+ * `References` lists the ancestry oldest-first, so its first entry is the root.
+ * Falling back to `In-Reply-To` handles clients that omit `References`, and
+ * finally a message that starts a thread is its own root.
+ *
+ * This is what makes a thread global. Gmail's `threadId` is scoped to one
+ * mailbox, so two reps on the same conversation report different ids for it —
+ * keying on those would put one conversation on a company's timeline twice.
+ */
+export function rootMessageId(
+ headers: readonly GmailHeader[] | undefined,
+): string | null {
+ const references = header(headers, "references");
+ if (references) {
+ const first = references
+ .split(/\s+/)
+ .find((entry) => entry.startsWith("<"));
+ if (first) return normaliseMessageId(first);
+ }
+
+ const inReplyTo = header(headers, "in-reply-to");
+ if (inReplyTo) return normaliseMessageId(inReplyTo);
+
+ const own = header(headers, "message-id");
+ return own ? normaliseMessageId(own) : null;
+}
+
+/** Strips the angle brackets so `<a@b>` and `a@b` are the same identity. */
+export function normaliseMessageId(value: string): string {
+ return value.trim().replace(/^</, "").replace(/>$/, "").toLowerCase();
+}
+
+/** A short preview for the timeline row. Never the whole body. */
+export function snippetOf(body: string, limit = 200): string | null {
+ const flat = body.replace(/\s+/g, " ").trim();
+ if (!flat) return null;
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
+}
diff --git a/apps/api/src/google/participants.ts b/apps/api/src/google/participants.ts
new file mode 100644
index 00000000..88505425
--- /dev/null
+++ b/apps/api/src/google/participants.ts
@@ -0,0 +1,281 @@
+import { domainFromEmail } from "../companies/domain";
+
+/** One address off a header or an attendee list. */
+export type Participant = {
+ email: string;
+ name: string | null;
+};
+
+/**
+ * Local parts that never belong to a person worth putting in a CRM.
+ *
+ * Matched as whole local parts or prefixes: `noreply@` and `no-reply-1234@`
+ * are both machines, but `robert@` must not be caught by `bot`.
+ */
+const AUTOMATED_LOCAL_PARTS = [
+ "noreply",
+ "no-reply",
+ "donotreply",
+ "do-not-reply",
+ "notifications",
+ "notification",
+ "mailer-daemon",
+ "postmaster",
+ "bounce",
+ "bounces",
+ "auto-confirm",
+ "automated",
+ // Scheduling tools send the invite from their own address and put the
+ // organiser's name in the display name, so without these you get a contact
+ // called "Grand Ventures" whose email is [email protected].
+ "calendar-invite",
+ "calendar",
+ "invite",
+ "invites",
+ "invitations",
+ "meetings",
+ "scheduling",
+ "booking",
+ "bookings",
+ "reply",
+ "support",
+ "help",
+ "hello",
+ "info",
+ "contact",
+ "sales",
+ "billing",
+ "accounts",
+ "team",
+];
+
+/**
+ * Parses one address out of a mail header.
+ *
+ * Handles the three shapes Gmail actually returns: `[email protected]`,
+ * `Name <[email protected]>`, and `"Last, First" <[email protected]>`. Anything else yields null
+ * rather than a half-parsed address, because a junk `fromEmail` is worse than a
+ * dropped one — it becomes a contact.
+ */
+export function parseAddress(input: string): Participant | null {
+ const trimmed = input.trim();
+ if (!trimmed) return null;
+
+ const angled = trimmed.match(/^(.*)<([^<>]+)>\s*$/);
+
+ const rawEmail = (angled?.[2] ?? trimmed).trim().toLowerCase();
+ if (!isEmailish(rawEmail)) return null;
+
+ const rawName = angled?.[1]?.trim() ?? "";
+ // Display names arrive quoted more often than not, and the quotes are not
+ // part of anybody's name.
+ const name = rawName.replace(/^"(.*)"$/, "$1").trim();
+
+ return { email: rawEmail, name: name || null };
+}
+
+/** Splits a header that may carry several comma-separated addresses. */
+export function parseAddressList(
+ header: string | null | undefined,
+): Participant[] {
+ if (!header) return [];
+
+ const parts: string[] = [];
+ let current = "";
+ let inQuotes = false;
+ let inAngles = false;
+
+ // Not a plain `split(",")`: `"Last, First" <[email protected]>` contains a comma that
+ // is not a separator, and splitting on it produces two broken addresses.
+ for (const char of header) {
+ if (char === '"') inQuotes = !inQuotes;
+ if (char === "<") inAngles = true;
+ if (char === ">") inAngles = false;
+
+ if (char === "," && !inQuotes && !inAngles) {
+ parts.push(current);
+ current = "";
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+
+ const seen = new Set<string>();
+ const participants: Participant[] = [];
+
+ for (const part of parts) {
+ const parsed = parseAddress(part);
+ if (!parsed || seen.has(parsed.email)) continue;
+ seen.add(parsed.email);
+ participants.push(parsed);
+ }
+
+ return participants;
+}
+
+/** Whether an address is a machine rather than a person. */
+export function isAutomatedAddress(email: string): boolean {
+ const local = email.split("@")[0]?.toLowerCase() ?? "";
+ if (!local) return true;
+
+ return AUTOMATED_LOCAL_PARTS.some(
+ (pattern) =>
+ local === pattern ||
+ local.startsWith(`${pattern}-`) ||
+ local.startsWith(`${pattern}+`) ||
+ local.startsWith(`${pattern}_`),
+ );
+}
+
+/**
+ * Whether a name looks like it was derived from the address rather than given.
+ *
+ * `splitName` is deterministic, so a stored name that matches exactly what it
+ * would produce from the email alone is a placeholder nobody has improved on.
+ * That is the licence to overwrite it when a real display name turns up — and
+ * the guarantee that a name a human typed is never touched.
+ */
+export function isDerivedName(
+ email: string,
+ firstName: string,
+ lastName: string | null,
+): boolean {
+ const derived = splitName(null, email);
+ return (
+ derived.firstName === firstName && (derived.lastName ?? null) === lastName
+ );
+}
+
+/** A bare, lowercased hostname, or null for a free host or a malformed address. */
+export function workDomain(email: string): string | null {
+ return domainFromEmail(email);
+}
+
+export type ExternalFilterOptions = {
+ /**
+ * Our own domains — everyone on one is "us", not a lead.
+ *
+ * A set rather than a single domain: derived from the `User` table, so a team
+ * spread across two domains is handled without configuration.
+ */
+ ourDomains: ReadonlySet<string>;
+ /** Every address that belongs to a CRM user, for multi-domain teams. */
+ ourAddresses: ReadonlySet<string>;
+ /** Domains a human has marked "not a customer". */
+ suppressedDomains: ReadonlySet<string>;
+};
+
+/**
+ * The external side of a conversation.
+ *
+ * Drops our own people, machines, free hosts and suppressed domains, in that
+ * order. What survives is the set of addresses that could plausibly identify a
+ * company we sell to.
+ */
+export function externalParticipants(
+ participants: readonly Participant[],
+ options: ExternalFilterOptions,
+): Participant[] {
+ return participants.filter((participant) => {
+ if (options.ourAddresses.has(participant.email)) return false;
+
+ const domain = workDomain(participant.email);
+ // `workDomain` already returns null for gmail.com and friends, which is
+ // what keeps a lead's personal address from becoming a "Gmail" company.
+ if (!domain) return false;
+ if (options.ourDomains.has(domain)) return false;
+ if (options.suppressedDomains.has(domain)) return false;
+ if (isAutomatedAddress(participant.email)) return false;
+
+ return true;
+ });
+}
+
+/**
+ * The domain a thread or an event is really about.
+ *
+ * A customer call often has their lawyer or their auditor on it, so the most
+ * represented domain wins. `preferKnown` lets the caller break ties with
+ * "whichever of these we already have a company for", which is almost always
+ * the right answer and is why it is passed in rather than guessed here.
+ */
+export function dominantDomain(
+ participants: readonly Participant[],
+ preferKnown: ReadonlySet<string> = new Set(),
+): string | null {
+ const counts = new Map<string, number>();
+
+ for (const participant of participants) {
+ const domain = workDomain(participant.email);
+ if (!domain) continue;
+ counts.set(domain, (counts.get(domain) ?? 0) + 1);
+ }
+
+ if (counts.size === 0) return null;
+
+ let best: string | null = null;
+ let bestScore = -1;
+
+ for (const [domain, count] of counts) {
+ // A known company outranks a stranger with the same headcount on the
+ // thread; otherwise a single cc'd lawyer could steal the match.
+ const score = count * 2 + (preferKnown.has(domain) ? 1 : 0);
+ if (score > bestScore) {
+ best = domain;
+ bestScore = score;
+ }
+ }
+
+ return best;
+}
+
+/**
+ * Splits a display name into first and last.
+ *
+ * Everything after the first token is the surname, which is wrong for a
+ * minority of names and right for the overwhelming majority — and a contact
+ * whose surname reads "van der Berg" is fixable in one edit, whereas no name at
+ * all is a row nobody recognises.
+ */
+export function splitName(
+ name: string | null,
+ email: string,
+): { firstName: string; lastName: string | null } {
+ const cleaned = name?.trim().replace(/\s+/g, " ") ?? "";
+
+ if (cleaned && !cleaned.includes("@")) {
+ // "Last, First" is how a lot of corporate directories render it.
+ const comma = cleaned.match(/^([^,]+),\s*(.+)$/);
+ if (comma?.[1] && comma[2]) {
+ return { firstName: comma[2].trim(), lastName: comma[1].trim() };
+ }
+
+ const [first, ...rest] = cleaned.split(" ");
+ if (first) {
+ return {
+ firstName: first,
+ lastName: rest.length > 0 ? rest.join(" ") : null,
+ };
+ }
+ }
+
+ // No usable display name: the local part is the least-bad label, tidied so
+ // "jane.doe" reads as "Jane Doe" rather than as a slug.
+ const local = email.split("@")[0] ?? email;
+ const words = local
+ .split(/[._-]+/)
+ .filter(Boolean)
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1));
+
+ if (words.length === 0) return { firstName: email, lastName: null };
+
+ return {
+ firstName: words[0] as string,
+ lastName: words.length > 1 ? words.slice(1).join(" ") : null,
+ };
+}
+
+function isEmailish(value: string): boolean {
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
+}
diff --git a/apps/api/src/google/sync-state.service.ts b/apps/api/src/google/sync-state.service.ts
new file mode 100644
index 00000000..beb54b4d
--- /dev/null
+++ b/apps/api/src/google/sync-state.service.ts
@@ -0,0 +1,173 @@
+import {
+ type Db,
+ GoogleSyncStatus,
+ type MailboxSyncModel as MailboxSync,
+} from "@crm/db";
+import { Injectable, Logger } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import type { SyncSource } from "./google.constants";
+
+/**
+ * The cursor store.
+ *
+ * Every mutation a sync makes to its own bookkeeping goes through here, so
+ * "what state can a sync row be in" is answerable by reading one file rather
+ * than by grepping two sync services for `update`.
+ */
+@Injectable()
+export class SyncStateService {
+ private readonly logger = new Logger(SyncStateService.name);
+
+ constructor(@InjectDatabase() private readonly db: Db) {}
+
+ async get(userId: string, source: SyncSource): Promise<MailboxSync | null> {
+ return this.db.mailboxSync.findUnique({
+ where: { userId_source: { userId, source } },
+ });
+ }
+
+ async listForUser(userId: string): Promise<MailboxSync[]> {
+ return this.db.mailboxSync.findMany({ where: { userId } });
+ }
+
+ /**
+ * The rows a cron tick should attempt.
+ *
+ * Excludes `NEEDS_RECONNECT` — that state is terminal until a human acts, and
+ * retrying it every five minutes would be a pointless call to Google forever.
+ * Also excludes anything inside its rate-limit backoff.
+ */
+ async due(now: Date): Promise<MailboxSync[]> {
+ return this.db.mailboxSync.findMany({
+ where: {
+ status: { notIn: [GoogleSyncStatus.NEEDS_RECONNECT] },
+ OR: [{ retryAfter: null }, { retryAfter: { lte: now } }],
+ },
+ // Least-recently-synced first, so one busy mailbox cannot starve the
+ // rest when a tick runs out of budget. A never-synced row sorts first.
+ orderBy: [{ lastSyncedAt: { sort: "asc", nulls: "first" } }],
+ });
+ }
+
+ /** Creates the row when a source is first connected. Idempotent. */
+ async ensure(
+ userId: string,
+ source: SyncSource,
+ options: { autoCreate: boolean },
+ ): Promise<MailboxSync> {
+ return this.db.mailboxSync.upsert({
+ where: { userId_source: { userId, source } },
+ create: {
+ userId,
+ source,
+ // No cursor yet. The first pass records where "now" is and imports
+ // nothing — sync is forward-only.
+ status: GoogleSyncStatus.IDLE,
+ autoCreate: options.autoCreate,
+ },
+ // Reconnecting keeps the cursor: re-consenting must not rewind a
+ // mailbox. It *does* clear the error and lift a NEEDS_RECONNECT, which
+ // is the whole point of reconnecting.
+ update: {
+ status: GoogleSyncStatus.IDLE,
+ lastError: null,
+ retryAfter: null,
+ },
+ });
+ }
+
+ async markRunning(id: string): Promise<void> {
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: { status: GoogleSyncStatus.RUNNING, lastError: null },
+ });
+ }
+
+ /** A clean pass: advance the cursor, clear the error, stamp the time. */
+ async settle(
+ id: string,
+ update: {
+ cursor?: string | null;
+ status: GoogleSyncStatus;
+ },
+ ): Promise<void> {
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: {
+ ...update,
+ lastSyncedAt: new Date(),
+ lastError: null,
+ retryAfter: null,
+ },
+ });
+ }
+
+ /**
+ * The cursor is gone (Gmail 404 / Calendar 410).
+ *
+ * Drops it so the next pass starts from now. Forward-only means the gap is
+ * not fetched — reaching here at all takes roughly a week of the sync not
+ * running, so it is warned about rather than quietly healed.
+ */
+ async clearCursor(id: string, reason: string): Promise<void> {
+ this.logger.warn({
+ message: "Sync cursor invalidated — resuming from now",
+ syncId: id,
+ reason,
+ });
+
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: {
+ cursor: null,
+ status: GoogleSyncStatus.IDLE,
+ lastError: null,
+ },
+ });
+ }
+
+ async markNeedsReconnect(id: string, reason: string): Promise<void> {
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: {
+ status: GoogleSyncStatus.NEEDS_RECONNECT,
+ lastError: reason,
+ retryAfter: null,
+ },
+ });
+ }
+
+ async markRateLimited(id: string, retryAfterMs: number): Promise<void> {
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: {
+ status: GoogleSyncStatus.IDLE,
+ retryAfter: new Date(Date.now() + retryAfterMs),
+ },
+ });
+ }
+
+ async markFailed(id: string, reason: string): Promise<void> {
+ await this.db.mailboxSync.update({
+ where: { id },
+ data: { status: GoogleSyncStatus.FAILED, lastError: reason },
+ });
+ }
+
+ async setAutoCreate(
+ userId: string,
+ source: SyncSource,
+ enabled: boolean,
+ ): Promise<void> {
+ await this.db.mailboxSync.updateMany({
+ where: { userId, source },
+ data: { autoCreate: enabled },
+ });
+ }
+
+ async remove(userId: string, source?: SyncSource): Promise<void> {
+ await this.db.mailboxSync.deleteMany({
+ where: { userId, ...(source ? { source } : {}) },
+ });
+ }
+}
diff --git a/apps/api/src/google/sync.controller.ts b/apps/api/src/google/sync.controller.ts
new file mode 100644
index 00000000..a98d68f7
--- /dev/null
+++ b/apps/api/src/google/sync.controller.ts
@@ -0,0 +1,71 @@
+import {
+ Controller,
+ ForbiddenException,
+ Headers,
+ Logger,
+ Post,
+ ServiceUnavailableException,
+} from "@nestjs/common";
+import { ConfigService } from "@nestjs/config";
+import { AllowAnonymous } from "@thallesp/nestjs-better-auth";
+import type { EnvironmentVariables } from "../config/env.validation";
+import { GoogleSyncService } from "./google-sync.service";
+
+/**
+ * The cron entrypoint.
+ *
+ * One of the few non-tRPC surfaces, alongside `/health` and Better Auth: no
+ * user makes this request, so there is no session to authenticate and the tRPC
+ * auth middleware has nothing to check. `CRON_SECRET` is the guard instead.
+ */
+@Controller("internal/sync")
+export class SyncController {
+ private readonly logger = new Logger(SyncController.name);
+ private readonly secret: string | undefined;
+
+ constructor(
+ private readonly sync: GoogleSyncService,
+ config: ConfigService<EnvironmentVariables, true>,
+ ) {
+ this.secret = config.get("CRON_SECRET", { infer: true });
+ }
+
+ @Post("google")
+ @AllowAnonymous()
+ async google(@Headers("authorization") authorization?: string) {
+ // No secret configured means the route is open, which is worse than it
+ // being unavailable. Fail closed. This is the only thing gating the sync —
+ // there is no feature flag, because mailbox access is a condition of
+ // signing in and a switch that can disable a mandatory feature is a switch
+ // that is only ever wrong.
+ if (!this.secret) {
+ this.logger.error({
+ message: "CRON_SECRET is not set — refusing to run the sync route.",
+ });
+ throw new ServiceUnavailableException("Sync is not configured.");
+ }
+
+ if (!timingSafeEquals(authorization ?? "", `Bearer ${this.secret}`)) {
+ throw new ForbiddenException();
+ }
+
+ return this.sync.runDue();
+ }
+}
+
+/**
+ * Constant-time string comparison.
+ *
+ * A `===` on a shared secret leaks its prefix through response timing. The
+ * length check up front is fine to leak — it is the content that matters.
+ */
+function timingSafeEquals(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+
+ let mismatch = 0;
+ for (let index = 0; index < a.length; index += 1) {
+ mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index);
+ }
+
+ return mismatch === 0;
+}
diff --git a/apps/api/src/search/search.service.ts b/apps/api/src/search/search.service.ts
index 59f0da47..bed94e31 100644
--- a/apps/api/src/search/search.service.ts
+++ b/apps/api/src/search/search.service.ts
@@ -10,6 +10,8 @@ export type SearchHit = {
/** The line under the label — domain, company, whatever identifies it. */
detail: string | null;
iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
};
/** Per kind. Enough to be useful, few enough that the list stays scannable. */
@@ -40,7 +42,14 @@ export class SearchService {
},
take: PER_KIND,
orderBy: { name: "asc" },
- select: { id: true, name: true, domain: true, iconUrl: true },
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ },
}),
this.db.contact.findMany({
where: {
@@ -67,7 +76,14 @@ export class SearchService {
select: {
id: true,
name: true,
- company: { select: { name: true, iconUrl: true } },
+ company: {
+ select: {
+ name: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ },
+ },
},
}),
]);
@@ -81,6 +97,8 @@ export class SearchService {
label: company.name,
detail: company.domain,
iconUrl: company.iconUrl,
+ iconDarkUrl: company.iconDarkUrl,
+ iconTone: company.iconTone,
}),
),
...contacts.map(
@@ -92,6 +110,8 @@ export class SearchService {
(contact.email ?? "Unnamed"),
detail: contact.company?.name ?? contact.email,
iconUrl: null,
+ iconDarkUrl: null,
+ iconTone: null,
}),
),
...deals.map(
@@ -101,6 +121,8 @@ export class SearchService {
label: deal.name,
detail: deal.company.name,
iconUrl: deal.company.iconUrl,
+ iconDarkUrl: deal.company.iconDarkUrl,
+ iconTone: deal.company.iconTone,
}),
),
],
diff --git a/apps/api/test/contact-enrichment.spec.ts b/apps/api/test/contact-enrichment.spec.ts
new file mode 100644
index 00000000..261534c5
--- /dev/null
+++ b/apps/api/test/contact-enrichment.spec.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "bun:test";
+import {
+ looksLikeSameCompany,
+ nameMatchesLocalPart,
+ searchTerms,
+} from "../src/enrichment/contact-enrichment.service";
+
+describe("searchTerms", () => {
+ it("strips the initial off a run-together handle", () => {
+ // The case that forced this: searching "abigham" finds nothing, searching
+ // "bigham" returns linkedin.com/in/abigailbigham as the first result.
+ expect(searchTerms("abigham")).toContain("bigham");
+ expect(searchTerms("ymadar")).toContain("madar");
+ });
+
+ it("trusts an explicit separator over any guess", () => {
+ const terms = searchTerms("jane.doe");
+ expect(terms[0]).toBe("jane doe");
+ expect(terms).toContain("doe");
+ });
+
+ it("tries the whole handle before decomposing it", () => {
+ expect(searchTerms("nathan").indexOf("nathan")).toBe(0);
+ });
+
+ it("never emits a fragment too short to search usefully", () => {
+ expect(searchTerms("abc").every((term) => term.length >= 3)).toBe(true);
+ expect(searchTerms("jo")).toEqual([]);
+ });
+});
+
+describe("looksLikeSameCompany", () => {
+ it("matches an employer to the shorter name the CRM holds", () => {
+ // Yael Madar's employer reads "Valley Bank"; the CRM knows "Valley".
+ expect(looksLikeSameCompany("Valley Bank", "Valley", "valley.com")).toBe(
+ true,
+ );
+ expect(looksLikeSameCompany("HubSpot", "HubSpot", "hubspot.com")).toBe(
+ true,
+ );
+ });
+
+ it("rejects an unrelated employer", () => {
+ // The failure this exists to prevent: search handed back Lavazza's CEO for
+ // a HubSpot query, and something has to stop him being written down.
+ expect(
+ looksLikeSameCompany("Lavazza Group", "HubSpot", "hubspot.com"),
+ ).toBe(false);
+ expect(looksLikeSameCompany("", "HubSpot", "hubspot.com")).toBe(false);
+ });
+});
+
+describe("nameMatchesLocalPart", () => {
+ const person = (firstName: string, lastName: string) => ({
+ firstName,
+ lastName,
+ });
+
+ it("accepts the initial-plus-surname form", () => {
+ expect(nameMatchesLocalPart(person("Abbie", "Bigham"), "abigham")).toBe(
+ true,
+ );
+ expect(nameMatchesLocalPart(person("Yael", "Madar"), "ymadar")).toBe(true);
+ });
+
+ it("accepts first-name-only and run-together forms", () => {
+ expect(nameMatchesLocalPart(person("Nathan", "Owen"), "nathan")).toBe(true);
+ expect(nameMatchesLocalPart(person("Jane", "Doe"), "janedoe")).toBe(true);
+ });
+
+ it("rejects a stranger who merely turned up in the results", () => {
+ // This is the guard that keeps Antonio Baravalle from being filed as
+ // Abbie Bigham. The name is checked against the address, never derived
+ // from it.
+ expect(
+ nameMatchesLocalPart(person("Antonio", "Baravalle"), "abigham"),
+ ).toBe(false);
+ expect(nameMatchesLocalPart(person("Preeti", "Prajapati"), "ymadar")).toBe(
+ false,
+ );
+ });
+
+ it("rejects when the profile carries no name at all", () => {
+ expect(
+ nameMatchesLocalPart({ firstName: null, lastName: null }, "abigham"),
+ ).toBe(false);
+ });
+});
diff --git a/apps/api/test/enrichment.integration.spec.ts b/apps/api/test/enrichment.integration.spec.ts
index f3db16e9..8642fdd6 100644
--- a/apps/api/test/enrichment.integration.spec.ts
+++ b/apps/api/test/enrichment.integration.spec.ts
@@ -50,6 +50,9 @@ 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 { EnrichmentService } = await import(
"../src/enrichment/enrichment.service"
);
@@ -112,7 +115,12 @@ let userId: string;
beforeAll(async () => {
const client = new ContextDevClient(config);
- service = new EnrichmentService(db, client, new FastQueue());
+ service = new EnrichmentService(
+ db,
+ client,
+ new FastQueue(),
+ new ActivityStampService(db),
+ );
const user = await db.user.upsert({
where: { email: "enrichment-test@localhost" },
diff --git a/apps/api/test/enrichment.spec.ts b/apps/api/test/enrichment.spec.ts
index 7a2f592b..07a9e2c3 100644
--- a/apps/api/test/enrichment.spec.ts
+++ b/apps/api/test/enrichment.spec.ts
@@ -18,6 +18,8 @@ function emptyCompany(
logoUrl: null,
logoDarkUrl: null,
iconUrl: null,
+ iconDarkUrl: null,
+ iconTone: null,
brandColor: null,
industry: null,
subIndustry: null,
@@ -281,3 +283,68 @@ describe("EnrichmentQueue", () => {
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/google-api-client.spec.ts b/apps/api/test/google-api-client.spec.ts
new file mode 100644
index 00000000..a4c14326
--- /dev/null
+++ b/apps/api/test/google-api-client.spec.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it } from "bun:test";
+import { GoogleApiClient } from "../src/google/google-api.client";
+
+const realFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+/** Stubs `fetch` with one canned response. */
+function stub(
+ status: number,
+ body: unknown,
+ headers: Record<string, string> = {},
+): void {
+ globalThis.fetch = (async () =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json", ...headers },
+ })) as unknown as typeof fetch;
+}
+
+const client = new GoogleApiClient();
+const call = () => client.get<unknown>("https://example.test/x", "token");
+
+describe("GoogleApiClient", () => {
+ it("returns the payload on success", async () => {
+ stub(200, { ok: true });
+ expect(await call()).toEqual({ outcome: "ok", data: { ok: true } });
+ });
+
+ /**
+ * The two cursor invalidations the whole sync design turns on. Both mean
+ * "fall back to a bounded resync", not "something broke" — getting either
+ * wrong stalls a mailbox silently.
+ */
+ it("maps Gmail's 404 to cursor-invalid", async () => {
+ stub(404, { error: { message: "Requested entity was not found." } });
+ const result = await call();
+ expect(result.outcome).toBe("cursor-invalid");
+ });
+
+ it("maps Calendar's 410 to cursor-invalid", async () => {
+ stub(410, { error: { message: "Sync token is no longer valid." } });
+ const result = await call();
+ expect(result.outcome).toBe("cursor-invalid");
+ });
+
+ it("maps 401 to unauthorized, so the row can be marked for reconnect", async () => {
+ stub(401, { error: { message: "Invalid Credentials" } });
+ expect((await call()).outcome).toBe("unauthorized");
+ });
+
+ it("treats a quota 403 as rate limiting, not a hard failure", async () => {
+ stub(403, { error: { message: "User Rate Limit Exceeded" } });
+ const result = await call();
+
+ expect(result.outcome).toBe("rate-limited");
+ if (result.outcome === "rate-limited") {
+ expect(result.retryAfterMs).toBeGreaterThan(0);
+ }
+ });
+
+ it("treats a permission 403 as terminal", async () => {
+ // The overloaded status: same code, opposite handling. A permission
+ // failure retried every five minutes forever is a bug.
+ stub(403, { error: { message: "Insufficient Permission" } });
+ const result = await call();
+
+ expect(result.outcome).toBe("failed");
+ if (result.outcome === "failed") expect(result.retryable).toBe(false);
+ });
+
+ it("honours Retry-After on a 429", async () => {
+ stub(
+ 429,
+ { error: { message: "Too many requests" } },
+ { "retry-after": "600" },
+ );
+ const result = await call();
+
+ expect(result.outcome).toBe("rate-limited");
+ if (result.outcome === "rate-limited") {
+ expect(result.retryAfterMs).toBe(600_000);
+ }
+ });
+
+ it("marks 5xx retryable and 4xx not", async () => {
+ stub(503, { error: { message: "Backend error" } });
+ const server = await call();
+ expect(server.outcome === "failed" && server.retryable).toBe(true);
+
+ stub(400, { error: { message: "Bad request" } });
+ const client400 = await call();
+ expect(client400.outcome === "failed" && client400.retryable).toBe(false);
+ });
+
+ it("surfaces a network error as retryable rather than throwing", async () => {
+ globalThis.fetch = (async () => {
+ throw new Error("connect ECONNREFUSED");
+ }) as unknown as typeof fetch;
+
+ const result = await call();
+ expect(result.outcome).toBe("failed");
+ if (result.outcome === "failed") expect(result.retryable).toBe(true);
+ });
+});
diff --git a/apps/api/test/google-mime.spec.ts b/apps/api/test/google-mime.spec.ts
new file mode 100644
index 00000000..3779a0d8
--- /dev/null
+++ b/apps/api/test/google-mime.spec.ts
@@ -0,0 +1,214 @@
+import { describe, expect, it } from "bun:test";
+import {
+ decodeBase64Url,
+ type GmailPart,
+ header,
+ normaliseMessageId,
+ plainTextBody,
+ rootMessageId,
+ snippetOf,
+ stripHtml,
+ stripQuotedHistory,
+} from "../src/google/mime";
+
+const encode = (text: string): string =>
+ Buffer.from(text, "utf8")
+ .toString("base64")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+
+describe("header", () => {
+ const headers = [
+ { name: "Message-ID", value: "<[email protected]>" },
+ { name: "subject", value: "Pricing" },
+ ];
+
+ it("is case-insensitive", () => {
+ expect(header(headers, "message-id")).toBe("<[email protected]>");
+ expect(header(headers, "SUBJECT")).toBe("Pricing");
+ });
+
+ it("returns null for an absent header", () => {
+ expect(header(headers, "cc")).toBeNull();
+ expect(header(undefined, "cc")).toBeNull();
+ });
+});
+
+describe("decodeBase64Url", () => {
+ it("decodes unpadded base64url", () => {
+ expect(decodeBase64Url(encode("Hello, world"))).toBe("Hello, world");
+ });
+
+ it("survives junk without throwing", () => {
+ expect(() => decodeBase64Url("!!!!")).not.toThrow();
+ });
+});
+
+describe("plainTextBody", () => {
+ it("prefers text/plain from a nested multipart", () => {
+ const payload: GmailPart = {
+ mimeType: "multipart/mixed",
+ parts: [
+ {
+ mimeType: "multipart/alternative",
+ parts: [
+ { mimeType: "text/plain", body: { data: encode("The plain one") } },
+ {
+ mimeType: "text/html",
+ body: { data: encode("<p>The HTML one</p>") },
+ },
+ ],
+ },
+ ],
+ };
+
+ expect(plainTextBody(payload)).toBe("The plain one");
+ });
+
+ it("falls back to stripped HTML when there is no plain part", () => {
+ const payload: GmailPart = {
+ mimeType: "text/html",
+ body: { data: encode("<p>Hello</p><p>World</p>") },
+ };
+
+ // One newline per closing tag, not a blank line between paragraphs.
+ expect(plainTextBody(payload)).toBe("Hello\nWorld");
+ });
+
+ it("ignores attachment parts", () => {
+ const payload: GmailPart = {
+ mimeType: "multipart/mixed",
+ parts: [
+ {
+ mimeType: "text/plain",
+ filename: "notes.txt",
+ body: { data: encode("attachment text") },
+ },
+ { mimeType: "text/plain", body: { data: encode("body text") } },
+ ],
+ };
+
+ expect(plainTextBody(payload)).toBe("body text");
+ });
+
+ it("is empty rather than undefined for an empty payload", () => {
+ expect(plainTextBody(undefined)).toBe("");
+ });
+});
+
+describe("stripHtml", () => {
+ it("drops style and script blocks entirely", () => {
+ const html = "<style>p{color:red}</style><script>x()</script><p>Real</p>";
+ expect(stripHtml(html)).toBe("Real");
+ });
+
+ it("decodes the common entities", () => {
+ expect(stripHtml("<p>Tom &amp; Jerry &lt;3</p>")).toBe("Tom & Jerry <3");
+ });
+});
+
+describe("stripQuotedHistory", () => {
+ it("cuts a Gmail-style reply at the quote", () => {
+ const body = [
+ "Sounds good — Tuesday works.",
+ "",
+ "On Tue, 5 Aug 2025 at 14:02, Jane <[email protected]> wrote:",
+ "> Are you free Tuesday?",
+ ].join("\n");
+
+ expect(stripQuotedHistory(body)).toBe("Sounds good — Tuesday works.");
+ });
+
+ it("cuts an Outlook-style reply", () => {
+ const body = [
+ "Approved.",
+ "",
+ "-----Original Message-----",
+ "From: Jane",
+ ].join("\n");
+
+ expect(stripQuotedHistory(body)).toBe("Approved.");
+ });
+
+ it("cuts a forwarded block", () => {
+ const body =
+ "See below.\n\n---------- Forwarded message ---------\nFrom: X";
+ expect(stripQuotedHistory(body)).toBe("See below.");
+ });
+
+ it("drops trailing quote lines when there is no marker", () => {
+ expect(stripQuotedHistory("Yes.\n> earlier\n> earlier still")).toBe("Yes.");
+ });
+
+ it("leaves an unquoted body alone", () => {
+ expect(stripQuotedHistory("Just a first message.")).toBe(
+ "Just a first message.",
+ );
+ });
+});
+
+describe("rootMessageId", () => {
+ it("takes the first entry of References — the thread root", () => {
+ const headers = [
+ { name: "References", value: "<[email protected]> <[email protected]>" },
+ { name: "In-Reply-To", value: "<[email protected]>" },
+ { name: "Message-ID", value: "<[email protected]>" },
+ ];
+
+ expect(rootMessageId(headers)).toBe("[email protected]");
+ });
+
+ it("falls back to In-Reply-To when References is absent", () => {
+ const headers = [
+ { name: "In-Reply-To", value: "<[email protected]>" },
+ { name: "Message-ID", value: "<[email protected]>" },
+ ];
+
+ expect(rootMessageId(headers)).toBe("[email protected]");
+ });
+
+ it("uses its own id when the message starts the thread", () => {
+ expect(
+ rootMessageId([{ name: "Message-ID", value: "<[email protected]>" }]),
+ ).toBe("[email protected]");
+ });
+
+ it("gives two mailboxes' copies of one conversation the same root", () => {
+ // The whole point of keying on RFC headers rather than Gmail's threadId,
+ // which differs per mailbox. Same conversation, two reps, one CRM thread.
+ const repA = [
+ { name: "References", value: "<[email protected]>" },
+ { name: "Message-ID", value: "<[email protected]>" },
+ ];
+ const repB = [
+ { name: "References", value: "<[email protected]> <[email protected]>" },
+ { name: "Message-ID", value: "<[email protected]>" },
+ ];
+
+ expect(rootMessageId(repA)).toBe(rootMessageId(repB));
+ });
+});
+
+describe("normaliseMessageId", () => {
+ it("makes bracketed and bare ids the same identity", () => {
+ expect(normaliseMessageId("<[email protected]>")).toBe(
+ normaliseMessageId("[email protected]"),
+ );
+ });
+});
+
+describe("snippetOf", () => {
+ it("collapses whitespace", () => {
+ expect(snippetOf("a\n\n b")).toBe("a b");
+ });
+
+ it("truncates with an ellipsis", () => {
+ expect(snippetOf("x".repeat(300))?.length).toBe(200);
+ expect(snippetOf("x".repeat(300))?.endsWith("…")).toBe(true);
+ });
+
+ it("is null for an empty body", () => {
+ expect(snippetOf(" ")).toBeNull();
+ });
+});
diff --git a/apps/api/test/google-participants.spec.ts b/apps/api/test/google-participants.spec.ts
new file mode 100644
index 00000000..3ff6fcd8
--- /dev/null
+++ b/apps/api/test/google-participants.spec.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from "bun:test";
+import {
+ dominantDomain,
+ externalParticipants,
+ isAutomatedAddress,
+ isDerivedName,
+ type Participant,
+ parseAddress,
+ parseAddressList,
+ splitName,
+ workDomain,
+} from "../src/google/participants";
+
+const person = (email: string, name: string | null = null): Participant => ({
+ email,
+ name,
+});
+
+describe("parseAddress", () => {
+ const cases: [string, Participant | null][] = [
+ ["Jane Doe <[email protected]>", person("[email protected]", "Jane Doe")],
+ ['"Doe, Jane" <[email protected]>', person("[email protected]", "Doe, Jane")],
+ ["Jane Doe", null],
+ ["", null],
+ ["<>", null],
+ ];
+
+ for (const [input, expected] of cases) {
+ it(`parses ${JSON.stringify(input)}`, () => {
+ expect(parseAddress(input)).toEqual(expected);
+ });
+ }
+});
+
+describe("parseAddressList", () => {
+ it("does not split on a comma inside a quoted display name", () => {
+ // The whole reason this is not `header.split(",")`: naive splitting turns
+ // one person into two broken addresses.
+ const parsed = parseAddressList(
+ );
+
+ expect(parsed).toEqual([
+ person("[email protected]", "Doe, Jane"),
+ person("[email protected]"),
+ ]);
+ });
+
+ it("deduplicates repeated addresses", () => {
+ expect(parseAddressList("[email protected], [email protected]")).toHaveLength(1);
+ });
+
+ it("returns nothing for an absent header", () => {
+ expect(parseAddressList(null)).toEqual([]);
+ expect(parseAddressList(undefined)).toEqual([]);
+ });
+});
+
+describe("isAutomatedAddress", () => {
+ it("catches the machines", () => {
+ for (const email of [
+ ]) {
+ expect(isAutomatedAddress(email)).toBe(true);
+ }
+ });
+
+ it("does not catch people whose names start with a marker", () => {
+ // `bounce` must not swallow `bouncer@`, and a prefix rule that matched
+ // substrings would.
+ for (const email of [
+ ]) {
+ expect(isAutomatedAddress(email)).toBe(false);
+ }
+ });
+});
+
+describe("workDomain", () => {
+ it("rejects the free hosts", () => {
+ expect(workDomain("[email protected]")).toBeNull();
+ expect(workDomain("[email protected]")).toBeNull();
+ });
+
+ it("returns the bare host for a work address", () => {
+ expect(workDomain("[email protected]")).toBe("acme.com");
+ });
+});
+
+describe("externalParticipants", () => {
+ const options = {
+ ourDomains: new Set(["trycomp.ai"]),
+ ourAddresses: new Set(["[email protected]"]),
+ suppressedDomains: new Set(["greenhouse.io"]),
+ };
+
+ it("keeps only the other side of the conversation", () => {
+ const result = externalParticipants(
+ [
+ person("[email protected]"),
+ person("[email protected]"),
+ person("[email protected]", "Jane"),
+ ],
+ options,
+ );
+
+ expect(result).toEqual([person("[email protected]", "Jane")]);
+ });
+
+ it("drops free hosts, suppressed domains and machines", () => {
+ const result = externalParticipants(
+ [
+ person("[email protected]"),
+ person("[email protected]"),
+ person("[email protected]"),
+ person("[email protected]"),
+ ],
+ options,
+ );
+
+ expect(result).toEqual([person("[email protected]")]);
+ });
+
+ it("returns nothing for a wholly internal thread", () => {
+ expect(
+ externalParticipants([person("[email protected]")], options),
+ ).toEqual([]);
+ });
+});
+
+describe("dominantDomain", () => {
+ it("picks the best-represented domain", () => {
+ const domain = dominantDomain([
+ person("[email protected]"),
+ person("[email protected]"),
+ person("[email protected]"),
+ ]);
+
+ expect(domain).toBe("acme.com");
+ });
+
+ it("breaks a tie towards a company we already have", () => {
+ // A customer plus their lawyer, one each. Without the tiebreak the lawyer
+ // could take the thread.
+ const domain = dominantDomain(
+ [person("[email protected]"), person("[email protected]")],
+ new Set(["acme.com"]),
+ );
+
+ expect(domain).toBe("acme.com");
+ });
+
+ it("is null when nobody has a work domain", () => {
+ expect(dominantDomain([person("[email protected]")])).toBeNull();
+ });
+});
+
+describe("splitName", () => {
+ const cases: [
+ string | null,
+ string,
+ { firstName: string; lastName: string | null },
+ ][] = [
+ ["Jane Doe", "[email protected]", { firstName: "Jane", lastName: "Doe" }],
+ ["Doe, Jane", "[email protected]", { firstName: "Jane", lastName: "Doe" }],
+ [
+ "Jane van der Berg",
+ { firstName: "Jane", lastName: "van der Berg" },
+ ],
+ ["Jane", "[email protected]", { firstName: "Jane", lastName: null }],
+ // No display name: the local part is tidied rather than used raw.
+ [null, "[email protected]", { firstName: "Jane", lastName: "Doe" }],
+ [null, "[email protected]", { firstName: "Jane", lastName: null }],
+ // Some clients put the address in the display name slot.
+ ["[email protected]", "[email protected]", { firstName: "Jane", lastName: null }],
+ ];
+
+ for (const [name, email, expected] of cases) {
+ it(`splits ${JSON.stringify(name)} / ${email}`, () => {
+ expect(splitName(name, email)).toEqual(expected);
+ });
+ }
+});
+
+describe("isAutomatedAddress — scheduling tools", () => {
+ it("catches the addresses invites are sent from", () => {
+ // The bug this came from: a Luma invite created a contact called
+ // "Grand Ventures" whose email was [email protected], because the
+ // tool puts the organiser's name in the display name of its own address.
+ for (const email of [
+ ]) {
+ expect(isAutomatedAddress(email)).toBe(true);
+ }
+ });
+
+ it("catches shared inboxes, which are not people", () => {
+ for (const email of [
+ ]) {
+ expect(isAutomatedAddress(email)).toBe(true);
+ }
+ });
+
+ it("still lets real people through", () => {
+ for (const email of [
+ ]) {
+ expect(isAutomatedAddress(email)).toBe(false);
+ }
+ });
+});
+
+describe("isDerivedName", () => {
+ it("recognises a name that came from the address alone", () => {
+ // "Abigham" is what splitName produces from abigham@…, so it is a
+ // placeholder a real display name is allowed to replace.
+ expect(isDerivedName("[email protected]", "Abigham", null)).toBe(true);
+ expect(isDerivedName("[email protected]", "Jane", "Doe")).toBe(true);
+ });
+
+ it("leaves a real name alone", () => {
+ expect(isDerivedName("[email protected]", "Abbie", "Bigham")).toBe(false);
+ expect(isDerivedName("[email protected]", "Jane", "Doherty")).toBe(false);
+ });
+});
diff --git a/apps/api/test/google-scopes.spec.ts b/apps/api/test/google-scopes.spec.ts
new file mode 100644
index 00000000..f480f341
--- /dev/null
+++ b/apps/api/test/google-scopes.spec.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "bun:test";
+import {
+ CALENDAR_SCOPE,
+ GMAIL_SCOPE,
+ hasSyncScopes,
+ parseScopes,
+ SYNC_SCOPES,
+} from "@crm/auth/scopes";
+
+const BOTH = `openid,email,profile,${GMAIL_SCOPE},${CALENDAR_SCOPE}`;
+
+describe("parseScopes", () => {
+ it("handles the comma form Better Auth stores", () => {
+ expect(parseScopes("a,b,c")).toEqual(new Set(["a", "b", "c"]));
+ });
+
+ it("handles the space form Google returns", () => {
+ expect(parseScopes("a b c")).toEqual(new Set(["a", "b", "c"]));
+ });
+
+ it("is empty for null, undefined and blank", () => {
+ for (const value of [null, undefined, "", " "]) {
+ expect(parseScopes(value).size).toBe(0);
+ }
+ });
+});
+
+describe("hasSyncScopes", () => {
+ it("is true only when both scopes are present", () => {
+ expect(hasSyncScopes(BOTH)).toBe(true);
+ });
+
+ /**
+ * The case that makes the gate necessary. Google's granular consent lets
+ * someone untick one scope and still complete sign-in, so "they signed in"
+ * never implies "they granted it".
+ */
+ it("is false when granular consent dropped one of them", () => {
+ expect(hasSyncScopes(`openid,email,profile,${GMAIL_SCOPE}`)).toBe(false);
+ expect(hasSyncScopes(`openid,email,profile,${CALENDAR_SCOPE}`)).toBe(false);
+ });
+
+ it("is false for an account that predates the requirement", () => {
+ expect(hasSyncScopes("openid,email,profile")).toBe(false);
+ });
+
+ it("is false when the grant was revoked and the column cleared", () => {
+ expect(hasSyncScopes(null)).toBe(false);
+ });
+
+ it("does not match on a prefix", () => {
+ // A scope string that merely starts the same must not pass — set
+ // membership, not `includes()`.
+ expect(hasSyncScopes(`${GMAIL_SCOPE}.metadata,${CALENDAR_SCOPE}`)).toBe(
+ false,
+ );
+ });
+
+ it("covers exactly the scopes the provider requests", () => {
+ // Guards the two lists drifting: whatever sign-in asks for is what the
+ // gate insists on.
+ expect(hasSyncScopes(SYNC_SCOPES.join(","))).toBe(true);
+ });
+});
diff --git a/apps/api/vercel.json b/apps/api/vercel.json
new file mode 100644
index 00000000..7d437925
--- /dev/null
+++ b/apps/api/vercel.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://openapi.vercel.sh/vercel.json",
+ "crons": [
+ {
+ "path": "/internal/sync/google",
+ "schedule": "*/5 * * * *"
+ }
+ ]
+}
diff --git a/apps/app/app/(app)/companies/companies-search-params.ts b/apps/app/app/(app)/companies/companies-search-params.ts
index fc432ee6..b65f3143 100644
--- a/apps/app/app/(app)/companies/companies-search-params.ts
+++ b/apps/app/app/(app)/companies/companies-search-params.ts
@@ -5,6 +5,9 @@ import { createListSearchParams } from "@/components/data-table/list-search-para
* client table, so the two cannot ask for different things.
*/
export const companiesSearchParams = createListSearchParams({
- defaultSort: "name",
+ // Newest first: a CRM list is read to see what has changed, not to look
+ // something up alphabetically — that is what ⌘K is for.
+ defaultSort: "createdAt",
+ defaultDir: "desc",
facetIds: ["owner", "industry", "enrichment"] as const,
});
diff --git a/apps/app/app/(app)/companies/companies-table.tsx b/apps/app/app/(app)/companies/companies-table.tsx
index 8bd3e0e6..5f5b0eca 100644
--- a/apps/app/app/(app)/companies/companies-table.tsx
+++ b/apps/app/app/(app)/companies/companies-table.tsx
@@ -6,7 +6,10 @@ import {
type DataTableFacet,
} from "@crm/ui/components/data-table";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import { relativeTimeFromIso } from "@crm/ui/lib/format";
import { useQuery } from "@tanstack/react-query";
import {
@@ -35,6 +38,8 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [
<span className="flex min-w-0 items-center gap-2.5">
<EntityLogo
src={row.iconUrl ?? row.logoUrl}
+ darkSrc={row.iconDarkUrl}
+ tone={row.iconTone as EntityLogoTone | null | undefined}
name={row.name}
size="sm"
/>
@@ -71,6 +76,7 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [
{
id: "owner",
header: "Owner",
+ sortable: true,
width: "w-[16%]",
hideBelow: "md",
cell: (row) => <OwnerCell owner={row.owner} />,
@@ -93,11 +99,26 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [
cell: (row) => <span className="tabular-nums">{row.openDealCount}</span>,
},
{
- // Not sortable: "most recent activity" is an aggregate over a relation,
- // which Prisma cannot order by, and sorting the page in the browser would
- // only reorder the 25 rows already on screen.
+ // Hidden by default, but present: it is the table's default sort, and a
+ // default you cannot see or return to after sorting by something else is
+ // just an unexplained row order.
+ id: "createdAt",
+ header: "Created",
+ label: "Created date",
+ sortable: true,
+ align: "right",
+ width: "w-[10%]",
+ defaultHidden: true,
+ cell: (row) => (
+ <span className="text-muted-foreground" suppressHydrationWarning>
+ {relativeTimeFromIso(row.createdAt)}
+ </span>
+ ),
+ },
+ {
id: "lastActivity",
header: "Last activity",
+ sortable: true,
align: "right",
width: "w-[12%]",
hideBelow: "sm",
diff --git a/apps/app/app/(app)/contacts/contacts-search-params.ts b/apps/app/app/(app)/contacts/contacts-search-params.ts
index 45b5638e..d1da088f 100644
--- a/apps/app/app/(app)/contacts/contacts-search-params.ts
+++ b/apps/app/app/(app)/contacts/contacts-search-params.ts
@@ -1,6 +1,9 @@
import { createListSearchParams } from "@/components/data-table/list-search-params";
export const contactsSearchParams = createListSearchParams({
- defaultSort: "name",
+ // Newest first: a CRM list is read to see what has changed, not to look
+ // something up alphabetically — that is what ⌘K is for.
+ defaultSort: "createdAt",
+ defaultDir: "desc",
facetIds: ["owner", "company"] as const,
});
diff --git a/apps/app/app/(app)/contacts/contacts-table.tsx b/apps/app/app/(app)/contacts/contacts-table.tsx
index 267996f5..814a8735 100644
--- a/apps/app/app/(app)/contacts/contacts-table.tsx
+++ b/apps/app/app/(app)/contacts/contacts-table.tsx
@@ -66,13 +66,32 @@ const COLUMNS: DataTableColumn<ContactRow>[] = [
{
id: "owner",
header: "Owner",
+ sortable: true,
width: "w-[16%]",
hideBelow: "md",
cell: (row) => <OwnerCell owner={row.owner} />,
},
+ {
+ // Hidden by default, but present: it is the table's default sort, and a
+ // default you cannot see or return to after sorting by something else is
+ // just an unexplained row order.
+ id: "createdAt",
+ header: "Created",
+ label: "Created date",
+ sortable: true,
+ align: "right",
+ width: "w-[10%]",
+ defaultHidden: true,
+ cell: (row) => (
+ <span className="text-muted-foreground" suppressHydrationWarning>
+ {relativeTimeFromIso(row.createdAt)}
+ </span>
+ ),
+ },
{
id: "lastActivity",
header: "Last activity",
+ sortable: true,
align: "right",
width: "w-[12%]",
hideBelow: "sm",
diff --git a/apps/app/app/(app)/deals/deals-search-params.ts b/apps/app/app/(app)/deals/deals-search-params.ts
index 964c4e3e..ec5d8429 100644
--- a/apps/app/app/(app)/deals/deals-search-params.ts
+++ b/apps/app/app/(app)/deals/deals-search-params.ts
@@ -3,7 +3,10 @@ import { createListSearchParams } from "@/components/data-table/list-search-para
export const dealsSearchParams = createListSearchParams({
// Pipeline order by default: the deals closest to closing are the ones a rep
// opens this page to look at.
- defaultSort: "stage",
+ // Newest first: a CRM list is read to see what has changed, not to look
+ // something up alphabetically — that is what ⌘K is for.
+ defaultSort: "createdAt",
+ defaultDir: "desc",
tabId: "status",
facetIds: ["owner", "stage", "closing"] as const,
});
diff --git a/apps/app/app/(app)/deals/deals-table.tsx b/apps/app/app/(app)/deals/deals-table.tsx
index d8ebf7d7..114ccade 100644
--- a/apps/app/app/(app)/deals/deals-table.tsx
+++ b/apps/app/app/(app)/deals/deals-table.tsx
@@ -71,6 +71,7 @@ const COLUMNS: DataTableColumn<DealRow>[] = [
{
id: "owner",
header: "Owner",
+ sortable: true,
width: "w-[14%]",
hideBelow: "md",
cell: (row) => <OwnerCell owner={row.owner} />,
@@ -90,9 +91,27 @@ const COLUMNS: DataTableColumn<DealRow>[] = [
<EmptyCellValue />
),
},
+ {
+ // Hidden by default, but present: it is the table's default sort, and a
+ // default you cannot see or return to after sorting by something else is
+ // just an unexplained row order.
+ id: "createdAt",
+ header: "Created",
+ label: "Created date",
+ sortable: true,
+ align: "right",
+ width: "w-[10%]",
+ defaultHidden: true,
+ cell: (row) => (
+ <span className="text-muted-foreground" suppressHydrationWarning>
+ {relativeTimeFromIso(row.createdAt)}
+ </span>
+ ),
+ },
{
id: "lastActivity",
header: "Last activity",
+ sortable: true,
align: "right",
width: "w-[12%]",
hideBelow: "lg",
diff --git a/apps/app/app/(app)/layout.tsx b/apps/app/app/(app)/layout.tsx
index f6679607..6facff82 100644
--- a/apps/app/app/(app)/layout.tsx
+++ b/apps/app/app/(app)/layout.tsx
@@ -3,14 +3,17 @@ import { AppIconRail } from "@/components/app-icon-rail";
import { QuickSwitcher } from "@/components/crm/quick-switcher";
import { RecordSheetHost } from "@/components/crm/record-sheet/record-sheet-host";
import { MobileNavProvider } from "@/components/mobile-nav";
-import { requireSession } from "@/lib/session";
+import { requireGoogleAccess } from "@/lib/session";
export default async function AppLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
- const { user } = await requireSession();
+ // Not just `requireSession`: mailbox access is a condition of using this
+ // tool, and a granular-consent untick would otherwise leave someone inside
+ // the app with a CRM that silently syncs nothing.
+ const { user } = await requireGoogleAccess();
return (
<MobileNavProvider>
diff --git a/apps/app/app/(app)/settings/google-connection.tsx b/apps/app/app/(app)/settings/google-connection.tsx
new file mode 100644
index 00000000..68d2310b
--- /dev/null
+++ b/apps/app/app/(app)/settings/google-connection.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { Button } from "@crm/ui/components/button";
+import { Label } from "@crm/ui/components/label";
+import { StatusIndicator } from "@crm/ui/components/status-indicator";
+import { Switch } from "@crm/ui/components/switch";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { isSyncing, SYNC_POLL_MS } from "@/components/crm/sync-status";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+
+/**
+ * What each source contributes, in the rep's terms.
+ *
+ * The toggle copy says what a record *becoming* real depends on, because that
+ * is the only decision on this page with a consequence.
+ */
+const SOURCES = {
+ calendar: {
+ label: "Meetings",
+ autoCreate: "Add the company and contact when you meet someone new",
+ },
+ gmail: {
+ label: "Email",
+ autoCreate: "Add the company and contact when you reply to someone new",
+ },
+} as const;
+
+export function GoogleConnection() {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+
+ const status = useQuery({
+ ...trpc.google.status.queryOptions(),
+ // A sync is background work no client action caused, so per the API rules
+ // it is polled, not invalidated — and the poll stops the moment it settles.
+ refetchInterval: (query) =>
+ query.state.data?.sources.some((source) => isSyncing(source.status))
+ ? SYNC_POLL_MS
+ : false,
+ });
+
+ const purge = useMutation(
+ trpc.google.purgeSyncedData.mutationOptions({
+ onSuccess: async (result) => {
+ await cache.google();
+ toast.success(`Removed ${result.purged} synced items.`);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const revoke = useMutation(
+ trpc.google.revokeAccess.mutationOptions({
+ // A full navigation, not a router push: the grant is gone, so every
+ // cached render is wrong and the gate has to re-evaluate. Lands on
+ // /grant-access.
+ onSuccess: () => window.location.assign("/"),
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const setAutoCreate = useMutation(
+ trpc.google.setAutoCreate.mutationOptions({
+ onSuccess: () => cache.google({ settle: "record" }),
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const syncNow = useMutation(
+ trpc.google.syncNow.mutationOptions({
+ onSuccess: () => cache.google(),
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (!status.data) return null;
+
+ const { sources, hasRefreshToken } = status.data;
+
+ // Both scopes come from one grant at sign-in, so "Gmail connected but
+ // Calendar not" is not a state that exists. One section, not one per source.
+ const broken = sources.find(
+ (source) => source.status === "NEEDS_RECONNECT" || source.lastError,
+ );
+ const lastSyncedAt = sources
+ .map((source) => source.lastSyncedAt)
+ .filter((at): at is string => at !== null)
+ .sort()
+ .at(-1);
+
+ const healthy = !broken && hasRefreshToken;
+
+ return (
+ // No card: the page shell already owns the gutter, so a padded container
+ // here would indent every line away from the heading above it — and there
+ // is no border or fill to earn that indent. Sections separated by rules,
+ // like the record sheets.
+ <div className="flex max-w-3xl flex-col">
+ <section className="flex flex-col gap-2 pb-5">
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <div className="flex items-center gap-3">
+ <h2 className="font-medium text-sm">Google</h2>
+ <StatusIndicator
+ tone={healthy ? "success" : "warning"}
+ label={healthy ? "Connected" : "Needs attention"}
+ />
+ </div>
+
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={syncNow.isPending}
+ onClick={() => syncNow.mutate()}
+ >
+ {syncNow.isPending ? "Checking…" : "Check now"}
+ </Button>
+ </div>
+
+ <p className="text-pretty text-muted-foreground text-sm/6">
+ New meetings and email threads are added to the matching company as
+ they happen. Nothing from before you connected is imported, and
+ nothing is ever sent on your behalf.
+ </p>
+
+ <p className="text-muted-foreground text-xs">
+ {!hasRefreshToken
+ ? "Sign out and back in to finish setting up — Google did not return a refresh token."
+ : broken?.lastError
+ ? broken.lastError
+ : lastSyncedAt
+ ? `Last checked ${relativeTimeFromIso(lastSyncedAt)}`
+ : "Waiting for the first check"}
+ </p>
+ </section>
+
+ <section className="flex flex-col gap-5 border-t py-5">
+ {sources.map((source) => {
+ const copy = SOURCES[source.source];
+
+ return (
+ <div
+ key={source.source}
+ className="flex items-center justify-between gap-6"
+ >
+ <Label
+ htmlFor={`auto-create-${source.source}`}
+ className="flex flex-col items-start gap-1"
+ >
+ <span className="text-sm">{copy.label}</span>
+ <span className="font-normal text-muted-foreground text-xs">
+ {copy.autoCreate}
+ </span>
+ </Label>
+
+ <Switch
+ id={`auto-create-${source.source}`}
+ checked={source.autoCreate}
+ disabled={setAutoCreate.isPending}
+ onCheckedChange={(enabled) =>
+ setAutoCreate.mutate({ source: source.source, enabled })
+ }
+ />
+ </div>
+ );
+ })}
+ </section>
+
+ {/*
+ * Quiet by design. These are the irreversible actions and neither is
+ * anybody's daily business, so they sit at the bottom in muted type
+ * rather than as a third block competing for attention.
+ */}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t pt-5 text-muted-foreground text-xs">
+ <button
+ type="button"
+ className="underline underline-offset-3 hover:text-foreground disabled:opacity-50"
+ disabled={purge.isPending}
+ onClick={() => {
+ if (
+ !window.confirm(
+ "Delete every synced email and meeting from the CRM?",
+ )
+ ) {
+ return;
+ }
+ purge.mutate();
+ }}
+ >
+ Delete synced data
+ </button>
+
+ <button
+ type="button"
+ className="underline underline-offset-3 hover:text-foreground disabled:opacity-50"
+ disabled={revoke.isPending}
+ onClick={() => {
+ // Worth a confirm: one OAuth client means one grant, so this ends
+ // CRM access entirely, not just syncing.
+ if (
+ !window.confirm(
+ "Revoke Google access? You will be signed out and cannot use the CRM until you grant it again.",
+ )
+ ) {
+ return;
+ }
+ revoke.mutate();
+ }}
+ >
+ Revoke Google access
+ </button>
+
+ <a
+ href="https://myaccount.google.com/permissions"
+ target="_blank"
+ rel="noreferrer"
+ className="underline underline-offset-3 hover:text-foreground"
+ >
+ Manage in your Google account
+ </a>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/app/(app)/settings/page.tsx b/apps/app/app/(app)/settings/page.tsx
new file mode 100644
index 00000000..f2c23916
--- /dev/null
+++ b/apps/app/app/(app)/settings/page.tsx
@@ -0,0 +1,47 @@
+import type { Metadata } from "next";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+import { GoogleConnection } from "./google-connection";
+
+export const metadata: Metadata = {
+ title: "Settings",
+};
+
+export default async function SettingsPage() {
+ await requireSession();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+
+ // Awaited: the whole page is this one query, and rendering "Not connected"
+ // for a beat before flipping to "Connected" is worse than waiting for it.
+ await queryClient.prefetchQuery(trpc.google.status.queryOptions());
+
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Settings</PageShellTitle>
+ <PageShellDescription>
+ Your meetings and email, on the companies they belong to.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent>
+ <HydrateClient>
+ <GoogleConnection />
+ </HydrateClient>
+ </PageShellContent>
+ </PageShell>
+ );
+}
diff --git a/apps/app/app/(auth)/grant-access/grant-access.tsx b/apps/app/app/(auth)/grant-access/grant-access.tsx
new file mode 100644
index 00000000..63378ad0
--- /dev/null
+++ b/apps/app/app/(auth)/grant-access/grant-access.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { authClient, signOut } from "@crm/auth/client";
+import { SYNC_SCOPES } from "@crm/auth/scopes";
+import GoogleLogo from "@crm/ui/components/brand-logos/google";
+import { Button } from "@crm/ui/components/button";
+import { Spinner } from "@crm/ui/components/spinner";
+import { useState } from "react";
+import { toast } from "sonner";
+
+export function GrantAccess() {
+ const [pending, setPending] = useState(false);
+
+ async function handleGrant() {
+ setPending(true);
+
+ // 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.
+ const origin = window.location.origin;
+
+ // `linkSocial` rather than `signIn.social`: there is already a session and
+ // an account row, and this is a scope upgrade on the existing grant.
+ // Google's incremental authorisation means the resulting token covers the
+ // union, so sign-in keeps working either way.
+ const { error } = await authClient.linkSocial({
+ provider: "google",
+ scopes: [...SYNC_SCOPES],
+ callbackURL: `${origin}/`,
+ errorCallbackURL: `${origin}/grant-access`,
+ });
+
+ // On success the browser has already navigated to Google.
+ if (error) {
+ toast.error(error.message ?? "Could not reach Google.");
+ setPending(false);
+ }
+ }
+
+ async function handleSignOut() {
+ const { error } = await signOut();
+
+ if (error) {
+ toast.error(error.message ?? "Could not sign out.");
+ return;
+ }
+
+ window.location.assign("/sign-in");
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <Button
+ className="w-full"
+ disabled={pending}
+ onClick={handleGrant}
+ type="button"
+ >
+ {pending ? (
+ <Spinner data-icon="inline-start" />
+ ) : (
+ <GoogleLogo data-icon="inline-start" className="size-4" />
+ )}
+ Grant access
+ </Button>
+
+ {/*
+ * Somebody who does not want to grant this needs a way out that is not
+ * the back button into a redirect loop.
+ */}
+ <Button
+ className="w-full"
+ onClick={() => {
+ handleSignOut().catch(() => toast.error("Could not sign out."));
+ }}
+ type="button"
+ variant="ghost"
+ >
+ Sign out
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/app/app/(auth)/grant-access/page.tsx b/apps/app/app/(auth)/grant-access/page.tsx
new file mode 100644
index 00000000..c68eeb93
--- /dev/null
+++ b/apps/app/app/(auth)/grant-access/page.tsx
@@ -0,0 +1,52 @@
+import { hasSyncScopes } from "@crm/auth";
+import { db } from "@crm/db";
+import type { Metadata } from "next";
+import { redirect } from "next/navigation";
+import { AuthHeading, AuthShell } from "@/components/auth-shell";
+import { requireSession } from "@/lib/session";
+import { GrantAccess } from "./grant-access";
+
+export const metadata: Metadata = {
+ title: "Grant access",
+};
+
+/**
+ * The re-consent wall.
+ *
+ * Outside the `(app)` group deliberately: the gate lives in that group's
+ * layout, so a page inside it would redirect to itself.
+ *
+ * Reached by someone who is signed in but has not granted Gmail and Calendar —
+ * either they unticked a scope on Google's granular consent screen, or their
+ * account predates those scopes being required.
+ */
+export default async function GrantAccessPage() {
+ const { user } = await requireSession();
+
+ const account = await db.account.findFirst({
+ where: { userId: user.id, providerId: "google" },
+ select: { scope: true },
+ });
+
+ // Already granted — nothing to ask for. Guards the back button and a stale
+ // link as much as anything.
+ if (hasSyncScopes(account?.scope)) {
+ redirect("/");
+ }
+
+ return (
+ <AuthShell>
+ <AuthHeading
+ title="One more step"
+ description="Comp AI CRM reads your Gmail and Calendar so meetings and email threads show up on the right company. It is read-only — nothing is ever sent on your behalf."
+ />
+
+ <GrantAccess />
+
+ <p className="text-center text-muted-foreground text-sm/5">
+ Only conversations with companies in the CRM are stored. Personal mail
+ is discarded without being saved.
+ </p>
+ </AuthShell>
+ );
+}
diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsx
index d0850f00..c49c52a6 100644
--- a/apps/app/components/app-icon-rail.tsx
+++ b/apps/app/components/app-icon-rail.tsx
@@ -4,6 +4,7 @@ import Building from "@carbon/icons-react/es/Building";
import type { CarbonIconType } from "@carbon/icons-react/es/CarbonIcon";
import Dashboard from "@carbon/icons-react/es/Dashboard";
import Partnership from "@carbon/icons-react/es/Partnership";
+import Settings from "@carbon/icons-react/es/Settings";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
import { Button } from "@crm/ui/components/button";
import { Icon } from "@crm/ui/components/icon";
@@ -40,6 +41,7 @@ const ITEMS: RailItem[] = [
match: "prefix",
},
{ title: "Deals", href: "/deals", icon: Partnership, match: "prefix" },
+ { title: "Settings", href: "/settings", icon: Settings, match: "prefix" },
];
function isActive(item: RailItem, pathname: string): boolean {
diff --git a/apps/app/components/crm/company-cell.tsx b/apps/app/components/crm/company-cell.tsx
index a53b3fd6..afa42434 100644
--- a/apps/app/components/crm/company-cell.tsx
+++ b/apps/app/components/crm/company-cell.tsx
@@ -1,11 +1,17 @@
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
export type CompanyRef = {
id: string;
name: string;
domain: string | null;
iconUrl: string | null;
+ iconDarkUrl?: string | null;
+ /** `opaque` | `dark` | `light` — see `EntityLogo`. */
+ iconTone?: string | null;
logoUrl?: string | null;
};
@@ -17,6 +23,8 @@ export function CompanyCell({ company }: { company: CompanyRef | null }) {
<span className="flex min-w-0 items-center gap-2">
<EntityLogo
src={company.iconUrl ?? company.logoUrl}
+ darkSrc={company.iconDarkUrl}
+ tone={company.iconTone as EntityLogoTone | null | undefined}
name={company.name}
size="sm"
/>
diff --git a/apps/app/components/crm/quick-switcher.tsx b/apps/app/components/crm/quick-switcher.tsx
index 1381355b..55837c4c 100644
--- a/apps/app/components/crm/quick-switcher.tsx
+++ b/apps/app/components/crm/quick-switcher.tsx
@@ -9,7 +9,10 @@ import {
CommandItem,
CommandList,
} from "@crm/ui/components/command";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";
import { useQuery } from "@tanstack/react-query";
import { parseAsBoolean, useQueryState } from "nuqs";
@@ -106,7 +109,13 @@ export function QuickSwitcher() {
value={`${hit.kind}:${hit.id}`}
onSelect={() => go(kind, hit.id)}
>
- <EntityLogo src={hit.iconUrl} name={hit.label} size="sm" />
+ <EntityLogo
+ src={hit.iconUrl}
+ darkSrc={hit.iconDarkUrl}
+ tone={hit.iconTone as EntityLogoTone | null | undefined}
+ name={hit.label}
+ size="sm"
+ />
<span className="flex min-w-0 flex-col">
<span className="truncate">{hit.label}</span>
{hit.detail ? (
diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsx
index 13be66b9..6e9d814a 100644
--- a/apps/app/components/crm/record-sheet/company-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx
@@ -7,7 +7,10 @@ import StarFilled from "@carbon/icons-react/es/StarFilled";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
import { Button } from "@crm/ui/components/button";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import { Icon } from "@crm/ui/components/icon";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { TableCell } from "@crm/ui/components/table";
@@ -245,6 +248,8 @@ export function CompanySheet({ companyId }: { companyId: string }) {
media={
<EntityLogo
src={company?.iconUrl ?? company?.logoUrl}
+ darkSrc={company?.iconDarkUrl}
+ tone={company?.iconTone as EntityLogoTone | null | undefined}
name={company?.name ?? "?"}
size="lg"
/>
diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsx
index 7d66a603..2862c075 100644
--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx
@@ -5,7 +5,10 @@ import Partnership from "@carbon/icons-react/es/Partnership";
import Star from "@carbon/icons-react/es/Star";
import { Button } from "@crm/ui/components/button";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import { Icon } from "@crm/ui/components/icon";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { StatusIndicator } from "@crm/ui/components/status-indicator";
@@ -207,7 +210,13 @@ function CompanyStat({
onClick={() => openRecord({ kind: "company", id: company.id })}
className="flex min-w-0 items-center gap-2 underline-offset-2 hover:underline"
>
- <EntityLogo src={company.iconUrl} name={company.name} size="xs" />
+ <EntityLogo
+ src={company.iconUrl}
+ darkSrc={company.iconDarkUrl}
+ tone={company.iconTone as EntityLogoTone | null | undefined}
+ name={company.name}
+ size="xs"
+ />
<span className="truncate">{company.name}</span>
</button>
);
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index 88b12143..35124a84 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -3,7 +3,10 @@
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
-import { EntityLogo } from "@crm/ui/components/entity-logo";
+import {
+ EntityLogo,
+ type EntityLogoTone,
+} from "@crm/ui/components/entity-logo";
import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";
import { TableCell } from "@crm/ui/components/table";
import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";
@@ -118,6 +121,8 @@ export function DealSheet({ dealId }: { dealId: string }) {
deal ? (
<EntityLogo
src={deal.company.iconUrl}
+ darkSrc={deal.company.iconDarkUrl}
+ tone={deal.company.iconTone as EntityLogoTone | null | undefined}
name={deal.company.name}
size="lg"
/>
diff --git a/apps/app/components/crm/record-sheet/record-parts.tsx b/apps/app/components/crm/record-sheet/record-parts.tsx
index c7d4a680..86976dd9 100644
--- a/apps/app/components/crm/record-sheet/record-parts.tsx
+++ b/apps/app/components/crm/record-sheet/record-parts.tsx
@@ -115,7 +115,23 @@ export function MetaLine({
lead?: ReactNode;
parts: (string | null | undefined)[];
}) {
- const rest = parts.filter((part): part is string => Boolean(part));
+ // Deduplicated, case-insensitively. The parts come from different fields that
+ // can legitimately hold the same string — a contact at a company called
+ // Architect whose title is "Architect" would otherwise read
+ // "Architect · Architect", and render two children under the same key.
+ const seen = new Set<string>();
+ const rest: string[] = [];
+
+ for (const part of parts) {
+ const value = part?.trim();
+ if (!value) continue;
+
+ const key = value.toLowerCase();
+ if (seen.has(key)) continue;
+
+ seen.add(key);
+ rest.push(value);
+ }
return (
<>
diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.ts
index a46c1398..c7b518de 100644
--- a/apps/app/components/crm/record-sheet/record-stack.ts
+++ b/apps/app/components/crm/record-sheet/record-stack.ts
@@ -7,6 +7,10 @@ import {
useQueryStates,
} from "nuqs";
import { useCallback, useMemo } from "react";
+import {
+ TIMELINE_PARAM,
+ timelineTabParser,
+} from "@/components/crm/timeline/timeline-search-params";
const RECORD_KINDS = ["company", "contact", "deal"] as const;
@@ -27,25 +31,29 @@ const FORM_TAB: Record<RecordForm, string> = {
/**
* Everything about what the sheet is showing: which records are open
- * (innermost last), which tab of the innermost one, and which quick-add form
- * inside that.
+ * (innermost last), which tab of the innermost one, which quick-add form inside
+ * that, and how the Activity panel is filtered.
*
* A stack rather than a single id because the interesting move is sideways:
* from a company to one of its deals to somebody on that deal. Closing the
* deal should put you back on the company you came from, not on the table.
*
- * All three ride in one hook so a write to any of them can clear the others.
- * Moving to another record has to reset the tab and drop a half-typed form —
- * otherwise they reappear, out of context, on whatever you opened next.
+ * All four ride in one hook so a write to any of them can clear the others.
+ * Moving to another record has to reset the tab, drop a half-typed form and
+ * forget the timeline filter — otherwise they reappear, out of context, on
+ * whatever you opened next.
*
- * `tab` and `add` replace rather than push: flicking through tabs is reading,
- * not navigating, and a Back button that walks you through four panels before
- * it closes the sheet is a Back button nobody presses twice.
+ * They replace rather than push: flicking through tabs is reading, not
+ * navigating, and a Back button that walks you through four panels before it
+ * closes the sheet is a Back button nobody presses twice.
*/
const params = {
record: parseAsArrayOf(parseAsString, ",").withDefault([]),
tab: parseAsString,
add: parseAsStringLiteral(RECORD_FORMS),
+ // Owned by the timeline, cleared from here. `useQueryState` over there and
+ // this entry are the same key, so the two stay in step.
+ [TIMELINE_PARAM]: timelineTabParser,
};
export function recordKey(ref: RecordRef): string {
@@ -77,6 +85,7 @@ export function useRecordStack() {
record: next.length === 0 ? null : next.map(recordKey),
tab: null,
add: null,
+ [TIMELINE_PARAM]: null,
},
{ history },
);
@@ -148,9 +157,16 @@ export function useRecordSheetView(fallbackTab: string) {
const setTab = useCallback(
(next: string) => {
- // Leaving the panel abandons the form that lived in it, and the
- // default tab is the absence of the param rather than a value.
- void setParams({ tab: next === fallbackTab ? null : next, add: null });
+ // Leaving the panel abandons the form that lived in it and the filter
+ // that was on it — the tabs unmount their contents, so a timeline
+ // returned to has always started at All; the param going too is what
+ // keeps that true now the filter outlives the component. The default
+ // tab is the absence of the param rather than a value.
+ void setParams({
+ tab: next === fallbackTab ? null : next,
+ add: null,
+ [TIMELINE_PARAM]: null,
+ });
},
[setParams, fallbackTab],
);
diff --git a/apps/app/components/crm/sync-status.tsx b/apps/app/components/crm/sync-status.tsx
new file mode 100644
index 00000000..91472463
--- /dev/null
+++ b/apps/app/components/crm/sync-status.tsx
@@ -0,0 +1,69 @@
+import type { GoogleSyncStatus } from "@crm/db/enums";
+import {
+ StatusIndicator,
+ type StatusTone,
+} from "@crm/ui/components/status-indicator";
+
+/**
+ * How a mailbox sync is getting on.
+ *
+ * `NEEDS_RECONNECT` is deliberately not an error tone shared with `FAILED`:
+ * a failure is ours to chase, a reconnect is the rep's to fix, and the settings
+ * page needs to tell those apart at a glance.
+ */
+const PRESENTATION: Record<
+ GoogleSyncStatus,
+ { label: string; tone: StatusTone; busy?: boolean }
+> = {
+ IDLE: { label: "Connected", tone: "success" },
+ RUNNING: { label: "Syncing", tone: "info", busy: true },
+ NEEDS_RECONNECT: { label: "Reconnect needed", tone: "warning" },
+ FAILED: { label: "Sync failed", tone: "error" },
+};
+
+export function SyncIndicator({
+ status,
+ title,
+ className,
+}: {
+ status: GoogleSyncStatus | null;
+ title?: string | null;
+ className?: string;
+}) {
+ if (status === null) {
+ return (
+ <StatusIndicator
+ tone="neutral"
+ label="Not connected"
+ className={className}
+ />
+ );
+ }
+
+ const { label, tone, busy } = PRESENTATION[status];
+
+ return (
+ <StatusIndicator
+ tone={tone}
+ busy={busy}
+ label={label}
+ title={title ?? undefined}
+ className={className}
+ />
+ );
+}
+
+/**
+ * Still going to change on its own.
+ *
+ * A sync is background work no client action caused, so — exactly like
+ * enrichment — there is nothing to invalidate and the only way to notice it
+ * finished is to ask. One definition, so the settings page and the record sheet
+ * cannot disagree about when to stop asking.
+ */
+export function isSyncing(status: GoogleSyncStatus | null): boolean {
+ return status === "RUNNING";
+}
+
+/** How often to ask, in ms, while a sync is still working. */
+export const SYNC_POLL_MS = 5_000;
diff --git a/apps/app/components/crm/timeline/email-thread-entry.tsx b/apps/app/components/crm/timeline/email-thread-entry.tsx
new file mode 100644
index 00000000..70188bcf
--- /dev/null
+++ b/apps/app/components/crm/timeline/email-thread-entry.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@crm/ui/components/accordion";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { ThreadMessage } from "@crm/ui/components/thread-message";
+import { relativeTimeFromIso } from "@crm/ui/lib/format";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { useTRPC } from "@/lib/trpc/client";
+
+const timeFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+});
+
+/**
+ * A synced Gmail thread, collapsed to one line.
+ *
+ * The messages are fetched only when it is opened: the timeline payload carries
+ * a snippet and a count, and email bodies are the one thing that must never
+ * ride along on a list response.
+ */
+export function EmailThreadEntry({
+ threadId,
+ messageCount,
+}: {
+ threadId: string;
+ messageCount: number;
+}) {
+ const trpc = useTRPC();
+ const [opened, setOpened] = useState(false);
+
+ const thread = useQuery({
+ ...trpc.google.thread.queryOptions({ threadId }),
+ enabled: opened,
+ });
+
+ return (
+ <Accordion
+ type="single"
+ collapsible
+ onValueChange={(value) => {
+ // Latched: collapsing again should not throw away what we fetched.
+ if (value) setOpened(true);
+ }}
+ >
+ <AccordionItem value={threadId} className="border-b-0">
+ <AccordionTrigger className="py-1 text-muted-foreground text-xs">
+ {messageCount === 1 ? "1 message" : `${messageCount} messages`}
+ </AccordionTrigger>
+
+ <AccordionContent>
+ {thread.isPending ? (
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-1/3" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ ) : thread.isError ? (
+ <p className="text-muted-foreground text-sm">
+ {thread.error.message}
+ </p>
+ ) : (
+ <div className="flex flex-col">
+ {thread.data?.messages.map((message) => (
+ <ThreadMessage
+ key={message.id}
+ from={message.fromName ?? message.fromEmail}
+ fromEmail={message.fromEmail}
+ sentAt={timeFormat.format(new Date(message.sentAt))}
+ direction={message.direction}
+ body={message.body}
+ action={
+ message.gmailUrl ? (
+ <a
+ href={message.gmailUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="text-muted-foreground underline underline-offset-3 hover:text-foreground"
+ >
+ Open in Gmail
+ </a>
+ ) : null
+ }
+ />
+ ))}
+ </div>
+ )}
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+}
+
+/** "3 messages · latest 2h ago", for the collapsed row. */
+export function threadSummary(
+ messageCount: number,
+ lastMessageAt: string,
+): string {
+ const count = messageCount === 1 ? "1 message" : `${messageCount} messages`;
+ return `${count} · latest ${relativeTimeFromIso(lastMessageAt)}`;
+}
diff --git a/apps/app/components/crm/timeline/meeting-entry.tsx b/apps/app/components/crm/timeline/meeting-entry.tsx
new file mode 100644
index 00000000..7206638f
--- /dev/null
+++ b/apps/app/components/crm/timeline/meeting-entry.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { AttendeeList } from "@crm/ui/components/attendee-list";
+import { useQuery } from "@tanstack/react-query";
+import { useTRPC } from "@/lib/trpc/client";
+
+const rangeFormat = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+});
+
+const timeOnly = new Intl.DateTimeFormat(undefined, {
+ hour: "numeric",
+ minute: "2-digit",
+});
+
+const dayOnly = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+});
+
+/**
+ * A synced calendar event on the timeline.
+ *
+ * The attendee list is fetched lazily for the same reason the thread is: the
+ * timeline row carries a count, and pulling every attendee of every meeting on
+ * a busy company would be a join per row for information most rows never show.
+ */
+export function MeetingEntry({
+ eventId,
+ startsAt,
+ endsAt,
+ isAllDay,
+ attendeeCount,
+ conferenceUrl,
+}: {
+ eventId: string;
+ startsAt: string;
+ endsAt: string;
+ isAllDay: boolean;
+ attendeeCount: number;
+ conferenceUrl: string | null;
+}) {
+ const trpc = useTRPC();
+
+ // Only worth a request when there is somebody to show.
+ const event = useQuery({
+ ...trpc.google.event.queryOptions({ eventId }),
+ enabled: attendeeCount > 0,
+ });
+
+ return (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <span className="text-muted-foreground text-xs">
+ {formatRange(startsAt, endsAt, isAllDay)}
+ </span>
+
+ {event.data?.attendees && event.data.attendees.length > 0 ? (
+ <AttendeeList attendees={event.data.attendees} />
+ ) : null}
+
+ {conferenceUrl ? (
+ <a
+ href={conferenceUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="text-muted-foreground text-xs underline underline-offset-3 hover:text-foreground"
+ >
+ Join call
+ </a>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * "5 Aug, 14:00 – 15:00", collapsing the second date when it is the same day —
+ * which it almost always is, and repeating it reads like a two-day meeting.
+ */
+function formatRange(
+ startsAt: string,
+ endsAt: string,
+ isAllDay: boolean,
+): string {
+ const start = new Date(startsAt);
+ const end = new Date(endsAt);
+
+ if (isAllDay) return `${dayOnly.format(start)} · All day`;
+
+ const sameDay = start.toDateString() === end.toDateString();
+
+ return sameDay
+ ? `${rangeFormat.format(start)} – ${timeOnly.format(end)}`
+ : `${rangeFormat.format(start)} – ${rangeFormat.format(end)}`;
+}
diff --git a/apps/app/components/crm/timeline/timeline-entry.tsx b/apps/app/components/crm/timeline/timeline-entry.tsx
index ffa599db..74fb32ec 100644
--- a/apps/app/components/crm/timeline/timeline-entry.tsx
+++ b/apps/app/components/crm/timeline/timeline-entry.tsx
@@ -11,6 +11,8 @@ import { useCrmCache } from "@/lib/trpc/cache";
import { useTRPC } from "@/lib/trpc/client";
import type { RouterOutputs } from "@/lib/trpc/types";
import { ActivityIcon, activityLabel } from "./activity-icon";
+import { EmailThreadEntry, threadSummary } from "./email-thread-entry";
+import { MeetingEntry } from "./meeting-entry";
export type TimelineEntryData =
RouterOutputs["activities"]["timeline"]["entries"][number];
@@ -56,6 +58,15 @@ export function TimelineEntry({
const change = entry.type === "STAGE_CHANGE" ? stageChange(entry.meta) : null;
const when = entry.occurredAt ?? entry.createdAt;
+ // A synced entry was not written by the person whose mailbox it came from,
+ // so it is attributed to the source rather than to them.
+ const synced = entry.meta?.synced === true;
+ const author = synced
+ ? entry.emailThread
+ ? "via Gmail"
+ : "via Calendar"
+ : entry.createdBy.name;
+
return (
<li className="flex gap-3 py-3">
<span className="mt-0.5 text-muted-foreground">
@@ -96,8 +107,17 @@ export function TimelineEntry({
) : null}
<span className="text-muted-foreground text-xs">
- {entry.createdBy.name} · {timeFormat.format(new Date(when))}
+ {author} · {timeFormat.format(new Date(when))}
</span>
+
+ {entry.emailThread ? (
+ <span className="text-muted-foreground text-xs">
+ {threadSummary(
+ entry.emailThread.messageCount,
+ entry.emailThread.lastMessageAt,
+ )}
+ </span>
+ ) : null}
</div>
{entry.body ? (
@@ -106,6 +126,24 @@ export function TimelineEntry({
</p>
) : null}
+ {entry.calendarEvent ? (
+ <MeetingEntry
+ eventId={entry.calendarEvent.id}
+ startsAt={entry.calendarEvent.startsAt}
+ endsAt={entry.calendarEvent.endsAt}
+ isAllDay={entry.calendarEvent.isAllDay}
+ attendeeCount={entry.calendarEvent.attendeeCount}
+ conferenceUrl={entry.calendarEvent.conferenceUrl}
+ />
+ ) : null}
+
+ {entry.emailThread ? (
+ <EmailThreadEntry
+ threadId={entry.emailThread.id}
+ messageCount={entry.emailThread.messageCount}
+ />
+ ) : null}
+
{showContext && (entry.deal || entry.contact) ? (
<div className="flex flex-wrap items-center gap-3 text-xs">
{entry.deal ? (
diff --git a/apps/app/components/crm/timeline/timeline-search-params.ts b/apps/app/components/crm/timeline/timeline-search-params.ts
index 0fb3137e..51a180de 100644
--- a/apps/app/components/crm/timeline/timeline-search-params.ts
+++ b/apps/app/components/crm/timeline/timeline-search-params.ts
@@ -1,15 +1,52 @@
+import { parseAsStringLiteral } from "nuqs/server";
+
/**
- * The timeline's filter.
+ * The timeline's filter, in the URL like every other view state here: "the
+ * Attio deal, on Activity, showing what's outstanding" is then a link you can
+ * send someone, and it survives a refresh.
+ *
+ * What makes that safe is `replace`, nuqs's default: flicking between Upcoming
+ * and Done is reading, not navigating, so it rewrites the current history entry
+ * instead of stacking four of them in front of the Back button that closes the
+ * sheet. Same call `tab` and `add` make in `record-stack.ts`.
*
- * Component state rather than a URL param: the timeline now lives inside a
- * record sheet, and the sheet's identity is already in `?record=`. Adding the
- * filter there too would mean a glance at "Upcoming" becomes a history entry
- * the back button has to walk through before it closes the sheet.
+ * Imported from `nuqs/server` for the same reason the list parsers are —
+ * parsers are plain data, and nothing here should drag a client-only module
+ * into a server component that wants to read the same key.
*/
-export const TIMELINE_TABS = ["all", "notes", "upcoming", "done"] as const;
+/**
+ * `email` and `meetings` cover what a rep logged by hand *and* what the Google
+ * sync projected. Splitting those apart would turn "have we spoken to them?"
+ * into two questions with two answers.
+ */
+export const TIMELINE_TABS = [
+ "all",
+ "notes",
+ "email",
+ "meetings",
+ "upcoming",
+ "done",
+] as const;
export type TimelineTab = (typeof TIMELINE_TABS)[number];
+/**
+ * The URL key, shared with `record-stack.ts`, which clears it when you leave
+ * the Activity panel or move to another record — the filter describes one
+ * record's timeline, and a `?timeline=done` still hanging off the URL two
+ * records later is either a lie or a surprise.
+ */
+export const TIMELINE_PARAM = "timeline";
+
+/**
+ * A literal parser rather than a plain string one, so a hand-edited
+ * `?timeline=whatever` falls back to All instead of asking the API to filter
+ * by a value it has never heard of. `all` is the default, and therefore the
+ * absence of the param.
+ */
+export const timelineTabParser =
+ parseAsStringLiteral(TIMELINE_TABS).withDefault("all");
+
/** The API filter a tab maps to. `all` splits into pinned + history. */
export function historyFilter(tab: TimelineTab) {
return tab === "all" ? ("history" as const) : tab;
diff --git a/apps/app/components/crm/timeline/timeline.tsx b/apps/app/components/crm/timeline/timeline.tsx
index af7b3572..36d3fcba 100644
--- a/apps/app/components/crm/timeline/timeline.tsx
+++ b/apps/app/components/crm/timeline/timeline.tsx
@@ -4,14 +4,16 @@ import { Button } from "@crm/ui/components/button";
import { Spinner } from "@crm/ui/components/spinner";
import { ToggleGroup, ToggleGroupItem } from "@crm/ui/components/toggle-group";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { useState } from "react";
+import { useQueryState } from "nuqs";
import { useTRPC } from "@/lib/trpc/client";
import { ActivityComposer } from "./activity-composer";
import { TimelineEntry, type TimelineEntryData } from "./timeline-entry";
import {
historyFilter,
+ TIMELINE_PARAM,
TIMELINE_TABS,
type TimelineTab,
+ timelineTabParser,
} from "./timeline-search-params";
/** Exactly one of these — a timeline is always about one record. */
@@ -23,6 +25,8 @@ export type TimelineAnchor =
const TAB_LABELS: Record<TimelineTab, string> = {
all: "All",
notes: "Notes",
+ email: "Email",
+ meetings: "Meetings",
upcoming: "Upcoming",
done: "Done",
};
@@ -34,23 +38,35 @@ const dayFormat = new Intl.DateTimeFormat(undefined, {
year: "numeric",
});
-/** Groups entries by calendar day, preserving the order they arrived in. */
+/**
+ * Entries under one heading per day, in the order they arrive.
+ *
+ * Keyed by a map rather than by comparing against the previous entry: run-length
+ * grouping silently depends on the list being sorted by the very field it groups
+ * on, and the moment that stops being true it emits the same day twice — which
+ * React sees as duplicate keys. The API does order by `occurredAt`, so runs
+ * *are* contiguous; this just refuses to be the thing that breaks if that ever
+ * changes.
+ */
function byDay(entries: TimelineEntryData[]) {
- const groups: { day: string; label: string; entries: TimelineEntryData[] }[] =
- [];
+ const groups = new Map<
+ string,
+ { day: string; label: string; entries: TimelineEntryData[] }
+ >();
for (const entry of entries) {
const at = new Date(entry.occurredAt ?? entry.createdAt);
const day = at.toDateString();
- const last = groups[groups.length - 1];
- if (last?.day === day) {
- last.entries.push(entry);
+
+ const group = groups.get(day);
+ if (group) {
+ group.entries.push(entry);
} else {
- groups.push({ day, label: dayFormat.format(at), entries: [entry] });
+ groups.set(day, { day, label: dayFormat.format(at), entries: [entry] });
}
}
- return groups;
+ return [...groups.values()];
}
/**
@@ -67,7 +83,7 @@ function byDay(entries: TimelineEntryData[]) {
export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
const trpc = useTRPC();
- const [tab, setTab] = useState<TimelineTab>("all");
+ const [tab, setTab] = useQueryState(TIMELINE_PARAM, timelineTabParser);
const counts = useQuery(trpc.activities.timelineCounts.queryOptions(anchor));
@@ -102,7 +118,11 @@ export function Timeline({ anchor }: { anchor: TimelineAnchor }) {
<ToggleGroup
type="single"
value={tab}
- onValueChange={(next) => next && setTab(next as TimelineTab)}
+ onValueChange={(next) => {
+ // The group clears its value when you click the active item;
+ // a timeline with no filter at all is not a state it has.
+ if (next) void setTab(next as TimelineTab);
+ }}
variant="outline"
size="sm"
>
diff --git a/apps/app/lib/session.ts b/apps/app/lib/session.ts
index accd9fc7..10177f42 100644
--- a/apps/app/lib/session.ts
+++ b/apps/app/lib/session.ts
@@ -1,4 +1,5 @@
-import { auth, type Session } from "@crm/auth";
+import { auth, hasSyncScopes, type Session } from "@crm/auth";
+import { db } from "@crm/db";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
@@ -17,3 +18,41 @@ export async function requireSession(): Promise<Session> {
return session;
}
+
+/**
+ * The scopes Google has actually granted this user.
+ *
+ * `cache()`d, so the gate below costs one query per request no matter how many
+ * layouts and pages ask.
+ */
+const grantedScope = cache(async (userId: string): Promise<string | null> => {
+ const account = await db.account.findFirst({
+ where: { userId, providerId: "google" },
+ select: { scope: true },
+ });
+
+ return account?.scope ?? null;
+});
+
+/**
+ * A session that has granted Gmail and Calendar.
+ *
+ * Requesting the scopes at sign-in is not the same as having them: Google's
+ * granular consent lets someone untick one and complete sign-in anyway, and an
+ * account created before those scopes were required still carries the old
+ * grant. Either way the CRM would look signed-in and quietly sync nothing, so
+ * this is the check that makes mailbox access a real condition of using the
+ * tool rather than an intention.
+ *
+ * Sends them to `/grant-access`, which is outside the app shell — gating inside
+ * it would redirect the page that does the gating.
+ */
+export async function requireGoogleAccess(): Promise<Session> {
+ const session = await requireSession();
+
+ if (!hasSyncScopes(await grantedScope(session.user.id))) {
+ redirect("/grant-access");
+ }
+
+ return session;
+}
diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.ts
index 7f2bca3a..21355919 100644
--- a/apps/app/lib/trpc/cache.ts
+++ b/apps/app/lib/trpc/cache.ts
@@ -46,6 +46,14 @@ export type CrmCache = {
deal(id?: string, options?: Options): Promise<void>;
/** A note, a task, or a task being ticked off. */
activity(options?: Options): Promise<void>;
+ /**
+ * Connecting, disconnecting, a manual sync, or suppressing a domain.
+ *
+ * A *scheduled* sync is not this: nothing the browser did caused it, so it is
+ * polled rather than invalidated (see `sync-status`). This is only for the
+ * writes a rep triggers from the settings page.
+ */
+ google(options?: Options): Promise<void>;
/** An import writes across every table, so nothing is assumed to survive. */
everything(): Promise<void>;
};
@@ -163,6 +171,23 @@ export function useCrmCache(): CrmCache {
options,
),
+ google: (options) =>
+ run(
+ [trpc.google.status.queryKey()],
+ [
+ // A sync writes threads and meetings onto timelines, and
+ // auto-creation writes whole companies and contacts — so a
+ // disconnect-and-purge has to reach the lists too, not just the
+ // settings page it was pressed on.
+ ...activityKeys(),
+ ...listKeys(),
+ trpc.companies.byId.queryKey(),
+ trpc.contacts.byId.queryKey(),
+ trpc.dashboard.summary.queryKey(),
+ ],
+ options,
+ ),
+
everything: () => queryClient.invalidateQueries(),
};
}
diff --git a/bun.lock b/bun.lock
index 6747ba1f..5c37ede1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10,6 +10,20 @@
"typescript": "5.9.2",
},
},
+ "apps/agent": {
+ "name": "agent",
+ "version": "0.0.1",
+ "dependencies": {
+ "@crm/db": "workspace:*",
+ "eve": "^0.29.4",
+ "zod": "^4.4.3",
+ },
+ "devDependencies": {
+ "@crm/typescript-config": "workspace:*",
+ "@types/node": "^24.0.0",
+ "typescript": "^5.9.2",
+ },
+ },
"apps/api": {
"name": "api",
"version": "0.0.1",
@@ -160,6 +174,12 @@
"sharp",
],
"packages": {
+ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.4", "@ai-sdk/provider-utils": "5.0.18", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-N1P6bdW/aC5rxLeuGYgx3X4el3DoZy8UWlky+g+AeIZSmxaEi/AToHJL4cmZ6nCPHk1byqJWwC+PaOZG0hK0dw=="],
+
+ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-tbHKNLirllUNF3ZlkCsXnwab2ZV1Sl4b1H/Cp9ruCce15IBmskE8Gwkk0yo9xDWY+jho2of7lVXtwSsyrq7cwQ=="],
+
+ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.4", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8", "undici": "^7.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-UBNCrkxS5llgN2/RXLBRkjCFTIuL6YB1Goq5c+yRecnznhtX4XPjTwLHz2hrsTltTVZ0rqVegtnwFXdPBkjDHA=="],
+
"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
@@ -304,8 +324,12 @@
"@electric-sql/pglite-tools": ["@electric-sql/[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" } }, "sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg=="],
+ "@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "2.0.1", "tslib": "^2.4.0" } }, "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g=="],
+
"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+ "@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ=="],
+
"@floating-ui/core": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="],
"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="],
@@ -388,6 +412,8 @@
"@mrleebo/prisma-ast": ["@mrleebo/[email protected]", "", { "dependencies": { "chevrotain": "^10.5.0", "lilconfig": "^2.1.0" } }, "sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw=="],
+ "@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" } }, "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw=="],
+
"@nestjs/cache-manager": ["@nestjs/[email protected]", "", { "peerDependencies": { "@nestjs/common": "^9.0.0 || ^10.0.0 || ^11.0.0", "@nestjs/core": "^9.0.0 || ^10.0.0 || ^11.0.0", "cache-manager": ">=6", "keyv": ">=5", "rxjs": "^7.8.1" } }, "sha512-HMtiOfHz75NZX7mJn1VnZGLSachVI04TnUc5wvEogIaKwk5BDQHgtP5htxreizjv7oxKalJbuTyxtiF6bE+bgQ=="],
"@nestjs/common": ["@nestjs/[email protected]", "", { "dependencies": { "file-type": "21.3.4", "iterare": "1.2.1", "load-esm": "1.0.3", "tslib": "2.8.1", "uid": "2.0.2" }, "peerDependencies": { "class-transformer": ">=0.4.1", "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, "optionalPeers": ["class-transformer", "class-validator"] }, "sha512-bRImsxibie+AM7xjdwcrm/gr5YeacI65kSBNzTufa1Ib5iwziaY/lqMtRh9THq6pbV4e1HP9aI2ZxGUumnmaoQ=="],
@@ -430,6 +456,8 @@
"@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ=="],
+
"@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="],
"@prisma/adapter-pg": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.9.1", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-Ho2RK1KanQxLNSC0sR5bpiiVep10sWPLXCcxK+KXfI/Q69TMRbiafSvLPv3V9snimX72rMCqGlyJ4sBO4lKTAw=="],
@@ -584,6 +612,38 @@
"@reduxjs/toolkit": ["@reduxjs/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw=="],
+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA=="],
+
+ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA=="],
+
+ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ=="],
+
+ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg=="],
+
+ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA=="],
+
+ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg=="],
+
+ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A=="],
+
+ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg=="],
+
+ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ=="],
+
+ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw=="],
+
+ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A=="],
+
+ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw=="],
+
+ "@rolldown/binding-wasm32-wasi": ["@rolldown/[email protected]", "", { "dependencies": { "@emnapi/core": "2.0.0-alpha.3", "@emnapi/runtime": "2.0.0-alpha.3", "@napi-rs/wasm-runtime": "^1.2.0" } }, "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww=="],
+
+ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw=="],
+
+ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ=="],
+
+ "@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
+
"@sec-ant/readable-stream": ["@sec-ant/[email protected]", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
"@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
@@ -658,6 +718,8 @@
"@turbo/windows-arm64": ["@turbo/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-VN30vh3b3Czh2WzYHNTfF1FE0YMZ5aHsLO8dBMGHJewA6792wX6iJR8ZxlzFW6WdOu0gEAKIvlYhfyT81Wkm4Q=="],
+ "@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
+
"@types/body-parser": ["@types/[email protected]", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
@@ -730,6 +792,8 @@
"@types/validator": ["@types/[email protected]", "", {}, "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA=="],
+ "@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],
+
"@visx/curve": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg=="],
"@visx/event": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/point": "4.0.1-alpha.0" } }, "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g=="],
@@ -748,8 +812,14 @@
"@visx/vendor": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-array": "3.0.3", "@types/d3-color": "3.1.0", "@types/d3-delaunay": "6.0.1", "@types/d3-format": "3.0.1", "@types/d3-geo": "3.1.0", "@types/d3-interpolate": "3.0.1", "@types/d3-path": "3.1.1", "@types/d3-scale": "4.0.2", "@types/d3-shape": "3.1.7", "@types/d3-time": "3.0.0", "@types/d3-time-format": "2.1.0", "d3-array": "3.2.1", "d3-color": "3.1.0", "d3-delaunay": "6.0.2", "d3-format": "3.1.0", "d3-geo": "3.1.0", "d3-interpolate": "3.0.1", "d3-path": "3.1.0", "d3-scale": "4.0.2", "d3-shape": "3.2.0", "d3-time": "3.1.0", "d3-time-format": "4.1.0", "internmap": "2.0.3" } }, "sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ=="],
+ "@workflow/serde": ["@workflow/[email protected]", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="],
+
"accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
+ "agent": ["agent@workspace:apps/agent"],
+
+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "4.0.36", "@ai-sdk/provider": "4.0.4", "@ai-sdk/provider-utils": "5.0.18" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-e0MpNtufu6JmcmwMUTgM1smCRkP5z014iPaKgnCm7kmMsTSIZbOJN2vglhPq0WIj/6x7ewVi6W0FyIR0pjaE3Q=="],
+
"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
@@ -880,6 +950,8 @@
"confbox": ["[email protected]", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],
+ "consola": ["[email protected]", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],
+
"content-disposition": ["[email protected]", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["[email protected]", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
@@ -900,6 +972,8 @@
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
+ "crossws": ["[email protected]", "", { "peerDependencies": { "srvx": ">=0.11.5" }, "optionalPeers": ["srvx"] }, "sha512-pz3oubH/dt12KjqsUB0IuXW4nwRDQ583iDsP4555Cpdqx0NoU7pGlWBcayyFI8f/l/idRpgjMEfwuOxSWJYlIA=="],
+
"cssesc": ["[email protected]", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
@@ -930,6 +1004,8 @@
"d3-timer": ["[email protected]", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
+ "db0": ["[email protected]", "", { "peerDependencies": { "@electric-sql/pglite": "*", "@libsql/client": "*", "better-sqlite3": "*", "drizzle-orm": "*", "mysql2": "*", "sqlite3": "*" }, "optionalPeers": ["@electric-sql/pglite", "@libsql/client", "better-sqlite3", "drizzle-orm", "mysql2", "sqlite3"] }, "sha512-RiXXi4WaNzPTHEOu8UPQKMooIbqOEyqA1t7Z6MsdxSCeb8iUC9ko3LcmsLmeUt2SM5bctfArZKkRQggKZz7JNw=="],
+
"debounce-fn": ["[email protected]", "", { "dependencies": { "mimic-fn": "^3.0.0" } }, "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
@@ -1004,6 +1080,8 @@
"env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
+ "env-runner": ["[email protected]", "", { "dependencies": { "crossws": "^0.4.8", "exsolve": "^1.1.0", "httpxy": "^0.5.4", "srvx": "^0.11.19" }, "peerDependencies": { "@netlify/runtime": "^4.1.23", "@vercel/queue": ">=0.2.0", "miniflare": "^4.20260515.0", "wrangler": "^4.0.0" }, "optionalPeers": ["@netlify/runtime", "@vercel/queue", "miniflare", "wrangler"], "bin": { "env-runner": "dist/cli.mjs" } }, "sha512-2LRJM4P2KLX6J83QZZrMqvgCDt/D5ea7wPcI3yYiy5cG/9rX5QwdwZFx0D7ktWnjdRyZxYjttGGorb5nFqb1CA=="],
+
"error-ex": ["[email protected]", "", { "dependencies": { "is-arrayish": "^0.2.1" } }, "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ=="],
"es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
@@ -1024,6 +1102,8 @@
"etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
+ "eve": ["[email protected]", "", { "dependencies": { "nitro": "3.0.260610-beta", "undici": "8.9.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0", "ai": "^7.0.38", "braintrust": "^3.0.0", "just-bash": "^3.0.0", "microsandbox": "^0.5.0" }, "optionalPeers": ["@opentelemetry/api", "braintrust", "just-bash", "microsandbox"], "bin": { "eve": "./bin/eve.js" } }, "sha512-EwOmL37l+Iuu7Umno7at3flFpMs4AtT9cg1J4dt7EZ8ZdxaCvGXwvKGwiulMkG8oXkMQ5CNhxMi2ruHJwrtpwQ=="],
+
"eventemitter3": ["[email protected]", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="],
"eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
@@ -1124,6 +1204,8 @@
"graphmatch": ["[email protected]", "", {}, "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg=="],
+ "h3": ["[email protected]", "", { "dependencies": { "rou3": "^0.8.1", "srvx": "^0.11.15" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"], "bin": { "h3": "bin/h3.mjs" } }, "sha512-Esv0DMIuPkCTSWCA0vO73vcTqwzH1wjSrAO1TXNu/K3up1sZHa9EKMapbmxCDYBeymC3fVTk4qxp7ogQWQ+KgA=="],
+
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
@@ -1138,10 +1220,14 @@
"hono": ["[email protected]", "", {}, "sha512-+SwvkaiJtxsiPjhy9LivY/1m7UsNqCJetM1BrZl9A5DkQhlbHQDU730mMiDPWjnoCYOM8Chf3WrCJw27kNTPFQ=="],
+ "hookable": ["[email protected]", "", {}, "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ=="],
+
"hookified": ["[email protected]", "", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
"http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
+ "httpxy": ["[email protected]", "", {}, "sha512-uDjmnPyp1q4Sgzf3w+J/Fc6UqcCEj0x4Wjp7OqK5dGhNeDgpyrAmnS6ey8QWrX3SWDon2DMKf9sBa5X9+CVyMA=="],
+
"human-signals": ["[email protected]", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="],
"iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
@@ -1214,6 +1300,8 @@
"json-parse-even-better-errors": ["[email protected]", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="],
+ "json-schema": ["[email protected]", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],
+
"json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
@@ -1332,6 +1420,10 @@
"next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
+ "nf3": ["[email protected]", "", {}, "sha512-RWVLAWozmVD3AaDmaU3qMGB3v+yNlH5d9qqStI4e/WLlNQVnJ4YErGDbYCIrGFyrHdbF6I6Baf0Ae6c7tFYmSg=="],
+
+ "nitro": ["[email protected]", "", { "dependencies": { "consola": "^3.4.2", "crossws": "^0.4.6", "db0": "^0.3.4", "env-runner": "^0.1.12", "h3": "2.0.1-rc.22", "hookable": "^6.1.1", "nf3": "^0.3.17", "ocache": "^0.1.5", "ofetch": "2.0.0-alpha.3", "ohash": "^2.0.11", "rolldown": "^1.1.0", "srvx": "^0.11.16", "unenv": "2.0.0-rc.24", "unstorage": "2.0.0-alpha.7" }, "peerDependencies": { "@vercel/queue": "^0.3.0", "dotenv": "*", "giget": "*", "jiti": "^2.7.0", "rollup": "^4.61.1", "vite": "^7 || ^8", "xml2js": "^0.6.2", "zephyr-agent": "^0.2.0" }, "optionalPeers": ["@vercel/queue", "dotenv", "giget", "jiti", "rollup", "vite", "xml2js", "zephyr-agent"], "bin": { "nitro": "dist/cli/index.mjs" } }, "sha512-KPb4L5yaF/Rx/xoGMpgHRJvZhbhGiqbRKOwwPLCH9jKTKTsEUHLjnJas85AeCzaswqa8Wi52eQBtRsODC4PS0Q=="],
+
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g=="],
"node-releases": ["[email protected]", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="],
@@ -1346,6 +1438,10 @@
"object-treeify": ["[email protected]", "", {}, "sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A=="],
+ "ocache": ["[email protected]", "", { "dependencies": { "ohash": "^2.0.11" } }, "sha512-kNNnkkVQup/QDvmTz8Q84wc2ntiyoVHDxa6eHWKt5qdGAmFRBIxy83rxgCYEjW0x06UJ9E3P6VgM2yY4rOBH4w=="],
+
+ "ofetch": ["[email protected]", "", {}, "sha512-zpYTCs2byOuft65vI3z43Dd6iSdFbOZZLb9/d21aCpx2rGastVU9dOCv0lu4ykc1Ur1anAYjDi3SUvR0vq50JA=="],
+
"ohash": ["[email protected]", "", {}, "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ=="],
"on-finished": ["[email protected]", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
@@ -1510,6 +1606,8 @@
"robust-predicates": ["[email protected]", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="],
+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.142.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.2.1", "@rolldown/binding-darwin-arm64": "1.2.1", "@rolldown/binding-darwin-x64": "1.2.1", "@rolldown/binding-freebsd-x64": "1.2.1", "@rolldown/binding-linux-arm-gnueabihf": "1.2.1", "@rolldown/binding-linux-arm64-gnu": "1.2.1", "@rolldown/binding-linux-arm64-musl": "1.2.1", "@rolldown/binding-linux-ppc64-gnu": "1.2.1", "@rolldown/binding-linux-s390x-gnu": "1.2.1", "@rolldown/binding-linux-x64-gnu": "1.2.1", "@rolldown/binding-linux-x64-musl": "1.2.1", "@rolldown/binding-openharmony-arm64": "1.2.1", "@rolldown/binding-wasm32-wasi": "1.2.1", "@rolldown/binding-win32-arm64-msvc": "1.2.1", "@rolldown/binding-win32-x64-msvc": "1.2.1" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw=="],
+
"rou3": ["[email protected]", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="],
"router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
@@ -1576,6 +1674,8 @@
"sqlstring": ["[email protected]", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
+ "srvx": ["[email protected]", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-LqZxxBDMKuMAZzFzJnDCkFOrs9MZQZr0LvHiO/SuSZVdQaXD7xQ5UWTUxheJrQPve1qk9MG2B/yttUvJxw8egQ=="],
+
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
@@ -1656,12 +1756,16 @@
"undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
+ "unenv": ["[email protected]", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],
+
"unicorn-magic": ["[email protected]", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
"universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
"unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
+ "unstorage": ["[email protected]", "", { "peerDependencies": { "@azure/app-configuration": "^1.11.0", "@azure/cosmos": "^4.9.1", "@azure/data-tables": "^13.3.2", "@azure/identity": "^4.13.0", "@azure/keyvault-secrets": "^4.10.0", "@azure/storage-blob": "^12.31.0", "@capacitor/preferences": "^6 || ^7 || ^8", "@deno/kv": ">=0.13.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.36.2", "@vercel/blob": ">=0.27.3", "@vercel/functions": "^2.2.12 || ^3.0.0", "@vercel/kv": "^1.0.1", "aws4fetch": "^1.0.20", "chokidar": "^4 || ^5", "db0": ">=0.3.4", "idb-keyval": "^6.2.2", "ioredis": "^5.9.3", "lru-cache": "^11.2.6", "mongodb": "^6 || ^7", "ofetch": "*", "uploadthing": "^7.7.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/functions", "@vercel/kv", "aws4fetch", "chokidar", "db0", "idb-keyval", "ioredis", "lru-cache", "mongodb", "ofetch", "uploadthing"] }, "sha512-ELPztchk2zgFJnakyodVY3vJWGW9jy//keJ32IOJVGUMyaPydwcA1FtVvWqT0TNRch9H+cMNEGllfVFfScImog=="],
+
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-callback-ref": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
@@ -1916,6 +2020,8 @@
"@reduxjs/toolkit/reselect": ["[email protected]", "", {}, "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="],
+ "@rolldown/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA=="],
+
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
@@ -1930,6 +2036,8 @@
"@visx/vendor/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ=="],
+ "agent/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
"api/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"app/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA=="],
@@ -1968,8 +2076,12 @@
"enquirer/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+ "eve/undici": ["[email protected]", "", {}, "sha512-aWZpUj7XoGonMClx4gdDRfgBjqeA+F473aDmROQQbM9n6PRfK/u1q/a0X4wMTgcHfT8H6fpbt98PFuDUwFg2YA=="],
+
"form-data/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
+ "h3/rou3": ["[email protected]", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
+
"log-symbols/is-unicode-supported": ["[email protected]", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="],
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
diff --git a/docs/environment.md b/docs/environment.md
index 4877d893..cdfda6c8 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -62,6 +62,33 @@ 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.
+
+## Gmail and Calendar sync
+
+Always on. Same OAuth client, same callback — the two read-only scopes are added to the existing Google provider rather than to a second one, so there is no extra redirect URI to register.
+
+The scopes are requested **at sign-in** and are a condition of using the CRM: `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.
+
+**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.
+
+| 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.
+- **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.
+
+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.
diff --git a/docs/plan/gmail-calendar-plan.md b/docs/plan/gmail-calendar-plan.md
new file mode 100644
index 00000000..ae6fe4dd
--- /dev/null
+++ b/docs/plan/gmail-calendar-plan.md
@@ -0,0 +1,821 @@
+# Plan — Gmail & Calendar
+
+Put the conversation back in the CRM. Three features, in the order they should
+be built:
+
+1. **Meetings on the record.** A calendar event with someone from Acme shows on
+ Acme's timeline — before it happens, and after.
+2. **Email threads in-line.** A thread with someone from Acme shows on Acme's
+ timeline, collapsed to a subject and a snippet, expandable to the messages.
+3. **Auto-created companies and contacts.** Booking a meeting or holding a
+ two-way thread with a new domain creates the company and the contact, so
+ nobody types what Google already knows.
+
+Read it with [`AGENTS.md`](../../AGENTS.md), [`api.md`](../api.md),
+[`design.md`](../design.md) and [`crm-plan.md`](../crm-plan.md). The conventions
+there are assumed, not repeated: single tenant, tRPC as the data surface,
+services throw `HttpException`, freshness via `useCrmCache()`, all UI from
+`/packages/ui`.
+
+---
+
+## 1. The decisions that carry the design
+
+Six choices. Everything else follows.
+
+1. **Gmail and Calendar are granted at sign-in, and using the CRM is
+ conditional on them.** This is an internal, single-tenant tool where seeing
+ the conversation on a record *is* the product, so a rep with an account and no
+ mailbox is a half-configured account nobody notices is broken. The scopes go
+ on the provider config; because Google's granular consent lets someone untick
+ one and still finish signing in, the app also gates on what was actually
+ granted. §3.
+2. **Google's per-mailbox ids are not identities.** Gmail `threadId` is scoped
+ to one mailbox, so two reps on one thread would create two CRM threads.
+ Identity is the RFC 822 `Message-ID` for email and `iCalUID` for calendar,
+ both of which are global. §4.2.
+3. **Email and calendar get real tables; the timeline gets a projection.** One
+ `Activity` row per thread and per event, linked by FK. The timeline query,
+ its indexes, its filters and its cursor paging are untouched. §4.
+4. **Nothing is stored unless it is relevant.** A message is persisted only if a
+ participant resolves to a company we track, or qualifies to create one.
+ A rep's inbox contains their doctor. §5.
+5. **Auto-creation needs two-way engagement.** A thread the rep replied to, or a
+ meeting on the calendar. Not a received newsletter. §6.
+6. **Sync is cron-driven and its cursor lives in Postgres.** The API is a
+ serverless function; there is no worker to hold state, and the existing
+ in-process `EnrichmentQueue` deliberately drops work on shutdown. §7.
+
+### Choice table
+
+| Decision | Choice | Why |
+| --- | --- | --- |
+| Connect flow | Scopes on the provider config, requested at sign-in | §3.1. Internal tool — mailbox access is a condition of having an account. |
+| Enforcement | `requireGoogleAccess()` gate in the app shell | §3.1. Granular consent means "signed in" never implies "granted". |
+| Repair path | `authClient.linkSocial({ provider: "google", scopes })` | §3.1. Re-consent for a partial grant or a pre-existing account. |
+| Connected? | `Account.scope` contains both scopes | §3.1. The grant itself is the state — nothing to keep in sync. |
+| Token refresh | `auth.api.getAccessToken({ providerId: "google", userId })` | Better Auth refreshes on demand. No hand-rolled refresh. |
+| Disconnect | There isn't one — only purge-and-re-import, or revoke | §3.4. Syncing is mandatory, and a local disconnect would be undone by the next reconcile anyway. |
+| Scopes | `gmail.readonly`, `calendar.readonly`, read-only | Nothing writes to Google in v1. Sending mail is a separate decision. |
+| Google app type | **Internal** (Workspace-only) | Skips OAuth verification entirely. §3.3. |
+| Email identity | `Message-ID` header, unique | Gmail `threadId` is per-mailbox. §4.2. |
+| Thread identity | Root of `References` / `In-Reply-To`, unique | Same conversation, one CRM thread, whoever synced it. |
+| Event identity | `(iCalUID, originalStartTime)`, unique | `iCalUID` is shared across attendees *and* recurrence instances. §4.2. |
+| Timeline | One projected `Activity` per thread/event, FK-linked | Keeps the one-index-scan timeline in `activities.service.ts`. |
+| Relevance | Participant domain must resolve to a `Company`, or qualify to create one | §5. Privacy and junk prevention are the same rule. |
+| Bodies | Stored, plain text, quoted history stripped | "In-line" means readable. Never logged, never in list payloads. |
+| Sync trigger | Vercel Cron → authenticated internal route | §7. Pub/Sub push is a later upgrade behind the same handler. |
+| Sync state | `MailboxSync` row per account per source | Serverless has no memory between invocations. |
+| Backfill | **None.** Forward-only from first sight of a mailbox | §7.3. Nobody asked for three months of old mail in their CRM, and it deletes a whole class of machinery. |
+| Feature flag | None. Sync is simply on | §13. It gates nothing that can genuinely be absent, and defaults to off — so it is only ever wrong. |
+| Freshness | Poll while syncing, mirroring `enrichment-status` | A background write the browser did not cause. `api.md`. |
+| New UI | Added to `/packages/ui` | `design.md` — thread disclosure and attendee list are new primitives. |
+
+### Judgment calls worth your veto
+
+- **Calendar ships before Gmail.** Smaller API, cleaner dedupe key, no body
+ parsing, no privacy surface worth arguing about, and it proves the whole
+ connect → cron → project → render pipeline on the easy case. Gmail then adds
+ only Gmail's problems. If you want threads first, say so — but Phase 2 is
+ about two weeks cheaper than Phase 3 for most of the perceived value.
+- **Read-only, both APIs.** No sending, no event creation, no "log this email"
+ button writing back. It halves the scope review and removes every way this
+ feature can damage a customer relationship. Writing is a v2 conversation.
+- **Auto-create fires without an approval queue.** The guardrails in §6 are
+ tight enough that a review queue would mostly be a list of correct rows
+ waiting for someone to click Accept — and approval queues rot. Instead every
+ auto-created record is tagged with its provenance and is filterable, so a bad
+ rule is visible and reversible in bulk. Say the word if you want the queue.
+- **We store message bodies.** The alternative — metadata plus a deep link to
+ Gmail — is more private and much less useful, because the point is reading the
+ thread without leaving the record. §10 covers what that obliges us to do.
+- **Personal mail is dropped at ingest, not stored-then-hidden.** Slightly more
+ work at sync time, and the only version of this that survives someone reading
+ the database.
+
+---
+
+## 2. What exists that we build on
+
+| Thing | Where | Use |
+| --- | --- | --- |
+| Google OAuth, Better Auth | `packages/auth/src/auth.ts` | Add `scope` and `accessType: "offline"` here. Scope strings live in `packages/auth/src/scopes.ts`, imported by the API and the app. |
+| `Account.accessToken` / `refreshToken` / `scope` | `schema.prisma` | Better Auth already persists per-provider tokens. |
+| `domainFromEmail()` + free-domain blocklist | `apps/api/src/companies/domain.ts` | The matching backbone. Already rejects gmail.com et al. |
+| `EnrichmentService.companyForEmail()` | `apps/api/src/enrichment/enrichment.service.ts:197` | Find-or-create company by domain, then enqueue enrichment. Auto-creation reuses this verbatim. |
+| `ActivityType.EMAIL` / `MEETING` | `schema.prisma` | The enum values already exist and are already in `NOTE_TYPES`. |
+| Timeline, cursor-paged, filter tabs | `apps/api/src/activities/activities.service.ts` | Extended, not replaced. |
+| Enrichment polling pattern | `apps/app/components/crm/enrichment-status.tsx` | Copy the shape for sync status. |
+| Cache fan-out | `apps/app/lib/trpc/cache.ts` | Add `cache.google()`; do not list keys at call sites. |
+
+---
+
+## 3. Connecting an account
+
+### 3.1 Scopes at sign-in, and the gate behind them
+
+The scopes go on the provider config in `packages/auth/src/auth.ts`, so every
+sign-in asks for them:
+
+```ts
+socialProviders.google = {
+ ...env.google,
+ scope: [...SYNC_SCOPES], // gmail.readonly, calendar.readonly
+ accessType: "offline", // so Google issues a refresh token
+};
+```
+
+Four behaviours make this work, all read out of the installed
+`[email protected]` rather than assumed:
+
+- **Scopes merge, they don't replace.** The Google provider builds
+ `["email", "profile", "openid"]`, then appends `options.scope`, then appends
+ any per-call `scopes`.
+- **Incremental authorisation is already on.** The provider hardcodes
+ `additionalParams: { include_granted_scopes: "true" }`, so a token issued for
+ a widened grant covers the union rather than only the new scopes.
+- **Re-consenting updates the account in place.** The OAuth callback finds the
+ existing account by `(providerId, accountId)` and updates the tokens, both
+ expiries and `scope`. That makes the repair path idempotent.
+- **`Account.scope` is the connection state.** The granted scopes are persisted
+ as a string, so "did they actually grant it?" is a column read.
+
+**Requesting is not the same as granting.** Google's granular consent lets
+someone untick a scope and finish signing in anyway, and any account created
+before these scopes were required still carries the old grant. Either way the
+person lands inside a CRM that looks signed-in and silently syncs nothing — so
+asking at sign-in is necessary but not sufficient, and the app gates on the
+result:
+
+- `requireGoogleAccess()` (`apps/app/lib/session.ts`) reads `Account.scope`,
+ `cache()`d so it costs one query per request, and redirects to
+ `/grant-access` when either scope is missing.
+- The `(app)` layout calls it instead of `requireSession()`, so the gate covers
+ every page in the shell at once.
+- `/grant-access` lives outside the `(app)` group deliberately — a page inside
+ it would be redirected by the very layout doing the gating. It explains what
+ is read and why, and offers `linkSocial` to re-consent, plus a sign-out for
+ anyone who would rather not.
+
+`prompt: "consent"` is deliberately **not** set: it is a provider-level option,
+so it would show the consent screen on every sign-in forever. It is not needed,
+because a first sign-in — and any sign-in asking for a scope not yet granted —
+prompts anyway, and it is that prompt which mints the refresh token. The
+missing-refresh-token case is detected (`hasRefreshToken`) and repaired rather
+than pre-empted.
+
+### 3.2 Reading and refreshing tokens
+
+Never touch `Account.accessToken` directly. A `GoogleTokenService` wraps:
+
+```ts
+const { accessToken } = await auth.api.getAccessToken({
+ body: { providerId: "google", userId },
+});
+```
+
+which refreshes if expired (within five seconds of expiry, per the
+implementation) and persists the new token. Confirmed present in 1.6.25 as
+`/get-access-token`. If it throws, the connection is dead — mark the
+`MailboxSync` row `NEEDS_RECONNECT` and surface a reconnect prompt; do not retry
+in a loop.
+
+### 3.3 Google Cloud setup (Phase 0, and it gates everything)
+
+- One OAuth client, existing GCP project, add the two scopes.
+- Set the consent screen **User type: Internal**. This is the whole ball game.
+ `gmail.readonly` is a **restricted** scope (Google's own classification, not a
+ judgement call), and an External app using it needs OAuth verification *plus*
+ a CASA security assessment, renewed annually — months of work. For an Internal
+ app Google's documentation is explicit: *"scopes aren't listed on the consent
+ screen and use of restricted or sensitive scopes doesn't require further
+ review by Google."* This CRM is already internal-only behind Google sign-in,
+ so the exemption costs us nothing.
+
+ Two caveats worth writing down now, because both are expensive later: the
+ exemption is tied to the **Internal user type specifically** — an External app
+ that merely happens to target Workspace users does not get it — and going
+ External at any point in the future means the full restricted-scope review.
+ If this CRM will ever be sold or opened to another domain, that decision
+ belongs here, not in a year.
+- Enable the Gmail API and the Google Calendar API on the project.
+- The callback is the **existing** `…/api/auth/callback/google`. Extending the
+ grant adds no new redirect URI, which is one fewer thing to get wrong across
+ preview environments.
+
+### 3.4 There is no disconnect
+
+Making mailbox access a condition of having an account settles this section:
+there is no supported state where a signed-in rep is not syncing, so there is no
+disconnect button.
+
+That is not only a policy choice, it is what the mechanics allow. A local
+disconnect would delete the `MailboxSync` rows, and the next reconcile — which
+derives those rows from the grant — would rebuild them within five minutes. A
+button that appears to work and silently undoes itself is worse than no button.
+Better Auth also **refuses to unlink the last account**
+(`FAILED_TO_UNLINK_LAST_ACCOUNT`), and Google is our only sign-in, so unlinking
+was never available either.
+
+What the settings page offers instead:
+
+- **Delete and re-import** (`google.purgeSyncedData`) — deletes every thread and
+ event this mailbox contributed, cascading to the projected activities, then
+ resets the cursors so the window re-imports from scratch. This is the answer to
+ "get my mail out of the CRM", and it should not need a migration.
+- **Revoke Google access** — calls Google's revoke endpoint. One OAuth client
+ means one grant per user, so this ends *CRM access itself*, not just syncing:
+ the scopes disappear, the gate catches the next request, and the person lands
+ on `/grant-access`. Worded as such and behind a confirm, never as a default.
+
+The only design with independent revocation — mailbox access off, sign-in intact
+— is a **separate GCP OAuth client** for sync. Under a mandatory-sync policy
+that state is not wanted, so the second client stays unbuilt. §15.
+
+**The missing-refresh-token edge case** still applies: if Google decides not to
+re-prompt, no refresh token is issued and `getAccessToken` fails an hour later.
+`hasRefreshToken` detects it and the settings page shows a reconnect banner
+rather than the sync dying quietly.
+
+
+---
+
+## 4. Data model
+
+### 4.1 New models
+
+```prisma
+enum GoogleSyncStatus {
+ IDLE
+ RUNNING
+ NEEDS_RECONNECT
+ FAILED
+}
+
+enum EmailDirection {
+ INBOUND
+ OUTBOUND
+}
+
+/// Per-user, per-source cursor. In Postgres because the API is serverless and
+/// the in-process queue drops work on shutdown by design.
+model MailboxSync {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ /// "gmail" | "calendar".
+ source String
+
+ status GoogleSyncStatus @default(IDLE)
+ /// Gmail: the last processed historyId. Calendar: nextSyncToken.
+ /// Stamped with "now" on first sight — there is no backfill, so nothing
+ /// before that point is ever read.
+ cursor String?
+ lastSyncedAt DateTime?
+ lastError String?
+
+ @@unique([userId, source])
+ @@map("mailboxSync")
+}
+
+/// One conversation, whoever's mailbox it came from.
+model EmailThread {
+ id String @id @default(cuid())
+ /// The RFC 822 Message-ID of the thread root — global, unlike Gmail's
+ /// mailbox-scoped threadId. This is what stops two reps on one thread
+ /// producing two CRM threads.
+ rootMessageId String @unique
+ subject String?
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: SetNull)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ firstMessageAt DateTime
+ lastMessageAt DateTime
+ messageCount Int @default(0)
+
+ messages EmailMessage[]
+ activity Activity?
+
+ @@index([companyId, lastMessageAt])
+ @@map("emailThread")
+}
+
+model EmailMessage {
+ id String @id @default(cuid())
+ threadId String
+ thread EmailThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
+
+ /// Global message identity. Unique, so account B's sync skips what
+ /// account A already ingested.
+ rfcMessageId String @unique
+ /// Whose mailbox produced this copy, and its id there — for deep links.
+ syncedByUserId String?
+ gmailMessageId String?
+
+ direction EmailDirection
+ fromEmail String
+ fromName String?
+ /// [{ email, name, kind: "to" | "cc" }]. Not a table: nothing queries it.
+ recipients Json
+ subject String?
+ snippet String?
+ /// Plain text, quoted history stripped. Never logged; never in list payloads.
+ body String?
+ sentAt DateTime
+
+ @@index([threadId, sentAt])
+ @@map("emailMessage")
+}
+
+model CalendarEvent {
+ id String @id @default(cuid())
+ /// Shared by every attendee's copy of the event, and by every instance of a
+ /// recurrence — which is why the start time is part of the key.
+ iCalUid String
+ originalStartTime DateTime
+ /// Set on an instance of a recurring series.
+ recurringEventId String?
+
+ title String?
+ description String?
+ location String?
+ conferenceUrl String?
+ startsAt DateTime
+ endsAt DateTime
+ isAllDay Boolean @default(false)
+ status String
+ organizerEmail String?
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: SetNull)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ syncedByUserId String?
+ googleEventId String?
+
+ attendees CalendarAttendee[]
+ activity Activity?
+
+ @@unique([iCalUid, originalStartTime])
+ @@index([companyId, startsAt])
+ @@map("calendarEvent")
+}
+
+model CalendarAttendee {
+ id String @id @default(cuid())
+ eventId String
+ event CalendarEvent @relation(fields: [eventId], references: [id], onDelete: Cascade)
+
+ email String
+ name String?
+ /// needsAction | declined | tentative | accepted
+ responseStatus String?
+ isOrganizer Boolean @default(false)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ @@unique([eventId, email])
+ @@map("calendarAttendee")
+}
+
+/// Domains we never match on and never create from — vendors, ATSs,
+/// newsletters. Grows by hand and by a "not a customer" action in the UI.
+model SuppressedDomain {
+ domain String @id
+ reason String?
+ createdAt DateTime @default(now())
+ @@map("suppressedDomain")
+}
+```
+
+### 4.2 Why those keys, specifically
+
+Both were checked against Google's docs rather than assumed, because getting
+either wrong produces duplicates that are painful to unpick later.
+
+- **Gmail `threadId` is mailbox-scoped.** If two of our reps are on one thread,
+ each mailbox reports a different `threadId` for it. Deduping on `threadId`
+ would put the same conversation on Acme's timeline twice. The RFC 822
+ `Message-ID` header is globally unique per message, so `EmailMessage`
+ deduplicates on that, and the thread is keyed by the root message id — the
+ first entry of `References`, else `In-Reply-To`, else the message's own
+ `Message-ID`.
+- **`iCalUID` is shared across attendees' copies** — that is its purpose, per
+ RFC 5545 and Google's own reference — **and it is also shared by every
+ instance of a recurring series**, where only the `id` differs. So the key is
+ `(iCalUid, originalStartTime)`: `originalStartTime` identifies the instance
+ even if that instance has been moved.
+
+### 4.3 Changes to existing models
+
+```prisma
+enum RecordSource {
+ MANUAL
+ IMPORT
+ EMAIL
+ CALENDAR
+}
+
+model Company {
+ // …
+ source RecordSource @default(MANUAL)
+ emailThreads EmailThread[]
+ calendarEvents CalendarEvent[]
+}
+
+model Contact {
+ // …
+ source RecordSource @default(MANUAL)
+ emailThreads EmailThread[]
+ calendarEvents CalendarEvent[]
+ eventAttendance CalendarAttendee[]
+}
+
+model Activity {
+ // …
+ /// The projection link. Unique: one timeline entry per thread and per event.
+ emailThreadId String? @unique
+ emailThread EmailThread? @relation(fields: [emailThreadId], references: [id], onDelete: Cascade)
+ calendarEventId String? @unique
+ calendarEvent CalendarEvent? @relation(fields: [calendarEventId], references: [id], onDelete: Cascade)
+}
+
+model User {
+ // …
+ mailboxSyncs MailboxSync[]
+}
+```
+
+`Activity.createdById` stays required and is set to the user whose mailbox
+ingested the item — but the UI renders synced entries as "via Gmail" rather than
+as something that person wrote, because they didn't.
+
+Migration: `bun run --filter=@crm/db db:migrate`, named
+`add_google_sync`. Nothing backfills; existing rows default to `MANUAL`.
+
+### 4.4 Why project into `Activity` rather than union three tables
+
+The timeline is one indexed range scan over `activity(companyId, createdAt)`,
+with cursor paging and four filter counts. A union across three tables loses the
+index, makes the cursor a compound mess, and rewrites code that works. Instead
+sync writes one `Activity` per thread and per event and keeps it current:
+
+- New message in a known thread → update the projected activity's `occurredAt`
+ and snippet. One row per thread, not per message.
+- Event moved or cancelled → update the projected activity, or delete it when
+ the event is cancelled.
+
+The row is a summary. Expanding it fetches the messages or the attendees through
+a separate procedure (§8), so the timeline payload does not carry email bodies.
+
+---
+
+## 5. Matching: from a Google payload to a CRM record
+
+One resolver, `GoogleMatchService`, used by both syncs. Given the participant
+addresses of a thread or an event:
+
+1. **Drop our own people.** Any address on our own Workspace domain, and any
+ address belonging to a `User`. What is left is the external side.
+2. **Drop noise.** `domainFromEmail()` already returns `null` for free hosts.
+ Also drop `SuppressedDomain` hits and no-reply local parts
+ (`noreply`, `no-reply`, `notifications`, `donotreply`, `mailer-daemon`,
+ `bounce`, `via .*` senders).
+3. **Contact first, then company.** An exact `Contact.email` match wins —
+ `Contact.email` is already unique. Otherwise resolve the domain against
+ `Company.domain`, which is already unique and normalised.
+4. **If nothing matches**, hand off to §6. If §6 declines, **the item is not
+ stored at all.**
+5. **Stamp both ids.** Per the existing timeline convention, an activity carries
+ `companyId` even when it is really about a contact, so the company timeline
+ stays a single scan.
+
+Multiple external domains on one thread (a customer plus their lawyer) attach to
+the domain with the most participants, tie-broken by whichever already exists as
+a `Company`. It is a heuristic; it is also visibly wrong when it is wrong, and
+re-attaching is a single field edit.
+
+---
+
+## 6. Auto-creating companies and contacts
+
+The rule is **two-way engagement**, evaluated per source:
+
+| Source | Creates when | Rationale |
+| --- | --- | --- |
+| Calendar | An event with ≥1 external attendee, status not `cancelled`, and our user is organiser or has not declined | Somebody put time in a diary. That is as strong a signal as this CRM gets. |
+| Gmail | The connected user has **sent** ≥1 message in the thread | A reply proves a relationship. Inbound-only is a newsletter, a recruiter, or spam. |
+
+Then, in both cases, all of:
+
+- The external domain is non-free (`domainFromEmail()` returns non-null), not
+ our own, and not in `SuppressedDomain`.
+- The sender is not a no-reply address.
+- The thread has ≥1 message, or the event ≥1 confirmed external attendee.
+
+Creation itself reuses what exists: **`EnrichmentService.companyForEmail(email)`
+already does exactly this job** — normalise the domain, find or upsert the
+`Company`, and enqueue enrichment so the logo, industry and description fill in
+behind the scenes. Contacts are created alongside, with the display name from
+the `From` header or the attendee's `displayName` split into first/last, falling
+back to the local part.
+
+Everything created this way is stamped `source = EMAIL | CALENDAR`, which gives
+a filter on the companies and contacts tables, a bulk undo, and an honest answer
+to "where did all these come from".
+
+A per-user **"Auto-create records" toggle**, default **on for calendar, off for
+Gmail** on first connect. Meetings are unambiguous; the first week of mailbox
+auto-creation is where a bad rule shows up, and it should be a deliberate opt-in
+after the rep has seen what the sync matches.
+
+---
+
+## 7. Sync mechanics
+
+### 7.1 Shape
+
+The API is a bundled Vercel function (`apps/api/api/index.ts`) — no long-lived
+process, so no in-memory scheduler. A **Vercel Cron** hits an internal route
+every 5 minutes; the route iterates connected accounts and runs one incremental
+pass each.
+
+```ts
+// apps/api/vercel.ts (vercel.ts is the current recommendation over vercel.json)
+crons: [{ path: "/internal/sync/google", schedule: "*/5 * * * *" }],
+```
+
+The route sits outside tRPC — it is not a user action — and is guarded by a
+`CRON_SECRET` bearer check plus Vercel's cron header, alongside `/health` as one
+of the few non-tRPC surfaces `api.md` permits. It returns immediately after a
+bounded amount of work.
+
+> **Plan check:** minute-level cron needs a Pro plan; Hobby is once a day. Worth
+> confirming before Phase 2.
+
+### 7.2 Incremental sync
+
+Both APIs are cursor-based, and both invalidate cursors. Verified behaviour:
+
+- **Gmail** — `users.history.list(startHistoryId)` returns changes since a
+ `historyId`. History records are retained "typically at least one week"; an
+ out-of-range `startHistoryId` returns **HTTP 404**, and the client must fall
+ back to a full sync. We do not: forward-only means the cursor is re-pointed at
+ now and the gap is dropped, because refetching it would be importing old mail.
+- **Calendar** — `events.list` returns `nextSyncToken` on the final page. An
+ expired or ACL-invalidated token returns **HTTP 410 Gone**, requiring a full
+ resync. Incremental results always include deleted entries, so cancellations
+ arrive as events to remove — delete the projected activity when one does.
+
+### 7.3 No backfill — forward-only
+
+Nothing from before a mailbox was first seen is ever imported.
+
+- **Gmail** — the first pass calls `users.getProfile`, stores the current
+ `historyId` as the cursor, and imports **nothing**. Every later tick is
+ `history.list` from that point, so only mail that arrives after connection is
+ read. When the cursor falls out of Gmail's retention window (a 404, which
+ takes roughly a week of the sync not running), the gap is *not* fetched: the
+ cursor is re-pointed at now and the miss is logged.
+- **Calendar** — `timeMin` is `now`, never earlier. Events that *start* from now
+ onwards are imported, including ones booked before sync was switched on,
+ because a meeting in next Tuesday's diary is the entire point of the feature
+ and putting it on a timeline is not back-dating anything. Past meetings are
+ never read.
+
+What this deletes, which is most of the reason to do it: the chunk loop, the
+`backfilledTo` resume column, the `BACKFILLING` status, `GMAIL_BACKFILL_DAYS`,
+the cursor-invalidation path that re-entered a backfill, and the progress UI
+that had to explain all of it. A tick is now one shape — "what changed since the
+cursor?" — rather than two.
+
+The cost is honest and small: a company added today shows conversations from
+today. The history is in Gmail, where it always was.
+
+### 7.4 Idempotency and ordering
+
+Every write is an upsert on the natural key from §4.2, so re-running a window is
+free. Two reps' syncs racing on the same thread is settled by the unique index
+on `rfcMessageId`, exactly as the `Company.domain` index already settles two
+contacts arriving at a new company.
+
+### 7.5 Later: near-real-time
+
+Gmail `users.watch` + Cloud Pub/Sub push turns 5 minutes into seconds. It also
+adds a Pub/Sub topic, a push endpoint, and a `watch` registration that **expires
+every 7 days** and must be renewed on a schedule. Build it behind the same
+handler the cron calls, once the polling version has proven the matching rules.
+Not Phase 2 work.
+
+---
+
+## 8. API surface
+
+One module, `apps/api/src/google`, one router per `api.md`
+(`google.router.ts`, `@Router({ alias: "google" })`, `@UseMiddlewares(AuthMiddleware)`),
+thin over services.
+
+| Procedure | Kind | Notes |
+| --- | --- | --- |
+| `google.status` | query | Per-source: connected, `status`, `lastSyncedAt`, `lastError`, auto-create toggles. Drives the settings page and the poll. |
+| `google.purgeSyncedData` | mutation | Deletes every thread and event this mailbox contributed. Syncing continues forward from the current cursor. Not a disconnect — see §3.4. |
+| `google.revokeAccess` | mutation | The explicit hard revoke. Calls Google's revoke endpoint; the rep re-consents at next sign-in. Confirmed in the UI, never the default. |
+| `google.syncNow` | mutation | Enqueues a pass for the calling user. Rate-limited; it is a nicety, not the mechanism. |
+| `google.setAutoCreate` | mutation | `{ source, enabled }`. |
+| `google.suppressDomain` | mutation | "Not a customer" — adds to `SuppressedDomain` and optionally deletes what it matched. |
+| `email.thread` | query | `{ threadId }` → messages with bodies. Only called on expand. |
+| `calendar.event` | query | `{ eventId }` → attendees, conference link, description. |
+
+Connecting needs no procedure — the client calls `authClient.linkSocial()`
+directly, and `google.status` reads the result off `Account.scope`.
+
+Extensions to existing surfaces:
+
+- `activities.contracts.ts` — add `"email"` and `"meetings"` to `TimelineFilter`;
+ `activities.service.ts` — the matching arms in `filterClause()` and the extra
+ counts in `timelineCounts()`.
+- `ENTRY_SELECT` — include a *summary* of the linked thread/event
+ (`messageCount`, `lastMessageAt`, `startsAt`, attendee count). Not bodies.
+- `companies.service.ts` / `contacts.service.ts` — `nextMeetingAt` and
+ `lastEmailAt` on the detail payload, and `source` as a filterable column.
+
+Regenerate and **commit** `apps/api/src/generated/server.ts` with the router
+change, per `api.md`.
+
+---
+
+## 9. UI
+
+### 9.1 New primitives — in `/packages/ui`, per `design.md`
+
+Nothing bespoke in `apps/app`, no `className` overrides, no new radii:
+
+- `accordion.tsx` — via `bun run --filter=@crm/ui ui:add accordion`. The thread
+ disclosure. Not currently in the package.
+- `thread-message.tsx` — one message: sender, time, direction, body. Composes
+ `avatar`, `separator`.
+- `attendee-list.tsx` — stacked avatars with response status, over `avatar` and
+ `tooltip`.
+- `connection-card.tsx` — a connected-service row with status and actions, over
+ `card`, `status-indicator`, `button`. Reused by any future integration.
+
+### 9.2 Timeline
+
+`timeline-entry.tsx` gets two branches beside the existing `STAGE_CHANGE` one:
+
+- **EMAIL** — subject, `"3 messages · latest 2h ago"`, direction arrow, snippet.
+ Expands into an accordion of `ThreadMessage`s, fetching `email.thread` on
+ first open. Deep-links to Gmail via the stored `gmailMessageId`.
+- **MEETING** — title, time range, `AttendeeList`, conference link. An upcoming
+ meeting sorts by `startsAt` and reads "in 2 days"; `relativeTimeFromIso()`
+ already exists in `@crm/ui/lib/format`.
+
+`activity-icon.tsx` already maps both types. Filter tabs gain **Email** and
+**Meetings** (`timeline-search-params.ts`, nuqs, per the existing pattern).
+
+### 9.3 Settings
+
+A new `apps/app/app/(app)/settings/page.tsx` — there is no settings route yet.
+**One card, not one per source.** Both scopes come from a single grant at
+sign-in, so "Gmail connected but Calendar not" is not a state that exists, and
+rendering it as two identical cards invented a distinction the system does not
+have. The card carries connection health, when it last checked, and the two
+auto-create toggles — the only decision on the page with a consequence. The
+destructive actions from §3.4 sit underneath as quiet text links, because
+neither is anybody's daily business. No connect button: the gate guarantees the
+scopes before anyone reaches this page.
+
+### 9.4 Freshness
+
+Sync is a background write no client action caused, so per `api.md` it is
+**polled, not invalidated**. Mirror the enrichment pattern exactly — a
+`components/crm/sync-status.tsx` exporting `isSyncing()` and `SYNC_POLL_MS`, so
+the rule has one definition. Poll on the settings page *and* on the record sheet
+while a sync is running, remembering the lesson already recorded in
+`api.md`: the company sheet polled and the companies table did not, and a
+newly-added company stayed blank in the table until a reload.
+
+User-initiated actions still invalidate through `useCrmCache()`. Add a
+`cache.google()` that fans out to the activity keys plus companies and contacts
+lists — and note that `activities.timeline` must use `pathKey()`, not
+`queryKey()`, because it is read both as an infinite query and as a plain one.
+
+---
+
+## 10. Privacy, security, logging
+
+This is the part that makes the feature acceptable rather than merely working.
+
+- **Relevance filtering at ingest, not at read.** Non-matching mail is never
+ written. §5.
+- **Never log content.** `api.md` already bans headers, query strings and
+ bodies. Extend it in spirit: no subjects, no snippets, no addresses in log
+ lines. Log counts, ids, and domains. `logger.log({ message: "Gmail sync",
+ userId, threadsWritten, messagesWritten })` — one object, per the rules.
+- **Bodies never appear in list payloads.** `ENTRY_SELECT` carries a snippet;
+ bodies come only from `email.thread`, one thread at a time.
+- **Read scopes only**, and the reconnect path revokes and re-consents rather
+ than silently widening.
+- **Disconnect means it.** Deleting the account row stops sync; `{ purge: true }`
+ removes the messages, threads, events and their projected activities. Someone
+ will ask for this on their last day, and the answer should not be a migration.
+- **Every rep sees every synced thread** — that follows from "signed in is the
+ entire authorisation model" in `api.md`, and it is a real consequence worth
+ saying out loud before the first sync runs, not after. If that is not
+ acceptable, it is a row-level permissions decision that belongs in this plan
+ now rather than as a retrofit.
+
+---
+
+## 11. Failure modes to design for
+
+| Failure | Response |
+| --- | --- |
+| Refresh token revoked | `NEEDS_RECONNECT` on the sync row, banner in settings, stop trying. |
+| `historyId` too old (404) | Clear cursor, resume from now, log the gap. §7.3. |
+| `syncToken` gone (410) | Clear cursor, re-read from `now` forward. §7.2. |
+| Google rate limits (429/403) | Exponential backoff persisted on the sync row; skip that account this tick. |
+| Cron tick overruns | Chunked work with a wall-clock budget; the cursor makes the next tick resume, not restart. |
+| Two reps, one thread | Unique `rfcMessageId`. §4.2. |
+| Auto-create makes junk | `source` filter → bulk delete → `SuppressedDomain`. §6. |
+| Deploy mid-tick | The cursor only advances on a settled pass, so at worst a window is re-read — every write is an upsert. |
+
+---
+
+## 12. Phases
+
+| Phase | Scope | Done when |
+| --- | --- | --- |
+| **0 — Google Cloud** | Internal consent screen, both APIs enabled, redirect URIs for all envs | Consent screen shows the two scopes; no verification required. |
+| **1 — Connect** | Scopes on the provider, `accessType: "offline"`, `requireGoogleAccess()` gate, `/grant-access`, `GoogleTokenService`, `MailboxSync`, settings page, `google.status`. No sync. | A fresh sign-in grants both scopes and lands in the app; a user who unticks one is bounced to `/grant-access` and can re-consent; an account predating the requirement is caught by the same gate. |
+| **2 — Calendar** | Calendar sync, `CalendarEvent`/`CalendarAttendee`, matching, projection, `MEETING` timeline entry, Meetings filter | A meeting with an existing company appears on its timeline within 5 minutes, and a cancellation removes it. |
+| **3 — Gmail** | Gmail sync, `EmailThread`/`EmailMessage`, thread accordion, Email filter | A thread with an existing company appears collapsed and expands to readable messages. |
+| **4 — Auto-create** | §6 rules, `RecordSource`, `SuppressedDomain`, filters, bulk undo, toggles | A meeting with an unknown work domain creates an enriched company and a contact; a newsletter creates nothing. |
+| **5 — Real-time (optional)** | `users.watch` + Pub/Sub push, 7-day renewal | Threads land in seconds; the cron stays as the safety net. |
+
+Phases 1–3 are the user's stated ask. Phase 4 is the "would be cool", and it
+should not ship before Phase 3 has run on real mailboxes for a week — the
+matching rules need to be observed against real mail before they are allowed to
+write rows.
+
+---
+
+## 13. Environment
+
+| Variable | Where | Notes |
+| --- | --- | --- |
+| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | exists | Unchanged. Same client, same callback — the grant is just widened at sign-in. |
+| `CRON_SECRET` | new | Bearer guard on `/internal/sync/google`. The route fails closed without it, so a local checkout simply never runs the cron. |
+
+Nothing else. There is deliberately **no feature flag**: a switch earns its keep
+only when it gates something that can genuinely be absent, and sync has
+everything it needs the moment the app boots — the OAuth client is mandatory
+because Google is the only sign-in, and the scopes are a condition of having an
+account. A switch that can disable a mandatory feature, defaulting to off, is a
+switch that is only ever wrong. **Our own domains are derived** from the `User`
+table rather than configured, so they cannot go stale when the team adds a
+second one.
+
+All added to `EnvironmentVariables` in `apps/api/src/config/env.validation.ts`
+with `class-validator` decorators, and to `docs/environment.md`.
+
+---
+
+## 14. Testing
+
+- **Unit, no network.** Matching (§5) and the auto-create rules (§6) are pure
+ functions over parsed payloads — table-driven `bun test` with fixtures for the
+ awkward cases: two external domains, a no-reply sender, a free-host address, a
+ thread the rep never replied to, a declined meeting, a moved recurrence
+ instance.
+- **Idempotency.** Run a fixture window twice; assert row counts are identical.
+- **Cross-mailbox dedupe.** Ingest the same conversation as two different
+ mailboxes with different `threadId`s; assert one `EmailThread`, one projected
+ `Activity`.
+- **Cursor invalidation.** Stub 404 and 410 and assert the cursor is cleared and
+ the next pass resumes from now, rather than a crash or a silent stall.
+
+---
+
+## 15. Open questions
+
+1. **Whose mail syncs?** Every signed-in user who connects, or a defined sales
+ group? Affects volume and the §10 visibility question.
+2. **Visibility.** §10 — every rep seeing every synced thread follows from the
+ current auth model. Confirm that is intended.
+3. **Retention.** Do synced messages age out (say, 24 months), or live as long
+ as the company record?
+4. **Attachments.** Out of scope here. `crm-plan.md` §7 already picks Vercel Blob
+ for CRM attachments; email attachments would reuse it, but v1 stores names
+ and sizes only, not bytes.
+5. **Cron granularity.** Confirm the Vercel plan supports `*/5`.
+6. **Does hard revocation need to be per-feature?** §3.4 — with one OAuth client
+ there is one Google grant, so revoking mailbox access also revokes sign-in.
+ Under the mandatory-sync policy that is arguably the correct behaviour, since
+ an account that will not grant the scopes cannot use the CRM anyway. Revisit
+ only if someone needs "keep my login, stop reading my mail", which the policy
+ currently says is not a state we support.
diff --git a/docs/plan/people-enrichment-agent.md b/docs/plan/people-enrichment-agent.md
new file mode 100644
index 00000000..c31a6244
--- /dev/null
+++ b/docs/plan/people-enrichment-agent.md
@@ -0,0 +1,451 @@
+# Plan — People enrichment agent (eve + LinkedIn)
+
+An [eve](https://eve.dev/docs) agent that works out who the people in the CRM
+actually are, using real profile data rather than inference.
+
+Read it with [`AGENTS.md`](../../AGENTS.md), [`api.md`](../api.md),
+[`design.md`](../design.md) and
+[`gmail-calendar-plan.md`](./gmail-calendar-plan.md), whose sync is what puts
+these contacts in the CRM in the first place.
+
+---
+
+## 0. Phase 0 is done — what the API actually does
+
+Run against the real key on 2026-07-31, using addresses from our own CRM. This
+section exists because it **changed the architecture**, and because half of it
+contradicts the vendor's own marketing page.
+
+### People search is broken. Do not build on it.
+
+`GET /api/v1/search/people?keywords=...` returns `HTTP 200` with a well-formed
+payload of **entirely unrelated people**. `keywords=bigham hubspot` returned a
+list of Seattle-area engineers; `keywords=Abbie Bigham` returned Italian
+executives — Lavazza's CEO, an HR lead at Reply. Different random set each time.
+The parameter appears to be ignored.
+
+This matters more than a broken endpoint usually would: search was the entry
+point of the original design. Email → search → candidates → match was the whole
+identity-resolution flow, and it does not exist.
+
+### What does work, and works well
+
+| Endpoint | Status | Notes |
+| --- | --- | --- |
+| `GET /api/v1/profile/overview?username=<slug>` | **Excellent** | Full name, headline, current positions with company URNs and logos, follower count, connection count, join date. |
+| `GET /api/v1/companies/company/info?name=<slug>` | **Excellent** | Id, universal name, LinkedIn URL, tagline, full description. Takes `name`, *not* `username`. |
+| `GET /api/v1/profile/contact-info?username=<slug>` | Works | — |
+| `GET /api/v1/profile/skills` | Exists, different params | Rejects `username`; wants a URN or profile id. |
+| `profile/experience`, `profile/posts`, `companies/company/employees` | **Do not exist** | 404 under the documented names, despite being on the marketing page. The real names need finding before anything depends on them. |
+
+### The architecture this forces — and it is better
+
+LinkDAPI is an **enricher, not a finder**. Given a slug it is superb; given a
+name it is useless. So the resolver stage moves to a real search engine:
+
+```
+email + company → Context.dev web search (site:linkedin.com/in) → slug
+slug → LinkDAPI profile/overview → deep structured profile
+```
+
+Proven end to end on a real CRM contact:
+
+```
+ → site:linkedin.com/in ymadar "Valley"
+ → yael-madar
+ → Yael Madar — VP, Fund Finance & Venture Lending — Valley Bank
+```
+
+`y` + `madar`. That is the "Ymadar" row from the contacts list, resolved to a
+real person with a real title at the right employer.
+
+It also means the two vendors are used for what each is actually good at.
+Context.dev is a search engine and cannot read LinkedIn (LinkedIn blocks
+scrapers); LinkDAPI can read LinkedIn and cannot search. Neither alone solves
+this.
+
+### Hit rate is partial, and that is the honest headline
+
+`[email protected]` resolved to **nothing** — no candidate slug at all. An
+unusual local part at an 8,000-person company is the hard case, and it is the
+one that prompted this work. Expect a meaningful miss rate on exactly the
+contacts that look worst in the UI.
+
+Two consequences:
+
+- The fallback matters. When no slug resolves, the existing Context.dev
+ extract path still runs and may find a team page.
+- **A miss must stay a miss.** With search returning plausible strangers, the
+ temptation to accept a near-match is exactly how Antonio Baravalle ends up
+ filed as Abbie Bigham. §5's confidence bands are not ceremony.
+
+### A bug this spike caught in already-shipped code
+
+Context.dev's `web.search` rejects `numResults < 10`. `ContextDevClient.search`
+defaulted to 5, so **every call would have failed validation** — the contact
+enrichment shipped last turn could never have worked. Fixed; worth recording as
+the reason to spike against a real key rather than a type definition.
+
+---
+
+## 1. What this is actually for
+
+The prompt for this was a contacts list reading `Abigham`, `Ymadar`, `Chris` —
+names derived from an email address because Google Calendar returned no
+`displayName`. Fixing those is the *entry* case, and on its own it would not
+justify an agent.
+
+The reason to do this properly is what a profile carries beyond a name:
+
+| Signal | Why a CRM wants it |
+| --- | --- |
+| Full name, headline, title | The contacts list stops looking broken. |
+| Work history and tenure | "Started 3 months ago" is a different conversation from "eight years in seat". |
+| **Job changes** | A champion moving to a new company is the single highest-intent event in B2B sales, and nobody sees it today. |
+| Seniority and function | Who actually signs, versus who you have been emailing. |
+| Company headcount and growth | Qualification, without asking. |
+| Mutual connections | A warm path in. |
+
+The agent does **both**: it fills the fields *and* it produces the output. The
+fields are the substrate — you cannot write "you are meeting the VP who joined
+four months ago" without knowing the title and the start date — and the output
+is the reason anyone opens the CRM. Neither half is optional, and shipping only
+the fields is what makes enrichment feel like admin.
+
+Job-change detection is the prize. It is also impossible without a people data
+source, which is why the existing Context.dev path cannot grow into it alone.
+
+### What exists today, and what happens to it
+
+`ContactEnrichmentService` (`apps/api/src/enrichment/contact-enrichment.service.ts`)
+already does a sourced web lookup: search, read a page, write only what the page
+states. It is deliberately timid — it refuses to guess, so it returns nothing
+for most people.
+
+It is **not** deleted by this plan. It becomes the fallback the agent reaches
+for when LinkedIn has no match, which is common for junior people, non-US
+markets, and anyone who does not keep a profile. §5.
+
+---
+
+## 2. The decisions that carry the design
+
+1. **Curated tools, not a raw OpenAPI connection.** Not to save money — one won
+ deal at $10–15k ARR funds more enrichment than this will ever run. Because
+ the surface is not trustworthy: several advertised endpoints 404 and the
+ search endpoint returns confident nonsense (§0). Tools pin the agent to what
+ is verified to work. §4.
+2. **The agent proposes; the CRM decides.** Writes go through one tool that
+ stamps provenance, and a low-confidence identity match is approval-gated
+ rather than merged. Getting a person wrong is worse than not knowing them. §6.
+3. **Identity matching is the hard part, not data fetching.** `[email protected]`
+ → which of the four Bighams at a 8,000-person company? This gets a skill, a
+ confidence rubric and evals. §5.
+4. **A separate Vercel app, sharing `@crm/db`.** eve is its own runtime with its
+ own build; it does not embed in NestJS. It reads and writes the CRM through
+ the workspace database package, not through a new internal HTTP API. §3.
+5. **Rate limits are a correctness concern, not a billing one.** A 429 mid-run
+ is a half-enriched contact. The token bucket exists so the agent never
+ discovers the tier cap. §7.
+6. **Provenance on every field.** Which endpoint, which profile URL, when,
+ how confident. Without it nobody can tell an enriched field from a typed one,
+ and nobody will trust either. §6.
+
+### Choice table
+
+| Decision | Choice | Why |
+| --- | --- | --- |
+| Framework | eve, `apps/agent`, own Vercel project | Durable sessions, approval gating, schedules and evals are all things we would otherwise hand-roll. |
+| Model | `anthropic/claude-sonnet-5` via AI Gateway | The default. Routes over project OIDC, so no provider key to manage. Matching is not a frontier-model problem; revisit if eval scores say otherwise. |
+| LinkedIn access | LinkDAPI over RapidAPI, **profile + company endpoints only** | Its people *search* is broken — §0. Profile-by-slug and company-by-name are excellent. |
+| Finding the person | Context.dev web search resolves the LinkedIn slug | §0. The one thing LinkDAPI cannot do, and the thing a real search engine is good at. |
+| Tool surface | Curated tools, not an OpenAPI connection | Not cost — *predictability*. Half the advertised endpoints do not exist under the documented names (§0), so the surface has to be pinned to what is verified. |
+| CRM access | `@crm/db` directly | Already a workspace package. A second internal API would be plumbing with no reader. |
+| Trigger | eve schedule (Vercel Cron) over a bounded queue | Same shape as the Google sync — cursor in Postgres, work bounded per tick. |
+| Write path | One `update_contact` tool, provenance stamped | §6. |
+| Low confidence | eve `approval: always()` on merges below the bar | §6. Cheap to add now, impossible to retrofit trust later. |
+| Fallback | Existing Context.dev search | Covers the long tail LinkedIn misses. |
+| Retention | Raw payload in `ContactEnrichment`, mirroring `CompanyEnrichment` | Re-deriving a field later costs nothing — the pattern already paid off once, for `iconTone`. |
+| Coverage | Every contact with a work domain, re-checked on a cadence | Billing is not a constraint: one won deal at $10–15k ARR pays for far more enrichment than this will ever run. |
+
+### Judgment calls worth your veto
+
+- **Curated tools rather than the full API.** You lose the agent's ability to
+ improvise across endpoints we did not anticipate. You gain a predictable bill.
+ If a use case turns up that the four tools cannot serve, add a fifth — that is
+ cheaper than discovering an agent spent 4,000 credits exploring.
+- **Job-change detection is Phase 4, not Phase 1.** It needs a baseline to
+ diff against, so it cannot exist until enrichment has been running a while.
+ Worth saying out loud because it is the most valuable part and it is last.
+- **The agent never emails anyone.** It reads, matches and writes CRM fields.
+ Outbound stays a human action. eve makes it easy to give an agent a channel
+ and a send tool, and that is a different product decision with a different
+ risk profile.
+- **Contacts only, initially.** LinkDAPI's company endpoints are tempting, but
+ Context.dev already fills company firmographics and two sources writing the
+ same columns is a merge conflict nobody owns. §8.
+
+---
+
+## 3. Where it lives
+
+eve is a filesystem-first framework: an agent is a directory, and the slot a
+file lands in determines how it loads. It builds and runs as its own app, so it
+becomes a third workspace app beside `api` and `app`.
+
+```text
+apps/agent/
+├── package.json # name = "agent"; the root agent takes its name from here
+├── agent/
+│ ├── agent.ts # model + runtime config
+│ ├── instructions.md # what the agent is for and what it must not do
+│ ├── lib/ # shared helpers — import-only, never reaches the sandbox
+│ │ ├── linkdapi.ts # typed client: auth, retry, rate limit, credit accounting
+│ │ └── crm.ts # @crm/db queries the tools call
+│ ├── tools/ # one file per tool; filename IS the model-facing name
+│ │ ├── find_person.ts
+│ │ ├── get_profile.ts
+│ │ ├── find_colleagues.ts
+│ │ └── update_contact.ts
+│ ├── skills/
+│ │ └── identity-matching.md
+│ └── schedules/
+│ └── enrich.ts # becomes a Vercel Cron Job on deploy
+└── evals/ # sibling of agent/, not inside it
+```
+
+Naming is path-derived — `agent/tools/find_person.ts` is the tool `find_person`,
+and you never write a `name` field.
+
+**Deployment.** `eve link` creates/links a Vercel project and pulls its env.
+Schedules become Vercel Cron Jobs, evaluated in UTC. A string model id routes
+through the AI Gateway authenticated by project OIDC, so there is no Anthropic
+key to rotate. Note that `eve dev` never fires schedules on their cadence —
+there is a dispatch route for triggering one while iterating.
+
+**Monorepo wiring.** `apps/agent` joins the bun workspace and gets a
+`turbo.json` declaring `passThroughEnv` for `DATABASE_URL` and the RapidAPI key,
+matching how `apps/api` does it. `check-types` and `lint` join the root
+pipeline; `build` is `eve build`.
+
+---
+
+## 4. The tools
+
+Four, deliberately. Each one runs in the app runtime with access to
+`process.env` and `lib/`, and each is a place to put a rate limiter rather than
+hope the model paces itself.
+
+| Tool | Wraps | Notes |
+| --- | --- | --- |
+| `resolve_profile` | Context.dev `web.search`, `site:linkedin.com/in` | Turns an email + company into **candidate slugs**. Never returns a match — returns candidates for §5 to judge. This replaces the LinkDAPI search that does not work. |
+| `get_profile` | LinkDAPI `profile/overview` (+ `contact-info`) | One slug, in full. The deep data nothing else can reach. |
+| `get_company` | LinkDAPI `companies/company/info?name=` | Tagline, description, LinkedIn URL — company context for a brief. |
+| `research_web` | Context.dev `web.extract` | The fallback when no slug resolves, and the source of non-LinkedIn context (funding, launches) for briefs. |
+| `update_contact` | `@crm/db` | The only write. §6. |
+
+Two things go in `lib/linkdapi.ts` rather than in each tool:
+
+- **A token bucket sized to the tier.** Testing is 7 requests/minute, Hobby 30,
+ Developer 70. Not a cost control — a 429 in the middle of a run leaves a
+ half-enriched contact, and the agent must not be the thing that discovers the
+ cap.
+- **Call accounting.** Endpoint plus the contact it was for. Not for the bill,
+ for the debugging: when a profile comes back wrong you want to know exactly
+ what was asked.
+
+A note from eve's own docs that applies here: *a step interrupted mid-execution
+re-runs*, so anything non-idempotent must be made idempotent or gated. Our
+writes are upserts keyed on contact id, so a replay is free; the *credit spend*
+is not, which is another reason the counter is on the client and not the tool.
+
+---
+
+## 5. Identity matching
+
+The actual problem. `[email protected]` is one address at a company with
+thousands of employees, and picking the wrong Bigham writes a real person's
+career history onto the wrong CRM record.
+
+This gets a **skill** — an on-demand procedure the agent loads when it needs it —
+rather than being buried in the system prompt:
+
+`agent/skills/identity-matching.md` sets out the evidence hierarchy:
+
+1. **Exact email on the profile** — decisive. LinkDAPI exposes contact info on
+ some profiles; when the address matches, the match is certain.
+2. **Local-part decomposition against a real name.** `abigham` is consistent
+ with `a` + `bigham` and with `abi` + `gham`. Checked *against candidates*,
+ never used to generate a name — the direction matters, and it is the whole
+ difference between this and guessing.
+3. **Company match**, current employer equals the contact's company.
+4. **Corroboration** — the meeting we already synced, the thread they replied
+ on, the title they signed off with in an email footer.
+
+And the confidence bands the write path keys on:
+
+| Confidence | Evidence | Behaviour |
+| --- | --- | --- |
+| `high` | Email match, or unique local-part decomposition at the right company | Merged automatically. |
+| `medium` | Consistent decomposition but more than one plausible candidate | Written as a **suggestion**; a rep accepts or rejects. |
+| `low` | Company match only | Discarded. Not stored, not shown. |
+
+When LinkDAPI returns nothing, the agent falls back to the existing Context.dev
+search path, which is already sourced and already refuses to guess.
+
+**Evals live and die on this.** `evals/` gets a fixture set of real addresses
+with known answers — including the ones that *should* resolve to nothing — and
+the metric is precision first: a wrong merge costs more than a missing one.
+
+---
+
+## 6. Writing back, and provenance
+
+One tool, `update_contact`, and it never writes a bare field:
+
+```prisma
+model ContactEnrichment {
+ contactId String @id
+ contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ source String // "linkdapi" | "context.dev"
+ sourceUrl String? // the profile the claim came from
+ confidence String // high | medium | low
+ raw Json // the payload, so re-deriving costs nothing
+ fetchedAt DateTime @default(now())
+
+ @@map("contactEnrichment")
+}
+```
+
+Mirrors `CompanyEnrichment` deliberately: keeping the raw payload has already
+paid for itself once — `iconTone` and `iconDarkUrl` were backfilled for every
+company from stored payloads without spending a credit.
+
+`Contact` gains `enrichmentStatus`, `enrichedAt` and `enrichmentError` matching
+`Company`, so the UI reuses `isEnriching()` / the existing poll rather than
+inventing a second freshness mechanism (`api.md`: background writes the browser
+cannot see are polled, not invalidated).
+
+**Approval.** eve's `approval: always()` pauses a tool call durably until a
+person signs off. `update_contact` takes a policy rather than a flag: automatic
+at `high`, approval-gated at `medium`. eve's own responsible-use guidance is
+that agents run permissively unless you configure otherwise and that model
+behaviour alone should not be relied on to prevent sensitive writes — a
+confidence rubric in a prompt is model behaviour; the approval policy is not.
+
+**Never overwrite a human.** Same rule the rest of the codebase already
+follows: `brandToUpdate` fills only empty fields, and `isDerivedName()` is
+already the test for "this name is a placeholder nobody has improved on".
+
+---
+
+## 7. Scheduling and coverage
+
+`agent/schedules/enrich.ts` — a `defineSchedule` with a `run` handler rather
+than a markdown prompt, because the batch has to be selected in code:
+
+```ts
+export default defineSchedule({
+ cron: "*/10 * * * *",
+ async run({ receive }) { /* claim a bounded batch, hand each to the agent */ },
+});
+```
+
+Sizing is set by the rate limit, not the budget:
+
+- **Batch size** is the per-minute cap times the tick, with headroom. At
+ Developer (70/min) and a 10-minute tick that is hundreds of contacts, which is
+ more than the whole database.
+- **Every contact with a work domain**, not just the ones with ugly names and
+ not just the ones on open deals. A correct title on a contact nobody is
+ actively selling to is what makes the *next* deal's brief good.
+- **Re-check on a cadence, not once.** A profile read once is a fact that decays;
+ a profile read every 30 days is a job-change feed (Phase 4). This is the
+ single biggest behavioural difference the "billing is irrelevant" call buys,
+ and it is worth taking deliberately rather than by omission.
+
+Pick the tier from the measured request rate, then stop thinking about it.
+
+---
+
+## 8. What this does *not* touch
+
+- **Company firmographics.** Context.dev owns those columns. LinkDAPI's company
+ endpoints are for *people* context — headcount, who works there — and land in
+ new fields or not at all.
+- **The Google sync's matching.** `GoogleMatchService` decides which company a
+ thread belongs to. That is a different question from who a person is, and
+ merging them would couple a cheap local decision to a paid network call.
+- **Outbound anything.**
+
+---
+
+## 9. The part to decide before building
+
+LinkDAPI is an **unofficial** LinkedIn API. Using it is a business decision, not
+a technical one, and it belongs to you rather than to this plan — but it should
+be made deliberately rather than discovered:
+
+- **LinkedIn's terms prohibit automated collection**, and they enforce against
+ it. The exposure is to the data provider and to LinkedIn, not to a court's
+ view of the CFAA, which `hiQ v. LinkedIn` largely settled in favour of public
+ data. Practically: this is what Apollo, Clearbit, ZoomInfo and most of the
+ sales stack do, and it is priced accordingly.
+- **This is personal data under UK/EU GDPR** even though it is professional and
+ public. What that actually requires of an internal B2B CRM: a lawful basis
+ (legitimate interest is the usual one, and wants a balancing test on file), a
+ retention period, and the ability to answer an access or erasure request.
+ `ContactEnrichment` with `sourceUrl` and `fetchedAt` is most of the answer —
+ it makes "where did this come from and when" a query rather than an
+ investigation.
+- **Keep it to business context.** Name, title, employer, tenure, public
+ profile. Nothing about a person outside their work, and none of the special
+ categories, regardless of what an endpoint returns.
+- **Single-provider risk.** An unofficial API breaks when LinkedIn changes.
+ `lib/linkdapi.ts` being the only file that knows the vendor is what makes
+ swapping it a day rather than a rewrite.
+
+None of this blocks the build. It does mean §6's provenance is not a nicety —
+it is the thing that makes the rest defensible.
+
+---
+
+## 10. Phases
+
+| Phase | Scope | Done when |
+| --- | --- | --- |
+| **0 — Spike** | ~~Prove the API resolves real CRM addresses~~ | **Done — §0.** Search is unusable; profile and company are excellent; the hybrid resolver works end to end on a real contact; hit rate is partial. |
+| **1 — Skeleton** | `apps/agent`, `eve link`, `update_contact` writing to `@crm/db`, schedule claiming a batch, no LinkedIn | A contact's title changes because the agent changed it, on a cron, in a deployed environment. The loop is proven before the vendor is in it. |
+| **2 — Enrichment** | Five tools, `identity-matching` skill, confidence bands, `ContactEnrichment` | `Ymadar` becomes Yael Madar, VP Fund Finance at Valley Bank, with a `sourceUrl` against it — and an ambiguous address becomes a suggestion rather than a wrong answer. |
+| **3 — Trust** | Approval on `medium`, evals with a labelled fixture set, provenance in the contact sheet | Precision measured, not asserted. A rep can see where a field came from. |
+| **4 — Meeting prep briefs** | On a calendar event with external attendees, research everyone and write a brief to the timeline before the call | Opening a company the morning of a call shows who is attending, what they do, how long they have been there, what the company just announced, and where the deal stands. **This is the feature people will describe to other people.** It is only possible because the Calendar sync already knows the meeting is coming. |
+| **5 — Job changes** | Re-read on a 30-day cadence, diff against the stored payload, activity + task on a move | A champion changing employer creates an activity on their old company's timeline and a task for their owner. The highest-intent signal in B2B, and nobody else in the stack sees it. |
+
+Phase 0 already earned its keep: it deleted the original resolver design, found
+a shipped bug, and replaced a marketing-page assumption with a measured one.
+
+The ordering after that is deliberate. Phases 1–3 make the data trustworthy;
+4 and 5 are what a rep would actually miss if you took it away. Resist doing 4
+first — a brief built on unverified identities is confidently wrong in front of
+a customer, which is the one failure mode that costs a deal rather than a
+click.
+
+---
+
+## 11. Open questions
+
+1. **Whose credits?** One shared app key (`principalType: "app"`, which is
+ eve's default when `getToken` is the only auth), or per-rep? Shared is
+ simpler and almost certainly right for an internal tool.
+2. **Does a `medium` suggestion surface in the UI, or a queue?** The Gmail plan
+ argued against approval queues because they rot. A suggestion inline on the
+ contact — "LinkedIn thinks this is Abbie Bigham · accept" — probably beats a
+ separate inbox, but it is more UI work.
+3. **Retention.** How long does `ContactEnrichment.raw` live? It is the thing
+ that makes re-derivation free and the thing an erasure request is about.
+4. **Do we enrich every contact, or only ones on open deals?** Every contact is
+ simpler; deal-scoped is far cheaper and probably where the value is.
+5. **Is `find_colleagues` allowed to create contacts?** Listing a company's
+ employees is a lead-generation capability, not an enrichment one. It should
+ not create records in v1, and that line is worth holding deliberately.
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 55857f93..536e3da2 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -5,7 +5,8 @@
"type": "module",
"exports": {
".": "./src/index.ts",
- "./client": "./src/client.ts"
+ "./client": "./src/client.ts",
+ "./scopes": "./src/scopes.ts"
},
"scripts": {
"auth:generate": "better-auth generate --config src/auth.ts --output ../db/prisma/schema.prisma --y",
diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.ts
index d8058298..37b36fcd 100644
--- a/packages/auth/src/auth.ts
+++ b/packages/auth/src/auth.ts
@@ -2,11 +2,37 @@ import { db } from "@crm/db";
import { type BetterAuthOptions, betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { env } from "./env";
+import { SYNC_SCOPES } from "./scopes";
const socialProviders: NonNullable<BetterAuthOptions["socialProviders"]> = {};
if (env.google) {
- socialProviders.google = env.google;
+ socialProviders.google = {
+ ...env.google,
+
+ // Gmail and Calendar are asked for at sign-in, not behind a Connect
+ // button. This is an internal, single-tenant tool: reading the mailbox is
+ // what the CRM is for, so it is a condition of having an account rather
+ // than an optional extra.
+ //
+ // Requesting them here is necessary but not sufficient — Google's granular
+ // consent lets someone untick a scope and still finish signing in, so the
+ // app also gates on what was actually granted. See
+ // `requireGoogleAccess()` in the Next.js app.
+ scope: [...SYNC_SCOPES],
+
+ // Offline access, so Google issues a refresh token. Without it the
+ // connection dies silently one hour after sign-in, with nothing to
+ // refresh from.
+ //
+ // Deliberately not `prompt: "consent"`: it would show the consent screen
+ // on every single sign-in. It is not needed, because a first sign-in — and
+ // any sign-in that asks for a scope the user has not yet granted — makes
+ // Google prompt anyway, and it is that prompt which mints the refresh
+ // token. The missing-refresh-token case is detected and repaired rather
+ // than pre-empted.
+ accessType: "offline",
+ };
}
export const auth = betterAuth({
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index fa51be9c..ea661bcb 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -1 +1,10 @@
export { type Auth, auth, type Session, type SessionUser } from "./auth";
+export {
+ CALENDAR_SCOPE,
+ GMAIL_SCOPE,
+ hasSyncScopes,
+ IDENTITY_SCOPES,
+ parseScopes,
+ REQUIRED_SCOPES,
+ SYNC_SCOPES,
+} from "./scopes";
diff --git a/packages/auth/src/scopes.ts b/packages/auth/src/scopes.ts
new file mode 100644
index 00000000..a678eec3
--- /dev/null
+++ b/packages/auth/src/scopes.ts
@@ -0,0 +1,53 @@
+/**
+ * The Google scopes this CRM runs on.
+ *
+ * Defined here rather than in the API because the OAuth request is made from
+ * this package — and because the API, the sign-in page and the settings page all
+ * have to agree on the exact strings. Two copies of a scope list drift, and the
+ * failure mode is silent: the grant looks fine and `isConnected()` says no.
+ */
+
+/** Identity. Always requested; Better Auth's Google provider adds these itself. */
+export const IDENTITY_SCOPES = ["openid", "email", "profile"] as const;
+
+export const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
+export const CALENDAR_SCOPE =
+ "https://www.googleapis.com/auth/calendar.readonly";
+
+/**
+ * Read-only Gmail and Calendar.
+ *
+ * Requested at sign-in, not behind a Connect button: this is an internal,
+ * single-tenant tool where seeing the conversation on a record is the point, so
+ * a rep with a CRM account and no mailbox connected is a half-configured
+ * account nobody notices is broken.
+ *
+ * Read-only is not negotiable in v1 — nothing writes back to Google.
+ */
+export const SYNC_SCOPES = [GMAIL_SCOPE, CALENDAR_SCOPE] as const;
+
+/** Everything a fully provisioned account has granted. */
+export const REQUIRED_SCOPES = [...IDENTITY_SCOPES, ...SYNC_SCOPES] as const;
+
+/**
+ * Whether a grant covers the sync scopes.
+ *
+ * Takes the raw comma-separated `Account.scope` string, because that is the
+ * only place the truth lives — Google's granular consent lets someone untick a
+ * scope and still complete sign-in, so "they signed in" does not imply "they
+ * granted it".
+ */
+export function hasSyncScopes(scope: string | null | undefined): boolean {
+ const granted = parseScopes(scope);
+ return SYNC_SCOPES.every((needed) => granted.has(needed));
+}
+
+/** `Account.scope` as a set. Google returns it comma- or space-separated. */
+export function parseScopes(scope: string | null | undefined): Set<string> {
+ return new Set(
+ (scope ?? "")
+ .split(/[,\s]+/)
+ .map((entry) => entry.trim())
+ .filter(Boolean),
+ );
+}
diff --git a/packages/db/prisma/migrations/20260731200000_add_google_sync/migration.sql b/packages/db/prisma/migrations/20260731200000_add_google_sync/migration.sql
new file mode 100644
index 00000000..0d8cbc10
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731200000_add_google_sync/migration.sql
@@ -0,0 +1,192 @@
+-- CreateEnum
+CREATE TYPE "RecordSource" AS ENUM ('MANUAL', 'IMPORT', 'EMAIL', 'CALENDAR');
+
+-- CreateEnum
+CREATE TYPE "GoogleSyncStatus" AS ENUM ('IDLE', 'BACKFILLING', 'RUNNING', 'NEEDS_RECONNECT', 'FAILED');
+
+-- CreateEnum
+CREATE TYPE "EmailDirection" AS ENUM ('INBOUND', 'OUTBOUND');
+
+-- AlterTable
+ALTER TABLE "activity" ADD COLUMN "calendarEventId" TEXT,
+ADD COLUMN "emailThreadId" TEXT;
+
+-- AlterTable
+ALTER TABLE "company" ADD COLUMN "source" "RecordSource" NOT NULL DEFAULT 'MANUAL';
+
+-- AlterTable
+ALTER TABLE "contact" ADD COLUMN "source" "RecordSource" NOT NULL DEFAULT 'MANUAL';
+
+-- CreateTable
+CREATE TABLE "mailboxSync" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "source" TEXT NOT NULL,
+ "status" "GoogleSyncStatus" NOT NULL DEFAULT 'IDLE',
+ "cursor" TEXT,
+ "backfilledTo" TIMESTAMP(3),
+ "lastSyncedAt" TIMESTAMP(3),
+ "lastError" TEXT,
+ "retryAfter" TIMESTAMP(3),
+ "autoCreate" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "mailboxSync_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "emailThread" (
+ "id" TEXT NOT NULL,
+ "rootMessageId" TEXT NOT NULL,
+ "subject" TEXT,
+ "companyId" TEXT,
+ "contactId" TEXT,
+ "firstMessageAt" TIMESTAMP(3) NOT NULL,
+ "lastMessageAt" TIMESTAMP(3) NOT NULL,
+ "messageCount" INTEGER NOT NULL DEFAULT 0,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "emailThread_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "emailMessage" (
+ "id" TEXT NOT NULL,
+ "threadId" TEXT NOT NULL,
+ "rfcMessageId" TEXT NOT NULL,
+ "syncedByUserId" TEXT,
+ "gmailMessageId" TEXT,
+ "direction" "EmailDirection" NOT NULL,
+ "fromEmail" TEXT NOT NULL,
+ "fromName" TEXT,
+ "recipients" JSONB NOT NULL,
+ "subject" TEXT,
+ "snippet" TEXT,
+ "body" TEXT,
+ "sentAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "emailMessage_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "calendarEvent" (
+ "id" TEXT NOT NULL,
+ "iCalUid" TEXT NOT NULL,
+ "originalStartTime" TIMESTAMP(3) NOT NULL,
+ "recurringEventId" TEXT,
+ "title" TEXT,
+ "description" TEXT,
+ "location" TEXT,
+ "conferenceUrl" TEXT,
+ "startsAt" TIMESTAMP(3) NOT NULL,
+ "endsAt" TIMESTAMP(3) NOT NULL,
+ "isAllDay" BOOLEAN NOT NULL DEFAULT false,
+ "status" TEXT NOT NULL,
+ "organizerEmail" TEXT,
+ "companyId" TEXT,
+ "contactId" TEXT,
+ "syncedByUserId" TEXT,
+ "googleEventId" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "calendarEvent_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "calendarAttendee" (
+ "id" TEXT NOT NULL,
+ "eventId" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "name" TEXT,
+ "responseStatus" TEXT,
+ "isOrganizer" BOOLEAN NOT NULL DEFAULT false,
+ "contactId" TEXT,
+
+ CONSTRAINT "calendarAttendee_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "suppressedDomain" (
+ "domain" TEXT NOT NULL,
+ "reason" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "suppressedDomain_pkey" PRIMARY KEY ("domain")
+);
+
+-- CreateIndex
+CREATE INDEX "mailboxSync_status_idx" ON "mailboxSync"("status");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "mailboxSync_userId_source_key" ON "mailboxSync"("userId", "source");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "emailThread_rootMessageId_key" ON "emailThread"("rootMessageId");
+
+-- CreateIndex
+CREATE INDEX "emailThread_companyId_lastMessageAt_idx" ON "emailThread"("companyId", "lastMessageAt");
+
+-- CreateIndex
+CREATE INDEX "emailThread_contactId_lastMessageAt_idx" ON "emailThread"("contactId", "lastMessageAt");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "emailMessage_rfcMessageId_key" ON "emailMessage"("rfcMessageId");
+
+-- CreateIndex
+CREATE INDEX "emailMessage_threadId_sentAt_idx" ON "emailMessage"("threadId", "sentAt");
+
+-- CreateIndex
+CREATE INDEX "calendarEvent_companyId_startsAt_idx" ON "calendarEvent"("companyId", "startsAt");
+
+-- CreateIndex
+CREATE INDEX "calendarEvent_contactId_startsAt_idx" ON "calendarEvent"("contactId", "startsAt");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "calendarEvent_iCalUid_originalStartTime_key" ON "calendarEvent"("iCalUid", "originalStartTime");
+
+-- CreateIndex
+CREATE INDEX "calendarAttendee_contactId_idx" ON "calendarAttendee"("contactId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "calendarAttendee_eventId_email_key" ON "calendarAttendee"("eventId", "email");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "activity_emailThreadId_key" ON "activity"("emailThreadId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "activity_calendarEventId_key" ON "activity"("calendarEventId");
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_emailThreadId_fkey" FOREIGN KEY ("emailThreadId") REFERENCES "emailThread"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "activity" ADD CONSTRAINT "activity_calendarEventId_fkey" FOREIGN KEY ("calendarEventId") REFERENCES "calendarEvent"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "mailboxSync" ADD CONSTRAINT "mailboxSync_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "emailThread" ADD CONSTRAINT "emailThread_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "emailThread" ADD CONSTRAINT "emailThread_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "emailMessage" ADD CONSTRAINT "emailMessage_threadId_fkey" FOREIGN KEY ("threadId") REFERENCES "emailThread"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "calendarEvent" ADD CONSTRAINT "calendarEvent_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "calendarEvent" ADD CONSTRAINT "calendarEvent_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "calendarAttendee" ADD CONSTRAINT "calendarAttendee_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "calendarEvent"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "calendarAttendee" ADD CONSTRAINT "calendarAttendee_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
diff --git a/packages/db/prisma/migrations/20260731210000_forward_only_sync/migration.sql b/packages/db/prisma/migrations/20260731210000_forward_only_sync/migration.sql
new file mode 100644
index 00000000..7d3728b8
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731210000_forward_only_sync/migration.sql
@@ -0,0 +1,19 @@
+-- Sync is forward-only now, so there is no backfill for a row to be in the
+-- middle of. Anything mid-import becomes IDLE and carries on from wherever its
+-- cursor already points.
+UPDATE "mailboxSync" SET "status" = 'IDLE' WHERE "status" = 'BACKFILLING';
+
+-- AlterEnum
+BEGIN;
+CREATE TYPE "GoogleSyncStatus_new" AS ENUM ('IDLE', 'RUNNING', 'NEEDS_RECONNECT', 'FAILED');
+ALTER TABLE "public"."mailboxSync" ALTER COLUMN "status" DROP DEFAULT;
+ALTER TABLE "mailboxSync" ALTER COLUMN "status" TYPE "GoogleSyncStatus_new" USING ("status"::text::"GoogleSyncStatus_new");
+ALTER TYPE "GoogleSyncStatus" RENAME TO "GoogleSyncStatus_old";
+ALTER TYPE "GoogleSyncStatus_new" RENAME TO "GoogleSyncStatus";
+DROP TYPE "public"."GoogleSyncStatus_old";
+ALTER TABLE "mailboxSync" ALTER COLUMN "status" SET DEFAULT 'IDLE';
+COMMIT;
+
+-- AlterTable
+ALTER TABLE "mailboxSync" DROP COLUMN "backfilledTo";
+
diff --git a/packages/db/prisma/migrations/20260731220000_denormalise_last_activity/migration.sql b/packages/db/prisma/migrations/20260731220000_denormalise_last_activity/migration.sql
new file mode 100644
index 00000000..80214c93
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731220000_denormalise_last_activity/migration.sql
@@ -0,0 +1,33 @@
+-- AlterTable
+ALTER TABLE "company" ADD COLUMN "lastActivityAt" TIMESTAMP(3);
+
+-- AlterTable
+ALTER TABLE "contact" ADD COLUMN "lastActivityAt" TIMESTAMP(3);
+
+-- AlterTable
+ALTER TABLE "deal" ADD COLUMN "lastActivityAt" TIMESTAMP(3);
+
+-- CreateIndex
+CREATE INDEX "company_lastActivityAt_idx" ON "company"("lastActivityAt");
+
+-- CreateIndex
+CREATE INDEX "contact_lastActivityAt_idx" ON "contact"("lastActivityAt");
+
+-- CreateIndex
+CREATE INDEX "deal_lastActivityAt_idx" ON "deal"("lastActivityAt");
+
+
+-- Backfill from what is already there, so the new column is sortable on day one
+-- rather than after everyone's next activity. `createdAt` (not `occurredAt`) to
+-- match what the lateral join this replaces was reading.
+UPDATE "company" c SET "lastActivityAt" = a.max
+FROM (SELECT "companyId" AS id, MAX("createdAt") AS max FROM "activity" WHERE "companyId" IS NOT NULL GROUP BY "companyId") a
+WHERE c.id = a.id;
+
+UPDATE "contact" ct SET "lastActivityAt" = a.max
+FROM (SELECT "contactId" AS id, MAX("createdAt") AS max FROM "activity" WHERE "contactId" IS NOT NULL GROUP BY "contactId") a
+WHERE ct.id = a.id;
+
+UPDATE "deal" d SET "lastActivityAt" = a.max
+FROM (SELECT "dealId" AS id, MAX("createdAt") AS max FROM "activity" WHERE "dealId" IS NOT NULL GROUP BY "dealId") a
+WHERE d.id = a.id;
diff --git a/packages/db/prisma/migrations/20260731230000_logo_dark_mode/migration.sql b/packages/db/prisma/migrations/20260731230000_logo_dark_mode/migration.sql
new file mode 100644
index 00000000..3bdec9f7
--- /dev/null
+++ b/packages/db/prisma/migrations/20260731230000_logo_dark_mode/migration.sql
@@ -0,0 +1,4 @@
+-- AlterTable
+ALTER TABLE "company" ADD COLUMN "iconDarkUrl" TEXT,
+ADD COLUMN "iconTone" TEXT;
+
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 00b96447..8eddbcde 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -26,10 +26,11 @@ model User {
// CRM ownership. Better Auth owns every field above and `bun run
// auth:generate` rewrites them; these back-relations are ours and have to be
// put back if that ever wipes them.
- ownedCompanies Company[] @relation("CompanyOwner")
- ownedContacts Contact[] @relation("ContactOwner")
- ownedDeals Deal[] @relation("DealOwner")
- activities Activity[] @relation("ActivityAuthor")
+ ownedCompanies Company[] @relation("CompanyOwner")
+ ownedContacts Contact[] @relation("ContactOwner")
+ ownedDeals Deal[] @relation("DealOwner")
+ activities Activity[] @relation("ActivityAuthor")
+ mailboxSyncs MailboxSync[]
@@unique([email])
@@map("user")
@@ -133,6 +134,16 @@ enum EnrichmentStatus {
SKIPPED
}
+/// Where a record came from. Auto-created rows are tagged so a bad matching
+/// rule is visible and reversible in bulk, rather than silently indistinguishable
+/// from something a rep typed.
+enum RecordSource {
+ MANUAL
+ IMPORT
+ EMAIL
+ CALENDAR
+}
+
model Company {
id String @id @default(cuid())
name String
@@ -147,6 +158,18 @@ model Company {
logoDarkUrl String?
/// Square mark, used in table rows.
iconUrl String?
+ /// The dark-mode square mark, when the brand publishes one. Rare — most
+ /// brands ship a light-mode logo only, which is what `iconTone` is for.
+ iconDarkUrl String?
+ /// How `iconUrl` behaves against a background, from Context.dev's `mode` plus
+ /// the artwork's own dominant colour:
+ ///
+ /// - `opaque` — the icon is composed on its own background; never put a
+ /// surface behind it.
+ /// - `dark` — dark artwork on transparency; invisible in dark mode without
+ /// a light surface behind it.
+ /// - `light` — light artwork on transparency; the same problem in reverse.
+ iconTone String?
/// Hex. An accent only — brand colours would fight the design tokens.
brandColor String?
@@ -177,14 +200,29 @@ model Company {
enrichmentError String?
enrichment CompanyEnrichment?
- contacts Contact[] @relation("CompanyContacts")
- deals Deal[]
- activities Activity[]
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ /// MANUAL unless a sync created it. Filterable, so a bad auto-create rule can
+ /// be undone in bulk.
+ source RecordSource @default(MANUAL)
+
+ /// Denormalised max(activity.createdAt), written with the activity.
+ ///
+ /// A real column because it is a sortable column on every list, and ordering
+ /// by an aggregate over a relation is something Prisma cannot express — the
+ /// alternative is a correlated subquery per row, which would be the slowest
+ /// thing on the page. Maintained through `ActivityStampService`.
+ lastActivityAt DateTime?
+
+ contacts Contact[] @relation("CompanyContacts")
+ deals Deal[]
+ activities Activity[]
+ emailThreads EmailThread[]
+ calendarEvents CalendarEvent[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([ownerId])
@@index([name])
+ @@index([lastActivityAt])
@@map("company")
}
@@ -216,13 +254,27 @@ model Contact {
owner User? @relation("ContactOwner", fields: [ownerId], references: [id], onDelete: SetNull)
primaryOf Company? @relation("PrimaryContact")
- deals DealContact[]
- activities Activity[]
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ source RecordSource @default(MANUAL)
+
+ /// Denormalised max(activity.createdAt), written with the activity.
+ ///
+ /// A real column because it is a sortable column on every list, and ordering
+ /// by an aggregate over a relation is something Prisma cannot express — the
+ /// alternative is a correlated subquery per row, which would be the slowest
+ /// thing on the page. Maintained through `ActivityStampService`.
+ lastActivityAt DateTime?
+
+ deals DealContact[]
+ activities Activity[]
+ emailThreads EmailThread[]
+ calendarEvents CalendarEvent[]
+ eventAttendance CalendarAttendee[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([companyId])
@@index([ownerId])
+ @@index([lastActivityAt])
@@map("contact")
}
@@ -243,6 +295,14 @@ model Deal {
closedAt DateTime?
closedReason String?
+ /// Denormalised max(activity.createdAt), written with the activity.
+ ///
+ /// A real column because it is a sortable column on every list, and ordering
+ /// by an aggregate over a relation is something Prisma cannot express — the
+ /// alternative is a correlated subquery per row, which would be the slowest
+ /// thing on the page. Maintained through `ActivityStampService`.
+ lastActivityAt DateTime?
+
contacts DealContact[]
activities Activity[]
createdAt DateTime @default(now())
@@ -252,6 +312,7 @@ model Deal {
@@index([ownerId])
@@index([stage])
@@index([expectedCloseDate])
+ @@index([lastActivityAt])
@@map("deal")
}
@@ -291,9 +352,18 @@ model Activity {
createdById String
createdBy User @relation("ActivityAuthor", fields: [createdById], references: [id])
- /// { from, to } for STAGE_CHANGE; the credit cost for ENRICHMENT.
+ /// { from, to } for STAGE_CHANGE; the credit cost for ENRICHMENT; `{ synced:
+ /// true }` for anything a Google sync projected.
meta Json?
+ /// The projection links. Unique because a thread and an event each get exactly
+ /// one timeline entry, updated in place as the thread grows or the event moves
+ /// — the timeline stays one indexed range scan instead of a three-table union.
+ emailThreadId String? @unique
+ emailThread EmailThread? @relation(fields: [emailThreadId], references: [id], onDelete: Cascade)
+ calendarEventId String? @unique
+ calendarEvent CalendarEvent? @relation(fields: [calendarEventId], references: [id], onDelete: Cascade)
+
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -304,3 +374,183 @@ model Activity {
@@index([createdById])
@@map("activity")
}
+
+// ---------------------------------------------------------------------------
+// Google sync
+//
+// Gmail threads and Calendar events get real tables; the timeline gets one
+// projected Activity per thread and per event. Identity is deliberately global
+// rather than Google's per-mailbox ids — see docs/plan/gmail-calendar-plan.md §4.2.
+// ---------------------------------------------------------------------------
+
+enum GoogleSyncStatus {
+ IDLE
+ RUNNING
+ /// The refresh token is gone. Stop trying; the rep has to reconnect.
+ NEEDS_RECONNECT
+ FAILED
+}
+
+enum EmailDirection {
+ INBOUND
+ OUTBOUND
+}
+
+/// Per-user, per-source cursor.
+///
+/// In Postgres because the API is a serverless function with no memory between
+/// invocations, and because the in-process EnrichmentQueue deliberately drops
+/// queued work on shutdown — fine for enrichment, fatal for a resumable sync.
+model MailboxSync {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ /// "gmail" | "calendar".
+ source String
+
+ status GoogleSyncStatus @default(IDLE)
+ /// Gmail: the last processed historyId. Calendar: nextSyncToken.
+ ///
+ /// Stamped with "now" the first time a mailbox is seen, which is what makes
+ /// this forward-only: there is no backfill, so the cursor starts at the
+ /// moment of connection and nothing before it is ever read.
+ cursor String?
+ lastSyncedAt DateTime?
+ lastError String?
+ /// Set by the 429/403 handler; the cron skips this row until it passes.
+ retryAfter DateTime?
+ /// Auto-creation is opt-in per source — on for calendar, off for Gmail.
+ autoCreate Boolean @default(false)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([userId, source])
+ @@index([status])
+ @@map("mailboxSync")
+}
+
+/// One conversation, whoever's mailbox it came from.
+model EmailThread {
+ id String @id @default(cuid())
+ /// The RFC 822 Message-ID of the thread root — global, unlike Gmail's
+ /// mailbox-scoped threadId. This is what stops two reps on one thread
+ /// producing two CRM threads.
+ rootMessageId String @unique
+ subject String?
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: SetNull)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ firstMessageAt DateTime
+ lastMessageAt DateTime
+ messageCount Int @default(0)
+
+ messages EmailMessage[]
+ activity Activity?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([companyId, lastMessageAt])
+ @@index([contactId, lastMessageAt])
+ @@map("emailThread")
+}
+
+model EmailMessage {
+ id String @id @default(cuid())
+ threadId String
+ thread EmailThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
+
+ /// Global message identity. Unique, so account B's sync skips what account A
+ /// already ingested.
+ rfcMessageId String @unique
+ /// Whose mailbox produced this copy, and its id there — for deep links.
+ syncedByUserId String?
+ gmailMessageId String?
+
+ direction EmailDirection
+ fromEmail String
+ fromName String?
+ /// [{ email, name, kind: "to" | "cc" }]. Not a table: nothing queries it.
+ recipients Json
+ subject String?
+ snippet String?
+ /// Plain text, quoted history stripped. Never logged; never in list payloads.
+ body String?
+ sentAt DateTime
+
+ createdAt DateTime @default(now())
+
+ @@index([threadId, sentAt])
+ @@map("emailMessage")
+}
+
+model CalendarEvent {
+ id String @id @default(cuid())
+ /// Shared by every attendee's copy of the event, and by every instance of a
+ /// recurrence — which is why the start time is part of the key.
+ iCalUid String
+ originalStartTime DateTime
+ /// Set on an instance of a recurring series.
+ recurringEventId String?
+
+ title String?
+ description String?
+ location String?
+ conferenceUrl String?
+ startsAt DateTime
+ endsAt DateTime
+ isAllDay Boolean @default(false)
+ status String
+ organizerEmail String?
+
+ companyId String?
+ company Company? @relation(fields: [companyId], references: [id], onDelete: SetNull)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ syncedByUserId String?
+ googleEventId String?
+
+ attendees CalendarAttendee[]
+ activity Activity?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([iCalUid, originalStartTime])
+ @@index([companyId, startsAt])
+ @@index([contactId, startsAt])
+ @@map("calendarEvent")
+}
+
+model CalendarAttendee {
+ id String @id @default(cuid())
+ eventId String
+ event CalendarEvent @relation(fields: [eventId], references: [id], onDelete: Cascade)
+
+ email String
+ name String?
+ /// needsAction | declined | tentative | accepted
+ responseStatus String?
+ isOrganizer Boolean @default(false)
+ contactId String?
+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
+
+ @@unique([eventId, email])
+ @@index([contactId])
+ @@map("calendarAttendee")
+}
+
+/// Domains we never match on and never create from — vendors, ATSs, newsletters.
+/// Grows by hand and by a "not a customer" action in the UI.
+model SuppressedDomain {
+ domain String @id
+ reason String?
+ createdAt DateTime @default(now())
+
+ @@map("suppressedDomain")
+}
diff --git a/packages/ui/src/components/accordion.tsx b/packages/ui/src/components/accordion.tsx
new file mode 100644
index 00000000..133c9dfa
--- /dev/null
+++ b/packages/ui/src/components/accordion.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
+import { Accordion as AccordionPrimitive } from "radix-ui";
+import type * as React from "react";
+
+function Accordion({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+ return (
+ <AccordionPrimitive.Root
+ data-slot="accordion"
+ className={cn("flex w-full flex-col", className)}
+ {...props}
+ />
+ );
+}
+
+function AccordionItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
+ return (
+ <AccordionPrimitive.Item
+ data-slot="accordion-item"
+ className={cn("not-last:border-b", className)}
+ {...props}
+ />
+ );
+}
+
+function AccordionTrigger({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
+ return (
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ data-slot="accordion-trigger"
+ className={cn(
+ "group/accordion-trigger relative flex flex-1 items-start justify-between rounded-none border border-transparent py-2.5 text-left font-medium text-sm outline-none transition-all hover:underline focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:after:border-ring disabled:pointer-events-none disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDownIcon
+ data-slot="accordion-trigger-icon"
+ className="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden"
+ />
+ <ChevronUpIcon
+ data-slot="accordion-trigger-icon"
+ className="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline"
+ />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+ );
+}
+
+function AccordionContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
+ return (
+ <AccordionPrimitive.Content
+ data-slot="accordion-content"
+ className="overflow-hidden text-sm data-closed:animate-accordion-up data-open:animate-accordion-down"
+ {...props}
+ >
+ <div
+ className={cn(
+ "pt-0 pb-2.5 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ </AccordionPrimitive.Content>
+ );
+}
+
+export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
diff --git a/packages/ui/src/components/attendee-list.tsx b/packages/ui/src/components/attendee-list.tsx
new file mode 100644
index 00000000..49d267c0
--- /dev/null
+++ b/packages/ui/src/components/attendee-list.tsx
@@ -0,0 +1,115 @@
+import { Avatar, AvatarFallback } from "@crm/ui/components/avatar";
+import {
+ type StatusTone,
+ StatusIndicator,
+} from "@crm/ui/components/status-indicator";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@crm/ui/components/tooltip";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+export type Attendee = {
+ id: string;
+ email: string;
+ name: string | null;
+ /** Google's own values: needsAction | declined | tentative | accepted. */
+ responseStatus: string | null;
+ isOrganizer: boolean;
+};
+
+/**
+ * Whether someone actually turned up to the invitation.
+ *
+ * Mapped onto the shared tones rather than to colours directly, so a declined
+ * attendee reads the same red as a lost deal.
+ */
+const RESPONSE_TONE: Record<string, StatusTone> = {
+ accepted: "success",
+ declined: "error",
+ tentative: "warning",
+ needsAction: "neutral",
+};
+
+const RESPONSE_LABEL: Record<string, string> = {
+ accepted: "Accepted",
+ declined: "Declined",
+ tentative: "Maybe",
+ needsAction: "No reply",
+};
+
+/**
+ * The people on a meeting.
+ *
+ * Stacked avatars up to `max`, then a count. The full list is in the tooltip
+ * because a nine-person kickoff should not push the timeline entry to three
+ * lines.
+ */
+function AttendeeList({
+ attendees,
+ max = 5,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"div">, "children"> & {
+ attendees: readonly Attendee[];
+ max?: number;
+}) {
+ if (attendees.length === 0) return null;
+
+ const shown = attendees.slice(0, max);
+ const overflow = attendees.length - shown.length;
+
+ return (
+ <div
+ data-slot="attendee-list"
+ className={cn("flex items-center gap-2", className)}
+ {...props}
+ >
+ <div className="flex items-center -space-x-2">
+ {shown.map((attendee) => (
+ <Tooltip key={attendee.id}>
+ <TooltipTrigger asChild>
+ <Avatar size="sm" className="ring-2 ring-background">
+ <AvatarFallback>{initialsOf(attendee)}</AvatarFallback>
+ </Avatar>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span className="flex items-center gap-2">
+ {attendee.name ?? attendee.email}
+ <StatusIndicator
+ tone={RESPONSE_TONE[attendee.responseStatus ?? "needsAction"] ?? "neutral"}
+ label={
+ RESPONSE_LABEL[attendee.responseStatus ?? "needsAction"] ??
+ "No reply"
+ }
+ />
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+
+ {overflow > 0 ? (
+ <span className="text-muted-foreground text-xs">+{overflow}</span>
+ ) : null}
+ </div>
+ );
+}
+
+function initialsOf(attendee: Attendee): string {
+ const source =
+ attendee.name?.trim() && !attendee.name.includes("@")
+ ? attendee.name
+ : attendee.email;
+
+ return source
+ .split(/[\s._-]+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((word) => word.charAt(0).toUpperCase())
+ .join("");
+}
+
+export { AttendeeList };
diff --git a/packages/ui/src/components/entity-logo.tsx b/packages/ui/src/components/entity-logo.tsx
index e4db95af..cb3c0eb4 100644
--- a/packages/ui/src/components/entity-logo.tsx
+++ b/packages/ui/src/components/entity-logo.tsx
@@ -6,6 +6,33 @@ import { useState } from "react";
export type EntityLogoSize = "xs" | "sm" | "default" | "lg" | "xl";
+/**
+ * How the artwork behaves against a background, as resolved at enrichment time.
+ *
+ * - `opaque` — composed on its own tile; needs nothing from us.
+ * - `dark` — dark mark on transparency; vanishes in dark mode.
+ * - `light` — light mark on transparency; vanishes in light mode.
+ */
+export type EntityLogoTone = "opaque" | "dark" | "light";
+
+/**
+ * A surface, only for the theme where the artwork would otherwise disappear.
+ *
+ * Most brands publish one logo drawn for a white page, so on a dark row a black
+ * wordmark is simply not there. The alternative — a tile behind every logo —
+ * is what the note above rules out, and it would put a white square behind the
+ * icons that already arrive on their own background.
+ *
+ * `invert` rather than a coloured tile for the monochrome cases: it keeps the
+ * mark borderless, which is the whole point of this component, and a mark whose
+ * dominant colour is near-black or near-white is monochrome by definition.
+ */
+const TONE_CLASS: Record<EntityLogoTone, string> = {
+ opaque: "",
+ dark: "dark:invert",
+ light: "invert dark:invert-0",
+};
+
/**
* A square logo tile with an initials fallback.
*
@@ -23,11 +50,16 @@ export type EntityLogoSize = "xs" | "sm" | "default" | "lg" | "xl";
*/
export function EntityLogo({
src,
+ darkSrc,
+ tone,
name,
size = "default",
className,
}: {
src?: string | null;
+ /** The brand's own dark-mode artwork, when it publishes one. */
+ darkSrc?: string | null;
+ tone?: EntityLogoTone | null;
name: string;
size?: EntityLogoSize;
className?: string;
@@ -38,8 +70,13 @@ export function EntityLogo({
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const url = src?.trim() ? src : null;
+ const dark = darkSrc?.trim() ? darkSrc : null;
const showImage = url !== null && failedSrc !== url;
+ // A real dark-mode logo always beats a synthetic one, so the tone fix is
+ // skipped entirely when the brand published artwork for both.
+ const toneClass = dark ? "" : tone ? TONE_CLASS[tone] : "";
+
return (
<span
data-slot="entity-logo"
@@ -55,21 +92,41 @@ export function EntityLogo({
)}
>
{showImage ? (
- <img
- src={url}
- alt=""
- loading="lazy"
- decoding="async"
- // Several logo CDNs refuse a request that carries our origin.
- referrerPolicy="no-referrer"
- // A dead logo URL is common — brands move them — and the alt text of
- // a broken image is worse than the initials we would have shown.
- onError={() => setFailedSrc(url)}
- // `contain`, always: cropping a logo is never the right answer, and
- // with no border to letterbox against, a wide wordmark can use the
- // full width instead of being inset to escape the frame.
- className="size-full object-contain"
- />
+ <>
+ <img
+ src={url}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ // Several logo CDNs refuse a request that carries our origin.
+ referrerPolicy="no-referrer"
+ // A dead logo URL is common — brands move them — and the alt text
+ // of a broken image is worse than the initials we would have shown.
+ onError={() => setFailedSrc(url)}
+ // `contain`, always: cropping a logo is never the right answer, and
+ // with no border to letterbox against, a wide wordmark can use the
+ // full width instead of being inset to escape the frame.
+ //
+ // Swapped by CSS rather than by reading the theme in JS: a hook
+ // would render the wrong logo on the server and flip it on hydrate.
+ className={cn(
+ "size-full object-contain",
+ dark && "dark:hidden",
+ toneClass,
+ )}
+ />
+
+ {dark ? (
+ <img
+ src={dark}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ className="hidden size-full object-contain dark:block"
+ />
+ ) : null}
+ </>
) : (
initialsFromName(name)
)}
diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx
new file mode 100644
index 00000000..8d08c534
--- /dev/null
+++ b/packages/ui/src/components/switch.tsx
@@ -0,0 +1,33 @@
+"use client"
+
+import * as React from "react"
+import { Switch as SwitchPrimitive } from "radix-ui"
+
+import { cn } from "@crm/ui/lib/utils"
+
+function Switch({
+ className,
+ size = "default",
+ ...props
+}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
+ size?: "sm" | "default"
+}) {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ data-size={size}
+ className={cn(
+ "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ data-slot="switch-thumb"
+ className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
+ />
+ </SwitchPrimitive.Root>
+ )
+}
+
+export { Switch }
diff --git a/packages/ui/src/components/thread-message.tsx b/packages/ui/src/components/thread-message.tsx
new file mode 100644
index 00000000..267e4b9b
--- /dev/null
+++ b/packages/ui/src/components/thread-message.tsx
@@ -0,0 +1,84 @@
+import { Avatar, AvatarFallback } from "@crm/ui/components/avatar";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+/**
+ * One message in an email thread.
+ *
+ * Direction is carried by a rail down the left rather than by colour: a mail
+ * client's blue-for-mine is a convention this design system does not have, and
+ * a rail reads the same in both themes and to anyone who cannot see the hue.
+ */
+function ThreadMessage({
+ from,
+ fromEmail,
+ sentAt,
+ direction,
+ body,
+ action,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"article">, "children"> & {
+ from: string;
+ fromEmail: string;
+ /** Already formatted — the package does not own locale decisions. */
+ sentAt: string;
+ direction: "INBOUND" | "OUTBOUND";
+ body: string | null;
+ /** A deep link back to Gmail, usually. */
+ action?: React.ReactNode;
+}) {
+ const outbound = direction === "OUTBOUND";
+
+ return (
+ <article
+ data-slot="thread-message"
+ data-direction={direction}
+ className={cn(
+ "flex gap-3 border-l-2 py-3 pl-3",
+ outbound ? "border-l-foreground/30" : "border-l-border",
+ className,
+ )}
+ {...props}
+ >
+ <Avatar size="sm" className="mt-0.5">
+ <AvatarFallback>{initialsOf(from, fromEmail)}</AvatarFallback>
+ </Avatar>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="font-medium text-sm">{from}</span>
+ <span className="truncate text-muted-foreground text-xs">
+ {fromEmail}
+ </span>
+ <span className="ml-auto text-muted-foreground text-xs">
+ {sentAt}
+ </span>
+ </div>
+
+ {body ? (
+ <p className="whitespace-pre-wrap text-pretty text-muted-foreground text-sm/6">
+ {body}
+ </p>
+ ) : (
+ <p className="text-muted-foreground text-sm italic">No message body.</p>
+ )}
+
+ {action ? <div className="flex gap-3 text-xs">{action}</div> : null}
+ </div>
+ </article>
+ );
+}
+
+/** Up to two letters, from the display name if there is one. */
+function initialsOf(name: string, email: string): string {
+ const source = name.trim() && !name.includes("@") ? name : email;
+ const words = source.split(/[\s._-]+/).filter(Boolean);
+
+ return words
+ .slice(0, 2)
+ .map((word) => word.charAt(0).toUpperCase())
+ .join("");
+}
+
+export { ThreadMessage };