Entity Changelog

Status: ✅ Shipped (predates 2026-07-20; exact commit outside the shallow history) — entity_changelog (database/v1/25_tables_entity_changelog.sql) written by per-entity triggers (functions/43_entity_changelog_triggers.sql), surfaced as the Recent Activity feed in the Workbench entity view, the package About form, and the project/entity/member panels on the Projects page. Undo / field-level revert and package version diffing described below are not built. Retention (2026-10-02): entries are kept for Changelog.RetentionDays days — 30 by default, at most 365 — except for an entity under an open moderation report; see Retention Policy.

Overview

An entity changelog is a per-entity, append-only log of every meaningful change made to a character, mode, lorebook, or package. It records what changed, when, and by whom — giving creators a full edit history of their content and providing the foundation for collaborative editing, proposal review, and version diffing.

Today, entities only have created_at and updated_at timestamps. When a collaborator with can_edit modifies a character's system prompt, the owner sees the new content but has no way to know what it replaced, when the edit happened, or who made it. When the lorebook assistant auto-approves 20 entry changes in a session, the only record of the original state lives inside that specific session's snapshot — not on the entries themselves.

The entity changelog solves this by recording structured change events at the entity level. It is not a full snapshot/versioning system — it tracks what fields changed with enough context to display a human-readable activity feed, power undo-like workflows, and provide the audit trail that collaboration requires.


Why This Is a Prerequisite to Collaboration

The sharing system already has five permission flags: can_use, can_view, can_contribute, can_edit, can_manage. Three of these (can_contribute, can_edit, can_manage) involve modifying or reviewing modifications to content. Without a changelog:

  1. Editors are invisible. A user with can_edit can change a character's system prompt. The owner has no way to see that it changed, what the previous version was, or when the edit happened. This makes can_edit dangerous to grant.

  2. Proposals have no history. The planned entity_proposals system (see Sharing: Planned Features) lets contributors propose changes. Managers need to review these against the entity's current state and recent edit history to make informed decisions. Without a changelog, managers see proposed diffs in a vacuum.

  3. Undo is impossible. When someone makes a bad edit (or a well-intentioned one that breaks the character), there's no way to revert. The old content is gone. A changelog with field-level snapshots enables selective revert.

  4. Trust requires transparency. Creators won't share editing access if they can't see what editors changed. An activity feed ("Alice edited system prompt — 2 hours ago") builds the trust needed for collaborative workflows.

  5. Package version diffing is blocked. The Creator Workbench identifies version diffing as desirable but blocked by missing DB infrastructure. The entity changelog provides the building block — if each entity tracks its changes, a package publish can snapshot the changelog state and diff against the previous publish.


What Exists Today

Infrastructure Status Notes
entity_permission_audit table Exists Tracks permission changes only (grant, revoke, update). Does not track content changes.
updated_at on all entities Exists Tells you when something last changed, not what changed or who did it.
Lorebook assistant snapshots Exists lorebook_session_snapshot_entries captures entry state at session start. Session-scoped, not entry-scoped. Snapshot data lives in the assistant domain, not the lorebook domain.
Lorebook entry version column Exists (05e_add_version_to_lorebook_entries.sql) Integer incremented on update, used for optimistic locking in proposals. No history of what changed per version.
Package version + changelog fields Exists Semver string + freeform text. Manual, not structured. No per-field tracking.

Gap: No entity has structured change tracking. We know that something changed (updated_at) and sometimes how many times (version on lorebook entries), but never what changed, who changed it, or what the previous value was.


Proposed Design

Core Table: entity_changelog

A single, entity-type-agnostic changelog table. Every row is one change event.

entity_changelog
├── id                  SERIAL PRIMARY KEY
├── entity_type         INTEGER NOT NULL          -- 0=Character, 1=Mode, 2=Lorebook, 3=Persona, 4=Package
├── entity_id           INTEGER NOT NULL
├── user_id             INTEGER NOT NULL           -- who made the change
├── action              VARCHAR(30) NOT NULL        -- 'create', 'update', 'delete', 'restore', 'publish', 'unpublish'
├── changed_fields      JSONB                       -- { "name": { "old": "Elara", "new": "Elara the Wise" }, ... }
├── summary             VARCHAR(500)                -- human-readable summary (nullable, auto-generated or user-provided)
├── source              VARCHAR(30) NOT NULL        -- 'manual', 'api', 'assistant', 'proposal', 'import', 'system'
├── source_ref          VARCHAR(200)                -- optional reference (proposal ID, assistant session ID, import batch ID)
├── created_at          TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP

Indexes:

