Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: erase deleted Tribe people and their audit snapshots after 30 days (#8459)

[._.]/ Adam Eivy9fc5e36c051f
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5b374298d0..0d5560ea49 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -44,7 +44,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `sync_feed` — the commit-ordered federation change feed (#8315) behind the `memories` and catalog-table peer pulls: one row per live row version, `(stream = table name, row_sequence = that row's sync_sequence) → position`. A position is drawn at COMMIT by deferred constraint triggers serialized on one transaction-scoped advisory lock, so a transaction that commits late can never land below a cursor a peer already advanced past (the write-time `sync_sequence` could). Peers page by position; positions start at 1e15, so a pre-feed cursor replays each stream once after an upgrade (apply is LWW / ON CONFLICT, so nothing is duplicated). Machine-local bookkeeping — only the rows it points at federate. DDL: `server/lib/db/schema/syncFeed.js` + `init-db.sql`; existing rows are backfilled by db-migration `009-commit-ordered-sync-feed.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`. **One universe ships with the product:** `universe-reality` ("Reality"), seeded by `scripts/migrations/395-reality-universe-seed.js` — not by `data.reference/`, because universes are PG rows and `setup-data.js` only copies files. It carries the federated `factual: true` flag (#7616), which marks a world whose people and places are real so the catalog extractor reads captured text as lived record rather than invented story; `factual` is persisted ONLY when true, so every fiction universe keeps its exact on-disk shape and wire checksum, and `PORTOS_SCHEMA_VERSIONS.universes` is 12 so a `factual`-unaware peer cannot strip-then-LWW the flag away. The migration gates on the ABSENCE of any row with that id — tombstone included — so a Reality the user deleted is never resurrected by an upgrade.
- `voice_profiles` / `voice_profile_renders` — machine-local DB-primary records for approved `(universeId, characterId)` bindings and the latest rendered dialogue line per `(issueId, lineId)`. They store the promoted Kokoro/Piper preset, profile revision, route availability, benchmark provenance, and reproducible dialogue delivery details (engine/model revision, timing, controls, and mastering). The portable Universe character and federated pipeline issue keep only portable voice data and audio filenames; they never store a local profile id. Rendered benchmark WAVs, safe-basename source-asset metadata, and future local engine artifacts live under `data/voice-profiles/<profileId>/`. Both the PostgreSQL dump and that managed directory are included in normal backup, while peer sync intentionally carries neither. Adapter: `server/services/voice/profiles.js`.
-- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
+- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. **Deletes are erased after 30 days** (#8459): deleting a person is a soft delete (a recovery window only — the tombstone is never needed for sync), and the daily `tribePurge` sweep (`server/services/tribePurge.js` → `tribe.purgeDeletedPeople`) hard-deletes people tombstoned more than `DELETED_PERSON_RETENTION_DAYS` ago — cascading to their touchpoints, identities and memory links — and removes every `record_audit` snapshot of them. The same sweep expires all `tribe_*` `record_audit` rows older than the window, since those snapshots copy a third party's contact details and notes; creative-table audit rows are never touched. Adapter: `server/services/tribe.js`.
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 9e92bed739..b27ee68035 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -114,6 +114,7 @@ import { startImageRefsGc } from './imageRefsGc.js';
import { startImageCleanTmpGc } from './imageCleanTmpGc.js';
import { startOrphanedPartialGc } from './orphanedPartialGc.js';
import { startBeeperAttachmentGc } from './beeperAttachmentGc.js';
+import { startTribePurge } from './tribePurge.js';
import { initBridge as initBrainMemoryBridge } from './brainMemoryBridge.js';
import { initDrillCache } from './meatspacePostDrillCache.js';
import { registerPostReminderSchedule } from './meatspacePostReminder.js';
@@ -564,6 +565,10 @@ const startBackgroundServices = ({ spawnerReady, io }) => {
// bytes, so it is NOT gated on the ingestion toggle: turning scheduled sync
// off does not make an over-budget mirror stop being over budget.
startBeeperAttachmentGc();
+ // Erase Tribe people deleted more than 30 days ago — with their touchpoints,
+ // identities, memory links and audit snapshots — and expire older tribe audit
+ // snapshots (#8459). Deleting a contact must eventually erase a third party's data.
+ startTribePurge();
// Warm the catalog user-type registry from the user-type store (Postgres as of
// #1001; the settings.json slice under the escape hatch) before any catalog
// request can land, so user-defined types validate + mint ids immediately on
diff --git a/server/services/tribe.js b/server/services/tribe.js
index c5de5be044..6783daa98c 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -373,6 +373,17 @@ export async function updatePerson(id, updates) {
return result.rows[0] ? rowToPerson(result.rows[0]) : null;
}
+// Days a deleted person stays recoverable before `purgeDeletedPeople` erases
+// them for good. It is also the retention for the `record_audit` snapshots of
+// the tribe tables: a third party's contact details and conversation summaries
+// must not outlive the user's delete, and the audit log copies the full row
+// (#8459).
+export const DELETED_PERSON_RETENTION_DAYS = 30;
+const TRIBE_AUDITED_TABLES = ['tribe_people', 'tribe_touchpoints', 'tribe_identities'];
+
+// Soft delete. The row keeps every field until `purgeDeletedPeople` hard-deletes
+// it DELETED_PERSON_RETENTION_DAYS later. Tribe is machine-local, so the
+// tombstone is never needed for sync — it is only a short recovery window.
export async function deletePerson(id) {
await ensureReady();
const result = await query(
@@ -385,6 +396,54 @@ export async function deletePerson(id) {
return result.rowCount > 0;
}
+/**
+ * Erase people deleted more than `olderThanDays` ago, and expire the tribe
+ * tables' `record_audit` snapshots on the same window (#8459).
+ *
+ * The hard delete cascades to touchpoints, identities and memory links, and
+ * sets `beeper_participants.tribe_person_id` to NULL. The audit trigger writes a
+ * `hard_delete` snapshot for every row the cascade removes; those are erased in
+ * the same transaction, together with the person's earlier tombstone snapshot.
+ * Audit rows for the creative tables are never touched — there the log is the
+ * data-loss recovery source.
+ *
+ * Returns counts only, so callers can log without naming anyone.
+ */
+export async function purgeDeletedPeople({ olderThanDays = DELETED_PERSON_RETENTION_DAYS } = {}) {
+ if (!Number.isInteger(olderThanDays) || olderThanDays < 0) {
+ throw new ServerError('olderThanDays must be a non-negative integer', { status: 400, code: 'BAD_REQUEST' });
+ }
+ await ensureReady();
+ return withTransaction(async (client) => {
+ const purged = await client.query(
+ `DELETE FROM tribe_people
+ WHERE deleted = TRUE AND deleted_at < NOW() - make_interval(days => $1::int)
+ RETURNING id`,
+ [olderThanDays],
+ );
+ const ids = purged.rows.map((row) => String(row.id));
+ let auditRows = 0;
+ if (ids.length > 0) {
+ const snapshots = await client.query(
+ `DELETE FROM record_audit
+ WHERE (table_name = 'tribe_people' AND record_id = ANY($1::text[]))
+ OR (table_name IN ('tribe_touchpoints', 'tribe_identities')
+ AND row_snapshot->>'person_id' = ANY($1::text[]))`,
+ [ids],
+ );
+ auditRows += snapshots.rowCount;
+ }
+ const expired = await client.query(
+ `DELETE FROM record_audit
+ WHERE table_name = ANY($1::text[])
+ AND occurred_at < NOW() - make_interval(days => $2::int)`,
+ [TRIBE_AUDITED_TABLES, olderThanDays],
+ );
+ auditRows += expired.rowCount;
+ return { people: ids.length, auditRows };
+ });
+}
+
export async function listTouchpoints(personId, limit = 50) {
await ensureReady();
const result = await query(
diff --git a/server/services/tribePurge.db.test.js b/server/services/tribePurge.db.test.js
new file mode 100644
index 0000000000..53850ffd99
--- /dev/null
+++ b/server/services/tribePurge.db.test.js
@@ -0,0 +1,156 @@
+/**
+ * Postgres-backed proof that deleting a Tribe person eventually erases them
+ * (#8459): the real FK cascade, the real `record_audit` trigger (which writes a
+ * snapshot for every cascaded row mid-transaction), and the retention window.
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`
+ * (registered in vitest.config.db.js). Every assertion is scoped to this run's
+ * own ids so concurrent suites sharing the test DB are unaffected. Fixtures use
+ * placeholder names and handles only.
+ */
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import * as tribe from './tribe.js';
+import * as tribeIdentities from './tribeIdentities.js';
+import { runTribePurge } from './tribePurge.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ dbReady = true;
+ }
+}
+const runDb = requireDbOrSkip('services/tribePurge.db.test', dbReady, skipReason);
+
+const nonce = `tribepurge-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+const createdPersonIds = [];
+const createdMemoryIds = [];
+const creativeAuditIds = [];
+
+afterAll(async () => {
+ if (!dbReady) return;
+ if (createdPersonIds.length) {
+ await query('DELETE FROM tribe_people WHERE id = ANY($1::uuid[])', [createdPersonIds]).catch(() => {});
+ await query(
+ `DELETE FROM record_audit
+ WHERE (table_name = 'tribe_people' AND record_id = ANY($1::text[]))
+ OR (table_name IN ('tribe_touchpoints', 'tribe_identities') AND row_snapshot->>'person_id' = ANY($1::text[]))`,
+ [createdPersonIds],
+ ).catch(() => {});
+ }
+ if (createdMemoryIds.length) {
+ await query('DELETE FROM memories WHERE id = ANY($1::uuid[])', [createdMemoryIds]).catch(() => {});
+ }
+ if (creativeAuditIds.length) {
+ await query('DELETE FROM record_audit WHERE id = ANY($1::bigint[])', [creativeAuditIds]).catch(() => {});
+ }
+ await close();
+});
+
+// A person with one of everything the purge must erase: a touchpoint (whose
+// summary is conversation content), an identity (a handle), and a memory link.
+async function makePersonWithHistory(label) {
+ const person = await tribe.createPerson({
+ name: `Example Person ${label}`,
+ emails: [`${label}-${nonce}@example.com`],
+ phones: ['+15550100000'],
+ notes: 'Example private note',
+ });
+ createdPersonIds.push(person.id);
+ const touchpoint = await tribe.createTouchpoint(person.id, { channel: 'call', summary: 'Example conversation summary' });
+ const identity = await tribeIdentities.linkIdentity({
+ personId: person.id, kind: 'email', handle: `handle-${label}-${nonce}@example.com`,
+ });
+ const { rows } = await query(
+ `INSERT INTO memories (type, content) VALUES ('observation', $1) RETURNING id`,
+ [`Example memory ${nonce}`],
+ );
+ createdMemoryIds.push(rows[0].id);
+ await tribe.linkMemory(person.id, rows[0].id, 'example link');
+ return { personId: person.id, touchpointId: touchpoint.id, identityId: identity.id, memoryId: rows[0].id };
+}
+
+async function deleteAndBackdate(personId, days) {
+ expect(await tribe.deletePerson(personId)).toBe(true);
+ await query(
+ `UPDATE tribe_people SET deleted_at = NOW() - make_interval(days => $2::int) WHERE id = $1`,
+ [personId, days],
+ );
+}
+
+const count = async (sql, params) => Number((await query(sql, params)).rows[0].n);
+
+const personRows = (fx) => Promise.all([
+ count('SELECT COUNT(*) AS n FROM tribe_people WHERE id = $1', [fx.personId]),
+ count('SELECT COUNT(*) AS n FROM tribe_touchpoints WHERE id = $1', [fx.touchpointId]),
+ count('SELECT COUNT(*) AS n FROM tribe_identities WHERE id = $1', [fx.identityId]),
+ count('SELECT COUNT(*) AS n FROM tribe_memory_links WHERE person_id = $1', [fx.personId]),
+]);
+
+const personAuditRows = (personId) => count(
+ `SELECT COUNT(*) AS n FROM record_audit
+ WHERE (table_name = 'tribe_people' AND record_id = $1)
+ OR (table_name IN ('tribe_touchpoints', 'tribe_identities') AND row_snapshot->>'person_id' = $1)`,
+ [personId],
+);
+
+describe.skipIf(!runDb)('Tribe erasure sweep (#8459)', () => {
+ it('erases people past the window with their history and snapshots, keeps recent deletes, and leaves creative audit rows alone', async () => {
+ const expired = await makePersonWithHistory('expired');
+ const recent = await makePersonWithHistory('recent');
+ await deleteAndBackdate(expired.personId, 31);
+ await deleteAndBackdate(recent.personId, 5);
+
+ // A creative-table snapshot older than the window must survive: there the
+ // audit log is the data-loss recovery source.
+ const { rows: creative } = await query(
+ `INSERT INTO record_audit (table_name, record_id, record_name, action, row_snapshot, occurred_at)
+ VALUES ('universes', $1, 'Example Universe', 'tombstone', '{}'::jsonb, NOW() - INTERVAL '90 days')
+ RETURNING id`,
+ [`universe-${nonce}`],
+ );
+ creativeAuditIds.push(creative[0].id);
+
+ // A tribe snapshot older than the window for a person who still exists
+ // (restored after an earlier delete) expires on retention alone.
+ const { rows: staleTribe } = await query(
+ `INSERT INTO record_audit (table_name, record_id, record_name, action, row_snapshot, occurred_at)
+ VALUES ('tribe_people', $1, 'Example Person stale', 'untombstone', '{}'::jsonb, NOW() - INTERVAL '45 days')
+ RETURNING id`,
+ [`stale-${nonce}`],
+ );
+
+ expect(await personAuditRows(expired.personId)).toBeGreaterThan(0);
+
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ await runTribePurge();
+ const lines = log.mock.calls.map((args) => args.join(' ')).filter((line) => line.includes('Tribe purge'));
+ log.mockRestore();
+
+ // Expired person: every row and every audit snapshot is gone, including
+ // the hard_delete snapshots the cascade wrote during the purge itself.
+ expect(await personRows(expired)).toEqual([0, 0, 0, 0]);
+ expect(await personAuditRows(expired.personId)).toBe(0);
+
+ // Recently deleted person: untouched, including their tombstone snapshot.
+ expect(await personRows(recent)).toEqual([1, 1, 1, 1]);
+ expect(await count(
+ `SELECT COUNT(*) AS n FROM record_audit WHERE table_name = 'tribe_people' AND record_id = $1 AND action = 'tombstone'`,
+ [recent.personId],
+ )).toBe(1);
+
+ expect(await count('SELECT COUNT(*) AS n FROM record_audit WHERE id = $1', [creative[0].id])).toBe(1);
+ expect(await count('SELECT COUNT(*) AS n FROM record_audit WHERE id = $1', [staleTribe[0].id])).toBe(0);
+
+ // The log line carries counts only — no name, email or handle.
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatch(/erased \d+ deleted people, \d+ audit snapshots/);
+ expect(lines[0]).not.toMatch(/Example|example\.com|\+1555/);
+ });
+});
diff --git a/server/services/tribePurge.js b/server/services/tribePurge.js
new file mode 100644
index 0000000000..4d83e1f5c4
--- /dev/null
+++ b/server/services/tribePurge.js
@@ -0,0 +1,40 @@
+/**
+ * Scheduler registration for the Tribe erasure sweep (#8459).
+ *
+ * Deleting a Tribe person is a soft delete; this daily sweep turns it into a
+ * real erasure once the recovery window has passed — the person, their
+ * touchpoints, identities and memory links, and every `record_audit` snapshot
+ * of them. The same pass expires older tribe audit snapshots. The work itself
+ * lives in `tribe.purgeDeletedPeople`.
+ *
+ * The handler owns its rejections: a sweep runs outside the request lifecycle,
+ * where an escaping rejection takes the process down (root AGENTS.md). The log
+ * line carries counts only — never a name or handle.
+ */
+
+import { createSweepScheduler } from './sweepScheduler.js';
+import { purgeDeletedPeople } from './tribe.js';
+
+const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000;
+const INITIAL_DELAY_MS = 15 * 60 * 1000;
+
+export const runTribePurge = async () => {
+ const result = await purgeDeletedPeople().catch((err) => {
+ console.error(`❌ Tribe purge failed: ${err.message}`);
+ return null;
+ });
+ if (result && (result.people > 0 || result.auditRows > 0)) {
+ console.log(`🧹 Tribe purge: erased ${result.people} deleted people, ${result.auditRows} audit snapshots`);
+ }
+};
+
+export const {
+ start: startTribePurge,
+ stop: stopTribePurge,
+} = createSweepScheduler({
+ id: 'tribe-purge',
+ intervalMs: SWEEP_INTERVAL_MS,
+ initialDelayMs: INITIAL_DELAY_MS,
+ handler: runTribePurge,
+ source: 'tribePurge',
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 1aa27b53dc..d9a6e398f7 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -40,6 +40,7 @@ export const DB_TEST_INCLUDE = [
'lib/db/schema/beeper.db.test.js',
'services/beeperConversations.db.test.js',
'services/beeperTribe.db.test.js',
+ 'services/tribePurge.db.test.js',
'services/beeperSync.db.test.js',
'services/creativeDirector/projectsDB.test.js',
'services/musicVideo/projectsDB.test.js',