Skip to main content

Graph projection services

The backend runtime uses a durable scoped outbox and trusted Node workers for optional Neo4j/Memgraph projection. Browser applications require no graph password or graph driver.

Node exports​

Import from @cortexmemory/sdk/runtime/graph:

ExportResponsibility
ConvexGraphWorkerTransportFresh service JWT for bounded guarded backend operations
CortexGraphWorkerClaim/current/effect/complete lifecycle and optional run loop
CypherProjectionConnectorFixed parameterized projection/expansion against Neo4j or Memgraph
GraphConnectorErrorExplicit connector/worker error codes

Worker identity pins tenantId, memorySpaceId, connectorId and workerId. Transport options are deploymentUrl, fetchToken(signal) and optional timeout. Connector config selects engine/URI/private credentials/database plus the same scoped connector identity. The URI contains no credentials.

import { ConvexGraphWorkerTransport, CortexGraphWorker, CypherProjectionConnector }
from '@cortexmemory/sdk/runtime/graph';

export async function runGraph(options: {
deploymentUrl: string;
tenantId: string;
memorySpaceId: string;
connectorId: string;
workerId: string;
uri: string;
username: string;
password: string;
fetchToken: (signal: AbortSignal) => Promise<string>;
signal: AbortSignal;
}) {
const connector = new CypherProjectionConnector({
engine: 'neo4j', uri: options.uri, username: options.username, password: options.password,
tenantId: options.tenantId, memorySpaceId: options.memorySpaceId, connectorId: options.connectorId,
});
const transport = new ConvexGraphWorkerTransport({ deploymentUrl: options.deploymentUrl, fetchToken: options.fetchToken });
const worker = new CortexGraphWorker({
tenantId: options.tenantId, memorySpaceId: options.memorySpaceId,
connectorId: options.connectorId, workerId: options.workerId, connector, transport,
});
try { await worker.run(options.signal); }
finally { await worker.close(); }
}

Register the connector and its current service grant through trusted backend administration before starting the worker. step() executes one remote work item or returns idle; run(signal) polls; close() stops the loop and closes owned connector resources.

Consistency and failures​

Ordered outbox events, leases and source/profile provenance retain work while the service is stopped. Fresh grant/current-work checks precede effects; remote epoch/revision/hash fences prevent stale writes and tombstone resurrection. Backend retry policy owns reconciliation; the worker adds no unconstrained effect retry.

Graph status is distinct from response and memory status. A strict Agent requiring graph cannot silently downgrade when graph is missing. Dependency retirement includes derived/transitive references. Unknown remote outcomes remain explicit.

Root SDK Cypher adapters, legacy sync workers and explicit graph utilities remain advanced administrative facilities. They are separate from this backend outbox contract. See graph integration and memory barriers.

Explicit administrative adapter​

The root package exports CypherGraphAdapter and GraphAdapter from @cortexmemory/sdk. Use them in trusted Node administration with private Neo4j/Memgraph credentials. The adapter connects directly to the selected database; it does not verify a Cortex host JWT or add a runtime tenant/resource fence to arbitrary Cypher. Keep schema/query/traversal structure fixed and supply values as parameters. Do not accept model/browser-supplied Cypher, labels, relationship types, depth or filter clauses.

connect(config) requires URI, username and password, with optional database, pool size and connection timeout. Defaults are pool size 50 and connection acquisition timeout 60,000 ms; the driver transaction retry setting is 30,000 ms. Connecting an already connected adapter is rejected. Connection checks verify reachability, authentication and the supported ID dialect. isConnected() returns a boolean reachability check; disconnect() releases the owned driver. Connection/authentication errors use GraphConnectionError/GraphAuthenticationError with redacted connection details.

OperationParameters and return
query(query, params?)Cypher string or { cypher, params? }; explicit params override object params. Returns records, count and optional query statistics.
findNodes(label, properties?, limit?)Exact property matches; default limit 100; returns GraphNode[].
getNode(id)Returns GraphNode or null. The ID is the adapter's database node ID, not a Cortex logical resource ID.
createNode(node) / mergeNode(node, matchProperties)Creates or merges label/properties and returns a database ID. Merge correctness depends on the selected schema and match properties.
updateNode(id, properties) / deleteNode(id, detach?)Updates properties or deletes; detach defaults to true and removes connected relationships. Returns void.
createEdge(edge) / deleteEdge(id)Creates a typed from/to relationship with optional properties, returning its database ID; deletion returns void.
findEdges(type, properties?, limit?)Returns matching GraphEdge[], default limit 100.
traverse(config)Requires start ID/maxDepth, optional relationship types, direction and trusted Cypher filter/parameters; returns distinct connected nodes. Direction defaults to BOTH; omitted/empty relationship types follows all types.
findPath(config)Requires from/to IDs and maxHops with optional types/direction; returns nodes, relationships and path length, or null when no path exists.
batchWrite(operations)CREATE_NODE/UPDATE_NODE/DELETE_NODE/CREATE_EDGE/DELETE_EDGE within a graph transaction; returns void.
countNodes(label?) / countEdges(type?)Counts the selected graph records.
clearDatabase()Deletes every node and relationship in the selected database; this is not scoped user erasure.