Design decisions:

  1. One table for all entity types. Same pattern as entity_permissions and entity_permission_audit. Avoids N separate tables that all have the same schema.

  2. changed_fields is JSONB with old/new values. For update actions, each key is a field name, and the value is { "old": ..., "new": ... }. For create, old is null. For delete, new is null. This gives us enough for display, diff, and revert without storing full entity snapshots.

  3. Large text fields store truncated previews. System prompts, lorebook entry content, and other large text fields store a truncated preview (first 200 chars) in changed_fields plus a character count. The full old/new content is not stored inline — if needed, it can be reconstructed from the content tables or from a separate entity_changelog_content table (see Extensions below).

  4. source distinguishes how the change was made. This is critical for the activity feed — "Alice edited the system prompt" vs. "Lorebook Assistant auto-approved entry changes" vs. "Import from JSON file" are different events even though they all result in update actions.

  5. summary is optional and can be auto-generated. For manual edits, the system generates a summary like "Updated name and description." For proposal approvals, it copies the proposal description. For imports, it notes the source file. Creators can optionally provide their own summary (commit-message style).

What Gets Logged

Not every database write needs a changelog entry. The changelog tracks user-meaningful changes to entity content and configuration.

Action When changed_fields contains
create Entity is created All initial field values (old = null for each)
update Any content field is modified Only the fields that changed, with old/new values
delete Soft delete (is_deleted = true) { "is_deleted": { "old": false, "new": true } }
restore Soft delete reversed { "is_deleted": { "old": true, "new": false } }
publish is_public set to true { "is_public": { "old": false, "new": true } }
unpublish is_public set to false { "is_public": { "old": true, "new": false } }

What is NOT logged:

Entity-Specific Fields

Different entity types have different fields worth tracking. The changed_fields JSONB is flexible enough to handle this without schema changes, but the application layer should know which fields to capture.

Characters:

Modes:

Lorebooks:

Lorebook Entries:

Packages:

Sub-Entity Tracking

Lorebook entries, character greetings, and sub-prompts are children of a parent entity. Changes to them should appear in the parent's changelog for a unified activity feed.

Option A: sub_entity_type + sub_entity_id columns on entity_changelog

entity_changelog (extended)
├── ...
├── sub_entity_type     SMALLINT                   -- NULL for parent, or: 0=LorebookEntry, 1=Greeting, 2=SubPrompt
├── sub_entity_id       INTEGER                    -- NULL for parent entity changes

This keeps all changes in one table and one query: "give me the full history of this lorebook including entry changes."

Option B: Separate entity_type values for sub-entities

Add entity_type = 5 for lorebook entries, entity_type = 6 for greetings, etc. Requires joining on parent ID for the unified feed.

Recommended: Option A. Keeps the unified feed query simple. Sub-entity changes roll up to the parent naturally. The parent entity's changelog shows everything.


Recording Changes

Where Changelog Writes Happen

Changelog entries should be written by the database layer (stored procedures), not by application code. This ensures every write path — API endpoints, lorebook assistant, import, admin actions — produces changelog entries without relying on callers to remember.

Pattern: Modify existing fn_update_character, fn_update_lorebook_entry, etc. to:

  1. Compare old vs. new values
  2. Build the changed_fields JSONB from the diff
  3. Insert into entity_changelog
  4. Return the changelog entry ID (optional, for callers that want to reference it)
-- Pseudocode for fn_update_character with changelog
CREATE OR REPLACE FUNCTION fn_update_character(
    p_character_id INTEGER,
    p_user_id INTEGER,
    p_name VARCHAR DEFAULT NULL,
    p_description VARCHAR DEFAULT NULL,
    -- ... other updatable fields
    p_source VARCHAR DEFAULT 'manual',
    p_source_ref VARCHAR DEFAULT NULL,
    p_summary VARCHAR DEFAULT NULL
) RETURNS INTEGER AS $$
DECLARE
    v_old RECORD;
    v_changed JSONB := '{}';
    v_changelog_id INTEGER;
BEGIN
    SELECT * INTO v_old FROM characters WHERE id = p_character_id;

    IF p_name IS NOT NULL AND p_name IS DISTINCT FROM v_old.name THEN
        v_changed := v_changed || jsonb_build_object('name',
            jsonb_build_object('old', v_old.name, 'new', p_name));
    END IF;
    -- ... repeat for each field

    -- Only insert changelog if something actually changed
    IF v_changed != '{}' THEN
        INSERT INTO entity_changelog (entity_type, entity_id, user_id, action, changed_fields, source, source_ref, summary)
        VALUES (0, p_character_id, p_user_id, 'update', v_changed, p_source, p_source_ref, p_summary)
        RETURNING id INTO v_changelog_id;
    END IF;

    -- Apply the actual update
    UPDATE characters SET
        name = COALESCE(p_name, name),
        description = COALESCE(p_description, description),
        updated_at = CURRENT_TIMESTAMP
    WHERE id = p_character_id;

    RETURN v_changelog_id;
