@intelligo-dev/core
Database schema, email, logging, notifications, and the conversation, document and identity contracts.
Install
pnpm add @intelligo-dev/core drizzle-ormdrizzle-orm is a peer; react 19 is an optional one, needed only by the
email templates. Every other @intelligo-dev/* package depends on this one,
and this one imports none of them.
Use
import { db, withWorkspaceFilter } from "@intelligo-dev/core/db";
import { conversations } from "@intelligo-dev/core/db/schema";
import { createLogger } from "@intelligo-dev/core/logger";
import { eq } from "drizzle-orm";
const log = createLogger("Inbox");
const mine = await db
.select()
.from(conversations)
.where(
withWorkspaceFilter(
conversations.workspaceId,
workspace.id,
eq(conversations.userId, user.id)
)
);
log.info("Loaded conversations", { count: String(mine.length) });db connects on first use from DATABASE_URL: a Neon host takes the
WebSocket driver and anything else takes node-postgres, unless
INTELLIGO_DB_DRIVER says pg or neon-serverless. Every tenant-scoped query
filters on workspaceId; workspaceEq and withWorkspaceFilter make that the
short way to write one.
The logger writes one JSON line per call. Credential fields are always
replaced, and anything shaped like a secret is taken out of an error’s text;
in production emails and ids are shortened (LOG_FULL_IDS=1 keeps the ids of
runs, requests, jobs and conversations whole, so a line can be looked up
against its row). Work wrapped in withLogContext carries its fields on
every line, and setLogSink hands each written line to a function of yours:
import {
requestIdFrom,
setLogSink,
withLogContext,
} from "@intelligo-dev/core/logger";
// Once, from the composition root: an error tracker's breadcrumbs, a
// log service's client. The record is already redacted.
setLogSink((record) => tracker.addBreadcrumb(record));
// Around a unit of work. The chat route and the guards of
// `@intelligo-dev/next/route` do this for a request already.
await withLogContext({ requestId: requestIdFrom(request.headers) }, () =>
handle(request)
);currentLogContext() reads the context of the work a call is part of, or
undefined outside any: for a client of your own that passes the request id on
to the service it calls.
checkRequestOrigin(request, { appOrigin, allowed }) from /request-context
is the check the chat and upload routes make on a write: a GET, HEAD or
OPTIONS passes, and any other method passes only from the app’s own origin,
from one in allowed, or from a caller that sends no Origin and is not a
cross-site browser request. It answers { allowed }, with the refused origin
when it refuses, for a route of your own that takes a cookie and changes
something.
The leaves import nothing, so a client bundle, an edge runtime or another package can reach them without pulling in the database:
import { formatMoney, fromMajor } from "@intelligo-dev/core/money";
import { sanitizeForSystemPrompt } from "@intelligo-dev/core/prompt";
formatMoney(fromMajor(12.5, "USD"), "en-US"); // "$12.50", held as 12_500_000 micros
const system = `${basePrompt}\n\nAbout the user: ${sanitizeForSystemPrompt(profile)}`;sanitizeForSystemPrompt is one layer, not a guarantee. It strips role
markers, chat-template tokens and prompt tags in any language, but its
override phrases are English: a product adds its own language’s to
INJECTION_PATTERNS, and keeps user text out of the system prompt where it
can.
Exports
| Subpath | What |
|---|---|
/db |
Drizzle client and the workspace-scoped query helpers |
/db/schema |
Every framework table |
/conversations |
Conversation and message persistence |
/documents |
Document persistence and the title classifier |
/identity |
The identity graph: facts, memories, profile snapshots |
/attachments |
Rows for the files users put into conversations |
/storage |
Where those files’ bytes live: one adapter (S3, R2, disk) bound by the application |
/storage/s3 |
That adapter for any S3-compatible bucket (S3, R2, MinIO), signed without an SDK |
/email |
Transactional email and its templates |
/notifications |
In-app notification records and triggers |
/logger |
Structured logging with credential redaction |
/registry |
Registries that survive a bundler duplicating a module |
/money |
Amount-plus-currency value object in micros; imports nothing |
/request-context |
Where the framework reads the request’s headers from; bound by the adapter |
/prompt |
Prompt-injection sanitisation for user text bound for a system prompt; imports nothing |
/env |
Environment validation |
/testing |
For an app’s tests: the database they may write to, and one connection to it |
/testing is for integration tests, never an app’s own code.
useTestDatabase() points the framework at TEST_DATABASE_URL (or at
DATABASE_URL under a test runner) and throws in production;
testClient() is one raw pg connection to it for fixtures and assertions,
and closeTestClient() ends it. testDatabaseUrl() is the address they
resolve, for a tool of your own that connects by itself.
/db/schema gained two tables in 1.3: deploymentSpendDaily, what the
deployment’s providers were paid per UTC day, which the spend cap reads; and
maintenanceRuns, one row per scheduled route with when it last ran, which
the health page reads.
describeComposition() from /registry lists every registry of the process
by key, with whether it holds anything and how many entries, and no values:
what the composition root bound here, safe to show an operator. The admin
console’s health page shows it.
Storage
/storage is the port; /storage/s3 is an adapter for any S3-compatible
bucket. It signs requests itself (Signature Version 4 over fetch and Web
Crypto), so it adds no dependency and runs wherever fetch does. Bind it from
the composition root:
import { setStorageAdapter } from "@intelligo-dev/core/storage";
import { s3StorageFromEnv } from "@intelligo-dev/core/storage/s3";
const storage = s3StorageFromEnv(); // null without STORAGE_BUCKET
if (storage) setStorageAdapter(storage);s3StorageFromEnv reads STORAGE_BUCKET, STORAGE_ACCESS_KEY_ID,
STORAGE_SECRET_ACCESS_KEY, STORAGE_REGION (default auto, R2’s) and
STORAGE_ENDPOINT (R2’s https://<account>.r2.cloudflarestorage.com, a MinIO
URL; unset means AWS). A custom endpoint is addressed path-style; pass
createS3Storage({ …, pathStyle }) to choose. Uploads are buffered to be
hashed. A request the bucket does not answer within timeoutMs (default 30
seconds) is abandoned and the call throws.
Identity
/identity keeps what a product learns about a person, scoped to the
user and the workspace, with every change in the append-only
user_memory_audit trail that the privacy page, the export and erasure
read:
import { confirmFact, recordFact } from "@intelligo-dev/core/identity";
const { fact, written } = await recordFact(actor, {
category: "goal",
key: "profile.target-role",
value: { label: "Data engineer", level: "senior" },
confidence: 0.7,
extractionMethod: "llm_extraction",
});
await confirmFact(actor, fact.id); // the person agreed to itrecordFact stores a fact or replaces the one under the same category and
key, and audits it in the same transaction; confirmFact stamps
lastConfirmedAt; deleteFact takes who removed it, the user by default.
A fact the person wrote (explicit_user_input) is not replaced by an
llm_extraction no more confident than it: the call returns
written: false.
- Category is the shared axis synthesis and display filter on, a closed
list (
USER_FACT_CATEGORIES). A product’s own kinds live in the key, namespaced as it likes, and in the value. - Value is a string, or an object whose
labelis a line a person can read. The privacy page shows that line and nothing else of it. - Provenance is
extractionMethodwithlastConfirmedAt: an unconfirmedllm_extractionis what a model read, a confirmed one is what the person agreed to, andexplicit_user_inputis what they wrote.
What is not a fact is a memory: a decision, an insight, a summary of a
conversation. recordMemory(actor, { kind, content, importance }) stores
one, listMemories(actor) reads them, the most important first, and
deleteMemory(actor, id) removes one, each write in the same audit trail
by id and kind, never by its text. getProfileSnapshot(actor) reads what
saveProfileSnapshot stored. No embedding is written: a product that
searches by meaning computes and stores its own.
How facts reach a model is the product’s: listFacts(actor) in
prepareMessages, or a tool the agent calls when it needs them. Into a
system prompt they go through renderFactsForPrompt:
import { listFacts, renderFactsForPrompt } from "@intelligo-dev/core/identity";
const facts = renderFactsForPrompt(await listFacts(actor), {
maxChars: 1_500,
minConfidence: 0.6,
});
const system = facts
? `${basePrompt}\n\nWhat the user has told you about themselves:\n${facts}`
: basePrompt;It writes one - category: value line per fact, in listFacts order, up
to maxChars and never part of a line. A fact’s value is text a model
wrote down from what someone said, so each one passes
sanitizeForSystemPrompt, and a line that would make the whole read as an
instruction is left out: what it returns never trips
detectPromptInjection.
Notifications
createNotification writes an in-app notification for a user; its
metadata is stored as JSON text, and every read, createNotification’s
own result included, returns it parsed. A metadata.href makes the row a
link: a relative path the app’s locale-aware navigation resolves, such as
/chat?query=…, which opens a new chat with that question in the
composer. How often a person hears from the product, and which reminder
wins, is the product’s policy: keep it in a table of your own, keyed by
workspace, user and kind, beside the createNotification call.
Email through a provider of your own
Resend and Loops are chosen from their keys. Anything else with a send
(SES, Postmark, an SMTP relay) is bound from the composition root, before
assertEnv(), with EMAIL_PROVIDER=custom in the environment:
import { setEmailProvider } from "@intelligo-dev/core/email";
setEmailProvider({
async send({ to, subject, html, from, replyTo }) {
const { messageId } = await ses.send({ to, subject, html, from, replyTo });
return { id: messageId };
},
});Both halves are needed. The variable is read when the auth module loads and
is what holds sign-ups for email verification; the binding sends. Startup
refuses the variable with nothing bound, and warns about a binding without the
variable. A send that throws is tried again unless the error carries a
statusCode of 4xx other than 429.
Emails in your own words
The emails the framework sends itself are written in English. setEmailCopy
binds a resolver that is asked before each one goes out and may answer with
its subject, its body (a React Email element, or HTML) or both. What it does
not answer for is sent as written, and a resolver that throws costs the
translation, never the email:
import { setEmailCopy } from "@intelligo-dev/core/email";
setEmailCopy(async ({ key, variables, locale }) => {
const t = await messagesFor(locale ?? "en");
if (key === "welcome") {
return { subject: t.welcome.subject, react: <Welcome {...variables} /> };
}
return null;
});locale is the language the recipient chose (users.preferred_language), or
the one a caller of sendEmail named with locale. It is null for an address
with no account, such as someone being invited, and which language that email
is in is yours to say. The keys are welcome, verify-email, password-reset,
workspace-invitation, quota-warning, quota-exceeded, trial-warning,
trial-depleted, trial-expiry, payment-failed and
subscription-confirmed.
Environment
assertEnv() from /env fails at boot rather than at the first query when
DATABASE_URL, BETTER_AUTH_SECRET or NEXT_PUBLIC_APP_URL is missing;
validateEnv() returns the same findings, with warnings for the optional
Stripe, email and CRON_SECRET values. The composition root calls it once.
Migrations
The framework migration chain ships inside this package
(src/db/migrations) and is applied by intelligo migrate from
@intelligo-dev/cli.
Do not provision with drizzle-kit push. A pushed database has the schema and
no migration records, and the migrator refuses it rather than half-applying the
chain to tables that already exist.
Entry points
@intelligo-dev/core@intelligo-dev/core/db@intelligo-dev/core/db/schema@intelligo-dev/core/email@intelligo-dev/core/notifications@intelligo-dev/core/conversations@intelligo-dev/core/documents@intelligo-dev/core/identity@intelligo-dev/core/attachments@intelligo-dev/core/storage@intelligo-dev/core/storage/s3@intelligo-dev/core/env@intelligo-dev/core/registry@intelligo-dev/core/money@intelligo-dev/core/request-context@intelligo-dev/core/prompt@intelligo-dev/core/testing@intelligo-dev/core/logger