Skip to content

armgit / crm

Public Imported from GitHub
0

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

TypeScript

fix(agent): fill blank fields on the dispatch tick instead of sign-in (#117)

github-actions[bot]96609529f9f7
diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.ts
index 665438d8..43faef02 100644
--- a/apps/agent/agent/channels/crm.ts
+++ b/apps/agent/agent/channels/crm.ts
@@ -1,7 +1,6 @@
import { timingSafeEqual } from "node:crypto";
import { EnrichmentStatus } from "@crm/db";
import { defineChannel, POST } from "eve/channels";
-import { sweepBlankFacts } from "../lib/blank-facts";
import { verifyKey } from "../lib/context-dev";
import {
builderIdFromToken,
@@ -88,22 +87,6 @@ export default defineChannel({
},
),
- POST("/internal/crm/apply-blank-facts", async (request) => {
- if (!authorised(request)) {
- return new Response("Unauthorized", { status: 401 });
- }
-
- const sweep = await sweepBlankFacts();
-
- return Response.json({
- scanned: sweep.scanned,
- filled: sweep.filled,
- settled: sweep.settled,
- waiting: sweep.waiting,
- unscanned: sweep.unscanned,
- });
- }),
-
POST("/internal/crm/verify-key", async (request) => {
if (!authorised(request)) {
return new Response("Unauthorized", { status: 401 });
diff --git a/apps/agent/agent/schedules/dispatch.ts b/apps/agent/agent/schedules/dispatch.ts
index 4662099d..3032757e 100644
--- a/apps/agent/agent/schedules/dispatch.ts
+++ b/apps/agent/agent/schedules/dispatch.ts
@@ -1,5 +1,6 @@
import { defineSchedule } from "eve/schedules";
import crm from "../channels/crm";
+import { sweepBlankFacts } from "../lib/blank-facts";
import {
pendingAgentRunIds,
pendingBuilderSubmissionIds,
@@ -12,6 +13,8 @@ export default defineSchedule({
async run({ receive, waitUntil, appAuth }) {
waitUntil(
Promise.all([
+ sweepBlankFacts(),
+
drainAll((task) =>
receive(crm, {
message: brief(task),
diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.ts
index d0c489ae..2cdae2c2 100644
--- a/apps/api/src/agent/agent.module.ts
+++ b/apps/api/src/agent/agent.module.ts
@@ -6,7 +6,6 @@ import { AgentQueueService } from "./agent-queue.service";
import { AgentRunsService } from "./agent-runs.service";
import { AgentTriggerService } from "./agent-trigger.service";
import { AgentsRouter } from "./agents.router";
-import { BlankFactsService } from "./blank-facts.service";
import { ResearchKeyService } from "./research-key.service";
@Module({
@@ -18,14 +17,8 @@ import { ResearchKeyService } from "./research-key.service";
AgentRunsService,
AgentTriggerService,
AgentsRouter,
- BlankFactsService,
- ResearchKeyService,
- ],
- exports: [
- AgentTriggerService,
- AgentQueueService,
- BlankFactsService,
ResearchKeyService,
],
+ exports: [AgentTriggerService, AgentQueueService, ResearchKeyService],
})
export class AgentModule {}
diff --git a/apps/api/src/agent/blank-facts.service.ts b/apps/api/src/agent/blank-facts.service.ts
deleted file mode 100644
index bcd7786e..00000000
--- a/apps/api/src/agent/blank-facts.service.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { Injectable, Logger } from "@nestjs/common";
-import { bridge } from "./bridge";
-
-const SWEEP_TIMEOUT_MS = 60_000;
-
-export type BlankFactSweep = {
- scanned: number;
- filled: number;
- settled: number;
- waiting: number;
- unscanned: number;
-};
-
-const NOTHING: BlankFactSweep = {
- scanned: 0,
- filled: 0,
- settled: 0,
- waiting: 0,
- unscanned: 0,
-};
-
-/**
- * Applying a suggestion to a field nobody has filled is the agent's rule, in
- * the agent's code — `fillsBlank` knows what a human owns and what a derived
- * name is, and a second copy of that here is the thing `docs/api.md` forbids.
- * So this asks, and reports what came back.
- */
-@Injectable()
-export class BlankFactsService {
- private readonly logger = new Logger(BlankFactsService.name);
-
- async sweep(): Promise<BlankFactSweep> {
- const agent = bridge();
- if (!agent) return NOTHING;
-
- try {
- const response = await fetch(
- agent.url("/internal/crm/apply-blank-facts"),
- {
- method: "POST",
- headers: { authorization: `Bearer ${agent.secret}` },
- signal: AbortSignal.timeout(SWEEP_TIMEOUT_MS),
- },
- );
-
- if (!response.ok) {
- this.unreachable(`The agent answered ${response.status}.`);
- return NOTHING;
- }
-
- return { ...NOTHING, ...((await response.json()) as BlankFactSweep) };
- } catch (error) {
- this.unreachable(error instanceof Error ? error.message : String(error));
- return NOTHING;
- }
- }
-
- private unreachable(reason: string): void {
- this.logger.warn({
- message: "Could not apply suggestions to empty fields",
- reason,
- });
- }
-}
diff --git a/apps/api/src/backfill/backfill.service.ts b/apps/api/src/backfill/backfill.service.ts
index 33fcc07d..8f4b9607 100644
--- a/apps/api/src/backfill/backfill.service.ts
+++ b/apps/api/src/backfill/backfill.service.ts
@@ -6,7 +6,6 @@ import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Inject, Injectable, Logger, type OnModuleInit } from "@nestjs/common";
import type { Cache } from "cache-manager";
import { AgentTriggerService } from "../agent/agent-trigger.service";
-import { BlankFactsService } from "../agent/blank-facts.service";
import { FaviconService } from "../companies/favicon.service";
import { InjectDatabase } from "../database/database.constants";
import { ImageMirrorService } from "./image-mirror.service";
@@ -54,7 +53,6 @@ export class BackfillService implements OnModuleInit {
private readonly agent: AgentTriggerService,
private readonly favicon: FaviconService,
private readonly images: ImageMirrorService,
- private readonly facts: BlankFactsService,
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
@@ -76,7 +74,6 @@ export class BackfillService implements OnModuleInit {
const contacts = await this.runContacts();
const mirrored = await this.images.sweep();
- const facts = await this.facts.sweep();
this.logger.log({
message: "Automatic backfill swept",
@@ -84,9 +81,6 @@ export class BackfillService implements OnModuleInit {
remaining: companies.remaining + contacts.remaining,
iconsResolving: companies.iconsResolving,
imagesMirrored: mirrored.copied,
- blankFieldsFilled: facts.filled,
- suggestionsSettled: facts.settled,
- suggestionsWaiting: facts.waiting + facts.unscanned,
});
} catch (error) {
this.logger.error(
diff --git a/docs/agent.md b/docs/agent.md
index 639422d5..79d7f4c8 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -89,29 +89,34 @@ task row; exists because the API may not call Context.
- **`classifyKey` rejects on `401` and nothing else.**
- **The candidate key, never the stored one.**
-### `POST /internal/crm/apply-blank-facts`
-
-Applies every pending suggestion whose field is still empty, and clears the ones that
-have stopped saying anything. No session, no model, no task row, no credits —
-`sweepBlankFacts` (`lib/blank-facts.ts`) is a database pass. It exists as a route for
-the same reason `verify-key` does: the rule is `fillsBlank`, the rule lives here, and a
-second copy of it in Nest is what `api.md` forbids. `BlankFactsService` carries the
-question and reports the counts.
-
-- **Scans 2000 suggestions and fills at most 500 a pass**, and says what it did not
- reach (`unscanned`) rather than reporting a clean sweep it did not make.
-- **Idempotent** — a second pass over the same rows fills nothing, because they are no
- longer blank.
-- **The suggestions left are conflicts**, every one of them against a value already on
- the record. That number should be small and should be read as work for a rep.
+### Blank fields are filled on the dispatch tick
+
+`sweepBlankFacts` (`lib/blank-facts.ts`) applies every pending suggestion whose field is
+still empty and clears the ones that have stopped saying anything. It runs at the top of
+`schedules/dispatch.ts`, every minute, over **every contact in the workspace** — it is a
+database pass with no session, no model, no task row and no credits, so there is nothing
+to ration and nobody to scope it to.
+
+- **Scans 2000 suggestions and fills at most 500 a pass**, and reports what it did not
+ reach (`unscanned`) rather than a clean sweep it did not make.
+- **Idempotent** — a second pass fills nothing, because those fields are no longer blank.
+- **The suggestions left are conflicts**, every one against a value already on the
+ record. That number should stay small and reads as work for a rep.
+- **It does not belong on sign-in, and that is not a preference.** It lived there for one
+ release and never once ran. Two reasons, either fatal: `onSignedIn` fires on
+ `session.create`, so a rep already signed in never triggers it; and `BackfillService`
+ does its work in a detached `void (async () => …)()` after the response, on a Nest API
+ that is a Vercel **serverless function** (`apps/api/api/index.ts`) — the tail of that
+ chain is not guaranteed to run at all. A cron in the agent is the only trigger here
+ that is a fact rather than a hope.
### Backfills
Sign-in sweep covers records never looked up (10 credits/company);
`ImageMirrorService` in the same sweep re-hosts off-site pictures (free);
-the same sweep asks `apply-blank-facts` above (free);
`backfill:images` fixes enriched records missing only pictures (free);
-`backfill:facts` is the same fact sweep run by hand, with `--dry` to read it first.
+`backfill:facts` is the blank-field sweep above run by hand, with `--dry` to read it
+first — the cron covers it, so this is for a machine pointed at another database.
- **The image sweep keeps "every picture is ours" true**, not true-since-Tuesday.
25 rows/table/sweep.
@@ -144,9 +149,8 @@ wrong in the direction that looks useful.
into a blank is a click that can only say yes, and a rep with four hundred contacts
reads none of them. `fillsBlank` is the whole rule: no human value in the way and
nothing already found. **`PROBABLE` still means *a rep decides* when the field is
- already filled**, which is the case where a wrong answer costs something. The sign-in
- sweep applies the same rule to rows that predate it —
- `POST /internal/crm/apply-blank-facts`, above.
+ already filled**, which is the case where a wrong answer costs something. The dispatch
+ tick applies the same rule to rows that predate it — `sweepBlankFacts`, above.
- **Applying settles the field's other suggestions.** They were all offers to fill the
same blank, and the sheet shows one at a time — so left alone, accepting one reveals
the next, forever. The same rule holds when a rep accepts one (`decideFact`).