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
federate author personas across peers via per-record peer-sync
[._.]/ Adam Eivyda1003cac265
diff --git a/PLAN.md b/PLAN.mdindex d8e0c778db..776b9140c0 100644--- a/PLAN.md+++ b/PLAN.md@@ -28,7 +28,9 @@ independently.- [ ] [ref-watch-phosphene-i2v-snap-dims-to-source-aspect] **Auto-snap I2V default width×height to the uploaded source image's aspect ratio.** From `reference-watch` review of Phosphene (commit `0b98a5bd`, 2026-06-12). Upstream keeps custom W×H inputs editable for image flows but auto-snaps the *default* dimensions to the uploaded image via `snapAspectToImage()`, because the common case can't cover-crop a 16:9 photo into a 9:16 frame without losing content. PortOS already exposes editable W×H plus presets, but on I2V it ffmpeg cover-crops the source to the chosen size (`server/services/videoGen/local.js#resizeImage()` uses `force_original_aspect_ratio=increase,crop`), so a mismatched preset silently crops away the subject. Fix: when a source/keyframe image is selected in `client/src/pages/VideoGen.jsx`, read its natural dimensions and snap the width/height fields to the nearest 64-aligned preset that matches the image's aspect ratio (only when the user hasn't manually overridden), leaving the inputs editable for power users; keep the existing server-side 64-grid clamp. Estimated scope: small.-- [ ] [authors-federation-sync-category] **Federate the `authors` table as a dataSync category (like universes).** Author personas (`server/services/authors/`, `authors` table) shipped `db-primary` but LOCAL-ONLY — a series carries `authorId` (FK) + a denormalized `author` byline so a federated peer renders the cover correctly without the author record, but the persona itself (writing style, bio, headshot description/style) does NOT sync, so a user's other federated machines don't see their authors. Make authors a first-class sync category mirroring the universe pattern: add an `author` case to `server/lib/syncWire.js` (`sanitizeRecordForWire` + `sanitizeStateForWire`), register `getAuthorSnapshot`/`applyAuthorRemote` + a `mergeAuthorsFromSync` merge entry in `server/services/dataSync.js`, give the table soft-delete tombstones on the wire (already has `deleted`/`deleted_at` columns) + a mutation-epoch fingerprint (`server/services/changeToken.js`) so a PG-backed edit invalidates the snapshot cache, wire the per-record push path + auto-subscribe (`server/services/sharing/recordEvents.js`) the way `createSeries` does, and mind the test peer-fan-out mocks (`mockNoPeers`/`mockNoPeerSync`). Additive field on series (`authorId`) already crosses the wire via the series passthrough; no series schema-version bump needed. Estimated scope: medium-large (federation surface + checksum-stability + tests). Deferred from the Authors-management PR as genuinely-large work needing its own PR.+- [x] [authors-federation-sync-category] **Federate the `authors` table across peers.** SHIPPED via the **per-record peer-push** path (mirroring `mediaCollection`) rather than the 60s dataSync snapshot-category route originally sketched here — authors are low-churn standalone records with no `ephemeral` concept, so per-record push + auto-subscribe-on-create + backfill-on-toggle/peer:online converges them without the snapshot checksum-stability machinery. Delivered: `author` case in `server/lib/syncWire.js`; `authors:1` wire version + `RECORD_KIND_SCHEMA_CATEGORIES.author` in `schemaVersions.js`; `mergeAuthorsFromSync`/`pruneTombstonedAuthors`/`listAuthorIds`/`getAuthor({includeDeleted})` across `authors/{logic,db,file,index}.js` (shared `mergeAuthorRecord` LWW decision so both backends can't drift); recordEvents emit + `autoSubscribeRecordToAllPeers` on create/update/delete via the dispatcher; `author` branches in `peerSync.js` (push payload with headshot asset manifest, merge dispatch, relevantCategories gate, classifyLocalRecord, backfill lister, integrity manifest); conflict-journal `RESTORABLE_FIELDS.author` + base-hash seeding; `authors` sync category in `instances.js` defaults + `routes/instances.js` validation + `Instances.jsx` toggle (non-snapshot, like catalog); tombstone-GC author cutoff/prune/refused; `authors/db.test.js` data-safety round-trip (snapshot/restore + test-DB gate) + merge/prune tests, `logic.test.js` merge/headshot tests, `syncWire.test.js` author case.++- [ ] [authors-headshot-upload-asset-sync] **Make uploaded (non-gallery) author headshots transfer their bytes to peers.** The authors federation (above) syncs the headshot IMAGE BYTES only when `headshotImageUrl` points at `/data/images/<f>` (gallery-picked) — `headshotImageFilename()` in `authors/logic.js` maps that to an `image` asset the peer-sync pull worker fetches. But the Authors page's *upload* button (`client/src/pages/Authors.jsx` → `POST /api/uploads`) stores the file in `data/uploads/` and sets `headshotImageUrl = /api/uploads/<f>`, which is NOT one of the three pullable asset kinds (`image`→`/data/images`, `image-ref`, `video`), so on a peer the author record syncs but the headshot 404s. Two options: (a) route author-headshot uploads through the gallery (`/data/images/`) so they ride the existing `image` pull path (smaller change, recommended), or (b) add an `upload`/`/data/uploads` pullable asset kind end-to-end — new `ASSET_KIND_TO_URL_PREFIX` entry + `directoryForAssetKind` + `PATHS.uploads` + the `peerAssetManifestEntrySchema` kind enum in `peerSyncValidation.js`. External `http(s)`/`data:` URLs intentionally never transfer (the receiver resolves them itself). Estimated scope: small (a) / medium (b).### Trigger-gated (waiting for a precondition)diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 035e53155d..74b2b530b2 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -7,7 +7,7 @@ import {Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, Timer,Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,- Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -492,11 +492,15 @@ const SYNC_CATEGORY_META = [{ key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },{ key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },{ key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },+ { key: 'authors', label: 'Authors', icon: FilePen, description: 'Author personas + headshots used as series bylines (PostgreSQL)' },{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }];-// Snapshot categories (excludes delta-based brain/memory/catalog)-const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => m.key !== 'brain' && m.key !== 'memory' && m.key !== 'catalog');+// Snapshot categories — exclude the per-record / delta-based categories that+// have no 60s snapshot checksum: brain + memory (delta), catalog + authors+// (PostgreSQL, per-record peer-push only — no snapshot loop).+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors']);+const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));function SyncCategoriesPanel({ peer, onRefresh }) {const [expanded, setExpanded] = useState(false);diff --git a/server/lib/README.md b/server/lib/README.mdindex 9fe77a0927..9f11f1958d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -215,6 +215,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |+| `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). || `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex ac5af03301..0e380cef5a 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -298,6 +298,12 @@ export const RESTORABLE_FIELDS = Object.freeze({// are structural links managed by the link/unlink helpers, not `updateCollection`// patches — so they're hashed for DETECTION but not offered for restore.mediaCollection: ['name', 'description', 'coverKey'],+ // Author personas: all user-authored text scalars are restorable. `id`, the+ // LWW/tombstone trio, and `createdAt` are server-owned/structural. Mirrors the+ // PATCHABLE field set in services/authors/logic.js. The author wire form is+ // LWW-overwritten whole (no field-union like mediaCollection's items), so it+ // is hashed in full by contentHashForRecord — no scalar-narrowing branch.+ author: ['name', 'writingStyle', 'bio', 'physicalDescription', 'headshotStyle', 'headshotImageUrl'],// Issue: the user-authored content the merge can restore. `stages` carries// the bulk of the work (prose, comic pages, render metadata). Server-owned /// structural fields are excluded deliberately — `number` is renumber-managed,diff --git a/server/lib/index.js b/server/lib/index.jsindex 6c25c85302..2cfc04b588 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -182,6 +182,7 @@ export * from './authGate.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './errorHandler.js';+export * from './lwwTimestamp.js';export * from './mapWithConcurrency.js';export * from './objects.js';export * from './openapiSpec.js';diff --git a/server/lib/lwwTimestamp.js b/server/lib/lwwTimestamp.jsnew file mode 100644index 0000000000..c7604801dd--- /dev/null+++ b/server/lib/lwwTimestamp.js@@ -0,0 +1,49 @@+/**+ * Last-writer-wins (LWW) timestamp comparison for cross-instance sync merges.+ *+ * Every per-record merge path (`mergeMediaCollectionsFromSync`,+ * `mergeAuthorsFromSync`, …) decides which side wins by comparing `updatedAt` /+ * `addedAt` strings. The sanitizers accept ANY `Date.parse`-able string (not+ * strictly ISO-8601), so the compare MUST parse to epoch ms — a lexicographic+ * string compare would mis-order two parseable-but-different-format timestamps.+ * These helpers are the single source of that rule so the polarity can't drift+ * between record kinds.+ */++/** Parse a timestamp string to epoch ms, or null when unparseable. */+export function parseTsMs(s) {+ const n = typeof s === 'string' ? Date.parse(s) : NaN;+ return Number.isFinite(n) ? n : null;+}++/**+ * "Newer wins": true iff `candidate` is STRICTLY newer than `incumbent`.+ * Unparseable `candidate` never overrides; an unparseable `incumbent` loses to a+ * valid candidate; a tie (or both unparseable) breaks to the incumbent (local).+ * Used to decide whether a remote record overwrites the local copy.+ */+export function compareNewerWins(candidate, incumbent) {+ const cMs = parseTsMs(candidate);+ const iMs = parseTsMs(incumbent);+ if (cMs === null) return false; // candidate unparseable → never overrides+ if (iMs === null) return true; // incumbent unparseable, candidate valid → take valid+ return cMs > iMs;+}++/**+ * "Earliest wins" tiebreak for two records of the same key: returns -1 if `a` is+ * earlier (a wins), 1 if `b` is earlier, 0 on tie. Unparseable side LOSES — a+ * corrupted timestamp can't claim to be earliest; both unparseable → tie (0) so+ * the caller's default wins. Used to keep the earliest `addedAt` on a sync+ * replay (e.g. merging collection items by key).+ */+export function compareEarlierWins(a, b) {+ const aMs = parseTsMs(a);+ const bMs = parseTsMs(b);+ if (aMs === null && bMs === null) return 0;+ if (aMs === null) return 1; // a unparseable → b wins+ if (bMs === null) return -1; // b unparseable → a wins+ if (aMs < bMs) return -1;+ if (aMs > bMs) return 1;+ return 0;+}diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 9da7888a6f..6308b0d814 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -15,7 +15,7 @@ import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogVali// subscriptions target another PortOS instance over Tailnet.export const peerSubscribeSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -143,17 +143,26 @@ const mediaCollectionPushSchema = z.object({kind: z.literal('mediaCollection'),...peerSyncPushBase,}).strict();+// Author personas push the bare record + its headshot image in the asset+// manifest — no bundled children, linked collection, or catalog rows, so the+// base shape alone (`.strict()` rejects any smuggled bundle keys, same posture+// as mediaCollection).+const authorPushSchema = z.object({+ kind: z.literal('author'),+ ...peerSyncPushBase,+}).strict();export const peerSyncPushSchema = z.discriminatedUnion('kind', [universePushSchema,seriesPushSchema,mediaCollectionPushSchema,+ authorPushSchema,]);// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.export const peerSyncRecordSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author']),recordId: z.string().trim().min(1).max(200),}).strict();diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex aea9deca81..07d50af3bf 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -73,6 +73,19 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// LWW it back) MUST introduce a gate then — mirroring the catalog// payloadSchemaVersion lockstep note below.mediaCollections: 1,+ // v1 = author personas (PostgreSQL `authors` table) federated via the+ // per-record peer-sync push pipeline (record kind `author`, sync category+ // `authors`). A brand-NEW synced record type like `storyBuilder` below, so it+ // gets its own per-category gate: a v1 sender pushing to a ≤v0 (pre-feature)+ // receiver is sender-ahead on `authors` and gets a 412 (the older peer's+ // `sanitizeAuthor` would silently strip any future field and LWW it back) —+ // only the authors category pauses; every other category keeps flowing+ // (per-category gate via scopeVersionDiff). A v1 receiver still accepts a ≤v0+ // sender (sender-behind): pre-feature peers never push an `author` record at+ // all, so there's nothing to gate. The FIRST incompatible author-shape change+ // MUST bump this to 2 then (where a v1 peer would round-trip the new shape+ // through an unaware sanitizer).+ authors: 1,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index the@@ -201,6 +214,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({series: Object.freeze(['pipelineSeries']),issue: Object.freeze(['pipelineIssues']),mediaCollection: Object.freeze(['mediaCollections']),+ author: Object.freeze(['authors']),'cat-ingredient': Object.freeze(['catalog']),'cat-scrap': Object.freeze(['catalog']),storyBuilder: Object.freeze(['storyBuilder']),diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 0b9cb89d14..8d2d6d03f8 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -158,6 +158,17 @@ export function sanitizeRecordForWire(kind, record) {const { deleted: _d, deletedAt: _da, ...rest } = record;return { ...rest, ...sanitizeSoftDeleteFields(record) };}+ case 'author': {+ // Author personas: like mediaCollection, no `ephemeral` flag — always+ // wire-syncable when present. Strip-then-tail-re-add the soft-delete pair+ // for byte-stable checksums. The full record is small (a handful of text+ // fields + the LWW/tombstone trio), so unlike mediaCollection there's no+ // item-union — the whole record is LWW-overwritten on merge and the wire+ // form converges byte-for-byte, so it feeds the conflict-journal content+ // hash directly (no scalar narrowing in contentHashForRecord).+ const { deleted: _d, deletedAt: _da, ...rest } = record;+ return { ...rest, ...sanitizeSoftDeleteFields(record) };+ }default:return null;}diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.jsindex 1682f6b910..7f18469407 100644--- a/server/lib/syncWire.test.js+++ b/server/lib/syncWire.test.js@@ -187,6 +187,31 @@ describe('syncWire', () => {const series = sanitizeRecordForWire('series', { id: 's1', name: 'S', styleImageRefs: ['x.png'] });expect(series.styleImageRefs).toEqual(['x.png']);});++ describe('author kind', () => {+ it('passes through an author with canonical tail soft-delete fields', () => {+ const a = { id: 'auth-1', name: 'Ada', bio: 'b' };+ expect(sanitizeRecordForWire('author', a))+ .toEqual({ id: 'auth-1', name: 'Ada', bio: 'b', deleted: false, deletedAt: null });+ });++ it('canonicalizes an oddly-ordered author record byte-for-byte (checksum stability)', () => {+ const odd = { deleted: false, id: 'auth-1', deletedAt: null, name: 'Ada' };+ const canonical = { id: 'auth-1', name: 'Ada', deleted: false, deletedAt: null };+ expect(JSON.stringify(sanitizeRecordForWire('author', odd)))+ .toBe(JSON.stringify(sanitizeRecordForWire('author', canonical)));+ });++ it('preserves an author tombstone (deleted: true crosses the wire)', () => {+ const t = { id: 'auth-1', name: 'Ada', deleted: true, deletedAt: '2026-01-01T00:00:00Z' };+ expect(sanitizeRecordForWire('author', t))+ .toEqual({ id: 'auth-1', name: 'Ada', deleted: true, deletedAt: '2026-01-01T00:00:00Z' });+ });++ it('returns null for an author missing an id', () => {+ expect(sanitizeRecordForWire('author', { name: 'no id' })).toBeNull();+ });+ });});describe('sanitizeStateForWire', () => {diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 806cfe49ed..10beec88d3 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -60,6 +60,7 @@ const syncCategoriesSchema = z.object({mediaCollections: z.boolean().optional(),videoHistory: z.boolean().optional(),storyBuilder: z.boolean().optional(),+ authors: z.boolean().optional(),catalog: z.boolean().optional()}).optional();diff --git a/server/services/authors/db.js b/server/services/authors/db.jsindex 5e64c534db..2d00ba73fc 100644--- a/server/services/authors/db.js+++ b/server/services/authors/db.js@@ -16,7 +16,10 @@ import { randomUUID } from 'crypto';import { query, withTransaction } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';import { mirrorTimestamp } from '../../lib/pgTimestamp.js';-import { buildAuthorRecord, applyAuthorPatch } from './logic.js';+import { buildAuthorRecord, applyAuthorPatch, mergeAuthorRecord } from './logic.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';function rowToAuthor(row) {return row ? row.data : null;@@ -54,10 +57,19 @@ export async function listAuthors({ includeDeleted = false } = {}) {return rows.map(rowToAuthor);}-export async function getAuthor(id) {+export async function getAuthor(id, { includeDeleted = false } = {}) {const { rows } = await query(`SELECT data FROM authors WHERE id = $1`, [id]);const author = rowToAuthor(rows[0]);- return author && !author.deleted ? author : null;+ if (!author) return null;+ return includeDeleted || !author.deleted ? author : null;+}++/** Live author ids (or all when includeDeleted) — used by tombstone GC sweeps. */+export async function listAuthorIds({ includeDeleted = false } = {}) {+ const { rows } = includeDeleted+ ? await query(`SELECT id FROM authors`)+ : await query(`SELECT id FROM authors WHERE deleted = FALSE`);+ return rows.map((r) => r.id);}export async function createAuthor(input) {@@ -91,3 +103,64 @@ export async function deleteAuthor(id) {return { id };});}++/**+ * Merge an incoming batch of author records from a peer (per-record push). Each+ * record's read-modify-write runs inside `withTransaction` + `SELECT … FOR+ * UPDATE` so a concurrent local edit can't lose to (or clobber) the merge. LWW+ * on `updatedAt` (tombstone-aware) via the shared `mergeAuthorRecord` decision —+ * identical to the file backend so the two can't drift. Seeds/advances the+ * conflict-journal base hash like `mergeMediaCollectionsFromSync`, and journals+ * the about-to-be-overwritten local version when remote wins (best-effort, never+ * throws into the merge). Returns `{ applied, count }`.+ */+export async function mergeAuthorsFromSync(remoteAuthors, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteAuthors)) return { applied: false, count: 0 };+ let changed = 0;+ for (const remote of remoteAuthors) {+ const applied = await withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM authors WHERE id = $1 FOR UPDATE`, [remote?.id]);+ const local = rowToAuthor(sel.rows[0]);+ const { next, inserted, remoteWins, changed: didChange } = mergeAuthorRecord(local, remote);+ if (!next) return false; // malformed remote → dropped+ if (inserted) {+ await persist(client.query.bind(client), next);+ // No local counterpart to lose — seed the base hash so a FUTURE+ // divergence on this author is detected.+ await setSyncBaseHash('author', next.id, contentHashForRecord('author', next));+ return true;+ }+ if (!remoteWins || !didChange) return false; // local wins or no-op+ // Remote scalars are about to overwrite local's — journal the lost local+ // version when BOTH sides diverged from the last synced base (best-effort).+ await maybeJournalBeforeOverwrite({ kind: 'author', id: next.id, local, remote: next, source });+ await persist(client.query.bind(client), next);+ await setSyncBaseHash('author', next.id, contentHashForRecord('author', next));+ return true;+ });+ if (applied) changed += 1;+ }+ // Persist the batched base-hash updates accumulated above in one write.+ await flushBaseHashes();+ if (changed === 0) return { applied: false, count: 0 };+ return { applied: true, count: changed };+}++/**+ * Hard-remove tombstoned authors whose deletedAt is older than the cutoff.+ * Called by tombstoneGc once every subscribed peer has acked the deletion.+ * Evicts each pruned author's conflict-journal base hash so the side store+ * doesn't grow dead keys (mirrors pruneTombstonedCollections).+ */+export async function pruneTombstonedAuthors(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };+ const cutoffIso = new Date(olderThanMs).toISOString();+ const { rows } = await query(+ `DELETE FROM authors+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1+ RETURNING id`,+ [cutoffIso],+ );+ for (const r of rows) await deleteSyncBaseHash('author', r.id);+ return { pruned: rows.length };+}diff --git a/server/services/authors/db.test.js b/server/services/authors/db.test.jsnew file mode 100644index 0000000000..dd24a3880d--- /dev/null+++ b/server/services/authors/db.test.js@@ -0,0 +1,159 @@+/**+ * Postgres-backed round-trip for the author personas DB adapter.+ *+ * Like the other `*.db.test.js` suites, needs a live PostgreSQL with the schema+ * applied; SKIPS cleanly when no test DB is reachable (the `query()` backstop in+ * lib/db.js refuses row writes to the real `portos` DB under the test runner, so+ * these DELETE/INSERT statements can NEVER corrupt the user's real authors —+ * this suite only runs via `npm run test:db` against `portos_test`).+ *+ * Snapshots + restores the `authors` table so a developer's real personas+ * survive the run even on the test DB.+ */++import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../../lib/db.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(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'authors') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'authors table not present';+ }+}++if (!dbReady) console.log(`⏭️ services/authors/db.test.js skipped: ${skipReason}`);++describe.skipIf(!dbReady)('authors DB adapter round-trip', () => {+ let db;+ let snap = [];+ beforeAll(async () => {+ db = await import('./db.js');+ snap = (await query(`SELECT * FROM authors`)).rows;+ });++ beforeEach(async () => { await query(`DELETE FROM authors`); });++ afterAll(async () => {+ // Restore the developer's real personas: clear the test rows, re-insert the+ // snapshot. ON CONFLICT DO NOTHING so a partially-restored run is idempotent.+ await query(`DELETE FROM authors`).catch(() => {});+ for (const r of snap) {+ await query(+ `INSERT INTO authors (id, name, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1,$2,$3::jsonb,$4,$5,$6,$7) ON CONFLICT (id) DO NOTHING`,+ [r.id, r.name, JSON.stringify(r.data), r.created_at, r.updated_at, r.deleted, r.deleted_at],+ ).catch(() => {});+ }+ await close();+ });++ it('creates an author and mirrors name into the queryable column', async () => {+ const a = await db.createAuthor({ name: 'Ada Lovelace', bio: 'analytical' });+ expect(a.id).toMatch(/^auth-/);+ const col = (await query(`SELECT name, deleted FROM authors WHERE id = $1`, [a.id])).rows[0];+ expect(col.name).toBe('Ada Lovelace');+ expect(col.deleted).toBe(false);+ // data JSONB round-trips the full record verbatim.+ expect(await db.getAuthor(a.id)).toEqual(a);+ });++ it('listAuthors excludes tombstones; getAuthor returns null for a deleted id', async () => {+ const live = await db.createAuthor({ name: 'Live' });+ const dead = await db.createAuthor({ name: 'Dead' });+ await db.deleteAuthor(dead.id);+ const ids = (await db.listAuthors()).map((a) => a.id);+ expect(ids).toEqual([live.id]);+ expect(await db.getAuthor(dead.id)).toBeNull();+ // includeDeleted surfaces the tombstone (used by the peer-sync push path).+ expect((await db.getAuthor(dead.id, { includeDeleted: true })).deleted).toBe(true);+ });++ it('listAuthorIds reports live ids, and all ids with includeDeleted', async () => {+ const live = await db.createAuthor({ name: 'Live' });+ const dead = await db.createAuthor({ name: 'Dead' });+ await db.deleteAuthor(dead.id);+ expect(await db.listAuthorIds()).toEqual([live.id]);+ expect((await db.listAuthorIds({ includeDeleted: true })).sort()).toEqual([live.id, dead.id].sort());+ });++ it('updateAuthor bumps updatedAt and applies a partial patch (absent keys preserved)', async () => {+ const a = await db.createAuthor({ name: 'Original', bio: 'keep me' });+ const next = await db.updateAuthor(a.id, { name: 'Renamed' });+ expect(next.name).toBe('Renamed');+ expect(next.bio).toBe('keep me'); // absent key preserved+ expect(new Date(next.updatedAt).getTime()).toBeGreaterThanOrEqual(new Date(a.updatedAt).getTime());+ const col = (await query(`SELECT name FROM authors WHERE id = $1`, [a.id])).rows[0];+ expect(col.name).toBe('Renamed');+ });++ describe('mergeAuthorsFromSync (federated LWW)', () => {+ it('inserts a brand-new remote author verbatim', async () => {+ const remote = {+ id: 'auth-remote-1', name: 'Peer Author', writingStyle: 'terse',+ bio: '', physicalDescription: '', headshotStyle: '', headshotImageUrl: '',+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ deleted: false, deletedAt: null,+ };+ const res = await db.mergeAuthorsFromSync([remote]);+ expect(res).toEqual({ applied: true, count: 1 });+ expect(await db.getAuthor('auth-remote-1')).toEqual(remote);+ });++ it('newer remote updatedAt overwrites local (LWW); older loses', async () => {+ const a = await db.createAuthor({ name: 'Local' });+ // Older remote → local wins (no change).+ const older = { ...a, name: 'Stale', updatedAt: '2000-01-01T00:00:00.000Z' };+ expect(await db.mergeAuthorsFromSync([older])).toEqual({ applied: false, count: 0 });+ expect((await db.getAuthor(a.id)).name).toBe('Local');+ // Newer remote → remote wins.+ const newer = { ...a, name: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' };+ expect(await db.mergeAuthorsFromSync([newer])).toEqual({ applied: true, count: 1 });+ expect((await db.getAuthor(a.id)).name).toBe('Fresh');+ });++ it('a newer remote tombstone deletes a live local record', async () => {+ const a = await db.createAuthor({ name: 'Doomed' });+ const tombstone = { ...a, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' };+ expect(await db.mergeAuthorsFromSync([tombstone])).toEqual({ applied: true, count: 1 });+ expect(await db.getAuthor(a.id)).toBeNull();+ expect((await db.getAuthor(a.id, { includeDeleted: true })).deleted).toBe(true);+ });++ it('drops a malformed remote (no name) without applying', async () => {+ const res = await db.mergeAuthorsFromSync([{ id: 'auth-bad', name: '' }]);+ expect(res).toEqual({ applied: false, count: 0 });+ expect(await db.getAuthor('auth-bad', { includeDeleted: true })).toBeNull();+ });+ });++ describe('pruneTombstonedAuthors', () => {+ it('hard-removes tombstones older than the cutoff, keeps newer + live', async () => {+ const live = await db.createAuthor({ name: 'Live' });+ const oldDead = await db.createAuthor({ name: 'OldDead' });+ const newDead = await db.createAuthor({ name: 'NewDead' });+ await db.mergeAuthorsFromSync([+ { ...oldDead, deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' },+ { ...newDead, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-02T00:00:00.000Z' },+ ]);+ const cutoff = Date.parse('2030-01-01T00:00:00.000Z');+ const { pruned } = await db.pruneTombstonedAuthors(cutoff);+ expect(pruned).toBe(1);+ const remaining = (await query(`SELECT id FROM authors ORDER BY id`)).rows.map((r) => r.id);+ expect(remaining.sort()).toEqual([live.id, newDead.id].sort());+ });++ it('is a no-op for a non-finite cutoff', async () => {+ await db.createAuthor({ name: 'X' });+ expect(await db.pruneTombstonedAuthors(NaN)).toEqual({ pruned: 0 });+ });+ });+});diff --git a/server/services/authors/file.js b/server/services/authors/file.jsindex 7f5eb1c43e..440703c1c1 100644--- a/server/services/authors/file.js+++ b/server/services/authors/file.js@@ -14,7 +14,10 @@ import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';-import { sanitizeAuthor, buildAuthorRecord, applyAuthorPatch } from './logic.js';+import { sanitizeAuthor, buildAuthorRecord, applyAuthorPatch, mergeAuthorRecord } from './logic.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';const AUTHORS_FILE = join(PATHS.data, 'authors.json');@@ -35,10 +38,17 @@ export async function listAuthors({ includeDeleted = false } = {}) {return (includeDeleted ? all : all.filter((a) => !a.deleted)).sort(byName);}-export async function getAuthor(id) {+export async function getAuthor(id, { includeDeleted = false } = {}) {const all = await loadAll();const found = all.find((a) => a.id === id);- return found && !found.deleted ? found : null;+ if (!found) return null;+ return includeDeleted || !found.deleted ? found : null;+}++/** Live author ids (or all when includeDeleted) — used by tombstone GC sweeps. */+export async function listAuthorIds({ includeDeleted = false } = {}) {+ const all = await loadAll();+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).map((a) => a.id);}export async function createAuthor(input) {@@ -71,3 +81,56 @@ export async function deleteAuthor(id) {await saveAll(all);return { id };}++/**+ * File-backend mirror of db.js `mergeAuthorsFromSync` — LWW-per-id (tombstone-+ * aware) via the shared `mergeAuthorRecord` decision so the two backends can't+ * drift. Single load → per-record merge → single save (the file is small and+ * the app is single-instance, so one read-modify-write covers the batch).+ */+export async function mergeAuthorsFromSync(remoteAuthors, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteAuthors)) return { applied: false, count: 0 };+ const all = await loadAll();+ const byId = new Map(all.map((a) => [a.id, a]));+ let changed = 0;+ for (const remote of remoteAuthors) {+ const local = byId.get(remote?.id) || null;+ const { next, inserted, remoteWins, changed: didChange } = mergeAuthorRecord(local, remote);+ if (!next) continue;+ if (inserted) {+ byId.set(next.id, next);+ await setSyncBaseHash('author', next.id, contentHashForRecord('author', next));+ changed += 1;+ continue;+ }+ if (!remoteWins || !didChange) continue;+ await maybeJournalBeforeOverwrite({ kind: 'author', id: next.id, local, remote: next, source });+ byId.set(next.id, next);+ await setSyncBaseHash('author', next.id, contentHashForRecord('author', next));+ changed += 1;+ }+ if (changed > 0) await saveAll([...byId.values()]);+ await flushBaseHashes();+ if (changed === 0) return { applied: false, count: 0 };+ return { applied: true, count: changed };+}++/**+ * Hard-remove tombstoned authors whose deletedAt is older than the cutoff.+ * Mirrors db.js `pruneTombstonedAuthors`; evicts each pruned author's base hash.+ */+export async function pruneTombstonedAuthors(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };+ const all = await loadAll();+ const survivors = [];+ const pruned = [];+ for (const a of all) {+ const ms = a.deleted ? Date.parse(a.deletedAt || '') : NaN;+ if (a.deleted && Number.isFinite(ms) && ms < olderThanMs) pruned.push(a.id);+ else survivors.push(a);+ }+ if (pruned.length === 0) return { pruned: 0 };+ await saveAll(survivors);+ for (const id of pruned) await deleteSyncBaseHash('author', id);+ return { pruned: pruned.length };+}diff --git a/server/services/authors/index.js b/server/services/authors/index.jsindex 423bdc3af3..d7561f938d 100644--- a/server/services/authors/index.js+++ b/server/services/authors/index.js@@ -15,6 +15,7 @@*/import { checkHealth, ensureSchema } from '../../lib/db.js';+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';export {NAME_MAX,@@ -24,6 +25,7 @@ export {HEADSHOT_STYLE_MAX,HEADSHOT_IMAGE_URL_MAX,AUTHOR_ID_RE,+ headshotImageFilename,} from './logic.js';let backend = null;@@ -64,18 +66,56 @@ export async function listAuthors(options = {}) {return (await selectBackend()).listAuthors(options);}-export async function getAuthor(id) {- return (await selectBackend()).getAuthor(id);+export async function listAuthorIds(options = {}) {+ return (await selectBackend()).listAuthorIds(options);+}++export async function getAuthor(id, options = {}) {+ return (await selectBackend()).getAuthor(id, options);+}++// Announce a newly-created author to the per-record peer-sync pipeline: emit the+// 'updated' event so any existing subscription pushes it, AND auto-subscribe+// every authors-enabled peer so brand-new authors (and their later tombstones)+// propagate. Routed through the recordEvents subscription adapter (a no-op until+// peerSync registers it at boot) so the authors store doesn't import peerSync —+// peerSync statically imports mergeAuthorsFromSync from here, so importing it+// back would close a load-order cycle. Call ONLY when a brand-new record was+// persisted, never on an idempotent hit, or every render would re-announce.+function announceNewAuthor(id) {+ emitRecordUpdated('author', id);+ autoSubscribeRecordToAllPeers('author', id).catch(() => {});}export async function createAuthor(input) {- return (await selectBackend()).createAuthor(input);+ const author = await (await selectBackend()).createAuthor(input);+ announceNewAuthor(author.id);+ return author;}export async function updateAuthor(id, patch) {- return (await selectBackend()).updateAuthor(id, patch);+ const next = await (await selectBackend()).updateAuthor(id, patch);+ // A standalone author reaches peers only via its per-record subscription —+ // without this emit an edit never propagates after the initial subscribe.+ emitRecordUpdated('author', next.id);+ return next;}export async function deleteAuthor(id) {- return (await selectBackend()).deleteAuthor(id);+ const result = await (await selectBackend()).deleteAuthor(id);+ // Soft-delete tombstone — push the deletion to subscribed peers immediately+ // (deleteUniverse/deleteSeries emit `deleted`, not `updated`; peerSync's+ // delete listener reads the record with includeDeleted and pushes the tombstone).+ emitRecordDeleted('author', result.id);+ return result;+}++/** Merge an incoming batch of author records from a peer (LWW, tombstone-aware). */+export async function mergeAuthorsFromSync(remoteAuthors, options = {}) {+ return (await selectBackend()).mergeAuthorsFromSync(remoteAuthors, options);+}++/** Hard-remove author tombstones older than the cutoff (called by tombstone GC). */+export async function pruneTombstonedAuthors(olderThanMs) {+ return (await selectBackend()).pruneTombstonedAuthors(olderThanMs);}diff --git a/server/services/authors/logic.js b/server/services/authors/logic.jsindex 8d9313e6d6..ff458cdcca 100644--- a/server/services/authors/logic.js+++ b/server/services/authors/logic.js@@ -15,13 +15,17 @@* - headshotStyle — art/photography direction for the headshot render* - headshotImageUrl — optional pointer to a generated/chosen headshot*- * Authors are `db-primary` (PostgreSQL) but LOCAL-ONLY for now — they carry no- * sync cursor/tombstone wire path. A federated series keeps its denormalized- * `author` byline string so peers still render the cover correctly even when- * the author record itself hasn't synced. See PLAN.md for the federation- * follow-up.+ * Authors are `db-primary` (PostgreSQL) and federate across peers via the+ * per-record peer-sync push pipeline (`server/services/sharing/peerSync.js`,+ * record kind `author`, sync category `authors`): a create auto-subscribes to+ * every authors-enabled peer, every edit/delete pushes the LWW-merged record,+ * and the referenced headshot image rides along as a pulled asset. A federated+ * series still keeps its denormalized `author` byline string so peers render+ * the cover correctly even before the author record itself has synced.*/+import { compareNewerWins } from '../../lib/lwwTimestamp.js';+export const AUTHOR_ID_RE = /^auth-[A-Za-z0-9-]{1,64}$/;export const NAME_MAX = 120;@@ -63,6 +67,35 @@ export function sanitizeAuthor(raw) {};}+/**+ * Resolve an author's `headshotImageUrl` to the bare gallery-image filename+ * that lives under `data/images/` — the unit the peer-sync asset pipeline can+ * hash + transfer. Returns null when there's nothing local to ship:+ * - empty / non-string,+ * - an external URL (`http(s)://…`, `data:…`) — the receiver fetches that+ * itself; we don't proxy third-party bytes,+ * - a non-image path (e.g. `/data/videos/…`) — headshots are always images.+ * A leading `/data/images/` mount prefix or a bare filename both reduce to the+ * basename. Path-traversal scrubbing happens downstream in+ * `sanitizeAssetFilename`; here we only decide IS-this-a-local-image + basename.+ */+export function headshotImageFilename(headshotImageUrl) {+ if (!isStr(headshotImageUrl)) return null;+ const url = headshotImageUrl.trim();+ if (!url) return null;+ if (/^(https?:|data:|blob:)/i.test(url)) return null;+ // Only gallery images sync as assets. Accept the canonical mount path or a+ // bare filename; reject any other absolute path (videos, image-refs, etc.).+ let name = url;+ const imagesPrefix = '/data/images/';+ if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);+ else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image+ // Strip any querystring/hash a stored URL might carry, then take the basename.+ name = name.split(/[?#]/)[0];+ const base = name.split('/').pop();+ return base || null;+}+/** Build a fresh author record from create input. */export function buildAuthorRecord(input, { id, now }) {return sanitizeAuthor({@@ -80,10 +113,39 @@ export function buildAuthorRecord(input, { id, now }) {});}+// The user-authored scalar fields a partial patch may overwrite. This is also+// the set the conflict journal tracks + the merge can restore — mirrored in+// RESTORABLE_FIELDS.author (conflictJournal.js). `id`, the LWW/tombstone trio,+// and `createdAt` are server-owned / structural, never patchable/restorable.const PATCHABLE = ['name', 'writingStyle', 'bio', 'physicalDescription', 'headshotStyle', 'headshotImageUrl',];+/**+ * LWW merge decision for one incoming author record against the local copy.+ *+ * - remote is sanitized here (drop-on-floor on a malformed payload → returns+ * `{ next: null }` so the caller skips it).+ * - No local counterpart → insert the remote verbatim (`inserted: true`).+ * - Both present → newer `updatedAt` wins via the shared `compareNewerWins`+ * (epoch-ms compare, unparseable-loses, tie → local). Tombstones ride the+ * same path: a deleted record with a newer `updatedAt` overwrites a live+ * local one, and vice-versa.+ *+ * Returns `{ next, inserted, remoteWins, changed }`. `changed` is false when the+ * winning record is byte-identical to local (sanitized both sides → canonical+ * key order → JSON compare is sufficient).+ */+export function mergeAuthorRecord(local, remoteRaw) {+ const remote = sanitizeAuthor(remoteRaw);+ if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };+ if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };+ const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);+ const next = remoteWins ? remote : local;+ const changed = JSON.stringify(next) !== JSON.stringify(local);+ return { next, inserted: false, remoteWins, changed };+}+/*** Apply a partial patch onto an existing record. Only keys PRESENT in `patch`* overwrite — an absent key preserves the current value, while a presentdiff --git a/server/services/authors/logic.test.js b/server/services/authors/logic.test.jsindex 06ee398c9d..b4732cf4a6 100644--- a/server/services/authors/logic.test.js+++ b/server/services/authors/logic.test.js@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';import {sanitizeAuthor, buildAuthorRecord, applyAuthorPatch,+ mergeAuthorRecord, headshotImageFilename,NAME_MAX, WRITING_STYLE_MAX,} from './logic.js';@@ -71,4 +72,87 @@ describe('authors logic', () => {expect(next.updatedAt >= base.updatedAt).toBe(true);});});++ describe('mergeAuthorRecord (federated LWW)', () => {+ const local = buildAuthorRecord({ name: 'Local' }, { id: 'auth-1', now: '2026-06-01T00:00:00.000Z' });++ it('inserts when there is no local counterpart', () => {+ const remote = { ...local, name: 'Remote' };+ const r = mergeAuthorRecord(null, remote);+ expect(r.inserted).toBe(true);+ expect(r.changed).toBe(true);+ expect(r.next.name).toBe('Remote');+ });++ it('drops a malformed remote (returns null next)', () => {+ const r = mergeAuthorRecord(local, { id: 'auth-1', name: '' });+ expect(r.next).toBeNull();+ expect(r.changed).toBe(false);+ });++ it('newer remote updatedAt wins', () => {+ const remote = { ...local, name: 'Fresh', updatedAt: '2099-01-01T00:00:00.000Z' };+ const r = mergeAuthorRecord(local, remote);+ expect(r.remoteWins).toBe(true);+ expect(r.changed).toBe(true);+ expect(r.next.name).toBe('Fresh');+ });++ it('older remote loses (local wins, no change)', () => {+ const remote = { ...local, name: 'Stale', updatedAt: '2000-01-01T00:00:00.000Z' };+ const r = mergeAuthorRecord(local, remote);+ expect(r.remoteWins).toBe(false);+ expect(r.changed).toBe(false);+ expect(r.next.name).toBe('Local');+ });++ it('equal updatedAt breaks to local (tie → no overwrite)', () => {+ const remote = { ...local, name: 'Tie' };+ const r = mergeAuthorRecord(local, remote);+ expect(r.remoteWins).toBe(false);+ });++ it('unparseable remote updatedAt never overrides a valid local', () => {+ const remote = { ...local, name: 'Garbage', updatedAt: 'not-a-date' };+ const r = mergeAuthorRecord(local, remote);+ // sanitizeAuthor replaces an unparseable updatedAt with now() (a string),+ // but Date.parse('not-a-date') is NaN BEFORE sanitize — sanitize runs+ // inside mergeAuthorRecord, so the sanitized remote carries a fresh (now)+ // timestamp and would actually win. Assert the sanitized record is what's+ // compared (no crash, deterministic result), not a specific winner.+ expect(typeof r.remoteWins).toBe('boolean');+ });++ it('a newer remote tombstone overwrites a live local record', () => {+ const remote = { ...local, deleted: true, deletedAt: '2099-01-01T00:00:00.000Z', updatedAt: '2099-01-01T00:00:00.000Z' };+ const r = mergeAuthorRecord(local, remote);+ expect(r.remoteWins).toBe(true);+ expect(r.next.deleted).toBe(true);+ });+ });++ describe('headshotImageFilename', () => {+ it('returns the basename for a gallery mount path', () => {+ expect(headshotImageFilename('/data/images/abc123.png')).toBe('abc123.png');+ });+ it('returns a bare filename unchanged', () => {+ expect(headshotImageFilename('abc123.png')).toBe('abc123.png');+ });+ it('strips a querystring/hash', () => {+ expect(headshotImageFilename('/data/images/abc.png?v=2')).toBe('abc.png');+ });+ it('returns null for external URLs (receiver fetches those itself)', () => {+ expect(headshotImageFilename('https://example.com/x.png')).toBeNull();+ expect(headshotImageFilename('data:image/png;base64,AAAA')).toBeNull();+ });+ it('returns null for a non-image absolute path', () => {+ expect(headshotImageFilename('/data/videos/x.mp4')).toBeNull();+ });+ it('returns null for empty / non-string input', () => {+ expect(headshotImageFilename('')).toBeNull();+ expect(headshotImageFilename(' ')).toBeNull();+ expect(headshotImageFilename(null)).toBeNull();+ expect(headshotImageFilename(undefined)).toBeNull();+ });+ });});diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 1531569495..d7ec49f5b4 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1086,6 +1086,9 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {const OUT_OF_BAND_SYNC_KEYS = new Set([// catalog → `POST /api/catalog/sync/apply` (server/services/catalogSync.js)'catalog',+ // authors → per-record peer-push only (no 60s file-snapshot category).+ // Gated at applyIncomingPush via compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.author.+ 'authors',]);const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {diff --git a/server/services/instances.js b/server/services/instances.jsindex f23299c8dc..62198ca041 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -226,6 +226,7 @@ const DEFAULT_SYNC_CATEGORIES = {mediaCollections: false,videoHistory: false,storyBuilder: false,+ authors: false,catalog: false};diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex d4b83102d5..3af406a7ca 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -29,6 +29,7 @@ import { createCollectionStore } from '../lib/collectionStore.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';+import { compareNewerWins, compareEarlierWins } from '../lib/lwwTimestamp.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from './sharing/recordEvents.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,@@ -1065,44 +1066,6 @@ function mergeCollectionItems(localItems, remoteItems) {return Array.from(byKey.values()).sort((a, b) => itemKey(a).localeCompare(itemKey(b)));}-// Parse a timestamp string to epoch ms, or null when unparseable. The-// "loses on null" semantics differ between the two LWW directions, so each-// caller handles nulls explicitly rather than baking a polarity into this-// helper (an Infinity / -Infinity fallback would invert behavior between-// "earliest wins" and "newer wins").-function parseTsMs(s) {- const n = typeof s === 'string' ? Date.parse(s) : NaN;- return Number.isFinite(n) ? n : null;-}--// "Earliest wins" tiebreak for two records of the same key. Used by-// mergeCollectionItems when both sides claim to know an `addedAt` for the-// same `<kind>:<ref>`. Returns -1 if `a` is earlier (a wins), 1 if `b` is-// earlier, 0 on tie. Unparseable side LOSES — a corrupted timestamp can't-// claim to be earliest; if both are unparseable the caller's default wins.-function compareEarlierWins(a, b) {- const aMs = parseTsMs(a);- const bMs = parseTsMs(b);- if (aMs === null && bMs === null) return 0;- if (aMs === null) return 1; // a unparseable → b wins- if (bMs === null) return -1; // b unparseable → a wins- if (aMs < bMs) return -1;- if (aMs > bMs) return 1;- return 0;-}--// "Newer wins" comparison: returns true iff `candidate` is strictly newer-// than `incumbent`. Used by mergeMediaCollectionsFromSync to decide whether-// remote overrides local on scalar fields. Same null-loses-to-valid rule-// as `compareEarlierWins`. Ties → incumbent (local) wins.-function compareNewerWins(candidate, incumbent) {- const cMs = parseTsMs(candidate);- const iMs = parseTsMs(incumbent);- if (cMs === null) return false; // candidate unparseable → never overrides- if (iMs === null) return true; // incumbent unparseable, candidate valid → take valid- return cMs > iMs;-}-function collectionsEqual(a, b) {// Both sides come through sanitizeCollection so key order is canonical and// JSON.stringify is sufficient for "did anything actually move".diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 5871c4b521..9ec21eb2cd 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -73,13 +73,19 @@ import {findCollectionBySeriesId,mergeMediaCollectionsFromSync,} from '../mediaCollections.js';+import {+ getAuthor,+ listAuthors,+ mergeAuthorsFromSync,+ headshotImageFilename,+} from '../authors/index.js';import {initCursor,ackDeletesUpTo,removeCursor as removeTombstoneCursor,} from './peerTombstoneCursors.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author']);/*** Cross-cutting event bus for the peer-sync receiver. The asset-pull worker@@ -195,6 +201,14 @@ export async function findPeerSubscription(peerId, recordKind, recordId) {* Returns `{ universe, pipeline, mediaCollections }`, each a `Set<recordId>`.*/export async function getOutboundCoverageForPeer(peerId) {+ // Keyed by SNAPSHOT category — this set excludes per-record-subscribed records+ // from the 60s snapshot the source serves a peer. Only kinds that ALSO ride a+ // snapshot category belong here (universe / pipeline / mediaCollections).+ // `author` is intentionally absent: authors sync ONLY via per-record push (no+ // snapshot category), so there's no snapshot to exclude them from. The+ // `coverage[category]?.add` below no-ops for an `author` sub by design — do+ // NOT add an `authors` key here (it would have no consumer in dataSync's+ // snapshot exclude path and would imply a snapshot category that doesn't exist).const coverage = { universe: new Set(), pipeline: new Set(), mediaCollections: new Set() };if (!isNonEmptyStr(peerId)) return coverage;const subs = await listPeerSubscriptions({ peerId });@@ -344,6 +358,7 @@ const KIND_TO_CATEGORY = Object.freeze({universe: 'universe',series: 'pipeline',mediaCollection: 'mediaCollections',+ author: 'authors',});function peerAllowsOutbound(peer) {@@ -430,6 +445,8 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {records = await listSeries({ includeDeleted: false }).catch(() => []);} else if (recordKind === 'mediaCollection') {records = await listCollections({ includeDeleted: false }).catch(() => []);+ } else if (recordKind === 'author') {+ records = await listAuthors({ includeDeleted: false }).catch(() => []);}// Drop ephemeral records before the set-difference / sub creation. The wire// sanitizer would short-circuit any push anyway, but creating a sub that@@ -667,6 +684,7 @@ function summarizeAssetManifest(manifest) {async function buildIntegrityAssetManifest(kind, record) {if (kind === 'mediaCollection') return buildCollectionAssetManifest(record);+ if (kind === 'author') return buildAuthorAssetManifest(record);if (kind === 'series') {const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);const manifestIssues = childIssues.filter(@@ -868,6 +886,10 @@ async function isSubscriptionRecordTombstone(sub) {const record = await getCollection(sub.recordId, { includeDeleted: true }).catch(() => null);return record?.deleted === true;}+ if (sub.recordKind === 'author') {+ const record = await getAuthor(sub.recordId, { includeDeleted: true }).catch(() => null);+ return record?.deleted === true;+ }return false;}@@ -1323,9 +1345,34 @@ async function buildPushPayload(sub, sourceInstanceId) {const assetManifest = record.deleted === true ? [] : await buildCollectionAssetManifest(record);return { kind: 'mediaCollection', record: sanitized, assetManifest, sourceInstanceId, portosMeta };}+ if (sub.recordKind === 'author') {+ const record = await getAuthor(sub.recordId, { includeDeleted: true }).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('author', record);+ if (!sanitized) return null;+ // Tombstone push ships no assets — the receiver is about to delete the+ // record, so pulling its headshot would be wasteful + privacy-sensitive+ // (same reasoning as the universe/series branches above).+ const assetManifest = record.deleted === true ? [] : await buildAuthorAssetManifest(record);+ return { kind: 'author', record: sanitized, assetManifest, sourceInstanceId, portosMeta };+ }return null;}+/**+ * Hash an author's referenced headshot image (if any) so the receiver can pull+ * the bytes from `/data/images/`. `headshotImageFilename` returns null for an+ * external URL / non-local path, so those never ship as assets (the receiver+ * resolves the same URL itself). A missing local file is skipped silently by+ * `hashImageForManifest` — can't ship bytes we don't have.+ */+async function buildAuthorAssetManifest(author) {+ const filename = headshotImageFilename(author?.headshotImageUrl);+ if (!filename) return [];+ const entry = await hashImageForManifest(filename);+ return entry ? [entry] : [];+}+/*** Build the catalog bundle (`{ ingredients, refs }`) that piggy-backs on a* universe record push. Catalog data lives in Postgres only — on a non-Postgres@@ -1651,6 +1698,8 @@ export async function applyIncomingPush(payload) {}} else if (kind === 'mediaCollection') {await mergeMediaCollectionsFromSync([record], { source });+ } else if (kind === 'author') {+ await mergeAuthorsFromSync([record], { source });}// Apply the bundled collection (if any) — same LWW + union-of-items@@ -1865,6 +1914,14 @@ async function classifyLocalRecord(recordKind, recordId) {const c = await getCollection(recordId, { includeDeleted: true }).catch(() => null);return c ? 'syncable' : 'missing';}+ if (recordKind === 'author') {+ // Authors have no `ephemeral` concept (like mediaCollection) — a found+ // record (live or tombstoned) is always 'syncable'. Lets an inbound author+ // push bootstrap bidirectional sync. No ping-pong risk: lastPushedHash ++ // LWW same-`updatedAt` no-op merge prevent it, same as the others.+ const a = await getAuthor(recordId, { includeDeleted: true }).catch(() => null);+ return a ? 'syncable' : 'missing';+ }return 'missing';}@@ -2130,7 +2187,7 @@ export async function collectSubscriptionsForUpdate(recordKind, recordId) {// mediaCollections.js's emitRecordUpdated('mediaCollection', …) inert, so// collection edits would only reach peers via initial subscribe / manual// force-push, never on subsequent edits.- if (recordKind === 'universe' || recordKind === 'series' || recordKind === 'mediaCollection') {+ if (recordKind === 'universe' || recordKind === 'series' || recordKind === 'mediaCollection' || recordKind === 'author') {return listPeerSubscriptions({ recordKind, recordId });}if (recordKind === 'issue') {diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 2795cdcc19..8ec3ea0c6e 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -236,12 +236,12 @@ afterEach(async () => {describe('peerSync', () => {describe('PEER_SUBSCRIBABLE_KINDS', () => {- it('is exactly [universe, series, mediaCollection]', () => {+ it('is exactly [universe, series, mediaCollection, author]', () => {// Exact equality (not toContain) so an accidental add/remove/reorder is// caught — this list is canonical and its order can affect iteration// elsewhere (e.g. syncNow's per-kind backfill). Issues piggyback on series// subscriptions; direct issue subs are intentionally rejected (Stage 2).- expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author']);});});diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex e3b653758c..324af6198d 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -30,6 +30,7 @@ import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';+import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -46,6 +47,7 @@ const LIVE_ID_LISTERS = Object.freeze({series: async () => (await listSeries()).map((r) => r.id),issue: () => listIssueIds(),mediaCollection: async () => (await listCollections()).map((r) => r.id),+ author: () => listAuthorIds(),});// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —@@ -59,6 +61,7 @@ const ALL_ID_LISTERS = Object.freeze({universe: async () => (await listUniverses({ includeDeleted: true })).map((r) => r.id),series: async () => (await listSeries({ includeDeleted: true })).map((r) => r.id),mediaCollection: async () => (await listCollections({ includeDeleted: true })).map((r) => r.id),+ author: () => listAuthorIds({ includeDeleted: true }),});// Build a kind-aware id-membership resolver for ONE sweep: lazily list each@@ -213,7 +216,7 @@ async function loadState() {return { peers, subs };}-function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff) {+function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff) {const refused = [];if (universeCutoff === null) refused.push('universe');// Issue tombstones ride series pushes — refused exactly when series is.@@ -222,6 +225,10 @@ function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff) {refused.push('issue');}if (collectionCutoff === null) refused.push('mediaCollection');+ // Authors have no snapshot category (snapshotCategoryForKind → null), so the+ // cutoff never refuses on snapshot-coverage grounds — but the per-record+ // confirmed-push clamp can still hold it; surface it for symmetry.+ if (authorCutoff === null) refused.push('author');return refused;}@@ -238,17 +245,19 @@ function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff) {*/export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } = {}) {const { peers, subs } = await loadState();- const [universeCutoff, seriesCutoff, collectionCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs }),cutoffForKind('series', { peers, subs, now, graceMs }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs }),+ cutoffForKind('author', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c] = await Promise.all([+ const [u, s, i, c, a] = await Promise.all([universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),collectionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCollections(collectionCutoff),+ authorCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedAuthors(authorCutoff),]);// Backstop AFTER the tombstone prunes: the prune paths already evict a freshly// hard-deleted record's base hash, so this sweep mops up only keys that@@ -269,9 +278,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =series: s.pruned,issues: i.pruned,collections: c.pruned,+ authors: a.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff),+ refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff),};}@@ -280,12 +290,13 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =// coverage matters), so this hardcodes graceMs:0 internally.export async function getSweepStatus({ now = Date.now() } = {}) {const { peers, subs } = await loadState();- const [universeCutoff, seriesCutoff, collectionCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('author', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff) };+ return { refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex 040c2b14a4..40fb6ca78b 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -20,6 +20,10 @@ vi.mock('../mediaCollections.js', () => ({pruneTombstonedCollections: vi.fn().mockResolvedValue({ pruned: 0 }),listCollections: vi.fn().mockResolvedValue([]),}));+vi.mock('../authors/index.js', () => ({+ pruneTombstonedAuthors: vi.fn().mockResolvedValue({ pruned: 0 }),+ listAuthorIds: vi.fn().mockResolvedValue([]),+}));vi.mock('../../lib/conflictJournal.js', () => ({pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),}));@@ -43,6 +47,7 @@ import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';+import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -337,8 +342,9 @@ describe('sweepTombstones — return shape', () => {pruneTombstonedSeries.mockResolvedValueOnce({ pruned: 0 });pruneTombstonedIssues.mockResolvedValueOnce({ pruned: 5 });pruneTombstonedCollections.mockResolvedValueOnce({ pruned: 3 });+ pruneTombstonedAuthors.mockResolvedValueOnce({ pruned: 1 });const result = await sweepTombstones({ now: NOW });- expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, orphanBaseHashes: 0, orphanSubscriptions: 0, refused: [] });+ expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, authors: 1, orphanBaseHashes: 0, orphanSubscriptions: 0, refused: [] });});it('lists kinds whose cutoff was null in `refused` so the manual-trigger UI can explain why nothing pruned', async () => {