GraphQueryError has code QUERY_ERROR and can retain the query/cause; keep diagnostics private. GraphDatabaseError carries optional code/cause, and GraphNotFoundError uses NOT_FOUND where an operation rejects a missing node/edge/path. Null-returning reads remain distinct from those mutation errors.

import { CypherGraphAdapter, type GraphConnectionConfig } from '@cortexmemory/sdk';

export async function readAdministrativeGraph(config: GraphConnectionConfig, ownerId: string) {
const adapter = new CypherGraphAdapter();
try {
await adapter.connect(config);
const summary = await adapter.query({
cypher: 'MATCH (n:AdministrativeTask) WHERE n.ownerId = $ownerId RETURN n.title AS title LIMIT 20',
params: { ownerId },
});
const nodes = await adapter.findNodes('AdministrativeTask', { ownerId }, 20);
const startId = nodes[0]?.id;
const related = startId ? await adapter.traverse({
startId, relationshipTypes: ['DEPENDS_ON'], maxDepth: 2, direction: 'OUTGOING',
filter: 'connected.ownerId = $ownerId', filterParams: { ownerId },
}) : [];
return { rows: summary.records, count: summary.count, related };
} finally {
await adapter.disconnect();
}
}

This example owns the adapter/connection and performs only fixed administrative reads. Its manual graph records are separate from managed Cortex-v2 projections and the backend runtime connector.

Managed-v2 rebuild and erasure​

Managed domain graph projection has physical source identity, known tenant/space, source/ownership/reference revisions and generation-bound job receipts. It is a separate contract from arbitrary adapter CRUD and from @cortexmemory/sdk/runtime/graph workers. An old logical ID or ordinary SDK client cannot supply administrative rebuild/erasure authority.

verifyGraphSchema(adapter) returns { valid, constraints, indexes, missing }. assertManagedGraphCompatibility rejects unsupported/missing schema with GRAPH_SCHEMA_MIGRATION_REQUIRED; conflicting fixed definitions use GRAPH_SCHEMA_CONFLICT. initializeGraphSchema explicitly installs the supported managed-v2 schema. dropGraphSchema(adapter, { managedVersion: 2 }) drops only the fixed Cortex-v2 schema objects; global schema deletion is retired. Managed reads/transactions must be supported by the adapter. Transactions are bounded to 10 seconds, 256 queries and 1 MiB aggregate parameters; individual results are bounded to 257 records/1 MiB. GRAPH_TRANSACTION_CONFLICT permits a fresh graph-only attempt; GRAPH_TRANSACTION_OUTCOME_UNKNOWN requires reconciliation and never a replay of the primary mutation.

Create createGraphRebuildTransport({ url, deploymentKey }) with the deployment's explicit HTTP(S) origin and private administrator key. It exposes only sourcePage/edgePage and close; no environment/config credential discovery or ordinary Cortex authority is used. Requests select version 2, fixed kind, exact scope and native cursor/endCursor/numItems. Per-request timeouts default to 30 seconds and are capped at 30 seconds; responses are bounded to 8 MiB, and concurrent calls on one transport are rejected.

initialGraphSync(cortex, adapter, options) requires that fixed transport. Options select tenant/space, optional safe nonnegative per-table limits, relationships (default true), progress callback, cancellation signal and optional whole-operation deadline. It performs a rolling rebuild of managed-v2 snapshots and verifies current physical source/reference provenance before edges. The Cortex argument is not used as a credential source. Rebuild closes its transport when its active rebuild completes/stops; the adapter remains caller-owned.

import { initialGraphSync, createGraphRebuildTransport,
type Cortex, type GraphAdapter } from '@cortexmemory/sdk';

export async function rebuildAdministrativeScope(cortex: Cortex, adapter: GraphAdapter,
options: { url: string; deploymentKey: string; tenantId: string; memorySpaceId: string },
signal: AbortSignal) {
const transport = createGraphRebuildTransport({
url: options.url, deploymentKey: options.deploymentKey,
});
try {
return await initialGraphSync(cortex, adapter, {
transport, tenantId: options.tenantId, memorySpaceId: options.memorySpaceId,
syncRelationships: true, deadlineMs: 120_000, signal,
});
} finally {
transport.close();
}
}

