History
Record who changed what, with before and after snapshots, and show the changes field by field.
@tulip-systems/history is the change history module. Use it when the application wants to answer: who changed this, when, and what did it look like before?
Every entry stores the changed resource, the action, the actor, the time, and complete snapshots of the resource before and after the change. The UI compares the snapshots field by field.
When to use History
- an audit log of changes across the app
- the activity of one record, such as a task or a project
- comparing what a record looked like before and after a change
History is usually fed by Events: the mutation publishes an event with the row snapshots, and a listener records the change.
Entry points
// Definitions, filters, sorting, validators and label helpers
import { defineHistoryResource, historyFilters } from "@tulip-systems/history";
// The History service
import { History } from "@tulip-systems/history/server";
// The Drizzle adapter and the snapshot helper
import { historyDrizzleAdapter, historySnapshots } from "@tulip-systems/history/drizzle";
// The changes view and the comparison primitives
import { HistoryChanges, HistorySnapshotDiff } from "@tulip-systems/history/client";Import the styles in your global stylesheet:
@import "@tulip-systems/history/styles.css";Define a resource
A resource definition describes one kind of record in history. It validates the data you record with, describes the record, and tells the UI how to label and format its fields. Definitions hold no server code, so the same definition is used to record changes and to show them.
// app/admin/tasks/_lib/history.ts
import { defineHistoryResource } from "@tulip-systems/history";
import { findStatus } from "@tulip-systems/ui/status";
import { z } from "zod";
export const taskHistory = defineHistoryResource("task", {
label: "Tasks",
schema: z.object({
taskId: z.uuid(),
code: z.string(),
title: z.string(),
projectId: z.uuid(),
projectTitle: z.string(),
}),
describe: ({ data }) => ({
id: data.taskId,
label: `${data.code} · ${data.title}`,
context: [{ type: "project", id: data.projectId, label: data.projectTitle }],
}),
actions: { assigned: "Assigned" },
fields: {
updated_at: { ignore: true },
status: { label: "Status", format: (value) => findStatus(taskStatusConfig, String(value))?.label },
},
});describereturns the stored id and label of the record, and itscontext: the parent records, from broadest to nearest. Labels are stored as they were at the time of the change.actionsadds actions besidescreated,updatedanddeleted.history.recordonly accepts the actions of the resource.fieldsis keyed by snapshot key.ignoreleaves a field out of the comparison: an update that only changes ignored fields is not recorded.formatturns a stored value into readable text, such as a status label or the plain text of an editor document.
Set up the table
The app owns the table and its migrations. Make dedupeKey unique, so a retried event is recorded once.
// app/admin/history/_lib/schema.ts
export const historyEntries = pgTable(
"history_entries",
(t) => ({
...baseColumns,
resourceType: t.varchar().notNull(),
resourceId: t.varchar().notNull(),
resourceLabel: t.varchar().notNull(),
context: t.jsonb().$type<HistoryContext>().default([]).notNull(),
action: t.varchar().notNull(),
actorId: t.varchar(),
actorName: t.varchar(),
viaType: t.varchar(),
viaId: t.varchar(),
viaLabel: t.varchar(),
changedFields: t.jsonb().$type<string[]>().default([]).notNull(),
before: t.jsonb().$type<HistorySnapshot>(),
after: t.jsonb().$type<HistorySnapshot>(),
eventId: t.varchar(),
eventName: t.varchar(),
eventVersion: t.integer(),
dedupeKey: t.varchar().unique(),
occurredAt: t.timestamp({ withTimezone: true, precision: 3 }).notNull(),
}),
(t) => [
index("history_entries_occurred_at_idx").on(t.occurredAt.desc(), t.id.desc()),
index("history_entries_resource_idx").on(t.resourceType, t.resourceId, t.occurredAt.desc()),
index("history_entries_actor_idx").on(t.actorId, t.occurredAt.desc()),
index("history_entries_via_idx").on(t.viaId, t.occurredAt.desc()),
],
);Create the service with the Drizzle adapter:
// server/history/init.ts
import { historyDrizzleAdapter } from "@tulip-systems/history/drizzle";
import { History } from "@tulip-systems/history/server";
import * as schema from "@/app/admin/history/_lib/schema";
export const history = History.init({
database: historyDrizzleAdapter({ db, schema }),
});Record changes
Capture the complete row before and after the mutation with historySnapshots(). It selects OLD and NEW in RETURNING, which needs PostgreSQL 18. Select only after for an insert and only before for a delete.
const [task] = await db
.update(tasks)
.set(input)
.where(eq(tasks.id, input.id))
.returning({ ...getTableColumns(tasks), ...historySnapshots() });
await events.publish(taskUpdatedEvent, {
actor: { id: user.id, name: user.name },
taskId: task.id,
// ...
before: task.before,
after: task.after,
});Use historyActorSchema and historySnapshotSchema in the event schema, and record the change in a listener:
// app/admin/tasks/_lib/listeners.server.ts
export const taskHistoryEventListeners = {
taskUpdated: taskUpdatedEvent.listen(async ({ payload, event }) => {
await history.record(taskHistory, {
action: "updated",
data: payload,
actor: payload.actor,
before: payload.before,
after: payload.after,
event,
});
}),
};Passing event stores the event name and version, uses the event time as occurredAt, and derives the dedupeKey. You can also call history.record directly in a mutation, without an event. Leave out actor for changes made by the system.
record returns the stored entry, or null when nothing changed or the entry was already recorded.
Changes made by agents
When an AI agent or an MCP client makes a change for a user, the user is still the actor. Add via to the actor to record what they made it through. Its type is yours to choose, and the label is stored with the entry, like the actor's name:
actor: {
id: user.id,
name: user.name,
via: { type: "agent", id: agent.id, label: chat.title },
},The entry stores it as viaType, viaId and viaLabel. Filter on viaType for the changes of every agent, or on viaId for the changes of one.
Read history
// A page of entries, without their snapshots
const entries = await history.list({ filters, sorts, limit: 50, offset: 0 });
const total = await history.count({ filters });
// The activity of one task
const activity = await history.list({ filters: { resourceType: ["task"], resourceId: taskId } });
// One entry with its snapshots
const entry = await history.get({ id });
// Everyone who made a change, for an actor filter
const actors = await history.listActors();The service does not check permissions. Expose it through your own procedures, with your session and permission middleware, and use historyFiltersSchema and historySortsSchema as their input.
Show history
historyFilters and historySorts plug into the data table hooks of @tulip-systems/query, like any other table. The label helpers build titles from your definitions:
getHistoryEntryTitle(entry, resources): "Tasks · T-12 · Fix login · Updated"getHistoryContextLabel(entry.context, resources): "Projects: Website"getHistoryActionLabel(action, resource)andgetHistoryFieldLabel(key, resource)
Resource types and actions without a definition fall back to a humanized key.
On the entry page, HistoryChanges compares the snapshots field by field, with changed words highlighted, and HistorySnapshotDiff shows both snapshots as JSON:
const resource = historyResources.find((resource) => resource.type === entry.resourceType);
<HistoryChanges entry={entry} resource={resource} />
<HistorySnapshotDiff entry={entry} />The FieldComparison primitives they are built from are exported too, for your own comparisons.