END;
$$ LANGUAGE plpgsql;

No-Op Update Detection

The IS DISTINCT FROM comparison in the stored procedure naturally rejects saves where nothing actually changed — if the user hits Save without modifying anything, v_changed stays '{}' and no changelog entry is created.

This means updated_at should become a derived value from the changelog rather than a stored column that update functions bump directly. Today, every entity table has an updated_at TIMESTAMPTZ column that stored procedures set unconditionally on every save. With the changelog as the source of truth for when real changes happened, the stored column becomes redundant — or worse, a drift risk.

Migration path:

  1. Short term: Keep the updated_at column but only bump it when the changelog records a real change (guard behind v_changed != '{}'). This is the minimal change — existing queries still work.
  2. Long term: Replace updated_at with a DB view or generated column that reads MAX(created_at) from entity_changelog for that entity. Drop the stored column entirely. Entity tables keep created_at (immutable) but updated_at becomes:
-- In the entity view (e.g., vw_characters)
COALESCE(
    (SELECT MAX(created_at) FROM entity_changelog
     WHERE entity_type = 0 AND entity_id = c.id),
    c.created_at
) AS updated_at

This eliminates any possibility of updated_at drifting from reality. An entity's "last updated" timestamp is always the timestamp of its most recent changelog entry — no exceptions, no special cases.

Retention caps this (2026-10-02). The changelog keeps only Changelog.RetentionDays (30 days by default). An entity untouched for longer has no entries left, so a derived updated_at would fall back to created_at. This long-term step needs its own durable record, not the changelog. See Retention Policy.

Performance consideration: The (entity_type, entity_id, created_at DESC) index on entity_changelog makes the MAX(created_at) subquery efficient (index-only scan, single row). For hot paths like Browse sorting, a materialized/cached value may still be desirable — but it should be derived from the changelog, not maintained independently.

This prevents fake updates — a creator re-publishing a character or package without meaningful changes cannot game the "recently updated" sorting or display an "Updated" badge. If the changelog has no entries, there's no updated_at to inflate.

Where this matters:

Whitespace-only changes should also be filtered. The stored procedure should normalize text fields (trim trailing whitespace, normalize line endings) before comparison. A save that only changes "Hello " to "Hello" is not a meaningful update.

Round-trip no-ops are harder to detect at write time. A creator could toggle mode_locked on, save, toggle it off, save — two individually valid changelog entries that cancel each other out. Each save has a real diff, so the stored procedure correctly logs both. The fake-ness only shows up when you compare the entity's current state against its state at a previous point.

This matters for publish validation. When a creator bumps the version and publishes, the system should compute the net diff since the last publish — not just check whether changelog entries exist between the two publish events. If every field's current value matches the value at last-publish time, the net diff is empty and the "update" is hollow.

Implementation: On publish, compare the entity's current state against a snapshot taken at the previous publish (or use the changelog entries to reconstruct the previous state by walking old values backwards). If the net diff is empty, either:

Source Attribution

The source column tells the UI how to render the change:

Source Meaning Display example
manual Creator edited via the UI "You edited name and description"
api External API call "Updated via API"
assistant Lorebook assistant auto-approved a proposal "Lorebook Assistant created entry 'Dragon'"
proposal A contributor's proposal was approved "Alice's proposal approved by Bob"
import Imported from file (JSON, PNG, etc.) "Imported from character.json"
system System-initiated change (migration, content check) "System: content flagged and hidden"

Batch Changes

When multiple fields change in a single save (common — creator edits name + description + prompt in one form submit), that's one changelog entry with multiple keys in changed_fields.

When the lorebook assistant batch-approves 10 proposals, each proposal generates its own changelog entry on the affected entry. The parent lorebook gets a single summary entry: "Lorebook Assistant: 10 entries updated (session #42)".


API

Creator Endpoints

GET /api/creator/{entities}/{id}/changelog
    ?page=1&limit=20
    &action=update           (optional filter)
    &user_id=123             (optional filter — for multi-editor entities)
    &include_sub_entities=true  (default true — include entry/greeting changes)

