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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(#1031): unify per-domain mutationEpoch into shared changeToken registry
Adam Eivy5154f912a6ae
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3b23164759..3ae9ccad7f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@- **Generated images & videos now have a PostgreSQL index** — every generated image and video is mirrored into a new `media_assets` table (one row per asset), so media metadata — prompt, model, dimensions, lineage, timestamps — becomes queryable from the database instead of only by scanning `data/images/*` sidecars and `data/video-history.json`. The bytes and those files stay exactly where they are and remain authoritative; the table is a *derived* index, rebuilt from disk on boot (and pruned of any asset whose file has been removed) and kept current as new media finishes rendering. Nothing about the gallery, history, or generation flows changes for you — this is the foundation (Phase 3.2 of the Postgres-first plan, #1000) that later lets media collections and catalog attachments resolve through one queryable asset index. The index is simply not maintained under the `MEMORY_BACKEND=file` dev/test escape hatch (media still serves from disk).- **Creative Director state now lives in PostgreSQL** — Creative Director projects (treatment, scenes, and run history) moved out of the single monolithic `data/creative-director-projects.json` file into a `creative_director_projects` table, one row per project. The orchestrator rewrote that whole file ≈10 times per scene render, so a long session turned every project list/read into an O(N²) reserialize; per-project rows remove that contention, and concurrent writes to the same project (render-progress + agent-run updates) are now serialized with a row lock so they can't lose each other's updates. Existing installs are migrated automatically and losslessly on first boot — the legacy file is kept (renamed `…json.imported`) as a recovery source. Behavior is unchanged; this is a storage move (Phase 3 of the Postgres-first plan, #997). The file backend remains reachable under the `MEMORY_BACKEND=file` dev/test escape hatch.- **PostgreSQL is now a required dependency** — file-based JSON storage is no longer offered as a normal setup choice. `npm run setup:db` presents only Docker and Native PostgreSQL hosting modes (and auto-selects native when a healthy local PostgreSQL is already reachable). On boot, PortOS now verifies the database is reachable with the required schema and refuses to start with an actionable message if it isn't — instead of silently falling back to file-backed memory and serving a half-broken install (the creative catalog has no file-backed equivalent). `MEMORY_BACKEND=file` survives only as an explicit, unsupported development/test escape hatch. New docs: [`docs/STORAGE.md`](../docs/STORAGE.md) (the storage-classification contract — `db-primary` / `file-primary` / `asset-file-db-indexed` / `ephemeral-file` — plus a "new data store?" review checklist) and [`docs/BACKUP.md`](../docs/BACKUP.md) (backup/restore now that the Postgres dump is required system state).+- **Federation change-token unified across DB-backed Create domains (#1031)** — the three PostgreSQL Create migrations above (#1014 universes, #1015 pipeline series/issues, #1016 Story Builder sessions) each added their own near-identical module-level `mutationEpoch` counter so the cross-machine snapshot loop knew when to re-send a snapshot for records that no longer touch their `data/<domain>/` directory. Those three counters are now consolidated into one shared, domain-keyed change-token registry (`server/services/changeToken.js`): each store bumps `bumpChangeToken('universe' | 'pipeline' | 'storyBuilder')` on record write/delete, and the sync loop reads `getChangeToken(domain)`. The fingerprint string format (`epoch:N`) is unchanged, so this is entirely internal and **federation-invisible** — no schema-version bump, no wire change, and peers sync exactly as before. Eliminated the separate per-domain counters in `universeBuilder/store.js`, `storyBuilderStore/store.js`, and `pipeline/syncEpoch.js` (the latter kept as a thin re-export over the shared registry). An unknown-domain typo now fails fast at bump/get so it can't silently desync a peer.- **Local model pickers now show what's actually installed** — the Fallback Model dropdown in the AI Provider editor and the provider/model selector in the manuscript editorial review previously only listed the models stored on the provider record, so models you'd pulled in Ollama later (e.g. Command R+, Gemma) never appeared. Both pickers now fold in the live list of installed Ollama / LM Studio models. Embedding-only models (e.g. `nomic-embed-text`) are filtered out of these generation pickers since they can't run a prompt.- **Editorial model recommendation** — the manuscript editorial review now suggests the best installed local model for editing/feedback (a one-tap "Recommended for editing" chip), ranking models that follow instructions tightly (Qwen/Llama/Gemma) ahead of chatty/RAG-tuned ones (Command R+) and skipping embedding/code/vision models. The pick is always among your *installed* models, so it auto-adapts as you pull newer versions.- **Model context windows are now visible** — each model card on Settings → Local LLM shows its native context length (e.g. "32K ctx"), and the provider/model selector dropdowns (AI Provider editor, manuscript editorial review) annotate each local model with its window as a parenthetical.diff --git a/server/services/changeToken.js b/server/services/changeToken.jsnew file mode 100644index 0000000000..930a28d7d9--- /dev/null+++ b/server/services/changeToken.js@@ -0,0 +1,48 @@+/**+ * Change-token registry — the shared dataSync federation-invisibility signal (#1031).+ *+ * The dataSync snapshot loop fingerprints `data/<domain>/` directories to decide+ * WHEN to re-send a snapshot to peers. DB-backed Create domains (universes #1014,+ * pipeline series/issues #1015, story-builder sessions #1016) no longer touch+ * those directories on a record write/delete, so the dir fingerprint alone would+ * go stale and peers would silently stop receiving edits.+ *+ * Each migrated domain previously rolled its own module-level `mutationEpoch`+ * counter (three near-identical copies). This module consolidates them into ONE+ * domain-keyed monotonic counter map: a store bumps `bumpChangeToken(domain)` on+ * every record write/delete, and dataSync folds `getChangeToken(domain)` into the+ * domain's fingerprint via its existing sentinel key. The fingerprint string+ * format (`epoch:N`) is unchanged, so this stays byte-identical on the wire —+ * federation-invisible, no schema-version bump.+ *+ * Module-level (singleton) Map so dataSync reads ONE monotonic counter per domain+ * regardless of how many times a store facade is rebuilt (test PATHS.data swaps+ * recreate facades but must not reset the counter). Unknown domains fail-fast on+ * bump/get so a typo can't silently desync a peer.+ */++/** Known change-token domains — callers must pass one of these (no arbitrary strings). */+export const CHANGE_TOKEN_DOMAINS = Object.freeze(['universe', 'pipeline', 'storyBuilder']);++const DOMAIN_SET = new Set(CHANGE_TOKEN_DOMAINS);++// Singleton: one monotonic counter per domain. Survives facade rebuilds.+const counters = new Map();++function assertDomain(domain) {+ if (!DOMAIN_SET.has(domain)) {+ throw new Error(`changeToken: unknown domain "${domain}" — must be one of ${CHANGE_TOKEN_DOMAINS.join(', ')}`);+ }+}++/** Increment the domain's change token — call on every record write/delete. */+export function bumpChangeToken(domain) {+ assertDomain(domain);+ counters.set(domain, (counters.get(domain) || 0) + 1);+}++/** Read the domain's current change token (0 if never bumped). */+export function getChangeToken(domain) {+ assertDomain(domain);+ return counters.get(domain) || 0;+}diff --git a/server/services/changeToken.test.js b/server/services/changeToken.test.jsnew file mode 100644index 0000000000..befab71df7--- /dev/null+++ b/server/services/changeToken.test.js@@ -0,0 +1,47 @@+import { describe, it, expect } from 'vitest';+import {+ CHANGE_TOKEN_DOMAINS,+ bumpChangeToken,+ getChangeToken,+} from './changeToken.js';++describe('changeToken registry', () => {+ it('exposes the known domains', () => {+ expect(CHANGE_TOKEN_DOMAINS).toEqual(['universe', 'pipeline', 'storyBuilder']);+ });++ it('starts at 0 for an un-bumped domain', () => {+ // storyBuilder is not bumped by any other case in this file+ expect(getChangeToken('storyBuilder')).toBe(0);+ });++ it('bump increments the domain counter monotonically', () => {+ const before = getChangeToken('universe');+ bumpChangeToken('universe');+ expect(getChangeToken('universe')).toBe(before + 1);+ bumpChangeToken('universe');+ expect(getChangeToken('universe')).toBe(before + 2);+ });++ it('reads do not bump', () => {+ const a = getChangeToken('pipeline');+ const b = getChangeToken('pipeline');+ expect(a).toBe(b);+ });++ it('keeps per-domain counters independent', () => {+ const pipeBefore = getChangeToken('pipeline');+ const uniBefore = getChangeToken('universe');+ bumpChangeToken('pipeline');+ expect(getChangeToken('pipeline')).toBe(pipeBefore + 1);+ expect(getChangeToken('universe')).toBe(uniBefore); // untouched+ });++ it('fails fast on an unknown domain at bump', () => {+ expect(() => bumpChangeToken('bogus')).toThrow(/unknown domain "bogus"/);+ });++ it('fails fast on an unknown domain at get', () => {+ expect(() => getChangeToken('bogus')).toThrow(/unknown domain "bogus"/);+ });+});diff --git a/server/services/pipeline/syncEpoch.js b/server/services/pipeline/syncEpoch.jsindex 5f543b0619..8c8d116e38 100644--- a/server/services/pipeline/syncEpoch.js+++ b/server/services/pipeline/syncEpoch.js@@ -1,6 +1,7 @@/*** Pipeline mutation epoch — the dataSync federation-invisibility signal (#1015).*+ * Thin wrappers over the shared change-token registry (../changeToken.js, #1031).* Pipeline series + issues used to live in per-record dirs under* data/pipeline-series/{id} and data/pipeline-issues/{id}. dataSync's `pipeline`* snapshot-cache fingerprint stats those directories to decide WHEN to re-send@@ -9,29 +10,28 @@* those directories — without help, the dir fingerprint would never invalidate* and peers would silently stop receiving pipeline edits.*- * The fix mirrors the universe store's mutation epoch (#1014): a single- * module-level monotonic counter bumped on every series/issue record- * write/delete. dataSync folds it into the `pipeline` fingerprint (and the- * `mediaCollections` fingerprint, which filters collections by their linked- * series' ephemeral state) via a sentinel key, so the checksum cache invalidates- * on a DB edit just as it did on a file edit. Under the file backend the dirs- * still change too (harmless double-signal).+ * The fix folds a single monotonic counter — bumped on every series/issue record+ * write/delete — into the `pipeline` fingerprint (and the `mediaCollections`+ * fingerprint, which filters collections by their linked series' ephemeral state)+ * via a sentinel key, so the checksum cache invalidates on a DB edit just as it+ * did on a file edit. Under the file backend the dirs still change too (harmless+ * double-signal).*- * Module-level (not per-facade) so dataSync reads ONE monotonic counter- * regardless of how many times the series/issues facades are rebuilt (test- * PATHS.data swaps). Series AND issues share the one counter because dataSync's- * `pipeline` category covers both record kinds together — any pipeline mutation- * must invalidate that one checksum.+ * Series AND issues share the one counter because dataSync's `pipeline` category+ * covers both record kinds together — any pipeline mutation must invalidate that+ * one checksum. The shared registry is module-level (a domain-keyed singleton) so+ * dataSync reads ONE monotonic counter regardless of how many times the+ * series/issues facades are rebuilt (test PATHS.data swaps).*/-let pipelineEpoch = 0;+import { bumpChangeToken, getChangeToken } from '../changeToken.js';/** Current pipeline mutation epoch — folded into dataSync's fingerprint. */export function getPipelineMutationEpoch() {- return pipelineEpoch;+ return getChangeToken('pipeline');}/** Bump the epoch — called by the series/issues stores on every record write/delete. */export function bumpPipelineMutationEpoch() {- pipelineEpoch += 1;+ bumpChangeToken('pipeline');}diff --git a/server/services/storyBuilderStore/store.js b/server/services/storyBuilderStore/store.jsindex 72be1d55e7..839ae25e0a 100644--- a/server/services/storyBuilderStore/store.js+++ b/server/services/storyBuilderStore/store.js@@ -31,6 +31,7 @@ import { join } from 'path';import { PATHS } from '../../lib/fileUtils.js';import { createCollectionStore } from '../../lib/collectionStore.js';import { checkHealth, ensureSchema } from '../../lib/db.js';+import { bumpChangeToken, getChangeToken } from '../changeToken.js';// TYPE-level (storage layout) schema version stamped on the file backend's// data/story-builder/index.json — preserved so an install on the file escape@@ -48,14 +49,14 @@ function assertValidId(id) {}}-// --- Mutation epoch (the dataSync federation-invisibility fix) ----// Module-level so dataSync reads ONE monotonic counter regardless of how many-// times the facade is rebuilt (test PATHS.data swaps). Bumped on every record-// write/delete.-let mutationEpoch = 0;+// --- Mutation epoch (the dataSync federation-invisibility fix, #1031) ---+// Backed by the shared change-token registry (../changeToken.js) — a single+// domain-keyed monotonic counter that survives facade rebuilds (test PATHS.data+// swaps). Bumped on every record write/delete. Thin wrapper kept so call sites /+// tests don't all rewire./** Current Story Builder mutation epoch — folded into dataSync's fingerprint. */export function getStoryBuilderMutationEpoch() {- return mutationEpoch;+ return getChangeToken('storyBuilder');}// --- File backend (escape hatch / tests): wraps collectionStore ---@@ -152,14 +153,14 @@ function createFacade({ dir, sanitizeRecord }) {const saveOneNow = async (id, record) => {assertValidId(id);const out = await (await getBackend()).writeRaw(id, record);- mutationEpoch += 1;+ bumpChangeToken('storyBuilder');return out ?? record;};const deleteOneNow = async (id) => {assertValidId(id);await (await getBackend()).deleteRaw(id);- mutationEpoch += 1;+ bumpChangeToken('storyBuilder');};return {diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.jsindex d84140462b..3d7cf44373 100644--- a/server/services/universeBuilder/store.js+++ b/server/services/universeBuilder/store.js@@ -32,6 +32,7 @@ import { join } from 'path';import { PATHS } from '../../lib/fileUtils.js';import { createCollectionStore } from '../../lib/collectionStore.js';import { checkHealth, ensureSchema } from '../../lib/db.js';+import { bumpChangeToken, getChangeToken } from '../changeToken.js';// TYPE-level (storage layout) schema version stamped on the file backend's// data/universes/index.json — preserved so an install on the file escape hatch@@ -60,14 +61,14 @@ function assertValidId(id) {}}-// --- Mutation epoch (the dataSync federation-invisibility fix) ----// Module-level so dataSync reads ONE monotonic counter regardless of how many-// times the facade is rebuilt (test PATHS.data swaps). Bumped on every record-// write/delete (NOT run writes — those are local-only).-let mutationEpoch = 0;+// --- Mutation epoch (the dataSync federation-invisibility fix, #1031) ---+// Backed by the shared change-token registry (../changeToken.js) — a single+// domain-keyed monotonic counter that survives facade rebuilds (test PATHS.data+// swaps). Bumped on every record write/delete (NOT run writes — those are+// local-only). Thin wrapper kept so call sites / tests don't all rewire./** Current universe mutation epoch — folded into dataSync's fingerprint. */export function getUniverseMutationEpoch() {- return mutationEpoch;+ return getChangeToken('universe');}// --- File backend (escape hatch / tests): wraps collectionStore ---@@ -225,13 +226,13 @@ function createFacade({ dir, sanitizeRecord }) {writeRecord: async (id, record) => {assertValidId(id); // parity with collectionStore.saveOneNow — reject bad ids on BOTH backendsconst out = await (await getBackend()).writeRaw(id, record);- mutationEpoch += 1;+ bumpChangeToken('universe');return out ?? record;},deleteRecord: async (id) => {assertValidId(id); // parity with collectionStore.deleteOneNowawait (await getBackend()).deleteRaw(id);- mutationEpoch += 1;+ bumpChangeToken('universe');},// Render-history runs (local-only — no epoch bump)