Skip to content

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

feat([issue-2686]): federate Creative Commission feedback (schedule stays machine-local)

[._.]/ Adam Eivy0771314693eb
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 1acf1af3a6..479570b46a 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -527,13 +527,14 @@ 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: '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)' }
];
// 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']);
+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback']);
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.js
new file mode 100644
index 0000000000..6967ed0e75
--- /dev/null
+++ b/scripts/migrations/194-commission-feedback-federation.js
@@ -0,0 +1,36 @@
+/**
+ * Registration stub for Creative Commission feedback split-record federation
+ * (issue #2686, epic #2657 — Autonomous Creation Engine).
+ *
+ * Two things this change introduces, neither of which can run in the file-runner:
+ *
+ * 1. The `commission_feedback` table (+ its index). The DDL is idempotent and
+ * lives in `ensureSchema()` (`server/lib/db.js`), which runs at server boot
+ * AFTER the DB pool is up. The `scripts/migrations/` runner executes BEFORE
+ * the pool is initialized, so a table create cannot live here — the same
+ * reason migrations 048–052, 108, 160/161/162, 176, and 178 are boot-time +
+ * stub-registered.
+ *
+ * 2. The data backfill: splitting each commission's legacy INLINE `feedback[]`
+ * (Phase 2 storage) OUT into the new federated `commissionFeedback` record
+ * kind and clearing the inline array. That also needs the DB pool, so it
+ * runs at boot via `backfillAllCommissionFeedback()` (server/index.js, just
+ * before the commission scheduler arms) and is idempotent — after the first
+ * pass commissions carry `feedback: []`, so a re-run is a no-op, and the
+ * per-reaction upsert is never-clobber (a newer peer reaction always wins).
+ *
+ * This stub exists so the change is registered the standard way: it lands in
+ * `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).
+ */
+
+export default {
+ async up() {
+ console.log('🎯 commission_feedback: table created idempotently by ensureSchema at boot; inline→federated split runs via backfillAllCommissionFeedback — nothing to do in the file runner (#2686)');
+ },
+};
diff --git a/server/index.js b/server/index.js
index 684127d586..d51406afaa 100644
--- a/server/index.js
+++ b/server/index.js
@@ -212,7 +212,7 @@ import { verifyCollectionVersions } from './lib/collectionStore.js';
import { conflictJournalStore } from './lib/conflictJournal.js';
import { universeStore } from './services/universeBuilder.js';
import { seriesStore } from './services/pipeline/series.js';
-import { commissionStore } from './services/creativeCommissions/store.js';
+import { commissionStore, backfillAllCommissionFeedback } from './services/creativeCommissions/store.js';
import { issueStore } from './services/pipeline/issues.js';
import { storyBuilderStore } from './services/storyBuilder.js';
import { writersRoomStore } from './services/writersRoom/store.js';
@@ -648,6 +648,12 @@ startSeriesAutopilotScheduler().catch(err => console.error(`❌ Series Autopilot
// Commission. Boot only ARMS timers; nothing fires until a cadence elapses, and
// each fire gates on creative autonomy `execute` + the daily cos budget (so an
// `off`/`dry-run` install generates nothing). Sanctioned scheduled-automation.
+// Split any legacy INLINE commission feedback into the federated commissionFeedback
+// store (#2686) BEFORE arming the scheduler, so a fire reads the federated view.
+// Pure data movement (no LLM), idempotent, best-effort. The scripts/migrations
+// runner executes before the DB pool is up, so the data move lives here (see the
+// migration 194 registration stub); the table itself is created by ensureSchema.
+backfillAllCommissionFeedback().catch(err => console.error(`❌ Commission feedback backfill failed: ${err.message}`));
startCommissionScheduler().catch(err => console.error(`❌ Creative Commission scheduler init failed: ${err.message}`));
// Initialize CyberCity snapshot scheduler — records periodic city-state frames
// for the historical timeline scrubber (issue #877).
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index a6645f4994..c123487840 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -360,6 +360,10 @@ export const RESTORABLE_FIELDS = Object.freeze({
// is what the Conflicts UI offers for restore. `writersRoomFolder` matches the
// record kind.
writersRoomFolder: ['name', 'parentId', 'sortOrder'],
+ // A commissionFeedback (#2686) is one taste reaction — the user-authored fields
+ // 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'],
// 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.js
index 0226044cbd..1a4bf7735b 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -477,6 +477,25 @@ async function ensureSchemaImpl() {
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
`CREATE INDEX IF NOT EXISTS idx_creative_commissions_enabled ON creative_commissions (enabled)`,
+ // 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 on
+ // another. One row per reaction; the full sanitized record in `data` JSONB,
+ // with commission_id / run_id / created_at / updated_at mirrored for the
+ // per-commission hydration query, plus the soft-delete tombstone columns the
+ // LWW merge needs (a hard delete never propagates). Record kind
+ // `commissionFeedback`, sync category `commissionFeedback`.
+ `CREATE TABLE IF NOT EXISTS commission_feedback (
+ id TEXT PRIMARY KEY,
+ commission_id TEXT,
+ run_id TEXT,
+ data JSONB NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_commission_feedback_commission ON commission_feedback (commission_id, created_at)`,
];
for (const sql of upgrades) {
await pool.query(sql);
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index dccfe78864..fb8c8ff34d 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']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']),
recordId: z.string().trim().min(1).max(120),
}).strict();
@@ -256,6 +256,12 @@ const musicVideoProjectPushSchema = z.object({
...peerSyncPushBase,
...linkedTrackField,
}).strict();
+// Creative Commission feedback (#2686) — a body-less reaction record, no assets;
+// the sender always ships `assetManifest: []` (base still requires the field).
+const commissionFeedbackPushSchema = z.object({
+ kind: z.literal('commissionFeedback'),
+ ...peerSyncPushBase,
+}).strict();
export const peerSyncPushSchema = z.discriminatedUnion('kind', [
universePushSchema,
seriesPushSchema,
@@ -270,13 +276,14 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [
writersRoomFolderPushSchema,
writersRoomExercisePushSchema,
musicVideoProjectPushSchema,
+ commissionFeedbackPushSchema,
]);
// 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']),
+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']),
recordId: z.string().trim().min(1).max(200),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 981bad88ef..94ca81b86b 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -401,6 +401,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// it federates via its own channels / a follow-up. The FIRST incompatible
// project-shape change MUST bump this to 2.
musicVideoProjects: 1,
+ // v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)
+ // via the per-record peer-sync push pipeline (record kind `commissionFeedback`,
+ // sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).
+ // The taste reactions federate (so a 👍/👎 carries across a user's machines and
+ // conditions the same commission's next run) while the parent commission stays
+ // machine-local (a synced schedule would double-run). Body-less whole-record
+ // 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 = 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
@@ -501,6 +510,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
writersRoomFolder: Object.freeze(['writersRoomFolders']),
writersRoomExercise: Object.freeze(['writersRoomExercises']),
musicVideoProject: Object.freeze(['musicVideoProjects']),
+ commissionFeedback: Object.freeze(['commissionFeedback']),
});
/**
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index d3cf5afa77..fac06bc3c2 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -166,7 +166,8 @@ export function sanitizeRecordForWire(kind, record) {
case 'moodBoard':
case 'writersRoomFolder':
case 'writersRoomExercise':
- case 'musicVideoProject': {
+ case 'musicVideoProject':
+ case 'commissionFeedback': {
// Persona/music/creative-director/mood-board records: like mediaCollection,
// no `ephemeral` flag — always wire-syncable when present. Strip-then-tail-
// re-add the soft-delete pair for byte-stable checksums. The whole record
@@ -179,6 +180,9 @@ export function sanitizeRecordForWire(kind, record) {
// LWW kinds with no ephemeral counters — they wire identically (no liveMode
// strip like writersRoomWork below). A musicVideoProject (#1770:
// metadata + beat-aligned scenes[]) is the same whole-record LWW contract.
+ // A commissionFeedback (#2686: one reaction — commissionId/runId/rating/
+ // note/tags/at) is a body-less whole-record LWW record with no local-only
+ // fields to strip, so it rides this same group.
const { deleted: _d, deletedAt: _da, ...rest } = record;
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 4bf43a53cf..b2cb08d301 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -71,6 +71,7 @@ const syncCategoriesSchema = z.object({
writersRoomFolders: z.boolean().optional(),
writersRoomExercises: z.boolean().optional(),
musicVideoProjects: z.boolean().optional(),
+ commissionFeedback: z.boolean().optional(),
catalog: z.boolean().optional()
}).optional();
diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.js
index 96ab11cc96..b711673f3e 100644
--- a/server/services/conflictJournalResolver.js
+++ b/server/services/conflictJournalResolver.js
@@ -39,6 +39,7 @@ import { updateProject } from './creativeDirector/local.js';
import { updateProject as updateMusicVideoProject } from './musicVideo/projects.js';
import { restoreBoard } from './moodBoard/index.js';
import { updateWork, restoreFolder, restoreExercise } from './writersRoom/local.js';
+import { restoreCommissionFeedback } from './creativeCommissions/feedbackStore.js';
export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';
export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';
@@ -162,6 +163,13 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {
// and stamps updatedAt so the restored sprint wins the next LWW. A
// missing/tombstoned exercise 404s (→ ERR_TARGET_GONE).
await restoreExercise(recordId, patch).catch(translateGone);
+ } else if (kind === 'commissionFeedback') {
+ // restoreCommissionFeedback merges the snapshot's rating/note/tags, un-tombstones,
+ // and bumps updatedAt so the restore wins the next LWW and re-pushes. It returns
+ // null (not throw) for a missing record — translate that to ERR_TARGET_GONE so
+ // 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 {
throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);
}
diff --git a/server/services/creativeCommissions/feedbackDb.js b/server/services/creativeCommissions/feedbackDb.js
new file mode 100644
index 0000000000..3b51e20be8
--- /dev/null
+++ b/server/services/creativeCommissions/feedbackDb.js
@@ -0,0 +1,115 @@
+/**
+ * Creative Commission feedback — PostgreSQL leaf I/O (#2686, split-record
+ * federation).
+ *
+ * One row per reaction in `commission_feedback`: the full sanitized record
+ * (commissionId / runId / rating / note / tags / at) in `data` JSONB, with
+ * commission_id / run_id / created_at / updated_at / deleted / deleted_at
+ * mirrored into columns for the per-commission hydration query and the
+ * federation sweep. This is the DEFAULT backend for real installs; the file
+ * backend (collectionStore) is a dev/test escape hatch only (see feedbackStore.js).
+ *
+ * FEDERATED (unlike the parent commission, which stays machine-local): the
+ * `deleted`/`deleted_at` tombstone columns carry a soft-delete so a removal
+ * propagates without an out-of-date peer resurrecting it (the LWW merge never
+ * propagates a hard delete). `data` mirrors the soft-delete pair so a tombstone
+ * round-trips through the sanitizer.
+ *
+ * PURE leaf I/O — no sanitizing, no serialization, no LWW policy. The store
+ * facade (feedbackStore.js) owns the sanitizer + merge decision (via the pure
+ * feedbackLogic.js) and serializes writes on a per-id queue, so reads here return
+ * `data` verbatim (the columns are a queryable mirror, never read back) and
+ * writes are plain upserts.
+ */
+
+import { query } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+/** Raw stored record (the `data` JSONB), or null. Live only unless includeDeleted. */
+export async function readRaw(id, { includeDeleted = false } = {}) {
+ const { rows } = await query(
+ includeDeleted
+ ? `SELECT data FROM commission_feedback WHERE id = $1`
+ : `SELECT data FROM commission_feedback WHERE id = $1 AND deleted = FALSE`,
+ [id],
+ );
+ return rows[0]?.data ?? null;
+}
+
+/** Every LIVE feedback record's raw `data` JSONB, oldest reaction first. */
+export async function listRaw() {
+ const { rows } = await query(
+ `SELECT data FROM commission_feedback WHERE deleted = FALSE ORDER BY created_at ASC, id ASC`,
+ );
+ return rows.map((r) => r.data);
+}
+
+/** Every LIVE feedback record for one commission, oldest reaction first. */
+export async function listRawByCommission(commissionId) {
+ const { rows } = await query(
+ `SELECT data FROM commission_feedback
+ WHERE commission_id = $1 AND deleted = FALSE
+ ORDER BY created_at ASC, id ASC`,
+ [commissionId],
+ );
+ return rows.map((r) => r.data);
+}
+
+/** Every feedback id — live only by default, or all (incl. tombstones) when asked. */
+export async function listIds({ includeDeleted = false } = {}) {
+ const { rows } = await query(
+ includeDeleted
+ ? `SELECT id FROM commission_feedback`
+ : `SELECT id FROM commission_feedback WHERE deleted = FALSE`,
+ );
+ return rows.map((r) => r.id);
+}
+
+/**
+ * Upsert one feedback record. `data` is written verbatim (lossless); the typed
+ * mirror columns are bind-sanitized. `created_at` is preserved on conflict (only
+ * the first INSERT sets it), so a re-rating (deterministic id) keeps the original
+ * creation moment while `updated_at`/`data` reflect the new reaction.
+ */
+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 commission_feedback (id, commission_id, run_id, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)
+ ON CONFLICT (id) DO UPDATE SET
+ commission_id = EXCLUDED.commission_id,
+ run_id = EXCLUDED.run_id,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ typeof record?.commissionId === 'string' && record.commissionId ? record.commissionId : null,
+ typeof record?.runId === 'string' && record.runId ? record.runId : null,
+ JSON.stringify(record),
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ deleted,
+ deletedAt,
+ ],
+ );
+ return record;
+}
+
+/** Hard-remove tombstoned rows 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 commission_feedback
+ 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/feedbackLogic.js b/server/services/creativeCommissions/feedbackLogic.js
new file mode 100644
index 0000000000..5e29750e4a
--- /dev/null
+++ b/server/services/creativeCommissions/feedbackLogic.js
@@ -0,0 +1,126 @@
+/**
+ * Creative Commission feedback — pure record transforms for cross-peer
+ * federation (#2686, Autonomous Creation Engine split-record federation).
+ *
+ * Phase 2 (#2657) stored taste reactions INLINE on the `CreativeCommission`
+ * record (`commission.feedback[]`). But a commission is deliberately
+ * MACHINE-LOCAL (a synced schedule would double-run on every peer — see
+ * store.js), which made feedback machine-local too: a 👍/👎 rated on machine A
+ * never reached machine B. This module splits feedback OUT into its own
+ * federated record kind (`commissionFeedback`, sync category `commissionFeedback`,
+ * PostgreSQL `commission_feedback`) so your taste carries across your machines,
+ * while the commission's `schedule` (+ future home-peer pointer) stays local.
+ *
+ * ONE ROW PER REACTION (not an aggregate-per-commission blob): federating an
+ * array as a single LWW record would let a rating on machine A clobber a
+ * concurrent rating on machine B (last writer wins the whole array). Per-reaction
+ * records federate independently — each converges on its own id — so both
+ * machines' taste survives. Re-rating the SAME run reuses a DETERMINISTIC id
+ * (`cfeedback-<runId>`) so the second reaction LWW-updates the first in place
+ * (one reaction per run) rather than stacking a duplicate — sync-safe, because
+ * the PortOS LWW merge never propagates a hard delete (removing the prior entry
+ * from an array would resurrect on the next inbound sync).
+ *
+ * Storage-agnostic (no I/O) so the PostgreSQL backend (feedbackDb.js) and the
+ * test/dev file backend can never drift in how an incoming reaction is sanitized
+ * or LWW-merged. Mirrors writersRoom/syncLogic.js's body-less folder path.
+ */
+
+import { compareNewerWins } from '../../lib/lwwTimestamp.js';
+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+
+const isStr = (v) => typeof v === 'string';
+
+// The peer-sync record kind. Exported so the feedback store / peerSync.js
+// reference one source of truth instead of bare strings.
+export const COMMISSION_FEEDBACK_KIND = 'commissionFeedback';
+
+// A feedback record id is a queryable primary key (no filesystem path use), but
+// we still gate it so a malformed peer payload can't plant an unaddressable row.
+// `cfeedback-<runId>` for run-keyed reactions (runId is itself `run-<uuid>`) and
+// `cfeedback-<uuid>` for the rare run-less reaction.
+export const CFEEDBACK_ID_RE = /^cfeedback-[0-9a-z-]+$/i;
+
+/**
+ * Deterministic id for a reaction tied to a run — so re-rating that run
+ * LWW-updates the SAME record instead of appending a duplicate. runIds are
+ * globally-unique UUIDs (`run-<uuid>`), so the runId alone disambiguates across
+ * commissions. Returns null for a missing/non-string runId (the caller then
+ * mints a random id).
+ */
+export function deterministicFeedbackId(runId) {
+ if (!isStr(runId) || !runId) return null;
+ return `cfeedback-${runId}`;
+}
+
+/**
+ * Normalize a raw feedback record into the canonical stored/wire shape. Returns
+ * null for a non-object, an id-less/invalid-id record, or a record without a
+ * usable rating ('up'/'down' or a non-zero number) — the "drop on the floor"
+ * contract every sanitizer shares, so a malformed peer payload can't land. The
+ * body (commissionId / runId / rating / note / tags / at) passes through
+ * verbatim; the LWW key (`updatedAt`) + soft-delete trio are normalized so the
+ * wire/hash shape is stable regardless of on-disk key position.
+ */
+export function sanitizeCommissionFeedbackForSync(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ if (!isStr(raw.id) || !CFEEDBACK_ID_RE.test(raw.id)) return null;
+ const isUp = raw.rating === 'up' || (typeof raw.rating === 'number' && raw.rating > 0);
+ const isDown = raw.rating === 'down' || (typeof raw.rating === 'number' && raw.rating < 0);
+ if (!isUp && !isDown) return null;
+ const rating = typeof raw.rating === 'number' ? raw.rating : (isUp ? 'up' : 'down');
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt
+ : (isStr(raw.at) ? raw.at : new Date().toISOString());
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);
+ return {
+ id: raw.id,
+ commissionId: isStr(raw.commissionId) ? raw.commissionId : null,
+ runId: isStr(raw.runId) ? raw.runId : null,
+ rating,
+ note: isStr(raw.note) ? raw.note : '',
+ tags: Array.isArray(raw.tags) ? raw.tags.filter(isStr).slice(0, 20) : [],
+ at: isStr(raw.at) ? raw.at : createdAt,
+ createdAt,
+ updatedAt,
+ deleted,
+ deletedAt,
+ };
+}
+
+/**
+ * LWW merge decision for one incoming feedback record against the local copy —
+ * mirrors `mergeFolderRecord` (writersRoom/syncLogic.js's body-less path):
+ * - remote sanitized here (drop-on-floor on a malformed payload → `next: null`).
+ * - No local counterpart → insert the remote verbatim (`inserted: true`).
+ * - Both present → newer `updatedAt` wins (`compareNewerWins`: epoch-ms,
+ * unparseable-loses, tie → local). Tombstones ride the same path.
+ * Returns `{ next, inserted, remoteWins, changed }`; `changed` is false when the
+ * winner is byte-identical to local. The whole record is LWW-overwritten (no
+ * field-union), so it is hashed in full by `contentHashForRecord`.
+ */
+export function mergeCommissionFeedbackRecord(local, remoteRaw) {
+ const remote = sanitizeCommissionFeedbackForSync(remoteRaw);
+ if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };
+ if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };
+ // Derive the local LWW key through the SAME sanitizer so the compare is
+ // symmetric; fall back to the raw key defensively (local came from our own
+ // store, so sanitize can't legitimately return null).
+ const localKey = sanitizeCommissionFeedbackForSync(local)?.updatedAt ?? local.updatedAt;
+ const remoteWins = compareNewerWins(remote.updatedAt, localKey);
+ const next = remoteWins ? remote : local;
+ const changed = JSON.stringify(next) !== JSON.stringify(local);
+ return { next, inserted: false, remoteWins, changed };
+}
+
+/**
+ * Render a federated feedback record down to the inline `{ id, runId, rating,
+ * note, tags, at }` shape `directive.js` (`renderFeedbackDigest`) and the client
+ * rate UI (which keys by `runId`) already consume — so the split is invisible to
+ * both. Returns null for a record the sanitizer rejects.
+ */
+export function toInlineFeedback(raw) {
+ const rec = sanitizeCommissionFeedbackForSync(raw);
+ if (!rec) return null;
+ return { id: rec.id, runId: rec.runId, rating: rec.rating, note: rec.note, tags: rec.tags, at: rec.at };
+}
diff --git a/server/services/creativeCommissions/feedbackLogic.test.js b/server/services/creativeCommissions/feedbackLogic.test.js
new file mode 100644
index 0000000000..a25ca56870
--- /dev/null
+++ b/server/services/creativeCommissions/feedbackLogic.test.js
@@ -0,0 +1,108 @@
+import { describe, it, expect } from 'vitest';
+import {
+ COMMISSION_FEEDBACK_KIND,
+ CFEEDBACK_ID_RE,
+ deterministicFeedbackId,
+ sanitizeCommissionFeedbackForSync,
+ mergeCommissionFeedbackRecord,
+ toInlineFeedback,
+} from './feedbackLogic.js';
+
+describe('feedbackLogic — kind + id', () => {
+ it('names the record kind', () => {
+ expect(COMMISSION_FEEDBACK_KIND).toBe('commissionFeedback');
+ });
+
+ it('mints a deterministic id per run and null for a missing run', () => {
+ expect(deterministicFeedbackId('run-abc')).toBe('cfeedback-run-abc');
+ expect(CFEEDBACK_ID_RE.test(deterministicFeedbackId('run-abc'))).toBe(true);
+ expect(deterministicFeedbackId(null)).toBeNull();
+ expect(deterministicFeedbackId('')).toBeNull();
+ });
+});
+
+describe('sanitizeCommissionFeedbackForSync', () => {
+ it('normalizes an up/down reaction with the soft-delete trio', () => {
+ const rec = sanitizeCommissionFeedbackForSync({
+ id: 'cfeedback-run-1', commissionId: 'commission-x', runId: 'run-1',
+ rating: 'up', note: 'more Magritte', tags: ['surreal', 42], at: '2026-01-01T00:00:00.000Z',
+ });
+ expect(rec).toMatchObject({
+ id: 'cfeedback-run-1', commissionId: 'commission-x', runId: 'run-1',
+ rating: 'up', note: 'more Magritte', tags: ['surreal'], deleted: false, deletedAt: null,
+ });
+ expect(rec.updatedAt).toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('preserves a non-zero numeric rating verbatim', () => {
+ expect(sanitizeCommissionFeedbackForSync({ id: 'cfeedback-a', rating: 3 }).rating).toBe(3);
+ expect(sanitizeCommissionFeedbackForSync({ id: 'cfeedback-a', rating: -2 }).rating).toBe(-2);
+ });
+
+ it('drops a record with a bad id, no id, or no usable rating', () => {
+ expect(sanitizeCommissionFeedbackForSync({ id: 'nope', rating: 'up' })).toBeNull();
+ expect(sanitizeCommissionFeedbackForSync({ rating: 'up' })).toBeNull();
+ expect(sanitizeCommissionFeedbackForSync({ id: 'cfeedback-a', rating: 0 })).toBeNull();
+ expect(sanitizeCommissionFeedbackForSync({ id: 'cfeedback-a', rating: 'meh' })).toBeNull();
+ expect(sanitizeCommissionFeedbackForSync(null)).toBeNull();
+ });
+
+ it('normalizes a tombstone', () => {
+ const rec = sanitizeCommissionFeedbackForSync({ id: 'cfeedback-a', rating: 'up', deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' });
+ expect(rec.deleted).toBe(true);
+ expect(rec.deletedAt).toBe('2026-02-02T00:00:00.000Z');
+ });
+});
+
+describe('mergeCommissionFeedbackRecord (LWW)', () => {
+ const base = { id: 'cfeedback-run-1', commissionId: 'c1', runId: 'run-1', rating: 'up', at: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' };
+
+ it('inserts when there is no local copy', () => {
+ const { next, inserted, remoteWins } = mergeCommissionFeedbackRecord(null, base);
+ expect(inserted).toBe(true);
+ expect(remoteWins).toBe(true);
+ expect(next.id).toBe('cfeedback-run-1');
+ });
+
+ it('newer remote updatedAt wins', () => {
+ const local = { ...base };
+ const remote = { ...base, rating: 'down', updatedAt: '2026-03-03T00:00:00.000Z' };
+ const { next, remoteWins, changed } = mergeCommissionFeedbackRecord(local, remote);
+ expect(remoteWins).toBe(true);
+ expect(changed).toBe(true);
+ expect(next.rating).toBe('down');
+ });
+
+ it('older remote loses to a newer local (LWW, no clobber)', () => {
+ const local = { ...base, rating: 'down', updatedAt: '2026-03-03T00:00:00.000Z' };
+ const remote = { ...base, rating: 'up', updatedAt: '2026-01-01T00:00:00.000Z' };
+ const { next, remoteWins } = mergeCommissionFeedbackRecord(local, remote);
+ expect(remoteWins).toBe(false);
+ expect(next.rating).toBe('down');
+ });
+
+ it('drops a malformed remote (ratingless)', () => {
+ const { next } = mergeCommissionFeedbackRecord({ ...base }, { id: 'cfeedback-run-1', rating: 0 });
+ expect(next).toBeNull();
+ });
+
+ it('a tombstone with a newer updatedAt wins', () => {
+ const local = { ...base };
+ const remote = { ...base, deleted: true, deletedAt: '2026-04-04T00:00:00.000Z', updatedAt: '2026-04-04T00:00:00.000Z' };
+ const { next, remoteWins } = mergeCommissionFeedbackRecord(local, remote);
+ expect(remoteWins).toBe(true);
+ expect(next.deleted).toBe(true);
+ });
+});
+
+describe('toInlineFeedback', () => {
+ it('renders the inline { id, runId, rating, note, tags, at } view directive.js consumes', () => {
+ const inline = toInlineFeedback({ id: 'cfeedback-run-1', commissionId: 'c1', runId: 'run-1', rating: 'up', note: 'hi', tags: ['a'], at: '2026-01-01T00:00:00.000Z' });
+ expect(inline).toEqual({ id: 'cfeedback-run-1', runId: 'run-1', rating: 'up', note: 'hi', tags: ['a'], at: '2026-01-01T00:00:00.000Z' });
+ expect(inline).not.toHaveProperty('commissionId');
+ });
+
+ it('returns null for a rejected record', () => {
+ expect(toInlineFeedback({ id: 'bad', rating: 'up' })).toBeNull();
+ });
+});
diff --git a/server/services/creativeCommissions/feedbackStore.js b/server/services/creativeCommissions/feedbackStore.js
new file mode 100644
index 0000000000..3f06bde94c
--- /dev/null
+++ b/server/services/creativeCommissions/feedbackStore.js
@@ -0,0 +1,361 @@
+/**
+ * Creative Commission feedback store — federated per-reaction record kind
+ * (#2686, split-record federation).
+ *
+ * Owns the `commissionFeedback` record kind: taste reactions split OUT of the
+ * machine-local commission so they federate across sync peers (a 👍/👎 rated on
+ * machine A conditions the same commission's next run on machine B), while the
+ * commission's schedule stays local. See feedbackLogic.js for the WHY and the
+ * per-reaction / deterministic-id rationale.
+ *
+ * Structure mirrors ./store.js: a `createPgFileFacade` picks the PostgreSQL leaf
+ * (feedbackDb.js — the real backend for every install) or the collectionStore
+ * file backend (`data/commission-feedback/`, the dev/test escape hatch). The
+ * facade owns the sanitizer + LWW merge uniformly (applied on the service side,
+ * not inside a backend) so the two backends can't drift, and serializes every
+ * read-modify-write on a shared per-id write queue — commissions are written only
+ * by the single main server process, so in-process per-id serialization is
+ * sufficient (no row lock), and it keeps the sync-receive merge from racing a
+ * concurrent user rating of the same run.
+ *
+ * The federation wiring (peerSync push/receive/tombstoneGc/conflict-resolver)
+ * imports the `*ForSync` facades below, exactly as it imports writersRoom/sync.js.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS } from '../../lib/fileUtils.js';
+import { createCollectionStore } from '../../lib/collectionStore.js';
+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';
+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
+import {
+ contentHashForRecord,
+ setSyncBaseHash,
+ deleteSyncBaseHash,
+ flushBaseHashes,
+ maybeJournalBeforeOverwrite,
+} from '../../lib/conflictJournal.js';
+import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
+import {
+ COMMISSION_FEEDBACK_KIND,
+ CFEEDBACK_ID_RE,
+ deterministicFeedbackId,
+ sanitizeCommissionFeedbackForSync,
+ mergeCommissionFeedbackRecord,
+ toInlineFeedback,
+} from './feedbackLogic.js';
+
+export const TYPE = 'commission-feedback';
+export const FEEDBACK_SCHEMA_VERSION = 1;
+
+const isStr = (v) => typeof v === 'string';
+const notDeleted = (r) => r && r.deleted !== true;
+
+// --- File backend (dev/test escape hatch): wraps collectionStore ---
+function makeFileBackend(dir) {
+ const cs = createCollectionStore({ dir, type: TYPE, schemaVersion: FEEDBACK_SCHEMA_VERSION });
+ let stamped = false;
+ const ensureTypeIndex = async () => {
+ if (stamped) return;
+ stamped = true;
+ await cs.saveTypeIndex({}).catch(() => { stamped = false; });
+ };
+ return {
+ name: 'file',
+ readRaw: async (id, { includeDeleted = false } = {}) => {
+ const rec = await cs.loadOne(id);
+ if (!rec) return null;
+ return includeDeleted || notDeleted(rec) ? rec : null;
+ },
+ listRaw: async () => (await cs.loadAll()).filter(notDeleted),
+ listRawByCommission: async (commissionId) =>
+ (await cs.loadAll()).filter((r) => notDeleted(r) && r?.commissionId === commissionId),
+ listIds: async ({ includeDeleted = false } = {}) =>
+ (await cs.loadAll()).filter((r) => includeDeleted || notDeleted(r)).map((r) => r.id),
+ writeRaw: async (id, record) => { await ensureTypeIndex(); await cs.saveOneNow(id, record); return record; },
+ pruneTombstoned: async (olderThanMs) => {
+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };
+ const all = await cs.loadAll();
+ const stale = all.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(),
+ };
+}
+
+// --- PostgreSQL backend: pure leaf I/O from ./feedbackDb.js ---
+function makePgBackend(db) {
+ return {
+ name: 'postgres',
+ readRaw: db.readRaw,
+ listRaw: db.listRaw,
+ listRawByCommission: db.listRawByCommission,
+ listIds: db.listIds,
+ writeRaw: db.writeRaw,
+ pruneTombstoned: db.pruneTombstoned,
+ };
+}
+
+const pgBackend = () => resolvePgBackend({
+ requirement: 'Creative Commission feedback requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',
+ loadDb: () => import('./feedbackDb.js'),
+ makePg: makePgBackend,
+});
+
+let _facade = null;
+let _facadeDir = null;
+
+function createFacade(dir) {
+ const { getBackend, getBackendName } = createPgFileFacade({
+ makeFile: () => makeFileBackend(dir),
+ makePg: () => pgBackend(),
+ });
+ const queueRecordWrite = createRecordWriteQueue();
+ return {
+ dir,
+ type: TYPE,
+ getBackendName,
+ readRaw: async (id, opts) => (await getBackend()).readRaw(id, opts),
+ listRaw: async () => (await getBackend()).listRaw(),
+ listRawByCommission: async (id) => (await getBackend()).listRawByCommission(id),
+ listIds: async (opts) => (await getBackend()).listIds(opts),
+ writeRaw: async (id, record) => (await getBackend()).writeRaw(id, record),
+ pruneTombstoned: async (olderThanMs) => (await getBackend()).pruneTombstoned(olderThanMs),
+ queueRecordWrite,
+ };
+}
+
+function feedbackStore() {
+ const dir = join(PATHS.data, TYPE);
+ if (_facade && _facadeDir === dir) return _facade;
+ _facade = createFacade(dir);
+ _facadeDir = dir;
+ return _facade;
+}
+
+/** Reset the memoized facade — test seam only. */
+export function _resetFeedbackStore() {
+ _facade = null;
+ _facadeDir = null;
+}
+
+/**
+ * Record (or re-record) a reaction for a commission run. Deterministic id per
+ * run (`cfeedback-<runId>`) so re-rating LWW-updates in place — one reaction per
+ * run, sync-safe. Run-less reactions get a random id. Returns the sanitized
+ * stored record, or null when the rating is unusable (the caller validates
+ * commission/run existence before calling this). Serialized per-id so a
+ * concurrent sync-receive merge of the same record can't clobber it.
+ */
+export async function recordFeedback({ commissionId, runId = null, rating, note = '', tags = [] }) {
+ const store = feedbackStore();
+ const id = deterministicFeedbackId(runId) || `cfeedback-${randomUUID()}`;
+ const result = await store.queueRecordWrite(id, async () => {
+ const existing = await store.readRaw(id, { includeDeleted: true });
+ const now = new Date().toISOString();
+ const record = sanitizeCommissionFeedbackForSync({
+ id,
+ commissionId,
+ runId,
+ rating,
+ note,
+ tags,
+ at: now,
+ createdAt: existing?.createdAt || now,
+ updatedAt: now,
+ deleted: false,
+ deletedAt: null,
+ });
+ if (!record) return null;
+ await store.writeRaw(id, record);
+ return 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.
+ autoSubscribeRecordToAllPeers(COMMISSION_FEEDBACK_KIND, id).catch(() => {});
+ return result;
+}
+
+/**
+ * The inline `feedback[]` view for one commission (oldest reaction first), mapped
+ * to the `{ id, runId, rating, note, tags, at }` shape directive.js + the client
+ * rate UI consume. Hydrated onto the machine-local commission on read so the
+ * split is invisible to both.
+ */
+export async function listFeedbackForCommission(commissionId) {
+ const raw = await feedbackStore().listRawByCommission(commissionId);
+ return raw
+ .map(sanitizeCommissionFeedbackForSync)
+ .filter(Boolean)
+ .sort((a, b) => String(a.at).localeCompare(String(b.at)))
+ .map(toInlineFeedback);
+}
+
+/**
+ * The inline `feedback[]` view for MANY commissions in one pass (avoids an N+1
+ * over listCommissions). Returns a Map<commissionId, inlineFeedback[]>.
+ */
+export async function listFeedbackByCommissionIds(commissionIds) {
+ const want = new Set(commissionIds);
+ const raw = await feedbackStore().listRaw();
+ const byId = new Map();
+ for (const r of raw) {
+ const rec = sanitizeCommissionFeedbackForSync(r);
+ if (!rec || !rec.commissionId || !want.has(rec.commissionId)) continue;
+ if (!byId.has(rec.commissionId)) byId.set(rec.commissionId, []);
+ byId.get(rec.commissionId).push(rec);
+ }
+ const out = new Map();
+ for (const [cid, list] of byId) {
+ list.sort((a, b) => String(a.at).localeCompare(String(b.at)));
+ out.set(cid, list.map(toInlineFeedback));
+ }
+ return out;
+}
+
+// ---------- federation facades (imported by the peer-sync layer) ----------
+
+/** One feedback record's sanitized wire form (tombstone surfaced), or null. */
+export async function getCommissionFeedbackForSync(id) {
+ const raw = await feedbackStore().readRaw(id, { includeDeleted: true });
+ return raw ? sanitizeCommissionFeedbackForSync(raw) : null;
+}
+
+/** Every LIVE feedback record as `{ id, updatedAt }` for full-sync coverage compare. */
+export async function listCommissionFeedbackForSync() {
+ const raw = await feedbackStore().listRaw();
+ return raw
+ .map(sanitizeCommissionFeedbackForSync)
+ .filter(Boolean)
+ .map((r) => ({ id: r.id, updatedAt: r.updatedAt }));
+}
+
+/** Every feedback id — live only by default, or all (incl. tombstones) for the sweep. */
+export async function listCommissionFeedbackIdsForSync(options = {}) {
+ return feedbackStore().listIds(options);
+}
+
+/**
+ * Merge an incoming batch of feedback records from a peer (LWW, tombstone-aware).
+ * Serialized per-id on the same write queue as recordFeedback so a user rating
+ * can't clobber the merge (or vice versa). Journals the about-to-be-overwritten
+ * local version when the remote wins, and seeds the conflict-journal base hash —
+ * mirrors writersRoom's `mergeBodylessFromSync`, minus the PG row lock (the
+ * single-process per-id queue serializes both writers). Returns `{ applied, count }`.
+ */
+export async function mergeCommissionFeedbackFromSync(remoteRecords, { source = { via: 'sync', peerId: null } } = {}) {
+ if (!Array.isArray(remoteRecords)) return { applied: false, count: 0 };
+ const store = feedbackStore();
+ let changed = 0;
+ for (const remote of remoteRecords) {
+ const id = remote?.id;
+ if (!isStr(id) || !CFEEDBACK_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 } = mergeCommissionFeedbackRecord(local, remote);
+ if (!next) return false; // malformed remote → dropped
+ if (!inserted && (!remoteWins || !didChange)) return false; // local wins, or no-op
+ if (!inserted) {
+ await maybeJournalBeforeOverwrite({ kind: COMMISSION_FEEDBACK_KIND, id: next.id, local, remote: next, source });
+ }
+ await store.writeRaw(id, next);
+ await setSyncBaseHash(COMMISSION_FEEDBACK_KIND, next.id, contentHashForRecord(COMMISSION_FEEDBACK_KIND, next));
+ return true;
+ });
+ if (applied) changed += 1;
+ }
+ await flushBaseHashes();
+ return changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };
+}
+
+/** Hard-remove tombstoned feedback older than the cutoff; evicts each pruned id's base hash. */
+export async function pruneTombstonedCommissionFeedback(olderThanMs) {
+ const result = await feedbackStore().pruneTombstoned(olderThanMs);
+ for (const id of result.ids || []) await deleteSyncBaseHash(COMMISSION_FEEDBACK_KIND, id).catch(() => {});
+ return result;
+}
+
+/**
+ * Restore a feedback record from a conflict-journal snapshot (Conflicts UI).
+ * Merges the RESTORABLE fields, un-tombstones, bumps `updatedAt` so the restore
+ * wins the next LWW and re-pushes. A missing record returns null (→ ERR_TARGET_GONE).
+ */
+export async function restoreCommissionFeedback(id, patch) {
+ const store = feedbackStore();
+ const result = await store.queueRecordWrite(id, async () => {
+ const current = await store.readRaw(id, { includeDeleted: true });
+ if (!current) return null;
+ const now = new Date().toISOString();
+ const next = sanitizeCommissionFeedbackForSync({
+ ...current,
+ ...(isStr(patch?.rating) || typeof patch?.rating === 'number' ? { rating: patch.rating } : {}),
+ ...(isStr(patch?.note) ? { note: patch.note } : {}),
+ ...(Array.isArray(patch?.tags) ? { tags: patch.tags } : {}),
+ deleted: false,
+ deletedAt: null,
+ updatedAt: now,
+ });
+ if (!next) return null;
+ await store.writeRaw(id, next);
+ return next;
+ });
+ if (!result) return null;
+ emitRecordUpdated(COMMISSION_FEEDBACK_KIND, id);
+ return result;
+}
+
+/**
+ * Soft-delete (tombstone) a feedback record so the removal federates. Idempotent.
+ * No route calls this today (re-rating LWW-updates in place; a deleted commission
+ * leaves its feedback records addressable for peers that still hold the
+ * commission) — it exists so the tombstone/GC wiring stays consistent with the
+ * record-kind pattern and a future "forget this reaction" affordance can reuse it.
+ */
+export async function deleteCommissionFeedback(id) {
+ const store = feedbackStore();
+ const existed = await store.queueRecordWrite(id, async () => {
+ const current = await store.readRaw(id, { includeDeleted: true });
+ if (!current || current.deleted === true) return false;
+ const now = new Date().toISOString();
+ await store.writeRaw(id, sanitizeCommissionFeedbackForSync({ ...current, deleted: true, deletedAt: now, updatedAt: now }));
+ return true;
+ });
+ if (!existed) return { id, deleted: false };
+ emitRecordDeleted(COMMISSION_FEEDBACK_KIND, id);
+ return { id, deleted: true };
+}
+
+/**
+ * Migrate a commission's INLINE `feedback[]` (Phase 2 storage) into the federated
+ * store, then return true if any were moved (the caller clears the inline array).
+ * Idempotent: deterministic ids + `ON CONFLICT` upsert mean re-running is a no-op
+ * once migrated, and a newer federated reaction (re-rated on a peer) is never
+ * clobbered because we only write when the record is ABSENT. Used by the
+ * split-record migration (#2686) and defensively by the commission read path.
+ */
+export async function backfillInlineFeedback(commissionId, inlineFeedback) {
+ if (!Array.isArray(inlineFeedback) || inlineFeedback.length === 0) return false;
+ const store = feedbackStore();
+ let wrote = 0;
+ for (const entry of inlineFeedback) {
+ if (!entry || typeof entry !== 'object') continue;
+ const id = deterministicFeedbackId(entry.runId) || (isStr(entry.id) && CFEEDBACK_ID_RE.test(entry.id) ? entry.id : `cfeedback-${randomUUID()}`);
+ const at = isStr(entry.at) ? entry.at : new Date().toISOString();
+ const record = sanitizeCommissionFeedbackForSync({
+ id, commissionId, runId: entry.runId ?? null, rating: entry.rating,
+ note: entry.note, tags: entry.tags, at, createdAt: at, updatedAt: at,
+ deleted: false, deletedAt: null,
+ });
+ if (!record) continue;
+ const didWrite = await store.queueRecordWrite(id, async () => {
+ const existing = await store.readRaw(id, { includeDeleted: true });
+ if (existing) return false; // already federated (possibly newer) — never clobber
+ await store.writeRaw(id, record);
+ return true;
+ });
+ if (didWrite) { wrote += 1; autoSubscribeRecordToAllPeers(COMMISSION_FEEDBACK_KIND, id).catch(() => {}); }
+ }
+ return wrote > 0;
+}
diff --git a/server/services/creativeCommissions/feedbackStore.test.js b/server/services/creativeCommissions/feedbackStore.test.js
new file mode 100644
index 0000000000..443a25ddcb
--- /dev/null
+++ b/server/services/creativeCommissions/feedbackStore.test.js
@@ -0,0 +1,148 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory collectionStore (same posture as store.test.js) so CRUD + merge are
+// exercised without the filesystem or Postgres.
+const feedbackRecords = new Map();
+const makeMemStore = () => ({
+ loadAll: async () => [...feedbackRecords.values()],
+ loadOne: async (id) => feedbackRecords.get(id) || null,
+ saveOne: async (id, rec) => { feedbackRecords.set(id, rec); },
+ saveOneNow: async (id, rec) => { feedbackRecords.set(id, rec); },
+ deleteOne: async (id) => { feedbackRecords.delete(id); },
+ deleteOneNow: async (id) => { feedbackRecords.delete(id); },
+ saveTypeIndex: async () => {},
+ verifySchemaVersion: async () => ({ ok: true }),
+});
+vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: () => makeMemStore() }));
+vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-feedback' } }));
+// Keep federation side-effects inert in this store-level unit test.
+const emitRecordUpdated = vi.fn();
+const emitRecordDeleted = vi.fn();
+const autoSubscribeRecordToAllPeers = vi.fn(() => Promise.resolve());
+vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers }));
+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 {
+ recordFeedback,
+ listFeedbackForCommission,
+ listFeedbackByCommissionIds,
+ getCommissionFeedbackForSync,
+ listCommissionFeedbackForSync,
+ listCommissionFeedbackIdsForSync,
+ mergeCommissionFeedbackFromSync,
+ pruneTombstonedCommissionFeedback,
+ restoreCommissionFeedback,
+ deleteCommissionFeedback,
+ backfillInlineFeedback,
+} = await import('./feedbackStore.js');
+
+beforeEach(() => { feedbackRecords.clear(); vi.clearAllMocks(); });
+
+describe('recordFeedback + hydration', () => {
+ it('writes one federated record per reaction (deterministic id per run) and subscribes peers', async () => {
+ const rec = await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'more Magritte' });
+ expect(rec.id).toBe('cfeedback-run-A');
+ expect(rec).toMatchObject({ commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'more Magritte' });
+ expect(autoSubscribeRecordToAllPeers).toHaveBeenCalledWith('commissionFeedback', 'cfeedback-run-A');
+ const inline = await listFeedbackForCommission('c1');
+ expect(inline).toHaveLength(1);
+ expect(inline[0]).toMatchObject({ runId: 'run-A', rating: 'up', note: 'more Magritte' });
+ });
+
+ it('re-rating the same run LWW-updates in place (one reaction per run)', async () => {
+ await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'first' });
+ const createdAt = feedbackRecords.get('cfeedback-run-A').createdAt;
+ await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'down', note: 'changed my mind' });
+ const all = [...feedbackRecords.values()].filter((r) => r.runId === 'run-A');
+ expect(all).toHaveLength(1);
+ expect(all[0]).toMatchObject({ rating: 'down', note: 'changed my mind', createdAt });
+ });
+
+ it('returns null for an unusable rating', async () => {
+ expect(await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 0 })).toBeNull();
+ });
+
+ 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' });
+ const c1 = await listFeedbackForCommission('c1');
+ expect(c1.map((f) => f.runId)).toEqual(['run-A']);
+ const map = await listFeedbackByCommissionIds(['c1', 'c2']);
+ expect(map.get('c1')).toHaveLength(1);
+ expect(map.get('c2')).toHaveLength(1);
+ });
+});
+
+describe('federation facades', () => {
+ it('merges an incoming remote reaction (LWW) and exposes it for sync', async () => {
+ const remote = { id: 'cfeedback-run-Z', commissionId: 'c9', runId: 'run-Z', rating: 'up', note: 'peer', at: '2026-05-05T00:00:00.000Z', updatedAt: '2026-05-05T00:00:00.000Z' };
+ const res = await mergeCommissionFeedbackFromSync([remote], { source: { via: 'sync', peerId: 'peer-a' } });
+ expect(res).toEqual({ applied: true, count: 1 });
+ const forSync = await getCommissionFeedbackForSync('cfeedback-run-Z');
+ expect(forSync).toMatchObject({ id: 'cfeedback-run-Z', rating: 'up' });
+ const live = await listCommissionFeedbackForSync();
+ expect(live).toEqual([{ id: 'cfeedback-run-Z', updatedAt: '2026-05-05T00:00:00.000Z' }]);
+ });
+
+ it('a stale remote does not clobber a newer local reaction', async () => {
+ await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'down', note: 'newer' });
+ feedbackRecords.get('cfeedback-run-A').updatedAt = '2026-09-09T00:00:00.000Z';
+ const stale = { id: 'cfeedback-run-A', commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'older', at: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' };
+ const res = await mergeCommissionFeedbackFromSync([stale], { source: { via: 'sync', peerId: 'peer-a' } });
+ expect(res.count).toBe(0);
+ expect(feedbackRecords.get('cfeedback-run-A').note).toBe('newer');
+ });
+
+ it('soft-deletes (tombstones) and prunes past a cutoff, then lists ids incl. deleted', async () => {
+ await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'up' });
+ const del = await deleteCommissionFeedback('cfeedback-run-A');
+ expect(del).toEqual({ id: 'cfeedback-run-A', deleted: true });
+ expect(emitRecordDeleted).toHaveBeenCalledWith('commissionFeedback', 'cfeedback-run-A');
+ // tombstone excluded from the live view but present in the includeDeleted id list
+ expect(await listFeedbackForCommission('c1')).toEqual([]);
+ expect(await listCommissionFeedbackIdsForSync({ includeDeleted: true })).toContain('cfeedback-run-A');
+ // Backdate the tombstone so it's older than the cutoff, then prune.
+ feedbackRecords.get('cfeedback-run-A').deletedAt = '2020-01-01T00:00:00.000Z';
+ const pruned = await pruneTombstonedCommissionFeedback(Date.parse('2021-01-01T00:00:00.000Z'));
+ expect(pruned.pruned).toBe(1);
+ expect(feedbackRecords.has('cfeedback-run-A')).toBe(false);
+ });
+
+ it('restores a tombstoned reaction from a snapshot, un-deleting it', async () => {
+ await recordFeedback({ commissionId: 'c1', runId: 'run-A', rating: 'up', note: 'x' });
+ await deleteCommissionFeedback('cfeedback-run-A');
+ const restored = await restoreCommissionFeedback('cfeedback-run-A', { rating: 'down', note: 'restored' });
+ expect(restored).toMatchObject({ deleted: false, rating: 'down', note: 'restored' });
+ expect(emitRecordUpdated).toHaveBeenCalledWith('commissionFeedback', 'cfeedback-run-A');
+ expect(await restoreCommissionFeedback('cfeedback-missing', {})).toBeNull();
+ });
+});
+
+describe('backfillInlineFeedback', () => {
+ it('migrates legacy inline reactions once, never clobbering a newer federated one', async () => {
+ const wrote = await backfillInlineFeedback('c1', [
+ { id: 'feedback-legacy', runId: 'run-A', rating: 'up', note: 'legacy', at: '2026-01-01T00:00:00.000Z' },
+ { runId: 'run-B', rating: 'down', note: 'legacy2', at: '2026-01-02T00:00:00.000Z' },
+ ]);
+ expect(wrote).toBe(true);
+ // run-A got a deterministic id; run-B too.
+ expect(feedbackRecords.has('cfeedback-run-A')).toBe(true);
+ expect(feedbackRecords.has('cfeedback-run-B')).toBe(true);
+ // Re-running is a no-op (records already present → never clobber).
+ feedbackRecords.get('cfeedback-run-A').note = 'peer-updated';
+ const again = await backfillInlineFeedback('c1', [{ runId: 'run-A', rating: 'up', note: 'legacy', at: '2026-01-01T00:00:00.000Z' }]);
+ expect(again).toBe(false);
+ expect(feedbackRecords.get('cfeedback-run-A').note).toBe('peer-updated');
+ });
+
+ it('is a no-op for empty/absent inline feedback', async () => {
+ expect(await backfillInlineFeedback('c1', [])).toBe(false);
+ expect(await backfillInlineFeedback('c1', null)).toBe(false);
+ });
+});
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 58b9b821a2..9e932f61ef 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -16,17 +16,21 @@
* (`createRecordWriteQueue`, identical to universeBuilder), and delegates only
* plain leaf I/O to the selected backend.
*
- * Commissions are MACHINE-LOCAL and NOT federated in Phase 1 — the same rationale
- * as `seriesAutopilotScheduler`'s settings-based schedules: a schedule that
+ * The COMMISSION stays MACHINE-LOCAL and NOT federated — the same rationale as
+ * `seriesAutopilotScheduler`'s settings-based schedules: a schedule that
* federated across sync peers would double-run on every machine. The DB row
* carries no sync cursor/tombstone (deletes are hard deletes, mirroring tribe).
- * Federation is Phase 2 work, and it must split this record: the brief/feedback
- * CAN federate, but the `schedule` field (+ a future "home peer" pointer) MUST
- * stay machine-local, or the whole double-run avoidance breaks.
*
- * The record shape is stable/forward-looking: `feedback[]` + `feedbackWindow`
- * exist now (Phase 1 leaves feedback empty) so Phase 2 only needs the rate
- * surface, not a schema change.
+ * FEEDBACK, by contrast, IS federated as of #2686 (split-record federation): the
+ * taste reactions live in their own `commissionFeedback` record kind (see
+ * ./feedbackStore.js) so a 👍/👎 rated on machine A conditions the SAME
+ * commission's next run on machine B, while the `schedule` (+ future home-peer
+ * pointer) stays local. The commission's `feedback[]` field is now a READ-THROUGH
+ * VIEW hydrated from the federated store on read (listCommissions/getCommission);
+ * `submitCommissionFeedback` writes the federated store, not this row. Legacy
+ * inline reactions (Phase 2 storage) are split into the federated store lazily on
+ * read and by `backfillAllCommissionFeedback()` at boot. `feedbackWindow` stays
+ * on the machine-local record (a per-machine directive-tuning knob).
*
* Mutations emit `commission:changed` on `commissionEvents` so the scheduler
* re-arms crons off the DATA changing (any writer), not off the three REST
@@ -44,6 +48,12 @@ import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/p
import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
import { isValidCron } from '../eventScheduler.js';
import { commissionToCron } from './directive.js';
+import {
+ recordFeedback,
+ listFeedbackForCommission,
+ listFeedbackByCommissionIds,
+ backfillInlineFeedback,
+} from './feedbackStore.js';
// Emits `commission:changed` on any create/update/delete (not on run-record
// appends, which don't affect scheduling). The scheduler subscribes to re-sync.
@@ -279,15 +289,49 @@ export function assertValidSchedule(schedule) {
return cron;
}
+/**
+ * Persist `feedback: []` on the machine-local commission after its legacy inline
+ * reactions have been split into the federated store — WITHOUT bumping
+ * `updatedAt` (the storage migration doesn't change scheduling, so it must not
+ * re-arm crons or win an LWW it has no business in). Serialized on the per-id
+ * queue like every other RMW here.
+ */
+async function clearInlineFeedback(id) {
+ const store = commissionStore();
+ await store.queueRecordWrite(id, async () => {
+ const currentRaw = await store.readRaw(id);
+ if (!currentRaw) return;
+ const current = sanitizeCommission(currentRaw);
+ if (current.feedback.length === 0) return;
+ await store.writeRaw(id, { ...current, feedback: [] });
+ });
+}
+
export async function listCommissions() {
const raw = await commissionStore().listRaw();
- return raw.map(sanitizeCommission).filter(Boolean);
+ const recs = raw.map(sanitizeCommission).filter(Boolean);
+ // Hydrate the federated feedback view (read-through) in ONE pass — feedback is
+ // no longer stored inline on the machine-local commission (#2686). Read-only:
+ // any un-migrated legacy inline feedback is split lazily by getCommission /
+ // backfillAllCommissionFeedback, not on this hot list path.
+ const byId = await listFeedbackByCommissionIds(recs.map((r) => r.id)).catch(() => new Map());
+ for (const r of recs) r.feedback = byId.get(r.id) || [];
+ return recs;
}
export async function getCommission(id) {
const raw = await commissionStore().readRaw(id);
const rec = raw ? sanitizeCommission(raw) : null;
if (!rec) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
+ // Lazily migrate any legacy inline feedback (Phase 2 storage) into the
+ // federated store, then clear it — so the scheduler's pre-fire read and the
+ // route GET always see the federated feedback even before the boot backfill
+ // runs. Idempotent (deterministic ids, never-clobber upsert).
+ if (rec.feedback.length > 0) {
+ await backfillInlineFeedback(id, rec.feedback).catch(() => {});
+ await clearInlineFeedback(id).catch(() => {});
+ }
+ rec.feedback = await listFeedbackForCommission(id).catch(() => []);
return rec;
}
@@ -419,35 +463,48 @@ export async function recordCommissionRun(id, runEntry) {
* recordCommissionRun, which also stays silent).
*/
export async function submitCommissionFeedback(id, input) {
- const store = commissionStore();
- const result = await store.queueRecordWrite(id, async () => {
- const currentRaw = await store.readRaw(id);
- if (!currentRaw) return { notFound: true };
- const current = sanitizeCommission(currentRaw);
- // The UI always rates a specific run; reject a runId that isn't on the record
- // so feedback can't dangle against a non-existent run.
- if (input?.runId && !current.runs.some((r) => r.id === input.runId)) {
- throw makeErr(`Run not found on commission: ${input.runId}`, ERR_VALIDATION);
- }
- const entry = sanitizeFeedbackEntry({
- ...input,
- id: `feedback-${randomUUID()}`,
- at: new Date().toISOString(),
- });
- if (!entry) throw makeErr('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);
- // UPSERT by runId, don't append: re-rating a run must REPLACE its prior
- // reaction, not stack a second one. The UI shows only the latest reaction per
- // run, but `renderFeedbackDigest` consumes every entry — so a stacked
- // like-then-dislike for the same run would fold BOTH a "like" and a "dislike"
- // for one output into the next directive, and repeated votes would each burn a
- // `feedbackWindow` slot. Dropping the prior same-runId entry keeps one reaction
- // per run and moves the re-rated run to the most-recent position.
- const prior = (current.feedback || []).filter((f) => !f.runId || f.runId !== entry.runId);
- const feedback = [...prior, entry].slice(-MAX_PERSISTED_FEEDBACK);
- const next = { ...current, feedback, updatedAt: new Date().toISOString() };
- await store.writeRaw(id, next);
- return { record: next };
+ // getCommission validates existence (→404), hydrates the federated feedback
+ // view, and lazily splits any legacy inline reactions into the federated store.
+ const commission = await getCommission(id);
+ // The UI always rates a specific run; reject a runId that isn't on the record
+ // so feedback can't dangle against a non-existent run.
+ if (input?.runId && !commission.runs.some((r) => r.id === input.runId)) {
+ throw makeErr(`Run not found on commission: ${input.runId}`, ERR_VALIDATION);
+ }
+ // Write to the FEDERATED feedback store (#2686): one record per reaction,
+ // deterministic id per run so a re-rating LWW-updates in place (one reaction
+ // per run) and the change propagates to every sync peer — the machine-local
+ // commission no longer carries feedback inline.
+ const rec = await recordFeedback({
+ commissionId: id,
+ runId: input?.runId ?? null,
+ rating: input?.rating,
+ note: input?.note,
+ tags: input?.tags,
});
- if (result?.notFound) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
- return result.record;
+ if (!rec) throw makeErr('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);
+ commission.feedback = await listFeedbackForCommission(id).catch(() => []);
+ return commission;
+}
+
+/**
+ * Boot-time backfill (#2686 split-record migration): move every commission's
+ * legacy INLINE feedback into the federated store and clear the inline array.
+ * Idempotent — after the first pass commissions carry `feedback: []`, so a
+ * re-run is a no-op. Invoked from server boot after the DB is ready (the
+ * scripts/migrations runner executes before the pool is up, so the data move
+ * can't live there — see migration 194's registration stub).
+ */
+export async function backfillAllCommissionFeedback() {
+ const raw = await commissionStore().listRaw();
+ let migrated = 0;
+ for (const r of raw) {
+ const rec = sanitizeCommission(r);
+ if (!rec || rec.feedback.length === 0) continue;
+ await backfillInlineFeedback(rec.id, rec.feedback).catch(() => {});
+ await clearInlineFeedback(rec.id).catch(() => {});
+ migrated += 1;
+ }
+ if (migrated > 0) console.log(`🎯 Commission feedback: split ${migrated} commission(s)' inline reactions into the federated store (#2686)`);
+ return { migrated };
}
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 791e49c7ee..9ae1ede0df 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -2,18 +2,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { creativeCommissionUpdateSchema } from '../../lib/creativeCommissionValidation.js';
// In-memory collectionStore so CRUD is exercised without touching the filesystem.
+// Keyed by collection `type` so the machine-local commission store and the
+// federated commissionFeedback store (#2686) don't share one map — `records` is
+// the commission map the assertions reach into directly.
const records = new Map();
-const makeMemStore = () => ({
- loadAll: async () => [...records.values()],
- loadOne: async (id) => records.get(id) || null,
- saveOne: async (id, rec) => { records.set(id, rec); },
- saveOneNow: async (id, rec) => { records.set(id, rec); },
- deleteOne: async (id) => { records.delete(id); },
- deleteOneNow: async (id) => { records.delete(id); },
- saveTypeIndex: async () => {},
- verifySchemaVersion: async () => ({ ok: true }),
-});
-vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: () => makeMemStore() }));
+const feedbackRecords = new Map();
+const mapForType = (type) => (type === 'commission-feedback' ? feedbackRecords : records);
+const makeMemStore = (type) => {
+ const store = mapForType(type);
+ return {
+ loadAll: async () => [...store.values()],
+ loadOne: async (id) => store.get(id) || null,
+ saveOne: async (id, rec) => { store.set(id, rec); },
+ saveOneNow: async (id, rec) => { store.set(id, rec); },
+ deleteOne: async (id) => { store.delete(id); },
+ deleteOneNow: async (id) => { store.delete(id); },
+ saveTypeIndex: async () => {},
+ verifySchemaVersion: async () => ({ ok: true }),
+ };
+};
+vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: ({ type }) => makeMemStore(type) }));
vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data' } }));
const {
@@ -31,7 +39,7 @@ const {
} = await import('./store.js');
const { buildCommissionDirective } = await import('./directive.js');
-beforeEach(() => records.clear());
+beforeEach(() => { records.clear(); feedbackRecords.clear(); });
const validInput = () => ({
name: 'Nightly Surreal',
@@ -242,7 +250,9 @@ describe('submitCommissionFeedback', () => {
const updated = await submitCommissionFeedback(created.id, { runId: 'run-A', rating: 'up', note: 'more Magritte' });
expect(updated.feedback).toHaveLength(1);
expect(updated.feedback[0]).toMatchObject({ runId: 'run-A', rating: 'up', note: 'more Magritte' });
- expect(updated.feedback[0].id).toMatch(/^feedback-/);
+ // Feedback now lives in the federated commissionFeedback store (#2686), keyed
+ // by a deterministic per-run id so a re-rating LWW-updates in place.
+ expect(updated.feedback[0].id).toMatch(/^cfeedback-/);
});
it('closes the loop: the reaction folds into the next directive', async () => {
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 85dc1a5c26..ef71e1f130 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1124,6 +1124,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// file-snapshot category). Gated at applyIncomingPush via
// compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.musicVideoProject.
'musicVideoProjects',
+ // Creative Commission feedback (#2686) → per-record peer-push only (no 60s
+ // file-snapshot category). Gated at applyIncomingPush via
+ // compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.commissionFeedback.
+ 'commissionFeedback',
// 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's
diff --git a/server/services/instances.js b/server/services/instances.js
index 0b90a1969e..b544fd6030 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -280,6 +280,7 @@ const DEFAULT_SYNC_CATEGORIES = {
writersRoomFolders: false,
writersRoomExercises: false,
musicVideoProjects: false,
+ commissionFeedback: false,
catalog: false
};
@@ -317,6 +318,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([
['writersRoomFolders', 'writersRoomFolder'],
['writersRoomExercises', 'writersRoomExercise'],
['musicVideoProjects', 'musicVideoProject'],
+ ['commissionFeedback', 'commissionFeedback'],
]);
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.js
index 7d248d3ead..3ac9a31a97 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -38,6 +38,7 @@ import { listProjects } from '../creativeDirector/local.js';
import { listProjects as listMusicVideoProjects } from '../musicVideo/projects.js';
import { listBoards } from '../moodBoard/index.js';
import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';
+import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';
import { initCursor, removeCursor as removeTombstoneCursor } from './peerTombstoneCursors.js';
import {
PEER_SUBSCRIBABLE_KINDS,
@@ -390,6 +391,10 @@ async function listRecordsForKind(recordKind) {
records = await listExercisesForSync().catch(() => []);
} else if (recordKind === 'musicVideoProject') {
records = await listMusicVideoProjects({ includeDeleted: false }).catch(() => []);
+ } else if (recordKind === 'commissionFeedback') {
+ // Live feedback reactions as { id, updatedAt } (#2686) — same coverage-compare
+ // reason as folders. Body-less, so no asset manifest backfill.
+ records = await listCommissionFeedbackForSync().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.js
index 132d9caeef..671a59366d 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -152,6 +152,13 @@ vi.mock('../writersRoom/sync.js', async (importOriginal) => ({
listFoldersForSync: vi.fn().mockResolvedValue([]),
listExercisesForSync: vi.fn().mockResolvedValue([]),
}));
+// #2686: commissionFeedback is a per-record store peerSync's getFullSyncCoverageForPeer
+// iterates via PEER_SUBSCRIBABLE_KINDS. Mock the lister so the zero-records
+// coverage assertions don't read the real (dev-Postgres) backend.
+vi.mock('../creativeCommissions/feedbackStore.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listCommissionFeedbackForSync: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../../lib/peerHttpClient.js', async () => ({
peerFetch: vi.fn(),
@@ -233,6 +240,7 @@ import { listAuthors } from '../authors/index.js';
import { listProjects as listCreativeDirectorProjects } from '../creativeDirector/local.js';
import { listBoards } from '../moodBoard/index.js';
import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';
+import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import { reconcileMediaAssets } from '../mediaAssetIndex/index.js';
import { getBackendName } from '../memoryBackend.js';
@@ -341,6 +349,7 @@ beforeEach(async () => {
vi.mocked(listWorksForSync).mockReset().mockResolvedValue([]);
vi.mocked(listFoldersForSync).mockReset().mockResolvedValue([]);
vi.mocked(listExercisesForSync).mockReset().mockResolvedValue([]);
+ vi.mocked(listCommissionFeedbackForSync).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');
@@ -387,7 +396,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']);
+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']);
});
});
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index fed078ffe3..d089cb9238 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -45,6 +45,7 @@ import {
getFolderForSync,
getExerciseForSync,
} from '../writersRoom/sync.js';
+import { getCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';
import { ackDeletesUpTo } from './peerTombstoneCursors.js';
import {
buildAssetManifestWithCollection,
@@ -150,6 +151,10 @@ async function isSubscriptionRecordTombstone(sub) {
const record = await getMusicVideoProject(sub.recordId, { includeDeleted: true }).catch(() => null);
return record?.deleted === true;
}
+ if (sub.recordKind === 'commissionFeedback') {
+ const record = await getCommissionFeedbackForSync(sub.recordId).catch(() => null);
+ return record?.deleted === true;
+ }
return false;
}
@@ -824,6 +829,15 @@ export async function buildPushPayload(sub, sourceInstanceId) {
...(linkedTrack ? { linkedTrack } : {}),
};
}
+ if (sub.recordKind === 'commissionFeedback') {
+ // Body-less (#2686) — no asset manifest, just the LWW record envelope
+ // (one taste reaction). A tombstone ships the same shape (deleted:true).
+ const record = await getCommissionFeedbackForSync(sub.recordId).catch(() => null);
+ if (!record) return null;
+ const sanitized = sanitizeRecordForWire('commissionFeedback', record);
+ if (!sanitized) return null;
+ return { kind: 'commissionFeedback', record: sanitized, assetManifest: [], sourceInstanceId, portosMeta };
+ }
return null;
}
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index 0bdc5bc0d7..d400b7e624 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -40,6 +40,7 @@ import {
getExerciseForSync,
mergeExercisesFromSync,
} from '../writersRoom/sync.js';
+import { getCommissionFeedbackForSync, mergeCommissionFeedbackFromSync } from '../creativeCommissions/feedbackStore.js';
import {
ackDeletesUpTo,
} from './peerTombstoneCursors.js';
@@ -318,6 +319,8 @@ export async function applyIncomingPush(payload) {
// gates whether a PRESENT-but-different local draft body may be overwritten —
// a stale push that lost the LWW must NOT clobber newer local prose.
workMergeApplied = mergeResult?.applied === true;
+ } else if (kind === 'commissionFeedback') {
+ await mergeCommissionFeedbackFromSync([record], { source });
} else if (kind === 'writersRoomFolder') {
await mergeFoldersFromSync([record], { source });
} else if (kind === 'writersRoomExercise') {
@@ -658,5 +661,11 @@ async function classifyLocalRecord(recordKind, recordId) {
const p = await getMusicVideoProject(recordId, { includeDeleted: true }).catch(() => null);
return p ? 'syncable' : 'missing';
}
+ if (recordKind === 'commissionFeedback') {
+ // Body-less, no `ephemeral` concept (#2686) — a found reaction (live or
+ // tombstoned) is always 'syncable'. Same no-ping-pong guards as folders.
+ const fb = await getCommissionFeedbackForSync(recordId).catch(() => null);
+ return fb ? 'syncable' : 'missing';
+ }
return 'missing';
}
\ No newline at end of file
diff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.js
index 30cd09f385..5874d5ddbc 100644
--- a/server/services/sharing/peerSyncShared.js
+++ b/server/services/sharing/peerSyncShared.js
@@ -16,7 +16,7 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils
import { getPeers } from '../instances.js';
-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject']);
+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback']);
/**
* Cross-cutting event bus for the peer-sync receiver. The asset-pull worker
@@ -101,6 +101,7 @@ export const KIND_TO_CATEGORY = Object.freeze({
writersRoomFolder: 'writersRoomFolders',
writersRoomExercise: 'writersRoomExercises',
musicVideoProject: 'musicVideoProjects',
+ commissionFeedback: 'commissionFeedback',
});
export function peerAllowsOutbound(peer) {
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 9c0e48c343..31ed4077b7 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -55,6 +55,9 @@ import {
pruneTombstonedFolders, listFolderIdsForSync,
pruneTombstonedExercises, listExerciseIdsForSync,
} from '../writersRoom/sync.js';
+import {
+ pruneTombstonedCommissionFeedback, listCommissionFeedbackIdsForSync,
+} from '../creativeCommissions/feedbackStore.js';
import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';
import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
@@ -81,6 +84,7 @@ const LIVE_ID_LISTERS = Object.freeze({
writersRoomWork: () => listWorkIdsForSync(),
writersRoomFolder: () => listFolderIdsForSync(),
writersRoomExercise: () => listExerciseIdsForSync(),
+ commissionFeedback: () => listCommissionFeedbackIdsForSync(),
});
// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —
@@ -104,6 +108,7 @@ const ALL_ID_LISTERS = Object.freeze({
writersRoomWork: () => listWorkIdsForSync({ includeDeleted: true }),
writersRoomFolder: () => listFolderIdsForSync({ includeDeleted: true }),
writersRoomExercise: () => listExerciseIdsForSync({ includeDeleted: true }),
+ commissionFeedback: () => listCommissionFeedbackIdsForSync({ includeDeleted: true }),
});
// Build a kind-aware id-membership resolver for ONE sweep: lazily list each
@@ -347,6 +352,7 @@ function refusedFromCutoffs(cutoffs) {
workCutoff,
folderCutoff,
exerciseCutoff,
+ commissionFeedbackCutoff,
} = cutoffs;
if (universeCutoff === null) refused.push('universe');
// Issue tombstones ride series pushes — refused exactly when series is.
@@ -368,6 +374,7 @@ function refusedFromCutoffs(cutoffs) {
if (workCutoff === null) refused.push('writersRoomWork');
if (folderCutoff === null) refused.push('writersRoomFolder');
if (exerciseCutoff === null) refused.push('writersRoomExercise');
+ if (commissionFeedbackCutoff === null) refused.push('commissionFeedback');
return refused;
}
@@ -398,6 +405,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
workCutoff,
folderCutoff,
exerciseCutoff,
+ commissionFeedbackCutoff,
] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs }),
cutoffForKind('series', { peers, subs, now, graceMs }),
@@ -412,9 +420,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
cutoffForKind('writersRoomWork', { peers, subs, now, graceMs }),
cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs }),
cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs }),
+ cutoffForKind('commissionFeedback', { peers, subs, now, graceMs }),
]);
const issueCutoff = seriesCutoff;
- const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre] = await Promise.all([
+ const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre, cfb] = 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),
@@ -429,6 +438,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
workCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(workCutoff),
folderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(folderCutoff),
exerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(exerciseCutoff),
+ commissionFeedbackCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedCommissionFeedback(commissionFeedbackCutoff),
]);
// 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
@@ -459,9 +469,10 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =
writersRoomWorks: wr.pruned,
writersRoomFolders: wrf.pruned,
writersRoomExercises: wre.pruned,
+ commissionFeedback: cfb.pruned,
orphanBaseHashes: orphan.pruned,
orphanSubscriptions: orphanSubs.pruned,
- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }),
+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff }),
};
}
@@ -470,7 +481,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] = await Promise.all([
+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff] = await Promise.all([
cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),
cutoffForKind('series', { peers, subs, now, graceMs: 0 }),
cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),
@@ -484,8 +495,9 @@ export async function getSweepStatus({ now = Date.now() } = {}) {
cutoffForKind('writersRoomWork', { peers, subs, now, graceMs: 0 }),
cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs: 0 }),
cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs: 0 }),
+ cutoffForKind('commissionFeedback', { peers, subs, now, graceMs: 0 }),
]);
- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff }) };
+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff }) };
}
export const TOMBSTONE_GRACE_MS = GRACE_MS;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index fe0ac8b7ff..1cda08216e 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -56,6 +56,10 @@ vi.mock('../writersRoom/sync.js', () => ({
pruneTombstonedExercises: vi.fn().mockResolvedValue({ pruned: 0 }),
listExerciseIdsForSync: vi.fn().mockResolvedValue([]),
}));
+vi.mock('../creativeCommissions/feedbackStore.js', () => ({
+ pruneTombstonedCommissionFeedback: vi.fn().mockResolvedValue({ pruned: 0 }),
+ listCommissionFeedbackIdsForSync: vi.fn().mockResolvedValue([]),
+}));
vi.mock('../../lib/conflictJournal.js', () => ({
pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
@@ -464,6 +468,7 @@ describe('sweepTombstones — return shape', () => {
writersRoomWorks: 10,
writersRoomFolders: 11,
writersRoomExercises: 12,
+ commissionFeedback: 0,
orphanBaseHashes: 0,
orphanSubscriptions: 0,
refused: [],