Response:
{
    items: [
        {
            id: 1234,
            action: "update",
            userId: 42,
            userName: "Alice",
            userAvatarUrl: "...",
            changedFields: { "name": { "old": "Elara", "new": "Elara the Wise" } },
            summary: "Updated character name",
            source: "manual",
            sourceRef: null,
            subEntityType: null,
            subEntityId: null,
            subEntityName: null,
            createdAt: "2026-02-26T10:00:00Z"
        },
        ...
    ],
    total: 47,
    page: 1,
    limit: 20
}

Admin Endpoints

GET /api/admin/changelog
    ?entity_type=0&entity_id=123   (optional — specific entity)
    &user_id=42                     (optional — specific user)
    &action=delete                  (optional — specific action)
    &from=2026-01-01&to=2026-02-01 (optional — date range)
    &page=1&limit=50

Frontend

Activity Feed Component

A reusable <ActivityFeed> component that renders changelog entries as a vertical timeline. Lives in shared/src/components/common/ for use by both clientConsole and adminConsole.

Each entry renders as:

[Avatar] Alice edited name and description          2 hours ago
         name: "Elara" → "Elara the Wise"
         description: "A wandering healer" → "A wandering healer and scholar"

[Avatar] Lorebook Assistant created entry "Dragon"  1 day ago
         via session #42

[Avatar] You published this character                3 days ago

Interactions:

Where It Appears

Page Location What it shows
Creator Hub > Character > Edit New "History" tab alongside existing tabs Character changelog including greeting changes
Creator Hub > Mode > Edit "History" tab Mode changelog including sub-prompt link changes
Creator Hub > Lorebook > Edit "History" tab Lorebook changelog including entry changes
Lorebook Assistant Inspector panel, new "History" tab Entry-level changes from the current and past sessions
Package Workbench "History" tab in About section Package changelog including component swaps
Admin Console Dedicated "Audit" page Global changelog search with filters

Revert Flow

  1. Creator clicks "Revert" on a changelog entry
  2. Confirmation modal shows the diff that will be applied (reversing old ↔ new)
  3. On confirm, API sends an update with the old values and source: 'manual', summary: 'Reverted change from [date]'
  4. This creates a new changelog entry — the original entry is never modified (append-only)

Relationship to Existing Features

Permission Audit Trail

The existing entity_permission_audit table remains separate. Permission changes are a different domain from content changes — they have different fields, different access patterns, and different audiences (permission audit is primarily for the sharing feature, changelog is for the editing workflow).

The frontend could interleave permission audit entries into the activity feed for a unified view, but they remain separate tables with separate APIs.

Lorebook Assistant Snapshots

The lorebook assistant's lorebook_session_snapshot_entries table captures a full lorebook snapshot at session start for diff computation within the session. The entity changelog does not replace this — snapshots serve a different purpose (session-scoped before/after comparison).

However, when the assistant applies changes (auto-approve or manual approve), those changes should now produce entity changelog entries with source: 'assistant' and source_ref: 'session:{sessionId}'. This connects the assistant's work to the permanent entity history.

Package Version Diffing

The Creator Workbench identifies version diffing as blocked by missing DB infrastructure. The entity changelog partially unblocks this:

