Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Refactor README and agent instructions for clarity and functionality
Lewis Carhartebee94b3c528
diff --git a/README.md b/README.mdindex 47d400b4..8a60f02e 100644--- a/README.md+++ b/README.md@@ -1,20 +1,22 @@<h1 align="center">CRM</h1><p align="center">- An open-source CRM that fills itself in.<br>- It reads your Gmail and Calendar, works out who the people are, and writes what it learns onto the record.+ <strong>An open-source, agentic-first CRM.</strong><br>+ A durable research agent is the product. The database is just where it writes things down.</p><p align="center">+ <a href="#the-agent"><strong>The agent</strong></a> ·+ <a href="#the-stack"><strong>Stack</strong></a> ·<a href="#quick-start"><strong>Quick start</strong></a> ·<a href="#configuration"><strong>Configuration</strong></a> ·- <a href="#the-agent"><strong>The agent</strong></a> ·<a href="#deploying"><strong>Deploying</strong></a> ·<a href="./CONTRIBUTING.md"><strong>Contributing</strong></a></p><p align="center"><img alt="MIT licence" src="https://img.shields.io/badge/licence-MIT-blue.svg">+ <img alt="Built with eve" src="https://img.shields.io/badge/agent-eve-black.svg"><img alt="Built with Bun" src="https://img.shields.io/badge/runtime-Bun-black.svg"><img alt="Postgres" src="https://img.shields.io/badge/database-Postgres-336791.svg"></p>@@ -30,20 +32,28 @@## What this is-Most CRMs are a database with a form in front of it. Somebody has to type into that-form, and nobody does, so the data rots and the tool becomes a place deals go to be-forgotten.--This one is built the other way round. Gmail and Calendar are the source of truth:-when you email a customer, the thread lands on their record; when you take a meeting-with someone new, they become a contact at a company that already has a logo and an-industry. A research agent then works out who these people actually are — real name,-current title, employer — and writes it down with the evidence attached.--The rule it never breaks: **nothing about a person is guessed.** A contact who arrived-as `[email protected]` is called "Pmarchetti" until something proves otherwise —-the address is not a name, and a model asked what it stands for will happily invent-someone. A confidently wrong fact about a customer is worse than a blank field,+Most CRMs are a database with a form in front of it. The AI ones bolt a chat box onto+the side of that form. Both leave the actual work — finding out what is true, and+writing it down — to a human who has better things to do.++This is built the other way round. **The agent is not a feature of the CRM; the CRM is+where the agent keeps its notes.** It runs on its own deployment, on its own schedule,+against its own work queue. It decides what to look at next, books its own follow-ups,+spends a research budget, and stops when the budget runs out. Nothing about it is+request-response: close the browser and it keeps going.++The API deliberately has no intelligence in it at all. NestJS reports that *something+happened* — a thread was ingested, a company was created, an attendee is unknown — by+writing a row to a queue. The agent leases that row and decides what it means. A Nest+service that calls an enrichment API is treated as a bug, and+[`docs/api.md`](./docs/api.md) explains the outage that made that a rule.++The rule the agent itself never breaks: **nothing about a person is guessed.** No tool+accepts a confidence score, because a model asked to grade its own certainty will, and+it will be wrong in the direction that makes it look useful. Tools report what they+*observed* — `crm.signature-block`, `github.account-identity` — and a ledger prices the+evidence. Strong evidence writes to the record. Weak evidence becomes a suggestion a+human settles. A confidently wrong fact about a customer is worse than a blank field,because nobody can tell it is wrong.It is single-tenant and internal by design. Sign-in is Google, the allow-list is one@@ -88,6 +98,110 @@ customer data.</tr></table>+## The agent++[`apps/agent`](./apps/agent) is its own deployment, built on+[**eve**](https://eve.dev) — Vercel's filesystem-first framework for durable agents.+A tool is a file, a skill is a markdown file, a schedule is a file, and the runtime+handles the durable part: sessions that survive a redeploy, work that resumes where it+stopped.++| | |+| --- | --- |+| **18 authored tools** | `read_crm_history`, `search_crm`, `identify_contact`, `research_person`, `enrich_company`, `record_fact`, `schedule_recheck`… |+| **4 skills** | `evidence.md`, `identity-matching.md`, `data-boundaries.md`, `writing-a-brief.md` — prose the agent reads, versioned like code |+| **1 schedule** | `dispatch.ts`, which decides nothing. It leases what is due and starts a session per row. |+| **A sandbox** | `bash`, `grep`, `glob` and a `/workspace`, with **`deny-all` egress** |++**It runs itself.** `lib/tasks.ts` is the work queue: `claimDue` leases rows with+`FOR UPDATE SKIP LOCKED`, so two dispatchers take disjoint work and a run that dies+frees its row when the lease expires. Anything that looks like "every N minutes, the+oldest ten contacts" belongs in a task's `dueAt`, not in a cron expression. When the+agent wants another look at somebody it calls `schedule_recheck` and says why — and+the reason is shown to the rep, because an agent that cannot say why it will be back+in fourteen days does not have a reason, it has a default.++**Every outside source is optional, and it is designed to run with none of them.**+With no API keys at all it still works: `read_crm_history` reads your own threads,+meetings and signature blocks, which is free and is the best evidence there is — no+data vendor can sell you a reply from the person's own address. Each key opens one+more place to look. It is told at the start of every session which ones this install+has, so it plans around what it actually has rather than discovering the gaps one+failed call at a time, and it prints the list at startup:++```+[agent] on LinkedIn (RAPIDAPI_KEY)+[agent] off Web research (PERPLEXITY_API_KEY)+[agent] off Company brand data (CONTEXT_DEV_API_KEY)+```++**The sandbox has no network and no database.** Turning it on is what gives the model+a shell — the difference between a tool-caller and something that can keep a dossier,+diff this month's profile against last month's, and grep a thread for a signature+block. `deny-all` egress costs nothing, because `web_fetch` runs in the app runtime+and `web_search` at the model provider. What it removes is the only path by which a+customer's email body could leave through a shell command. The other half of that rule+is an absence: **the sandbox is never given `DATABASE_URL`.** A shell with credentials+and egress is exfiltration-shaped even in an internal tool; a shell with neither is a+text processor.++**You can talk to it, and watch it work.** Every contact, company and deal has an+**Agent** tab — the steps as it takes them, the leads it throws away and why, and its+questions answered in place when it cannot decide between two people. Conversations+are durable and survive a reload; the record travels in a signed token rather than+being bolted onto the front of your message. Set `AGENT_BRIDGE_SECRET` to the same+value in both processes to turn it on. Without it the tab reports that it is not+configured, and the agent carries on running its own schedule.++[`docs/agent.md`](./docs/agent.md) is the full write-up.++## The stack++A [Turborepo](https://turborepo.dev) monorepo on [Bun](https://bun.com), deployed on+[Vercel](https://vercel.com).++| | |+| --- | --- |+| **Agent** | [eve](https://eve.dev) — durable sessions, tools, skills, schedules, sandboxes |+| **Model** | [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) — no provider SDK, and OIDC on Vercel means no key to manage |+| **Sandbox** | [Vercel Sandbox](https://vercel.com/docs/vercel-sandbox) in production, Docker or microsandbox locally |+| **Front end** | [Next.js](https://nextjs.org) App Router · [shadcn/ui](https://ui.shadcn.com) · [nuqs](https://nuqs.dev) for URL state |+| **API** | [NestJS](https://nestjs.com) with [nestjs-trpc](https://nestjs-trpc.io) — HTTP, auth, tRPC, Google sync |+| **Data** | [Prisma](https://prisma.io) · Postgres ([Neon](https://neon.tech)) · optional Redis ([Upstash](https://upstash.com)) |+| **Auth** | [Better Auth](https://better-auth.com), Google-only, one allow-list |+| **Files** | [Vercel Blob](https://vercel.com/docs/vercel-blob) — mirrors profile pictures so they survive the source going away |+| **Tooling** | [Biome](https://biomejs.dev) · TypeScript everywhere |++The app talks to the API over **tRPC**, and the router type is generated from the+NestJS routers — so the front end is type-safe from the Prisma row to the table cell.+List state (filters, sort, page) lives in the URL, so copying the address bar+reproduces the view.++### Layout++| Path | |+| --- | --- |+| `apps/agent` | The research agent — tools, skills, schedules, sandbox |+| `apps/app` | Next.js front end · :3000 |+| `apps/api` | NestJS API — HTTP, auth, tRPC, Google sync · :3001 |+| `packages/db` | Prisma schema, migrations, shared Postgres client |+| `packages/auth` | Better Auth config and the sign-in allow-list |+| `packages/ui` | shadcn/ui components, the Tailwind theme |+| `packages/env` | Finds and loads the root `.env` |++### Three rules the codebase holds to++Written up where the work happens, not in a style guide:++- **Intelligence never lives in the API** ([docs/api.md](./docs/api.md)). Nest reports+ that something happened; the agent decides what it means. Two copies of an identity+ matcher once drifted until one matched every employer on earth.+- **`packages/ui` is the only source of UI** ([docs/design.md](./docs/design.md)). No+ overriding styles at the call site.+- **There are no organizations.** Single tenant, deliberately. An `organizationId`+ that is always the same value is a column, an index and a permissions check that+ buys nothing and reads like a real one at review time.+## Quick startYou need [Bun](https://bun.com) and Docker.@@ -164,69 +278,6 @@ short version:| `REDIS_URL` | A shared cache. Without it, per-instance and in-memory. || `CRON_SECRET` | Guards the Gmail/Calendar sync route. Required to use it. |-## The agent--The research agent is a separate deployment in [`apps/agent`](./apps/agent), built on-[eve](https://eve.dev). The API never enriches anything itself — it queues a row that-says *this happened* (a company was created, an attendee is unknown, a meeting is-tomorrow) and the agent decides what that means.--**Every outside source it can reach is optional, and it is designed to run with none-of them.** With no API keys at all it still works: `read_crm_history` reads your own-threads, meetings and signature blocks, which is free and is the best evidence there-is — no data vendor can sell you a reply from the person's own address. Each key you-add opens one more place to look. The agent is told at the start of every session-which ones this install has, so it plans around what it actually has rather than-discovering the gaps one failed call at a time, and it prints the list at startup:--```-[agent] on LinkedIn (RAPIDAPI_KEY)-[agent] off Web research (PERPLEXITY_API_KEY)-[agent] off Company brand data (CONTEXT_DEV_API_KEY)-```--Instead of asserting confidence, it reports **evidence** and a ledger scores it.-Strong evidence writes to the record; weak evidence becomes a suggestion a human-settles. Both are the system working — and if it cannot confirm something, it leaves-the field empty and says so.--You can also watch it work. Every contact has an **Agent** tab: the steps it takes as-it takes them, the leads it throws away and why, and its questions answered in place-when it cannot decide between two people. Set `AGENT_BRIDGE_SECRET` to the same value-in both processes to turn it on — without it the tab reports that it is not-configured and nothing else changes. [`docs/agent.md`](./docs/agent.md) has the-details.--## What's inside--A [Turborepo](https://turborepo.dev) monorepo on [Bun](https://bun.com).--| Path | |-| --- | --- |-| `apps/app` | [Next.js](https://nextjs.org) front end · :3000 |-| `apps/api` | [NestJS](https://nestjs.com) API — HTTP, auth, tRPC, Google sync · :3001 |-| `apps/agent` | The research agent ([eve](https://eve.dev)) |-| `packages/db` | [Prisma](https://prisma.io) schema, migrations, shared Postgres client |-| `packages/auth` | [Better Auth](https://better-auth.com) config and the sign-in allow-list |-| `packages/ui` | [shadcn/ui](https://ui.shadcn.com) components, the Tailwind theme |-| `packages/env` | Finds and loads the root `.env` |--The app talks to the API over **tRPC**, and the router type is generated from the-NestJS routers — so the front end is type-safe from the Prisma row to the table cell.-List state (filters, sort, page) lives in the URL via [nuqs](https://nuqs.dev), so-copying the address bar reproduces the view.--Three rules the codebase holds to, written up where the work happens:--- **Intelligence never lives in the API** ([docs/api.md](./docs/api.md)). Nest reports- that something happened; the agent decides what it means. Two copies of an identity- matcher once drifted until one matched every employer on earth.-- **`packages/ui` is the only source of UI** ([docs/design.md](./docs/design.md)). No- overriding styles at the call site.-- **There are no organizations.** Single tenant, deliberately. An `organizationId`- that is always the same value is a column, an index and a permissions check that- buys nothing and reads like a real one at review time.-## Tasks| Command | |diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.tsindex 293229cc..f3097f91 100644--- a/apps/agent/agent/channels/crm.ts+++ b/apps/agent/agent/channels/crm.ts@@ -1,4 +1,7 @@+import { EnrichmentStatus } from "@crm/db";import { defineChannel } from "eve/channels";+import { settle } from "../lib/enrichment";+import { completeTask, taskSubject } from "../lib/tasks";/*** The CRM itself, as a place work arrives from.@@ -13,11 +16,68 @@ import { defineChannel } from "eve/channels";* fact on a record rather than a message to a person. If this ever needs to* tell somebody something, the timeline is where it goes.*/++/** The token format this channel owns. eve namespaces it by file stem. */+function taskToken(taskId: string): string {+ return `crm:task:${taskId}`;+}++/** The task a session is working for, or null if it is not working for one. */+function taskFromToken(token: string | undefined): string | null {+ if (!token) return null;+ const prefix = "crm:task:";+ return token.startsWith(prefix) ? token.slice(prefix.length) : null;+}+export default defineChannel({// No inbound HTTP surface. Work reaches this channel by hand-off from the// dispatcher, not by request — the API queues a row, it does not call us.routes: [],+ /**+ * A turn ending is what retires the row.+ *+ * The dispatcher cannot do it: `receive` returns a `Session` the moment the+ * message is accepted, so awaiting it says the work *started*, never that it+ * finished. Completing there would retire rows before the research ran; not+ * completing there — which is what the code did — meant nothing retired them+ * at all, the lease expired, and the row was dispatched again ten minutes+ * later, forever, resuming the same session and paying for another turn.+ *+ * `session.waiting` is the boundary that actually means "this turn is done+ * and the session is ready for the next message", so it is the one that+ * closes the task.+ */+ events: {+ async "session.waiting"(_data, channel) {+ const taskId = taskFromToken(channel.continuationToken);+ if (!taskId) return;++ const subject = await completeTask(taskId, "ran");+ // Null means somebody already closed it — a later turn on the same+ // thread, or the retirement sweep. Not ours to settle.+ if (subject) await settle(subject, EnrichmentStatus.COMPLETE);+ },++ async "turn.failed"(data, channel) {+ const taskId = taskFromToken(channel.continuationToken);+ if (!taskId) return;++ const reason =+ typeof data === "object" && data && "error" in data+ ? String((data as { error: unknown }).error)+ : "The research turn failed.";++ // The row is deliberately *not* closed. A failed turn is worth another+ // go, and leaving it open lets the lease expire and the attempt cap+ // decide when to stop — the same path a crashed run takes. Only the+ // record is updated, so the sheet stops claiming somebody is working+ // on it in the meantime; the next claim puts it back to RUNNING.+ const subject = await taskSubject(taskId);+ if (subject) await settle(subject, EnrichmentStatus.FAILED, reason);+ },+ },+async receive(input, { send }) {const taskId =typeof input.target?.taskId === "string" ? input.target.taskId : null;@@ -30,7 +90,7 @@ export default defineChannel({return send(input.message, {auth: input.auth,continuationToken: taskId- ? `crm:task:${taskId}`+ ? taskToken(taskId): `crm:adhoc:${crypto.randomUUID()}`,});},diff --git a/apps/agent/agent/instructions.md b/apps/agent/agent/instructions.mdindex be465e9c..38ae3c64 100644--- a/apps/agent/agent/instructions.md+++ b/apps/agent/agent/instructions.md@@ -1,7 +1,8 @@-# People research agent+# CRM research agent-You work out who the people in our CRM are, so a rep opens a record already-knowing who they are dealing with.+You work out who the people in our CRM are, what the companies are, and where+the deals stand — so a rep opens a record already knowing what they are dealing+with.## The one rule@@ -27,17 +28,55 @@ human. Both are the system working.So there is nothing to argue with and no bar to clear by trying harder. Reportwhat you found, accurately, and move on.-## Where to look, in order+## The record you were opened on-1. **`read_crm_history` first, always.** It is free, and it is the best evidence- we have: a reply from their own address, a signature block, a meeting they- attended. No data vendor can sell us any of that.+Every session starts from one record, and your session instructions say which+and give you its id. Read that record before anything else:++| Opened on | Start with |+| --------- | --------------------- |+| a person | `read_crm_history` |+| a company | `read_company_history`|+| a deal | `read_deal_history` |++All three are free — our own database, no vendor, no budget — and they are the+best evidence in the system besides.++## The three records are joined, and so are your tools++A contact works somewhere. A company has people and deals. A deal has a company+and the people on it. **You can always get from any one to the others**, and+each read hands you the ids to do it:++- `read_crm_history` returns the contact's **company id** and the deals they are+ on.+- `read_company_history` returns **every contact there, with their ids**, and+ every deal.+- `read_deal_history` returns the company and everyone attached, with ids.+- `search_crm` finds any of the three by name, email address or domain.++So two answers are always wrong:++**"I don't have a tool that lists contacts by company."** You do. It is+`read_company_history`, and the person asking is looking at that company.++**"Could you paste the contact's name or email address?"** Never ask a rep for+an id, and never ask them to search for you. Call `search_crm`. If it returns+nothing, say so — that is a real answer. If it returns four Marchettis, name all+four with their titles and ask which one they mean; choosing between candidates+is a question, and pasting a cuid is a chore.++## Where to look outside, in order++1. **The CRM first, always.** A reply from their own address, a signature block,+ a meeting they attended. No data vendor can sell us any of that.2. **LinkedIn** (`resolve_linkedin_profile` → `get_linkedin_profile`) foridentity: name, current title, employer, tenure. Self-reported, andauthoritative for who someone is.-3. **The open web** (`web_search`, `web_fetch`, `research_person`) for context:- news, funding, what they have said publicly. Sometimes wrong about job- titles — where it disagrees with LinkedIn about identity, LinkedIn wins.+3. **The open web** (`web_search`, `web_fetch`, `research_person`,+ `research_company`) for context: news, funding, what they have said publicly.+ Sometimes wrong about job titles — where it disagrees with LinkedIn about+ identity, LinkedIn wins.Search results are not evidence. A search for "Paula Marchetti" once returnedBrightwater's CEO. A search tells you where to look.@@ -51,7 +90,8 @@ that says only what the mailbox proves is a good outcome.## Your budget-Each contact comes with a research budget, and vendor calls spend it. When it is+Each session comes with a research budget, and **only vendor calls spend it**.+Every read of our own CRM is free, however many you make. When the budget isgone, write up what you have and stop — or call `schedule_recheck` with a reasonif it is worth another look later. Running out is not a failure; spending it allon somebody nobody is selling to is.diff --git a/apps/agent/agent/instructions/task.ts b/apps/agent/agent/instructions/task.tsindex 2ec486d2..5f5f87ac 100644--- a/apps/agent/agent/instructions/task.ts+++ b/apps/agent/agent/instructions/task.ts@@ -1,7 +1,6 @@-import { db } from "@crm/db";import { defineDynamic, defineInstructions } from "eve/instructions";-import { capabilitiesMarkdown } from "../lib/capabilities";import { focusOn, setBudget } from "../lib/focus";+import { sessionPreamble } from "../lib/preamble";/*** What this particular session is for.@@ -15,94 +14,40 @@ import { focusOn, setBudget } from "../lib/focus";* Resolved at `session.started` rather than per turn. Prompt caches are keyed* on the prompt, so a preamble that changed every turn would re-ingest the* whole conversation at uncached prices for information that does not change.+ *+ * The prose itself lives in `lib/preamble.ts` — three records, three different+ * conversations, and a test that says so. This file is the one place that+ * decides *focus*, because seeding it is what lets the audit hook file every+ * event against the right record: a hook sees events, not arguments.*/export default defineDynamic({events: {"session.started": async (_event, ctx) => {const attributes = ctx.session.auth.current?.attributes ?? {};- const contactId = asString(attributes.contactId);- const companyId = asString(attributes.companyId);- const dealId = asString(attributes.dealId);const budget = asNumber(attributes.budget);- const reason = asString(attributes.reason);const kind = asString(attributes.taskKind);- // Which outside sources exist is a property of the install, not of the- // task, so it is stated even for a session that is not about anybody in- // particular. An agent that learns its limits from four failed tool- // calls has already spent the budget it needed for the work.- // The panel opens on three kinds of record, and each is a different- // conversation. A session about a deal that opens by describing a- // person is a session that has to be told what it is looking at before- // it can be useful.- if (!contactId) {- if (companyId) {- return defineInstructions({- markdown: await companyMarkdown(companyId, ctx.session.id),- });- }- if (dealId) {- return defineInstructions({- markdown: await dealMarkdown(dealId, ctx.session.id),- });- }- return defineInstructions({ markdown: capabilitiesMarkdown() });- }-- // Seeding the session state here is what lets the audit hook file every- // event against the right record — a hook sees events, not arguments.- focusOn({ contactId, sessionId: ctx.session.id });if (budget) setBudget(budget);- const contact = await db.contact.findUnique({- where: { id: contactId },- select: {- firstName: true,- lastName: true,- email: true,- title: true,- company: { select: { name: true, domain: true } },- brief: { select: { refreshedAt: true } },- _count: { select: { emailThreads: true, calendarEvents: true } },+ const { markdown, focus } = await sessionPreamble(+ {+ contactId: asString(attributes.contactId),+ companyId: asString(attributes.companyId),+ dealId: asString(attributes.dealId),},- });-- if (!contact) {- return defineInstructions({ markdown: capabilitiesMarkdown() });- }-- const name = [contact.firstName, contact.lastName]- .filter(Boolean)- .join(" ");+ {+ // The dispatcher names a task; the panel never does. That is the+ // only signal available at session start, and it is a reliable one.+ dispatched: Boolean(kind),+ kind,+ reason: asString(attributes.reason),+ budget,+ },+ );- const known =- contact._count.emailThreads > 0 || contact._count.calendarEvents > 0- ? `We have ${contact._count.emailThreads} thread(s) and ${contact._count.calendarEvents} meeting(s) with them — read those first.`- : "We have never corresponded with them, so there is nothing internal to go on.";+ focusOn({ ...focus, sessionId: ctx.session.id });- return defineInstructions({- markdown: [- "## This session",- "",- `You are working on **${name}** (\`${contactId}\`)${- contact.email ? `, ${contact.email}` : ""- }${contact.company?.name ? `, at ${contact.company.name}` : ""}.`,- kind ? `Task: **${kind}**.` : "",- reason ? `Why now: ${reason}` : "",- budget- ? `Budget: **${budget}** vendor calls. Spend them where they matter.`- : "",- "",- known,- contact.brief- ? `A background already exists, written ${contact.brief.refreshedAt.toDateString()}. Replace it only if you learn something it does not say.`- : "There is no background on them yet.",- "",- capabilitiesMarkdown(),- ]- .filter(Boolean)- .join("\n"),- });+ return defineInstructions({ markdown });},},});@@ -115,122 +60,3 @@ function asNumber(value: unknown): number | null {const parsed = typeof value === "string" ? Number(value) : value;return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : null;}--/**- * A session opened from a company's record.- *- * Shorter than the contact preamble because a company has less to say about- * itself: what it is, who we know there, and whether anyone has looked it up.- */-async function companyMarkdown(- companyId: string,- sessionId: string,-): Promise<string> {- focusOn({ companyId, sessionId });-- const company = await db.company.findUnique({- where: { id: companyId },- select: {- name: true,- domain: true,- industry: true,- description: true,- enrichmentStatus: true,- _count: { select: { contacts: true, deals: true } },- },- });-- if (!company) return capabilitiesMarkdown();-- return [- "## This session",- "",- `You are working on **${company.name}**${- company.domain ? ` (${company.domain})` : ""- }${company.industry ? `, ${company.industry}` : ""}.`,- `We know ${company._count.contacts} contact(s) and ${company._count.deals} deal(s) there.`,- company.description- ? "There is already a description on the record."- : "There is no description on the record yet.",- "",- capabilitiesMarkdown(),- ].join("\n");-}--/**- * A session opened from a deal's record.- *- * A deal is the one record where the *state* matters as much as the facts:- * which stage, how much, who is on it, and when it was last touched. Those are- * the questions a rep opens a deal to ask, so they are what the session starts- * knowing.- */-async function dealMarkdown(- dealId: string,- sessionId: string,-): Promise<string> {- const deal = await db.deal.findUnique({- where: { id: dealId },- select: {- name: true,- stage: true,- amount: true,- currency: true,- expectedCloseDate: true,- lastActivityAt: true,- company: { select: { id: true, name: true } },- contacts: {- select: {- role: true,- contact: {- select: { id: true, firstName: true, lastName: true, title: true },- },- },- },- },- });-- if (!deal) return capabilitiesMarkdown();-- // Focused on the company, because that is the record every fact the agent- // can write hangs off — a deal has no fields of its own to enrich.- focusOn({ companyId: deal.company?.id ?? null, sessionId });-- const people = deal.contacts- .map(({ role, contact }) => {- const name = [contact.firstName, contact.lastName]- .filter(Boolean)- .join(" ");- return `${name}${contact.title ? ` (${contact.title})` : ""}${- role ? ` — ${role}` : ""- } \`${contact.id}\``;- })- .join("; ");-- return [- "## This session",- "",- `You are working on the deal **${deal.name}**${- deal.company ? ` at ${deal.company.name}` : ""- }.`,- `Stage: **${deal.stage}**${- deal.amount- ? `. Amount: ${deal.amount} ${deal.currency ?? ""}`.trim()- : ""- }${- deal.expectedCloseDate- ? `. Expected close: ${deal.expectedCloseDate.toDateString()}`- : ""- }.`,- deal.lastActivityAt- ? `Last touched ${deal.lastActivityAt.toDateString()}.`- : "Nothing has happened on it yet.",- people ? `People on it: ${people}` : "Nobody is attached to it yet.",- "",- "You can research the people and the company behind it with the usual",- "tools — a deal itself has no fields to enrich, so anything you learn is",- "recorded against them.",- "",- capabilitiesMarkdown(),- ].join("\n");-}diff --git a/apps/agent/agent/lib/accounts.ts b/apps/agent/agent/lib/accounts.tsnew file mode 100644index 00000000..031b2342--- /dev/null+++ b/apps/agent/agent/lib/accounts.ts@@ -0,0 +1,655 @@+import { ActivityType, db, EmailDirection } from "@crm/db";+import { isDerivedName } from "./names";++/**+ * The CRM's other two records: companies and deals.+ *+ * `crm.ts` reads a person. This reads what a person hangs off, and it exists+ * because the agent could not. A session opened on a company knew the count of+ * contacts there and not one of their ids, so asked the rep to paste one — the+ * CRM's own join, handed back to the human as homework. A deal was worse: the+ * agent could name the stage and had no way to see what had happened in it.+ *+ * Both reads are free — our own Postgres, no vendor, no budget — and both+ * **name the neighbouring records and give their ids**, because that is what+ * turns "I need an identifier" into a second tool call.+ */++/** How much of a body to hand back. Enough to read a signature block. */+const BODY_LIMIT = 4000;++export type AccountThread = {+ subject: string | null;+ /** Whose thread it is, so a company-wide read is still attributable. */+ contact: { id: string; name: string } | null;+ messageCount: number;+ lastMessageAt: string;+ messages: {+ direction: string;+ from: string;+ fromName: string | null;+ sentAt: string;+ body: string | null;+ }[];+};++export type AccountMeeting = {+ title: string | null;+ startsAt: string;+ upcoming: boolean;+ attendees: { email: string; name: string | null }[];+};++export type AccountNote = {+ type: string;+ subject: string | null;+ body: string | null;+ occurredAt: string;+};++export type CompanyPerson = {+ id: string;+ name: string;+ title: string | null;+ email: string | null;+ linkedinUrl: string | null;+ lastActivityAt: string | null;+ threads: number;+ meetings: number;+ /** Still named after their email address — nobody has worked out who they are. */+ needsIdentity: boolean;+};++export type CompanyDeal = {+ id: string;+ name: string;+ stage: string;+ open: boolean;+ amount: number | null;+ currency: string;+ expectedCloseDate: string | null;+ lastActivityAt: string | null;+ contacts: { id: string; name: string; role: string | null }[];+};++export type CompanyHistory = {+ company: {+ id: string;+ name: string;+ domain: string | null;+ website: string | null;+ industry: string | null;+ location: string | null;+ description: string | null;+ linkedinUrl: string | null;+ enrichmentStatus: string;+ };+ people: CompanyPerson[];+ deals: CompanyDeal[];+ threads: AccountThread[];+ meetings: AccountMeeting[];+ notes: AccountNote[];+ stats: {+ people: number;+ openDeals: number;+ emails: number;+ meetings: number;+ theyReplied: boolean;+ lastReplyAt: string | null;+ lastReplyFrom: string | null;+ nextMeetingAt: string | null;+ };+};++/**+ * Everything we know about an account: who works there, what is being sold to+ * them, and every word exchanged with any of them.+ *+ * The people list is the point. A company session that cannot name its own+ * contacts spends its first turn asking the rep for a cuid, and a rep who has+ * the record open on screen is being asked to do the join by hand.+ */+export async function readCompanyHistory(+ companyId: string,+ options: {+ threads?: number;+ messagesPerThread?: number;+ people?: number;+ } = {},+): Promise<CompanyHistory | null> {+ const company = await db.company.findUnique({+ where: { id: companyId },+ select: {+ id: true,+ name: true,+ domain: true,+ website: true,+ industry: true,+ subIndustry: true,+ city: true,+ country: true,+ description: true,+ linkedinUrl: true,+ enrichmentStatus: true,+ },+ });++ if (!company) return null;++ // A thread or a meeting is stamped with the company when the sync can+ // resolve one, but it is only ever stamped with the contact when the+ // counterparty was already on file — so both paths are checked. Missing the+ // second reads as an account nobody has ever emailed.+ const belongsToCompany = { OR: [{ companyId }, { contact: { companyId } }] };++ const [people, deals, threads, meetings, notes, lastInbound, counts] =+ await Promise.all([+ db.contact.findMany({+ where: { companyId },+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "asc" }],+ take: options.people ?? 25,+ select: {+ id: true,+ firstName: true,+ lastName: true,+ title: true,+ email: true,+ linkedinUrl: true,+ lastActivityAt: true,+ _count: { select: { emailThreads: true, calendarEvents: true } },+ },+ }),+ db.deal.findMany({+ where: { companyId },+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "desc" }],+ take: 20,+ select: {+ id: true,+ name: true,+ stage: true,+ amount: true,+ currency: true,+ expectedCloseDate: true,+ lastActivityAt: true,+ contacts: {+ select: {+ role: true,+ contact: {+ select: { id: true, firstName: true, lastName: true },+ },+ },+ },+ },+ }),+ db.emailThread.findMany({+ where: belongsToCompany,+ orderBy: { lastMessageAt: "desc" },+ take: options.threads ?? 5,+ select: {+ subject: true,+ messageCount: true,+ lastMessageAt: true,+ contact: { select: { id: true, firstName: true, lastName: true } },+ messages: {+ orderBy: { sentAt: "desc" },+ take: options.messagesPerThread ?? 4,+ select: {+ direction: true,+ fromEmail: true,+ fromName: true,+ sentAt: true,+ body: true,+ snippet: true,+ },+ },+ },+ }),+ db.calendarEvent.findMany({+ where: {+ OR: [+ { companyId },+ { contact: { companyId } },+ { attendees: { some: { contact: { companyId } } } },+ ],+ },+ orderBy: { startsAt: "desc" },+ take: 10,+ select: {+ title: true,+ startsAt: true,+ attendees: { select: { email: true, name: true } },+ },+ }),+ recentNotes({ companyId }),+ db.emailMessage.findFirst({+ where: {+ direction: EmailDirection.INBOUND,+ thread: belongsToCompany,+ },+ orderBy: { sentAt: "desc" },+ select: { sentAt: true, fromEmail: true, fromName: true },+ }),+ Promise.all([+ db.contact.count({ where: { companyId } }),+ db.emailMessage.count({ where: { thread: belongsToCompany } }),+ db.calendarEvent.count({+ where: {+ OR: [{ companyId }, { contact: { companyId } }],+ },+ }),+ ]),+ ]);++ const [peopleCount, emailCount, meetingCount] = counts;+ const now = new Date();++ return {+ company: {+ id: company.id,+ name: company.name,+ domain: company.domain,+ website: company.website,+ industry: [company.industry, company.subIndustry]+ .filter(Boolean)+ .join(" / "),+ location: [company.city, company.country].filter(Boolean).join(", "),+ description: company.description,+ linkedinUrl: company.linkedinUrl,+ enrichmentStatus: company.enrichmentStatus,+ },+ people: people.map((person) => ({+ id: person.id,+ name: fullName(person),+ title: person.title,+ email: person.email,+ linkedinUrl: person.linkedinUrl,+ lastActivityAt: person.lastActivityAt?.toISOString() ?? null,+ threads: person._count.emailThreads,+ meetings: person._count.calendarEvents,+ needsIdentity: isDerivedName(+ person.email,+ person.firstName,+ person.lastName,+ ),+ })),+ deals: deals.map(toCompanyDeal),+ threads: threads.map(toAccountThread),+ meetings: meetings.map((meeting) => toAccountMeeting(meeting, now)),+ notes,+ stats: {+ people: peopleCount,+ openDeals: deals.filter((deal) => isOpen(deal.stage)).length,+ emails: emailCount,+ meetings: meetingCount,+ theyReplied: lastInbound !== null,+ lastReplyAt: lastInbound?.sentAt.toISOString() ?? null,+ lastReplyFrom: lastInbound+ ? (lastInbound.fromName ?? lastInbound.fromEmail)+ : null,+ nextMeetingAt:+ meetings+ .filter((meeting) => meeting.startsAt > now)+ .sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime())[0]+ ?.startsAt.toISOString() ?? null,+ },+ };+}++export type DealHistory = {+ deal: {+ id: string;+ name: string;+ stage: string;+ open: boolean;+ daysInStage: number;+ stageChangedAt: string;+ amount: number | null;+ currency: string;+ expectedCloseDate: string | null;+ closedAt: string | null;+ closedReason: string | null;+ owner: string | null;+ createdAt: string;+ };+ company: { id: string; name: string; domain: string | null };+ people: {+ id: string;+ name: string;+ title: string | null;+ email: string | null;+ role: string | null;+ }[];+ /** Every stage this deal has been through, oldest first. */+ stageHistory: { from: string | null; to: string | null; at: string }[];+ threads: AccountThread[];+ meetings: AccountMeeting[];+ notes: AccountNote[];+ stats: {+ theyReplied: boolean;+ lastReplyAt: string | null;+ lastReplyFrom: string | null;+ nextMeetingAt: string | null;+ daysSinceLastActivity: number | null;+ };+ /** Why the correspondence here is the account's and not the deal's. */+ note: string;+};++/**+ * Where a deal actually stands, as opposed to what its stage field says.+ *+ * The two answers differ often enough to be the reason this exists: a deal+ * sitting in `CONTRACT_SENT` for six weeks with no inbound reply is not a+ * contract-sent deal, and the only way to know is to read the stage clock, the+ * last reply and the next meeting together.+ */+export async function readDealHistory(+ dealId: string,+ options: { threads?: number; messagesPerThread?: number } = {},+): Promise<DealHistory | null> {+ const deal = await db.deal.findUnique({+ where: { id: dealId },+ select: {+ id: true,+ name: true,+ stage: true,+ stageChangedAt: true,+ amount: true,+ currency: true,+ expectedCloseDate: true,+ closedAt: true,+ closedReason: true,+ lastActivityAt: true,+ createdAt: true,+ owner: { select: { name: true, email: true } },+ company: { select: { id: true, name: true, domain: true } },+ contacts: {+ select: {+ role: true,+ contact: {+ select: {+ id: true,+ firstName: true,+ lastName: true,+ title: true,+ email: true,+ },+ },+ },+ },+ },+ });++ if (!deal) return null;++ const contactIds = deal.contacts.map(({ contact }) => contact.id);++ // Email and calendar are filed against a person and a company, never against+ // a deal — Google has no idea our deals exist. So the correspondence here is+ // the account's, narrowed to the people on the deal where there are any. The+ // return says so rather than letting the agent infer that every thread it is+ // reading was about this deal.+ const relatedThreads =+ contactIds.length > 0+ ? {+ OR: [+ { contactId: { in: contactIds } },+ { companyId: deal.company.id },+ ],+ }+ : { companyId: deal.company.id };++ const [stageChanges, threads, meetings, notes, lastInbound] =+ await Promise.all([+ db.activity.findMany({+ where: { dealId, type: ActivityType.STAGE_CHANGE },+ orderBy: { createdAt: "asc" },+ take: 25,+ select: { meta: true, createdAt: true },+ }),+ db.emailThread.findMany({+ where: relatedThreads,+ orderBy: { lastMessageAt: "desc" },+ take: options.threads ?? 5,+ select: {+ subject: true,+ messageCount: true,+ lastMessageAt: true,+ contact: { select: { id: true, firstName: true, lastName: true } },+ messages: {+ orderBy: { sentAt: "desc" },+ take: options.messagesPerThread ?? 4,+ select: {+ direction: true,+ fromEmail: true,+ fromName: true,+ sentAt: true,+ body: true,+ snippet: true,+ },+ },+ },+ }),+ db.calendarEvent.findMany({+ where:+ contactIds.length > 0+ ? {+ OR: [+ { contactId: { in: contactIds } },+ { attendees: { some: { contactId: { in: contactIds } } } },+ { companyId: deal.company.id },+ ],+ }+ : { companyId: deal.company.id },+ orderBy: { startsAt: "desc" },+ take: 10,+ select: {+ title: true,+ startsAt: true,+ attendees: { select: { email: true, name: true } },+ },+ }),+ recentNotes({ dealId }),+ db.emailMessage.findFirst({+ where: { direction: EmailDirection.INBOUND, thread: relatedThreads },+ orderBy: { sentAt: "desc" },+ select: { sentAt: true, fromEmail: true, fromName: true },+ }),+ ]);++ const now = new Date();++ return {+ deal: {+ id: deal.id,+ name: deal.name,+ stage: deal.stage,+ open: isOpen(deal.stage),+ daysInStage: daysSince(deal.stageChangedAt, now),+ stageChangedAt: deal.stageChangedAt.toISOString(),+ amount: deal.amount === null ? null : Number(deal.amount),+ currency: deal.currency,+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,+ closedAt: deal.closedAt?.toISOString() ?? null,+ closedReason: deal.closedReason,+ owner: deal.owner?.name ?? deal.owner?.email ?? null,+ createdAt: deal.createdAt.toISOString(),+ },+ company: deal.company,+ people: deal.contacts.map(({ role, contact }) => ({+ id: contact.id,+ name: fullName(contact),+ title: contact.title,+ email: contact.email,+ role,+ })),+ stageHistory: stageChanges.map((change) => {+ const meta = (change.meta ?? {}) as { from?: unknown; to?: unknown };+ return {+ from: typeof meta.from === "string" ? meta.from : null,+ to: typeof meta.to === "string" ? meta.to : null,+ at: change.createdAt.toISOString(),+ };+ }),+ threads: threads.map(toAccountThread),+ meetings: meetings.map((meeting) => toAccountMeeting(meeting, now)),+ notes,+ stats: {+ theyReplied: lastInbound !== null,+ lastReplyAt: lastInbound?.sentAt.toISOString() ?? null,+ lastReplyFrom: lastInbound+ ? (lastInbound.fromName ?? lastInbound.fromEmail)+ : null,+ nextMeetingAt:+ meetings+ .filter((meeting) => meeting.startsAt > now)+ .sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime())[0]+ ?.startsAt.toISOString() ?? null,+ daysSinceLastActivity: deal.lastActivityAt+ ? daysSince(deal.lastActivityAt, now)+ : null,+ },+ note:+ contactIds.length > 0+ ? "Email and meetings are filed against people and companies, never against a deal. The correspondence here is with the people on this deal and with the rest of the account — read the subjects before treating any of it as being about this deal."+ : "Nobody is attached to this deal, so the correspondence here is the whole account's. Attaching the people on it would make this answer sharper.",+ };+}++/** The stages that are still in play. */+function isOpen(stage: string): boolean {+ return (+ stage !== "CLOSED_WON" &&+ stage !== "CLOSED_LOST" &&+ stage !== "UNQUALIFIED_TO_BUY"+ );+}++/**+ * Typed notes on the timeline, without the email and meeting projections.+ *+ * Every thread and every event already lands on the timeline as an `Activity`,+ * so including those types here would hand the same conversation back twice —+ * once as a note saying an email happened, and once as the email.+ */+async function recentNotes(+ where: { companyId: string } | { dealId: string },+): Promise<AccountNote[]> {+ const rows = await db.activity.findMany({+ where: {+ ...where,+ type: {+ in: [+ ActivityType.NOTE,+ ActivityType.CALL,+ ActivityType.TASK,+ ActivityType.ENRICHMENT,+ ],+ },+ },+ orderBy: { createdAt: "desc" },+ take: 10,+ select: {+ type: true,+ subject: true,+ body: true,+ occurredAt: true,+ createdAt: true,+ },+ });++ return rows.map((row) => ({+ type: row.type,+ subject: row.subject,+ body: row.body ? row.body.slice(0, BODY_LIMIT) : null,+ occurredAt: (row.occurredAt ?? row.createdAt).toISOString(),+ }));+}++function toAccountThread(thread: {+ subject: string | null;+ messageCount: number;+ lastMessageAt: Date;+ contact: { id: string; firstName: string; lastName: string | null } | null;+ messages: {+ direction: string;+ fromEmail: string;+ fromName: string | null;+ sentAt: Date;+ body: string | null;+ snippet: string | null;+ }[];+}): AccountThread {+ return {+ subject: thread.subject,+ contact: thread.contact+ ? { id: thread.contact.id, name: fullName(thread.contact) }+ : null,+ messageCount: thread.messageCount,+ lastMessageAt: thread.lastMessageAt.toISOString(),+ messages: thread.messages.map((message) => ({+ direction: message.direction,+ from: message.fromEmail,+ fromName: message.fromName,+ sentAt: message.sentAt.toISOString(),+ body: (message.body ?? message.snippet)?.slice(0, BODY_LIMIT) ?? null,+ })),+ };+}++function toAccountMeeting(+ meeting: {+ title: string | null;+ startsAt: Date;+ attendees: { email: string; name: string | null }[];+ },+ now: Date,+): AccountMeeting {+ return {+ title: meeting.title,+ startsAt: meeting.startsAt.toISOString(),+ upcoming: meeting.startsAt > now,+ attendees: meeting.attendees,+ };+}++function toCompanyDeal(deal: {+ id: string;+ name: string;+ stage: string;+ amount: unknown;+ currency: string;+ expectedCloseDate: Date | null;+ lastActivityAt: Date | null;+ contacts: {+ role: string | null;+ contact: { id: string; firstName: string; lastName: string | null };+ }[];+}): CompanyDeal {+ return {+ id: deal.id,+ name: deal.name,+ stage: deal.stage,+ open: isOpen(deal.stage),+ amount: deal.amount === null ? null : Number(deal.amount),+ currency: deal.currency,+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,+ lastActivityAt: deal.lastActivityAt?.toISOString() ?? null,+ contacts: deal.contacts.map(({ role, contact }) => ({+ id: contact.id,+ name: fullName(contact),+ role,+ })),+ };+}++function fullName(person: {+ firstName: string;+ lastName: string | null;+}): string {+ return [person.firstName, person.lastName].filter(Boolean).join(" ");+}++function daysSince(date: Date, now: Date): number {+ return Math.max(0, Math.floor((now.getTime() - date.getTime()) / 86_400_000));+}diff --git a/apps/agent/agent/lib/crm.ts b/apps/agent/agent/lib/crm.tsindex 6ceac406..45dc220d 100644--- a/apps/agent/agent/lib/crm.ts+++ b/apps/agent/agent/lib/crm.ts@@ -144,7 +144,31 @@ export type CrmHistory = {email: string | null;title: string | null;companyName: string | null;+ /**+ * The company **id**, not just its name.+ *+ * Its absence was a real dead end: every company tool takes an id, this+ * was the only place a contact session could have learned one, and it+ * returned a display string. So an agent sitting on a contact who plainly+ * works somewhere reported that it had no company to look at.+ */+ company: {+ id: string;+ name: string;+ domain: string | null;+ industry: string | null;+ } | null;};+ /** The deals this person is attached to — the other way out of a contact. */+ deals: {+ id: string;+ name: string;+ stage: string;+ role: string | null;+ amount: number | null;+ currency: string;+ expectedCloseDate: string | null;+ }[];threads: {subject: string | null;messageCount: number;@@ -202,7 +226,25 @@ export async function readCrmHistory(email: true,title: true,companyId: true,- company: { select: { name: true } },+ company: {+ select: { id: true, name: true, domain: true, industry: true },+ },+ deals: {+ orderBy: { deal: { lastActivityAt: "desc" } },+ select: {+ role: true,+ deal: {+ select: {+ id: true,+ name: true,+ stage: true,+ amount: true,+ currency: true,+ expectedCloseDate: true,+ },+ },+ },+ },},});@@ -276,7 +318,17 @@ export async function readCrmHistory(email: contact.email,title: contact.title,companyName: contact.company?.name ?? null,+ company: contact.company,},+ deals: contact.deals.map(({ role, deal }) => ({+ id: deal.id,+ name: deal.name,+ stage: deal.stage,+ role,+ amount: deal.amount === null ? null : Number(deal.amount),+ currency: deal.currency,+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,+ })),threads: threads.map((thread) => ({subject: thread.subject,messageCount: thread.messageCount,diff --git a/apps/agent/agent/lib/enrichment.ts b/apps/agent/agent/lib/enrichment.tsnew file mode 100644index 00000000..44b8d3f0--- /dev/null+++ b/apps/agent/agent/lib/enrichment.ts@@ -0,0 +1,85 @@+import { db, EnrichmentStatus } from "@crm/db";+import type { TaskSubject } from "./tasks";++/**+ * The enrichment status on a record, driven by the task lifecycle.+ *+ * This exists because the previous arrangement asked the model to keep the+ * status honest and it could not. `enrich_company` writes RUNNING and COMPLETE+ * around its own vendor call, which is right as far as it goes — but a+ * `company-profile` session that answers without reaching for that tool leaves+ * the record saying PENDING with no work outstanding, and a contact had no+ * equivalent at all. `setEnrichmentStatus` was written for contacts and never+ * called from anywhere, so every contact in the database sat at PENDING from+ * the moment it was inserted, which the UI rendered as "Queued" forever.+ *+ * So the status follows the queue rather than the model's intentions: claimed+ * is RUNNING, parked is COMPLETE, given up on is FAILED. A tool that knows+ * something more specific still wins — see `UNSETTLED`.+ *+ * COMPLETE means *we looked and the run finished*, not *we found everything*.+ * That is already what `enrich_company` means by it: it settles COMPLETE even+ * when the vendor returned nothing new, with a note saying so.+ */++/**+ * Somebody is working on this now.+ *+ * Unconditional, and it has to be: a retry after a failed attempt is genuinely+ * running again, so gating this on the previous status would strand a record+ * on FAILED while a session was actively researching it.+ */+export async function markRunning(subject: TaskSubject): Promise<void> {+ await write(subject, EnrichmentStatus.RUNNING, null, false);+}++/**+ * Nobody is working on this any more, and here is how it ended.+ *+ * Only from RUNNING, which is what lets a tool win. A tool that reached a+ * terminal answer knows more than the queue does — that a company has no domain+ * to look up (SKIPPED), or that the vendor refused (FAILED, with the reason) —+ * and settling the task must not flatten those into a bland COMPLETE and lose+ * the message the rep would have read.+ */+export async function settle(+ subject: TaskSubject,+ status: EnrichmentStatus,+ error?: string,+): Promise<void> {+ await write(subject, status, error ?? null, true);+}++async function write(+ subject: TaskSubject,+ status: EnrichmentStatus,+ error: string | null,+ onlyIfRunning: boolean,+): Promise<void> {+ const data = {+ enrichmentStatus: status,+ enrichmentError: error,+ ...(status === EnrichmentStatus.COMPLETE ? { enrichedAt: new Date() } : {}),+ };++ const guard = onlyIfRunning+ ? { enrichmentStatus: EnrichmentStatus.RUNNING }+ : {};++ // `updateMany` for the status guard, and because a row can be deleted+ // between the dispatch and the session parking — a `update` would throw on+ // a record the rep removed while the agent was still reading about it.+ if (subject.contactId) {+ await db.contact.updateMany({+ where: { id: subject.contactId, ...guard },+ data,+ });+ }++ if (subject.companyId) {+ await db.company.updateMany({+ where: { id: subject.companyId, ...guard },+ data,+ });+ }+}diff --git a/apps/agent/agent/lib/lookup.ts b/apps/agent/agent/lib/lookup.tsnew file mode 100644index 00000000..85b551dd--- /dev/null+++ b/apps/agent/agent/lib/lookup.ts@@ -0,0 +1,299 @@+import { db } from "@crm/db";+import { domainOf, normalise } from "./names";++/**+ * Turning what a rep said into the record they meant.+ *+ * This is the gap that produced "I need an actual identifier: a contact's+ * name, email address, or a contact ID". The agent had a lookup by id and a+ * lookup by email and nothing that took the words a person would actually+ * type, so a rep sitting on the Comp AI record — with the answer on screen —+ * was asked to go and find a cuid.+ *+ * Free, local, and deliberately not clever: containment against the fields a+ * human would have searched, then a score that puts exact matches first. No+ * fuzzy distance, because "Northwind" matching "Northwind Savings Group" is+ * useful and "Marchetti" matching "Marchetta" is a wrong record in a CRM.+ * Ambiguity is returned, not resolved — four Marchettis is an answer.+ */++export type RecordKind = "contact" | "company" | "deal";++export type ContactHit = {+ kind: "contact";+ id: string;+ name: string;+ title: string | null;+ email: string | null;+ company: { id: string; name: string } | null;+ lastActivityAt: string | null;+};++export type CompanyHit = {+ kind: "company";+ id: string;+ name: string;+ domain: string | null;+ industry: string | null;+ contacts: number;+ deals: number;+};++export type DealHit = {+ kind: "deal";+ id: string;+ name: string;+ stage: string;+ amount: number | null;+ currency: string;+ company: { id: string; name: string };+};++export type SearchHit = ContactHit | CompanyHit | DealHit;++export type SearchResult = {+ query: string;+ contacts: ContactHit[];+ companies: CompanyHit[];+ deals: DealHit[];+ total: number;+};++/**+ * Everything in the CRM that could be what they meant.+ *+ * An address searches for the person who owns it *and* the company on its+ * domain, because "who is [email protected]" and "what is Fernhill" are the+ * same question asked from two ends.+ */+export async function searchCrm(+ query: string,+ options: { kinds?: RecordKind[]; limit?: number } = {},+): Promise<SearchResult> {+ const term = query.trim();+ const kinds = options.kinds ?? ["contact", "company", "deal"];+ const limit = options.limit ?? 10;++ if (term.length < 2) {+ return { query: term, contacts: [], companies: [], deals: [], total: 0 };+ }++ const wants = (kind: RecordKind) => kinds.includes(kind);+ const email = term.includes("@") ? term.toLowerCase() : null;+ // A bare domain is a company query in every case that matters: nobody types+ // "fernhill.com" hoping for a deal called Fernhill.com.+ const domain = email ? domainOf(email) : bareDomain(term);+ const words = term.split(/\s+/).filter((word) => word.length >= 2);++ const [contacts, companies, deals] = await Promise.all([+ wants("contact") ? searchContacts(term, words, email, limit) : [],+ wants("company") ? searchCompanies(term, words, domain, limit) : [],+ wants("deal") ? searchDeals(term, words, limit) : [],+ ]);++ return {+ query: term,+ contacts,+ companies,+ deals,+ total: contacts.length + companies.length + deals.length,+ };+}++async function searchContacts(+ term: string,+ words: string[],+ email: string | null,+ limit: number,+): Promise<ContactHit[]> {+ const contains = words.flatMap((word) => [+ { firstName: { contains: word, mode: "insensitive" as const } },+ { lastName: { contains: word, mode: "insensitive" as const } },+ { email: { contains: word, mode: "insensitive" as const } },+ ]);++ const rows = await db.contact.findMany({+ where: {+ OR: [+ ? [{ email: { equals: email, mode: "insensitive" as const } }]+ : []),+ ...contains,+ // The whole phrase against the company, so "Comp AI" finds the+ // people there rather than only a person called Comp.+ { company: { name: { contains: term, mode: "insensitive" as const } } },+ ],+ },+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "asc" }],+ take: limit * 3,+ select: {+ id: true,+ firstName: true,+ lastName: true,+ title: true,+ email: true,+ lastActivityAt: true,+ company: { select: { id: true, name: true } },+ },+ });++ return rows+ .map((row) => {+ const name = [row.firstName, row.lastName].filter(Boolean).join(" ");+ return {+ score: score(term, [name, row.email ?? "", row.company?.name ?? ""]),+ hit: {+ kind: "contact" as const,+ id: row.id,+ name,+ title: row.title,+ email: row.email,+ company: row.company,+ lastActivityAt: row.lastActivityAt?.toISOString() ?? null,+ },+ };+ })+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map((row) => row.hit);+}++async function searchCompanies(+ term: string,+ words: string[],+ domain: string | null,+ limit: number,+): Promise<CompanyHit[]> {+ const rows = await db.company.findMany({+ where: {+ OR: [+ { name: { contains: term, mode: "insensitive" } },+ ...(domain+ ? [{ domain: { contains: domain, mode: "insensitive" as const } }]+ : []),+ ...words.map((word) => ({+ name: { contains: word, mode: "insensitive" as const },+ })),+ ],+ },+ orderBy: [{ lastActivityAt: "desc" }, { name: "asc" }],+ take: limit * 3,+ select: {+ id: true,+ name: true,+ domain: true,+ industry: true,+ _count: { select: { contacts: true, deals: true } },+ },+ });++ return rows+ .map((row) => ({+ score: score(term, [row.name, row.domain ?? ""]),+ hit: {+ kind: "company" as const,+ id: row.id,+ name: row.name,+ domain: row.domain,+ industry: row.industry,+ contacts: row._count.contacts,+ deals: row._count.deals,+ },+ }))+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map((row) => row.hit);+}++async function searchDeals(+ term: string,+ words: string[],+ limit: number,+): Promise<DealHit[]> {+ const rows = await db.deal.findMany({+ where: {+ OR: [+ { name: { contains: term, mode: "insensitive" } },+ ...words.map((word) => ({+ name: { contains: word, mode: "insensitive" as const },+ })),+ { company: { name: { contains: term, mode: "insensitive" } } },+ ],+ },+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "desc" }],+ take: limit * 3,+ select: {+ id: true,+ name: true,+ stage: true,+ amount: true,+ currency: true,+ company: { select: { id: true, name: true } },+ },+ });++ return rows+ .map((row) => ({+ score: score(term, [row.name, row.company.name]),+ hit: {+ kind: "deal" as const,+ id: row.id,+ name: row.name,+ stage: row.stage,+ amount: row.amount === null ? null : Number(row.amount),+ currency: row.currency,+ company: row.company,+ },+ }))+ .sort((a, b) => b.score - a.score)+ .slice(0, limit)+ .map((row) => row.hit);+}++/**+ * How well a row answers the query: exact, then prefix, then containment, and+ * only then the individual words.+ *+ * The two tiers matter because the SQL above is an `OR` across every word — it+ * has to be, or "Paula Marchetti" would miss a contact filed as "P. Marchetti"+ * — which means a two-word query drags in everything matching either half.+ * Whole-phrase hits score at least 1 and word hits always score below it, so+ * the row a person meant is never buried under the rows that share a word with+ * it.+ *+ * Ordering happens here rather than in Postgres because the interesting rank+ * is across three tables, and `similarity()` would mean an extension a+ * self-hoster has to install. These result sets are tens of rows.+ */+function score(term: string, fields: string[]): number {+ const needle = normalise(term);+ if (!needle) return 0;++ let best = 0;+ for (const field of fields) {+ const hay = normalise(field);+ if (!hay) continue;+ if (hay === needle) best = Math.max(best, 4);+ else if (hay.startsWith(needle)) best = Math.max(best, 3);+ else if (hay.includes(needle)) best = Math.max(best, 2);+ }+ if (best > 0) return best;++ const words = term+ .split(/\s+/)+ .map(normalise)+ .filter((word) => word.length >= 2);+ if (words.length === 0) return 0;++ const hay = fields.map(normalise).join(" ");+ return words.filter((word) => hay.includes(word)).length / words.length;+}++/** `fernhill.com` → `fernhill.com`; `Fernhill` → null. */+function bareDomain(term: string): string | null {+ const candidate = term+ .trim()+ .toLowerCase()+ .replace(/^https?:\/\//, "");+ return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(candidate) ? candidate : null;+}diff --git a/apps/agent/agent/lib/preamble.ts b/apps/agent/agent/lib/preamble.tsnew file mode 100644index 00000000..895c15f8--- /dev/null+++ b/apps/agent/agent/lib/preamble.ts@@ -0,0 +1,362 @@+import { db } from "@crm/db";+import { capabilitiesMarkdown } from "./capabilities";++/**+ * What a session is told before it says anything.+ *+ * Two things vary, and both were getting the agent into trouble.+ *+ * **Which record.** A person, a company and a deal are three different+ * conversations. The company preamble used to say "we know 6 contact(s) here"+ * and could not name one of them, so the agent — knowing people existed and+ * having no way to address any of them — asked the rep to paste a contact id+ * off the screen they were looking at. Every neighbouring record is now named+ * **with its id**, because an id in the preamble is a tool call and a count is+ * a dead end.+ *+ * **Who opened it.** A dispatched task is a research pass with a budget. A rep+ * in the contact sheet is a conversation. Told neither, the agent assumed the+ * first, which is how a question got a work plan back.+ *+ * Pure apart from reading the database: the focus to seed is *returned* rather+ * than set, so `instructions/task.ts` owns that one side effect and these are+ * testable outside an eve turn.+ */++export type Opened = {+ /** Started by `schedules/dispatch.ts` rather than by a person. */+ dispatched: boolean;+ kind?: string | null;+ reason?: string | null;+ budget?: number | null;+};++export type Preamble = {+ markdown: string;+ /** What the audit hook should file this session's events against. */+ focus: { contactId?: string | null; companyId?: string | null };+};++/** The record the session was opened on, whichever it is. */+export async function sessionPreamble(+ record: {+ contactId?: string | null;+ companyId?: string | null;+ dealId?: string | null;+ },+ opened: Opened,+): Promise<Preamble> {+ if (record.contactId) return contactPreamble(record.contactId, opened);+ if (record.companyId) return companyPreamble(record.companyId, opened);+ if (record.dealId) return dealPreamble(record.dealId, opened);+ return noRecordPreamble();+}++/**+ * What kind of exchange this is, said in one line.+ *+ * The same record supports both, and they want opposite behaviour: a+ * dispatched pass should go and find things, a rep with the sheet open wants+ * the question in front of them answered from what we already have.+ */+function opening(opened: Opened, questions: string): string {+ if (opened.dispatched) {+ return [+ "This session was started by the dispatcher, not by a person. Nobody is",+ "waiting on a reply — do the work, record what you find, and stop.",+ ].join(" ");+ }++ return [+ "**A rep has this record open and is talking to you.** Answer what they",+ `actually asked — usually some form of ${questions} — from what the CRM`,+ "already holds, and say plainly when we do not know something. Research it",+ "further only if the answer needs it or they ask you to. Never ask them for",+ "an id, a name or an address you can look up yourself.",+ ].join(" ");+}++/**+ * A session opened from a person's record.+ *+ * Their company id is stated outright. Its absence was a dead end with a+ * confusing symptom: the agent could see where somebody worked, had no id to+ * pass to any company tool, and reported that no company was available — about+ * a contact who plainly had one.+ */+export async function contactPreamble(+ contactId: string,+ opened: Opened,+): Promise<Preamble> {+ const contact = await db.contact.findUnique({+ where: { id: contactId },+ select: {+ firstName: true,+ lastName: true,+ email: true,+ title: true,+ company: { select: { id: true, name: true, domain: true } },+ brief: { select: { refreshedAt: true } },+ deals: {+ orderBy: { deal: { lastActivityAt: "desc" } },+ take: 5,+ select: {+ role: true,+ deal: { select: { id: true, name: true, stage: true } },+ },+ },+ _count: { select: { emailThreads: true, calendarEvents: true } },+ },+ });++ if (!contact) {+ return { markdown: capabilitiesMarkdown(), focus: { contactId } };+ }++ const name = [contact.firstName, contact.lastName].filter(Boolean).join(" ");++ const known =+ contact._count.emailThreads > 0 || contact._count.calendarEvents > 0+ ? `We have ${contact._count.emailThreads} thread(s) and ${contact._count.calendarEvents} meeting(s) with them — read those first.`+ : "We have never corresponded with them, so there is nothing internal to go on.";++ const deals = contact.deals+ .map(+ ({ role, deal }) =>+ `${deal.name} (${deal.stage}${role ? `, ${role}` : ""}) \`${deal.id}\``,+ )+ .join("; ");++ const markdown = [+ "## This session",+ "",+ `You are working on **${name}** (\`${contactId}\`)${+ contact.email ? `, ${contact.email}` : ""+ }${contact.title ? `, ${contact.title}` : ""}.`,+ opened.kind ? `Task: **${opened.kind}**.` : "",+ opened.reason ? `Why now: ${opened.reason}` : "",+ opened.budget+ ? `Budget: **${opened.budget}** vendor calls. Spend them where they matter.`+ : "",+ "",+ opening(+ opened,+ "who this person is, whether they are still there, or what to know before a call",+ ),+ "",+ contact.company+ ? `They work at **${contact.company.name}**${+ contact.company.domain ? ` (${contact.company.domain})` : ""+ }, company id \`${contact.company.id}\` — pass that straight to \`read_company_history\`, \`enrich_company\` or \`research_company\` when the question reaches past this one person.`+ : "They are not attached to a company. `search_crm` will find one by name or domain if the conversation needs it.",+ deals ? `They are on: ${deals}.` : "They are not on any deal.",+ "",+ known,+ contact.brief+ ? `A background already exists, written ${contact.brief.refreshedAt.toDateString()}. Replace it only if you learn something it does not say.`+ : "There is no background on them yet.",+ "",+ "Start with `read_crm_history` on this contact id.",+ "",+ capabilitiesMarkdown(),+ ]+ .filter(Boolean)+ .join("\n");++ return {+ markdown,+ focus: { contactId, companyId: contact.company?.id ?? null },+ };+}++/**+ * A session opened from a company's record.+ *+ * The people are **named, with their ids**, which is the whole fix: a count+ * told the agent that contacts existed without letting it address one, so it+ * handed the CRM's own join back to the person using it.+ */+export async function companyPreamble(+ companyId: string,+ opened: Opened,+): Promise<Preamble> {+ const company = await db.company.findUnique({+ where: { id: companyId },+ select: {+ name: true,+ domain: true,+ industry: true,+ description: true,+ contacts: {+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "asc" }],+ take: 12,+ select: { id: true, firstName: true, lastName: true, title: true },+ },+ deals: {+ orderBy: [{ lastActivityAt: "desc" }, { createdAt: "desc" }],+ take: 8,+ select: { id: true, name: true, stage: true },+ },+ _count: { select: { contacts: true } },+ },+ });++ if (!company) {+ return { markdown: capabilitiesMarkdown(), focus: { companyId } };+ }++ const people = company.contacts+ .map((person) => {+ const name = [person.firstName, person.lastName]+ .filter(Boolean)+ .join(" ");+ return `- ${name}${person.title ? ` — ${person.title}` : ""} \`${person.id}\``;+ })+ .join("\n");++ const more =+ company._count.contacts > company.contacts.length+ ? `\n- …and ${company._count.contacts - company.contacts.length} more; \`read_company_history\` lists them all.`+ : "";++ const deals = company.deals+ .map((deal) => `${deal.name} (${deal.stage}) \`${deal.id}\``)+ .join("; ");++ const markdown = [+ "## This session",+ "",+ `You are working on **${company.name}**${+ company.domain ? ` (${company.domain})` : ""+ }${company.industry ? `, ${company.industry}` : ""} — company id \`${companyId}\`.`,+ "",+ opening(+ opened,+ "what this company does, who we know there, or what has changed recently",+ ),+ "",+ people+ ? `### Who we know there (${company._count.contacts})\n\n${people}${more}\n\nThose are contact ids. Use them directly — with \`read_crm_history\`, \`identify_contact\` or \`record_fact\`. Never ask a rep which contact they mean without naming these first.`+ : "We have no contacts on file here yet.",+ "",+ deals ? `Deals: ${deals}.` : "There are no deals here.",+ company.description+ ? "There is already a description on the record."+ : "There is no description on the record yet.",+ "",+ "Start with `read_company_history` on this company id — it returns the people, the deals, the correspondence and the notes in one free call.",+ "",+ capabilitiesMarkdown(),+ ]+ .filter(Boolean)+ .join("\n");++ return { markdown, focus: { companyId } };+}++/**+ * A session opened from a deal's record.+ *+ * A deal is the one record where the *state* matters as much as the facts:+ * which stage, how much, who is on it, and when it was last touched. Those are+ * the questions a rep opens a deal to ask, so they are what the session starts+ * knowing.+ */+export async function dealPreamble(+ dealId: string,+ opened: Opened,+): Promise<Preamble> {+ const deal = await db.deal.findUnique({+ where: { id: dealId },+ select: {+ name: true,+ stage: true,+ amount: true,+ currency: true,+ expectedCloseDate: true,+ lastActivityAt: true,+ company: { select: { id: true, name: true } },+ contacts: {+ select: {+ role: true,+ contact: {+ select: { id: true, firstName: true, lastName: true, title: true },+ },+ },+ },+ },+ });++ if (!deal) return { markdown: capabilitiesMarkdown(), focus: {} };++ const people = deal.contacts+ .map(({ role, contact }) => {+ const name = [contact.firstName, contact.lastName]+ .filter(Boolean)+ .join(" ");+ return `${name}${contact.title ? ` (${contact.title})` : ""}${+ role ? ` — ${role}` : ""+ } \`${contact.id}\``;+ })+ .join("; ");++ const markdown = [+ "## This session",+ "",+ `You are working on the deal **${deal.name}**${+ deal.company ? ` at ${deal.company.name}` : ""+ } — deal id \`${dealId}\`${+ deal.company ? `, company id \`${deal.company.id}\`` : ""+ }.`,+ `Stage: **${deal.stage}**${+ deal.amount+ ? `. Amount: ${deal.amount} ${deal.currency ?? ""}`.trim()+ : ""+ }${+ deal.expectedCloseDate+ ? `. Expected close: ${deal.expectedCloseDate.toDateString()}`+ : ""+ }.`,+ deal.lastActivityAt+ ? `Last touched ${deal.lastActivityAt.toDateString()}.`+ : "Nothing has happened on it yet.",+ people ? `People on it: ${people}` : "Nobody is attached to it yet.",+ "",+ opening(+ opened,+ "where this stands, who else should be involved, or what the risk is",+ ),+ "",+ "Start with `read_deal_history` on this deal id. It returns the stage clock, every stage this deal has moved through, the last reply from their side and the next meeting — which is how you answer *where does this stand* rather than reciting the stage field back.",+ "",+ "You can research the people and the company behind it with the usual tools — a deal itself has no fields to enrich, so anything you learn is recorded against them.",+ "",+ capabilitiesMarkdown(),+ ].join("\n");++ // Focused on the company, because that is the record every fact the agent+ // can write hangs off — a deal has no fields of its own to enrich.+ return { markdown, focus: { companyId: deal.company?.id ?? null } };+}++/**+ * No record at all — the dev TUI, or a dispatched pass over the queue.+ *+ * Worth saying rather than falling through to bare capabilities: without it+ * the agent has no idea the CRM is searchable, and waits to be handed an id.+ */+export function noRecordPreamble(): Preamble {+ return {+ markdown: [+ "## This session",+ "",+ "No record was named, so nothing is in focus yet.",+ "`list_outstanding_work` shows contacts with research outstanding, and",+ "`search_crm` finds any contact, company or deal by name, email address or",+ "domain. Look the record up rather than asking for an id.",+ "",+ capabilitiesMarkdown(),+ ].join("\n"),+ focus: {},+ };+}diff --git a/apps/agent/agent/lib/tasks.ts b/apps/agent/agent/lib/tasks.tsindex 3f95ea1f..4ecbad98 100644--- a/apps/agent/agent/lib/tasks.ts+++ b/apps/agent/agent/lib/tasks.ts@@ -16,11 +16,30 @@ export type LeasedTask = {kind: string;reason: string;budget: number;+ attempts: number;+};++/** The subject of a row, which is what an enrichment status hangs off. */+export type TaskSubject = {+ id: string;+ contactId: string | null;+ companyId: string | null;+ kind: string;};/** How long a dispatcher tick holds a row before another one may retry it. */const LEASE_MS = 10 * 60_000;+/**+ * How many hand-offs a row gets before it is given up on.+ *+ * The lease makes a crashed run recoverable; this makes an unrecoverable one+ * stop. Three is enough to ride out a redeploy and a transient vendor outage,+ * and small enough that a task which can never park costs three model turns+ * rather than one every ten minutes until somebody notices.+ */+export const MAX_ATTEMPTS = 3;+/*** Claims due work atomically.*@@ -32,6 +51,9 @@ const LEASE_MS = 10 * 60_000;** The lease is a deadline rather than a flag, so a run that crashes mid-task* frees itself. A `finishedAt` is what actually retires a row.+ *+ * Each claim charges an attempt. Rows that have spent their allowance are+ * skipped here and retired by `retireExhausted`.*/export async function claimDue(limit: number): Promise<LeasedTask[]> {const now = new Date();@@ -39,34 +61,101 @@ export async function claimDue(limit: number): Promise<LeasedTask[]> {return db.$queryRaw<LeasedTask[]>`UPDATE "agentTask" AS t- SET "leasedUntil" = ${until}, "startedAt" = COALESCE(t."startedAt", ${now})+ SET "leasedUntil" = ${until},+ "startedAt" = COALESCE(t."startedAt", ${now}),+ "attempts" = t."attempts" + 1FROM (SELECT id FROM "agentTask"WHERE "finishedAt" IS NULLAND "dueAt" <= ${now}AND ("leasedUntil" IS NULL OR "leasedUntil" < ${now})+ AND "attempts" < ${MAX_ATTEMPTS}ORDER BY "priority" DESC, "dueAt" ASCLIMIT ${limit}FOR UPDATE SKIP LOCKED) AS dueWHERE t.id = due.id- RETURNING t.id, t."contactId", t."companyId", t.kind, t.reason, t.budget;+ RETURNING t.id, t."contactId", t."companyId", t.kind, t.reason, t.budget, t.attempts;`;}+/**+ * Gives up on rows that have been dispatched their allowance without ever+ * reporting back, and hands them to the caller so the record can say so.+ *+ * Only unleased rows, so a run still legitimately in flight on its last+ * attempt is left alone.+ */+export async function retireExhausted(): Promise<TaskSubject[]> {+ const now = new Date();++ return db.$queryRaw<TaskSubject[]>`+ UPDATE "agentTask" AS t+ SET "finishedAt" = ${now},+ "outcome" = ${`Gave up after ${MAX_ATTEMPTS} attempts: the session never reported back.`}+ WHERE t."finishedAt" IS NULL+ AND t."attempts" >= ${MAX_ATTEMPTS}+ AND (t."leasedUntil" IS NULL OR t."leasedUntil" < ${now})+ RETURNING t.id, t."contactId", t."companyId", t.kind;+ `;+}++/**+ * Retires a row, once.+ *+ * The `finishedAt IS NULL` guard is what makes this idempotent: a session parks+ * at the end of every turn, and only the turn that belongs to this dispatch+ * should close the row. A second park — a rep carrying on the same thread from+ * the sheet, say — finds it already closed and returns null rather than+ * re-stamping an outcome over the real one.+ */export async function completeTask(taskId: string,outcome: string,sessionId?: string,-): Promise<void> {- await db.agentTask.update({- where: { id: taskId },+): Promise<TaskSubject | null> {+ const { count } = await db.agentTask.updateMany({+ where: { id: taskId, finishedAt: null },data: {finishedAt: new Date(),outcome: outcome.slice(0, 500),...(sessionId ? { sessionId } : {}),},});++ if (count === 0) return null;++ return db.agentTask.findUnique({+ where: { id: taskId },+ select: { id: true, contactId: true, companyId: true, kind: true },+ });+}++/** Who a row is about, without disturbing it. */+export async function taskSubject(+ taskId: string,+): Promise<TaskSubject | null> {+ return db.agentTask.findUnique({+ where: { id: taskId },+ select: { id: true, contactId: true, companyId: true, kind: true },+ });+}++/**+ * Records which durable session took the work.+ *+ * Written at hand-off rather than at completion, because `receive` resolves as+ * soon as the session accepts the message — the run itself outlives the+ * dispatcher tick that started it, and this is the only thread back to it.+ */+export async function noteSession(+ taskId: string,+ sessionId: string,+): Promise<void> {+ await db.agentTask.updateMany({+ where: { id: taskId, finishedAt: null },+ data: { sessionId },+ });}/**diff --git a/apps/agent/agent/schedules/dispatch.ts b/apps/agent/agent/schedules/dispatch.tsindex c3b6fd19..bf0151e2 100644--- a/apps/agent/agent/schedules/dispatch.ts+++ b/apps/agent/agent/schedules/dispatch.ts@@ -1,6 +1,8 @@+import { EnrichmentStatus } from "@crm/db";import { defineSchedule } from "eve/schedules";import crm from "../channels/crm";-import { claimDue, completeTask } from "../lib/tasks";+import { markRunning, settle } from "../lib/enrichment";+import { claimDue, noteSession, retireExhausted } from "../lib/tasks";/** Per tick. The cap is concurrency, not ambition — the queue keeps. */const BATCH = 5;@@ -26,13 +28,26 @@ export default defineSchedule({async run({ receive, waitUntil, appAuth }) {waitUntil((async () => {+ // Rows that spent their attempts without a session ever reporting+ // back. Retiring them before claiming keeps the sweep on the same+ // clock as the work rather than needing a schedule of its own.+ for (const abandoned of await retireExhausted()) {+ await settle(+ abandoned,+ EnrichmentStatus.FAILED,+ "Research was attempted several times and never completed.",+ );+ }+const tasks = await claimDue(BATCH);if (tasks.length === 0) return;await Promise.all(tasks.map(async (task) => {+ await markRunning(task);+try {- await receive(crm, {+ const session = await receive(crm, {message: brief(task),// The channel keys its continuation token off this, so a// re-dispatched lease resumes the run rather than starting@@ -53,14 +68,21 @@ export default defineSchedule({},});- await completeTask(task.id, "ran");+ // Hand-off, not completion: `receive` resolves the moment the+ // session accepts the message, and the run outlives this tick.+ // Retiring the row is the channel's `session.waiting` hook,+ // which fires when the turn is genuinely over. Completing here+ // instead would close rows before the research ran.+ await noteSession(task.id, session.id);} catch (error) {- // The lease expires on its own, so a failure here is a retry- // later rather than a row nobody ever picks up again.- await completeTask(- task.id,- `failed: ${error instanceof Error ? error.message : String(error)}`,- );+ const reason =+ error instanceof Error ? error.message : String(error);++ // A hand-off that threw never reached a session, so nothing+ // downstream will ever close this row. Leave it open for the+ // lease to re-offer, bounded by the attempt cap, and say on the+ // record why nothing is happening yet.+ await settle(task, EnrichmentStatus.FAILED, reason);}}),);@@ -82,8 +104,21 @@ function brief(task: {reason: string;contactId: string | null;companyId: string | null;+ attempts: number;}): string {- switch (task.kind) {+ // A retry resumes the same durable session, so the transcript is already+ // there — saying so is what stops it being read as a fresh identical request+ // and researched from scratch on somebody else's budget.+ const again =+ task.attempts > 1+ ? `This is attempt ${task.attempts}; the earlier one did not finish. Carry on from what is already in this thread rather than starting again. `+ : "";++ return again + work(task.kind, task.reason);+}++function work(kind: string, reason: string): string {+ switch (kind) {case "identify":return "Work out who this contact actually is, and record what you find. Read what we already have before spending anything.";case "profile":@@ -94,6 +129,6 @@ function brief(task: {case "company-profile":return "Fill in what we know about this company: brand, industry, location, links. Write a brief if there is something worth saying.";default:- return `Handle this: ${task.reason}`;+ return `Handle this: ${reason}`;}}diff --git a/apps/agent/agent/tools/read_company_history.ts b/apps/agent/agent/tools/read_company_history.tsnew file mode 100644index 00000000..fc542aab--- /dev/null+++ b/apps/agent/agent/tools/read_company_history.ts@@ -0,0 +1,55 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { readCompanyHistory } from "../lib/accounts";+import { focusOn } from "../lib/focus";++/**+ * The account, and everyone in it.+ *+ * The company equivalent of `read_crm_history`, and it exists because a+ * session opened on a company could count its contacts and not name one. The+ * agent's own words: "I don't have a tool that lists contacts by company, only+ * ones that look up a specific contact by ID or email" — so it asked the rep+ * to paste an id that the CRM had already joined for them.+ *+ * Free, like every read of our own database. It should be the first call in a+ * company session, and it is usually the last one needed: the people, the+ * deals, the correspondence and the notes come back together, each with the id+ * a follow-up tool wants.+ */+export default defineTool({+ description:+ "Read everything the CRM has on a company: every contact there with their id, title and whether we have heard from them; every deal with stage and value; recent email threads with full bodies; meetings; and notes. Free and fast — call it first in a company session, and whenever you need to find a person at a company you already know.",+ inputSchema: z.object({+ companyId: z.string(),+ threads: z+ .number()+ .int()+ .min(1)+ .max(20)+ .default(5)+ .describe("How many recent threads to read across the whole account."),+ people: z+ .number()+ .int()+ .min(1)+ .max(100)+ .default(25)+ .describe("How many contacts to list."),+ }),+ async execute({ companyId, threads, people }) {+ focusOn({ companyId });++ const history = await readCompanyHistory(companyId, { threads, people });+ if (!history) return { found: false as const, reason: "No such company." };++ return {+ found: true as const,+ ...history,+ note:+ history.people.length === 0+ ? "We have no contacts on file at this company, so there is nobody here to research yet."+ : "Every person above carries their contact id — use it directly with read_crm_history, identify_contact or record_fact. Never ask a rep for an id that is in this list.",+ };+ },+});diff --git a/apps/agent/agent/tools/read_crm_history.ts b/apps/agent/agent/tools/read_crm_history.tsindex 57436ade..706acd87 100644--- a/apps/agent/agent/tools/read_crm_history.ts+++ b/apps/agent/agent/tools/read_crm_history.ts@@ -19,7 +19,7 @@ import { focusOn } from "../lib/focus";*/export default defineTool({description:- "Read everything the CRM already has on a contact: email threads with full message bodies, meetings, whether they have ever replied, and who else we know at their company. Free, fast, and the best evidence there is — call it before paying for a lookup.",+ "Read everything the CRM already has on a contact: email threads with full message bodies, meetings, whether they have ever replied, their company and its id, the deals they are on, and who else we know at their company. Free, fast, and the best evidence there is — call it before paying for a lookup.",inputSchema: z.object({contactId: z.string(),threads: z@@ -36,13 +36,22 @@ export default defineTool({const history = await readCrmHistory(contactId, { threads });if (!history) return { found: false as const, reason: "No such contact." };+ const evidence =+ history.stats.emails === 0 && history.stats.meetings === 0+ ? "We have never actually spoken to this person. Nothing here is evidence of anything."+ : "A signature block or a reply from their own address is primary evidence — record it as `crm.signature-block` or `crm.thread-reply`.";++ // The ids are called out because the absence of one used to end the+ // conversation: an agent that could see `companyName` and no id would+ // report that there was no company to look at.+ const reach = history.contact.company+ ? ` Their company is \`${history.contact.company.id}\` — read_company_history or enrich_company take that id directly.`+ : " They are not attached to a company; search_crm will find one by name or domain if the question needs it.";+return {found: true as const,...history,- note:- history.stats.emails === 0 && history.stats.meetings === 0- ? "We have never actually spoken to this person. Nothing here is evidence of anything."- : "A signature block or a reply from their own address is primary evidence — record it as `crm.signature-block` or `crm.thread-reply`.",+ note: evidence + reach,};},});diff --git a/apps/agent/agent/tools/read_deal_history.ts b/apps/agent/agent/tools/read_deal_history.tsnew file mode 100644index 00000000..e586e2f9--- /dev/null+++ b/apps/agent/agent/tools/read_deal_history.ts@@ -0,0 +1,42 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { readDealHistory } from "../lib/accounts";+import { focusOn } from "../lib/focus";++/**+ * Where a deal stands, rather than what its stage field says.+ *+ * A stage is a rep's last opinion, entered by hand, and it goes stale in+ * exactly the situation somebody opens the record to ask about. This returns+ * the things that disagree with it: how long it has sat in that stage, when+ * anyone on the other side last replied, whether there is a meeting booked,+ * and every stage it moved through to get here.+ *+ * Free. Nothing here costs budget, and it is the only way to answer "where+ * does this stand?" without asking the rep who is asking.+ */+export default defineTool({+ description:+ "Read a deal in full: stage and how long it has been there, value, close date, the whole stage history, who is on it with their contact ids, the correspondence and meetings with those people, and the notes. Free — call it first in a deal session.",+ inputSchema: z.object({+ dealId: z.string(),+ threads: z+ .number()+ .int()+ .min(1)+ .max(20)+ .default(5)+ .describe("How many recent threads to read."),+ }),+ async execute({ dealId, threads }) {+ const history = await readDealHistory(dealId, { threads });+ if (!history) return { found: false as const, reason: "No such deal." };++ // A deal has no fields of its own to enrich, so anything learned here is+ // recorded against the company or the people on it — which is what the+ // focus has to point at for the audit trail to file it correctly.+ focusOn({ companyId: history.company.id });++ return { found: true as const, ...history };+ },+});diff --git a/apps/agent/agent/tools/search_crm.ts b/apps/agent/agent/tools/search_crm.tsnew file mode 100644index 00000000..d3e9c864--- /dev/null+++ b/apps/agent/agent/tools/search_crm.ts@@ -0,0 +1,47 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { searchCrm } from "../lib/lookup";++/**+ * Finding the record somebody meant.+ *+ * Every other CRM tool here takes an id, and until this existed there was no+ * way to obtain one except from a rep. So the agent asked — "could you paste+ * the contact's name or email address" — which is the CRM asking its user to+ * do a lookup on its behalf, from a screen that is already showing the answer.+ *+ * Free, local, and returns ambiguity rather than resolving it. Four people+ * called Marchetti come back as four rows with their titles and employers,+ * because choosing between them is a rep's three-second decision and a wrong+ * guess is a wrong record.+ */+export default defineTool({+ description:+ "Find contacts, companies and deals by name, email address, domain or deal name — the way a person would search. Returns each match with its id, so you never have to ask a rep for one. Free. Use it whenever a question names a record you do not have the id for.",+ inputSchema: z.object({+ query: z+ .string()+ .min(2)+ .describe(+ "A name, an email address, a domain, or part of one. 'Comp AI', 'marchetti', 'fernhill.com'.",+ ),+ kinds: z+ .array(z.enum(["contact", "company", "deal"]))+ .optional()+ .describe("Narrow the search. Defaults to all three."),+ limit: z.number().int().min(1).max(25).default(10),+ }),+ async execute({ query, kinds, limit }) {+ const result = await searchCrm(query, { kinds, limit });++ return {+ ...result,+ note:+ result.total === 0+ ? "Nothing in the CRM matches. That is an answer: say so rather than asking the rep to search for you. Try a shorter or differently spelled term first — a surname alone often works where a full name does not."+ : result.total > 1+ ? "More than one match. If it is genuinely ambiguous, name the candidates and ask which — never ask for an id."+ : undefined,+ };+ },+});diff --git a/apps/agent/test/accounts.integration.spec.ts b/apps/agent/test/accounts.integration.spec.tsnew file mode 100644index 00000000..404857db--- /dev/null+++ b/apps/agent/test/accounts.integration.spec.ts@@ -0,0 +1,332 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { ActivityType, DealStage, db, EmailDirection } from "@crm/db";+import { readCompanyHistory, readDealHistory } from "../agent/lib/accounts";++/**+ * The account reads, against a real database.+ *+ * These exist because of one sentence the agent said to a rep: "I don't have a+ * tool that lists contacts by company." The assertion that matters in here is+ * not the shape of the payload — it is that a company read comes back holding+ * the **ids** of the people at it, because that is the difference between the+ * agent answering and the agent asking the human to do a join.+ *+ * A real Postgres rather than a mock, for the same reason `facts` is: the+ * joins are the behaviour. A stubbed Prisma would happily return contacts for+ * a thread filter that matches nothing in practice.+ */++const suffix = process.env.TEST_RUN_ID ?? "accounts-spec";+const domain = `fernhill-${suffix}.test`;++let companyId: string;+let dealId: string;+let paulaId: string;+let placeholderId: string;+let userId: string;++const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000);+const daysAhead = (days: number) => new Date(Date.now() + days * 86_400_000);++beforeAll(async () => {+ await cleanup();++ // Better Auth mints user ids, so the column has no database default.+ const user = await db.user.create({+ data: {+ id: `user-${suffix}`,+ name: "Rep One",+ email: `rep.${suffix}@example.test`,+ emailVerified: true,+ },+ select: { id: true },+ });+ userId = user.id;++ const company = await db.company.create({+ data: {+ name: `Fernhill Systems ${suffix}`,+ domain,+ industry: "Security software",+ lastActivityAt: daysAgo(1),+ },+ select: { id: true },+ });+ companyId = company.id;++ const paula = await db.contact.create({+ data: {+ firstName: "Paula",+ lastName: "Marchetti",+ title: "Growth Specialist",+ email: `paula.marchetti@${domain}`,+ companyId,+ lastActivityAt: daysAgo(1),+ },+ select: { id: true },+ });+ paulaId = paula.id;++ // Named after their own address, which is what `needsIdentity` reports.+ const placeholder = await db.contact.create({+ data: {+ firstName: "Tsomerville",+ lastName: null,+ email: `tsomerville@${domain}`,+ companyId,+ lastActivityAt: daysAgo(30),+ },+ select: { id: true },+ });+ placeholderId = placeholder.id;++ const deal = await db.deal.create({+ data: {+ name: `Fernhill platform ${suffix}`,+ companyId,+ ownerId: userId,+ stage: DealStage.CONTRACT_SENT,+ stageChangedAt: daysAgo(42),+ amount: 48_000,+ currency: "USD",+ expectedCloseDate: daysAhead(14),+ lastActivityAt: daysAgo(3),+ contacts: { create: [{ contactId: paulaId, role: "Champion" }] },+ },+ select: { id: true },+ });+ dealId = deal.id;++ await db.activity.createMany({+ data: [+ {+ type: ActivityType.STAGE_CHANGE,+ subject: "Stage changed",+ companyId,+ dealId,+ createdById: userId,+ createdAt: daysAgo(60),+ meta: { from: "DEMO_BOOKED", to: "QUALIFIED_TO_BUY" },+ },+ {+ type: ActivityType.STAGE_CHANGE,+ subject: "Stage changed",+ companyId,+ dealId,+ createdById: userId,+ createdAt: daysAgo(42),+ meta: { from: "QUALIFIED_TO_BUY", to: "CONTRACT_SENT" },+ },+ {+ type: ActivityType.NOTE,+ subject: "Pricing pushback",+ body: "They want the security review done before signing.",+ occurredAt: daysAgo(5),+ companyId,+ dealId,+ createdById: userId,+ },+ // A projection of an email. It must not come back as a note as well.+ {+ type: ActivityType.EMAIL,+ subject: "Re: Contract",+ companyId,+ dealId,+ createdById: userId,+ },+ ],+ });++ const thread = await db.emailThread.create({+ data: {+ rootMessageId: `<root.${suffix}@example.test>`,+ subject: "Re: Contract",+ companyId,+ contactId: paulaId,+ firstMessageAt: daysAgo(9),+ lastMessageAt: daysAgo(3),+ messageCount: 2,+ },+ select: { id: true },+ });++ await db.emailMessage.createMany({+ data: [+ {+ threadId: thread.id,+ rfcMessageId: `<out.${suffix}@example.test>`,+ direction: EmailDirection.OUTBOUND,+ fromEmail: `rep.${suffix}@example.test`,+ recipients: [],+ subject: "Contract",+ body: "Sending the paperwork over.",+ sentAt: daysAgo(9),+ },+ {+ threadId: thread.id,+ rfcMessageId: `<in.${suffix}@example.test>`,+ direction: EmailDirection.INBOUND,+ fromEmail: `paula.marchetti@${domain}`,+ fromName: "Paula Marchetti",+ recipients: [],+ subject: "Re: Contract",+ body: "Thanks — Paula Marchetti, Growth Specialist, Fernhill.",+ sentAt: daysAgo(3),+ },+ ],+ });++ await db.calendarEvent.create({+ data: {+ iCalUid: `event.${suffix}@example.test`,+ originalStartTime: daysAhead(4),+ title: "Security review",+ startsAt: daysAhead(4),+ endsAt: daysAhead(4),+ status: "confirmed",+ companyId,+ contactId: paulaId,+ attendees: {+ create: [+ { email: `paula.marchetti@${domain}`, name: "Paula Marchetti" },+ ],+ },+ },+ });+});++afterAll(cleanup);++async function cleanup(): Promise<void> {+ const company = await db.company.findFirst({+ where: { domain },+ select: { id: true },+ });++ if (company) {+ await db.activity.deleteMany({ where: { companyId: company.id } });+ await db.calendarEvent.deleteMany({ where: { companyId: company.id } });+ await db.emailThread.deleteMany({ where: { companyId: company.id } });+ await db.deal.deleteMany({ where: { companyId: company.id } });+ await db.contact.deleteMany({ where: { companyId: company.id } });+ await db.company.delete({ where: { id: company.id } });+ }++ await db.user.deleteMany({ where: { email: `rep.${suffix}@example.test` } });+}++describe("readCompanyHistory", () => {+ it("names every contact at the company, with their id", async () => {+ const history = await readCompanyHistory(companyId);++ // The whole reason this function exists: the ids are in the payload, so+ // the agent never has to ask a rep for one.+ expect(history?.people.map((person) => person.id).sort()).toEqual(+ [paulaId, placeholderId].sort(),+ );+ expect(history?.people.find((person) => person.id === paulaId)?.title).toBe(+ "Growth Specialist",+ );+ });++ it("flags a contact still named after their email address", async () => {+ const history = await readCompanyHistory(companyId);+ const people = Object.fromEntries(+ (history?.people ?? []).map((person) => [+ person.id,+ person.needsIdentity,+ ]),+ );++ expect(people[placeholderId]).toBe(true);+ expect(people[paulaId]).toBe(false);+ });++ it("returns the deals with stage, value and who is on them", async () => {+ const history = await readCompanyHistory(companyId);+ const deal = history?.deals.find((row) => row.id === dealId);++ expect(deal?.stage).toBe("CONTRACT_SENT");+ expect(deal?.open).toBe(true);+ expect(deal?.amount).toBe(48_000);+ expect(deal?.contacts).toEqual([+ { id: paulaId, name: "Paula Marchetti", role: "Champion" },+ ]);+ expect(history?.stats.openDeals).toBe(1);+ });++ it("reads the correspondence and knows they replied", async () => {+ const history = await readCompanyHistory(companyId);++ expect(history?.threads[0]?.subject).toBe("Re: Contract");+ expect(history?.threads[0]?.contact?.id).toBe(paulaId);+ // Bodies, not snippets — a signature block is the best title evidence+ // there is, and it only exists in the body.+ expect(history?.threads[0]?.messages[0]?.body).toContain(+ "Growth Specialist",+ );+ expect(history?.stats.theyReplied).toBe(true);+ expect(history?.stats.lastReplyFrom).toBe("Paula Marchetti");+ expect(history?.stats.nextMeetingAt).not.toBeNull();+ });++ it("leaves email and meeting projections out of the notes", async () => {+ const history = await readCompanyHistory(companyId);++ expect(history?.notes.map((note) => note.subject)).toEqual([+ "Pricing pushback",+ ]);+ });++ it("returns null for a company that does not exist", async () => {+ expect(await readCompanyHistory("nope")).toBeNull();+ });+});++describe("readDealHistory", () => {+ it("reports the stage clock, not just the stage", async () => {+ const history = await readDealHistory(dealId);++ expect(history?.deal.stage).toBe("CONTRACT_SENT");+ expect(history?.deal.open).toBe(true);+ // Six weeks in contract-sent is the answer to "where does this stand",+ // and the stage field alone cannot say it.+ expect(history?.deal.daysInStage).toBeGreaterThanOrEqual(41);+ });++ it("returns every stage it moved through, oldest first", async () => {+ const history = await readDealHistory(dealId);++ expect(history?.stageHistory.map((change) => change.to)).toEqual([+ "QUALIFIED_TO_BUY",+ "CONTRACT_SENT",+ ]);+ });++ it("names who is on it, with ids and roles", async () => {+ const history = await readDealHistory(dealId);++ expect(history?.people).toEqual([+ {+ id: paulaId,+ name: "Paula Marchetti",+ title: "Growth Specialist",+ email: `paula.marchetti@${domain}`,+ role: "Champion",+ },+ ]);+ expect(history?.company.id).toBe(companyId);+ });++ it("says the correspondence is the account's, not the deal's", async () => {+ const history = await readDealHistory(dealId);++ expect(history?.threads).toHaveLength(1);+ expect(history?.stats.theyReplied).toBe(true);+ expect(history?.note).toContain("never against a deal");+ });++ it("returns null for a deal that does not exist", async () => {+ expect(await readDealHistory("nope")).toBeNull();+ });+});diff --git a/apps/agent/test/lookup.integration.spec.ts b/apps/agent/test/lookup.integration.spec.tsnew file mode 100644index 00000000..99193e8f--- /dev/null+++ b/apps/agent/test/lookup.integration.spec.ts@@ -0,0 +1,183 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { DealStage, db } from "@crm/db";+import { searchCrm } from "../agent/lib/lookup";++/**+ * Finding a record from what a person would type.+ *+ * The behaviour under test is the one whose absence was visible to a user: a+ * rep asked about "the Comp AI contact" and was told to paste an email+ * address, because every lookup the agent had took an id. Each case here is a+ * phrasing that has to resolve without help.+ */++const suffix = process.env.TEST_RUN_ID ?? "lookup-spec";+const domain = `northwind-${suffix}.test`;+const otherDomain = `brightwater-${suffix}.test`;++let northwindId: string;+let brightwaterId: string;+let paulaId: string;+let peterId: string;+let dealId: string;++beforeAll(async () => {+ await cleanup();++ const user = await db.user.create({+ data: {+ id: `user-${suffix}`,+ name: "Rep One",+ email: `rep.${suffix}@example.test`,+ emailVerified: true,+ },+ select: { id: true },+ });++ const northwind = await db.company.create({+ data: { name: `Northwind ${suffix}`, domain },+ select: { id: true },+ });+ northwindId = northwind.id;++ const brightwater = await db.company.create({+ data: { name: `Brightwater ${suffix}`, domain: otherDomain },+ select: { id: true },+ });+ brightwaterId = brightwater.id;++ // Two Marchettis at two companies: the ambiguity the tool is supposed to+ // hand back rather than resolve.+ const paula = await db.contact.create({+ data: {+ firstName: "Paula",+ lastName: "Marchetti",+ title: "Growth Specialist",+ email: `paula.marchetti@${domain}`,+ companyId: northwindId,+ lastActivityAt: new Date(),+ },+ select: { id: true },+ });+ paulaId = paula.id;++ const peter = await db.contact.create({+ data: {+ firstName: "Peter",+ lastName: "Marchetti",+ title: "Controller",+ email: `peter.marchetti@${otherDomain}`,+ companyId: brightwaterId,+ },+ select: { id: true },+ });+ peterId = peter.id;++ const deal = await db.deal.create({+ data: {+ name: `Northwind renewal ${suffix}`,+ companyId: northwindId,+ ownerId: user.id,+ stage: DealStage.QUALIFIED_TO_BUY,+ amount: 12_000,+ },+ select: { id: true },+ });+ dealId = deal.id;+});++afterAll(cleanup);++async function cleanup(): Promise<void> {+ const companies = await db.company.findMany({+ where: { domain: { in: [domain, otherDomain] } },+ select: { id: true },+ });+ const ids = companies.map((company) => company.id);++ if (ids.length > 0) {+ await db.activity.deleteMany({ where: { companyId: { in: ids } } });+ await db.deal.deleteMany({ where: { companyId: { in: ids } } });+ await db.contact.deleteMany({ where: { companyId: { in: ids } } });+ await db.company.deleteMany({ where: { id: { in: ids } } });+ }++ await db.user.deleteMany({ where: { email: `rep.${suffix}@example.test` } });+}++describe("searchCrm", () => {+ it("finds a company by name", async () => {+ const result = await searchCrm(`Northwind ${suffix}`);++ expect(result.companies[0]?.id).toBe(northwindId);+ expect(result.companies[0]?.contacts).toBe(1);+ });++ it("finds the people at a company named in the query", async () => {+ const result = await searchCrm(`Northwind ${suffix}`);++ // "the Comp AI contact", in the shape it actually arrives in. Naming the+ // employer has to reach the person, or the agent is back to asking.+ expect(result.contacts.map((hit) => hit.id)).toContain(paulaId);+ });++ it("returns both people behind an ambiguous surname", async () => {+ const result = await searchCrm("Marchetti");++ expect(result.contacts.map((hit) => hit.id).sort()).toEqual(+ [paulaId, peterId].sort(),+ );+ // Each carries what a rep needs to choose between them in one glance.+ expect(result.contacts.every((hit) => hit.company !== null)).toBe(true);+ expect(result.contacts.map((hit) => hit.title)).toContain("Controller");+ });++ it("finds a person by their address, and the company on its domain", async () => {+ const result = await searchCrm(`paula.marchetti@${domain}`);++ expect(result.contacts[0]?.id).toBe(paulaId);+ expect(result.companies[0]?.id).toBe(northwindId);+ });++ it("treats a bare domain as the company", async () => {+ const result = await searchCrm(domain);++ expect(result.companies[0]?.id).toBe(northwindId);+ });++ it("finds a deal by name", async () => {+ const result = await searchCrm(`Northwind renewal ${suffix}`);++ expect(result.deals[0]?.id).toBe(dealId);+ expect(result.deals[0]?.amount).toBe(12_000);+ });++ it("narrows to the kinds asked for", async () => {+ const result = await searchCrm(`Northwind ${suffix}`, {+ kinds: ["contact"],+ });++ expect(result.companies).toHaveLength(0);+ expect(result.deals).toHaveLength(0);+ expect(result.contacts.length).toBeGreaterThan(0);+ });++ it("finds nothing rather than guessing", async () => {+ const result = await searchCrm("zzyzxqqq");++ expect(result.total).toBe(0);+ });++ it("ranks a whole-phrase match above rows sharing only one word", async () => {+ const result = await searchCrm(`Paula Marchetti`);++ // The SQL is an OR across the words — it has to be, or a contact filed+ // as "P. Marchetti" would be missed — so Peter comes back too. He must+ // not come back first.+ expect(result.contacts[0]?.id).toBe(paulaId);+ });++ it("refuses a query too short to mean anything", async () => {+ expect((await searchCrm("a")).total).toBe(0);+ });+});diff --git a/apps/agent/test/preamble.integration.spec.ts b/apps/agent/test/preamble.integration.spec.tsnew file mode 100644index 00000000..4c9189f7--- /dev/null+++ b/apps/agent/test/preamble.integration.spec.ts@@ -0,0 +1,228 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { DealStage, db } from "@crm/db";+import {+ companyPreamble,+ contactPreamble,+ dealPreamble,+ noRecordPreamble,+ sessionPreamble,+} from "../agent/lib/preamble";++/**+ * What each kind of session is told before it speaks.+ *+ * Three records, three conversations — and the assertions that matter are the+ * ones about **ids**. A preamble that names a neighbouring record without its+ * id is the exact state the agent was in when it asked a rep to paste a+ * contact id off the screen in front of them, and when it reported that a+ * contact with an employer had no company available.+ */++const suffix = process.env.TEST_RUN_ID ?? "preamble-spec";+const domain = `fernhill-${suffix}.test`;++let companyId: string;+let dealId: string;+let paulaId: string;+let tomiId: string;++const rep = { dispatched: false };++beforeAll(async () => {+ await cleanup();++ const user = await db.user.create({+ data: {+ id: `user-${suffix}`,+ name: "Rep One",+ email: `rep.${suffix}@example.test`,+ emailVerified: true,+ },+ select: { id: true },+ });++ const company = await db.company.create({+ data: {+ name: `Fernhill Systems ${suffix}`,+ domain,+ industry: "Security software",+ },+ select: { id: true },+ });+ companyId = company.id;++ const paula = await db.contact.create({+ data: {+ firstName: "Paula",+ lastName: "Marchetti",+ title: "Growth Specialist",+ email: `paula.marchetti@${domain}`,+ companyId,+ lastActivityAt: new Date(),+ },+ select: { id: true },+ });+ paulaId = paula.id;++ const tomi = await db.contact.create({+ data: {+ firstName: "Tomi",+ lastName: "Okonkwo",+ title: "Head of Security",+ email: `tomi.okonkwo@${domain}`,+ companyId,+ },+ select: { id: true },+ });+ tomiId = tomi.id;++ const deal = await db.deal.create({+ data: {+ name: `Fernhill platform ${suffix}`,+ companyId,+ ownerId: user.id,+ stage: DealStage.CONTRACT_SENT,+ amount: 48_000,+ contacts: { create: [{ contactId: paulaId, role: "Champion" }] },+ },+ select: { id: true },+ });+ dealId = deal.id;+});++afterAll(cleanup);++async function cleanup(): Promise<void> {+ const company = await db.company.findFirst({+ where: { domain },+ select: { id: true },+ });++ if (company) {+ await db.activity.deleteMany({ where: { companyId: company.id } });+ await db.deal.deleteMany({ where: { companyId: company.id } });+ await db.contact.deleteMany({ where: { companyId: company.id } });+ await db.company.delete({ where: { id: company.id } });+ }++ await db.user.deleteMany({ where: { email: `rep.${suffix}@example.test` } });+}++describe("companyPreamble", () => {+ it("names every contact it lists, with their id", async () => {+ const { markdown } = await companyPreamble(companyId, rep);++ // The fix, stated as a test: the agent can address these people without+ // asking anyone for anything.+ expect(markdown).toContain(+ `Paula Marchetti — Growth Specialist \`${paulaId}\``,+ );+ expect(markdown).toContain(`Tomi Okonkwo — Head of Security \`${tomiId}\``);+ expect(markdown).toContain("Never ask a rep which contact they mean");+ });++ it("carries the deals and the company's own id", async () => {+ const { markdown, focus } = await companyPreamble(companyId, rep);++ expect(markdown).toContain(`company id \`${companyId}\``);+ expect(markdown).toContain(`(CONTRACT_SENT) \`${dealId}\``);+ expect(focus).toEqual({ companyId });+ });++ it("points at the company read, not the contact one", async () => {+ const { markdown } = await companyPreamble(companyId, rep);++ expect(markdown).toContain("Start with `read_company_history`");+ });+});++describe("contactPreamble", () => {+ it("states the company id, not just its name", async () => {+ const { markdown, focus } = await contactPreamble(paulaId, rep);++ // Without this the agent could see where somebody worked and still+ // report that there was no company available to look at.+ expect(markdown).toContain(`company id \`${companyId}\``);+ expect(focus).toEqual({ contactId: paulaId, companyId });+ });++ it("lists the deals they are on", async () => {+ const { markdown } = await contactPreamble(paulaId, rep);++ expect(markdown).toContain(`(CONTRACT_SENT, Champion) \`${dealId}\``);+ });++ it("offers a way out when they have no company", async () => {+ const orphan = await db.contact.create({+ data: { firstName: "Nobody", email: `nobody.${suffix}@example.test` },+ select: { id: true },+ });++ const { markdown } = await contactPreamble(orphan.id, rep);+ expect(markdown).toContain("`search_crm` will find one");++ await db.contact.delete({ where: { id: orphan.id } });+ });+});++describe("dealPreamble", () => {+ it("carries the deal, the company and the people, all with ids", async () => {+ const { markdown, focus } = await dealPreamble(dealId, rep);++ expect(markdown).toContain(`deal id \`${dealId}\``);+ expect(markdown).toContain(`company id \`${companyId}\``);+ expect(markdown).toContain(`Champion \`${paulaId}\``);+ // A deal has no fields of its own, so anything learned is filed against+ // the account.+ expect(focus).toEqual({ companyId });+ });+});++describe("who opened the session", () => {+ it("tells a rep's session to answer the question", async () => {+ const { markdown } = await companyPreamble(companyId, {+ dispatched: false,+ });++ expect(markdown).toContain("A rep has this record open");+ expect(markdown).not.toContain("Nobody is waiting on a reply");+ });++ it("tells a dispatched session to do the work and stop", async () => {+ const { markdown } = await companyPreamble(companyId, {+ dispatched: true,+ kind: "identity",+ });++ expect(markdown).toContain("Nobody is waiting on a reply");+ expect(markdown).not.toContain("A rep has this record open");+ });+});++describe("sessionPreamble", () => {+ it("routes each record kind to its own conversation", async () => {+ const contact = await sessionPreamble({ contactId: paulaId }, rep);+ const company = await sessionPreamble({ companyId }, rep);+ const deal = await sessionPreamble({ dealId }, rep);++ expect(contact.markdown).toContain("Start with `read_crm_history`");+ expect(company.markdown).toContain("Start with `read_company_history`");+ expect(deal.markdown).toContain("Start with `read_deal_history`");+ });++ it("prefers the contact when a session carries more than one id", async () => {+ const { markdown } = await sessionPreamble(+ { contactId: paulaId, companyId, dealId },+ rep,+ );++ expect(markdown).toContain("Start with `read_crm_history`");+ });++ it("tells a session with no record that the CRM is searchable", async () => {+ const { markdown } = await sessionPreamble({}, rep);++ expect(markdown).toBe(noRecordPreamble().markdown);+ expect(markdown).toContain("`search_crm`");+ });+});diff --git a/apps/agent/test/tasks.integration.spec.ts b/apps/agent/test/tasks.integration.spec.tsindex 4ead1ccf..786fbb13 100644--- a/apps/agent/test/tasks.integration.spec.ts+++ b/apps/agent/test/tasks.integration.spec.ts@@ -1,6 +1,12 @@import { afterEach, beforeEach, describe, expect, it } from "bun:test";import { db } from "@crm/db";-import { claimDue, completeTask, scheduleTask } from "../agent/lib/tasks";+import {+ claimDue,+ completeTask,+ MAX_ATTEMPTS,+ retireExhausted,+ scheduleTask,+} from "../agent/lib/tasks";/*** The work queue against a real database.@@ -14,13 +20,17 @@ import { claimDue, completeTask, scheduleTask } from "../agent/lib/tasks";const kind = "test-lease";async function clear() {+ // Tasks first: they reference the contacts below.await db.agentTask.deleteMany({ where: { kind } });+ await db.contact.deleteMany({ where: { email: { startsWith: "lease-" } } });}beforeEach(clear);afterEach(clear);-async function queue(overrides: { priority?: number; dueAt?: Date } = {}) {+async function queue(+ overrides: { priority?: number; dueAt?: Date; contactId?: string } = {},+) {return db.agentTask.create({data: {kind,@@ -28,6 +38,26 @@ async function queue(overrides: { priority?: number; dueAt?: Date } = {}) {dueAt: overrides.dueAt ?? new Date(Date.now() - 1000),priority: overrides.priority ?? 0,budget: 4,+ contactId: overrides.contactId ?? null,+ },+ select: { id: true },+ });+}++/** Frees a leased row the way a dispatcher dying mid-run would. */+async function expire(taskId: string) {+ await db.agentTask.update({+ where: { id: taskId },+ data: { leasedUntil: new Date(Date.now() - 1000) },+ });+}++/** A contact to hang a task off, so the subject can be asserted on. */+async function someone() {+ return db.contact.create({+ data: {+ firstName: "Lease",+ email: `lease-${crypto.randomUUID()}@example.test`,},select: { id: true },});@@ -87,6 +117,30 @@ describe("claimDue", () => {expect((await claimDue(10)).map((t) => t.id)).toContain(task.id);});+ /**+ * The money bug. Two rows were re-leased every ten minutes for an hour and a+ * half, resuming the same durable session and paying for a model turn each+ * time, because nothing counted how often that had already happened.+ */+ it("stops handing out a row that has spent its attempts", async () => {+ const task = await queue();++ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ expect((await claimDue(10)).map((t) => t.id)).toContain(task.id);+ await expire(task.id);+ }++ expect(await claimDue(10)).toHaveLength(0);+ });++ it("counts the attempts it has handed out", async () => {+ const task = await queue();++ expect((await claimDue(10))[0]?.attempts).toBe(1);+ await expire(task.id);+ expect((await claimDue(10))[0]?.attempts).toBe(2);+ });+it("stops claiming once the work is finished", async () => {const task = await queue();await claimDue(10);@@ -101,6 +155,64 @@ describe("claimDue", () => {});});+describe("retireExhausted", () => {+ it("gives up on a row that never reported back, and says who it was about", async () => {+ const contact = await someone();+ const task = await queue({ contactId: contact.id });++ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ await claimDue(10);+ await expire(task.id);+ }++ const retired = await retireExhausted();+ expect(retired.map((t) => t.id)).toContain(task.id);+ // The subject comes back so the caller can tell the record, rather than+ // leaving it saying somebody is still working on it.+ expect(retired.find((t) => t.id === task.id)?.contactId).toBe(contact.id);++ const row = await db.agentTask.findUnique({ where: { id: task.id } });+ expect(row?.finishedAt).not.toBeNull();+ expect(row?.outcome).toContain("Gave up");+ });++ it("leaves a row that is still leased on its last attempt alone", async () => {+ const task = await queue();++ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ await claimDue(10);+ if (attempt < MAX_ATTEMPTS - 1) await expire(task.id);+ }++ // Still holding a live lease: the run may yet park and close it itself.+ expect(await retireExhausted()).toHaveLength(0);+ });++ it("leaves work that still has attempts left", async () => {+ await queue();+ await claimDue(10);++ expect(await retireExhausted()).toHaveLength(0);+ });+});++describe("completeTask", () => {+ it("retires a row once, and reports who it was about", async () => {+ const contact = await someone();+ const task = await queue({ contactId: contact.id });+ await claimDue(10);++ const subject = await completeTask(task.id, "ran");+ expect(subject?.contactId).toBe(contact.id);++ // A session parks at the end of every turn. Only the turn that belongs to+ // this dispatch may close the row — a later one must not re-stamp it.+ expect(await completeTask(task.id, "ran again")).toBeNull();+ const row = await db.agentTask.findUnique({ where: { id: task.id } });+ expect(row?.outcome).toBe("ran");+ });+});+describe("scheduleTask", () => {it("books work with the agent's own reason", async () => {const dueAt = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000);diff --git a/apps/api/src/agent/agent-queue.service.ts b/apps/api/src/agent/agent-queue.service.tsnew file mode 100644index 00000000..9b4c675b--- /dev/null+++ b/apps/api/src/agent/agent-queue.service.ts@@ -0,0 +1,73 @@+import type { Db } from "@crm/db";+import { Injectable } from "@nestjs/common";+import { InjectDatabase } from "../database/database.constants";++/**+ * Whether a record has agent work outstanding.+ *+ * This exists because `enrichmentStatus` cannot answer the question and was+ * being asked it anyway. `PENDING` is the column's *default*, so every contact+ * and company carries it from the moment it is inserted — and the sheet+ * rendered that as "Queued", on 62 of 73 records against 3 rows in the queue.+ * A status that is true at birth says nothing about whether anybody intends to+ * do anything.+ *+ * Reading the queue is filing, not intelligence: it counts rows the agent+ * wrote and decides nothing about a person, so it belongs on this side of+ * `docs/api.md`'s line.+ */+@Injectable()+export class AgentQueueService {+ constructor(@InjectDatabase() private readonly db: Db) {}++ /** Of these companies, the ones with an unfinished task. */+ async queuedCompanies(ids: readonly string[]): Promise<Set<string>> {+ return this.queued("companyId", ids);+ }++ /** Of these contacts, the ones with an unfinished task. */+ async queuedContacts(ids: readonly string[]): Promise<Set<string>> {+ return this.queued("contactId", ids);+ }++ /** One record, for a detail view that has no list to batch with. */+ async isQueued(subject: {+ companyId?: string;+ contactId?: string;+ }): Promise<boolean> {+ const row = await this.db.agentTask.findFirst({+ where: {+ finishedAt: null,+ ...(subject.companyId ? { companyId: subject.companyId } : {}),+ ...(subject.contactId ? { contactId: subject.contactId } : {}),+ },+ select: { id: true },+ });++ return row !== null;+ }++ /**+ * One query for the whole page rather than one per row — a list of 50+ * companies is 50 lookups done the obvious way, on every keystroke of the+ * table's search box.+ */+ private async queued(+ column: "companyId" | "contactId",+ ids: readonly string[],+ ): Promise<Set<string>> {+ if (ids.length === 0) return new Set();++ const rows = await this.db.agentTask.findMany({+ where: { finishedAt: null, [column]: { in: [...ids] } },+ select: { [column]: true },+ distinct: [column],+ });++ return new Set(+ rows+ .map((row) => (row as Record<string, string | null>)[column])+ .filter((id): id is string => id !== null),+ );+ }+}diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.tsindex f1523c5e..29bc1e3f 100644--- a/apps/api/src/agent/agent.module.ts+++ b/apps/api/src/agent/agent.module.ts@@ -1,16 +1,18 @@import { Module } from "@nestjs/common";+import { AgentQueueService } from "./agent-queue.service";import { AgentTriggerService } from "./agent-trigger.service";/*** The API's entire relationship with the research agent.*- * One service, one verb: *this happened*. What replaced `EnrichmentModule` is- * smaller than the module docstring it replaced, which is the point — there is- * no queue here, no vendor client, and nothing that knows what a LinkedIn- * profile is.+ * Two services and two verbs: *this happened*, and *is anything outstanding*.+ * What replaced `EnrichmentModule` is smaller than the module docstring it+ * replaced, which is the point — there is no vendor client here, and nothing+ * that knows what a LinkedIn profile is. Writing a row saying a company was+ * created and counting the rows not yet done are both filing.*/@Module({- providers: [AgentTriggerService],- exports: [AgentTriggerService],+ providers: [AgentTriggerService, AgentQueueService],+ exports: [AgentTriggerService, AgentQueueService],})export class AgentModule {}diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex ebc68a8b..acf918ff 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -12,6 +12,7 @@ import {Logger,NotFoundException,} from "@nestjs/common";+import { AgentQueueService } from "../agent/agent-queue.service";import { AgentTriggerService } from "../agent/agent-trigger.service";import { blankToNull, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";@@ -51,6 +52,13 @@ export type CompanyRow = {brandColor: string | null;industry: string | null;enrichmentStatus: EnrichmentStatus;+ /**+ * Whether the agent actually has this company on its list.+ *+ * Separate from `enrichmentStatus` because that column defaults to PENDING+ * and so cannot tell "waiting its turn" from "nobody ever asked".+ */+ queued: boolean;source: RecordSource;owner: {id: string;@@ -97,6 +105,7 @@ export class CompaniesService {constructor(@InjectDatabase() private readonly db: Db,private readonly agent: AgentTriggerService,+ private readonly queue: AgentQueueService,) {}async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {@@ -138,6 +147,10 @@ export class CompaniesService {this.facetCounts(input),]);+ // After the page is known, so it is one query for the rows on screen+ // rather than a join that would have to be repeated for the facet counts.+ const queued = await this.queue.queuedCompanies(rows.map((row) => row.id));+return {rows: rows.map((row) => ({id: row.id,@@ -150,6 +163,7 @@ export class CompaniesService {brandColor: row.brandColor,industry: row.industry,enrichmentStatus: row.enrichmentStatus,+ queued: queued.has(row.id),source: row.source,owner: row.owner,contactCount: row._count.contacts,@@ -240,6 +254,7 @@ export class CompaniesService {return {...rest,+ queued: await this.queue.isQueued({ companyId: id }),createdAt: createdAt.toISOString(),enrichedAt: enrichedAt?.toISOString() ?? null,primaryContactId: primaryContact?.id ?? null,diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 75af00a7..3ae2eaca 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -13,6 +13,7 @@ import {Logger,NotFoundException,} from "@nestjs/common";+import { AgentQueueService } from "../agent/agent-queue.service";import { AgentTriggerService } from "../agent/agent-trigger.service";import { CompanyDirectoryService } from "../companies/company-directory.service";import { blankToNull, toCents } from "../crm/values";@@ -123,6 +124,7 @@ export class ContactsService {@InjectDatabase() private readonly db: Db,private readonly companies: CompanyDirectoryService,private readonly agent: AgentTriggerService,+ private readonly queue: AgentQueueService,) {}async list(input: ContactListInput): Promise<ListResult<ContactRow>> {@@ -247,6 +249,8 @@ export class ContactsService {return {...rest,company,+ /** Whether the agent has this person on its list — see `AgentQueueService`. */+ queued: await this.queue.isQueued({ contactId: id }),createdAt: createdAt.toISOString(),brief: brief? {diff --git a/apps/app/app/(app)/companies/companies-table.tsx b/apps/app/app/(app)/companies/companies-table.tsxindex 5f5b0eca..48f865d0 100644--- a/apps/app/app/(app)/companies/companies-table.tsx+++ b/apps/app/app/(app)/companies/companies-table.tsx@@ -137,7 +137,9 @@ const COLUMNS: DataTableColumn<CompanyRow>[] = [label: "Enrichment status",defaultHidden: true,width: "w-[14%]",- cell: (row) => <EnrichmentIndicator status={row.enrichmentStatus} />,+ cell: (row) => (+ <EnrichmentIndicator status={row.enrichmentStatus} queued={row.queued} />+ ),},];@@ -156,7 +158,9 @@ export function CompaniesTable() {// invalidate on. Ask while any row on this page is still working — a new// company's logo then lands in the table rather than waiting for a reload.refetchInterval: (query) =>- query.state.data?.rows.some((row) => isEnriching(row.enrichmentStatus))+ query.state.data?.rows.some((row) =>+ isEnriching(row.enrichmentStatus, row.queued),+ )? ENRICHMENT_POLL_MS: false,});diff --git a/apps/app/components/crm/enrichment-status.tsx b/apps/app/components/crm/enrichment-status.tsxindex abcddaf7..34efb692 100644--- a/apps/app/components/crm/enrichment-status.tsx+++ b/apps/app/components/crm/enrichment-status.tsx@@ -5,34 +5,50 @@ import {} from "@crm/ui/components/status-indicator";/**- * How the agent is getting on with a company.+ * How the agent is getting on with a record.** `SKIPPED` is neutral, not an error: there was nothing to find (an unknown* domain, a free email host), and no credits were spent. `FAILED` is the one* worth chasing.+ *+ * `PENDING` is the awkward one, and it is why this takes a `queued` flag. It is+ * the column's *default*, so it is true of every record from the moment it is+ * inserted — it means "no research has run", which is not the same as "research+ * is about to run". Rendering it unconditionally as "Queued" told every rep+ * that all 62 unenriched records were in a queue that held 3.*/const PRESENTATION: Record<EnrichmentStatus,{ label: string; tone: StatusTone; busy?: boolean }> = {- PENDING: { label: "Queued", tone: "neutral" },- RUNNING: { label: "Enriching", tone: "info", busy: true },+ PENDING: { label: "Not researched", tone: "neutral" },+ RUNNING: { label: "Researching", tone: "info", busy: true },COMPLETE: { label: "Enriched", tone: "success" },FAILED: { label: "Enrichment failed", tone: "error" },SKIPPED: { label: "Nothing found", tone: "neutral" },};+/** What `PENDING` becomes when the agent really does have the record on its list. */+const QUEUED = { label: "Queued", tone: "neutral" as StatusTone, busy: false };++function present(status: EnrichmentStatus, queued: boolean) {+ return status === "PENDING" && queued ? QUEUED : PRESENTATION[status];+}+export function EnrichmentIndicator({status,+ /** Whether an unfinished agent task names this record. */+ queued = false,/** The error, when there is one — shown on hover rather than in the row. */title,className,}: {status: EnrichmentStatus;+ queued?: boolean;title?: string | null;className?: string;}) {- const { label, tone, busy } = PRESENTATION[status];+ const { label, tone, busy } = present(status, queued);return (<StatusIndicator@@ -52,9 +68,13 @@ export function EnrichmentIndicator({* nothing to invalidate — the only way to notice it finished is to ask. Anything* rendering an enriched field (a logo, an industry) polls on this while it is* true and stops the moment it settles.+ *+ * `PENDING` alone is not enough to keep polling, and used to be: a contact+ * could never leave it, so every open contact sheet asked the server the same+ * question every three seconds until the tab was closed.*/-export function isEnriching(status: EnrichmentStatus): boolean {- return status === "PENDING" || status === "RUNNING";+export function isEnriching(status: EnrichmentStatus, queued = false): boolean {+ return status === "RUNNING" || (status === "PENDING" && queued);}/** How often to ask, in ms, while the agent is still working. */diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 34e96718..5a969a67 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -155,8 +155,10 @@ export function CompanySheet({ companyId }: { companyId: string }) {const query = useQuery({...trpc.companies.byId.queryOptions({ id: companyId }),refetchInterval: (current) => {- const status = current.state.data?.enrichmentStatus;- return status && isEnriching(status) ? ENRICHMENT_POLL_MS : false;+ const record = current.state.data;+ return record && isEnriching(record.enrichmentStatus, record.queued)+ ? ENRICHMENT_POLL_MS+ : false;},});@@ -251,6 +253,7 @@ export function CompanySheet({ companyId }: { companyId: string }) {company && company.enrichmentStatus !== "COMPLETE" ? (<EnrichmentIndicatorstatus={company.enrichmentStatus}+ queued={company.queued}title={company.enrichmentError}/>) : nulldiff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 956957c5..b60255e5 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -89,8 +89,10 @@ export function ContactSheet({ contactId }: { contactId: string }) {const query = useQuery({...trpc.contacts.byId.queryOptions({ id: contactId }),refetchInterval: (current) => {- const status = current.state.data?.enrichmentStatus;- return status && isEnriching(status) ? ENRICHMENT_POLL_MS : false;+ const record = current.state.data;+ return record && isEnriching(record.enrichmentStatus, record.queued)+ ? ENRICHMENT_POLL_MS+ : false;},});const contact = query.data;@@ -167,6 +169,7 @@ export function ContactSheet({ contactId }: { contactId: string }) {{contact.enrichmentStatus !== "COMPLETE" ? (<EnrichmentIndicatorstatus={contact.enrichmentStatus}+ queued={contact.queued}title={contact.enrichmentError}/>) : null}diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.tsindex 6436b555..8f415bce 100644--- a/apps/app/lib/agent-transcript.ts+++ b/apps/app/lib/agent-transcript.ts@@ -44,6 +44,9 @@ export type Source = {*/const VERBS: Record<string, string> = {read_crm_history: "Read our emails and meetings with them",+ read_company_history: "Read everything we have on the company",+ read_deal_history: "Read the deal and where it has been",+ search_crm: "Looked the record up in the CRM",resolve_linkedin_profile: "Searched for their LinkedIn profile",get_linkedin_profile: "Read a LinkedIn profile",get_contact_work_history: "Read their work history",diff --git a/docs/agent.md b/docs/agent.mdindex 94022f98..64786b92 100644--- a/docs/agent.md+++ b/docs/agent.md@@ -69,6 +69,67 @@ throw.`reason` is shown to the rep. An agent that cannot say why it will be back infourteen days does not have a reason, it has a default.+## Three records, and no dead ends between them++The CRM has contacts, companies and deals, and the agent is opened on any of+them. Every read hands back the **ids** of the neighbouring records, and that+rule is not decoration — the two worst answers this agent has given both came+from breaking it:++> I don't have a tool that lists contacts by company, only ones that look up a+> specific contact by ID or email. Could you paste the contact's name or email+> address?++Said to a rep who had the company open, with the contacts on screen. The+company preamble reported a *count* of contacts, the only read took a+`contactId`, and the agent correctly concluded it had nowhere to go. And, on a+contact who plainly worked somewhere, that no company was available: the+history returned `companyName`, a display string, while every company tool+takes an id.++So:++| Read | Free | Hands back |+| --- | --- | --- |+| `read_crm_history` | yes | the contact's **company id**, the deals they are on, their colleagues |+| `read_company_history` | yes | **every contact with their id**, every deal, the account's threads and meetings, the notes |+| `read_deal_history` | yes | the stage clock, every stage it moved through, the people on it with ids, the last reply |+| `search_crm` | yes | contacts, companies and deals matching what a person would type |++**A preamble or a tool result that names a record without its id is a bug**,+because the only recovery available to the agent is to ask the human — which is+the CRM handing its own join back to the person using it. Ambiguity is+different, and fine: four Marchettis come back as four rows with their titles,+and asking which one is a question rather than a chore.++`search_crm` deliberately does no fuzzy matching. "Northwind" reaching+"Northwind Savings Group" is useful; "Marchetti" reaching "Marchetta" is a+wrong record in a CRM, and a wrong record about a real person is the one+failure this whole design exists to prevent.++### A session is a conversation, and they are not all the same one++`lib/preamble.ts` builds what a session is told before it speaks, and it varies+on two axes:++- **Which record.** A person is asked who they are, a company what it does and+ who we know there, a deal where it stands. Each preamble names that record's+ neighbours, with ids, and points at the read to start from.+- **Who opened it.** A dispatched task is a research pass with a budget; a rep+ in the sheet is a conversation. Told neither, the agent assumed the first,+ which is how a question got a work plan back. `taskKind` is the tell — the+ dispatcher sets it and the panel never does.++The prose lives in `lib/preamble.ts` rather than in `instructions/task.ts` so+that `test/preamble.integration.spec.ts` can assert the thing that actually+matters: that a company session can name its own contacts. `task.ts` is the+resolver, and it owns the one side effect — seeding `lib/focus.ts`, without+which the audit hook files a session's events against nothing.++Adding a fourth record kind is an entry in `sessionPreamble`, a read beside the+other three, and a line in `TOOL_VERBS` (`apps/app/lib/agent-transcript.ts`),+which a test enforces so no tool ever shows a rep a bare slug.+## What the agent may read, and what may leaveIt may read **everything**, including full email bodies — single-tenant internaldiff --git a/packages/db/prisma/migrations/20260801190000_agent_task_attempts/migration.sql b/packages/db/prisma/migrations/20260801190000_agent_task_attempts/migration.sqlnew file mode 100644index 00000000..cd0eb94f--- /dev/null+++ b/packages/db/prisma/migrations/20260801190000_agent_task_attempts/migration.sql@@ -0,0 +1,12 @@+-- Bounded retries for the agent's work queue.+--+-- `leasedUntil` alone cannot distinguish a run that died (retry it) from one+-- that can never finish (stop). Rows in the second case were re-leased every+-- ten minutes indefinitely, resuming the same durable session and paying for a+-- model turn on each pass.+ALTER TABLE "agentTask" ADD COLUMN "attempts" INTEGER NOT NULL DEFAULT 0;++-- Existing open rows have already been dispatched at least once; several have+-- been dispatched many times. Seed them at 1 rather than 0 so the cap counts+-- from roughly where they actually are instead of granting a fresh allowance.+UPDATE "agentTask" SET "attempts" = 1 WHERE "startedAt" IS NOT NULL AND "finishedAt" IS NULL;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex a2231810..89054c19 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -412,6 +412,14 @@ model AgentTask {/// Research units this task may spend. Depth is a decision, and this is/// what the agent decides it against.budget Int @default(4)+ /// How many times this row has been handed to a session.+ ///+ /// The lease is a deadline rather than a flag so a crashed run frees its+ /// row — but a deadline alone cannot tell "died, retry me" from "cannot+ /// ever finish". Without a count the second case is re-leased every ten+ /// minutes forever, resuming the same durable session and paying for a+ /// model turn each time. Two rows did exactly that for an hour and a half.+ attempts Int @default(0)dueAt DateTime/// Held by a dispatcher tick. An expired lease is free to reclaim, which is