User Profile API
Profiles are data, not identity authority. Complete supported-layer export/erasure uses fixed administrative transport and explicit tenant scope. Domain views can be partial; deletion receipts disclose verification, unknown outcomes and shared/foreign/provenance residuals. Omitted tenant selects tenantless data.
Usage boundary
Access the namespace on an explicitly configured root Cortex client. Host JWT and deployment-operator transports are distinct; validate current resource scope and do not infer authority from AuthContext metadata. See administrative operations.
Profiles and paginated administration
get, getVersion and getAtTimestamp return null when the profile or retained version is absent. update stores the supplied profile data with version tracking; merge applies partial fields; getOrCreate supplies defaults only for an absent profile. list defaults to limit 50, maximum 1000, offset 0, createdAt sorting descending. It returns users, total, effective limit/offset and hasMore. Display-name/email contains filters are applied by the SDK. export serializes profile rows; it is distinct from the supported ownership-closure export below.
Complete supported export
Create a fixed administrative transport with cortex.users.createExportTransport({ url, deploymentKey, timeoutMs? }). The URL is the deployment's HTTP(S) origin, without credentials, path, query or fragment; the key remains only in the trusted server. Timeout defaults to 30,000 ms and must be an integer 1–30,000. The transport allows only inspect/page/inspectEdge/readNode/resolveFile operations and uses deployment administrator authentication. A host JWT or a cast AuthContext does not provide this authority.
exportData(userId, { transport, tenantId?, pageSize?, signal? }) yields a validated event stream. The header pins identity and consistency: "rolling-read"; record events include node/fingerprint and either full record or membership projection. Blob metadata, sequenced base64 chunks and blob-end hashes describe retained files. The terminal manifest contains complete: true, table records/projections/pages, page and projection counts, observations, blobs, diagnostics, exclusions and start/end times. Completion is a validated ownership-closure export under rolling reads, not an atomic database snapshot.
Stage the output privately and commit it only after receiving the terminal manifest and the iterator finishes normally. A yielded header, record or blob is insufficient. On protocol/scope/change/file/budget error or cancellation, discard the staged output. serializeExportEvent preserves the canonical Convex encoding and returns one JSON string without a newline; add your own line delimiter. Do not convert tagged Convex values to lossy plain JSON.
import type { Cortex } from '@cortexmemory/sdk';
type PrivateExportStage = {
append(line: string): Promise<void>;
commit(): Promise<void>;
discard(): Promise<void>;
};
export async function exportSupportedUser(cortex: Cortex,
options: { url: string; deploymentKey: string; userId: string; tenantId: string },
stage: PrivateExportStage, signal?: AbortSignal) {
const transport = cortex.users.createExportTransport({
url: options.url, deploymentKey: options.deploymentKey, timeoutMs: 30_000,
});
let terminalManifestReceived = false;
try {
for await (const event of cortex.users.exportData(options.userId, {
transport, tenantId: options.tenantId, pageSize: 50, signal,
})) {
await stage.append(cortex.users.serializeExportEvent(event) + '\n');
if (event.type === 'manifest') terminalManifestReceived = event.complete;
}
if (!terminalManifestReceived) throw new Error('Export did not finish with a manifest');
await stage.commit();
} catch (error) {
await stage.discard();
throw error;
}
}
The supported closure excludes operational registries/governance/graph queue, external derived graphs, custom application tables, deployment configuration/credentials, purged records/history, foreign-owned or disconnected unowned components, and incoming share-source/editor/viewer content. Registered runtime-owned scopes are refused by this legacy export surface; use the supported runtime administrator procedures for those resources. Omitted tenant means tenantless identity, not every tenant.
Supported erasure and receipts
delete(userId) defaults to profile-only deletion. cascade: true selects supported ownership-aware erasure. Supply erasureTransport: cortex.users.createErasureTransport({ url, deploymentKey, timeoutMs? }); transport URL and timeout constraints match the export origin rules. Its seven fixed operations are discoverPage, checkRecord, checkBinaryReferences, verifyPage, getReceiptPage, eraseRecord and purgeExpiredReceiptsPage. Only one call may be in flight. close() cancels owned requests and prevents further calls.
dryRun: true previews supported deletion without executing it. Verification defaults to true; verify: false does not skip ownership/readiness preflight or establish verified completion. When a graph adapter is configured for managed graph deletion, provide a matching graphParticipant with the adapter and fixed createGraphErasureTransport({ url, deploymentKey }) disposal transport; missing/mismatched participation blocks the operation. Shared/foreign records and protected bytes/retained versions are preserved according to ownership. Registered runtime-owned scopes are refused, rather than silently processed as legacy rows.
import type { Cortex } from '@cortexmemory/sdk';
export async function eraseSupportedUser(cortex: Cortex,
options: { url: string; deploymentKey: string; userId: string;
tenantId: string; dryRun: boolean }) {
const erasureTransport = cortex.users.createErasureTransport({
url: options.url, deploymentKey: options.deploymentKey,
});
try {
return await cortex.users.delete(options.userId, {
tenantId: options.tenantId, cascade: true, dryRun: options.dryRun,
verify: true, erasureTransport,
});
} finally {
erasureTransport.close();
}
}
UserDeleteResult includes profile/layer counts, totalDeleted, deletedLayers, verification and optional erasure. Inspect the receipt:
| Receipt field | Interpretation |
|---|---|
operationId, domain, deletionScope | Identifies the original operation and the exclusiveSupportedPrimary selection. |
executed, complete | Distinguishes a preview from executed selected-domain completion. |
fullUserDataErased | Remains false; supported primary closure does not cover every external/custom/shared family. |
planned, outcomes, remaining, blockers | Records selected work, per-item commits/absence and what could not finish. |
perTable, totalDeleted | Counts deleted, detached, preserved, already-absent and retained-version outcomes. |
graph | Reports notConfigured/prepared/complete/partial, exact jobs and node count. |
verification | Reports notExecuted/notRequested/verified/failed and its own completion flag. |
exclusions, errors, unknown | Defines coverage and unresolved mutation outcomes. |
An exception may contain a partial receipt after earlier selected rows committed; it does not roll those commits back. Transport errors classify outcome as notSent, rolledBack or unknown. For unknown outcomes, inspect the original persisted receipt through getReceiptPage before any further mutation; retain its original operation/domain/item identities. There is no public blind resume helper. Do not turn a timeout or partial result into a new cascade request. deleteMany reports per-user outcomes, completion and unstarted users; it is not all-or-nothing across users.
Parameter and result contracts
These are reference definitions for the explicit server APIs. Optional fields use ?; timestamps are milliseconds since epoch unless an operation accepts a Date. Resource identifiers and participant metadata do not grant runtime authority.
UserProfile
export interface UserProfile {
id: string;
tenantId?: string;
data: Record<string, unknown>;
version: number;
createdAt: number;
updatedAt: number;
}
UserVersion
export interface UserVersion {
version: number;
data: Record<string, unknown>;
timestamp: number;
}
ListUsersFilter
export interface ListUsersFilter {
tenantId?: string;
limit?: number;
offset?: number;
createdAfter?: number;
createdBefore?: number;
updatedAfter?: number;
updatedBefore?: number;
sortBy?: "createdAt" | "updatedAt";
sortOrder?: "asc" | "desc";
displayName?: string;
email?: string;
}
| Field | Meaning and defaults |
|---|---|
tenantId | Filter by tenant ID for multi-tenant isolation |
limit | Maximum results to return (default: 50, max: 1000) |
offset | Skip first N results for pagination (default: 0) |
createdAfter | Filter by createdAt > timestamp |
createdBefore | Filter by createdAt < timestamp |
updatedAfter | Filter by updatedAt > timestamp |
updatedBefore | Filter by updatedAt < timestamp |
sortBy | Sort by field (default: "createdAt") |
sortOrder | Sort order (default: "desc") |
displayName | Filter by displayName (client-side, contains match) |
email | Filter by email (client-side, contains match) |
ListUsersResult
export interface ListUsersResult {
users: UserProfile[];
total: number;
limit: number;
offset: number;
hasMore: boolean;
}
| Field | Meaning and defaults |
|---|---|
users | Array of user profiles |
total | Total count before pagination |
limit | Limit used for this query |
offset | Offset used for this query |
hasMore | Whether there are more results beyond this page |
UserFilters
export interface UserFilters extends ListUsersFilter {}
Also inherits ListUsersFilter. See shared contracts.
UserExportTransportOptions
export interface UserExportTransportOptions {
url: string;
deploymentKey: string;
timeoutMs?: number;
}
UserExportDataOptions
export interface UserExportDataOptions extends UserExportCallOptions {
transport: UserExportTransport;
tenantId?: string;
pageSize?: number;
}
Also inherits UserExportCallOptions. See shared contracts.
UserExportEvent
export type UserExportEvent =
| {
type: "header";
format: "cortex-user-export";
version: 1;
identity: UserExportIdentity;
consistency: "rolling-read";
startedAt: number;
}
| {
type: "record";
node: UserExportNode;
fingerprint: string;
disposition: "record" | "membershipProjection";
record: ReturnType<typeof convexToJson>;
}
| ({ type: "blob" } & UserExportBlob)
| {
type: "chunk";
storageId: string;
sequence: number;
byteLength: number;
data: string;
}
| {
type: "blobEnd";
storageId: string;
chunks: number;
size: number;
sha256: string;
}
| {
type: "manifest";
version: 1;
complete: true;
identity: UserExportIdentity;
consistency: "rolling-read";
startedAt: number;
endedAt: number;
tableManifest: {
domain: UserExportDomain;
records: number;
projections: number;
pages: number;
}[];
pageCount: number;
projectionCount: number;
pageObservations: UserExportClosure["pageObservations"];
blobs: UserExportBlob[];
diagnostics: UserExportEdgeWitness[];
exclusions: string[];
};
UserExportBlob
export interface UserExportBlob {
storageId: string;
size: number;
mimeType: string;
sha256: string;
referrers: { node: UserExportNode; version?: number }[];
}
DeleteUserOptions
export interface DeleteUserOptions extends ErasureOptions {
cascade?: boolean;
verify?: boolean;
dryRun?: boolean;
}
| Field | Meaning and defaults |
|---|---|
cascade | Enable cascade deletion across all layers (default: false) |
verify | Run verification after deletion (default: true) |
dryRun | Preview what would be deleted without actually deleting (default: false) |
Also inherits ErasureOptions. See erasure options.
ErasureOptions
export interface ErasureOptions {erasureTransport?:ErasureTransport;tenantId?:string;signal?:AbortSignal;graphParticipant?:ErasureGraphParticipant;dryRun?:boolean;verify?:boolean}
ErasureReceipt
export interface ErasureReceipt {
version:1;operationId:string;domain:ErasureDomain;deletionScope:"exclusiveSupportedPrimary";
executed:boolean;complete:boolean;fullUserDataErased:boolean;startedAt:number;endedAt:number;
planned:ErasureProjection[];outcomes:ErasureOutcome[];remaining:string[];blockers:{id:string;reason:string}[];
perTable:Record<string,{deleted:number;detached:number;preserved:number;alreadyAbsent:number;retainedVersions:number}>;
totalDeleted:number;graph:{state:"notConfigured"|"prepared"|"complete"|"partial";jobs:GraphJobReceipt[];nodesDeleted:number};
verification:{state:"notExecuted"|"notRequested"|"verified"|"failed";complete:boolean};
exclusions:string[];errors:string[];unknown:string[];
}
ErasureOutcome
export interface ErasureOutcome extends ErasureEnvelope {
operationId:string;itemKey:string;table:string;id:string;state:"committed"|"alreadyAbsent";
deleted:number;detached:number;retainedVersions:number;messages:number;serializedBytes?:number;
blobs:{storageId:string;disposition:"deleted"|"protected"|"missing"}[];graphJobs:GraphJobReceipt[];
}
Also inherits ErasureEnvelope. See shared contracts.
UserDeleteResult
export interface UserDeleteResult {
erasure?: ErasureReceipt;
userId: string;
deletedAt: number;
conversationsDeleted: number;
conversationMessagesDeleted: number;
immutableRecordsDeleted: number;
mutableKeysDeleted: number;
vectorMemoriesDeleted: number;
factsDeleted: number;
graphNodesDeleted?: number;
verification: {
complete: boolean;
scope?: "user-profile";
issues: string[];
};
totalDeleted: number;
deletedLayers: string[];
}
Public methods
The following signatures describe the TypeScript namespace. Parameter and result fields are defined on this page; the installed @cortexmemory/sdk declarations also provide their compile-time types. Signatures are reference notation, not application code to execute.
createExportTransport
Creates only the fixed administrative export transport; never changes SDK identity.
cortex.users.createExportTransport(options: UserExportTransportOptions): UserExportTransport
createErasureTransport
cortex.users.createErasureTransport(options:Parameters<typeof createErasureTransport>[0]): ErasureTransport
serializeExportEvent
Canonical JSON text for exportData events; publish after the terminal manifest.
cortex.users.serializeExportEvent(event: UserExportEvent): string
exportData
Administrative complete export. Consume through the terminal manifest before publishing a bundle.
cortex.users.exportData(userId: string, options: UserExportDataOptions): AsyncGenerator<UserExportEvent>
get
Get user profile by ID
cortex.users.get(userId: string): Promise<UserProfile | null>
update
Update user profile (creates new version by default)
cortex.users.update(userId: string, data: Record<string, unknown>): Promise<UserProfile>
delete
Delete a profile or explicitly erase its supported exclusive primary scope
cortex.users.delete(userId: string, options?: DeleteUserOptions): Promise<UserDeleteResult>
list
List user profiles with pagination, filtering, and sorting
cortex.users.list(filters?: ListUsersFilter): Promise<ListUsersResult>
search
Search user profiles with filters
cortex.users.search(filters: UserFilters): Promise<UserProfile[]>
count
Count user profiles with optional filters
cortex.users.count(filters?: UserFilters): Promise<number>
getVersion
Get specific version of user profile
cortex.users.getVersion(userId: string, version: number): Promise<UserVersion | null>
getHistory
Get version history of user profile
cortex.users.getHistory(userId: string): Promise<UserVersion[]>
getAtTimestamp
Get user profile at specific timestamp
cortex.users.getAtTimestamp(userId: string, timestamp: Date): Promise<UserVersion | null>
exists
Check if user profile exists
cortex.users.exists(userId: string): Promise<boolean>
getOrCreate
Get user profile or create with defaults if doesn't exist
cortex.users.getOrCreate(userId: string, defaults?: Record<string, unknown>): Promise<UserProfile>
merge
Merge partial updates with existing profile
cortex.users.merge(userId: string, updates: Record<string, unknown>): Promise<UserProfile>
export
Export user profiles with optional related data
cortex.users.export(options?: ExportUsersOptions): Promise<string>
updateMany
Bulk update multiple users by explicit IDs or filters
cortex.users.updateMany(userIdsOrFilters: string[] | UserFilters, updates: { data: Record<string, unknown> }, options?: { skipVersioning?: boolean; dryRun?: boolean }): Promise<{ updated: number; userIds: string[] }>
deleteMany
Bulk delete multiple users by explicit IDs or filters
cortex.users.deleteMany(userIdsOrFilters: string[] | UserFilters, options?: DeleteUserOptions): Promise<{ deleted: number; userIds: string[]; complete: boolean; outcomes: UserDeleteResult[]; unstarted: string[] }>
Errors and lifecycle
Validation, missing capability, authorization, stale version and partial/unknown committed outcomes are explicit. Inspect operation/write/deletion receipts before recovery; do not repeat an external effect under a new identity after uncertainty. Close owned clients and graph resources at the end of the server workflow.
See runtime client for ordinary app execution and error handling for recovery boundaries.