This is not a full snapshot-based diff (you can't reconstruct the complete entity state at an arbitrary point in time), but it covers the most common use case: "what changed since the last publish?"

Retention caps this (2026-10-02). Entries older than Changelog.RetentionDays (30 days by default) are deleted. A diff between publishes further apart than the window loses its older entries, so version diffing needs the snapshot table below rather than the changelog alone.

For full state reconstruction, a separate entity_snapshots table would be needed. That can be added later as an extension without changing the changelog design.


Extensions (Post-v1)

Large Content Storage

For entities with large text fields (system prompts, lorebook entry content), storing full old/new values in changed_fields JSONB would bloat the table. The base design stores truncated previews. If full content diffing is needed:

Option: entity_changelog_content table:

entity_changelog_content
├── id              SERIAL PRIMARY KEY
├── changelog_id    INTEGER NOT NULL REFERENCES entity_changelog(id) ON DELETE CASCADE
├── field_name      VARCHAR(100) NOT NULL
├── old_content     TEXT
├── new_content     TEXT

This keeps the main changelog table lean while allowing full-text diffs for specific entries when needed. The API would have an ?expand=content parameter to include full diffs.

Retention Policy

Shipped (owner decision 2026-10-02): age-based, one platform window. The changelog keeps 30 days of history by default. The window is the platform setting Changelog.RetentionDays: admin-editable under Admin console → System Settings → System and MCP → "Edit history retention (days)". It accepts 1 to 365 days. There is no "keep forever" value and no per-tier window. The options considered before the decision were per-tier age pruning, compaction and archival. Compaction and archival were not taken.

How it runs. AuthService's ChangelogPartitionMaintenanceService (worker key changelog_partition_maintenance) runs every 24 h. It reads the setting fresh on every tick, so a change applies without a restart. Each tick:

  1. Creates the runway: monthly partitions for the current month and the next two, as before. This step runs whatever the retention steps do.
  2. Drops whole partitions whose entire range is older than the window (fn_drop_expired_changelog_partitions).
  3. Deletes the older rows of the remaining partitions in batches of 5,000 (fn_delete_expired_changelog_rows). Each batch is its own short transaction. A tick runs at most 200 batches; if rows are left, the next tick comes 10 minutes later. These batches cover the partition the cutoff falls in, any partition kept back by a hold, and entity_changelog_default.

The window is not month-aligned. A month's rows therefore age out a day at a time, and in steady state the batches do nearly all the work. A whole-partition drop carries the first run's backlog, or the backlog left after the window is lowered.

The cutoff is now() minus the window in 24-hour days, by the database clock. The 1..365 bound is enforced twice: at save time (the settings validator refuses anything else with out_of_range) and again in SQL (22023) before anything is deleted. The boot-time migration replay never deletes changelog rows.

Holds. Rows of an entity under an open moderation report (reports.status 0 or 1) are never deleted, and a partition that holds one is never dropped whole. Its other expired rows still go row by row. The first sweep after the report resolves deletes the held rows that have expired.

What a report holds:

The one definition of a hold is fn_changelog_held_entities() (functions/44). These existing mechanisms don't map onto changelog rows:

A hold protects the rows still present when the report becomes visible. The drop checks the hold only once it holds every lock its drops need, so nothing waits between the check and the drop. A batch delete is a single statement. So a report filed in the same instant can only miss rows that were already being deleted.

A future hold that names an entity is added to fn_changelog_held_entities(), and both deletion paths honour it.

Lock behaviour. All of this was measured on PG 18.

An unusable stored value never deletes more than the platform allows. An empty value means the default (30). A value the admin page accepts (1 to 365, fractions included) is used, with a fraction rounded up. Anything the page would refuse is read as 365 days (the ceiling) and logs a Warning on every tick. That includes a value below 1 such as 0.2, one above 365, whitespace, or anything that isn't a number, and such a value is reachable only by editing the row by hand.

Consequences. The Recent Activity panels show only the window. Their empty state reads "No recent activity". The first tick after the deploy deletes everything older than 30 days, and that cannot be undone; backups keep it for up to 30 more days. Lowering the window deletes the older history at the next tick. Raising it restores nothing.

What a 30-day window means for the designs above. Several designs on this page assume a long-lived changelog, and the window caps each of them:

Each one reaches back only as far as the window. Anything that must outlive it needs its own durable record, such as a snapshot or a revision row, and must not rely on the changelog.

Webhook Integration

Expose changelog events as webhooks for integrations. A creator could set up a Discord webhook that posts whenever an editor modifies their character: "Alice updated Elara's system prompt."


Implementation Phases

Phase 1: Core Infrastructure

Phase 2: Activity Feed UI

Phase 3: Collaboration Integration

Phase 4: Revert and Advanced Features


Scope Summary

In scope Out of scope
Structured per-field change tracking Full entity snapshots / point-in-time reconstruction
Append-only event log Mutable edit history
All entity types (character, mode, lorebook, persona, package) Conversation messages (already have their own versioning)
Sub-entity changes (entries, greetings, sub-prompts) Binary content (images, avatars — tracked as URL changes only)
Human-readable activity feed Machine-readable API event stream (webhooks are a post-v1 extension)
Creator-facing UI Public-facing changelog (e.g., on shared content pages — possible extension)
Revert individual changes Branch/merge workflows

Acceptance Criteria — Retention (2026-10-02)

Retention is not done until every box below is verified ✅ against the running product. The rest of this page predates the Acceptance Criteria rule and has no checklist of its own.

User use cases — satisfiable + accessible (verify by driving the UI, not the code):

Behavior:

Invariants that must stay true:

Edges:

Acceptance Criteria — Who a row names (FX1, 2026-10-03)

user_id is "who made the change" (see the table above). Rows about lorebook entries, mode sub-prompts and character ↔ lorebook links used to be filed under the parent's owner whatever the edit, so a collaborator's edit carried the owner's name and outlived the collaborator's account. The fix: every writer names its editor in app.changelog_user_id, and every trigger resolves the actor through fn_changelog_actor. The named editor wins, and the owner is only the fallback.

Behavior:

Invariants that must stay true:

Edges: