Examples: Complete application examples demonstrating TypeGraph patterns
# Agent Decision Replay
> Reconstruct the graph an agent actually saw and replay the same reasoning code
This example shows recorded-time capture as an agent-debugging tool. An agent
chooses the best source for a claim by traversing a knowledge graph and ranking
papers by citation authority. Later, the graph changes: a paper is removed and
new citations arrive. A live rerun gives a different answer, but
`store.asOfRecorded(decisionTime)` reconstructs the exact graph the agent saw.
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/21-agent-decision-replay.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/21-agent-decision-replay.ts)
:::
## What It Demonstrates
- `history: true` capture on a knowledge graph used by an AI agent.
- `store.recordedNow()` as the durable decision-time checkpoint.
- One reasoning function that runs unchanged against live and recorded views.
- A sealed recorded `query()` plus `degree()` graph algorithm over reconstructed
history.
- Why live reruns cannot explain old decisions once the evidence graph changes.
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/21-agent-decision-replay.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/21-agent-decision-replay.ts
```
## The Reusable Shape
The agent takes a read surface, not a concrete store. A live `StoreView` and a
recorded `RecordedStoreView` both satisfy the parts it needs:
```typescript
type EvidenceView = Pick<
RecordedStoreView,
"query" | "degree" | "nodes"
>;
async function recommendSource(view: EvidenceView, claimId: string) {
const supporterIds = await view
.query()
.from("Claim", "c")
.whereNode("c", (c) => c.id.eq(claimId))
.traverse("supports", "e", { direction: "in" })
.to("Paper", "p")
.select((ctx) => ctx.p.id)
.execute();
const scored = await Promise.all(
supporterIds.map(async (id) => ({
id,
citations: await view.degree(id, {
edges: ["cites"],
direction: "in",
}),
})),
);
return scored.sort((a, b) => b.citations - a.citations)[0];
}
```
At decision time, save the recorded anchor:
```typescript
const decisionTime = await store.recordedNow();
if (decisionTime === undefined) throw new Error("expected recorded history");
const original = await recommendSource(
store.view({ mode: "current" }),
claim.id,
);
```
During audit, replay the same code against the old graph:
```typescript
const replay = await recommendSource(
store.asOfRecorded(decisionTime),
claim.id,
);
```
## Sample Output
```text
Agent answers: 'best source for the claim?'
-> Kaplan - Scaling Laws (3 citations)
recorded at: 2026-...
Re-run on the CURRENT graph (the evidence moved):
-> Hoffmann - Compute-Optimal LLMs (3 citations)
x This is a different answer.
Replay on `store.asOfRecorded(decisionTime)` (same code):
-> Kaplan - Scaling Laws (3 citations)
ok Reproduced exactly.
```
## When to Use This Pattern
Use recorded decision replay when agent output must be explainable after the
graph changes:
- Eval replay for graph-grounded agents
- Audit trails for automated decisions
- Debugging "why did the agent say this?" incidents
- Reproducible RAG and knowledge-graph experiments
See [Temporal queries](/queries/temporal#recorded-time-bitemporal) for the
recorded-time rules and [Graph Algorithms](/graph-algorithms) for `degree()`.
# Agent-Driven Schema
> Runtime schema evolution end-to-end — an agent proposes new kinds and edges, the validator gates them, store.evolve commits, the live graph absorbs them with no restart and no codegen.
A runnable end-to-end demonstration of [graph extensions](/graph-extensions) —
the 0.25.0 feature that lets you grow the schema **at runtime** when something
new shows up in the world. An agent (LLM, scraper, ETL pipeline) proposes new
node and edge kinds from observed data, the validator gates the proposal, and
`store.evolve()` commits the new schema as a durable version. The live graph
starts ingesting under the new schema in the same process, with full Zod
validation, fulltext indexing, unique constraints, and cross-kind edge
enforcement — no restart, no codegen, no `any` cast on the read side.
:::tip[Just want the code?]
Full source on GitHub: [`packages/typegraph/examples/16-graph-extensions.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/16-graph-extensions.ts)
:::
:::note[Want to see this against real data with a real LLM?]
A separate demo repo runs the same loop against public-record clinical
research data with an open-weight LLM proposing schema after each stage of
the corpus arrives:
[`pdlug/typegraph-clinical-demo`](https://github.com/pdlug/typegraph-clinical-demo).
:::
## The shape of the loop
Runtime schema evolution is one verb (`store.evolve`) sitting between two
deliberate sources of friction:
1. **The validator.** Every proposal — even one built in TypeScript by your
own code — flows through `validateGraphExtension`, which returns
structured `{path, code, message}` issues. Typos, unknown property
refinements, malformed edge endpoints all come back as routable errors
instead of throwing deep in `evolve`.
2. **The incompatibility classifier.** Once data exists, `evolve` rejects
any change that would corrupt it — narrowing a type, removing a
required field on a populated kind, dropping an edge with live rows.
A misbehaving agent can't silently break the graph.
You provide the third moving part — the operator gate. Nothing in TypeGraph
auto-applies what an agent proposes. Your code decides whether to call
`evolve` on a validated proposal; the library makes sure the call is safe
when you do.
## What you get
The example walks through nine steps against a fresh SQLite database,
starting with a single compile-time kind (`Document`) and ending with three
kinds the agent invented at runtime. Sample output:
```text
[1] Booted with compile-time kind: Document
Active schema version: 1
Materialized 1 compile-time index
[2] Agent proposal validated:
nodes: Paper, Author
edges: authoredBy
[3] evolve() committed and materialized
Active schema version: 2
registry.hasNodeType('Paper'): true
registry.hasEdgeType('authoredBy'): true
[4] Ingested 2 Paper, 2 Author, 2 authoredBy edges
fulltext("Paper", "transformer architecture") -> 1 hit(s)
score=0.61 title="Attention is all you need"
Duplicate doi rejected: true
[5] Dynamic multi-hop traversal Paper -> Author:
Language models are unsupervised multitask learners (#1) by Alec Radford
[6] Incompatible re-proposal rejected:
Paper.year: TYPE_CHANGE (number -> string)
[7] Deprecated kinds: [Document]
[8] removeKinds(['Author']) — cascading edge cleanup
registry.hasNodeType('Author'): false
registry.hasEdgeType('authoredBy'): false
Active schema version: 5
[9] Restart parity:
validation.status: VALID
registry.hasNodeType('Paper'): true
registry.hasNodeType('Author') (removed in step 7): false
deprecatedKinds: [Document]
Found 2 Paper nodes after restart
```
The interesting moments are step 4 (fulltext + unique-constraint
enforcement against a runtime kind), step 6 (the incompatibility gate),
and step 9 (everything survives a fresh `createStoreWithSchema` against
the same database — kinds, deprecation flags, indexes).
## The boot graph
Start with one compile-time kind so the live graph has structure before
the agent shows up. Everything compile-time stays type-safe end-to-end
even as extension kinds accumulate around it:
```typescript
const Document = defineNode("Document", {
schema: z.object({
title: z.string(),
body: z.string(),
}),
});
const documentTitle = defineNodeIndex(Document, { fields: ["title"] });
const baseGraph = defineGraph({
id: "research_corpus",
nodes: { Document: { type: Document } },
edges: {},
indexes: [documentTitle],
});
const { backend } = createLocalSqliteBackend();
const [store] = await createStoreWithSchema(baseGraph, backend);
```
## Scene by scene
### 1. The agent returns a JSON proposal
What an LLM or scraper actually hands back is a JSON document, not a typed
value. `validateGraphExtension(unknown, { strict })` is the Result-style
entry point: it walks the document, collects every structural issue, and
returns a typed `GraphExtension` on success. Strict mode rejects unknown
sibling keys so a field typo (`node` instead of `nodes`) fails loudly
instead of silently producing an empty extension.
```typescript
const agentJson: unknown = JSON.parse(`{
"nodes": {
"Paper": {
"description": "Academic paper inferred from the corpus",
"properties": {
"title": { "type": "string", "minLength": 1, "searchable": {} },
"abstract": { "type": "string", "searchable": {}, "optional": true },
"doi": { "type": "string", "minLength": 1 },
"year": { "type": "number", "int": true, "min": 1900, "max": 2100 }
},
"unique": [{ "name": "paper_doi_unique", "fields": ["doi"] }]
},
"Author": {
"properties": {
"name": { "type": "string", "minLength": 1, "searchable": {} },
"affiliation": { "type": "string", "optional": true }
}
}
},
"edges": {
"authoredBy": {
"from": ["Paper"], "to": ["Author"],
"properties": { "order": { "type": "number", "int": true, "min": 1 } }
}
},
"indexes": [
{ "entity": "node", "kind": "Paper",
"name": "paper_by_year", "fields": ["year"] }
]
}`);
const result = validateGraphExtension(agentJson, { strict: true });
if (!result.success) {
// result.error.issues is a structured list — route it back to the agent.
throw result.error;
}
const extension: GraphExtension = result.data;
```
Each issue carries a stable `code` (`UNKNOWN_DOCUMENT_KEY`,
`INVALID_PROPERTY_REFINEMENT`, `MISSING_REQUIRED_FIELD`, …) — useful both
for routing failures back to the model in a repair loop and for treating
validation outcomes as data instead of exceptions.
### 2. Commit + materialize atomically
`evolve` runs the incompatibility check, commits a new schema version, and
returns a new `Store` carrying the merged registry. `eager: {}` turns it
into a one-call "schema committed AND indexes materialized" verb so the
returned store is ready to ingest by the time the promise resolves:
```typescript
const evolved = await store.evolve(extension, { eager: {} });
```
### 3. Ingest under the new schema
Extension kinds get the same CRUD surface as compile-time kinds — there's no
separate dynamic API to learn. The difference is at the type system: extension
kinds aren't visible at compile time, so the collection's type is the generic
`NodeCollection` rather than a kind-specific one. Property validation, unique
constraints, fulltext indexing, and edge endpoint enforcement all run live:
```typescript
const papers = evolved.getNodeCollectionOrThrow("Paper");
const authors = evolved.getNodeCollectionOrThrow("Author");
const authoredBy = evolved.getEdgeCollectionOrThrow("authoredBy");
const attention = await papers.create({
title: "Attention is all you need",
abstract: "We propose a new simple network architecture, the Transformer.",
doi: "10.5555/3295222.3295349",
year: 2017,
});
await authoredBy.create(attention, vaswani, { order: 1 });
// The `searchable: {}` brand on Paper.title flows through to the
// backend's fulltext index — same BM25 retrieval extension kinds get
// at compile time.
const hits = await evolved.search.fulltext("Paper", {
query: "transformer architecture",
limit: 3,
});
// Unique-constraint enforcement is live for extension kinds too.
const duplicate = await papers.create({
title: "Duplicate doi",
doi: "10.5555/3295222.3295349", // same doi as `attention` above
year: 2024,
}).catch((err) => err);
// → UniqueConstraintError
```
### 4. Multi-hop traversals over runtime kinds
The typed query builder methods (`from`, `traverse`, `to`) require
compile-time kind literals so they can give you full intellisense. For
runtime kinds, use the `*Dynamic` siblings — they accept arbitrary strings,
validate them against the registry (typo → `KindNotFoundError`), and surface
a `.field("name").number().gte(...)` predicate API so an MCP server can
traverse a runtime graph without an `as any`:
```typescript
const rows = await evolved
.query()
.fromDynamic("Paper", "p")
.traverseDynamic("authoredBy", "a")
.toDynamic("Author", "u")
.whereNode("p", (p) => p.field("year").number().gte(2018))
.select((ctx) => ({
paperTitle: ctx.p.title,
authorName: ctx.u.name,
order: ctx.a.order,
}))
.execute();
```
Dynamic and typed methods mix freely — `from("Document", ...)` chained to
`traverseDynamic("authoredBy", ...)` is well-formed.
### 5. The incompatibility gate
The agent (or any caller) eventually proposes something that would corrupt
existing data. Against an empty kind some changes are allowed; against a
populated one, the classifier rejects them:
```typescript
const breakingProposal: GraphExtension = {
...extension,
nodes: {
...extension.nodes,
Paper: {
...extension.nodes!.Paper!,
properties: {
...extension.nodes!.Paper!.properties,
year: { type: "string" }, // was number — TYPE_CHANGE
},
},
},
};
const rejection = await evolved
.evolve(breakingProposal)
.catch((err) => err);
if (rejection instanceof IncompatibleChangeError) {
for (const change of rejection.changes) {
console.log(`${change.kind}.${change.field}: ${change.type}`);
}
// → Paper.year: TYPE_CHANGE
}
```
This is the "data corruption" backstop. A misbehaving agent in a tight loop
cannot evolve the schema into a shape that breaks existing rows.
### 6. Deprecate and remove
Deprecation is a **signal**, not a gate. It surfaces in
`store.introspect().deprecatedKinds` for codegen tools and lint rules, but
reads and writes against the deprecated kind continue to work:
```typescript
const deprecated = await evolved.deprecateKinds(["Document"]);
// Document is now flagged but still fully usable.
await deprecated.nodes.Document.create({
title: "Legacy doc",
body: "Still readable, just flagged",
});
```
Removal is the harder verb. `removeKinds(["Author"], { eager: {} })`
commits a new schema version that drops `Author` and cascades to any edge
whose endpoints depend on it (here, `authoredBy`). With `eager: {}` the
data-cleanup phase runs inline — rows and edge data are deleted before the
verb returns:
```typescript
const trimmed = await deprecated.removeKinds(["Author"], { eager: {} });
// registry.hasNodeType('Author') -> false
// registry.hasEdgeType('authoredBy') -> false (cascaded)
```
### 7. Restart parity
The whole point of "durable schema versions" is that nothing above is
in-memory state. A fresh process opening the same database sees every
accepted extension, deprecation flag, and materialized index without
re-running any verb:
```typescript
const [restored, validation] = await createStoreWithSchema(baseGraph, backend);
// validation.status === "VALID"
// restored.registry.hasNodeType("Paper") -> true
// restored.registry.hasNodeType("Author") -> false (removed in step 6)
// restored.introspect().deprecatedKinds -> ["Document"]
const papers = restored.getNodeCollectionOrThrow("Paper");
await papers.find({}); // returns the rows from step 3
```
This is what makes runtime evolution safe for production: agent-proposed
schema is regular schema by the time the next process starts up.
## Run it
```bash
git clone https://github.com/nicia-ai/typegraph
cd typegraph
pnpm install
npx tsx packages/typegraph/examples/16-graph-extensions.ts
```
The example builds the graph, walks every step against an in-memory SQLite
database, and prints output for each. To persist it, point
`createLocalSqliteBackend()` at a file path. To run on Postgres, swap the
import to `createPostgresBackend` — see [Backend Setup](/backend-setup).
## Next steps
- [Graph Extensions](/graph-extensions) — the full reference for
`defineGraphExtension`, `validateGraphExtension`, `evolve`,
`deprecateKinds`, `removeKinds`, and the structured-issue codes
- [`pdlug/typegraph-clinical-demo`](https://github.com/pdlug/typegraph-clinical-demo)
— the same loop driven by an open-weight LLM against public-record
clinical data, with a repair loop and a smoke-test pattern that catches
latent shape mismatches the static validator can't
- [Schema Migrations](/schema-management) — the lower-level primitives
graph extensions ride on top of (`SchemaVersion`, change classification,
reconciliation watermarks)
- [Dynamic Queries](/queries/source) — `fromDynamic`, `traverseDynamic`,
and the predicate accessor for runtime kinds
# Audit Trail
> Complete change tracking with user attribution and diff generation
This example shows how to build a comprehensive audit system that:
- **Tracks all changes** using TypeGraph's temporal model
- **Attributes changes** to users and sessions
- **Generates diffs** between versions
- **Supports compliance queries** (who changed what, when)
- **Exports audit logs** for external systems
## How TypeGraph Enables Auditing
TypeGraph's temporal model provides built-in auditing capabilities:
1. **Every update creates a new version** - Old data is preserved with `valid_to` timestamp
2. **Temporal queries** - Query any point in time with `asOf` or get full history with `includeEnded`
3. **Metadata fields** - `createdAt`, `updatedAt`, `version` are tracked automatically
This example extends the built-in capabilities with:
- User attribution (who made the change)
- Change descriptions (why the change was made)
- Structured diffs (what exactly changed)
## Schema Definition
```typescript
import { z } from "zod";
import { defineNode, defineEdge, defineGraph, searchable } from "@nicia-ai/typegraph";
// Audited entity (example: Settings)
const Setting = defineNode("Setting", {
schema: z.object({
key: z.string(),
value: z.string(),
category: z.string(),
description: z.string().optional(),
}),
});
// Audit queries frequently include free-text predicates: "find all
// changes mentioning GDPR" or "find changes where the reason contains
// 'security patch'". Marking `reason` as `searchable()` enables BM25
// ranked fulltext over that column without an external search service.
// Users making changes
const User = defineNode("User", {
schema: z.object({
email: z.string().email(),
name: z.string(),
role: z.enum(["admin", "editor", "viewer"]),
}),
});
// Explicit audit log entries (for cross-cutting concerns)
const AuditEntry = defineNode("AuditEntry", {
schema: z.object({
entityType: z.string(),
entityId: z.string(),
action: z.enum(["create", "update", "delete", "restore"]),
timestamp: z.string().datetime(),
changes: z.record(z.object({
before: z.unknown().optional(),
after: z.unknown().optional(),
})).optional(),
reason: searchable({ language: "english" }).optional(),
ipAddress: z.string().optional(),
userAgent: z.string().optional(),
}),
});
// Sessions for grouping changes
const Session = defineNode("Session", {
schema: z.object({
startedAt: z.string().datetime(),
endedAt: z.string().datetime().optional(),
ipAddress: z.string().optional(),
userAgent: z.string().optional(),
}),
});
// Edges
const performedBy = defineEdge("performedBy");
const inSession = defineEdge("inSession");
const hasSession = defineEdge("hasSession");
const graph = defineGraph({
id: "audit_trail",
nodes: {
Setting: {
type: Setting,
unique: [
{
name: "setting_key",
fields: ["key"],
scope: "kind",
collation: "binary",
},
],
},
User: {
type: User,
unique: [
{
name: "user_email",
fields: ["email"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
AuditEntry: { type: AuditEntry },
Session: { type: Session },
},
edges: {
performedBy: { type: performedBy, from: [AuditEntry], to: [User] },
inSession: { type: inSession, from: [AuditEntry], to: [Session] },
hasSession: { type: hasSession, from: [User], to: [Session] },
},
});
```
## Audit Context
Create a context object to track the current user and session:
```typescript
interface AuditContext {
userId: string;
sessionId?: string;
ipAddress?: string;
userAgent?: string;
reason?: string;
}
// Thread-local storage for audit context (Node.js)
import { AsyncLocalStorage } from "async_hooks";
const auditContext = new AsyncLocalStorage();
function withAuditContext(context: AuditContext, fn: () => Promise): Promise {
return auditContext.run(context, fn);
}
function getAuditContext(): AuditContext | undefined {
return auditContext.getStore();
}
```
## Audited Operations
### Create with Audit
```typescript
async function createSetting(
key: string,
value: string,
category: string
): Promise> {
const ctx = getAuditContext();
if (!ctx) throw new Error("Audit context required");
return store.transaction(async (tx) => {
// Create the setting
const setting = await tx.nodes.Setting.create({
key,
value,
category,
});
// Create audit entry
await createAuditEntry(tx, {
entityType: "Setting",
entityId: setting.id,
action: "create",
changes: {
key: { after: key },
value: { after: value },
category: { after: category },
},
});
return setting;
});
}
```
### Update with Audit
```typescript
async function updateSetting(
id: string,
updates: Partial<{ value: string; description: string }>
): Promise> {
const ctx = getAuditContext();
if (!ctx) throw new Error("Audit context required");
return store.transaction(async (tx) => {
// Get current state
const current = await tx.nodes.Setting.getById(id);
if (!current) throw new Error(`Setting not found: ${id}`);
// Calculate changes
const changes: Record = {};
for (const [key, newValue] of Object.entries(updates)) {
const oldValue = current[key as keyof typeof current];
if (oldValue !== newValue) {
changes[key] = { before: oldValue, after: newValue };
}
}
// Skip if no actual changes
if (Object.keys(changes).length === 0) {
return current;
}
// Update the setting
const updated = await tx.nodes.Setting.update(id, updates);
// Create audit entry
await createAuditEntry(tx, {
entityType: "Setting",
entityId: id,
action: "update",
changes,
});
return updated;
});
}
```
### Delete with Audit
```typescript
async function deleteSetting(id: string): Promise {
const ctx = getAuditContext();
if (!ctx) throw new Error("Audit context required");
await store.transaction(async (tx) => {
// Get current state for audit
const current = await tx.nodes.Setting.getById(id);
if (!current) throw new Error(`Setting not found: ${id}`);
// Delete (soft delete)
await tx.nodes.Setting.delete(id);
// Create audit entry
await createAuditEntry(tx, {
entityType: "Setting",
entityId: id,
action: "delete",
changes: {
key: { before: current.key },
value: { before: current.value },
category: { before: current.category },
},
});
});
}
```
### Create Audit Entry
```typescript
interface AuditEntryInput {
entityType: string;
entityId: string;
action: "create" | "update" | "delete" | "restore";
changes?: Record;
}
async function createAuditEntry(
tx: Transaction,
input: AuditEntryInput
): Promise> {
const ctx = getAuditContext()!;
const entry = await tx.nodes.AuditEntry.create({
entityType: input.entityType,
entityId: input.entityId,
action: input.action,
timestamp: new Date().toISOString(),
changes: input.changes,
reason: ctx.reason,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
// Link to user
const user = await tx.nodes.User.getById(ctx.userId);
if (!user) throw new Error(`User not found: ${ctx.userId}`);
await tx.edges.performedBy.create(entry, user, {});
// Link to session if present
if (ctx.sessionId) {
const session = await tx.nodes.Session.getById(ctx.sessionId);
if (!session) throw new Error(`Session not found: ${ctx.sessionId}`);
await tx.edges.inSession.create(entry, session, {});
}
return entry;
}
```
## Querying Audit History
### Get Entity History
```typescript
interface HistoryEntry {
version: number;
timestamp: string;
action: string;
changes?: Record;
user: { name: string; email: string };
reason?: string;
}
async function getEntityHistory(
entityType: string,
entityId: string
): Promise {
return store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) =>
a.entityType.eq(entityType).and(a.entityId.eq(entityId))
)
.traverse("performedBy", "e")
.to("User", "u")
.orderBy((ctx) => ctx.a.timestamp, "desc")
.select((ctx) => ({
version: ctx.a.version,
timestamp: ctx.a.timestamp,
action: ctx.a.action,
changes: ctx.a.changes,
user: {
name: ctx.u.name,
email: ctx.u.email,
},
reason: ctx.a.reason,
}))
.execute();
}
```
### Get User Activity
```typescript
interface UserActivity {
timestamp: string;
entityType: string;
entityId: string;
action: string;
}
async function getUserActivity(
userId: string,
options: { since?: Date; limit?: number } = {}
): Promise {
const { since, limit = 100 } = options;
let query = store
.query()
.from("User", "u")
.whereNode("u", (u) => u.id.eq(userId))
.traverse("performedBy", "e", { direction: "in" })
.to("AuditEntry", "a");
if (since) {
query = query.whereNode("a", (a) => a.timestamp.gte(since.toISOString()));
}
return query
.orderBy((ctx) => ctx.a.timestamp, "desc")
.limit(limit)
.select((ctx) => ({
timestamp: ctx.a.timestamp,
entityType: ctx.a.entityType,
entityId: ctx.a.entityId,
action: ctx.a.action,
}))
.execute();
}
```
### Changes in Time Range
```typescript
interface ChangeReport {
entityType: string;
entityId: string;
changeCount: number;
users: string[];
lastChange: string;
}
async function getChangesInRange(
startDate: Date,
endDate: Date
): Promise {
const entries = await store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) =>
a.timestamp.gte(startDate.toISOString()).and(
a.timestamp.lte(endDate.toISOString())
)
)
.traverse("performedBy", "e")
.to("User", "u")
.select((ctx) => ({
entityType: ctx.a.entityType,
entityId: ctx.a.entityId,
timestamp: ctx.a.timestamp,
userName: ctx.u.name,
}))
.execute();
// Group by entity
const grouped = new Map();
for (const entry of entries) {
const key = `${entry.entityType}:${entry.entityId}`;
const existing = grouped.get(key);
if (existing) {
existing.changeCount++;
if (!existing.users.includes(entry.userName)) {
existing.users.push(entry.userName);
}
if (entry.timestamp > existing.lastChange) {
existing.lastChange = entry.timestamp;
}
} else {
grouped.set(key, {
entityType: entry.entityType,
entityId: entry.entityId,
changeCount: 1,
users: [entry.userName],
lastChange: entry.timestamp,
});
}
}
return Array.from(grouped.values());
}
```
## Using TypeGraph's Built-in Temporal Features
### View Entity at Point in Time
```typescript
async function getSettingAsOf(
id: string,
timestamp: Date
): Promise {
return store
.query()
.from("Setting", "s")
.temporal("asOf", timestamp.toISOString())
.whereNode("s", (s) => s.id.eq(id))
.select((ctx) => ctx.s)
.first();
}
```
### Get All Versions
```typescript
interface SettingVersion {
props: SettingProps;
validFrom: string;
validTo: string | undefined;
version: number;
}
async function getSettingVersions(id: string): Promise {
return store
.query()
.from("Setting", "s")
.temporal("includeEnded")
.whereNode("s", (s) => s.id.eq(id))
.orderBy((ctx) => ctx.s.validFrom, "desc")
.select((ctx) => ({
props: ctx.s,
validFrom: ctx.s.validFrom,
validTo: ctx.s.validTo,
version: ctx.s.version,
}))
.execute();
}
```
### Compare Versions
```typescript
interface VersionDiff {
field: string;
before: unknown;
after: unknown;
}
async function compareVersions(
id: string,
version1: number,
version2: number
): Promise {
const versions = await store
.query()
.from("Setting", "s")
.temporal("includeEnded")
.whereNode("s", (s) => s.id.eq(id).and(s.version.in([version1, version2])))
.orderBy((ctx) => ctx.s.version, "asc")
.select((ctx) => ctx.s)
.execute();
if (versions.length !== 2) {
throw new Error("Versions not found");
}
const [before, after] = versions;
const diffs: VersionDiff[] = [];
const allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);
for (const key of allKeys) {
const beforeVal = before[key as keyof typeof before];
const afterVal = after[key as keyof typeof after];
if (JSON.stringify(beforeVal) !== JSON.stringify(afterVal)) {
diffs.push({ field: key, before: beforeVal, after: afterVal });
}
}
return diffs;
}
```
## Session Management
### Start Session
```typescript
async function startSession(
userId: string,
metadata: { ipAddress?: string; userAgent?: string }
): Promise> {
return store.transaction(async (tx) => {
const session = await tx.nodes.Session.create({
startedAt: new Date().toISOString(),
ipAddress: metadata.ipAddress,
userAgent: metadata.userAgent,
});
const user = await tx.nodes.User.getById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
await tx.edges.hasSession.create(user, session, {});
return session;
});
}
```
### End Session
```typescript
async function endSession(sessionId: string): Promise {
await store.nodes.Session.update(sessionId, {
endedAt: new Date().toISOString(),
});
}
```
### Get Session Activity
```typescript
async function getSessionActivity(
sessionId: string
): Promise> {
return store
.query()
.from("Session", "s")
.whereNode("s", (s) => s.id.eq(sessionId))
.traverse("inSession", "e", { direction: "in" })
.to("AuditEntry", "a")
.orderBy((ctx) => ctx.a.timestamp, "asc")
.select((ctx) => ({
timestamp: ctx.a.timestamp,
action: ctx.a.action,
entityType: ctx.a.entityType,
}))
.execute();
}
```
## Compliance Queries
### Who Changed This?
```typescript
async function whoChanged(
entityType: string,
entityId: string,
field: string
): Promise> {
const entries = await store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) =>
a.entityType.eq(entityType).and(a.entityId.eq(entityId))
)
.traverse("performedBy", "e")
.to("User", "u")
.orderBy((ctx) => ctx.a.timestamp, "desc")
.select((ctx) => ({
changes: ctx.a.changes,
user: ctx.u.name,
timestamp: ctx.a.timestamp,
}))
.execute();
return entries
.filter((e) => e.changes && field in e.changes)
.map((e) => ({
user: e.user,
timestamp: e.timestamp,
before: e.changes![field].before,
after: e.changes![field].after,
}));
}
```
### When Was This Value Set?
```typescript
async function whenWasValueSet(
entityType: string,
entityId: string,
field: string,
value: unknown
): Promise<{ timestamp: string; user: string } | undefined> {
const entries = await store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) =>
a.entityType.eq(entityType).and(a.entityId.eq(entityId))
)
.traverse("performedBy", "e")
.to("User", "u")
.orderBy((ctx) => ctx.a.timestamp, "asc")
.select((ctx) => ({
changes: ctx.a.changes,
user: ctx.u.name,
timestamp: ctx.a.timestamp,
}))
.execute();
const entry = entries.find(
(e) => e.changes && field in e.changes && e.changes[field].after === value
);
return entry ? { timestamp: entry.timestamp, user: entry.user } : undefined;
}
```
### Search Audit Trail by Reason
Compliance questions rarely come with exact match criteria — "find
everything related to the data-retention incident in Q3" is more
common than "find entries with reason = 'X'". Fulltext over the
`reason` field gives reviewers a BM25-ranked list instead of a brittle
substring match:
```typescript
async function searchAuditByReason(
query: string,
options: { since?: Date; limit?: number } = {},
) {
const { since, limit = 25 } = options;
const hits = await store.search.fulltext("AuditEntry", {
query,
limit: since ? limit * 4 : limit,
includeSnippets: true,
});
if (since === undefined) {
return hits.map((hit) => ({
entry: hit.node,
score: hit.score,
snippet: hit.snippet,
}));
}
const cutoff = since.toISOString();
return hits
.filter((hit) => hit.node.timestamp >= cutoff)
.slice(0, limit)
.map((hit) => ({
entry: hit.node,
score: hit.score,
snippet: hit.snippet,
}));
}
```
For stricter date-range composition (the fulltext candidate pool is
bounded by the `limit` above), use the query-builder path:
```typescript
async function searchAuditInRange(
query: string,
startDate: Date,
endDate: Date,
limit = 25,
) {
return store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) =>
a.$fulltext
.matches(query, limit * 2)
.and(a.timestamp.gte(startDate.toISOString()))
.and(a.timestamp.lte(endDate.toISOString())),
)
.select((ctx) => ctx.a)
.execute();
}
```
## Export Audit Logs
### Stream to External System
```typescript
async function* exportAuditLogs(
since: Date,
batchSize = 1000
): AsyncGenerator {
const stream = store
.query()
.from("AuditEntry", "a")
.whereNode("a", (a) => a.timestamp.gte(since.toISOString()))
.traverse("performedBy", "e")
.to("User", "u")
.orderBy((ctx) => ctx.a.timestamp, "asc")
.select((ctx) => ({
...ctx.a,
performedBy: ctx.u.email,
}))
.stream({ batchSize });
let batch: AuditEntryProps[] = [];
for await (const entry of stream) {
batch.push(entry);
if (batch.length >= batchSize) {
yield batch;
batch = [];
}
}
if (batch.length > 0) {
yield batch;
}
}
// Usage
async function syncToExternalAuditSystem(since: Date): Promise {
for await (const batch of exportAuditLogs(since)) {
await externalAuditApi.ingestBatch(batch);
}
}
```
## Next Steps
- [Document Management](/examples/document-management) - CMS with semantic search
- [Product Catalog](/examples/product-catalog) - Categories, variants, inventory
- [Workflow Engine](/examples/workflow-engine) - State machines with approvals
# Bitemporal Time Travel
> Valid time plus recorded time for corrections, effective dating, and the bitemporal 2x2
This example shows TypeGraph's built-in temporal history path:
- **Valid time**: when a fact is true in the world, controlled by
`validFrom` / `validTo` and read with `store.asOf(T)`.
- **Recorded time**: when TypeGraph wrote the fact down, enabled with
`history: true` and read with `store.asOfRecorded(T)`.
Together they let you answer the audit question a single clock cannot express
for TypeGraph-managed writes: what TypeGraph captured as true at a recorded
commit instant.
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/20-bitemporal-time-travel.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/20-bitemporal-time-travel.ts)
:::
## What It Demonstrates
- Recorded-time reconstruction after a correction: the invoice amount as it was
first reported versus the amount known now.
- Valid-time effective dating: a promotion active only inside its validity
window.
- The bitemporal 2x2: the same subscription question answered at two valid-time
instants and two recorded-time instants.
- `store.recordedNow()` as the stable recorded-time anchor after writes.
- `store.asOf(validT).asOfRecorded(recordedT)` for independent valid and
recorded axes.
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/20-bitemporal-time-travel.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/20-bitemporal-time-travel.ts
```
It uses an in-memory SQLite backend with `history: true`, so it needs no Docker
or external services.
## Core API
```typescript
const [store] = await createStoreWithSchema(graph, backend, {
history: true,
});
const invoice = await store.nodes.Invoice.create({
vendor: "Acme",
amount: 1000,
});
const asReported = await store.recordedNow();
if (asReported === undefined) throw new Error("expected recorded history");
await store.nodes.Invoice.update(invoice.id, {
vendor: "Acme",
amount: 1250,
});
const reportedThen = await store
.asOfRecorded(asReported)
.nodes.Invoice.getById(invoice.id);
```
For independent axes, start from a valid-time view and add the recorded-time pin:
```typescript
const capturedOnJul15BeforeCorrection = await store
.asOf("2024-07-15T00:00:00.000Z")
.asOfRecorded(beforeCorrection)
.nodes.Subscription.getById(subscriptionId);
```
Direct `store.asOfRecorded(T)` is diagonal sugar: it pins the recorded axis and
the valid-time axis to the same recorded instant. Chaining from `store.asOf(T)`
is the form to use when the domain-effective date and the TypeGraph-capture date
are different.
## Sample Output
```text
[1] Recorded time - a correction
Invoice inv_... (vendor: Acme)
as reported (asOfRecorded): $1000
as known now (live read): $1250
[3] Both axes - the bitemporal 2x2
valid-time ↓ \ recorded-time -> before correction now
valid May 1 ✓ active ✓ active
valid Jul 15 ✗ inactive ✓ active
```
The Jul-15 / before-correction cell is the important one: at that valid date,
the captured graph state had the subscription already cancelled, even though you
now know it was still active.
## When to Use This Pattern
Use bitemporal reads when the difference between **truth in the domain** and
**captured TypeGraph state** matters:
- Financial restatements and audit reports
- Policy or contract effective dating
- Compliance snapshots generated from later-corrected data
- Support investigations where the system's earlier captured state matters
See [Temporal queries](/queries/temporal#recorded-time-bitemporal) for the full
API contract and limitations.
# Breach Forensics
> Pin an access graph to the breach instant and traverse the real blast radius
This example uses bitemporal graph reconstruction for incident response. The
question after a breach is not "what can this account reach now?" It is "what
could this account reach at the moment of compromise?"
By the time the investigation starts, dangerous grants may have been revoked or
hard-deleted. A live graph can understate exposure. With `history: true`, you can
pin the access graph to the recorded breach instant and run `reachable()` over
the reconstructed graph.
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/22-breach-forensics.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/22-breach-forensics.ts)
:::
## What It Demonstrates
- A role/access graph with `Account -> Role -> Resource` paths.
- A dangerous `deployer -> admin` escalation edge that is later hard-deleted.
- `store.recordedNow()` as the breach-time recorded anchor.
- `store.asOfRecorded(breachTime).reachable(...)` to reconstruct the blast
radius at compromise time.
- Point reads (`getByIds`) on the recorded view to resolve reached resources.
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/22-breach-forensics.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/22-breach-forensics.ts
```
## The Access Graph
```text
svc-deploy --assumes--> deployer --grants--> ci-secrets
|
escalates
v
admin --grants--> prod-db, customer-pii
```
The `escalates` edge is the dangerous misconfiguration. Incident response
removes it, but the recorded graph still knows it existed at the breach instant.
## Core API
```typescript
const breachTime = await store.recordedNow();
if (breachTime === undefined) throw new Error("expected recorded history");
await store.edges.escalates.hardDelete(overGrant.id);
const reachedAtBreach = await store
.asOfRecorded(breachTime)
.reachable(account.id, {
edges: ["assumes", "escalates", "grants"],
maxHops: 10,
});
```
The example wraps this in a small helper that accepts either a live view or a
recorded view:
```typescript
type AccessView = Pick<
RecordedStoreView,
"reachable" | "nodes"
>;
```
That shape matters: incident-response code can run the same traversal against
"now" and "then" without duplicating logic.
## Sample Output
```text
Reachable resources on the CURRENT graph:
- ci-secrets (medium)
Looks contained - but the escalation was deleted.
Reachable resources reconstructed AT THE BREACH INSTANT:
- ci-secrets (medium)
- prod-db (high) <- EXPOSED
- customer-pii (critical) <- EXPOSED
```
## When to Use This Pattern
Use bitemporal graph forensics when deleted or corrected relationships affect
the answer:
- Identity and access blast-radius analysis
- Data-sharing and entitlement investigations
- Incident timelines where cleanup changed the graph
- "Who could reach what?" reports at a historical recorded instant
See [Temporal queries](/queries/temporal#recorded-time-bitemporal) for
recorded-time constraints and [Graph Algorithms](/graph-algorithms) for
`reachable()`.
# Document Management System
> A complete CMS example with semantic search, versioning, and access control
This example builds a document management system with:
- **Document hierarchy** (folders, documents, sections)
- **Semantic search** with vector embeddings
- **Version history** using temporal queries
- **Access control** with permission inheritance
- **Related documents** discovery
## Schema Definition
```typescript
import { z } from "zod";
import {
defineNode,
defineEdge,
defineGraph,
embedding,
searchable,
subClassOf,
partOf,
hasPart,
} from "@nicia-ai/typegraph";
// Base content type (abstract)
const Content = defineNode("Content", {
schema: z.object({
title: z.string(),
createdBy: z.string(),
status: z.enum(["draft", "published", "archived"]).default("draft"),
}),
});
// Folder extends Content
const Folder = defineNode("Folder", {
schema: z.object({
title: z.string(),
createdBy: z.string(),
status: z.enum(["draft", "published", "archived"]).default("draft"),
path: z.string(), // /engineering/specs
}),
});
// Document extends Content
const Document = defineNode("Document", {
schema: z.object({
// Both fields are indexed for BM25 ranked fulltext. Combined with
// the embedding below, this unlocks hybrid retrieval: title matches
// (proper nouns, acronyms, terms-of-art) via BM25 plus paraphrased
// / conceptual matches via the embedding.
title: searchable({ language: "english" }),
content: searchable({ language: "english" }),
createdBy: z.string(),
status: z.enum(["draft", "published", "archived"]).default("draft"),
contentType: z.enum(["markdown", "html", "plaintext"]).default("markdown"),
embedding: embedding(1536).optional(),
}),
});
// Users and permissions
const User = defineNode("User", {
schema: z.object({
email: z.string().email(),
name: z.string(),
role: z.enum(["admin", "editor", "viewer"]).default("viewer"),
}),
});
const Permission = defineNode("Permission", {
schema: z.object({
level: z.enum(["read", "write", "admin"]),
}),
});
// Edges
const contains = defineEdge("contains");
const relatedTo = defineEdge("relatedTo", {
schema: z.object({
type: z.enum(["references", "supersedes", "related"]),
confidence: z.number().min(0).max(1).optional(),
}),
});
const hasPermission = defineEdge("hasPermission");
const createdBy = defineEdge("createdBy");
// Graph definition
const graph = defineGraph({
id: "document_management",
nodes: {
Content: { type: Content },
Folder: {
type: Folder,
unique: [
{
name: "folder_path",
fields: ["path"],
scope: "kind",
collation: "binary",
},
],
},
Document: { type: Document },
User: {
type: User,
unique: [
{
name: "user_email",
fields: ["email"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
Permission: { type: Permission },
},
edges: {
contains: { type: contains, from: [Folder], to: [Folder, Document] },
relatedTo: { type: relatedTo, from: [Document], to: [Document] },
hasPermission: { type: hasPermission, from: [User], to: [Content] },
createdBy: { type: createdBy, from: [Content], to: [User] },
},
ontology: [
// Type hierarchy
subClassOf(Folder, Content),
subClassOf(Document, Content),
// Compositional relationships
partOf(Document, Folder),
hasPart(Folder, Document),
],
});
```
## Database Setup
```typescript
import { createLocalSqliteBackend } from "@nicia-ai/typegraph/adapters/drizzle/sqlite/local";
import { createStoreWithSchema } from "@nicia-ai/typegraph";
// `createLocalSqliteBackend` loads sqlite-vec (an optional peer dep) and wires
// the vector strategy, so `embedding()` fields are persisted to real `vec0`
// KNN storage. It also runs the base DDL for you.
const { backend } = createLocalSqliteBackend({ path: "documents.db" });
// `searchable()` fields require the durable fulltext-materialization
// step that `createStoreWithSchema` performs at boot. Bare
// `createStore()` is an attach-only path and would throw
// `StoreNotInitializedError` on the first fulltext write.
const [store] = await createStoreWithSchema(graph, backend);
```
## Core Operations
### Creating Folder Structure
```typescript
async function createFolderPath(path: string, userId: string): Promise> {
const parts = path.split("/").filter(Boolean);
let currentPath = "";
let parentFolder: Node | undefined;
for (const part of parts) {
currentPath += `/${part}`;
// The `folder_path` unique constraint makes this atomic: concurrent
// callers converge on one folder instead of racing to create duplicates.
const result = await store.nodes.Folder.getOrCreateByConstraint(
"folder_path",
{
title: part,
path: currentPath,
createdBy: userId,
status: "published",
},
);
if (result.action === "created" && parentFolder) {
await store.edges.contains.create(parentFolder, result.node, {});
}
parentFolder = result.node;
}
return parentFolder!;
}
```
### Creating Documents with Embeddings
```typescript
import OpenAI from "openai";
const openai = new OpenAI();
async function generateEmbedding(text: string): Promise {
const response = await openai.embeddings.create({
model: "text-embedding-ada-002",
input: text,
});
return response.data[0].embedding;
}
async function createDocument(
folderId: string,
title: string,
content: string,
userId: string
): Promise> {
const embedding = await generateEmbedding(`${title}\n\n${content}`);
const document = await store.nodes.Document.create({
title,
content,
createdBy: userId,
status: "draft",
contentType: "markdown",
embedding,
});
// Link to folder
const folder = await store.nodes.Folder.getById(folderId);
if (!folder) throw new Error(`Folder not found: ${folderId}`);
await store.edges.contains.create(folder, document, {});
// Link to creator
const user = await store.nodes.User.getById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
await store.edges.createdBy.create(document, user, {});
return document;
}
```
### Updating Documents (Versioned)
```typescript
async function updateDocument(
documentId: string,
updates: { title?: string; content?: string; status?: "draft" | "published" | "archived" }
): Promise> {
const current = await store.nodes.Document.getById(documentId);
if (!current) throw new Error(`Document not found: ${documentId}`);
// If content changed, regenerate embedding
let embedding = current.embedding;
if (updates.content && updates.content !== current.content) {
const text = `${updates.title ?? current.title}\n\n${updates.content}`;
embedding = await generateEmbedding(text);
}
// Update creates a new version automatically
return store.nodes.Document.update(documentId, {
...updates,
embedding,
});
}
```
## Searching Documents
Document search is the canonical hybrid-retrieval use case. Users search
for proper nouns, project names, and quoted phrases that embeddings
smooth over, plus conceptual questions that keyword search alone
can't answer. This example shows both sides.
### Semantic Search
Embedding-only search is still useful when the query is a paraphrase or
a question rather than a set of keywords:
```typescript
async function searchDocumentsSemantically(
query: string,
options: {
folderId?: string;
status?: "draft" | "published" | "archived";
limit?: number;
minScore?: number;
} = {}
): Promise {
const { folderId, status = "published", limit = 10, minScore = 0.7 } = options;
const queryEmbedding = await generateEmbedding(query);
let queryBuilder = store
.query()
.from("Document", "d")
.whereNode("d", (d) =>
d.embedding
.similarTo(queryEmbedding, limit, { metric: "cosine", minScore })
.and(d.status.eq(status)),
);
// If folderId specified, filter to folder descendants
if (folderId) {
queryBuilder = store
.query()
.from("Folder", "f")
.whereNode("f", (f) => f.id.eq(folderId))
.traverse("contains", "e")
.recursive()
.to("Document", "d")
.whereNode("d", (d) =>
d.embedding
.similarTo(queryEmbedding, limit, { metric: "cosine", minScore })
.and(d.status.eq(status)),
);
}
// Results are already ordered by similarity (most similar first).
return queryBuilder.select((ctx) => ctx.d).execute();
}
```
### Fulltext Search (BM25 with snippets)
When the user types a proper noun, filename, or exact phrase, keyword
search outperforms embeddings — and snippets give them a preview of
where the match occurred:
```typescript
async function findDocumentsByKeyword(
query: string,
options: { limit?: number } = {},
): Promise> {
const hits = await store.search.fulltext("Document", {
query,
limit: options.limit ?? 10,
includeSnippets: true,
});
return hits.map((hit) => ({
document: hit.node,
score: hit.score,
snippet: hit.snippet,
}));
}
```
### Hybrid Search (the production-grade path)
Most document-search products want both signals. `store.search.hybrid()`
runs fulltext + vector in parallel and fuses the rankings with RRF.
Each hit carries sub-scores from each half for debugging:
```typescript
async function searchDocuments(
query: string,
options: {
status?: "draft" | "published" | "archived";
limit?: number;
} = {},
): Promise> {
const { status = "published", limit = 10 } = options;
const queryEmbedding = await generateEmbedding(query);
const hits = await store.search.hybrid("Document", {
limit,
vector: {
fieldPath: "embedding",
queryEmbedding,
metric: "cosine",
k: limit * 4,
},
fulltext: {
query,
k: limit * 4,
includeSnippets: true,
},
fusion: { method: "rrf", k: 60 },
});
return hits
.filter((hit) => hit.node.status === status)
.map((hit) => ({
document: hit.node,
score: hit.score,
snippet: hit.fulltext?.snippet,
}));
}
```
### Folder-Scoped Hybrid Search (query builder path)
For tighter composition — "only within this folder subtree, using hybrid
retrieval" — `$fulltext.matches()` and `.similarTo()` combine in one
query-builder statement. The fusion runs at the SQL layer:
```typescript
async function searchInFolder(
folderId: string,
query: string,
limit = 10,
): Promise {
const queryEmbedding = await generateEmbedding(query);
return store
.query()
.from("Folder", "f")
.whereNode("f", (f) => f.id.eq(folderId))
.traverse("contains", "e")
.recursive()
.to("Document", "d")
.whereNode("d", (d) =>
d.$fulltext
.matches(query, limit * 4)
.and(d.embedding.similarTo(queryEmbedding, limit * 4))
.and(d.status.eq("published")),
)
.fuseWith({ k: 60 })
.select((ctx) => ctx.d)
.limit(limit)
.execute();
}
```
### Find Related Documents
```typescript
async function findRelatedDocuments(
documentId: string,
limit = 5
): Promise> {
// First, get explicit relationships
const explicit = await store
.query()
.from("Document", "d")
.whereNode("d", (d) => d.id.eq(documentId))
.traverse("relatedTo", "e")
.to("Document", "related")
.select((ctx) => ({
document: ctx.related,
relationship: ctx.e.type,
}))
.execute();
// Then, find semantically similar documents
const source = await store.nodes.Document.getById(documentId);
if (!source) throw new Error(`Document not found: ${documentId}`);
if (!source.embedding) {
return explicit;
}
const similar = await store
.query()
.from("Document", "d")
.whereNode("d", (d) =>
d.embedding
.similarTo(source.embedding!, limit * 2, { metric: "cosine", minScore: 0.8 })
.and(d.id.neq(documentId))
)
.select((ctx) => ({
document: ctx.d,
relationship: "similar" as const,
}))
.limit(limit)
.execute();
return [...explicit, ...similar].slice(0, limit);
}
```
## Version History
### Get Document History
```typescript
interface DocumentVersion {
title: string;
content: string;
status: string;
validFrom: string;
validTo: string | undefined;
version: number;
}
async function getDocumentHistory(documentId: string): Promise {
return store
.query()
.from("Document", "d")
.temporal("includeEnded")
.whereNode("d", (d) => d.id.eq(documentId))
.orderBy((ctx) => ctx.d.validFrom, "desc")
.select((ctx) => ({
title: ctx.d.title,
content: ctx.d.content,
status: ctx.d.status,
validFrom: ctx.d.validFrom,
validTo: ctx.d.validTo,
version: ctx.d.version,
}))
.execute();
}
```
### View Document at Point in Time
```typescript
async function getDocumentAsOf(
documentId: string,
timestamp: Date
): Promise {
return store
.query()
.from("Document", "d")
.temporal("asOf", timestamp.toISOString())
.whereNode("d", (d) => d.id.eq(documentId))
.select((ctx) => ctx.d)
.first();
}
```
### Compare Versions
```typescript
async function compareVersions(
documentId: string,
version1: number,
version2: number
): Promise<{ before: DocumentProps; after: DocumentProps } | undefined> {
const versions = await store
.query()
.from("Document", "d")
.temporal("includeEnded")
.whereNode("d", (d) =>
d.id.eq(documentId).and(d.version.in([version1, version2]))
)
.orderBy((ctx) => ctx.d.version, "asc")
.select((ctx) => ctx.d)
.execute();
if (versions.length !== 2) return undefined;
return { before: versions[0], after: versions[1] };
}
```
## Access Control
### Check Read Permission
```typescript
async function canRead(userId: string, contentId: string): Promise {
// Check direct permission
const directPermission = await store
.query()
.from("User", "u")
.whereNode("u", (u) => u.id.eq(userId))
.traverse("hasPermission", "p")
.to("Content", "c", { includeSubClasses: true })
.whereNode("c", (c) => c.id.eq(contentId))
.first();
if (directPermission) return true;
// Check inherited permission (from parent folders)
const content = await store.nodes.Content.getById(contentId);
if (!content) return false;
// Walk up the folder tree checking permissions
const parentFolders = await store
.query()
.from("Folder", "f")
.traverse("contains", "e")
.recursive()
.to("Content", "c", { includeSubClasses: true })
.whereNode("c", (c) => c.id.eq(contentId))
.select((ctx) => ctx.f.id)
.execute();
for (const folderId of parentFolders) {
const folderPermission = await store
.query()
.from("User", "u")
.whereNode("u", (u) => u.id.eq(userId))
.traverse("hasPermission", "p")
.to("Folder", "f")
.whereNode("f", (f) => f.id.eq(folderId))
.first();
if (folderPermission) return true;
}
return false;
}
```
### Grant Permission
```typescript
async function grantPermission(
userId: string,
contentId: string,
level: "read" | "write" | "admin"
): Promise {
const user = await store.nodes.User.getById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
const content = await store.nodes.Content.getById(contentId);
if (!content) throw new Error(`Content not found: ${contentId}`);
// Create permission node
const permission = await store.nodes.Permission.create({ level });
// Link user to content via permission
await store.edges.hasPermission.create(user, content, {});
}
```
## Folder Navigation
### Get Folder Contents
```typescript
interface FolderContents {
folders: Array<{ id: string; title: string; path: string }>;
documents: Array<{ id: string; title: string; status: string }>;
}
async function getFolderContents(folderId: string): Promise {
const folders = await store
.query()
.from("Folder", "parent")
.whereNode("parent", (f) => f.id.eq(folderId))
.traverse("contains", "e")
.to("Folder", "child")
.select((ctx) => ({
id: ctx.child.id,
title: ctx.child.title,
path: ctx.child.path,
}))
.execute();
const documents = await store
.query()
.from("Folder", "parent")
.whereNode("parent", (f) => f.id.eq(folderId))
.traverse("contains", "e")
.to("Document", "doc")
.select((ctx) => ({
id: ctx.doc.id,
title: ctx.doc.title,
status: ctx.doc.status,
}))
.execute();
return { folders, documents };
}
```
### Get Breadcrumb Path
`store.algorithms.reachable` walks `contains` edges in reverse to collect
every ancestor folder, tagged with its depth from the starting content:
```typescript
async function getBreadcrumb(
contentId: string
): Promise> {
const ancestors = await store.algorithms.reachable(contentId, {
edges: ["contains"],
direction: "in",
excludeSource: true,
});
if (ancestors.length === 0) return [];
const folderIds = ancestors
.filter((node) => node.kind === "Folder")
.toSorted((a, b) => b.depth - a.depth) // root first
.map((node) => node.id);
const folders = await store.nodes.Folder.getByIds(folderIds);
return folders
.filter((folder): folder is NonNullable => folder !== undefined)
.map((folder) => ({
id: folder.id,
title: folder.title,
path: folder.path,
}));
}
```
`reachable` returns `{ id, kind, depth }` from a set-based BFS frontier, then a
single batched `getByIds` hydrates the folder properties.
## Bulk Operations
### Move Document to Folder
```typescript
async function moveDocument(documentId: string, targetFolderId: string): Promise {
await store.transaction(async (tx) => {
// Remove from current folder
const currentEdge = await tx
.query()
.from("Folder", "f")
.traverse("contains", "e")
.to("Document", "d")
.whereNode("d", (d) => d.id.eq(documentId))
.select((ctx) => ctx.e.id)
.first();
if (currentEdge) {
await tx.edges.contains.delete(currentEdge);
}
// Add to new folder
const document = await tx.nodes.Document.getById(documentId);
if (!document) throw new Error(`Document not found: ${documentId}`);
const targetFolder = await tx.nodes.Folder.getById(targetFolderId);
if (!targetFolder) throw new Error(`Folder not found: ${targetFolderId}`);
await tx.edges.contains.create(targetFolder, document, {});
});
}
```
### Bulk Archive
```typescript
async function archiveFolder(folderId: string): Promise {
// Get all documents in folder and subfolders
const documents = await store
.query()
.from("Folder", "f")
.whereNode("f", (f) => f.id.eq(folderId))
.traverse("contains", "e")
.recursive()
.to("Document", "d")
.select((ctx) => ctx.d.id)
.execute();
// Archive each document
await store.transaction(async (tx) => {
for (const docId of documents) {
await tx.nodes.Document.update(docId, { status: "archived" });
}
});
return documents.length;
}
```
## Next Steps
- [Product Catalog](/examples/product-catalog) - Categories, variants, inventory
- [Workflow Engine](/examples/workflow-engine) - State machines with approvals
- [Audit Trail](/examples/audit-trail) - Complete change tracking
# FHIR Graph Merge
> Reconcile overlapping FHIR-style records from independent branches into one canonical patient care graph.
This example shows TypeGraph's graph-merge primitive on a concrete healthcare
interoperability problem: two independent ingestion agents extract overlapping
FHIR-style records, disagree on patient spelling, and produce separate care
context. TypeGraph branches isolate those writes. `merge()` folds them into one
base graph, resolves the duplicate patient, repoints each branch's clinical
edges, and reports the conflict/provenance trail.
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/18-fhir-graph-merge.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/18-fhir-graph-merge.ts)
:::
:::caution[Synthetic demo data only]
This is an interoperability and data-exploration example. It is not clinical
decision support and should not be run on protected health information as-is.
The bundled patient record is synthetic and intentionally small.
:::
## What It Demonstrates
- `branch()` creates isolated working copies over fresh local SQLite backends.
- Two patient pairs are reconciled by **two different mechanisms**, so you can
see exact identity and fuzzy resolution side by side:
- **`Anna Rivera` / `Ana Rivera`** share a unique MRN. The unique constraint
forces this merge by **exact identity** — fuzzy scoring is bypassed, so the
similarity threshold is irrelevant to their collapse.
- **`Mohammed Ali` / `Mohamed Ali`** have **different** MRNs, so nothing forces
them. Only the in-memory fulltext name similarity clearing the threshold
collapses them — this is the case where similarity is actually decisive.
- Care-context edges from both branches are repointed onto each canonical
patient. The output proves this by reading context through `forPatient` edges
*into* the survivor, not via a blanket `.find()`.
- The merge report surfaces every spelling / identifier disagreement (name,
MRN, FHIR id) instead of silently choosing a winner.
- Report provenance shows which branch contributed the canonical nodes and
edges.
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/18-fhir-graph-merge.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/18-fhir-graph-merge.ts
```
The example uses in-memory SQLite backends, so it does not require Docker, a
FHIR server, or external services.
## Sample Output
```text
=== FHIR Graph Merge ===
Before merge:
base patients: 0
EHR branch patients: 2
claims branch patients: 2
After merge:
merged nodes: 9
merged edges: 10
entity resolutions: 2
conflicts:
- Patient.fhirId on patient-ana: claims-agent="Patient/claims-ana", ehr-agent="Patient/ehr-anna"
- Patient.name on patient-ana: claims-agent="Ana Rivera", ehr-agent="Anna Rivera"
- Patient.fhirId on patient-mohamed: claims-agent="Patient/claims-mohamed", ehr-agent="Patient/ehr-mohammed"
- Patient.mrn on patient-mohamed: claims-agent="MRN-205", ehr-agent="MRN-204"
- Patient.name on patient-mohamed: claims-agent="Mohamed Ali", ehr-agent="Mohammed Ali"
provenance:
- ehr-agent: 6 node(s), 6 edge(s)
- claims-agent: 5 node(s), 4 edge(s)
Canonical patients and their repointed care context:
Ana Rivera (MRN-001, 1974-03-09)
- Encounter: Hypertension follow-up (2026-04-11T09:30:00-07:00)
- Encounter: Kidney function review (2026-04-14T10:00:00-07:00)
- MedicationRequest: Lisinopril 10 MG Oral Tablet - Take one tablet by mouth daily
- Observation: Blood pressure panel = 152/96 mmHg (high)
- Observation: Estimated glomerular filtration rate = 54 mL/min/1.73m2 (low)
Mohamed Ali (MRN-205, 1990-08-21)
- Encounter: Cardiology consult (2026-05-02T13:00:00-07:00)
- Observation: LDL cholesterol = 168 mg/dL (high)
```
The `Mohamed Ali` line is the proof that fuzzy resolution and edge repointing
both work: the two spellings carried **different** MRNs (so no exact match
forced them), yet they collapsed to one patient — and that patient now owns the
EHR branch's cardiology encounter *and* the claims branch's lab observation,
each repointed from its origin branch.
## Graph Model
The example keeps the schema intentionally small:
| TypeGraph kind | FHIR-ish source | Purpose |
| -------------- | --------------- | ------- |
| `Patient` | `Patient` | The canonical person being reconciled |
| `Encounter` | `Encounter` | Clinical visit context |
| `Observation` | `Observation` | Vitals and lab evidence |
| `MedicationRequest` | `MedicationRequest` | Medication order |
| `forPatient` | `subject` references | Connects clinical resources to the patient |
| `duringEncounter` | `encounter` references | Connects observations/orders to visits |
| `reasonFor` | `reasonReference` | Connects an order to supporting evidence |
The `Patient` kind declares a unique MRN constraint:
```typescript
const careGraph = defineGraph({
nodes: {
Patient: {
type: Patient,
unique: [
{
name: "patient_mrn",
fields: ["mrn"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
},
});
```
A shared unique value is a **definitional** identity source: when two staged
nodes share all of a constraint's fields, they are forced to merge and fuzzy
scoring is bypassed entirely. That is what collapses `Anna Rivera` / `Ana Rivera`
(both `MRN-001`) — the similarity threshold never enters into it. The merge still
reports their property disagreements (`name`, `fhirId`).
## Merge Configuration
The example configures entity resolution only for `Patient`; other kinds merge
by ID and keep their branch-specific clinical context.
```typescript
const mergeOptions = {
resolve: {
Patient: {
// Block by shared birth date. The unique MRN constraint forces exact
// matches in its own bucket, so blocking does not need the MRN — and using
// it would split the different-MRN fuzzy pair apart.
block: (node) => node.birthDate,
similarity: { kind: "fulltext", fields: ["name"] },
threshold: 0.78,
},
},
onPropertyConflict: "flag",
branchOrder: [EHR_BRANCH, CLAIMS_BRANCH],
provenance: true,
};
```
The `fulltext` strategy is an in-memory trigram scorer. It does not require
embeddings, database fulltext indexes, or a specific backend, which makes it a
good default for bounded candidate dedup during merge. It is the **decisive**
signal for `Mohammed Ali` / `Mohamed Ali`: those records carry different MRNs,
so no unique match forces them — only the name score clearing `threshold`
collapses them.
## Why This Matters
FHIR imports often arrive from multiple systems: EHR exports, claims feeds,
lab feeds, patient-reported questionnaires, and agent-produced extraction
passes. Each source can be useful, but naive append-only ingestion leaves
duplicates and broken care context.
Graph merge gives you a deterministic reconciliation step:
1. Run each extractor in an isolated branch.
2. Keep all writes type-checked by the same TypeGraph schema.
3. Resolve entities by exact identity, blocking keys, and similarity.
4. Preserve branch-specific context by repointing edges.
5. Return a merge report that callers can inspect, persist, or route for human
review.
See [Graph Merge](/graph-merge) for the API reference and option semantics.
# Incremental Merge
> Ingest into a live graph in waves — mergeIncremental() folds a new source onto an already-committed graph without creating duplicates, and persists a queryable provenance trail.
This example shows TypeGraph's **incremental** merge path. Where the snapshot
[`merge()`](/examples/fhir-graph-merge) reconciles branches that all forked from
the *current* base, `mergeIncremental()` folds a new source's branch into a
`target` that has **already advanced** — re-discovering an entity that was
committed in an earlier wave and merging onto it instead of creating a duplicate.
It is the primitive for **continuous ingestion**: every new feed, crawl, or
agent batch lands on the live graph, deduplicated against what is already there.
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/19-incremental-merge.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/19-incremental-merge.ts)
:::
## What It Demonstrates
- A `target` graph that already holds one committed `Company` ("Acme Corp").
- A new provider branch (forked from an empty fork-point in this example) that
re-reports the same company under a different spelling
("ACME Corporation", same `acme.com` domain) and adds a genuinely new one
("Globex").
- `mergeIncremental()` recalls the committed company via its unique `domain` and
merges the new spelling **onto** it — the target keeps one Acme, not two.
- The name disagreement is flagged in the report instead of silently overwriting
the committed value.
- Provenance is persisted to a sidecar graph and queried back: "which canonical
entities did this provider contribute to?"
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/19-incremental-merge.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/19-incremental-merge.ts
```
It uses in-memory SQLite backends, so it needs no Docker or external services.
## Sample Output
```text
=== Incremental Graph Merge ===
Target before: [ 'Acme Corp (acme.com)' ]
Target after: [ 'Acme Corp (acme.com)', 'Globex (globex.io)' ]
No duplicate was created: the provider's "ACME Corporation" merged onto the
committed "Acme Corp" via the shared domain.
Merged nodes: 2
Entity resolutions: 1
Conflict on Company.name @ acme: provider-crunchbase="ACME Corporation"
Provenance persisted: 3 row(s) in sidecar "company_kb::merge-provenance"
Provenance — canonical entities this provider contributed to:
- Company "cb-globex" (from source "cb-globex")
- Company "acme" (from source "cb-acme")
```
## How It Works
```typescript
const result = await mergeIncremental({
forkPoint, // the frozen ancestor the provider branch forked from
target, // the live committed graph (already holds "Acme Corp")
branches: [provider],
options: {
resolve: {
Company: {
similarity: { kind: "fulltext", fields: ["name"] },
threshold: 0.9,
},
},
onPropertyConflict: "flag",
onBasePropertyConflict: "flag", // required by mergeIncremental (keep-base)
branchOrder: [PROVIDER],
persistProvenance: true,
},
});
```
Two ideas do the work:
1. **Unique `domain` as definitional identity.** The `Company` kind declares a
unique constraint on `domain`. The new-vs-base recall queries the target for
committed companies that share a staged company's domain, so "ACME
Corporation" (`acme.com`) is matched to the committed "Acme Corp" regardless
of the name spelling — no similarity threshold needs to be cleared.
2. **Keep-base conflict handling.** `onBasePropertyConflict: "flag"` guarantees
a stale branch value can never overwrite a newer committed one: the committed
`name` is kept and the provider's spelling is recorded as a conflict for
review.
The genuinely-new "Globex" has no committed match, so it is created. After the
commit, `persistProvenance` writes one row per contribution to a sidecar graph
on the target's backend, which `readProvenance` reads back later.
## Why This Matters
Real ingestion is never one-shot. Feeds arrive continuously, crawls re-run, and
agents produce overlapping batches. Append-only ingestion turns that into a pile
of duplicates; a full re-merge from scratch does not scale.
`mergeIncremental()` gives you a **steady-state ingestion loop**:
1. Take each new source as a branch off a known fork-point.
2. Merge it into the live target; already-known entities are recalled and
updated in place, inherited modifications/deletions propagate, and new ones
are created.
3. Keep concurrently changed committed data authoritative
(`onBasePropertyConflict: "flag"`).
4. Persist provenance so every canonical entity carries the trail of which
source contributed it.
See [Graph Merge](/graph-merge) for the full API reference, and
[FHIR Graph Merge](/examples/fhir-graph-merge) for the snapshot-merge
counterpart.
# Knowledge Graph for RAG
> Enhance retrieval with entity linking, relationship traversal, and multi-hop context
This example demonstrates how **graph structure enhances RAG** beyond vector similarity.
While [Semantic Search](/semantic-search) covers embedding basics, this guide focuses
on what graphs uniquely provide: entity disambiguation, relationship traversal,
and structured context that flat retrieval cannot offer.
## What Graphs Add to RAG
| Flat RAG | Graph RAG |
|----------|-----------|
| Returns similar chunks | Traverses to related entities and facts |
| Treats "Apple" the same everywhere | Disambiguates Apple Inc. vs. apple fruit |
| Context is unstructured text | Context includes structured relationships |
| Single-hop retrieval | Multi-hop reasoning across connections |
**Example**: For "What companies has Elon Musk founded?", flat RAG returns chunks
mentioning him. Graph RAG traverses from the "Elon Musk" entity through "founded"
edges to return structured company data—regardless of whether those facts appear
in the same chunk.
## Schema
```typescript
import { z } from "zod";
import { defineNode, defineEdge, defineGraph, embedding, inverseOf, searchable } from "@nicia-ai/typegraph";
// Source documents
const Document = defineNode("Document", {
schema: z.object({
title: searchable({ language: "english" }),
source: z.string(),
}),
});
// Text chunks with embeddings + fulltext
const Chunk = defineNode("Chunk", {
schema: z.object({
// `searchable()` enables `$fulltext.matches()` for BM25 ranking,
// complementing the embedding-based semantic search below.
text: searchable({ language: "english" }),
embedding: embedding(1536),
position: z.number().int(),
}),
});
// Extracted entities
const Entity = defineNode("Entity", {
schema: z.object({
name: searchable({ language: "english" }),
type: z.enum(["person", "organization", "location", "concept", "product", "event"]),
description: z.string().optional(),
embedding: embedding(1536).optional(),
}),
});
// Edges
const containsChunk = defineEdge("containsChunk");
const nextChunk = defineEdge("nextChunk");
const prevChunk = defineEdge("prevChunk");
const mentions = defineEdge("mentions", {
schema: z.object({
confidence: z.number().min(0).max(1).optional(),
}),
});
const relatesTo = defineEdge("relatesTo", {
schema: z.object({
relationship: z.string(), // "founded", "works_at", "located_in"
}),
});
export const graph = defineGraph({
id: "rag_graph",
nodes: {
Document: { type: Document },
Chunk: { type: Chunk },
Entity: {
type: Entity,
unique: [
{
name: "entity_name_type",
fields: ["name", "type"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
},
edges: {
containsChunk: { type: containsChunk, from: [Document], to: [Chunk] },
nextChunk: { type: nextChunk, from: [Chunk], to: [Chunk] },
prevChunk: { type: prevChunk, from: [Chunk], to: [Chunk] },
mentions: { type: mentions, from: [Chunk], to: [Entity] },
relatesTo: { type: relatesTo, from: [Entity], to: [Entity] },
},
ontology: [inverseOf(nextChunk, prevChunk)],
});
```
## Embedding Setup
Using [Vercel AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/embeddings):
```typescript
import { embed, embedMany } from "ai";
import { openai } from "@ai-sdk/openai";
const embeddingModel = openai.embeddingModel("text-embedding-3-small");
async function generateEmbedding(text: string): Promise {
const { embedding } = await embed({ model: embeddingModel, value: text });
return embedding;
}
async function generateEmbeddings(texts: string[]): Promise {
const { embeddings } = await embedMany({ model: embeddingModel, values: texts });
return embeddings;
}
```
## Ingestion with Entity Linking
The key graph RAG capability: linking chunks to disambiguated entities.
```typescript
import type { Node } from "@nicia-ai/typegraph";
interface ChunkData {
text: string;
entities: Array<{
name: string;
type: "person" | "organization" | "location" | "concept" | "product" | "event";
}>;
}
async function ingestDocument(
title: string,
source: string,
chunks: ChunkData[]
): Promise {
await store.transaction(async (tx) => {
const doc = await tx.nodes.Document.create({ title, source });
// Batch embed all chunks
const chunkEmbeddings = await generateEmbeddings(chunks.map((c) => c.text));
let prevChunk: Node | undefined;
for (const [i, chunkData] of chunks.entries()) {
const chunk = await tx.nodes.Chunk.create({
text: chunkData.text,
embedding: chunkEmbeddings[i],
position: i,
});
await tx.edges.containsChunk.create(doc, chunk, {});
if (prevChunk) {
await tx.edges.nextChunk.create(prevChunk, chunk, {});
}
// Link to entities (dedupe by unique constraint)
for (const entityData of chunkData.entities) {
const entityResult = await tx.nodes.Entity.getOrCreateByConstraint(
"entity_name_type",
{
name: entityData.name,
type: entityData.type,
}
);
// Compute expensive derived fields only for newly created entities
if (entityResult.action === "created") {
await tx.nodes.Entity.update(entityResult.node.id, {
embedding: await generateEmbedding(entityData.name),
});
}
await tx.edges.mentions.getOrCreateByEndpoints(
chunk,
entityResult.node,
{},
{ ifExists: "return" }
);
}
prevChunk = chunk;
}
});
}
```
## Graph-Specific Query Patterns
These patterns demonstrate capabilities that require graph structure—they cannot
be replicated with flat vector search.
### Entity-Based Retrieval
Find all chunks mentioning a specific entity, regardless of how it's phrased:
```typescript
async function findChunksByEntity(entityName: string) {
return store
.query()
.from("Entity", "e")
.whereNode("e", (e) => e.name.eq(entityName))
.traverse("mentions", "m", { direction: "in" })
.to("Chunk", "c")
.select((ctx) => ctx.c.text)
.execute();
}
```
### Multi-Hop Entity Traversal
Find entities connected through relationships:
```typescript
async function findRelatedEntities(entityName: string, maxHops = 2) {
const rows = await store
.query()
.from("Entity", "e")
.whereNode("e", (e) => e.name.eq(entityName))
.traverse("relatesTo", "r")
.recursive({ maxHops, depth: "depth" })
.to("Entity", "related")
.select((ctx) => ({
from: ctx.e.name,
to: ctx.related.name,
toId: ctx.related.id,
depth: ctx.depth,
}))
.execute();
// distinct paths can reach the same target; dedupe by target
const seen = new Set();
return rows
.filter((row) => {
if (seen.has(row.toId)) return false;
seen.add(row.toId);
return true;
})
.map((row) => ({
from: row.from,
to: row.to,
depth: row.depth,
}));
}
```
### Context Window Expansion
Get surrounding chunks for a match:
```typescript
async function getChunkWithContext(chunkId: string, windowSize = 1) {
const [before, after] = await Promise.all([
store
.query()
.from("Chunk", "c")
.whereNode("c", (c) => c.id.eq(chunkId))
.traverse("prevChunk", "e")
.recursive({ maxHops: windowSize })
.to("Chunk", "prev")
.orderBy("prev", "position", "desc")
.select((ctx) => ctx.prev.text)
.execute(),
store
.query()
.from("Chunk", "c")
.whereNode("c", (c) => c.id.eq(chunkId))
.traverse("nextChunk", "e")
.recursive({ maxHops: windowSize })
.to("Chunk", "next")
.orderBy("next", "position", "asc")
.select((ctx) => ctx.next.text)
.execute(),
]);
const chunk = await store.nodes.Chunk.getById(chunkId);
return {
before: before.toReversed(),
chunk: chunk?.text ?? "",
after,
};
}
```
## Hybrid Retrieval: Vector + Fulltext
Vector search handles semantic similarity; fulltext search
(`$fulltext.matches()`) nails exact-match terms that embeddings blur —
proper nouns, SKUs, technical jargon. Combining both with Reciprocal
Rank Fusion is the gold-standard RAG retrieval pattern.
### Query-builder fusion (single SQL query)
Use `$fulltext.matches()` and `.similarTo()` in the same `whereNode()`
and TypeGraph fuses the two ranked lists with RRF at the SQL layer:
```typescript
async function hybridSearch(query: string, limit = 10) {
const queryEmbedding = await generateEmbedding(query);
return store
.query()
.from("Chunk", "c")
.whereNode("c", (c) =>
c.$fulltext
.matches(query, limit * 4)
.and(c.embedding.similarTo(queryEmbedding, limit * 4))
)
.select((ctx) => ({
chunkId: ctx.c.id,
text: ctx.c.text,
}))
.limit(limit)
.execute();
}
```
Each source retrieves `limit * 4` candidates, RRF blends the rankings,
and the outer `LIMIT` trims to the final top-k. The two CTEs join by
`node_id` and the outer ORDER BY uses `1/(60 + rank_vec) + 1/(60 + rank_ft)`.
### Store API (tunable weights)
When you need to tune the fusion parameters (e.g. weighting fulltext
higher for entity-heavy queries), use `store.search.hybrid()`:
```typescript
async function tunedHybrid(query: string, limit = 10) {
const queryEmbedding = await generateEmbedding(query);
const hits = await store.search.hybrid("Chunk", {
limit,
vector: {
fieldPath: "embedding",
queryEmbedding,
metric: "cosine",
k: 50,
},
fulltext: {
query,
k: 50,
includeSnippets: true,
},
fusion: {
method: "rrf",
k: 60,
weights: { vector: 1.0, fulltext: 1.5 },
},
});
return hits.map((h) => ({
chunkId: h.node.id,
text: h.node.text,
score: h.score,
vectorRank: h.vector?.rank,
fulltextRank: h.fulltext?.rank,
snippet: h.fulltext?.snippet,
}));
}
```
See the [Fulltext Search guide](/fulltext-search) for tuning advice,
query modes, and the full hybrid retrieval playbook.
## Hybrid Retrieval: Vector + Graph
Combine vector similarity with graph traversal in a single query using the `from` option:
```typescript
async function hybridRetrieval(query: string, limit = 10) {
const queryEmbedding = await generateEmbedding(query);
// Single query: vector search + fan-out to entities AND document
const results = await store
.query()
.from("Chunk", "c")
.whereNode("c", (c) =>
c.embedding.similarTo(queryEmbedding, limit, { metric: "cosine", minScore: 0.7 })
)
.traverse("mentions", "m")
.to("Entity", "e")
.traverse("containsChunk", "d_edge", { direction: "in", from: "c" }) // Fan-out from chunk
.to("Document", "d")
// Results are already ordered by similarity (most similar first).
// When you need explicit scores, use `store.search.hybrid()` instead —
// it returns hits with `.score`, `.vector.score`, and `.fulltext.score`.
.select((ctx) => ({
chunkId: ctx.c.id,
text: ctx.c.text,
source: ctx.d.title,
entityName: ctx.e.name,
entityType: ctx.e.type,
}))
.execute();
// Group by chunk (one row per chunk-entity pair)
const byChunk = new Map }>();
for (const row of results) {
const existing = byChunk.get(row.chunkId);
if (existing) {
existing.entities.push({ name: row.entityName, type: row.entityType });
} else {
byChunk.set(row.chunkId, {
...row,
entities: [{ name: row.entityName, type: row.entityType }],
});
}
}
return [...byChunk.values()];
}
```
The `from` option enables **fan-out patterns** where you traverse multiple relationships
from the same node. Without `from`, traversals chain sequentially (A→B→C). With `from`,
you can branch: traverse from chunk to entities, AND from chunk to document.
## Building Structured Context
Format graph-enriched context for an LLM:
```typescript
async function buildGraphContext(query: string, extractedEntities: string[]) {
const queryEmbedding = await generateEmbedding(query);
// Get relevant chunks with sources
const chunks = await store
.query()
.from("Chunk", "c")
.whereNode("c", (c) =>
c.embedding.similarTo(queryEmbedding, 5, { metric: "cosine", minScore: 0.7 })
)
.traverse("containsChunk", "e", { direction: "in" })
.to("Document", "d")
.select((ctx) => ({ text: ctx.c.text, source: ctx.d.title }))
.execute();
// Get entity relationships from graph
const entityFacts = await Promise.all(
extractedEntities.map(async (name) => {
const relations = await store
.query()
.from("Entity", "e")
.whereNode("e", (e) => e.name.eq(name))
.traverse("relatesTo", "r")
.to("Entity", "target")
.select((ctx) => ctx.target.name)
.execute();
return relations.length > 0 ? { name, relatedTo: relations } : undefined;
})
);
return { chunks, entityFacts: entityFacts.filter(Boolean) };
}
function formatForPrompt(context: Awaited>): string {
let prompt = "## Relevant Passages\n\n";
for (const chunk of context.chunks) {
prompt += `**${chunk.source}**: ${chunk.text}\n\n`;
}
if (context.entityFacts.length > 0) {
prompt += "## Entity Relationships\n\n";
for (const entity of context.entityFacts) {
if (entity) {
prompt += `**${entity.name}** → ${entity.relatedTo.join(", ")}\n`;
}
}
}
return prompt;
}
```
## When to Use Graph RAG
**Use graph RAG when:**
- Queries require connecting facts across documents ("Who founded X and what else did they start?")
- Entity disambiguation matters (distinguishing "Apple" the company from "apple" the fruit)
- Relationship traversal provides value ("Find all companies in the same industry as X")
- You need structured facts alongside unstructured text
**Flat vector RAG may suffice when:**
- Simple "find similar content" queries
- No entity relationships to exploit
- Single-document question answering
## Next Steps
- [Semantic Search](/semantic-search) — Vector embedding fundamentals
- [Traversals](/queries/traverse) — Graph traversal patterns
- [Document Management](/examples/document-management) — Versioning and access control
# Multi-Tenant SaaS
> Complete multi-tenancy patterns with isolation, data partitioning, and tenant management
This example shows how to build a multi-tenant SaaS application with:
- **Three isolation strategies** (shared tables, schema per tenant, database per tenant)
- **Tenant-aware queries** that automatically filter data
- **Tenant provisioning** and lifecycle management
- **Cross-tenant analytics** for platform operators
- **Tenant migration** between isolation levels
## Choosing an Isolation Strategy
| Strategy | Isolation | Complexity | Cost | Best For |
|----------|-----------|------------|------|----------|
| Shared tables | Low | Low | Lowest | Many small tenants, B2C SaaS |
| Schema per tenant | Medium | Medium | Low | SMB customers, PostgreSQL only |
| Database per tenant | High | High | Highest | Enterprise, compliance requirements |
## Strategy 1: Shared Tables with Row-Level Isolation
All tenants share the same database tables, filtered by `tenantId`.
### Schema Definition
```typescript
import { z } from "zod";
import { defineNode, defineEdge, defineGraph, searchable } from "@nicia-ai/typegraph";
// Tenant metadata
const Tenant = defineNode("Tenant", {
schema: z.object({
slug: z.string(),
name: z.string(),
plan: z.enum(["free", "starter", "pro", "enterprise"]),
status: z.enum(["active", "suspended", "cancelled"]).default("active"),
createdAt: z.string().datetime(),
settings: z.record(z.unknown()).optional(),
}),
});
// All entities include tenantId
const Project = defineNode("Project", {
schema: z.object({
tenantId: z.string(),
// Searchable fields so tenants can run BM25 search against their
// own projects without paying for an external search service.
// Fulltext filtering composes with the tenantId predicate — every
// query is authoritatively tenant-scoped.
name: searchable({ language: "english" }),
description: searchable({ language: "english" }).optional(),
status: z.enum(["active", "archived"]).default("active"),
}),
});
const Task = defineNode("Task", {
schema: z.object({
tenantId: z.string(),
title: searchable({ language: "english" }),
status: z.enum(["todo", "in_progress", "done"]).default("todo"),
priority: z.enum(["low", "medium", "high"]).default("medium"),
}),
});
const User = defineNode("User", {
schema: z.object({
tenantId: z.string(),
email: z.string().email(),
name: z.string(),
role: z.enum(["owner", "admin", "member", "guest"]).default("member"),
}),
});
// Edges
const hasProject = defineEdge("hasProject");
const hasTask = defineEdge("hasTask");
const assignedTo = defineEdge("assignedTo");
const memberOf = defineEdge("memberOf");
const graph = defineGraph({
id: "multi_tenant",
nodes: {
Tenant: {
type: Tenant,
unique: [
{
name: "tenant_slug",
fields: ["slug"],
scope: "kind",
collation: "binary",
},
],
},
Project: { type: Project },
Task: { type: Task },
User: {
type: User,
unique: [
// Emails are scoped per tenant in the shared-tables strategy: the
// same address can be a member of more than one tenant, but not
// twice in the same one.
{
name: "user_tenant_email",
fields: ["tenantId", "email"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
},
edges: {
hasProject: { type: hasProject, from: [Tenant], to: [Project] },
hasTask: { type: hasTask, from: [Project], to: [Task] },
assignedTo: { type: assignedTo, from: [Task], to: [User] },
memberOf: { type: memberOf, from: [User], to: [Tenant] },
},
});
```
### Tenant-Scoped Store
Create a wrapper that automatically filters by tenant:
```typescript
interface TenantContext {
tenantId: string;
userId: string;
role: "owner" | "admin" | "member" | "guest";
}
function createTenantStore(store: Store, ctx: TenantContext) {
const projects = {
async list(options: { status?: string } = {}) {
let query = store
.query()
.from("Project", "p")
.whereNode("p", (p) => p.tenantId.eq(ctx.tenantId));
if (options.status) {
query = query.whereNode("p", (p) => p.status.eq(options.status));
}
return query.select((q) => q.p).execute();
},
async create(data: { name: string; description?: string }) {
const project = await store.nodes.Project.create({
...data,
tenantId: ctx.tenantId,
});
const tenant = await store.nodes.Tenant.getById(ctx.tenantId);
if (!tenant) throw new Error(`Tenant not found: ${ctx.tenantId}`);
await store.edges.hasProject.create(tenant, project, {});
return project;
},
async get(projectId: string) {
const project = await store.nodes.Project.getById(projectId);
if (!project || project.tenantId !== ctx.tenantId) {
throw new Error("Not found");
}
return project;
},
async update(projectId: string, updates: Partial) {
await projects.get(projectId); // Verify access
return store.nodes.Project.update(projectId, updates);
},
async delete(projectId: string) {
await projects.get(projectId); // Verify access
await store.nodes.Project.delete(projectId);
},
};
const tasks = {
async list(projectId: string) {
await projects.get(projectId); // Verify access
return store
.query()
.from("Project", "p")
.whereNode("p", (p) => p.id.eq(projectId))
.traverse("hasTask", "e")
.to("Task", "t")
.select((q) => q.t)
.execute();
},
async create(projectId: string, data: { title: string; priority?: string }) {
const project = await projects.get(projectId); // Verify access
const task = await store.nodes.Task.create({
...data,
tenantId: ctx.tenantId,
});
await store.edges.hasTask.create(project, task, {});
return task;
},
};
const users = {
async list() {
return store
.query()
.from("User", "u")
.whereNode("u", (u) => u.tenantId.eq(ctx.tenantId))
.select((q) => q.u)
.execute();
},
async invite(email: string, name: string, role: string) {
if (ctx.role !== "owner" && ctx.role !== "admin") {
throw new Error("Insufficient permissions");
}
const user = await store.nodes.User.create({
tenantId: ctx.tenantId,
email,
name,
role,
});
const tenant = await store.nodes.Tenant.getById(ctx.tenantId);
if (!tenant) throw new Error(`Tenant not found: ${ctx.tenantId}`);
await store.edges.memberOf.create(user, tenant, {});
return user;
},
};
return { projects, tasks, users };
}
// Usage in API handler
async function handleRequest(req: Request) {
const session = await getSession(req);
const tenantStore = createTenantStore(store, {
tenantId: session.tenantId,
userId: session.userId,
role: session.role,
});
// All queries are automatically tenant-scoped
const projects = await tenantStore.projects.list();
}
```
### Tenant Provisioning
```typescript
async function provisionTenant(
slug: string,
name: string,
ownerEmail: string,
ownerName: string,
plan: "free" | "starter" | "pro" | "enterprise" = "free"
): Promise<{ tenant: Node; owner: Node }> {
return store.transaction(async (tx) => {
// Atomic uniqueness check — the `tenant_slug` constraint guarantees
// concurrent callers can't both succeed.
const tenantResult = await tx.nodes.Tenant.getOrCreateByConstraint(
"tenant_slug",
{
slug,
name,
plan,
status: "active",
createdAt: new Date().toISOString(),
},
);
if (tenantResult.action !== "created") {
throw new Error("Tenant slug already exists");
}
const owner = await tx.nodes.User.create({
tenantId: tenantResult.node.id,
email: ownerEmail,
name: ownerName,
role: "owner",
});
await tx.edges.memberOf.create(owner, tenantResult.node, {});
return { tenant: tenantResult.node, owner };
});
}
```
## Strategy 2: Schema Per Tenant (PostgreSQL)
Each tenant gets their own PostgreSQL schema within the same database.
### Setup
```typescript
import { Pool } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";
import { sql } from "drizzle-orm";
import { createPostgresBackend, generatePostgresMigrationSQL } from "@nicia-ai/typegraph/adapters/drizzle/postgres";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function createTenantSchema(tenantId: string): Promise {
const schemaName = `tenant_${tenantId}`;
// Create schema
await pool.query(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);
// Run TypeGraph migrations in the tenant schema
await pool.query(`SET search_path TO ${schemaName}`);
await pool.query(generatePostgresMigrationSQL());
await pool.query(`SET search_path TO public`);
}
async function getTenantStore(tenantId: string): Promise {
const schemaName = `tenant_${tenantId}`;
// Create connection with schema
const client = await pool.connect();
await client.query(`SET search_path TO ${schemaName}`);
const db = drizzle(client);
const backend = createPostgresBackend(db);
// `searchable()` fields require the durable fulltext-materialization
// step `createStoreWithSchema` performs at boot; bare `createStore()`
// would throw `StoreNotInitializedError` on the first fulltext op.
const [store] = await createStoreWithSchema(graph, backend);
return store;
}
```
### Tenant Store Cache
```typescript
class TenantStoreManager {
private stores = new Map();
private maxCached = 100;
async getStore(tenantId: string): Promise {
const cached = this.stores.get(tenantId);
if (cached) {
cached.lastUsed = new Date();
return cached.store;
}
// Evict oldest if at capacity
if (this.stores.size >= this.maxCached) {
this.evictOldest();
}
const store = await getTenantStore(tenantId);
this.stores.set(tenantId, { store, lastUsed: new Date() });
return store;
}
private evictOldest(): void {
let oldest: { id: string; date: Date } | undefined;
for (const [id, { lastUsed }] of this.stores) {
if (!oldest || lastUsed < oldest.date) {
oldest = { id, date: lastUsed };
}
}
if (oldest) {
this.stores.delete(oldest.id);
}
}
}
const tenantManager = new TenantStoreManager();
```
### Provisioning with Schema
```typescript
async function provisionTenantWithSchema(
slug: string,
name: string,
ownerEmail: string
): Promise<{ tenantId: string }> {
const tenantId = generateUUID();
// Create schema and tables
await createTenantSchema(tenantId);
// Get tenant-specific store
const tenantStore = await tenantManager.getStore(tenantId);
// Create initial data
await tenantStore.nodes.User.create({
email: ownerEmail,
name: name,
role: "owner",
});
// Store tenant metadata in public schema
const publicDb = drizzle(pool);
await publicDb.insert(tenants).values({
id: tenantId,
slug,
name,
createdAt: new Date(),
});
return { tenantId };
}
```
## Strategy 3: Database Per Tenant
Each tenant gets their own database for maximum isolation.
### Tenant Database Manager
```typescript
interface TenantConfig {
id: string;
slug: string;
databaseUrl: string;
status: "active" | "suspended";
}
class TenantDatabaseManager {
private connections = new Map();
private maxConnections = 50;
async getStore(tenantId: string): Promise {
const cached = this.connections.get(tenantId);
if (cached) return cached.store;
// Get tenant config from central registry
const config = await this.getTenantConfig(tenantId);
if (config.status !== "active") {
throw new Error("Tenant is not active");
}
// Evict if at capacity
if (this.connections.size >= this.maxConnections) {
await this.evictLeastUsed();
}
// Create new connection
const pool = new Pool({ connectionString: config.databaseUrl, max: 5 });
const db = drizzle(pool);
const backend = createPostgresBackend(db);
const [store] = await createStoreWithSchema(graph, backend);
this.connections.set(tenantId, { pool, store });
return store;
}
async closeConnection(tenantId: string): Promise {
const conn = this.connections.get(tenantId);
if (conn) {
await conn.pool.end();
this.connections.delete(tenantId);
}
}
private async getTenantConfig(tenantId: string): Promise {
// Fetch from central tenant registry
const result = await centralDb
.select()
.from(tenantConfigs)
.where(eq(tenantConfigs.id, tenantId))
.get();
if (!result) throw new Error("Tenant not found");
return result;
}
private async evictLeastUsed(): Promise {
// Simple LRU eviction
const first = this.connections.keys().next().value;
if (first) {
await this.closeConnection(first);
}
}
}
const dbManager = new TenantDatabaseManager();
```
### Provisioning New Database
```typescript
async function provisionTenantDatabase(
slug: string,
name: string,
ownerEmail: string
): Promise<{ tenantId: string; databaseUrl: string }> {
const tenantId = generateUUID();
const dbName = `tenant_${tenantId.replace(/-/g, "_")}`;
// Create database (using admin connection)
const adminPool = new Pool({ connectionString: process.env.ADMIN_DATABASE_URL });
await adminPool.query(`CREATE DATABASE ${dbName}`);
await adminPool.end();
// Build connection URL
const baseUrl = new URL(process.env.DATABASE_BASE_URL!);
baseUrl.pathname = `/${dbName}`;
const databaseUrl = baseUrl.toString();
// Initialize TypeGraph tables
const tenantPool = new Pool({ connectionString: databaseUrl });
await tenantPool.query(generatePostgresMigrationSQL());
// Create initial data
const db = drizzle(tenantPool);
const backend = createPostgresBackend(db);
const [store] = await createStoreWithSchema(graph, backend);
await store.nodes.User.create({
email: ownerEmail,
name: name,
role: "owner",
});
await tenantPool.end();
// Register in central tenant registry
await centralDb.insert(tenantConfigs).values({
id: tenantId,
slug,
name,
databaseUrl,
status: "active",
createdAt: new Date(),
});
return { tenantId, databaseUrl };
}
```
## Cross-Tenant Operations
For platform administrators who need to query across tenants.
### Aggregated Metrics (Shared Tables)
```typescript
import { count, field } from "@nicia-ai/typegraph";
async function getTenantMetrics(): Promise<
Array<{ tenantId: string; projectCount: number; taskCount: number; userCount: number }>
> {
// Projects by tenant
const projectCounts = await store
.query()
.from("Project", "p")
.groupBy("p", "tenantId")
.aggregate({
tenantId: field("p", "tenantId"),
projectCount: count("p"),
})
.execute();
// Tasks by tenant
const taskCounts = await store
.query()
.from("Task", "t")
.groupBy("t", "tenantId")
.aggregate({
tenantId: field("t", "tenantId"),
taskCount: count("t"),
})
.execute();
// Users by tenant
const userCounts = await store
.query()
.from("User", "u")
.groupBy("u", "tenantId")
.aggregate({
tenantId: field("u", "tenantId"),
userCount: count("u"),
})
.execute();
// Merge results
const metrics = new Map();
for (const p of projectCounts) {
metrics.set(p.tenantId, { projectCount: p.projectCount, taskCount: 0, userCount: 0 });
}
for (const t of taskCounts) {
const existing = metrics.get(t.tenantId) || { projectCount: 0, taskCount: 0, userCount: 0 };
existing.taskCount = t.taskCount;
metrics.set(t.tenantId, existing);
}
for (const u of userCounts) {
const existing = metrics.get(u.tenantId) || { projectCount: 0, taskCount: 0, userCount: 0 };
existing.userCount = u.userCount;
metrics.set(u.tenantId, existing);
}
return Array.from(metrics.entries()).map(([tenantId, counts]) => ({
tenantId,
...counts,
}));
}
```
### Cross-Tenant Search (Database Per Tenant)
Fulltext search composes with tenant scope: the fulltext predicate
narrows the candidate pool by relevance, and the per-tenant store
supplies the isolation. Nothing from tenant A can ever appear in tenant
B's results because each store wraps a different database:
```typescript
async function searchAcrossTenants(
query: string,
tenantIds: string[]
): Promise }>> {
const results = await Promise.all(
tenantIds.map(async (tenantId) => {
try {
const store = await dbManager.getStore(tenantId);
const hits = await store.search.fulltext("Project", {
query,
limit: 10,
includeSnippets: true,
});
return {
tenantId,
results: hits.map((hit) => ({
...hit.node,
score: hit.score,
snippet: hit.snippet,
})),
};
} catch (error) {
console.error(`Failed to search tenant ${tenantId}:`, error);
return { tenantId, results: [] };
}
})
);
return results;
}
```
### Tenant-Scoped Fulltext (Shared Tables)
The composition most multi-tenant teams need: BM25 ranking *plus* a
tenantId filter in a single query. The fulltext predicate scales with
the tenant's data, not the whole table:
```typescript
async function searchTenantProjects(
tenantId: string,
query: string,
limit = 10,
) {
return store
.query()
.from("Project", "p")
.whereNode("p", (p) =>
// Tenant filter first so the fulltext match is always scoped.
p.tenantId.eq(tenantId).and(p.$fulltext.matches(query, limit)),
)
.select((ctx) => ctx.p)
.execute();
}
```
The tenant filter and fulltext match compose in one SQL statement; no
post-filter in JS and no risk of leaking another tenant's data even if
the caller forgets to verify.
## Tenant Lifecycle
### Suspend Tenant
```typescript
async function suspendTenant(tenantId: string, reason: string): Promise {
const current = await store.nodes.Tenant.getById(tenantId);
if (!current) throw new Error(`Tenant not found: ${tenantId}`);
await store.nodes.Tenant.update(tenantId, {
status: "suspended",
settings: {
...(current.settings || {}),
suspendedAt: new Date().toISOString(),
suspendReason: reason,
},
});
}
```
### Delete Tenant (Shared Tables)
```typescript
async function deleteTenant(tenantId: string): Promise {
await store.transaction(async (tx) => {
// Delete all tasks
const tasks = await tx
.query()
.from("Task", "t")
.whereNode("t", (t) => t.tenantId.eq(tenantId))
.select((ctx) => ctx.t.id)
.execute();
for (const taskId of tasks) {
await tx.nodes.Task.delete(taskId);
}
// Delete all projects
const projects = await tx
.query()
.from("Project", "p")
.whereNode("p", (p) => p.tenantId.eq(tenantId))
.select((ctx) => ctx.p.id)
.execute();
for (const projectId of projects) {
await tx.nodes.Project.delete(projectId);
}
// Delete all users
const users = await tx
.query()
.from("User", "u")
.whereNode("u", (u) => u.tenantId.eq(tenantId))
.select((ctx) => ctx.u.id)
.execute();
for (const userId of users) {
await tx.nodes.User.delete(userId);
}
// Delete tenant
await tx.nodes.Tenant.delete(tenantId);
});
}
```
### Delete Tenant (Database Per Tenant)
```typescript
async function deleteTenantDatabase(tenantId: string): Promise {
// Close active connection
await dbManager.closeConnection(tenantId);
// Get database name
const config = await getTenantConfig(tenantId);
const dbUrl = new URL(config.databaseUrl);
const dbName = dbUrl.pathname.slice(1);
// Drop database
const adminPool = new Pool({ connectionString: process.env.ADMIN_DATABASE_URL });
await adminPool.query(`DROP DATABASE IF EXISTS ${dbName}`);
await adminPool.end();
// Remove from registry
await centralDb.delete(tenantConfigs).where(eq(tenantConfigs.id, tenantId));
}
```
## Tenant Migration
Move tenant between isolation strategies:
```typescript
async function migrateTenantToSeparateDatabase(tenantId: string): Promise {
// 1. Create new database
const { databaseUrl } = await provisionTenantDatabase(
`migrated_${tenantId}`,
"Migrated Tenant",
"placeholder@example.com"
);
// 2. Get tenant data from shared tables
const sharedStore = store;
const projects = await sharedStore
.query()
.from("Project", "p")
.whereNode("p", (p) => p.tenantId.eq(tenantId))
.select((ctx) => ctx.p)
.execute();
const tasks = await sharedStore
.query()
.from("Task", "t")
.whereNode("t", (t) => t.tenantId.eq(tenantId))
.select((ctx) => ctx.t)
.execute();
const users = await sharedStore
.query()
.from("User", "u")
.whereNode("u", (u) => u.tenantId.eq(tenantId))
.select((ctx) => ctx.u)
.execute();
// 3. Insert into new database
const newStore = await dbManager.getStore(tenantId);
await newStore.transaction(async (tx) => {
for (const project of projects) {
await tx.nodes.Project.create(project);
}
for (const task of tasks) {
await tx.nodes.Task.create(task);
}
for (const user of users) {
await tx.nodes.User.create(user);
}
});
// 4. Delete from shared tables
await deleteTenant(tenantId);
return databaseUrl;
}
```
## Next Steps
- [Document Management](/examples/document-management) - CMS with semantic search
- [Product Catalog](/examples/product-catalog) - Categories, variants, inventory
- [Integration Patterns](/integration) - More deployment strategies
# Product Catalog
> E-commerce catalog with categories, variants, and inventory tracking
This example builds a product catalog system with:
- **Category hierarchy** with inheritance
- **Product variants** (size, color, etc.)
- **Inventory tracking** across warehouses
- **Product relationships** (bundles, accessories, alternatives)
- **Price history** using temporal queries
## Schema Definition
```typescript
import { z } from "zod";
import {
defineNode,
defineEdge,
defineGraph,
embedding,
searchable,
} from "@nicia-ai/typegraph";
// Category hierarchy
const Category = defineNode("Category", {
schema: z.object({
name: searchable({ language: "english" }),
slug: z.string(),
description: searchable({ language: "english" }).optional(),
imageUrl: z.string().url().optional(),
displayOrder: z.number().default(0),
isActive: z.boolean().default(true),
}),
});
// Products
const Product = defineNode("Product", {
schema: z.object({
sku: z.string(),
// `searchable()` enables BM25 fulltext matching on name + description.
// Combined with the `embedding` field below this supports hybrid
// retrieval — SKU-style exact matches that embeddings miss, plus
// conceptual matches that keyword search alone miss.
name: searchable({ language: "english" }),
description: searchable({ language: "english" }),
basePrice: z.number().positive(),
currency: z.string().default("USD"),
status: z.enum(["draft", "active", "discontinued"]).default("draft"),
embedding: embedding(1536).optional(),
}),
});
// Product variants (specific size/color combinations)
const Variant = defineNode("Variant", {
schema: z.object({
sku: z.string(),
// "Large / Blue" — variant names contain the exact tokens shoppers
// type ("blue", "xl"), so indexing them enables keyword retrieval
// that complements the product-level embedding.
name: searchable({ language: "english" }),
priceModifier: z.number().default(0), // Added to base price
attributes: z.record(z.string()), // { size: "L", color: "blue" }
isDefault: z.boolean().default(false),
}),
});
// Inventory
const Warehouse = defineNode("Warehouse", {
schema: z.object({
code: z.string(),
name: z.string(),
location: z.string(),
isActive: z.boolean().default(true),
}),
});
const Inventory = defineNode("Inventory", {
schema: z.object({
quantity: z.number().int().min(0),
reservedQuantity: z.number().int().min(0).default(0),
reorderPoint: z.number().int().min(0).default(10),
lastCountedAt: z.string().datetime().optional(),
}),
});
// Edges
const parentCategory = defineEdge("parentCategory");
const inCategory = defineEdge("inCategory", {
schema: z.object({ isPrimary: z.boolean().default(false) }),
});
const hasVariant = defineEdge("hasVariant");
const inventoryFor = defineEdge("inventoryFor");
const atWarehouse = defineEdge("atWarehouse");
const relatedProduct = defineEdge("relatedProduct", {
schema: z.object({
type: z.enum(["accessory", "alternative", "bundled", "upsell"]),
sortOrder: z.number().default(0),
}),
});
// Graph
const graph = defineGraph({
id: "product_catalog",
nodes: {
Category: {
type: Category,
unique: [
{
name: "category_slug",
fields: ["slug"],
scope: "kind",
collation: "binary",
},
],
},
Product: {
type: Product,
unique: [
{
name: "product_sku",
fields: ["sku"],
scope: "kind",
collation: "binary",
},
],
},
Variant: {
type: Variant,
unique: [
{
name: "variant_sku",
fields: ["sku"],
scope: "kind",
collation: "binary",
},
],
},
Warehouse: {
type: Warehouse,
unique: [
{
name: "warehouse_code",
fields: ["code"],
scope: "kind",
collation: "binary",
},
],
},
Inventory: { type: Inventory },
},
edges: {
parentCategory: { type: parentCategory, from: [Category], to: [Category] },
inCategory: { type: inCategory, from: [Product], to: [Category] },
hasVariant: { type: hasVariant, from: [Product], to: [Variant] },
inventoryFor: { type: inventoryFor, from: [Inventory], to: [Variant] },
atWarehouse: { type: atWarehouse, from: [Inventory], to: [Warehouse] },
relatedProduct: { type: relatedProduct, from: [Product], to: [Product] },
},
ontology: [
// Category hierarchy is modeled via the parentCategory edge, not ontology.
// Use ontology for type-level constraints, e.g.:
// disjointWith(Product, Category),
],
});
```
## Category Management
### Create Category Tree
```typescript
async function createCategory(
name: string,
slug: string,
parentSlug?: string
): Promise> {
const result = await store.nodes.Category.getOrCreateByConstraint(
"category_slug",
{ name, slug, isActive: true },
);
if (result.action === "created" && parentSlug) {
const parent = await store.nodes.Category.findByConstraint(
"category_slug",
{ slug: parentSlug },
);
if (parent) {
await store.edges.parentCategory.create(result.node, parent, {});
}
}
return result.node;
}
// Build initial category structure
await createCategory("Electronics", "electronics");
await createCategory("Phones", "phones", "electronics");
await createCategory("Accessories", "accessories", "electronics");
await createCategory("Cases", "cases", "accessories");
await createCategory("Chargers", "chargers", "accessories");
```
### Get Category with Ancestors
```typescript
interface CategoryWithPath {
id: string;
name: string;
slug: string;
path: Array<{ name: string; slug: string }>;
}
async function getCategoryWithPath(slug: string): Promise {
const category = await store.nodes.Category.findByConstraint(
"category_slug",
{ slug },
);
if (!category) return undefined;
// Walk `parentCategory` edges up to the root. `reachable` returns each
// ancestor with its depth from the starting node — sort by depth desc
// so the root comes first.
const ancestorIds = (
await store.algorithms.reachable(category.id, {
edges: ["parentCategory"],
excludeSource: true,
})
)
.toSorted((a, b) => b.depth - a.depth)
.map((node) => node.id);
const ancestors = await store.nodes.Category.getByIds(ancestorIds);
return {
id: category.id,
name: category.name,
slug: category.slug,
path: ancestors
.filter((c): c is NonNullable => c !== undefined)
.map((c) => ({ name: c.name, slug: c.slug })),
};
}
```
### Get Subcategories
```typescript
async function getSubcategories(
parentSlug: string,
includeNested = false
): Promise> {
const parent = await store.nodes.Category.findByConstraint(
"category_slug",
{ slug: parentSlug },
);
if (!parent) return [];
// `reachable` returns descendants tagged with their depth. Cap at 1 for
// immediate children only, or let it run to the configured default
// (10 hops) for the full subtree.
const descendants = await store.algorithms.reachable(parent.id, {
edges: ["parentCategory"],
direction: "in",
excludeSource: true,
maxHops: includeNested ? undefined : 1,
});
const children = (await store.nodes.Category.getByIds(
descendants.map((node) => node.id),
)).filter(
(category): category is NonNullable =>
category !== undefined && category.isActive,
);
const depthById = new Map(descendants.map((row) => [row.id, row.depth]));
return children
.map((category) => ({
id: category.id,
name: category.name,
slug: category.slug,
depth: depthById.get(category.id) ?? 1,
}))
.toSorted((a, b) => a.depth - b.depth);
}
```
## Product Management
### Create Product with Variants
```typescript
interface ProductInput {
sku: string;
name: string;
description: string;
basePrice: number;
categorySlug: string;
variants: Array<{
sku: string;
name: string;
priceModifier?: number;
attributes: Record;
isDefault?: boolean;
}>;
}
async function createProduct(input: ProductInput): Promise> {
return store.transaction(async (tx) => {
// Generate embedding for semantic search
const embedding = await generateEmbedding(`${input.name} ${input.description}`);
// Create product
const product = await tx.nodes.Product.create({
sku: input.sku,
name: input.name,
description: input.description,
basePrice: input.basePrice,
status: "draft",
embedding,
});
// Link to category
const category = await tx
.query()
.from("Category", "c")
.whereNode("c", (c) => c.slug.eq(input.categorySlug))
.select((ctx) => ctx.c)
.first();
if (category) {
await tx.edges.inCategory.create(product, category, { isPrimary: true });
}
// Create variants
for (const v of input.variants) {
const variant = await tx.nodes.Variant.create({
sku: v.sku,
name: v.name,
priceModifier: v.priceModifier ?? 0,
attributes: v.attributes,
isDefault: v.isDefault ?? false,
});
await tx.edges.hasVariant.create(product, variant, {});
}
return product;
});
}
```
### Get Product Details
```typescript
interface ProductDetails {
id: string;
sku: string;
name: string;
description: string;
basePrice: number;
status: string;
categories: Array<{ name: string; slug: string; isPrimary: boolean }>;
variants: Array<{
id: string;
sku: string;
name: string;
price: number;
attributes: Record;
inventory: number;
}>;
related: Array<{ id: string; name: string; type: string }>;
}
async function getProductDetails(sku: string): Promise {
const product = await store.nodes.Product.findByConstraint(
"product_sku",
{ sku },
);
if (!product) return undefined;
// `store.batch()` runs all three queries in sequence, one at a time —
// still three statements, and read-committed isolation means a write can
// land between them. It is the pool-pressure win, not a snapshot.
const [categories, variants, related] = await store.batch(
store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.id.eq(product.id))
.traverse("inCategory", "e")
.to("Category", "c")
.select((ctx) => ({
name: ctx.c.name,
slug: ctx.c.slug,
isPrimary: ctx.e.isPrimary,
})),
store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.id.eq(product.id))
.traverse("hasVariant", "e")
.to("Variant", "v")
.optionalTraverse("inventoryFor", "inv", { direction: "in" })
.to("Inventory", "i")
.select((ctx) => ({
id: ctx.v.id,
sku: ctx.v.sku,
name: ctx.v.name,
priceModifier: ctx.v.priceModifier,
attributes: ctx.v.attributes,
quantity: ctx.i?.quantity ?? 0,
reservedQuantity: ctx.i?.reservedQuantity ?? 0,
})),
store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.id.eq(product.id))
.traverse("relatedProduct", "e")
.to("Product", "r")
.orderBy("e", "sortOrder", "asc")
.select((ctx) => ({
id: ctx.r.id,
name: ctx.r.name,
type: ctx.e.type,
})),
);
return {
id: product.id,
sku: product.sku,
name: product.name,
description: product.description,
basePrice: product.basePrice,
status: product.status,
categories,
variants: variants.map((v) => ({
...v,
price: product.basePrice + v.priceModifier,
inventory: v.quantity - v.reservedQuantity,
})),
related,
};
}
```
## Inventory Management
### Update Inventory
```typescript
async function updateInventory(
variantSku: string,
warehouseCode: string,
quantity: number
): Promise {
const variant = await store
.query()
.from("Variant", "v")
.whereNode("v", (v) => v.sku.eq(variantSku))
.select((ctx) => ctx.v)
.first();
const warehouse = await store
.query()
.from("Warehouse", "w")
.whereNode("w", (w) => w.code.eq(warehouseCode))
.select((ctx) => ctx.w)
.first();
if (!variant || !warehouse) {
throw new Error("Variant or warehouse not found");
}
// Find existing inventory record
const existingInventory = await store
.query()
.from("Inventory", "i")
.traverse("inventoryFor", "e1")
.to("Variant", "v")
.whereNode("v", (v) => v.id.eq(variant.id))
.traverse("atWarehouse", "e2", { direction: "in" })
.to("Warehouse", "w")
.whereNode("w", (w) => w.id.eq(warehouse.id))
.select((ctx) => ctx.i)
.first();
if (existingInventory) {
await store.nodes.Inventory.update(existingInventory.id, {
quantity,
lastCountedAt: new Date().toISOString(),
});
} else {
const inventory = await store.nodes.Inventory.create({
quantity,
reservedQuantity: 0,
lastCountedAt: new Date().toISOString(),
});
await store.edges.inventoryFor.create(inventory, variant, {});
await store.edges.atWarehouse.create(inventory, warehouse, {});
}
}
```
### Reserve Inventory
```typescript
async function reserveInventory(
variantSku: string,
quantity: number
): Promise<{ success: boolean; warehouseCode?: string }> {
const inventories = await store
.query()
.from("Variant", "v")
.whereNode("v", (v) => v.sku.eq(variantSku))
.traverse("inventoryFor", "e", { direction: "in" })
.to("Inventory", "i")
.traverse("atWarehouse", "e2")
.to("Warehouse", "w")
.whereNode("w", (w) => w.isActive.eq(true))
.select((ctx) => ({
inventoryId: ctx.i.id,
warehouseCode: ctx.w.code,
available: ctx.i.quantity - ctx.i.reservedQuantity,
reservedQuantity: ctx.i.reservedQuantity,
}))
.execute();
// Find warehouse with enough inventory
const available = inventories.find((i) => i.available >= quantity);
if (!available) {
return { success: false };
}
await store.nodes.Inventory.update(available.inventoryId, {
reservedQuantity: available.reservedQuantity + quantity,
});
return { success: true, warehouseCode: available.warehouseCode };
}
```
### Low Stock Report
```typescript
import { field, sum, havingLt } from "@nicia-ai/typegraph";
interface LowStockItem {
productName: string;
variantSku: string;
variantName: string;
totalQuantity: number;
reorderPoint: number;
}
async function getLowStockItems(): Promise {
return store
.query()
.from("Product", "p")
.traverse("hasVariant", "e1")
.to("Variant", "v")
.traverse("inventoryFor", "e2", { direction: "in" })
.to("Inventory", "i")
.groupByNode("v")
.having(havingLt(sum("i", "quantity"), field("i", "reorderPoint")))
.aggregate({
productName: field("p", "name"),
variantSku: field("v", "sku"),
variantName: field("v", "name"),
totalQuantity: sum("i", "quantity"),
reorderPoint: field("i", "reorderPoint"),
})
.execute();
}
```
## Search and Discovery
Product search is a textbook hybrid-search problem: users type SKUs,
brand names, and category jargon that embeddings blur together, and
conceptual queries ("warm winter jacket") that exact keyword matching
misses. TypeGraph supports both in one query.
### Fulltext-only search (SKU / keyword hits)
`store.search.fulltext()` runs a ranked BM25 query across every
`searchable()` field on the node. Good for search-box autocomplete and
SKU lookups where the query is a bag of keywords rather than a
description:
```typescript
const hits = await store.search.fulltext("Product", {
query: "waterproof jacket",
limit: 20,
includeSnippets: true,
});
for (const hit of hits) {
console.log(hit.node.sku, hit.node.name, hit.score, hit.snippet);
}
```
### Hybrid product search (fulltext + semantic, fused)
For a production product-search feature, fuse fulltext and vector
retrieval with Reciprocal Rank Fusion. RRF is rank-based, so it handles
the score-scale mismatch between BM25 and cosine automatically:
```typescript
async function searchProducts(
query: string,
options: {
categorySlug?: string;
minPrice?: number;
maxPrice?: number;
limit?: number;
} = {}
): Promise> {
const { categorySlug, minPrice, maxPrice, limit = 20 } = options;
const queryEmbedding = await generateEmbedding(query);
// Limit category scope (if requested) to a set of IDs we can pass in
// as an equality filter. Applying this ahead of RRF shrinks the
// candidate pool before fusion — better latency and ranking quality.
let categoryIds: readonly string[] | undefined;
if (categorySlug) {
const root = await store.nodes.Category.findByConstraint(
"category_slug",
{ slug: categorySlug },
);
if (!root) return [];
const subtree = await store.algorithms.reachable(root.id, {
edges: ["parentCategory"],
direction: "in",
});
categoryIds = subtree.map((node) => node.id);
}
const hits = await store.search.hybrid("Product", {
limit,
vector: {
fieldPath: "embedding",
queryEmbedding,
metric: "cosine",
k: limit * 4,
},
fulltext: {
query,
k: limit * 4,
includeSnippets: true,
},
// Exact-name matches matter in commerce search — boost fulltext.
fusion: { method: "rrf", k: 60, weights: { vector: 1, fulltext: 1.5 } },
});
// Post-filter by status / price / category. The hybrid API does not
// compose with the query builder's predicates, so apply these after
// fusion. For heavier filtering, switch to the query-builder path
// below and filter inside the same SQL statement.
const filtered = hits.filter((hit) => {
if (hit.node.status !== "active") return false;
if (minPrice !== undefined && hit.node.basePrice < minPrice) return false;
if (maxPrice !== undefined && hit.node.basePrice > maxPrice) return false;
return true;
});
if (categoryIds === undefined) {
return filtered.map((hit) => ({
product: hit.node,
score: hit.score,
snippet: hit.fulltext?.snippet,
}));
}
// Category membership is a graph edge — check with a single batch query.
const categoryIdSet = new Set(categoryIds);
const productToCategories = new Map>();
const memberships = await store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.id.in(filtered.map((hit) => hit.node.id)))
.traverse("inCategory", "e")
.to("Category", "c")
.select((ctx) => ({ productId: ctx.p.id, categoryId: ctx.c.id }))
.execute();
for (const row of memberships) {
const cats = productToCategories.get(row.productId) ?? new Set();
cats.add(row.categoryId);
productToCategories.set(row.productId, cats);
}
return filtered
.filter((hit) => {
const cats = productToCategories.get(hit.node.id) ?? new Set();
return [...cats].some((id) => categoryIdSet.has(id));
})
.map((hit) => ({
product: hit.node,
score: hit.score,
snippet: hit.fulltext?.snippet,
}));
}
```
### Hybrid search composed with graph traversal (query builder)
When you need tighter composition with predicates and traversals — for
example, "only products in these categories, active, in stock" — use the
query builder. `$fulltext.matches()` and `.similarTo()` in the same
`whereNode()` compile to a two-CTE SQL statement with RRF at the
ORDER BY:
```typescript
const hits = await store
.query()
.from("Product", "p")
.whereNode("p", (p) =>
p.$fulltext
.matches(query, limit * 4)
.and(p.embedding.similarTo(queryEmbedding, limit * 4))
.and(p.status.eq("active")),
)
.traverse("inCategory", "e")
.to("Category", "c")
.whereNode("c", (c) => c.id.in([...categoryIdSet]))
.fuseWith({ k: 60, weights: { vector: 1, fulltext: 1.5 } })
.select((ctx) => ctx.p)
.limit(limit)
.execute();
```
Results come back already ranked by the fused RRF score. The traversal
filter is applied inside the same SQL statement, before the final
`LIMIT`, so recall is not sacrificed for composition.
### Get Products in Category
```typescript
async function getProductsInCategory(
categorySlug: string,
options: {
includeSubcategories?: boolean;
page?: number;
pageSize?: number;
sortBy?: "name" | "price" | "newest";
} = {}
): Promise<{ products: ProductProps[]; total: number }> {
const { includeSubcategories = true, page = 1, pageSize = 20, sortBy = "name" } = options;
const root = await store.nodes.Category.findByConstraint(
"category_slug",
{ slug: categorySlug },
);
if (!root) return { products: [], total: 0 };
const categoryIds = includeSubcategories
? (
await store.algorithms.reachable(root.id, {
edges: ["parentCategory"],
direction: "in",
})
).map((node) => node.id)
: [root.id];
const query = store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.status.eq("active"))
.traverse("inCategory", "e")
.to("Category", "c")
.whereNode("c", (c) => c.id.in(categoryIds))
.select((ctx) => ctx.p);
// Apply sorting
const sortedQuery =
sortBy === "price"
? query.orderBy((ctx) => ctx.p.basePrice, "asc")
: sortBy === "newest"
? query.orderBy((ctx) => ctx.p.createdAt, "desc")
: query.orderBy((ctx) => ctx.p.name, "asc");
const products = await sortedQuery
.limit(pageSize)
.offset((page - 1) * pageSize)
.execute();
const total = await store
.query()
.from("Product", "p")
.whereNode("p", (p) => p.status.eq("active"))
.traverse("inCategory", "e")
.to("Category", "c")
.whereNode("c", (c) => c.id.in(categoryIds))
.count();
return { products, total };
}
```
## Price History
### Track Price Changes
TypeGraph's temporal model automatically tracks all changes:
```typescript
async function getPriceHistory(
sku: string
): Promise> {
return store
.query()
.from("Product", "p")
.temporal("includeEnded")
.whereNode("p", (p) => p.sku.eq(sku))
.orderBy((ctx) => ctx.p.validFrom, "desc")
.select((ctx) => ({
price: ctx.p.basePrice,
validFrom: ctx.p.validFrom,
validTo: ctx.p.validTo,
}))
.execute();
}
```
### Price at Point in Time
```typescript
async function getPriceAsOf(sku: string, date: Date): Promise {
const product = await store
.query()
.from("Product", "p")
.temporal("asOf", date.toISOString())
.whereNode("p", (p) => p.sku.eq(sku))
.select((ctx) => ctx.p.basePrice)
.first();
return product;
}
```
## Next Steps
- [Document Management](/examples/document-management) - CMS with semantic search
- [Workflow Engine](/examples/workflow-engine) - State machines with approvals
- [Audit Trail](/examples/audit-trail) - Complete change tracking
# Provenance Retraction
> Retract bad sources, keep facts with alternate support, and replay belief changes with recorded time
This example shows provenance retraction on a derived knowledge graph. Distinct
source kinds support fact kinds through explicit justification nodes. When a
source is retracted, TypeGraph recomputes the well-founded support set:
- facts with alternate support stay current
- terminal facts can be derived without being valid premises themselves
- facts with no remaining support become non-current
- recorded-time reads can replay what the graph believed before and after
:::tip[Just want the code?]
Full source on GitHub:
[`packages/typegraph/examples/23-provenance-retraction.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/23-provenance-retraction.ts)
:::
## What It Demonstrates
- `@nicia-ai/typegraph/provenance` as a first-class package subpath.
- Multiple source node kinds via `source: { kinds: [...] }`.
- A terminal `DeployDecision` fact kind that is derived but is not allowed in
`premiseOf.from`.
- `createRetractionCapability()` over a store created with `{ history: true }`.
- `holding()` for current well-founded believed facts.
- `retract()` reports where facts died or survived through alternate
justifications.
- `store.asOfRecorded(T)` replays the fact currency before and after the
retraction.
- `unRetract()` clears a source's retraction flag and reopens supported facts.
## Run It
From the repository root:
```bash
pnpm --filter @nicia-ai/typegraph exec tsx examples/23-provenance-retraction.ts
```
Or from `packages/typegraph`:
```bash
npx tsx examples/23-provenance-retraction.ts
```
The example uses an in-memory SQLite backend with `history: true`, so it does
not require Docker or external services.
## Graph Shape
The example models a security advisory workflow:
```text
scanner-source -> justification-scanner-finding -> vulnerability-libvector
vendor-source -> justification-vendor-advisory -> vulnerability-libvector
vulnerability-libvector -> justification-block-deploy -> decision-block-deploy
```
`vulnerability-libvector` has two independent source-level supports.
`decision-block-deploy` depends on `vulnerability-libvector`, so it should
survive as long as the vulnerability fact still has at least one grounded
support path.
The graph is ordinary TypeGraph schema:
```typescript
const ScannerSource = defineNode("ScannerSource", {
schema: z.object({
title: z.string(),
retracted: z.boolean().default(false),
}),
});
const VendorSource = defineNode("VendorSource", {
schema: z.object({
title: z.string(),
retracted: z.boolean().default(false),
}),
});
const Vulnerability = defineNode("Vulnerability", {
schema: z.object({ cve: z.string(), packageName: z.string() }),
});
const DeployDecision = defineNode("DeployDecision", {
schema: z.object({ action: z.string() }),
});
```
`DeployDecision` is terminal: it is a fact kind and a valid derivation target,
but it is not a premise kind.
```typescript
const graph = defineGraph({
edges: {
premiseOf: {
type: premiseOf,
from: [ScannerSource, VendorSource, Vulnerability],
to: [Justification],
},
derives: {
type: derives,
from: [Justification],
to: [Vulnerability, DeployDecision],
},
},
});
```
Then the roles are mapped into provenance retraction:
```typescript
const provenance = createRetractionCapability(store, {
source: { kinds: ["ScannerSource", "VendorSource"] },
justification: { kind: "Justification" },
fact: { kinds: ["Vulnerability", "DeployDecision"] },
premiseOf: { kind: "premiseOf" },
derives: { kind: "derives" },
});
```
## Retraction
Retracting the scanner source does not kill the facts, because the vendor
advisory still supports `vulnerability-libvector`:
```typescript
const scannerReport = await provenance.retract(scanner);
console.log(scannerReport.survivedVia);
```
Retracting the vendor source too removes the last grounded support. The
vulnerability and deploy decision become non-current, but the recorded relation
still knows when they were believed:
```typescript
const beforeVendorRetraction = await store.recordedNow();
if (beforeVendorRetraction === undefined) throw new Error("expected history");
await provenance.retract(vendor);
const afterVendorRetraction = await store.recordedNow();
if (afterVendorRetraction === undefined) throw new Error("expected history");
const before = await store.asOfRecorded(beforeVendorRetraction).nodes.DeployDecision.getById(blockDeploy.id);
const after = await store.asOfRecorded(afterVendorRetraction).nodes.DeployDecision.getById(blockDeploy.id);
```
## Sample Output
```text
Initial derived beliefs:
holding(): decision-block-deploy, vulnerability-libvector
Retract the unverified scanner source.
died: (none)
survived: decision-block-deploy via justification-block-deploy; vulnerability-libvector via justification-vendor-advisory
unaffected: (none)
holding(): decision-block-deploy, vulnerability-libvector
Retract the vendor advisory too.
died: decision-block-deploy, vulnerability-libvector
survived: (none)
unaffected: (none)
holding(): (none)
Recorded-time replay of the deploy-block fact:
before vendor retraction: Block the production deploy
after vendor retraction: not current
```
## When to Use This Pattern
Use provenance retraction when derived facts must respond to source quality:
- AI memory and RAG citations where a source document is later invalidated
- security or compliance knowledge graphs with advisory retractions
- ingestion pipelines where downstream facts depend on upstream source trust
- audit workflows that need both current belief state and past belief replay
See [Provenance and Retraction](/provenance) for the API guide and
[Temporal queries](/queries/temporal#recorded-time-bitemporal) for the
recorded-time rules.
# Research Copilot
> Semantic search, ontology expansion, and graph algorithms combined into an explainable literature-review digest over a citation graph
A single runnable example that exercises nearly every TypeGraph capability —
typed schema, [ontology](/ontology), vector embeddings, recursive traversals,
and the [graph algorithms](/graph-algorithms) — against a corpus of
landmark ML papers. It produces an explainable literature-review digest in one
run against a single SQLite file, with zero external services.
:::tip[Just want the code?]
Full source on GitHub: [`packages/typegraph/examples/14-research-copilot.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/14-research-copilot.ts)
:::
## What You Get
A natural-language query comes in. The copilot returns a ranked, chronological
reading list with citation counts, authors, and topics — all computed against
a single in-memory SQLite database:
```text
Query: "contrastive self-supervised representation learning for vision"
Recommended reading order (chronological among top-ranked):
2012 ImageNet Classification with Deep Convolutional Neural Networks [3 citations]
Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton
topics: CNN, ComputerVision, DeepLearning
why: semantic 0.449 · topic match: DeepLearning · 3 incoming citations
2014 Adam: A Method for Stochastic Optimization [1 citation]
Diederik Kingma, Jimmy Ba
topics: Optimization
why: semantic 0.429 · 1 incoming citation
2019 Momentum Contrast for Unsupervised Visual Representation Learning [1 citation]
Kaiming He, Haoqi Fan, Yuxin Wu, et al.
topics: Contrastive, SelfSupervised, ComputerVision
why: semantic 0.523 · topic match: SelfSupervised, Contrastive · 1 incoming citation
2020 A Simple Framework for Contrastive Learning of Visual Representations [1 citation]
Ting Chen, Simon Kornblith, Mohammad Norouzi, et al.
topics: Contrastive, SelfSupervised, ComputerVision
why: semantic 0.436 · topic match: SelfSupervised, Contrastive · 1 incoming citation
2020 An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale [1 citation]
Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, et al.
topics: Transformer, ComputerVision, DeepLearning
why: semantic 0.350 · topic match: DeepLearning · 1 incoming citation
```
## Architecture
Each moving part maps to a single TypeGraph primitive:
| Feature | TypeGraph capability |
| ------------------------------------ | ----------------------------------------------------------- |
| Semantic paper retrieval | `embedding()` fields + cosine similarity |
| Topic hierarchy expansion | [Ontology](/ontology) + `store.algorithms.reachable()` |
| Citation-authority ranking | `store.algorithms.degree()` over `cites` |
| Explainable paper lineage | `store.algorithms.shortestPath()` over `cites` |
| "Does this trace back to X?" | `store.algorithms.canReach()` |
| Co-author discovery (2-hop) | `store.algorithms.neighbors()` |
| Reading-list assembly | [Query builder](/queries/overview) with typed traversals |
## Schema
Three node kinds and four edges model the citation graph plus a topic
hierarchy that supports query expansion:
```typescript
const Paper = defineNode("Paper", {
schema: z.object({
// Title + abstract are `searchable()` so BM25 ranks papers by
// keyword hits (rare technical terms, author surnames, dataset
// names) — exactly the queries where embeddings are least
// discriminative.
title: searchable({ language: "english" }),
year: z.number().int(),
abstract: searchable({ language: "english" }),
embedding: embedding(128),
}),
});
const Author = defineNode("Author", {
schema: z.object({ name: z.string() }),
});
const Topic = defineNode("Topic", {
schema: z.object({ name: z.string() }),
});
const cites = defineEdge("cites", { schema: z.object({}) });
const authoredBy = defineEdge("authored_by", { schema: z.object({}) });
const coversTopic = defineEdge("covers_topic", { schema: z.object({}) });
// Topic hierarchy: `CNN broader_than DL` reads "CNN is a more specific
// concept than DL". Recursive traversal expands narrow query terms into
// their ancestor concepts for higher recall.
const broaderThan = defineEdge("broader_than", { schema: z.object({}) });
const graph = defineGraph({
id: "research_copilot",
nodes: { Paper: { type: Paper }, Author: { type: Author }, Topic: { type: Topic } },
edges: {
cites: { type: cites, from: [Paper], to: [Paper] },
authored_by: { type: authoredBy, from: [Paper], to: [Author] },
covers_topic: { type: coversTopic, from: [Paper], to: [Topic] },
broader_than: { type: broaderThan, from: [Topic], to: [Topic] },
},
});
```
## Scene by Scene
The example walks through five capabilities end-to-end. Each produces real
console output against the seeded corpus of 18 landmark papers.
### 1. Semantic retrieval
Every paper has a 128-dimensional embedding. Rank the corpus against a
query embedding and take the top hits:
```typescript
const queryEmbedding = mockEmbedding(query);
const allPapers = await store.nodes.Paper.find();
const ranked = allPapers
.map((paper) => ({
paper,
similarity: cosine(queryEmbedding, paper.embedding),
}))
.sort((a, b) => b.similarity - a.similarity);
```
In production, swap the in-JS ranking for `p.embedding.similarTo(queryEmbedding, k)`
in a [query builder](/queries/overview) predicate — backed by pgvector or
sqlite-vec — to do the scoring in SQL. See [Semantic Search](/semantic-search).
`title` and `abstract` are declared `searchable()`, so the same corpus
is also indexed for BM25 via SQLite's FTS5. The example runs a
rare-token query against the fulltext index to show where BM25 wins —
dataset names, method acronyms, proper nouns — exactly the queries
embeddings smooth out:
```typescript
const fulltextHits = await store.search.fulltext("Paper", {
query: "Dropout",
limit: 3,
includeSnippets: true,
});
```
```text
─── Fulltext retrieval (BM25 via FTS5) for: "Dropout" ───
2.619 Dropout: A Simple Way to Prevent Neural Networks from Overfitting
Dropout: A Simple Way to Prevent Neural Networks from Overfitting
Randomly zeroing unit activations during training prevents co-adaptation and…
```
In production you'd fuse the two via `store.search.hybrid()`, which
runs both retrievers and blends them with Reciprocal Rank Fusion at
the SQL layer:
```typescript
const hits = await store.search.hybrid("Paper", {
limit: 10,
vector: { fieldPath: "embedding", queryEmbedding, metric: "cosine" },
fulltext: { query, includeSnippets: true },
// Weight fulltext slightly higher for the entity-heavy queries
// typical of literature search.
fusion: { method: "rrf", k: 60, weights: { vector: 1, fulltext: 1.25 } },
});
```
See the [Fulltext Search guide](/fulltext-search) for tuning and
[Example 15](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/15-fulltext-hybrid-search.ts)
for an end-to-end hybrid walkthrough.
### 2. Ontology-expanded topic matching
A query for the narrow topic `Contrastive` should also return papers tagged
with its ancestors (`SelfSupervised`, `DeepLearning`). `reachable()` walks
the `broader_than` edge recursively and returns every ancestor topic:
```typescript
const topicAncestors = await store.algorithms.reachable(contrastiveTopic, {
edges: ["broader_than"],
maxHops: 10,
excludeSource: true,
});
```
Then filter papers whose `covers_topic` edge lands in the expanded set:
```typescript
const topicMatches = await store
.query()
.from("Paper", "p")
.traverse("covers_topic", "e")
.to("Topic", "t")
.whereNode("t", (t) => t.id.in([...expandedTopicIds]))
.select((ctx) => ({ id: ctx.p.id, title: ctx.p.title, topic: ctx.t.name }))
.execute();
```
Output:
```text
Expanded set: {Contrastive, SelfSupervised, DeepLearning}
```
### 3. Citation-authority re-ranking
Pure vector similarity is noisy. Fuse it with in-degree on the `cites` edge
so highly-cited papers bubble up:
```typescript
const citationCount = await store.algorithms.degree(paperId, {
edges: ["cites"],
direction: "in",
});
const score = similarity + topicBonus + Math.log(citationCount + 1) / 10;
```
Output:
```text
score = similarity + 0.05 * topicMatches + log(1 + citations) / 10
rank score sim topic cites title
───────────────────────────────────────────────────────────────────
1 0.692 0.523 2 1 Momentum Contrast for Unsupervised Visual Representation Learning
2 0.638 0.449 1 3 ImageNet Classification with Deep Convolutional Neural Networks
3 0.606 0.436 2 1 A Simple Framework for Contrastive Learning of Visual Representations
```
### 4. Explainable lineage
"You've read AlexNet — how does SimCLR trace back to it?" `shortestPath`
returns an ordered list of nodes, which the example formats as a tree:
```typescript
const lineage = await store.algorithms.shortestPath(simclr.id, alex.id, {
edges: ["cites"],
maxHops: 6,
});
```
```text
2-hop citation lineage:
A Simple Framework for Contrastive Learning of Visual Representations
└─▶ Deep Residual Learning for Image Recognition
└─▶ ImageNet Classification with Deep Convolutional Neural Networks
```
### 5. Heritage check
`canReach` is the boolean sibling of `shortestPath` — useful when you don't
need the path, just the answer. Here: "which of these modern papers still
trace back to Rumelhart's 1986 backprop paper?"
```typescript
const reaches = await store.algorithms.canReach(paper.id, backprop.id, {
edges: ["cites"],
maxHops: 10,
});
```
```text
✓ "LLaMA: Open and Efficient Foundation Language Models" traces to Rumelhart 1986
✓ "Learning Transferable Visual Models From Natural Language" traces to Rumelhart 1986
✓ "Chain-of-Thought Prompting Elicits Reasoning in Large LMs" traces to Rumelhart 1986
✓ "A Simple Framework for Contrastive Learning of Visual Reps" traces to Rumelhart 1986
```
### 6. Collaborator discovery
`neighbors` returns the direct neighborhood of a node. Compose it — authors
of CLIP → their other papers → co-authors on those papers — to rank natural
collaborators by shared-paper count:
```typescript
const clipAuthors = await store.algorithms.neighbors(clip.id, {
edges: ["authored_by"],
depth: 1,
});
// For each CLIP author: walk authored_by backwards to all their papers,
// then forwards to all their co-authors.
const perAuthorPapers = await Promise.all(
clipAuthors.map((author) =>
store.algorithms.neighbors(author.id, {
edges: ["authored_by"],
direction: "in",
depth: 1,
}),
),
);
```
Issuing each level in parallel keeps the fan-out at `O(depth)` round-trips
instead of `O(authors × papers)`.
```text
Seed paper authors: Ilya Sutskever, Jong Wook Kim, Aditya Ramesh, Alec Radford, Chris Hallacy
Nearby collaborators beyond the original CLIP paper:
2× shared papers with CLIP authors Alex Krizhevsky
2× shared papers with CLIP authors Geoffrey Hinton
2× shared papers with CLIP authors Rewon Child
2× shared papers with CLIP authors Jeffrey Wu
1× shared papers with CLIP authors Nitish Srivastava
```
## Run It
The full source lives at
[`packages/typegraph/examples/14-research-copilot.ts`](https://github.com/nicia-ai/typegraph/blob/main/packages/typegraph/examples/14-research-copilot.ts).
From a checkout of the repository:
```bash
pnpm install
npx tsx packages/typegraph/examples/14-research-copilot.ts
```
The example builds the graph, runs every scene, and tears down — all
against an in-memory SQLite database. To persist it, point
`createExampleBackend()` at a file path. To run it on Postgres, swap the
import to `createPostgresBackend` — see [Backend Setup](/backend-setup).
## Next Steps
- [Graph Algorithms](/graph-algorithms) — the full API for `shortestPath`,
`reachable`, `canReach`, `neighbors`, and `degree`
- [Knowledge Graph for RAG](/examples/knowledge-graph-rag) — entity linking,
chunk traversal, and hybrid vector + fulltext retrieval
- [Ontology & Reasoning](/ontology) — inverse edges, subclass hierarchies,
and other ontology primitives beyond `broader_than`
- [Semantic Search](/semantic-search) — production vector search with
pgvector, sqlite-vec, and native libSQL / Turso vectors
# Workflow Engine
> State machines with approvals, assignments, and escalations
This example builds a workflow engine with:
- **State machine definitions** as graph schemas
- **Approval chains** with multiple approvers
- **Task assignment** and delegation
- **Escalation rules** based on time
- **Audit trail** of all state changes
## Schema Definition
```typescript
import { z } from "zod";
import { defineNode, defineEdge, defineGraph, implies } from "@nicia-ai/typegraph";
// Workflow definition (template)
const WorkflowDefinition = defineNode("WorkflowDefinition", {
schema: z.object({
name: z.string(),
description: z.string().optional(),
version: z.number().int().positive(),
isActive: z.boolean().default(true),
}),
});
// States within a workflow
const State = defineNode("State", {
schema: z.object({
name: z.string(),
type: z.enum(["initial", "intermediate", "terminal", "approval"]),
config: z.record(z.unknown()).optional(), // State-specific config
}),
});
// Transitions between states
const Transition = defineNode("Transition", {
schema: z.object({
name: z.string(),
condition: z.string().optional(), // Expression to evaluate
requiredRole: z.string().optional(),
}),
});
// Workflow instances
const WorkflowInstance = defineNode("WorkflowInstance", {
schema: z.object({
referenceId: z.string(), // ID of the entity being processed
referenceType: z.string(), // Type of entity (e.g., "PurchaseOrder")
status: z.enum(["active", "completed", "cancelled", "failed"]).default("active"),
data: z.record(z.unknown()).optional(), // Instance-specific data
createdAt: z.string().datetime(),
completedAt: z.string().datetime().optional(),
}),
});
// Tasks assigned to users
const Task = defineNode("Task", {
schema: z.object({
title: z.string(),
description: z.string().optional(),
type: z.enum(["action", "approval", "review", "notification"]),
status: z.enum(["pending", "in_progress", "completed", "rejected", "escalated"]).default("pending"),
dueDate: z.string().datetime().optional(),
priority: z.enum(["low", "medium", "high", "urgent"]).default("medium"),
result: z.record(z.unknown()).optional(),
completedAt: z.string().datetime().optional(),
}),
});
// Users
const User = defineNode("User", {
schema: z.object({
email: z.string().email(),
name: z.string(),
role: z.string(),
department: z.string().optional(),
}),
});
// Comments on tasks
const Comment = defineNode("Comment", {
schema: z.object({
content: z.string(),
createdAt: z.string().datetime(),
}),
});
// Edges
const hasState = defineEdge("hasState");
const hasTransition = defineEdge("hasTransition");
const fromState = defineEdge("fromState");
const toState = defineEdge("toState");
const usesDefinition = defineEdge("usesDefinition");
const currentState = defineEdge("currentState");
const hasTask = defineEdge("hasTask");
const assignedTo = defineEdge("assignedTo");
const createdBy = defineEdge("createdBy");
const hasComment = defineEdge("hasComment");
const reportsTo = defineEdge("reportsTo"); // For escalation chain
// Graph
const graph = defineGraph({
id: "workflow_engine",
nodes: {
WorkflowDefinition: {
type: WorkflowDefinition,
unique: [
{
name: "workflow_name_version",
fields: ["name", "version"],
scope: "kind",
collation: "binary",
},
],
},
State: { type: State },
Transition: { type: Transition },
WorkflowInstance: { type: WorkflowInstance },
Task: { type: Task },
User: {
type: User,
unique: [
{
name: "user_email",
fields: ["email"],
scope: "kind",
collation: "caseInsensitive",
},
],
},
Comment: { type: Comment },
},
edges: {
hasState: { type: hasState, from: [WorkflowDefinition], to: [State] },
hasTransition: { type: hasTransition, from: [WorkflowDefinition], to: [Transition] },
fromState: { type: fromState, from: [Transition], to: [State] },
toState: { type: toState, from: [Transition], to: [State] },
usesDefinition: { type: usesDefinition, from: [WorkflowInstance], to: [WorkflowDefinition] },
currentState: { type: currentState, from: [WorkflowInstance], to: [State] },
hasTask: { type: hasTask, from: [WorkflowInstance], to: [Task] },
assignedTo: { type: assignedTo, from: [Task], to: [User] },
createdBy: { type: createdBy, from: [Task, Comment, WorkflowInstance], to: [User] },
hasComment: { type: hasComment, from: [Task], to: [Comment] },
reportsTo: { type: reportsTo, from: [User], to: [User] },
},
ontology: [
// Escalation implies assignment
implies(reportsTo, assignedTo),
],
});
```
## Workflow Definition
### Create Approval Workflow
```typescript
async function createApprovalWorkflow(): Promise> {
return store.transaction(async (tx) => {
// Create workflow definition
const workflow = await tx.nodes.WorkflowDefinition.create({
name: "Purchase Order Approval",
description: "Multi-level approval for purchase orders",
version: 1,
isActive: true,
});
// Create states
const states = {
draft: await tx.nodes.State.create({
name: "Draft",
type: "initial",
}),
pendingManagerApproval: await tx.nodes.State.create({
name: "Pending Manager Approval",
type: "approval",
config: { approverRole: "manager", timeout: "48h" },
}),
pendingFinanceApproval: await tx.nodes.State.create({
name: "Pending Finance Approval",
type: "approval",
config: { approverRole: "finance", timeout: "24h" },
}),
approved: await tx.nodes.State.create({
name: "Approved",
type: "terminal",
}),
rejected: await tx.nodes.State.create({
name: "Rejected",
type: "terminal",
}),
};
// Link states to workflow
for (const state of Object.values(states)) {
await tx.edges.hasState.create(workflow, state, {});
}
// Create transitions
const transitions = [
{
from: states.draft,
to: states.pendingManagerApproval,
name: "Submit",
requiredRole: "requester",
},
{
from: states.pendingManagerApproval,
to: states.pendingFinanceApproval,
name: "Approve",
requiredRole: "manager",
condition: "amount > 1000",
},
{
from: states.pendingManagerApproval,
to: states.approved,
name: "Approve",
requiredRole: "manager",
condition: "amount <= 1000",
},
{
from: states.pendingManagerApproval,
to: states.rejected,
name: "Reject",
requiredRole: "manager",
},
{
from: states.pendingFinanceApproval,
to: states.approved,
name: "Approve",
requiredRole: "finance",
},
{
from: states.pendingFinanceApproval,
to: states.rejected,
name: "Reject",
requiredRole: "finance",
},
];
for (const t of transitions) {
const transition = await tx.nodes.Transition.create({
name: t.name,
requiredRole: t.requiredRole,
condition: t.condition,
});
await tx.edges.hasTransition.create(workflow, transition, {});
await tx.edges.fromState.create(transition, t.from, {});
await tx.edges.toState.create(transition, t.to, {});
}
return workflow;
});
}
```
## Workflow Instances
### Start Workflow
```typescript
interface StartWorkflowInput {
workflowName: string;
referenceId: string;
referenceType: string;
data?: Record;
createdByUserId: string;
}
async function startWorkflow(input: StartWorkflowInput): Promise> {
return store.transaction(async (tx) => {
// Find workflow definition
const workflow = await tx
.query()
.from("WorkflowDefinition", "w")
.whereNode("w", (w) => w.name.eq(input.workflowName).and(w.isActive.eq(true)))
.select((ctx) => ctx.w)
.first();
if (!workflow) {
throw new Error(`Workflow '${input.workflowName}' not found`);
}
// Find initial state
const initialState = await tx
.query()
.from("WorkflowDefinition", "w")
.whereNode("w", (w) => w.id.eq(workflow.id))
.traverse("hasState", "e")
.to("State", "s")
.whereNode("s", (s) => s.type.eq("initial"))
.select((ctx) => ctx.s)
.first();
if (!initialState) {
throw new Error("Workflow has no initial state");
}
// Create instance
const instance = await tx.nodes.WorkflowInstance.create({
referenceId: input.referenceId,
referenceType: input.referenceType,
status: "active",
data: input.data,
createdAt: new Date().toISOString(),
});
// Link to definition and state
await tx.edges.usesDefinition.create(instance, workflow, {});
await tx.edges.currentState.create(instance, initialState, {});
// Link to creator
const creator = await tx.nodes.User.getById(input.createdByUserId);
if (!creator) throw new Error(`User not found: ${input.createdByUserId}`);
await tx.edges.createdBy.create(instance, creator, {});
return instance;
});
}
```
### Get Available Transitions
```typescript
interface AvailableTransition {
id: string;
name: string;
targetState: string;
requiredRole?: string;
condition?: string;
}
async function getAvailableTransitions(
instanceId: string,
userId: string
): Promise {
// Get user's role
const user = await store.nodes.User.getById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
const userRole = user.role;
// Get current state
const currentState = await store
.query()
.from("WorkflowInstance", "i")
.whereNode("i", (i) => i.id.eq(instanceId))
.traverse("currentState", "e")
.to("State", "s")
.select((ctx) => ctx.s)
.first();
if (!currentState) {
throw new Error("Instance has no current state");
}
// Get transitions from current state
const transitions = await store
.query()
.from("State", "s")
.whereNode("s", (s) => s.id.eq(currentState.id))
.traverse("fromState", "e1", { direction: "in" })
.to("Transition", "t")
.traverse("toState", "e2")
.to("State", "target")
.select((ctx) => ({
id: ctx.t.id,
name: ctx.t.name,
targetState: ctx.target.name,
requiredRole: ctx.t.requiredRole,
condition: ctx.t.condition,
}))
.execute();
// Filter by role
return transitions.filter(
(t) => !t.requiredRole || t.requiredRole === userRole || userRole === "admin"
);
}
```
### Execute Transition
```typescript
async function executeTransition(
instanceId: string,
transitionId: string,
userId: string,
result?: Record
): Promise {
await store.transaction(async (tx) => {
const instance = await tx.nodes.WorkflowInstance.getById(instanceId);
if (!instance) throw new Error(`WorkflowInstance not found: ${instanceId}`);
if (instance.status !== "active") {
throw new Error("Workflow is not active");
}
// Verify transition is valid
const available = await getAvailableTransitions(instanceId, userId);
const transition = available.find((t) => t.id === transitionId);
if (!transition) {
throw new Error("Transition not available");
}
// Get target state
const targetState = await tx
.query()
.from("Transition", "t")
.whereNode("t", (t) => t.id.eq(transitionId))
.traverse("toState", "e")
.to("State", "s")
.select((ctx) => ctx.s)
.first();
// Remove current state edge
const currentStateEdge = await tx
.query()
.from("WorkflowInstance", "i")
.whereNode("i", (i) => i.id.eq(instanceId))
.traverse("currentState", "e")
.to("State", "s")
.select((ctx) => ctx.e.id)
.first();
if (currentStateEdge) {
await tx.edges.currentState.delete(currentStateEdge);
}
// Add new state edge
await tx.edges.currentState.create(instance, targetState!, {});
// Update instance data
const updatedData = { ...instance.data, lastTransition: transition.name, ...result };
const updates: Partial = { data: updatedData };
// Check if terminal state
if (targetState!.type === "terminal") {
updates.status = "completed";
updates.completedAt = new Date().toISOString();
}
await tx.nodes.WorkflowInstance.update(instanceId, updates);
// Complete any pending tasks
const pendingTasks = await tx
.query()
.from("WorkflowInstance", "i")
.whereNode("i", (i) => i.id.eq(instanceId))
.traverse("hasTask", "e")
.to("Task", "t")
.whereNode("t", (t) => t.status.in(["pending", "in_progress"]))
.select((ctx) => ctx.t.id)
.execute();
for (const taskId of pendingTasks) {
await tx.nodes.Task.update(taskId, {
status: "completed",
completedAt: new Date().toISOString(),
});
}
// Create tasks for new state if needed
if (targetState!.type === "approval") {
await createApprovalTask(tx, instanceId, targetState!, userId);
}
});
}
```
## Task Management
### Create Approval Task
```typescript
async function createApprovalTask(
tx: Transaction,
instanceId: string,
state: Node,
requesterId: string
): Promise {
const config = state.config as { approverRole: string; timeout: string } | undefined;
if (!config) return;
// Find approver (first user with matching role, or requester's manager)
let approver = await tx
.query()
.from("User", "u")
.whereNode("u", (u) => u.role.eq(config.approverRole))
.select((ctx) => ctx.u)
.first();
// If no direct match, walk the reporting chain upward until we hit someone
// with the approver role. The recursive traversal tags each hop with its
// depth so we can pick the nearest matching manager.
if (!approver) {
const candidates = await tx
.query()
.from("User", "requester")
.whereNode("requester", (u) => u.id.eq(requesterId))
.traverse("reportsTo", "e")
.recursive({ depth: "depth" })
.to("User", "manager")
.whereNode("manager", (u) => u.role.eq(config.approverRole))
.orderBy("depth", "asc")
.select((ctx) => ctx.manager)
.execute();
approver = candidates[0];
}
if (!approver) {
throw new Error(`No approver found with role '${config.approverRole}'`);
}
// Calculate due date
const dueDate = calculateDueDate(config.timeout);
// Create task
const task = await tx.nodes.Task.create({
title: `Approval Required: ${state.name}`,
description: `Please review and approve or reject.`,
type: "approval",
status: "pending",
priority: "medium",
dueDate: dueDate.toISOString(),
});
// Link task to instance and approver
const instance = await tx.nodes.WorkflowInstance.getById(instanceId);
if (!instance) throw new Error(`WorkflowInstance not found: ${instanceId}`);
await tx.edges.hasTask.create(instance, task, {});
await tx.edges.assignedTo.create(task, approver, {});
}
function calculateDueDate(timeout: string): Date {
const now = new Date();
const match = timeout.match(/^(\d+)(h|d)$/);
if (!match) return new Date(now.getTime() + 24 * 60 * 60 * 1000); // Default 24h
const value = parseInt(match[1], 10);
const unit = match[2];
if (unit === "h") {
return new Date(now.getTime() + value * 60 * 60 * 1000);
} else {
return new Date(now.getTime() + value * 24 * 60 * 60 * 1000);
}
}
```
### Get User's Tasks
```typescript
interface TaskWithContext {
id: string;
title: string;
type: string;
status: string;
priority: string;
dueDate?: string;
workflowName: string;
referenceId: string;
referenceType: string;
}
async function getUserTasks(
userId: string,
status?: "pending" | "in_progress"
): Promise {
let query = store
.query()
.from("User", "u")
.whereNode("u", (u) => u.id.eq(userId))
.traverse("assignedTo", "e", { direction: "in" })
.to("Task", "t");
if (status) {
query = query.whereNode("t", (t) => t.status.eq(status));
} else {
query = query.whereNode("t", (t) => t.status.in(["pending", "in_progress"]));
}
return query
.traverse("hasTask", "e2", { direction: "in" })
.to("WorkflowInstance", "i")
.traverse("usesDefinition", "e3")
.to("WorkflowDefinition", "w")
.select((ctx) => ({
id: ctx.t.id,
title: ctx.t.title,
type: ctx.t.type,
status: ctx.t.status,
priority: ctx.t.priority,
dueDate: ctx.t.dueDate,
workflowName: ctx.w.name,
referenceId: ctx.i.referenceId,
referenceType: ctx.i.referenceType,
}))
.orderBy((ctx) => ctx.t.dueDate, "asc")
.execute();
}
```
### Complete Task
```typescript
async function completeTask(
taskId: string,
userId: string,
decision: "approve" | "reject",
comment?: string
): Promise {
await store.transaction(async (tx) => {
const task = await tx.nodes.Task.getById(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
// Verify user is assigned
const assignee = await tx
.query()
.from("Task", "t")
.whereNode("t", (t) => t.id.eq(taskId))
.traverse("assignedTo", "e")
.to("User", "u")
.select((ctx) => ctx.u.id)
.first();
if (assignee !== userId) {
throw new Error("User is not assigned to this task");
}
// Update task
await tx.nodes.Task.update(taskId, {
status: decision === "approve" ? "completed" : "rejected",
completedAt: new Date().toISOString(),
result: { decision },
});
// Add comment if provided
if (comment) {
const commentNode = await tx.nodes.Comment.create({
content: comment,
createdAt: new Date().toISOString(),
});
await tx.edges.hasComment.create(task, commentNode, {});
const user = await tx.nodes.User.getById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
await tx.edges.createdBy.create(commentNode, user, {});
}
// Get workflow instance
const instance = await tx
.query()
.from("Task", "t")
.whereNode("t", (t) => t.id.eq(taskId))
.traverse("hasTask", "e", { direction: "in" })
.to("WorkflowInstance", "i")
.select((ctx) => ctx.i)
.first();
// Find and execute the appropriate transition
const transitions = await getAvailableTransitions(instance!.id, userId);
const transition = transitions.find((t) =>
decision === "approve" ? t.name === "Approve" : t.name === "Reject"
);
if (transition) {
await executeTransition(instance!.id, transition.id, userId, { decision });
}
});
}
```
## Escalation
### Check Overdue Tasks
```typescript
async function getOverdueTasks(): Promise> {
const now = new Date().toISOString();
return store
.query()
.from("Task", "t")
.whereNode("t", (t) =>
t.status
.in(["pending", "in_progress"])
.and(t.dueDate.isNotNull())
.and(t.dueDate.lt(now))
)
.traverse("assignedTo", "e")
.to("User", "u")
.select((ctx) => ({
task: ctx.t,
assignee: ctx.u,
}))
.execute();
}
```
### Escalate Task
```typescript
async function escalateTask(taskId: string): Promise {
await store.transaction(async (tx) => {
// Get current assignee
const currentAssignment = await tx
.query()
.from("Task", "t")
.whereNode("t", (t) => t.id.eq(taskId))
.traverse("assignedTo", "e")
.to("User", "u")
.select((ctx) => ({ edgeId: ctx.e.id, user: ctx.u }))
.first();
if (!currentAssignment) {
throw new Error("Task has no assignee");
}
// Single-hop traversal to the direct manager
const manager = await tx
.query()
.from("User", "u")
.whereNode("u", (u) => u.id.eq(currentAssignment.user.id))
.traverse("reportsTo", "e")
.to("User", "manager")
.select((ctx) => ctx.manager)
.first();
if (!manager) {
throw new Error("No manager found for escalation");
}
// Update task
await tx.nodes.Task.update(taskId, {
status: "escalated",
priority: "urgent",
});
// Reassign to manager
await tx.edges.assignedTo.delete(currentAssignment.edgeId);
const task = await tx.nodes.Task.getById(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
await tx.edges.assignedTo.create(task, manager, {});
// Add escalation comment
const comment = await tx.nodes.Comment.create({
content: `Task escalated from ${currentAssignment.user.name} due to timeout`,
createdAt: new Date().toISOString(),
});
await tx.edges.hasComment.create(task, comment, {});
});
}
```
### Run Escalation Job
```typescript
async function runEscalationJob(): Promise<{ escalated: number }> {
const overdueTasks = await getOverdueTasks();
let escalated = 0;
for (const { task } of overdueTasks) {
try {
await escalateTask(task.id);
escalated++;
} catch (error) {
console.error(`Failed to escalate task ${task.id}:`, error);
}
}
return { escalated };
}
```
## Workflow History
### Get Instance Timeline
```typescript
interface TimelineEvent {
timestamp: string;
type: "state_change" | "task_created" | "task_completed" | "comment";
description: string;
actor?: string;
}
async function getInstanceTimeline(instanceId: string): Promise {
const events: TimelineEvent[] = [];
// Run both history reads in sequence. Two statements, not one, and
// not a snapshot — under read-committed isolation the task view can observe
// a write the state-change view did not.
const [stateHistory, tasks] = await store.batch(
store
.query()
.from("WorkflowInstance", "i")
.temporal("includeEnded")
.whereNode("i", (i) => i.id.eq(instanceId))
.traverse("currentState", "e")
.to("State", "s")
.orderBy("e", "validFrom", "asc")
.select((ctx) => ({
stateName: ctx.s.name,
timestamp: ctx.e.validFrom,
})),
store
.query()
.from("WorkflowInstance", "i")
.whereNode("i", (i) => i.id.eq(instanceId))
.traverse("hasTask", "e")
.to("Task", "t")
.optionalTraverse("assignedTo", "a")
.to("User", "u")
.select((ctx) => ({
title: ctx.t.title,
status: ctx.t.status,
createdAt: ctx.t.createdAt,
completedAt: ctx.t.completedAt,
assignee: ctx.u?.name,
})),
);
for (const state of stateHistory) {
events.push({
timestamp: state.timestamp,
type: "state_change",
description: `Entered state: ${state.stateName}`,
});
}
for (const task of tasks) {
events.push({
timestamp: task.createdAt.toISOString(),
type: "task_created",
description: `Task created: ${task.title}`,
actor: task.assignee,
});
if (task.completedAt) {
events.push({
timestamp: task.completedAt,
type: "task_completed",
description: `Task ${task.status}: ${task.title}`,
actor: task.assignee,
});
}
}
// Sort by timestamp
return events.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
}
```
## Next Steps
- [Document Management](/examples/document-management) - CMS with semantic search
- [Product Catalog](/examples/product-catalog) - Categories, variants, inventory
- [Audit Trail](/examples/audit-trail) - Complete change tracking