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

feat(api): enhance onboarding and research key handling

Lewis Carhartf1d133213042
diff --git a/README.md b/README.md
index 65023907..1c53d2fe 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,10 @@
<p align="center">
- <a href="https://link.context.dev/crm"><img alt="Context" height="18" align="middle" src="./docs/images/context.png"></a>
- &nbsp;<a href="https://link.context.dev/crm"><strong>Powered by Context</strong></a>
+ <a href="https://link.context.dev/crm">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="./docs/images/powered-by-context-dark.png">
+ <img alt="Powered by Context" height="23" src="./docs/images/powered-by-context.png">
+ </picture>
+ </a>
</p>
<h1 align="center">CRM</h1>
diff --git a/apps/agent/.scratch/skip.ts b/apps/agent/.scratch/skip.ts
new file mode 100644
index 00000000..da180db3
--- /dev/null
+++ b/apps/agent/.scratch/skip.ts
@@ -0,0 +1,30 @@
+import { db, EnrichmentStatus } from "@crm/db";
+import { settle } from "../agent/lib/enrichment";
+
+const company = await db.company.create({
+ data: {
+ name: "Settle Probe",
+ domain: "settle-probe.test",
+ enrichmentStatus: EnrichmentStatus.PENDING,
+ },
+ select: { id: true, enrichmentStatus: true },
+});
+console.log("created ", company.enrichmentStatus);
+
+// Exactly what runBrand does when there is no key: settle before anything marks it RUNNING.
+await settle({ companyId: company.id }, EnrichmentStatus.SKIPPED, "no key");
+
+const after = await db.company.findUnique({
+ where: { id: company.id },
+ select: { enrichmentStatus: true },
+});
+console.log("after settle(SKIP) ", after?.enrichmentStatus);
+console.log(
+ "swept again? ",
+ after?.enrichmentStatus === "PENDING"
+ ? "YES — sweep re-queues PENDING"
+ : "NO — stuck",
+);
+
+await db.company.delete({ where: { id: company.id } });
+await db.$disconnect();
diff --git a/apps/agent/test/keyless-brand.integration.spec.ts b/apps/agent/test/keyless-brand.integration.spec.ts
new file mode 100644
index 00000000..31512c0e
--- /dev/null
+++ b/apps/agent/test/keyless-brand.integration.spec.ts
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, it } from "bun:test";
+import { db, EnrichmentStatus } from "@crm/db";
+import { settle } from "../agent/lib/enrichment";
+
+/**
+ * An install with no Context key still creates companies, and a `brand` task
+ * with nowhere to look is consumed and marked done. What must survive that is
+ * the *record*: the sign-in sweep re-queues companies whose enrichment never
+ * succeeded, and it decides that on `enrichmentStatus` being PENDING or FAILED.
+ *
+ * `runBrand` settles SKIPPED before anything marks the row RUNNING, and
+ * `settle` only writes over a RUNNING row — so the row stays PENDING and the
+ * sweep picks it up once a key exists. That is load bearing and entirely
+ * implicit, which is why it is pinned here: a `settle` that wrote
+ * unconditionally would strand every company added before the key, with
+ * nothing to say so.
+ */
+const created: string[] = [];
+
+afterEach(async () => {
+ if (created.length === 0) return;
+ await db.company.deleteMany({ where: { id: { in: created.splice(0) } } });
+});
+
+async function company(status: EnrichmentStatus) {
+ const row = await db.company.create({
+ data: {
+ name: "Keyless Probe",
+ domain: `keyless-${created.length}-${status}.test`.toLowerCase(),
+ enrichmentStatus: status,
+ },
+ select: { id: true },
+ });
+
+ created.push(row.id);
+ return row.id;
+}
+
+const statusOf = async (id: string) =>
+ (
+ await db.company.findUnique({
+ where: { id },
+ select: { enrichmentStatus: true },
+ })
+ )?.enrichmentStatus;
+
+describe("a brand task with no key", () => {
+ it("leaves the company where the sweep will find it again", async () => {
+ const id = await company(EnrichmentStatus.PENDING);
+
+ await settle(
+ { companyId: id },
+ EnrichmentStatus.SKIPPED,
+ "Context.dev is not configured, so there is nowhere to look.",
+ );
+
+ expect(await statusOf(id)).toBe(EnrichmentStatus.PENDING);
+ });
+
+ it("does not strand a company that had already failed", async () => {
+ const id = await company(EnrichmentStatus.FAILED);
+
+ await settle({ companyId: id }, EnrichmentStatus.SKIPPED, "no key");
+
+ expect(await statusOf(id)).toBe(EnrichmentStatus.FAILED);
+ });
+
+ it("still settles a lookup that genuinely ran", async () => {
+ const id = await company(EnrichmentStatus.RUNNING);
+
+ await settle({ companyId: id }, EnrichmentStatus.SKIPPED, "No brand.");
+
+ expect(await statusOf(id)).toBe(EnrichmentStatus.SKIPPED);
+ });
+});
diff --git a/apps/api/.scratch/existing.ts b/apps/api/.scratch/existing.ts
index 16f1b360..3102a5fe 100644
--- a/apps/api/.scratch/existing.ts
+++ b/apps/api/.scratch/existing.ts
@@ -4,13 +4,18 @@ import { readContextDevKey } from "@crm/db/settings";
// Simulate an existing deployment: key in the environment, nothing in the row.
await db.appSetting.upsert({
- where: { id: "app" },
- create: { id: "app", contextDevApiKey: null },
- update: { contextDevApiKey: null },
+ where: { id: "app" },
+ create: { id: "app", contextDevApiKey: null },
+ update: { contextDevApiKey: null },
});
-console.log("env var set? ", Boolean(process.env.CONTEXT_DEV_API_KEY?.trim()));
+console.log(
+ "env var set? ",
+ Boolean(process.env.CONTEXT_DEV_API_KEY?.trim()),
+);
console.log("key the app finds ", await readContextDevKey(db));
-console.log("=> researchKey.configured would be false, so the proxy gates everyone.");
+console.log(
+ "=> researchKey.configured would be false, so the proxy gates everyone.",
+);
await db.$disconnect();
diff --git a/apps/api/.scratch/shape.ts b/apps/api/.scratch/shape.ts
new file mode 100644
index 00000000..b3f2ff37
--- /dev/null
+++ b/apps/api/.scratch/shape.ts
@@ -0,0 +1,35 @@
+import { initTRPC } from "@trpc/server";
+import { z } from "zod";
+import { setResearchKeyInput } from "../src/settings/settings.contracts";
+import { formatTrpcError } from "../src/trpc/error-formatter";
+
+const t = initTRPC.create({ errorFormatter: formatTrpcError });
+
+const router = t.router({
+ setResearchKey: t.procedure.input(setResearchKeyInput).mutation(() => "ok"),
+});
+
+const server = Bun.serve({
+ port: 4599,
+ fetch: (req) =>
+ import("@trpc/server/adapters/fetch").then(({ fetchRequestHandler }) =>
+ fetchRequestHandler({
+ endpoint: "",
+ req,
+ router,
+ createContext: () => ({}),
+ }),
+ ),
+});
+
+for (const apiKey of ["short", "ctx live key with spaces", ""]) {
+ const res = await fetch(`http://localhost:4599/setResearchKey`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ apiKey }),
+ });
+ const body = await res.json();
+ console.log(JSON.stringify(apiKey).padEnd(28), "->", body.error.message);
+}
+
+server.stop();
diff --git a/apps/api/src/backfill/backfill.module.ts b/apps/api/src/backfill/backfill.module.ts
index 8915a83c..efe3483e 100644
--- a/apps/api/src/backfill/backfill.module.ts
+++ b/apps/api/src/backfill/backfill.module.ts
@@ -7,5 +7,6 @@ import { ImageMirrorService } from "./image-mirror.service";
@Module({
imports: [AgentModule, CompaniesModule],
providers: [BackfillService, ImageMirrorService],
+ exports: [BackfillService],
})
export class BackfillModule {}
diff --git a/apps/api/src/settings/settings.contracts.ts b/apps/api/src/settings/settings.contracts.ts
index bf951a31..b144f878 100644
--- a/apps/api/src/settings/settings.contracts.ts
+++ b/apps/api/src/settings/settings.contracts.ts
@@ -10,8 +10,8 @@ export const setResearchKeyInput = z.object({
apiKey: z
.string()
.trim()
- .min(8, "That is too short to be an API key.")
- .max(500)
+ .min(8, "That does not look like a Context API key — it is too short.")
+ .max(500, "That does not look like a Context API key — it is too long.")
.refine(
(value) => !/\s/.test(value),
"An API key has no spaces in it. Paste the whole key on its own.",
diff --git a/apps/api/src/settings/settings.module.ts b/apps/api/src/settings/settings.module.ts
index 8aaadaa6..e176c714 100644
--- a/apps/api/src/settings/settings.module.ts
+++ b/apps/api/src/settings/settings.module.ts
@@ -1,12 +1,13 @@
import { Module } from "@nestjs/common";
import { AgentModule } from "../agent/agent.module";
+import { BackfillModule } from "../backfill/backfill.module";
import { TrpcModule } from "../trpc/trpc.module";
import { ModelCatalogService } from "./model-catalog.service";
import { SettingsRouter } from "./settings.router";
import { SettingsService } from "./settings.service";
@Module({
- imports: [TrpcModule, AgentModule],
+ imports: [TrpcModule, AgentModule, BackfillModule],
providers: [ModelCatalogService, SettingsService, SettingsRouter],
exports: [SettingsService],
})
diff --git a/apps/api/src/settings/settings.service.ts b/apps/api/src/settings/settings.service.ts
index 22e345fd..ebb6e1b8 100644
--- a/apps/api/src/settings/settings.service.ts
+++ b/apps/api/src/settings/settings.service.ts
@@ -9,6 +9,7 @@ import {
} from "@crm/db/settings";
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { ResearchKeyService } from "../agent/research-key.service";
+import { BackfillService } from "../backfill/backfill.service";
import { InjectDatabase } from "../database/database.constants";
import {
type CatalogModel,
@@ -41,6 +42,7 @@ export class SettingsService {
@InjectDatabase() private readonly db: Db,
private readonly catalog: ModelCatalogService,
private readonly researchKeys: ResearchKeyService,
+ private readonly backfill: BackfillService,
) {}
async agentModel(): Promise<AgentModelSettings> {
@@ -116,6 +118,28 @@ export class SettingsService {
verified: check.outcome === "valid",
});
+ // Every company added while there was no key is still PENDING, because a
+ // brand task with nowhere to look leaves the record alone. The sign-in
+ // sweep would find them, but the person who just fixed it is standing
+ // here — so pick the work up now rather than on their next sign-in.
+ void this.backfill
+ .run("companies")
+ .then(({ queued, remaining }) => {
+ if (queued > 0) {
+ this.logger.log({
+ message: "Queued the research that was waiting on a key",
+ queued,
+ remaining,
+ });
+ }
+ })
+ .catch((error: unknown) => {
+ this.logger.warn(
+ { message: "Could not queue the waiting research" },
+ error instanceof Error ? error.stack : String(error),
+ );
+ });
+
return this.researchKey();
}
}
diff --git a/apps/api/src/trpc/error-formatter.ts b/apps/api/src/trpc/error-formatter.ts
new file mode 100644
index 00000000..f0855e92
--- /dev/null
+++ b/apps/api/src/trpc/error-formatter.ts
@@ -0,0 +1,65 @@
+import type { TRPCDefaultErrorShape, TRPCErrorFormatter } from "@trpc/server";
+
+interface Issue {
+ message?: unknown;
+ path?: unknown;
+}
+
+/**
+ * tRPC stringifies a failed input parse into the whole `ZodError`, so a form
+ * that sends eight characters too few shows the reader a JSON array with
+ * `code`, `minimum`, `inclusive` and a `path` in it. The sentence we wrote for
+ * that rule is in there, and it is the only part anybody wants.
+ *
+ * Read by duck-typing rather than `instanceof ZodError`: the error crosses a
+ * package boundary, and two copies of zod in a workspace would silently stop
+ * matching and put the JSON back on screen.
+ */
+function issuesIn(cause: unknown): Issue[] | null {
+ if (typeof cause !== "object" || cause === null) return null;
+
+ const issues = (cause as { issues?: unknown }).issues;
+
+ return Array.isArray(issues) && issues.length > 0
+ ? (issues as Issue[])
+ : null;
+}
+
+function sentence(issue: Issue): string | null {
+ if (typeof issue.message !== "string" || issue.message.trim() === "") {
+ return null;
+ }
+
+ const message = issue.message.trim();
+
+ // Zod's own defaults ("Required", "Invalid input") name nothing, so they are
+ // only useful with the field in front of them. Ours are whole sentences.
+ if (/[.!?]$/.test(message)) return message;
+
+ const field = Array.isArray(issue.path)
+ ? issue.path.filter((part) => typeof part === "string").at(-1)
+ : undefined;
+
+ return field ? `${field}: ${message}` : message;
+}
+
+export function readableInputError(
+ message: string,
+ cause: unknown,
+): string | null {
+ const issues = issuesIn(cause);
+ if (!issues) return null;
+
+ const sentences = [...new Set(issues.map(sentence).filter(Boolean))];
+
+ return sentences.length > 0 ? sentences.join(" ") : message;
+}
+
+export const formatTrpcError: TRPCErrorFormatter<
+ object,
+ TRPCDefaultErrorShape
+> = ({ shape, error }) => {
+ const readable = readableInputError(shape.message, error.cause);
+
+ return readable ? { ...shape, message: readable } : shape;
+};
diff --git a/apps/api/src/trpc/trpc.module.ts b/apps/api/src/trpc/trpc.module.ts
index 57fabf39..4aa38a25 100644
--- a/apps/api/src/trpc/trpc.module.ts
+++ b/apps/api/src/trpc/trpc.module.ts
@@ -1,6 +1,7 @@
import { Module } from "@nestjs/common";
import { TRPCModule } from "nestjs-trpc";
import { ContextLogger } from "../logging/context-logger";
+import { formatTrpcError } from "./error-formatter";
import { AuthMiddleware } from "./middlewares/auth.middleware";
import { DomainErrorMiddleware } from "./middlewares/domain-error.middleware";
import { LoggingMiddleware } from "./middlewares/logging.middleware";
@@ -13,6 +14,7 @@ import { TrpcErrorHandler } from "./trpc-error.handler";
basePath: "/api/trpc",
context: TrpcContext,
logger: new ContextLogger(),
+ errorFormatter: formatTrpcError,
onError: TrpcErrorHandler,
globalMiddlewares: [LoggingMiddleware, DomainErrorMiddleware],
}),
diff --git a/apps/api/test/error-formatter.spec.ts b/apps/api/test/error-formatter.spec.ts
new file mode 100644
index 00000000..6cd27af7
--- /dev/null
+++ b/apps/api/test/error-formatter.spec.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "bun:test";
+import { z } from "zod";
+import { setResearchKeyInput } from "../src/settings/settings.contracts";
+import { readableInputError } from "../src/trpc/error-formatter";
+
+const causeOf = (schema: z.ZodType, value: unknown) => {
+ const result = schema.safeParse(value);
+ if (result.success) throw new Error("expected the parse to fail");
+ return result.error;
+};
+
+describe("what a rejected form says", () => {
+ it("shows the sentence, not the ZodError", () => {
+ const cause = causeOf(setResearchKeyInput, { apiKey: "short" });
+
+ expect(readableInputError("ignored", cause)).toBe(
+ "That does not look like a Context API key — it is too short.",
+ );
+ });
+
+ it("never leaks the machinery a reader cannot act on", () => {
+ const cause = causeOf(setResearchKeyInput, { apiKey: "short" });
+ const shown = readableInputError("ignored", cause) ?? "";
+
+ for (const noise of [
+ "too_small",
+ "minimum",
+ "inclusive",
+ "path",
+ "[",
+ "{",
+ ]) {
+ expect(shown).not.toContain(noise);
+ }
+ });
+
+ it("names the field when zod's own default says nothing", () => {
+ const cause = causeOf(z.object({ website: z.string() }), {});
+
+ expect(readableInputError("ignored", cause)).toContain("website");
+ });
+
+ it("joins several complaints into one line, without repeating itself", () => {
+ const schema = z.object({
+ a: z.string().min(3, "Too short."),
+ b: z.string().min(3, "Too short."),
+ });
+ const cause = causeOf(schema, { a: "x", b: "y" });
+
+ expect(readableInputError("ignored", cause)).toBe("Too short.");
+ });
+
+ it("leaves an error that is not a failed parse alone", () => {
+ expect(readableInputError("Nope.", new Error("boom"))).toBeNull();
+ expect(readableInputError("Nope.", undefined)).toBeNull();
+ expect(readableInputError("Nope.", { issues: [] })).toBeNull();
+ });
+});
diff --git a/apps/app/app/(auth)/onboarding/research/research-form.tsx b/apps/app/app/(auth)/onboarding/research/research-form.tsx
index 1833e507..42b16873 100644
--- a/apps/app/app/(auth)/onboarding/research/research-form.tsx
+++ b/apps/app/app/(auth)/onboarding/research/research-form.tsx
@@ -11,11 +11,9 @@ import {
import { Input } from "@crm/ui/components/input";
import { Spinner } from "@crm/ui/components/spinner";
import { useMutation } from "@tanstack/react-query";
-import Link from "next/link";
import { useRouter } from "next/navigation";
import { useId } from "react";
import { toast } from "sonner";
-import { RESEARCH_SKIP_PATH } from "@/lib/onboarding";
import { useTRPC } from "@/lib/trpc/client";
export function ResearchForm() {
@@ -74,19 +72,10 @@ export function ResearchForm() {
</Field>
</FieldGroup>
- <div className="flex flex-col items-center gap-3">
- <Button type="submit" disabled={save.isPending} className="w-full">
- {save.isPending ? <Spinner data-icon="inline-start" /> : null}
- Continue
- </Button>
-
- <Link
- href={RESEARCH_SKIP_PATH}
- className="text-muted-foreground text-xxs underline underline-offset-4 hover:text-foreground"
- >
- Skip
- </Link>
- </div>
+ <Button type="submit" disabled={save.isPending}>
+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}
+ Continue
+ </Button>
</form>
);
}
diff --git a/apps/app/lib/onboarding.ts b/apps/app/lib/onboarding.ts
index 18924b83..5fb844c5 100644
--- a/apps/app/lib/onboarding.ts
+++ b/apps/app/lib/onboarding.ts
@@ -5,23 +5,10 @@ export const ONBOARDING_PATH = "/onboarding";
export const RESEARCH_PATH = "/onboarding/research";
-/**
- * Skip is a link the proxy answers rather than a page, so the gate that would
- * otherwise redirect it back to the form is the same thing that lets it go.
- */
-export const RESEARCH_SKIP_PATH = "/onboarding/research/skip";
-
export const ONBOARDING_COOKIE = "crm.onboarded";
export const RESEARCH_COOKIE = "crm.research";
-/**
- * Two cookies because they record two different facts: one caches *a key is
- * saved*, the other *this browser was asked and said not now*. One writer each,
- * and neither can be mistaken for the other.
- */
-export const RESEARCH_SKIPPED_COOKIE = "crm.research.skipped";
-
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
const GATE_TIMEOUT_MS = 2_000;
diff --git a/apps/app/proxy.ts b/apps/app/proxy.ts
index 44ab213d..999af5d7 100644
--- a/apps/app/proxy.ts
+++ b/apps/app/proxy.ts
@@ -7,8 +7,6 @@ import {
ONBOARDING_PATH,
RESEARCH_COOKIE,
RESEARCH_PATH,
- RESEARCH_SKIP_PATH,
- RESEARCH_SKIPPED_COOKIE,
readOnboardingGate,
readResearchGate,
settle,
@@ -31,10 +29,6 @@ export async function proxy(request: NextRequest) {
if (isUngated(pathname)) return NextResponse.next();
- if (pathname === RESEARCH_SKIP_PATH) {
- return remember(request, home(request), RESEARCH_SKIPPED_COOKIE);
- }
-
const onboarding = request.cookies.has(ONBOARDING_COOKIE)
? "settled"
: await readOnboardingGate(request);
@@ -45,19 +39,15 @@ export async function proxy(request: NextRequest) {
return remember(request, sendTo(ONBOARDING_PATH, request), ...settled);
}
- const skipped = request.cookies.has(RESEARCH_SKIPPED_COOKIE);
-
- const research: Gate = skipped
+ const research = request.cookies.has(RESEARCH_COOKIE)
? "settled"
- : request.cookies.has(RESEARCH_COOKIE)
- ? "settled"
- : await readResearchGate(request);
+ : await readResearchGate(request);
if (research === "required") {
return remember(request, sendTo(RESEARCH_PATH, request), ...settled);
}
- if (!skipped && research === "settled") settled.push(RESEARCH_COOKIE);
+ if (research === "settled") settled.push(RESEARCH_COOKIE);
return remember(request, past(request, onboarding, research), ...settled);
}
diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.ts
index 674ea346..280e44f6 100644
--- a/apps/app/test/onboarding-gate.spec.ts
+++ b/apps/app/test/onboarding-gate.spec.ts
@@ -4,7 +4,6 @@ import { NextRequest } from "next/server";
import {
ONBOARDING_COOKIE,
RESEARCH_COOKIE,
- RESEARCH_SKIPPED_COOKIE,
readOnboardingGate,
readResearchGate,
} from "../lib/onboarding";
@@ -279,39 +278,6 @@ describe("the research key gate", () => {
expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();
});
- it("lets a rep skip, and does not ask that browser again", async () => {
- const calls = setup({ configured: false });
-
- const skip = await proxy(
- request("/onboarding/research/skip", [SESSION_COOKIE]),
- );
-
- expect(redirectedTo(skip)).toBe("/");
- expect(skip.cookies.get(RESEARCH_SKIPPED_COOKIE)?.value).toBe("1");
- expect(calls.research).toBe(0);
-
- expect(
- redirectedTo(
- await proxy(
- request("/companies", [
- SESSION_COOKIE,
- `${RESEARCH_SKIPPED_COOKIE}=1`,
- ]),
- ),
- ),
- ).toBeNull();
- });
-
- it("does not record a key for a rep who only skipped", async () => {
- setup({ configured: false });
-
- const response = await proxy(
- request("/companies", [SESSION_COOKIE, `${RESEARCH_SKIPPED_COOKIE}=1`]),
- );
-
- expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();
- });
-
it("remembers the workspace answer even while the key is outstanding", async () => {
setup({ configured: false });
diff --git a/docs/api.md b/docs/api.md
index 824e31a8..90db5121 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -176,16 +176,13 @@ called, who works here, and what do we sell — and for nothing else.
The marker is written onto the *redirect* to the key form, so the workspace
is not re-read on every request during the window a rep is being asked
something else.
- - **Skip is a link the proxy answers, not a page.** `/onboarding/research/skip`
- never renders: the proxy recognises the path, writes the marker and sends
- them home. A route handler would have needed ungating — the gate would
- otherwise redirect the skip link back to the form it is trying to leave —
- and ungating is how you get a hole rather than a door.
- - **Two cookies, because they are two different facts.** `crm.research` caches
- *a key is saved*; `crm.research.skipped` records *this browser was asked and
- said not now*. Collapsing them into one would mean the skip link wrote a
- cookie claiming a key exists, and the proxy is careful not to: it only
- writes `crm.research` when the API actually said so.
+ - **There is no way past it but to answer, and that is the point.** It had a
+ Skip, and Skip was the one path that could strand an install: every company
+ added afterwards sits `PENDING` waiting for a key nobody is going to be
+ asked for again, and nothing anywhere says so. A gate whose escape hatch
+ silently accumulates broken records is not a gate. If it should become
+ optional again, the missing piece is somewhere that surfaces *N companies
+ are waiting on a key* — not a link that hides the question.
- **Settings → General is the same write.** `settings.setResearchKey` is
posted by both, so there is one write path and no second opinion about what
a valid key looks like — including the check: that mutation asks the agent
diff --git a/docs/environment.md b/docs/environment.md
index f3d88fff..de37b77b 100644
--- a/docs/environment.md
+++ b/docs/environment.md
@@ -212,6 +212,27 @@ whether a company arrives as itself or as a grey square with its initials in
it — so [the proxy asks for it](./api.md#the-gate-is-proxyts-and-it-is-answered-once-per-browser)
rather than leaving it to be discovered on a settings page nobody visits.
+- **An install that had the variable set is asked for the key again, and that
+ is the intended upgrade.** Nothing adopts the old value — no boot-time
+ migration, no fallback — so the first navigation after deploying lands
+ everyone on `/onboarding/research`, where they paste the key they already
+ have. It is one interruption, once, in exchange for the answer living in one
+ place rather than two — and it cannot be dismissed, because a dismissed gate
+ is an install quietly filling up with companies that have no logo.
+- **Nothing is lost in the meantime, and the wait is not a queue.** A `brand`
+ task with nowhere to look is consumed and marked done — but it settles
+ `SKIPPED` *before* anything marks the row `RUNNING`, and `settle` only writes
+ over a `RUNNING` row, so the company stays `PENDING`. `PENDING` is exactly
+ what the sign-in sweep re-queues, so the work is recovered from the record
+ rather than held in the queue. `test/keyless-brand.integration.spec.ts` pins
+ it, because a `settle` that wrote unconditionally would strand every company
+ added before the key with nothing to say so.
+- **Saving the key picks that work up immediately.**
+ `settings.setResearchKey` runs the company sweep itself rather than leaving it
+ to the next sign-in, because the person who just fixed it is standing there.
+ It is fire-and-forget: a sweep that fails logs and the sign-in one still
+ catches up. Contacts are not swept here — only one of the three portrait
+ sources is Context — and they are picked up on the next sign-in as before.
- **`readContextDevKey` in [`@crm/db/settings`](../packages/db/src/settings.ts)
is the only reader**, and it reads one column. Everything downstream —
`contextDevKey()` in the agent's `capabilities.ts`, the client in
diff --git a/docs/images/context.png b/docs/images/context.png
deleted file mode 100644
index c2557e15..00000000
Binary files a/docs/images/context.png and /dev/null differ
diff --git a/docs/images/powered-by-context-dark.png b/docs/images/powered-by-context-dark.png
new file mode 100644
index 00000000..57e5a1fd
Binary files /dev/null and b/docs/images/powered-by-context-dark.png differ
diff --git a/docs/images/powered-by-context.png b/docs/images/powered-by-context.png
new file mode 100644
index 00000000..9e08b10a
Binary files /dev/null and b/docs/images/powered-by-context.png differ
diff --git a/packages/db/src/settings.ts b/packages/db/src/settings.ts
index f817528a..f5ccb135 100644
--- a/packages/db/src/settings.ts
+++ b/packages/db/src/settings.ts
@@ -74,27 +74,3 @@ export function maskKey(key: string): string {
const trimmed = key.trim();
return trimmed.length > 4 ? `••••${trimmed.slice(-4)}` : "••••";
}
-
-/**
- * The key used to be an environment variable, and an install that still sets
- * one is an install that was working. Moving the answer into a row must not
- * quietly take the capability away and put a setup form in front of everybody,
- * so the first boot after the upgrade adopts what is already there.
- *
- * This is the **only** thing in the repo that reads that variable, it runs once
- * — a filled column is never overwritten — and after it has run the variable is
- * vestigial. It is a migration, not a fallback: nothing consults the
- * environment while answering a request.
- */
-export const LEGACY_CONTEXT_DEV_ENV = "CONTEXT_DEV_API_KEY";
-
-export async function adoptLegacyContextDevKey(db: Db): Promise<boolean> {
- const key = process.env[LEGACY_CONTEXT_DEV_ENV]?.trim();
-
- if (!key) return false;
- if (await readContextDevKey(db)) return false;
-
- await writeContextDevKey(db, key);
-
- return true;
-}
diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.css
index f44ac661..406968eb 100644
--- a/packages/ui/src/styles/globals.css
+++ b/packages/ui/src/styles/globals.css
@@ -187,11 +187,6 @@
--font-sans: var(--font-sans);
--font-mono: var(--font-mono);
-
- /* One step below text-xs, for the quiet way out of a form. */
- --text-xxs: 0.6875rem;
- --text-xxs--line-height: 1rem;
-
--radius-sm: 4px;
--radius-md: var(--radius);
--radius-lg: 8px;