BatchSyncResult reports per-table synced/failed counts, errors, duration, schemaVersion 2, exact scope, confirmed physical IDs, graph apply counts, complete, limited, consistency: "rolling" and legacyExcluded: true. Space-selected rebuilds exclude unscoped immutable/mutable kinds. Limits or omitted relationship work prevent complete coverage. GraphRebuildPartialError carries the partial result and original error; already confirmed graph work is not rolled back. Inspect the failed physical source before replanning rather than presenting partial counts as completion.

For erasure, createGraphErasureTransport({ url, deploymentKey }) exposes fixed preflight/status/dispose/close operations, with the same explicit origin/key, 30-second request bound, 8 MiB response bound and one in-flight call. prepareGraphErasure(items, { adapter, disposalTransport }) is read-only and requires captured physical lifecycle evidence; it checks managed source identity, relationships and copied-job coverage before primary effects. eraseGraphItem(prepared, { client, jobs }) applies only original generation-bound delete jobs, verifies remote absence/tombstone and disposes copied payloads against the expected disposal revision. A logical replacement lookup is insufficient evidence.

GraphErasureStatus reports original job ID/generation/identity/source revision, synced/suppressed state, request/projection digests, disposal revision/count and completion. verifyGraphErasure returns overall complete and per-item absent/tombstoned/queueComplete/disposedJobCount. GraphErasureProgressError retains original jobs, partial status and failed/unknown disposal outcome. An unknown response requires reading the original status before continuing. GraphCommittedPartial means primary data committed while graph acknowledgement remains incomplete: retry only those original graph jobs. GraphPrimaryOutcomeUnknown means inspect/replan the original primary intent without automatically resending; GraphJobUnresolved means a missing/expired/contradictory receipt cannot certify progress.

Supported user/space cascades accept the fixed graph participant described in erasure receipts. Managed erasure preserves unmanaged/foreign graph records; arbitrary clearDatabase is not a replacement for this workflow.

Administrative graph record contracts​

GraphConnectionConfig​

export interface GraphConnectionConfig {
uri: string;
username: string;
password: string;
database?: string;
maxConnectionPoolSize?: number;
connectionTimeout?: number;
}

GraphNode​

export interface GraphNode {
label: string;
properties: Record<string, unknown>;
id?: string;
}

GraphEdge​

export interface GraphEdge {
type: string;
from: string;
to: string;
properties?: Record<string, unknown>;
id?: string;
}

GraphQuery​

export interface GraphQuery {
cypher: string;
params?: Record<string, unknown>;
}

GraphQueryResult​

export interface GraphQueryResult {
records: Record<string, unknown>[];
count: number;
stats?: QueryStatistics;
}

QueryStatistics​

export interface QueryStatistics {
nodesCreated?: number;
nodesDeleted?: number;
relationshipsCreated?: number;
relationshipsDeleted?: number;
propertiesSet?: number;
labelsAdded?: number;
labelsRemoved?: number;
indexesAdded?: number;
constraintsAdded?: number;
}

GraphPath​

export interface GraphPath {
nodes: GraphNode[];
relationships: GraphEdge[];
length: number;
}

TraversalConfig​

export interface TraversalConfig {
startId: string;
relationshipTypes?: string[];
maxDepth: number;
direction?: "OUTGOING" | "INCOMING" | "BOTH";
filter?: string;
filterParams?: Record<string, unknown>;
}

ShortestPathConfig​

export interface ShortestPathConfig {
fromId: string;
toId: string;
maxHops: number;
relationshipTypes?: string[];
direction?: "OUTGOING" | "INCOMING" | "BOTH";
}

GraphOperation​

export interface GraphOperation {
type:
| "CREATE_NODE"
| "UPDATE_NODE"
| "DELETE_NODE"
| "CREATE_EDGE"
| "DELETE_EDGE";
data:
| GraphNode
| GraphEdge
| { id: string; properties?: Record<string, unknown> };
}

GraphJobReceipt​

export interface GraphJobReceipt { id: string; generation: string; identity: GraphIdentity; sourceRevision: number }

GraphApplyResult​

export interface GraphApplyResult {
disposition: "applied" | "idempotent" | "suppressed";
nodesCreated: number; nodesDeleted: number; relationshipsCreated: number; relationshipsDeleted: number;
absentTargets: string[];
}