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
address review (codex): federate the commission brief so synced feedback attaches on peers; push re-ratings via emitRecordUpdated; cap live feedback per commission
[._.]/ Adam Eivy30bb378bd9ff
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 439624cb73..190aeea770 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,4 +2,4 @@### Changed-- [issue-2686] Creative Commission taste feedback now federates across your machines. A 👍/👎 (and its note) rated on one machine flows to your other sync peers and steers the *same* commission's next run there — while each machine keeps its own schedule and only the owning machine fires the cron, so nothing double-runs. Feedback moved from an inline field on the machine-local commission into its own federated `commissionFeedback` record kind (one row per reaction, last-write-wins with soft-delete tombstones); a new **Commission Feedback** toggle appears under a peer's sync categories. Existing reactions are split into the federated store automatically at boot.+- [issue-2686] Creative Commissions now federate across your machines as a split record: the **brief** (name, intent, genre, generation settings) and your **taste feedback** (👍/👎 + notes) sync to your other peers, while each machine keeps its own **schedule** and **run history** — so the same commission and its accumulated taste appear everywhere, but only the machine you scheduled it on fires the cron (no double-run). A reaction rated on one machine steers that commission's next run on another. Two new sync-category toggles appear under a peer — **Commissions** (the brief) and **Commission Feedback** (the reactions) — both PostgreSQL-backed with soft-delete tombstones so removals propagate instead of resurrecting. Feedback moved out of an inline field into its own `commissionFeedback` record kind (one row per reaction, capped per commission); existing inline reactions are split into the federated store automatically at boot.diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 479570b46a..dcbdcd8ab7 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -527,6 +527,7 @@ const SYNC_CATEGORY_META = [{ key: 'writersRoomFolders', label: 'Writers Room Folders', icon: FolderTree, description: 'Writers Room library folders: names + nesting (PostgreSQL)' },{ key: 'writersRoomExercises', label: 'Writers Room Sprints', icon: Timer, description: 'Writers Room writing-sprint sessions + appended prose (PostgreSQL)' },{ key: 'musicVideoProjects', label: 'Music Video', icon: Video, description: 'Music Video projects: director board + beat-aligned scenes (PostgreSQL)' },+ { key: 'creativeCommissions', label: 'Commissions', icon: Target, description: 'Creative Commission briefs (name + intent + genre + generation settings) — the schedule + run history stay machine-local (PostgreSQL)' },{ key: 'commissionFeedback', label: 'Commission Feedback', icon: Target, description: 'Creative Commission taste reactions that steer the next run — the schedule stays machine-local (PostgreSQL)' },{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }];@@ -534,7 +535,7 @@ const SYNC_CATEGORY_META = [// Snapshot categories — exclude the per-record / delta-based categories that// have no 60s snapshot checksum: brain + memory (delta), catalog + authors/music// (PostgreSQL, per-record peer-push only — no snapshot loop).-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback']);+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions']);const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));// Indicator backed by REAL coverage diffing (record IDs vs confirmed pushes),diff --git a/scripts/migrations/194-commission-feedback-federation.js b/scripts/migrations/194-commission-feedback-federation.jsindex 6967ed0e75..427e5022ca 100644--- a/scripts/migrations/194-commission-feedback-federation.js+++ b/scripts/migrations/194-commission-feedback-federation.js@@ -23,10 +23,18 @@* `data/migrations.applied.json` so the migration ledger and `git log` show when* commission feedback began federating. No-op + idempotent: nothing to do here.*- * NOTE (schema-version bump): this change adds `commissionFeedback: 1` to- * `PORTOS_SCHEMA_VERSIONS` (server/lib/schemaVersions.js). No storage-layout- * migration is needed for that (it's a brand-new record kind, not a reshape of an- * existing on-disk store).+ * The commission BRIEF also federates now (record kind `creativeCommission`,+ * category `creativeCommissions`) so a synced reaction attaches to the same+ * commission on every peer — the `schedule`/`runs`/`assignment` stay+ * machine-local (stripped from the wire). That needs soft-delete tombstone+ * columns (`deleted`/`deleted_at`) on the existing `creative_commissions` table;+ * the idempotent `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` lives in ensureSchema+ * (server/lib/db.js) and runs at boot for installs predating the split.+ *+ * NOTE (schema-version bumps): this change adds `commissionFeedback: 1` AND+ * `creativeCommissions: 1` to `PORTOS_SCHEMA_VERSIONS` (server/lib/schemaVersions.js).+ * No storage-layout migration is needed for either (a brand-new record kind and an+ * additive tombstone-column upgrade, not a reshape of an existing on-disk store).*/export default {diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex c123487840..6c006d3b07 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -364,6 +364,10 @@ export const RESTORABLE_FIELDS = Object.freeze({// the Conflicts UI may restore are the rating + its note/tags. `commissionId`/// `runId` are structural keys (they address the reaction) and are excluded.commissionFeedback: ['rating', 'note', 'tags'],+ // A creativeCommission (#2686) restores its federated BRIEF fields; the+ // machine-local schedule/runs/assignment are never in a snapshot (stripped from+ // the wire) so they're excluded.+ creativeCommission: ['name', 'enabled', 'targetAbility', 'brief', 'generation', 'feedbackWindow'],// Writers Room exercises (#1645): the user-authored sprint fields the merge can// restore through `restoreExercise` — the appended prose + the sprint config.// Server-owned / structural fields are excluded (`id`/`createdAt`/`startedAt`/diff --git a/server/lib/db.js b/server/lib/db.jsindex 1a4bf7735b..f5e5adf6fc 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -474,9 +474,16 @@ async function ensureSchemaImpl() {enabled BOOLEAN NOT NULL DEFAULT TRUE,data JSONB NOT NULL,created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ)`,`CREATE INDEX IF NOT EXISTS idx_creative_commissions_enabled ON creative_commissions (enabled)`,+ // The commission BRIEF federates as of #2686 (record kind `creativeCommission`,+ // schedule/runs/assignment stay machine-local) — a delete must tombstone so it+ // propagates. Idempotent upgrade for installs predating the split.+ `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,+ `ALTER TABLE creative_commissions ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,// Creative Commission FEEDBACK — the split-record federation half (#2686).// Unlike the machine-local commission above, taste reactions FEDERATE so a// 👍/👎 rated on one machine conditions the same commission's next run ondiff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex fb8c8ff34d..ddd276157d 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', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -262,6 +262,11 @@ const commissionFeedbackPushSchema = z.object({kind: z.literal('commissionFeedback'),...peerSyncPushBase,}).strict();+// Creative Commission brief (#2686) — body-less; the sender ships `assetManifest: []`.+const creativeCommissionPushSchema = z.object({+ kind: z.literal('creativeCommission'),+ ...peerSyncPushBase,+}).strict();export const peerSyncPushSchema = z.discriminatedUnion('kind', [universePushSchema,seriesPushSchema,@@ -277,13 +282,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [writersRoomExercisePushSchema,musicVideoProjectPushSchema,commissionFeedbackPushSchema,+ creativeCommissionPushSchema,]);// 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', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),recordId: z.string().trim().min(1).max(200),}).strict();diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 94ca81b86b..70b44b4058 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -410,6 +410,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// LWW with soft-delete tombstones — the merge never propagates a hard delete.// The FIRST incompatible reaction-shape change MUST bump this to 2.commissionFeedback: 1,+ // v1 = Creative Commission BRIEF federation (PostgreSQL `creative_commissions`)+ // via the per-record peer-sync push pipeline (record kind `creativeCommission`,+ // sync category `creativeCommissions`, #2686). The brief/identity federates so a+ // synced reaction attaches to the SAME commission on every peer, while+ // `schedule`/`runs`/`assignment` stay MACHINE-LOCAL (stripped from the wire —+ // see syncWire's `creativeCommission` case) so only the owning machine fires the+ // cron (no double-run). Soft-delete tombstones; the FIRST incompatible+ // brief-shape change MUST bump this to 2.+ creativeCommissions: 1,// v1 = standalone media-library federation (#1566). NOT a record kind — it's// the wire contract for the library-level asset manifest a full-sync peer// advertises at GET /api/peer-sync/library-manifest. The receiver-pull sweep@@ -511,6 +520,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({writersRoomExercise: Object.freeze(['writersRoomExercises']),musicVideoProject: Object.freeze(['musicVideoProjects']),commissionFeedback: Object.freeze(['commissionFeedback']),+ creativeCommission: Object.freeze(['creativeCommissions']),});/**diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex fac06bc3c2..298f26bc2f 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -203,6 +203,21 @@ export function sanitizeRecordForWire(kind, record) {}return { ...rest, ...sanitizeSoftDeleteFields(record) };}+ case 'creativeCommission': {+ // The commission BRIEF federates (#2686) so a synced reaction attaches to+ // the SAME commission on every peer — but `schedule`, `runs`, and+ // `assignment` are MACHINE-LOCAL and MUST NOT transit: a federated schedule+ // would double-run on every peer (the whole reason the commission was+ // machine-local pre-#2686), `runs` is per-machine execution history, and+ // `assignment` pins a provider/model that may not exist on the peer. Strip+ // all three from the wire; the receiver carries its OWN values forward on+ // merge (preserveLocalCommissionFields). `feedback` also never rides here —+ // it federates as its own `commissionFeedback` record kind. Whole-record LWW+ // over what remains (id/name/enabled/targetAbility/brief/generation/+ // feedbackWindow), hashed in full by contentHashForRecord.+ const { deleted: _d, deletedAt: _da, schedule: _s, runs: _r, assignment: _a, feedback: _f, ...rest } = record;+ return { ...rest, ...sanitizeSoftDeleteFields(record) };+ }default:return null;}diff --git a/server/routes/instances.js b/server/routes/instances.jsindex b2cb08d301..23ffd7e86e 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -72,6 +72,7 @@ const syncCategoriesSchema = z.object({writersRoomExercises: z.boolean().optional(),musicVideoProjects: z.boolean().optional(),commissionFeedback: z.boolean().optional(),+ creativeCommissions: z.boolean().optional(),catalog: z.boolean().optional()}).optional();diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex b711673f3e..cb83d57c13 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -40,6 +40,7 @@ import { updateProject as updateMusicVideoProject } from './musicVideo/projects.import { restoreBoard } from './moodBoard/index.js';import { updateWork, restoreFolder, restoreExercise } from './writersRoom/local.js';import { restoreCommissionFeedback } from './creativeCommissions/feedbackStore.js';+import { restoreCommission } from './creativeCommissions/store.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';@@ -170,6 +171,12 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// the route serves a clean 409 (#2686).const restored = await restoreCommissionFeedback(recordId, patch).catch(translateGone);if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ } else if (kind === 'creativeCommission') {+ // restoreCommission merges the snapshot's brief fields, un-tombstones, and+ // bumps updatedAt so the restore wins the next LWW. Machine-local schedule/+ // runs/assignment are kept as-is. Returns null for a missing record (#2686).+ const restored = await restoreCommission(recordId, patch).catch(translateGone);+ if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);} else {throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}diff --git a/server/services/creativeCommissions/db.js b/server/services/creativeCommissions/db.jsindex e6f85e6f24..f7193ea7f4 100644--- a/server/services/creativeCommissions/db.js+++ b/server/services/creativeCommissions/db.js@@ -24,35 +24,59 @@import { query } from '../../lib/db.js';import { mirrorTimestamp } from '../../lib/pgTimestamp.js';-/** Raw stored record (the `data` JSONB), or null. No sanitize. */-export async function readRaw(id) {- const { rows } = await query(`SELECT data FROM creative_commissions WHERE id = $1`, [id]);+/** Raw stored record (the `data` JSONB), or null. Live only unless includeDeleted (#2686). */+export async function readRaw(id, { includeDeleted = false } = {}) {+ const { rows } = await query(+ includeDeleted+ ? `SELECT data FROM creative_commissions WHERE id = $1`+ : `SELECT data FROM creative_commissions WHERE id = $1 AND deleted = FALSE`,+ [id],+ );return rows[0]?.data ?? null;}-/** Every commission's raw `data` JSONB, oldest first (stable create order). */-export async function listRaw() {- const { rows } = await query(`SELECT data FROM creative_commissions ORDER BY created_at ASC, id ASC`);+/** Every commission's raw `data` JSONB, oldest first. Live only unless includeDeleted. */+export async function listRaw({ includeDeleted = false } = {}) {+ const { rows } = await query(+ includeDeleted+ ? `SELECT data FROM creative_commissions ORDER BY created_at ASC, id ASC`+ : `SELECT data FROM creative_commissions WHERE deleted = FALSE ORDER BY created_at ASC, id ASC`,+ );return rows.map((r) => r.data);}+/** Every commission id — live only by default, or all (incl. tombstones) for the sweep. */+export async function listIds({ includeDeleted = false } = {}) {+ const { rows } = await query(+ includeDeleted+ ? `SELECT id FROM creative_commissions`+ : `SELECT id FROM creative_commissions WHERE deleted = FALSE`,+ );+ return rows.map((r) => r.id);+}+/*** Upsert one record. `data` is written verbatim (lossless); the typed mirror* columns are bind-sanitized so a hand-edited/legacy record with a malformed* timestamp can't make the write throw. `created_at` is preserved on conflict- * (only the first INSERT sets it).+ * (only the first INSERT sets it). The soft-delete pair (#2686) is mirrored into+ * columns for the sweep AND stays in `data` (the sanitizer round-trips it).*/export async function writeRaw(id, record) {const now = new Date().toISOString();const createdAt = mirrorTimestamp(record?.createdAt, now);+ const deleted = record?.deleted === true;+ const deletedAt = deleted ? mirrorTimestamp(record?.deletedAt, now) : null;await query(- `INSERT INTO creative_commissions (id, name, enabled, data, created_at, updated_at)- VALUES ($1, $2, $3, $4::jsonb, $5, $6)+ `INSERT INTO creative_commissions (id, name, enabled, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)ON CONFLICT (id) DO UPDATE SETname = EXCLUDED.name,enabled = EXCLUDED.enabled,data = EXCLUDED.data,- updated_at = EXCLUDED.updated_at`,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,[id,typeof record?.name === 'string' ? record.name : '',@@ -60,12 +84,28 @@ export async function writeRaw(id, record) {JSON.stringify(record),createdAt,mirrorTimestamp(record?.updatedAt, createdAt),+ deleted,+ deletedAt,],);return record;}-/** Hard-delete a record. Idempotent — a missing row is a no-op. */+/** Hard-delete a record (used by the tombstone sweep). Idempotent — a missing row is a no-op. */export async function deleteRaw(id) {await query(`DELETE FROM creative_commissions WHERE id = $1`, [id]);}++/** Hard-remove tombstoned commissions whose `deleted_at` is older than the cutoff; returns their ids. */+export async function pruneTombstoned(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };+ const cutoffIso = new Date(olderThanMs).toISOString();+ const { rows } = await query(+ `DELETE FROM creative_commissions+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1+ RETURNING id`,+ [cutoffIso],+ );+ const ids = rows.map((r) => r.id);+ return { pruned: ids.length, ids };+}diff --git a/server/services/creativeCommissions/feedbackStore.js b/server/services/creativeCommissions/feedbackStore.jsindex 30e199cb80..ba7327a822 100644--- a/server/services/creativeCommissions/feedbackStore.js+++ b/server/services/creativeCommissions/feedbackStore.js@@ -47,6 +47,13 @@ import {export const TYPE = 'commission-feedback';export const FEEDBACK_SCHEMA_VERSION = 1;+// Per-commission cap on LIVE reactions — preserves the pre-#2686 inline+// MAX_PERSISTED_FEEDBACK bound so a long-lived nightly commission's feedback+// table can't grow without limit. Enforced sync-safely: the oldest excess+// reactions are TOMBSTONED (not array-dropped), so the cap propagates to peers+// via the normal tombstone path (the directive only ever reads the last+// `feedbackWindow` reactions anyway, so aging out the oldest is invisible).+export const MAX_LIVE_FEEDBACK_PER_COMMISSION = 100;const isStr = (v) => typeof v === 'string';const notDeleted = (r) => r && r.deleted !== true;@@ -172,12 +179,37 @@ export async function recordFeedback({ commissionId, runId = null, rating, notereturn record;});if (!result) return null;- // Push to every subscribed peer so the reaction (and later its tombstone)- // propagates without waiting for a reconnect — mirrors writersRoomFolder.+ // Subscribe every peer to this new record id, AND emit an update. autoSubscribe+ // only pushes to peers whose subscription is newly created — so a RE-RATING+ // (same deterministic id, already subscribed) would push NOTHING and peers keep+ // the stale reaction. emitRecordUpdated pushes the revised record to every+ // existing subscription, so a changed rating/note actually propagates.autoSubscribeRecordToAllPeers(COMMISSION_FEEDBACK_KIND, id).catch(() => {});+ emitRecordUpdated(COMMISSION_FEEDBACK_KIND, id);+ // Enforce the per-commission live cap sync-safely (tombstone the oldest excess).+ await enforceFeedbackCap(commissionId).catch(() => {});return result;}+/**+ * Keep a commission's LIVE reactions at or below MAX_LIVE_FEEDBACK_PER_COMMISSION+ * by TOMBSTONING the oldest excess (a re-rating reuses its run's id, so only+ * distinct newly-rated runs grow the count). Tombstoning — not array removal —+ * keeps the cap sync-safe: the removal federates via the normal tombstone path+ * instead of a peer resurrecting the aged-out reaction on the next sync.+ */+async function enforceFeedbackCap(commissionId) {+ const live = (await feedbackStore().listRawByCommission(commissionId))+ .map(sanitizeCommissionFeedbackForSync)+ .filter(Boolean)+ .sort((a, b) => String(a.at).localeCompare(String(b.at)));+ const excess = live.length - MAX_LIVE_FEEDBACK_PER_COMMISSION;+ if (excess <= 0) return;+ for (const rec of live.slice(0, excess)) {+ await deleteCommissionFeedback(rec.id).catch(() => {});+ }+}+/*** The inline `feedback[]` view for one commission (oldest reaction first), mapped* to the `{ id, runId, rating, note, tags, at }` shape directive.js + the clientdiff --git a/server/services/creativeCommissions/feedbackStore.test.js b/server/services/creativeCommissions/feedbackStore.test.jsindex 79d569cdb7..e9fe6b7265 100644--- a/server/services/creativeCommissions/feedbackStore.test.js+++ b/server/services/creativeCommissions/feedbackStore.test.js@@ -68,6 +68,21 @@ describe('recordFeedback + hydration', () => {expect(await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 0 })).toBeNull();});+ it('caps live reactions per commission by tombstoning the oldest excess (sync-safe bound)', async () => {+ const { MAX_LIVE_FEEDBACK_PER_COMMISSION } = await import('./feedbackStore.js');+ const N = MAX_LIVE_FEEDBACK_PER_COMMISSION + 3;+ for (let i = 0; i < N; i++) {+ await recordFeedback({ commissionId: 'c1', runId: `run-${String(i).padStart(4, '0')}`, rating: 'up', at: new Date(2026, 0, 1, 0, i).toISOString() });+ }+ const live = await listFeedbackForCommission('c1');+ expect(live).toHaveLength(MAX_LIVE_FEEDBACK_PER_COMMISSION);+ // The 3 oldest runs were tombstoned (not array-dropped) — their rows survive with deleted:true.+ expect(live.some((f) => f.runId === 'run-0000')).toBe(false);+ expect(feedbackRecords.get('cfeedback-run-0000')).toMatchObject({ deleted: true });+ // The newest survives.+ expect(live.some((f) => f.runId === `run-${String(N - 1).padStart(4, '0')}`)).toBe(true);+ });+it('hydrates only the requested commission and orders oldest-first', async () => {await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'a' });await recordFeedback({ commissionId: 'c2', runId: 'run-B', rating: 'down', note: 'b' });diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 5e39534c53..4b3e963f34 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -47,6 +47,15 @@ import { createCollectionStore } from '../../lib/collectionStore.js';import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/pgFileFacade.js';import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';import { isValidCron } from '../eventScheduler.js';+import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import {+ contentHashForRecord,+ setSyncBaseHash,+ deleteSyncBaseHash,+ flushBaseHashes,+ maybeJournalBeforeOverwrite,+} from '../../lib/conflictJournal.js';+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { commissionToCron } from './directive.js';import {recordFeedback,@@ -167,9 +176,60 @@ export function sanitizeCommission(raw) {runs: Array.isArray(raw.runs) ? raw.runs.slice(-MAX_PERSISTED_RUNS) : [],createdAt: isStr(raw.createdAt) ? raw.createdAt : now,updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : (isStr(raw.createdAt) ? raw.createdAt : now),+ // Soft-delete tombstone trio (#2686). The commission BRIEF federates so it+ // exists on every peer (letting a synced reaction attach to the same+ // commission); a delete must therefore propagate as a tombstone, not a hard+ // delete the LWW merge would never carry. `schedule`/`runs`/`assignment` stay+ // machine-local (stripped from the wire — see syncWire's `creativeCommission`+ // case + preserveLocalCommissionFields), so only the OWNING machine fires the+ // cron (no double-run). Pre-#2686 records carry neither field → live.+ deleted: raw.deleted === true,+ deletedAt: raw.deleted === true && isStr(raw.deletedAt) ? raw.deletedAt : null,};}+// The peer-sync record kind + id shape for the federated commission brief (#2686).+export const CREATIVE_COMMISSION_KIND = 'creativeCommission';+export const COMMISSION_ID_RE = /^commission-[0-9a-z-]+$/i;++/**+ * Normalize a raw commission into the canonical wire/stored shape for a sync+ * round-trip (drop-on-floor for a non-object / bad id). Reuses sanitizeCommission+ * (which now normalizes the soft-delete trio) — the machine-local fields+ * (schedule/runs/assignment) are stripped from the actual WIRE form by syncWire's+ * `creativeCommission` case, and carried forward from the local copy on merge by+ * preserveLocalCommissionFields, so they never transit or reset a peer's schedule.+ */+export function sanitizeCommissionForSync(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ if (!isStr(raw.id) || !COMMISSION_ID_RE.test(raw.id)) return null;+ return sanitizeCommission(raw);+}++/** Re-attach the receiver's local-only schedule/runs/assignment onto a winning remote. */+function preserveLocalCommissionFields(remote, local) {+ if (!local) return remote;+ return { ...remote, schedule: local.schedule, runs: local.runs, assignment: local.assignment };+}++/**+ * LWW merge decision for one incoming commission (mirrors mergeWorkRecord): the+ * remote is sanitized here (drop-on-floor → null), a missing local inserts it,+ * else newer `updatedAt` wins. When the remote wins, the receiver's own+ * machine-local schedule/runs/assignment are carried forward (the wire form never+ * carried them), so a peer's brief edit can't reset this machine's schedule.+ */+export function mergeCommissionRecord(local, remoteRaw) {+ const remote = sanitizeCommissionForSync(remoteRaw);+ if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };+ if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };+ const localKey = sanitizeCommission(local)?.updatedAt ?? local.updatedAt;+ const remoteWins = compareNewerWins(remote.updatedAt, localKey);+ const next = remoteWins ? preserveLocalCommissionFields(remote, sanitizeCommission(local)) : local;+ const changed = JSON.stringify(next) !== JSON.stringify(local);+ return { next, inserted: false, remoteWins, changed };+}+// --- File backend (dev/test escape hatch): wraps collectionStore ---// No sanitizer on the collectionStore — the facade sanitizes uniformly on the// service side so file and PG return an identical shape. The type-level index is@@ -186,12 +246,26 @@ function makeFileBackend(dir) {stamped = true;await cs.saveTypeIndex({}).catch(() => { stamped = false; });};+ const live = (r) => r && r.deleted !== true;return {name: 'file',- listRaw: () => cs.loadAll(),- readRaw: (id) => cs.loadOne(id),+ listRaw: async ({ includeDeleted = false } = {}) =>+ (await cs.loadAll()).filter((r) => includeDeleted || live(r)),+ readRaw: async (id, { includeDeleted = false } = {}) => {+ const rec = await cs.loadOne(id);+ if (!rec) return null;+ return includeDeleted || live(rec) ? rec : null;+ },+ listIds: async ({ includeDeleted = false } = {}) =>+ (await cs.loadAll()).filter((r) => includeDeleted || live(r)).map((r) => r.id),writeRaw: async (id, record) => { await ensureTypeIndex(); await cs.saveOneNow(id, record); return record; },deleteRaw: (id) => cs.deleteOneNow(id),+ pruneTombstoned: async (olderThanMs) => {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };+ const stale = (await cs.loadAll()).filter((r) => r?.deleted === true && isStr(r.deletedAt) && Date.parse(r.deletedAt) < olderThanMs);+ for (const r of stale) await cs.deleteOneNow(r.id);+ return { pruned: stale.length, ids: stale.map((r) => r.id) };+ },verify: () => cs.verifySchemaVersion(),};}@@ -204,8 +278,10 @@ function makePgBackend(db) {name: 'postgres',listRaw: db.listRaw,readRaw: db.readRaw,+ listIds: db.listIds,writeRaw: db.writeRaw,deleteRaw: db.deleteRaw,+ pruneTombstoned: db.pruneTombstoned,};}@@ -243,10 +319,12 @@ function createFacade(dir) {dir,type: TYPE,getBackendName,- listRaw: async () => (await getBackend()).listRaw(),- readRaw: async (id) => (await getBackend()).readRaw(id),+ listRaw: async (opts) => (await getBackend()).listRaw(opts),+ readRaw: async (id, opts) => (await getBackend()).readRaw(id, opts),+ listIds: async (opts) => (await getBackend()).listIds(opts),writeRaw: async (id, record) => (await getBackend()).writeRaw(id, record),deleteRaw: async (id) => (await getBackend()).deleteRaw(id),+ pruneTombstoned: async (olderThanMs) => (await getBackend()).pruneTombstoned(olderThanMs),queueRecordWrite,// Under PG, report ok WITHOUT forcing backend selection (the early boot// verifier runs before the dbReady gate); under the file escape hatch, read@@ -360,6 +438,12 @@ export async function createCommission(input) {const record = sanitizeCommission({ ...input, id, createdAt: now, updatedAt: now });await commissionStore().writeRaw(id, record);commissionEvents.emit('commission:changed', { id, action: 'create' });+ // Federate the commission BRIEF (#2686) so it exists on every peer and a synced+ // reaction can attach to the same commission. The schedule/runs/assignment stay+ // machine-local (stripped from the wire), so the peer holds the brief but never+ // fires the cron.+ autoSubscribeRecordToAllPeers(CREATIVE_COMMISSION_KIND, id).catch(() => {});+ emitRecordUpdated(CREATIVE_COMMISSION_KIND, id);return record;}@@ -406,25 +490,34 @@ export async function updateCommission(id, patch) {});if (!merged) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);commissionEvents.emit('commission:changed', { id, action: 'update' });+ // Push the brief change to subscribed peers (the schedule/runs/assignment are+ // stripped from the wire, so only the brief travels).+ emitRecordUpdated(CREATIVE_COMMISSION_KIND, id);return merged;}export async function deleteCommission(id) {const store = commissionStore();- // Serialize the read+delete on the SAME per-id write queue as- // update/recordRun/submitFeedback. Otherwise an in-flight feedback write (its- // own queued read→writeRaw) could interleave with a delete that runs outside- // the queue: feedback reads the row, delete hard-deletes it, feedback's- // writeRaw then upserts the stale record and resurrects the commission. With- // delete on the tail, a feedback write queued after it finds no row and 404s.+ // SOFT-delete (tombstone) now that the commission BRIEF federates (#2686): a+ // hard delete would never propagate (the LWW merge only adds/updates), so an+ // out-of-date peer would resurrect the commission on the next sync. Tombstone+ // instead — the deletion rides the same push path and the peer converges.+ // Serialized on the SAME per-id write queue as update/recordRun/submitFeedback+ // so an in-flight feedback/run write can't interleave and resurrect a live row.const existed = await store.queueRecordWrite(id, async () => {- const current = await store.readRaw(id);- if (!current) return false;- await store.deleteRaw(id);+ const currentRaw = await store.readRaw(id);+ if (!currentRaw) return false;+ const current = sanitizeCommission(currentRaw);+ if (current.deleted) return false;+ const now = new Date().toISOString();+ await store.writeRaw(id, { ...current, deleted: true, deletedAt: now, updatedAt: now });return true;});if (!existed) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ // Re-sync schedules (the scheduler cancels the now-tombstoned commission's cron)+ // and push the tombstone to peers.commissionEvents.emit('commission:changed', { id, action: 'delete' });+ emitRecordDeleted(CREATIVE_COMMISSION_KIND, id);return { id, deleted: true };}@@ -527,3 +620,95 @@ export async function backfillAllCommissionFeedback() {if (migrated > 0) console.log(`🎯 Commission feedback: split ${migrated} commission(s)' inline reactions into the federated store (#2686)`);return { migrated };}++// ---------- commission BRIEF federation facades (#2686) ----------+// The peer-sync layer imports these exactly as it imports writersRoom/sync.js.+// The commission record federates (so a synced reaction attaches to the same+// commission on every peer) while schedule/runs/assignment stay machine-local+// (stripped from the wire by syncWire, carried forward on merge).++/** One commission's sanitized record (tombstone surfaced), or null. */+export async function getCommissionForSync(id) {+ const raw = await commissionStore().readRaw(id, { includeDeleted: true });+ return raw ? sanitizeCommissionForSync(raw) : null;+}++/** Every LIVE commission as `{ id, updatedAt }` for full-sync coverage compare. */+export async function listCommissionsForSync() {+ const raw = await commissionStore().listRaw();+ return raw.map(sanitizeCommissionForSync).filter(Boolean).map((r) => ({ id: r.id, updatedAt: r.updatedAt }));+}++/** Every commission id — live only by default, or all (incl. tombstones) for the sweep. */+export async function listCommissionIdsForSync(options = {}) {+ return commissionStore().listIds(options);+}++/**+ * Merge an incoming batch of commission records from a peer (LWW, tombstone-aware).+ * Serialized per-id on the same write queue as the REST writers so a user edit+ * can't clobber the merge. Journals the about-to-be-overwritten local version+ * when the remote wins, seeds the conflict-journal base hash, and re-syncs the+ * scheduler (a merged brief/tombstone can change what's armed). Mirrors+ * writersRoom's `mergeBodylessFromSync`, minus the PG row lock.+ */+export async function mergeCommissionsFromSync(remoteRecords, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteRecords)) return { applied: false, count: 0 };+ const store = commissionStore();+ let changed = 0;+ for (const remote of remoteRecords) {+ const id = remote?.id;+ if (!isStr(id) || !COMMISSION_ID_RE.test(id)) continue;+ const applied = await store.queueRecordWrite(id, async () => {+ const local = await store.readRaw(id, { includeDeleted: true });+ const { next, inserted, remoteWins, changed: didChange } = mergeCommissionRecord(local, remote);+ if (!next) return false;+ if (!inserted && (!remoteWins || !didChange)) return false;+ if (!inserted) {+ await maybeJournalBeforeOverwrite({ kind: CREATIVE_COMMISSION_KIND, id: next.id, local, remote: next, source });+ }+ await store.writeRaw(id, next);+ await setSyncBaseHash(CREATIVE_COMMISSION_KIND, next.id, contentHashForRecord(CREATIVE_COMMISSION_KIND, next));+ return true;+ });+ if (applied) changed += 1;+ }+ await flushBaseHashes();+ if (changed > 0) commissionEvents.emit('commission:changed', { action: 'merge' });+ return changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };+}++/** Hard-remove tombstoned commissions older than the cutoff; evicts each base hash. */+export async function pruneTombstonedCommissions(olderThanMs) {+ const result = await commissionStore().pruneTombstoned(olderThanMs);+ for (const id of result.ids || []) await deleteSyncBaseHash(CREATIVE_COMMISSION_KIND, id).catch(() => {});+ return result;+}++/**+ * Restore a tombstoned/edited commission from a conflict-journal snapshot. Merges+ * the RESTORABLE brief fields, un-tombstones, bumps updatedAt so the restore wins+ * the next LWW and re-pushes. Returns null for a missing record (→ ERR_TARGET_GONE).+ */+export async function restoreCommission(id, patch) {+ const store = commissionStore();+ const result = await store.queueRecordWrite(id, async () => {+ const currentRaw = await store.readRaw(id, { includeDeleted: true });+ if (!currentRaw) return null;+ const current = sanitizeCommission(currentRaw);+ const next = sanitizeCommission({+ ...current,+ ...(patch && typeof patch === 'object' ? patch : {}),+ id, createdAt: current.createdAt,+ // Never let a snapshot restore resurrect the machine-local fields — keep ours.+ schedule: current.schedule, runs: current.runs, assignment: current.assignment,+ deleted: false, deletedAt: null, updatedAt: new Date().toISOString(),+ });+ await store.writeRaw(id, next);+ return next;+ });+ if (!result) return null;+ commissionEvents.emit('commission:changed', { id, action: 'restore' });+ emitRecordUpdated(CREATIVE_COMMISSION_KIND, id);+ return result;+}diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex a7594e421d..3dc147d36b 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -23,6 +23,19 @@ const makeMemStore = (type) => {};vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: ({ type }) => makeMemStore(type) }));vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data' } }));+// Keep the federation side-effects (peer push, conflict-journal disk I/O) inert+// so the store unit tests stay deterministic and offline.+vi.mock('../sharing/recordEvents.js', () => ({+ emitRecordUpdated: vi.fn(), emitRecordDeleted: vi.fn(),+ autoSubscribeRecordToAllPeers: vi.fn(() => Promise.resolve()),+}));+vi.mock('../../lib/conflictJournal.js', () => ({+ contentHashForRecord: vi.fn(() => 'hash'),+ setSyncBaseHash: vi.fn(() => Promise.resolve()),+ deleteSyncBaseHash: vi.fn(() => Promise.resolve()),+ flushBaseHashes: vi.fn(() => Promise.resolve()),+ maybeJournalBeforeOverwrite: vi.fn(() => Promise.resolve()),+}));const {sanitizeCommission,@@ -36,6 +49,10 @@ const {recordCommissionRun,submitCommissionFeedback,backfillAllCommissionFeedback,+ sanitizeCommissionForSync,+ mergeCommissionRecord,+ getCommissionForSync,+ mergeCommissionsFromSync,ERR_VALIDATION,ERR_NOT_FOUND,} = await import('./store.js');@@ -202,11 +219,22 @@ describe('recordCommissionRun', () => {});describe('deleteCommission', () => {- it('removes the record', async () => {+ it('SOFT-deletes (tombstones) the record so the deletion federates (#2686)', async () => {const created = await createCommission(validInput());const r = await deleteCommission(created.id);expect(r).toEqual({ id: created.id, deleted: true });- expect(records.has(created.id)).toBe(false);+ // The row survives as a tombstone (LWW never propagates a hard delete), but+ // it's excluded from live reads.+ expect(records.get(created.id)).toMatchObject({ deleted: true });+ expect(typeof records.get(created.id).deletedAt).toBe('string');+ await expect(getCommission(created.id)).rejects.toMatchObject({ code: ERR_NOT_FOUND });+ expect((await listCommissions()).some((c) => c.id === created.id)).toBe(false);+ });++ it('a second delete of an already-tombstoned commission 404s', async () => {+ const created = await createCommission(validInput());+ await deleteCommission(created.id);+ await expect(deleteCommission(created.id)).rejects.toMatchObject({ code: ERR_NOT_FOUND });});});@@ -245,6 +273,57 @@ describe('sanitizeCommission (feedback)', () => {});});+describe('commission BRIEF federation (#2686)', () => {+ it('sanitizeCommissionForSync normalizes the soft-delete trio and drops a bad id', () => {+ expect(sanitizeCommissionForSync({ id: 'not-a-commission' })).toBeNull();+ const rec = sanitizeCommissionForSync({ id: 'commission-x', name: 'Nightly' });+ expect(rec).toMatchObject({ id: 'commission-x', deleted: false, deletedAt: null });+ });++ it('mergeCommissionRecord inserts a remote and preserves LOCAL schedule/runs/assignment on a remote win', () => {+ const local = sanitizeCommission({+ id: 'commission-x', name: 'Local', updatedAt: '2026-01-01T00:00:00.000Z',+ schedule: { kind: 'DAILY', atLocalTime: '02:00' }, runs: [{ id: 'run-1', status: 'ok' }],+ assignment: { providerId: 'claude', model: 'opus' },+ });+ // Remote is the WIRE form (schedule/runs/assignment stripped) with a newer brief.+ const remote = { id: 'commission-x', name: 'Renamed on peer', brief: { intent: 'surreal' }, updatedAt: '2026-06-06T00:00:00.000Z' };+ const { next, remoteWins } = mergeCommissionRecord(local, remote);+ expect(remoteWins).toBe(true);+ expect(next.name).toBe('Renamed on peer');+ expect(next.brief.intent).toBe('surreal');+ // Machine-local fields carried forward from LOCAL, not reset by the remote.+ expect(next.schedule.atLocalTime).toBe('02:00');+ expect(next.runs).toHaveLength(1);+ expect(next.assignment.providerId).toBe('claude');+ });++ it('a stale remote loses to a newer local (no clobber)', () => {+ const local = sanitizeCommission({ id: 'commission-x', name: 'Newer', updatedAt: '2026-09-09T00:00:00.000Z' });+ const remote = { id: 'commission-x', name: 'Older', updatedAt: '2020-01-01T00:00:00.000Z' };+ const { next, remoteWins } = mergeCommissionRecord(local, remote);+ expect(remoteWins).toBe(false);+ expect(next.name).toBe('Newer');+ });++ it('mergeCommissionsFromSync inserts a remote commission the peer can now attach feedback to', async () => {+ const remote = { id: 'commission-peer', name: 'From peer A', brief: { intent: 'dreamlike' }, updatedAt: '2026-05-05T00:00:00.000Z' };+ const res = await mergeCommissionsFromSync([remote], { source: { via: 'sync', peerId: 'peer-a' } });+ expect(res).toEqual({ applied: true, count: 1 });+ const got = await getCommission('commission-peer');+ expect(got.name).toBe('From peer A');+ // Inserted with no schedule → the receiver won't fire it (no double-run).+ expect(got.schedule.atLocalTime).toBeNull();+ });++ it('getCommissionForSync surfaces a tombstone after delete', async () => {+ const created = await createCommission(validInput());+ await deleteCommission(created.id);+ const wire = await getCommissionForSync(created.id);+ expect(wire).toMatchObject({ id: created.id, deleted: true });+ });+});+describe('legacy inline feedback → federated split (#2686)', () => {// Seed a pre-#2686 record that still carries INLINE feedback (Phase 2 storage),// written straight into the machine-local commission map.diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex ef71e1f130..17dc561abe 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1128,6 +1128,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// file-snapshot category). Gated at applyIncomingPush via// compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.commissionFeedback.'commissionFeedback',+ // Creative Commission brief (#2686) → per-record peer-push only (no 60s+ // file-snapshot category). Gated at applyIncomingPush via+ // compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.creativeCommission.+ 'creativeCommissions',// Standalone media library (#1566) → its own receiver-pull endpoint// (GET /api/peer-sync/library-manifest), NOT the file-snapshot transfer.// Versioned for the manifest envelope and gated by syncMediaLibraryFromPeer'sdiff --git a/server/services/instances.js b/server/services/instances.jsindex b544fd6030..5e6f418281 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -281,6 +281,7 @@ const DEFAULT_SYNC_CATEGORIES = {writersRoomExercises: false,musicVideoProjects: false,commissionFeedback: false,+ creativeCommissions: false,catalog: false};@@ -319,6 +320,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([['writersRoomExercises', 'writersRoomExercise'],['musicVideoProjects', 'musicVideoProject'],['commissionFeedback', 'commissionFeedback'],+ ['creativeCommissions', 'creativeCommission'],]);export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 3ac9a31a97..823dc416e8 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -39,6 +39,7 @@ import { listProjects as listMusicVideoProjects } from '../musicVideo/projects.jimport { listBoards } from '../moodBoard/index.js';import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';+import { listCommissionsForSync } from '../creativeCommissions/store.js';import { initCursor, removeCursor as removeTombstoneCursor } from './peerTombstoneCursors.js';import {PEER_SUBSCRIBABLE_KINDS,@@ -395,6 +396,10 @@ async function listRecordsForKind(recordKind) {// Live feedback reactions as { id, updatedAt } (#2686) — same coverage-compare// reason as folders. Body-less, so no asset manifest backfill.records = await listCommissionFeedbackForSync().catch(() => []);+ } else if (recordKind === 'creativeCommission') {+ // Live commission briefs as { id, updatedAt } (#2686). Body-less on the wire+ // (schedule/runs/assignment stripped), so no asset manifest backfill.+ records = await listCommissionsForSync().catch(() => []);}return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 671a59366d..7c4ae82352 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -159,6 +159,10 @@ vi.mock('../creativeCommissions/feedbackStore.js', async (importOriginal) => ({...(await importOriginal()),listCommissionFeedbackForSync: vi.fn().mockResolvedValue([]),}));+vi.mock('../creativeCommissions/store.js', async (importOriginal) => ({+ ...(await importOriginal()),+ listCommissionsForSync: vi.fn().mockResolvedValue([]),+}));vi.mock('../../lib/peerHttpClient.js', async () => ({peerFetch: vi.fn(),@@ -241,6 +245,7 @@ import { listProjects as listCreativeDirectorProjects } from '../creativeDirectoimport { listBoards } from '../moodBoard/index.js';import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';+import { listCommissionsForSync } from '../creativeCommissions/store.js';import { peerFetch } from '../../lib/peerHttpClient.js';import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';import { getBackendName } from '../memoryBackend.js';@@ -350,6 +355,7 @@ beforeEach(async () => {vi.mocked(listFoldersForSync).mockReset().mockResolvedValue([]);vi.mocked(listExercisesForSync).mockReset().mockResolvedValue([]);vi.mocked(listCommissionFeedbackForSync).mockReset().mockResolvedValue([]);+ vi.mocked(listCommissionsForSync).mockReset().mockResolvedValue([]);// Catalog bundle defaults: non-postgres backend (no bundle), empty DB read,// no-op apply. The catalog-bundle suite overrides these per-test.vi.mocked(getBackendName).mockReset().mockReturnValue('file');@@ -396,7 +402,7 @@ describe('peerSync', () => {// 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', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);});});diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex d089cb9238..2010c157a7 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -46,6 +46,7 @@ import {getExerciseForSync,} from '../writersRoom/sync.js';import { getCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';+import { getCommissionForSync } from '../creativeCommissions/store.js';import { ackDeletesUpTo } from './peerTombstoneCursors.js';import {buildAssetManifestWithCollection,@@ -155,6 +156,10 @@ async function isSubscriptionRecordTombstone(sub) {const record = await getCommissionFeedbackForSync(sub.recordId).catch(() => null);return record?.deleted === true;}+ if (sub.recordKind === 'creativeCommission') {+ const record = await getCommissionForSync(sub.recordId).catch(() => null);+ return record?.deleted === true;+ }return false;}@@ -838,6 +843,15 @@ export async function buildPushPayload(sub, sourceInstanceId) {if (!sanitized) return null;return { kind: 'commissionFeedback', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };}+ if (sub.recordKind === 'creativeCommission') {+ // The commission BRIEF (#2686). sanitizeRecordForWire strips the machine-local+ // schedule/runs/assignment, so only the federatable brief travels. No assets.+ const record = await getCommissionForSync(sub.recordId).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('creativeCommission', record);+ if (!sanitized) return null;+ return { kind: 'creativeCommission', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };+ }return null;}diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex d400b7e624..a0e374aeb7 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -41,6 +41,7 @@ import {mergeExercisesFromSync,} from '../writersRoom/sync.js';import { getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';+import { getCommissionForSync, mergeCommissionsFromSync } from '../creativeCommissions/store.js';import {ackDeletesUpTo,} from './peerTombstoneCursors.js';@@ -321,6 +322,8 @@ export async function applyIncomingPush(payload) {workMergeApplied = mergeResult?.applied === true;} else if (kind === 'commissionFeedback') {await mergeCommissionFeedbackFromSync([record], { source });+ } else if (kind === 'creativeCommission') {+ await mergeCommissionsFromSync([record], { source });} else if (kind === 'writersRoomFolder') {await mergeFoldersFromSync([record], { source });} else if (kind === 'writersRoomExercise') {@@ -667,5 +670,11 @@ async function classifyLocalRecord(recordKind, recordId) {const fb = await getCommissionFeedbackForSync(recordId).catch(() => null);return fb ? 'syncable' : 'missing';}+ if (recordKind === 'creativeCommission') {+ // The commission brief (#2686) — no `ephemeral` concept; a found commission+ // (live or tombstoned) is always 'syncable'.+ const c = await getCommissionForSync(recordId).catch(() => null);+ return c ? 'syncable' : 'missing';+ }return 'missing';}\ No newline at end of filediff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.jsindex 5874d5ddbc..dd0fb116c9 100644--- a/server/services/sharing/peerSyncShared.js+++ b/server/services/sharing/peerSyncShared.js@@ -16,7 +16,7 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtilsimport { getPeers } from '../instances.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);/*** Cross-cutting event bus for the peer-sync receiver. The asset-pull worker@@ -102,6 +102,7 @@ export const KIND_TO_CATEGORY = Object.freeze({writersRoomExercise: 'writersRoomExercises',musicVideoProject: 'musicVideoProjects',commissionFeedback: 'commissionFeedback',+ creativeCommission: 'creativeCommissions',});export function peerAllowsOutbound(peer) {diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex 31ed4077b7..b225f5948b 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -58,6 +58,9 @@ import {import {pruneTombstonedCommissionFeedback, listCommissionFeedbackIdsForSync,} from '../creativeCommissions/feedbackStore.js';+import {+ pruneTombstonedCommissions, listCommissionIdsForSync,+} from '../creativeCommissions/store.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -85,6 +88,7 @@ const LIVE_ID_LISTERS = Object.freeze({writersRoomFolder: () => listFolderIdsForSync(),writersRoomExercise: () => listExerciseIdsForSync(),commissionFeedback: () => listCommissionFeedbackIdsForSync(),+ creativeCommission: () => listCommissionIdsForSync(),});// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —@@ -109,6 +113,7 @@ const ALL_ID_LISTERS = Object.freeze({writersRoomFolder: () => listFolderIdsForSync({ includeDeleted: true }),writersRoomExercise: () => listExerciseIdsForSync({ includeDeleted: true }),commissionFeedback: () => listCommissionFeedbackIdsForSync({ includeDeleted: true }),+ creativeCommission: () => listCommissionIdsForSync({ includeDeleted: true }),});// Build a kind-aware id-membership resolver for ONE sweep: lazily list each@@ -353,6 +358,7 @@ function refusedFromCutoffs(cutoffs) {folderCutoff,exerciseCutoff,commissionFeedbackCutoff,+ creativeCommissionCutoff,} = cutoffs;if (universeCutoff === null) refused.push('universe');// Issue tombstones ride series pushes — refused exactly when series is.@@ -375,6 +381,7 @@ function refusedFromCutoffs(cutoffs) {if (folderCutoff === null) refused.push('writersRoomFolder');if (exerciseCutoff === null) refused.push('writersRoomExercise');if (commissionFeedbackCutoff === null) refused.push('commissionFeedback');+ if (creativeCommissionCutoff === null) refused.push('creativeCommission');return refused;}@@ -406,6 +413,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =folderCutoff,exerciseCutoff,commissionFeedbackCutoff,+ creativeCommissionCutoff,] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs }),cutoffForKind('series', { peers, subs, now, graceMs }),@@ -421,9 +429,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs }),cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs }),cutoffForKind('commissionFeedback', { peers, subs, now, graceMs }),+ cutoffForKind('creativeCommission', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre, cfb] = await Promise.all([+ const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre, cfb, cc] = 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),@@ -439,6 +448,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =folderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(folderCutoff),exerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(exerciseCutoff),commissionFeedbackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissionFeedback(commissionFeedbackCutoff),+ creativeCommissionCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissions(creativeCommissionCutoff),]);// 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@@ -470,9 +480,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =writersRoomFolders: wrf.pruned,writersRoomExercises: wre.pruned,commissionFeedback: cfb.pruned,+ creativeCommissions: cc.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff }),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),};}@@ -481,7 +492,7 @@ 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, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),@@ -496,8 +507,9 @@ export async function getSweepStatus({ now = Date.now() } = {}) {cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs: 0 }),cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs: 0 }),cutoffForKind('commissionFeedback', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('creativeCommission', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff }) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex 1cda08216e..312169fad5 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -60,6 +60,10 @@ vi.mock('../creativeCommissions/feedbackStore.js', () => ({pruneTombstonedCommissionFeedback: vi.fn().mockResolvedValue({ pruned: 0 }),listCommissionFeedbackIdsForSync: vi.fn().mockResolvedValue([]),}));+vi.mock('../creativeCommissions/store.js', () => ({+ pruneTombstonedCommissions: vi.fn().mockResolvedValue({ pruned: 0 }),+ listCommissionIdsForSync: vi.fn().mockResolvedValue([]),+}));vi.mock('../../lib/conflictJournal.js', () => ({pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),}));@@ -469,6 +473,7 @@ describe('sweepTombstones — return shape', () => {writersRoomFolders: 11,writersRoomExercises: 12,commissionFeedback: 0,+ creativeCommissions: 0,orphanBaseHashes: 0,orphanSubscriptions: 0,refused: [],