Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
fix: stop a finished enrichment reading as failed (#173)
Guzman Pintos2946580afdd4
diff --git a/apps/agent/agent/lib/brand.ts b/apps/agent/agent/lib/brand.tsindex d9b30a3a..fdd7740b 100644--- a/apps/agent/agent/lib/brand.ts+++ b/apps/agent/agent/lib/brand.ts@@ -2,6 +2,7 @@ import { db, EnrichmentStatus } from "@crm/db";import { mirrorBrandImages } from "./brand-images";import { brandToUpdate, filledFields, stillFillable } from "./brand-mapping";import { brandByDomain, contextDevEnabled } from "./context-dev";+import { UNLESS_COMPLETE } from "./enrichment";export type BrandResult = {enriched: boolean;@@ -65,15 +66,20 @@ export async function runBrand({}if (!company.domain) {- await settle(companyId, EnrichmentStatus.SKIPPED, "No domain to look up.");+ await settle(+ companyId,+ EnrichmentStatus.SKIPPED,+ "No domain to look up.",+ UNLESS_COMPLETE,+ );return { enriched: false, reason: "No domain on this company." };}const charge = spend(2);if (!charge.ok) return { enriched: false, reason: charge.reason };- await db.company.update({- where: { id: companyId },+ await db.company.updateMany({+ where: { id: companyId, ...UNLESS_COMPLETE },data: {enrichmentStatus: EnrichmentStatus.RUNNING,enrichmentError: null,@@ -157,13 +163,18 @@ export function brandOutcome(result: BrandResult): string {return `Filled ${filled.join(", ")}.${mirrored.length > 0 ? ` Copied ${mirrored.length} image(s) in-house.` : ""}`;}+type SettleGuard =+ | typeof UNLESS_COMPLETE+ | { enrichmentStatus: EnrichmentStatus };+async function settle(companyId: string,status: EnrichmentStatus,error: string,+ guard: SettleGuard = { enrichmentStatus: EnrichmentStatus.RUNNING },): Promise<void> {- await db.company.update({- where: { id: companyId },+ await db.company.updateMany({+ where: { id: companyId, ...guard },data: { enrichmentStatus: status, enrichmentError: error },});}diff --git a/apps/agent/agent/lib/enrichment.ts b/apps/agent/agent/lib/enrichment.tsindex 06efad02..5155f75e 100644--- a/apps/agent/agent/lib/enrichment.ts+++ b/apps/agent/agent/lib/enrichment.ts@@ -1,16 +1,46 @@import { db, EnrichmentStatus, type Prisma } from "@crm/db";+import { ownsCompanyStatus, ownsContactStatus } from "@crm/db/agent-tasks";import type { TaskSubject } from "./tasks";+type StatusGuard =+ | EnrichmentStatus+ | { not: EnrichmentStatus }+ | { in: EnrichmentStatus[] };+type SettleGuard = {- enrichmentStatus?: EnrichmentStatus;+ enrichmentStatus?: StatusGuard;OR?: Array<{enrichmentStatus: EnrichmentStatus;updatedAt?: { lt: Date };}>;};+type OwnedColumns = {+ contactId: string | null;+ companyId: string | null;+};++export const UNLESS_COMPLETE = {+ enrichmentStatus: { not: EnrichmentStatus.COMPLETE },+} as const;++function ownedColumns(subject: TaskSubject): OwnedColumns {+ return {+ contactId:+ subject.contactId && ownsContactStatus(subject.kind)+ ? subject.contactId+ : null,+ companyId:+ subject.companyId && ownsCompanyStatus(subject.kind)+ ? subject.companyId+ : null,+ };+}+export async function markRunning(subject: TaskSubject): Promise<void> {- await write(subject, EnrichmentStatus.RUNNING, null, false);+ await write(ownedColumns(subject), EnrichmentStatus.RUNNING, null, {+ ...UNLESS_COMPLETE,+ });}export async function settle(@@ -18,16 +48,19 @@ export async function settle(status: EnrichmentStatus,error?: string,): Promise<void> {- await write(subject, status, error ?? null, true);+ const owned = ownedColumns(subject);+ if (!owned.contactId && !owned.companyId) return;++ await write(owned, status, error ?? null, await settleable(subject, status));}async function write(- subject: TaskSubject,+ owned: OwnedColumns,status: EnrichmentStatus,error: string | null,- onlyIfRunning: boolean,+ guard: SettleGuard,): Promise<void> {- if (!subject.contactId && !subject.companyId) return;+ if (!owned.contactId && !owned.companyId) return;const data = {enrichmentStatus: status,@@ -35,20 +68,16 @@ async function write(enrichedAt: status === EnrichmentStatus.COMPLETE ? new Date() : undefined,};- const guard: SettleGuard = onlyIfRunning- ? await settleable(subject, status)- : {};-- if (subject.contactId) {+ if (owned.contactId) {await db.contact.updateMany({- where: { id: subject.contactId, ...guard },+ where: { id: owned.contactId, ...guard },data,});}- if (subject.companyId) {+ if (owned.companyId) {await db.company.updateMany({- where: { id: subject.companyId, ...guard },+ where: { id: owned.companyId, ...guard },data,});}@@ -59,6 +88,30 @@ async function settleable(status: EnrichmentStatus,): Promise<SettleGuard> {const running = { enrichmentStatus: EnrichmentStatus.RUNNING };++ if (status === EnrichmentStatus.COMPLETE) {+ const done = {+ enrichmentStatus: {+ in: [EnrichmentStatus.RUNNING, EnrichmentStatus.COMPLETE],+ },+ };++ const endedAt = await taskEndedAt(subject.id);+ if (!endedAt) return done;+ if (await hasOpenRequest(subject)) return done;++ return {+ OR: [+ running,+ { enrichmentStatus: EnrichmentStatus.COMPLETE },+ {+ enrichmentStatus: EnrichmentStatus.PENDING,+ updatedAt: { lt: endedAt },+ },+ ],+ };+ }+if (status !== EnrichmentStatus.FAILED) return running;const endedAt = await taskEndedAt(subject.id);diff --git a/apps/agent/agent/lib/stale-tasks.ts b/apps/agent/agent/lib/stale-tasks.tsindex e43dab47..c85d51fc 100644--- a/apps/agent/agent/lib/stale-tasks.ts+++ b/apps/agent/agent/lib/stale-tasks.ts@@ -1,5 +1,9 @@import { db, EnrichmentStatus, type Prisma } from "@crm/db";-import { isEnrichmentKind, MAX_ATTEMPTS } from "@crm/db/agent-tasks";+import {+ MAX_ATTEMPTS,+ ownsCompanyStatus,+ ownsContactStatus,+} from "@crm/db/agent-tasks";import { DISPATCH } from "./dispatch-config";import { settle } from "./enrichment";import { retireExhausted, type TaskSubject } from "./tasks";@@ -214,12 +218,16 @@ function finishedElsewhere(task: OpenTask,completed: Map<string, Date>,): boolean {- if (!isEnrichmentKind(task.kind)) return false;if (task.attempts === 0 || task.startedAt === null) return false;const subjectId = task.contactId ?? task.companyId;if (!subjectId) return false;+ const owns = task.contactId+ ? ownsContactStatus(task.kind)+ : ownsCompanyStatus(task.kind);+ if (!owns) return false;+const enrichedAt = completed.get(subjectId);if (!enrichedAt) return false;diff --git a/apps/agent/test/close-task.integration.spec.ts b/apps/agent/test/close-task.integration.spec.tsindex a92746df..08ef6080 100644--- a/apps/agent/test/close-task.integration.spec.ts+++ b/apps/agent/test/close-task.integration.spec.ts@@ -2,11 +2,15 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test";import { db, EnrichmentStatus } from "@crm/db";import { closeTask, taskToken } from "../agent/channels/crm";-const kind = "test-close-task";+const kind = "identify";const email = `close-task-${crypto.randomUUID()}@example.test`;+const taskIds: string[] = [];+async function clear() {- await db.agentTask.deleteMany({ where: { kind } });+ if (taskIds.length > 0) {+ await db.agentTask.deleteMany({ where: { id: { in: taskIds.splice(0) } } });+ }await db.contact.deleteMany({ where: { email } });}@@ -36,6 +40,8 @@ async function running() {select: { id: true },});+ taskIds.push(task.id);+return { contactId: contact.id, taskId: task.id };}diff --git a/apps/agent/test/enrichment.integration.spec.ts b/apps/agent/test/enrichment.integration.spec.tsindex 06eec5a0..3db33938 100644--- a/apps/agent/test/enrichment.integration.spec.ts+++ b/apps/agent/test/enrichment.integration.spec.ts@@ -35,7 +35,7 @@ async function contact() {function subjectOf(ids: { contactId?: string; companyId?: string }) {return {id: "task",- kind: "test",+ kind: ids.contactId ? "identify" : "brand",contactId: ids.contactId ?? null,companyId: ids.companyId ?? null,};@@ -258,4 +258,182 @@ describe("the record follows the task", () => {await settle(subject, EnrichmentStatus.COMPLETE);});++ it("leaves a company the brand task already finished alone", async () => {+ const org = await company();+ const brand = subjectOf({ companyId: org.id });++ await markRunning(brand);+ await settle(brand, EnrichmentStatus.COMPLETE);++ const profile = {+ ...brand,+ id: "company-profile",+ kind: "company-profile",+ };+ await markRunning(profile);++ const row = await db.company.findUnique({+ where: { id: org.id },+ select: { enrichmentStatus: true, enrichedAt: true },+ });+ expect(row?.enrichmentStatus).toBe("COMPLETE");+ expect(row?.enrichedAt).not.toBeNull();+ });++ it("still stamps the hour a recheck finished on a complete contact", async () => {+ const person = await contact();+ const identify = subjectOf({ contactId: person.id });++ await markRunning(identify);+ await settle(identify, EnrichmentStatus.COMPLETE);++ const first = await db.contact.findUniqueOrThrow({+ where: { id: person.id },+ select: { enrichedAt: true },+ });++ const recheck = { ...identify, id: "recheck", kind: "recheck" };+ await settle(recheck, EnrichmentStatus.COMPLETE);++ const second = await db.contact.findUniqueOrThrow({+ where: { id: person.id },+ select: { enrichmentStatus: true, enrichedAt: true },+ });+ expect(second.enrichmentStatus).toBe("COMPLETE");+ expect(second.enrichedAt?.getTime()).toBeGreaterThanOrEqual(+ first.enrichedAt?.getTime() ?? 0,+ );+ });++ it("lets a finished run land on the fresh look that asked for it", async () => {+ const person = await contact();++ const row = await db.contact.findUniqueOrThrow({+ where: { id: person.id },+ select: { updatedAt: true },+ });++ const task = await db.agentTask.create({+ data: {+ contactId: person.id,+ kind: "identify",+ reason: "lifecycle",+ attempts: 1,+ dueAt: row.updatedAt,+ finishedAt: new Date(row.updatedAt.getTime() + 1),+ },+ select: { id: true },+ });++ await settle(+ { ...subjectOf({ contactId: person.id }), id: task.id },+ EnrichmentStatus.COMPLETE,+ );++ const done = await statusOfContact(person.id);+ expect(done?.enrichmentStatus).toBe("COMPLETE");+ expect(done?.enrichedAt).not.toBeNull();+ });++ it("leaves a fresh look to the newer task a late run cannot satisfy", async () => {+ const person = await contact();++ const row = await db.contact.findUniqueOrThrow({+ where: { id: person.id },+ select: { updatedAt: true },+ });++ const ended = await db.agentTask.create({+ data: {+ contactId: person.id,+ kind: "identify",+ reason: "lifecycle",+ attempts: 1,+ dueAt: row.updatedAt,+ finishedAt: new Date(row.updatedAt.getTime() + 1),+ },+ select: { id: true },+ });++ await db.agentTask.create({+ data: {+ contactId: person.id,+ kind: "recheck",+ reason: "lifecycle",+ dueAt: new Date(),+ },+ select: { id: true },+ });++ await settle(+ { ...subjectOf({ contactId: person.id }), id: ended.id },+ EnrichmentStatus.COMPLETE,+ );++ expect((await statusOfContact(person.id))?.enrichmentStatus).toBe(+ "PENDING",+ );+ });++ it("never lets a company-profile session touch the company column", async () => {+ const org = await company();+ const brand = subjectOf({ companyId: org.id });++ await markRunning(brand);++ const profile = {+ ...brand,+ id: "company-profile",+ kind: "company-profile",+ };+ await settle(profile, EnrichmentStatus.FAILED, "the agent turn failed");++ const row = await db.company.findUnique({+ where: { id: org.id },+ select: { enrichmentStatus: true, enrichmentError: true },+ });+ expect(row?.enrichmentStatus).toBe("RUNNING");+ expect(row?.enrichmentError).toBeNull();+ });++ it("never lets a portrait timeout mark a person failed", async () => {+ const person = await contact();+ const identify = subjectOf({ contactId: person.id });++ await markRunning(identify);++ const portrait = { ...identify, id: "portrait", kind: "portrait" };+ await settle(portrait, EnrichmentStatus.FAILED, "the picture timed out");++ const row = await db.contact.findUnique({+ where: { id: person.id },+ select: { enrichmentStatus: true, enrichmentError: true },+ });+ expect(row?.enrichmentStatus).toBe("RUNNING");+ expect(row?.enrichmentError).toBeNull();+ });++ it("keeps that company complete when the later session fails", async () => {+ const org = await company();+ const brand = subjectOf({ companyId: org.id });++ await markRunning(brand);+ await settle(brand, EnrichmentStatus.COMPLETE);++ const profile = {+ ...brand,+ id: "company-profile",+ kind: "company-profile",+ };+ await markRunning(profile);+ await settle(profile, EnrichmentStatus.FAILED, "the agent turn failed");++ const row = await db.company.findUnique({+ where: { id: org.id },+ select: { enrichmentStatus: true, enrichmentError: true },+ });+ expect(row?.enrichmentStatus).toBe("COMPLETE");+ expect(row?.enrichmentError).toBeNull();+ });});diff --git a/apps/agent/test/keyless-brand.integration.spec.ts b/apps/agent/test/keyless-brand.integration.spec.tsindex 7b2902b3..d6487b6b 100644--- a/apps/agent/test/keyless-brand.integration.spec.ts+++ b/apps/agent/test/keyless-brand.integration.spec.ts@@ -1,5 +1,7 @@-import { afterEach, describe, expect, it } from "bun:test";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "bun:test";import { db, EnrichmentStatus } from "@crm/db";+import { readContextDevKey, writeContextDevKey } from "@crm/db/settings";+import { runBrand } from "../agent/lib/brand";import { settle } from "../agent/lib/enrichment";/**@@ -132,3 +134,48 @@ describe("a brand task with no key", () => {expect(await statusOf(id)).toBe(EnrichmentStatus.COMPLETE);});});++async function domainlessCompany(status: EnrichmentStatus) {+ const row = await db.company.create({+ data: {+ name: `Keyless Probe ${created.length}`,+ enrichmentStatus: status,+ },+ select: { id: true },+ });++ created.push(row.id);+ return row.id;+}++describe("a brand task on a company with no domain", () => {+ let key: string | null;++ beforeAll(async () => {+ key = await readContextDevKey(db);+ });++ afterAll(async () => {+ await writeContextDevKey(db, key ?? "");+ });++ it("marks the company skipped, because no sweep will find it again", async () => {+ await writeContextDevKey(db, "ctx-test-key");+ const id = await domainlessCompany(EnrichmentStatus.PENDING);++ const result = await runBrand({ companyId: id });++ expect(result.enriched).toBe(false);+ expect(await statusOf(id)).toBe(EnrichmentStatus.SKIPPED);+ });++ it("still leaves a keyless install's company pending for the sweep", async () => {+ await writeContextDevKey(db, "");+ const id = await domainlessCompany(EnrichmentStatus.PENDING);++ const result = await runBrand({ companyId: id });++ expect(result.enriched).toBe(false);+ expect(await statusOf(id)).toBe(EnrichmentStatus.PENDING);+ });+});diff --git a/apps/agent/test/stale-tasks.integration.spec.ts b/apps/agent/test/stale-tasks.integration.spec.tsindex 4bf530ae..adc78db1 100644--- a/apps/agent/test/stale-tasks.integration.spec.ts+++ b/apps/agent/test/stale-tasks.integration.spec.ts@@ -52,7 +52,7 @@ async function queue(overrides: {}) {return db.agentTask.create({data: {- kind: overrides.kind ?? kind,+ kind: overrides.kind ?? (overrides.companyId ? "brand" : kind),reason: REASON,dueAt: overrides.dueAt ?? new Date(Date.now() - MINUTE_MS),priority: 0,@@ -168,6 +168,48 @@ describe("a task whose record is already done", () => {expect(closed?.outcome).toContain("already up to date");});+ it("keeps research work on a company the brand task just finished", async () => {+ const account = await anAccount(+ EnrichmentStatus.COMPLETE,+ new Date(Date.now() - 29 * MINUTE_MS),+ );+ const task = await queue({+ kind: "company-profile",+ companyId: account.id,+ attempts: 1,+ startedAt: new Date(Date.now() - 30 * MINUTE_MS),+ leasedUntil: new Date(Date.now() - MINUTE_MS),+ });++ const sweep = await reconcileStaleTasks();+ expect(sweep.released).toBeGreaterThanOrEqual(1);++ const kept = await row(task.id);+ expect(kept?.finishedAt).toBeNull();+ expect(kept?.leasedUntil).toBeNull();+ });++ it("keeps meeting prep for a contact another task just enriched", async () => {+ const contact = await someone(+ EnrichmentStatus.COMPLETE,+ new Date(Date.now() - 29 * MINUTE_MS),+ );+ const task = await queue({+ kind: "meeting-prep",+ contactId: contact.id,+ attempts: 1,+ startedAt: new Date(Date.now() - 30 * MINUTE_MS),+ leasedUntil: new Date(Date.now() - MINUTE_MS),+ });++ const sweep = await reconcileStaleTasks();+ expect(sweep.released).toBeGreaterThanOrEqual(1);++ const kept = await row(task.id);+ expect(kept?.finishedAt).toBeNull();+ expect(kept?.leasedUntil).toBeNull();+ });+it("keeps event work that names a record the agent just enriched", async () => {const account = await anAccount(EnrichmentStatus.COMPLETE,diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.tsindex 4ef47b0f..3b214330 100644--- a/apps/api/src/agent/agent-trigger.service.ts+++ b/apps/api/src/agent/agent-trigger.service.ts@@ -71,22 +71,30 @@ export class AgentTriggerService {});}- async companyRequested(companyId: string, reason: string): Promise<void> {- await this.enqueue({- companyId,- kind: "brand",- reason,- priority: PRIORITY.brand,- budget: 2,- });+ async companyRequested(companyId: string, reason: string): Promise<boolean> {+ const brand = await this.enqueue(+ {+ companyId,+ kind: "brand",+ reason,+ priority: PRIORITY.brand,+ budget: 2,+ },+ true,+ );- await this.enqueue({- companyId,- kind: "company-profile",- reason,- priority: PRIORITY.requested,- budget: 8,- });+ const profile = await this.enqueue(+ {+ companyId,+ kind: "company-profile",+ reason,+ priority: PRIORITY.requested,+ budget: 8,+ },+ true,+ );++ return brand || profile;}async workspaceChanged(website: string, reason: string): Promise<void> {@@ -98,14 +106,21 @@ export class AgentTriggerService {});}- async contactCreated(contactId: string, reason: string): Promise<void> {- await this.enqueue({- contactId,- kind: "identify",- reason,- priority: PRIORITY.identify,- budget: 4,- });+ async contactCreated(+ contactId: string,+ reason: string,+ required = false,+ ): Promise<boolean> {+ return this.enqueue(+ {+ contactId,+ kind: "identify",+ reason,+ priority: PRIORITY.identify,+ budget: 4,+ },+ required,+ );}async slackPeopleRequested(reason: string, required = false): Promise<void> {diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.tsindex d90faf42..d2157334 100644--- a/apps/api/src/companies/companies.contracts.ts+++ b/apps/api/src/companies/companies.contracts.ts@@ -248,7 +248,7 @@ export const companyEnrichOutput = z.object({export const companyResearchOutput = z.object({ok: z.literal(true),- queued: z.literal(true),+ queued: z.boolean(),});export const companySetPrimaryContactOutput = z.object({diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex e9ec9d89..3960dc33 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -554,20 +554,26 @@ export class CompaniesService {async enrich(id: string): Promise<{ id: string; queued: boolean }> {const company = await this.db.company.findUnique({where: { id },- select: { id: true },+ select: { id: true, updatedAt: true },});if (!company) {throw new NotFoundException(`No company with id ${id}.`);}- await this.db.company.update({- where: { id },- data: { enrichmentStatus: "PENDING", enrichmentError: null },- });- await this.agent.companyRequested(id, "A rep asked for a fresh look");+ const queued = await this.agent.companyRequested(+ id,+ "A rep asked for a fresh look",+ );++ if (queued) {+ await this.db.company.updateMany({+ where: { id, updatedAt: company.updatedAt },+ data: { enrichmentStatus: "PENDING", enrichmentError: null },+ });+ }- return { id, queued: true };+ return { id, queued };}async research(id: string, actingUserId: string) {@@ -586,12 +592,12 @@ export class CompaniesService {);}- await this.agent.companyRequested(+ const queued = await this.agent.companyRequested(id,`Briefing requested by a rep (${actingUserId})`,);- return { ok: true as const, queued: true as const };+ return { ok: true as const, queued };}async setPrimaryContact(companyId: string, contactId: string | null) {diff --git a/apps/api/src/contacts/contacts.contracts.ts b/apps/api/src/contacts/contacts.contracts.tsindex c0d81ff8..78d0aeb1 100644--- a/apps/api/src/contacts/contacts.contracts.ts+++ b/apps/api/src/contacts/contacts.contracts.ts@@ -272,7 +272,7 @@ export const contactNameOutput = z.object({export const contactEnrichOutput = z.object({id: z.string(),- queued: z.literal(true),+ queued: z.boolean(),});export const bulkResultOutput = z.object({diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 3e1565f4..043fd4b7 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -671,29 +671,32 @@ export class ContactsService {};}- async enrich(id: string): Promise<{ id: string; queued: true }> {+ async enrich(id: string): Promise<{ id: string; queued: boolean }> {const contact = await this.db.contact.findUnique({where: { id },- select: { id: true, imageUrl: true, linkedinUrl: true },+ select: { id: true, imageUrl: true, linkedinUrl: true, updatedAt: true },});if (!contact) {throw new NotFoundException(`No contact with id ${id}.`);}- await this.db.contact.update({- where: { id },- data: { enrichmentStatus: "PENDING", enrichmentError: null },- });-- await this.agent.contactCreated(+ const queued = await this.agent.contactCreated(id,contact.linkedinUrl && !contact.imageUrl? "A rep asked for a fresh look — they have a LinkedIn profile on file but no picture": "A rep asked for a fresh look",+ true,);- return { id, queued: true };+ if (queued) {+ await this.db.contact.updateMany({+ where: { id, updatedAt: contact.updatedAt },+ data: { enrichmentStatus: "PENDING", enrichmentError: null },+ });+ }++ return { id, queued };}async decideFact(diff --git a/apps/api/test/bulk.spec.ts b/apps/api/test/bulk.spec.tsindex 3b887183..9a031518 100644--- a/apps/api/test/bulk.spec.ts+++ b/apps/api/test/bulk.spec.ts@@ -19,9 +19,9 @@ const secondOwnerId = `second-owner-${suffix}`;const ours = { OR: [{ email: { endsWith: `@${domain}` } }] };const agent = {- contactCreated: async () => undefined,+ contactCreated: async () => true,companyCreated: async () => undefined,- companyRequested: async () => undefined,+ companyRequested: async () => true,withCrmEvents: withDiscardedCrmEvents,} as unknown as AgentTriggerService;diff --git a/apps/api/test/company-requested.spec.ts b/apps/api/test/company-requested.spec.tsnew file mode 100644index 00000000..138a1d36--- /dev/null+++ b/apps/api/test/company-requested.spec.ts@@ -0,0 +1,54 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+import { AgentTriggerService } from "../src/agent/agent-trigger.service";++const suffix = process.env.TEST_RUN_ID ?? "company-requested-spec";+const name = `Requested Co ${suffix}`;+const reason = `A rep asked for a fresh look (${suffix})`;++const agent = new AgentTriggerService(db);++let companyId: string;+let bridgeSecret: string | undefined;++async function clean() {+ if (companyId) await db.agentTask.deleteMany({ where: { companyId } });+ await db.company.deleteMany({ where: { name } });+}++beforeAll(async () => {+ bridgeSecret = process.env.AGENT_BRIDGE_SECRET;+ process.env.AGENT_BRIDGE_SECRET = "";++ await db.company.deleteMany({ where: { name } });+ const company = await db.company.create({+ data: { name, domain: `requested-${suffix}.test`.toLowerCase() },+ select: { id: true },+ });+ companyId = company.id;+});++afterAll(async () => {+ await clean();++ if (bridgeSecret === undefined) {+ delete process.env.AGENT_BRIDGE_SECRET;+ } else {+ process.env.AGENT_BRIDGE_SECRET = bridgeSecret;+ }+});++describe("asking for a fresh look", () => {+ it("says what it actually queued", async () => {+ expect(await agent.companyRequested(companyId, reason)).toBe(true);++ expect(await agent.companyRequested(companyId, reason)).toBe(false);++ await db.agentTask.updateMany({+ where: { companyId, reason, finishedAt: null },+ data: { finishedAt: new Date(), outcome: "done" },+ });++ expect(await agent.companyRequested(companyId, reason)).toBe(true);+ });+});diff --git a/apps/api/test/fields.spec.ts b/apps/api/test/fields.spec.tsindex 73e83a1d..acecd137 100644--- a/apps/api/test/fields.spec.ts+++ b/apps/api/test/fields.spec.ts@@ -31,9 +31,9 @@ const queued: {}[] = [];const agent = {- contactCreated: async () => undefined,+ contactCreated: async () => true,companyCreated: async () => undefined,- companyRequested: async () => undefined,+ companyRequested: async () => true,withCrmEvents: withDiscardedCrmEvents,fieldBackfillRecords: async (entity: FieldEntity,diff --git a/apps/api/test/mailbox-thread-writer.spec.ts b/apps/api/test/mailbox-thread-writer.spec.tsindex 92ba96b9..da6b3486 100644--- a/apps/api/test/mailbox-thread-writer.spec.ts+++ b/apps/api/test/mailbox-thread-writer.spec.ts@@ -20,10 +20,10 @@ const rootId = `<root-${suffix}@mail.test>`;const movedRoot = `outlook-conversation:${suffix}`;const agent = {- contactCreated: async () => undefined,+ contactCreated: async () => true,companyCreated: async () => undefined,withCrmEvents: withDiscardedCrmEvents,- companyRequested: async () => undefined,+ companyRequested: async () => true,} as unknown as AgentTriggerService;const stamp = new ActivityStampService(db);diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.tsindex 244920a7..cac084ab 100644--- a/apps/api/test/record-delete.spec.ts+++ b/apps/api/test/record-delete.spec.ts@@ -25,10 +25,10 @@ const userId = `user-${suffix}`;const stamp = new ActivityStampService(db);const agent = {- contactCreated: async () => undefined,+ contactCreated: async () => true,companyCreated: async () => undefined,withCrmEvents: withDiscardedCrmEvents,- companyRequested: async () => undefined,+ companyRequested: async () => true,} as unknown as AgentTriggerService;const directory = new CompanyDirectoryService(agent);diff --git a/apps/api/test/tracking-filing.integration.spec.ts b/apps/api/test/tracking-filing.integration.spec.tsindex 2c152cb7..f9da0767 100644--- a/apps/api/test/tracking-filing.integration.spec.ts+++ b/apps/api/test/tracking-filing.integration.spec.ts@@ -28,9 +28,10 @@ const queued: string[] = [];const agent = {contactCreated: async (id: string) => {queued.push(id);+ return true;},companyCreated: async () => undefined,- companyRequested: async () => undefined,+ companyRequested: async () => true,withCrmEvents: withDiscardedCrmEvents,} as unknown as AgentTriggerService;diff --git a/apps/app/components/crm/enrichment-actions.tsx b/apps/app/components/crm/enrichment-actions.tsxindex 90c899d7..f7d10d30 100644--- a/apps/app/components/crm/enrichment-actions.tsx+++ b/apps/app/components/crm/enrichment-actions.tsx@@ -36,9 +36,13 @@ export function EnrichmentActions({const research = useMutation(trpc.companies.research.mutationOptions({- onSuccess: async () => {+ onSuccess: async (result) => {await cache.activity();- toast.success("Brief added to the timeline.");+ toast.success(+ result.queued+ ? "Researching — the brief lands on the timeline when it finishes."+ : "Already researching.",+ );},onError: (error) => toast.error(error.message),}),@@ -82,10 +86,12 @@ export function ContactEnrichmentAction({ contactId }: { contactId: string }) {const enrich = useMutation(trpc.contacts.enrich.mutationOptions({- onSuccess: async () => {+ onSuccess: async (result) => {await cache.contact(contactId);toast.success(- "Taking another look — this page will update when it finishes.",+ result.queued+ ? "Taking another look — this page will update when it finishes."+ : "Already running.",);},onError: (error) => toast.error(error.message),diff --git a/packages/db/src/agent-tasks.ts b/packages/db/src/agent-tasks.tsindex 4f65eec6..c7137ccf 100644--- a/packages/db/src/agent-tasks.ts+++ b/packages/db/src/agent-tasks.ts@@ -29,20 +29,16 @@ export function isDirectKind(kind: string): kind is DirectKind {return (DIRECT_KINDS as readonly string[]).includes(kind);}-export const ENRICHMENT_KINDS = [- "brand",- "portrait",- "identify",- "profile",- "recheck",- "company-profile",- "workspace-profile",-] as const;+export const CONTACT_STATUS_KINDS = ["identify", "profile", "recheck"] as const;-export type EnrichmentKind = (typeof ENRICHMENT_KINDS)[number];+export const COMPANY_STATUS_KINDS = ["brand"] as const;++export function ownsContactStatus(kind: string): boolean {+ return (CONTACT_STATUS_KINDS as readonly string[]).includes(kind);+}-export function isEnrichmentKind(kind: string): kind is EnrichmentKind {- return (ENRICHMENT_KINDS as readonly string[]).includes(kind);+export function ownsCompanyStatus(kind: string): boolean {+ return (COMPANY_STATUS_KINDS as readonly string[]).includes(kind);}export const MAX_ATTEMPTS = 3;