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): dormant remote commission inserts, brief-scoped LWW clock, preserve un-migrated feedback on merge, cap after sync
[._.]/ Adam Eivy1b22f1200b2a
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 6c006d3b07..015c0325d7 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -365,9 +365,9 @@ export const RESTORABLE_FIELDS = Object.freeze({// `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'],+ // machine-local schedule/runs/assignment/enabled are never in a snapshot+ // (stripped from the wire) so they're excluded.+ creativeCommission: ['name', '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/syncWire.js b/server/lib/syncWire.jsindex 298f26bc2f..f8a7724b38 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -205,18 +205,24 @@ export function sanitizeRecordForWire(kind, 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) };+ // the SAME commission on every peer — but `schedule`, `runs`, `assignment`,+ // and `enabled` are MACHINE-LOCAL and MUST NOT transit: a federated schedule+ // (or enabled flag) would arm/double-run the cron 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 them; the receiver keeps its OWN values on merge+ // (preserveLocalCommissionFields) and a fresh insert lands dormant. `feedback`+ // never rides here either — it federates as its own `commissionFeedback`+ // record kind. The LWW key on the wire is the BRIEF clock (`briefUpdatedAt`),+ // NOT the general `updatedAt` (which local-only edits bump) — so a+ // schedule-only edit can't push a stale brief and a delayed brief edit still+ // wins. Whole-record LWW over what remains (id/name/targetAbility/brief/+ // generation/feedbackWindow), hashed in full by contentHashForRecord.+ const { deleted: _d, deletedAt: _da, schedule: _s, runs: _r, assignment: _a,+ feedback: _f, enabled: _e, briefUpdatedAt: _bu, updatedAt: _ua, ...rest } = record;+ const briefClock = typeof record.briefUpdatedAt === 'string' ? record.briefUpdatedAt+ : (typeof record.updatedAt === 'string' ? record.updatedAt : undefined);+ return { ...rest, ...(briefClock ? { updatedAt: briefClock } : {}), ...sanitizeSoftDeleteFields(record) };}default:return null;diff --git a/server/services/creativeCommissions/feedbackStore.js b/server/services/creativeCommissions/feedbackStore.jsindex ba7327a822..2e3df8349c 100644--- a/server/services/creativeCommissions/feedbackStore.js+++ b/server/services/creativeCommissions/feedbackStore.js@@ -281,24 +281,30 @@ export async function mergeCommissionFeedbackFromSync(remoteRecords, { source =if (!Array.isArray(remoteRecords)) return { applied: false, count: 0 };const store = feedbackStore();let changed = 0;+ const touchedCommissions = new Set();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 (!next) return null; // malformed remote → dropped+ if (!inserted && (!remoteWins || !didChange)) return null; // local wins, or no-opif (!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;+ return next;});- if (applied) changed += 1;+ if (applied) { changed += 1; if (applied.commissionId) touchedCommissions.add(applied.commissionId); }}await flushBaseHashes();+ // Re-apply the per-commission live cap AFTER the batch — two disconnected peers+ // that each accumulated up-to-cap distinct reactions would otherwise leave the+ // receiver with up to 2× the cap live after reconnection. Tombstone the oldest+ // excess (sync-safe) on each commission the merge grew.+ for (const commissionId of touchedCommissions) await enforceFeedbackCap(commissionId).catch(() => {});return changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };}diff --git a/server/services/creativeCommissions/feedbackStore.test.js b/server/services/creativeCommissions/feedbackStore.test.jsindex e9fe6b7265..e032c2b8c7 100644--- a/server/services/creativeCommissions/feedbackStore.test.js+++ b/server/services/creativeCommissions/feedbackStore.test.js@@ -105,6 +105,18 @@ describe('federation facades', () => {expect(live).toEqual([{ id: 'cfeedback-run-Z', updatedAt: '2026-05-05T00:00:00.000Z' }]);});+ it('re-applies the per-commission cap AFTER a sync merge (two peers reconciling cannot exceed the bound)', async () => {+ const { MAX_LIVE_FEEDBACK_PER_COMMISSION } = await import('./feedbackStore.js');+ // Simulate a reconnection delivering a batch that pushes past the cap.+ const batch = Array.from({ length: MAX_LIVE_FEEDBACK_PER_COMMISSION + 5 }, (_, i) => ({+ id: `cfeedback-run-${String(i).padStart(4, '0')}`, commissionId: 'c9', runId: `run-${i}`,+ rating: 'up', at: new Date(2026, 0, 1, 0, i).toISOString(), updatedAt: new Date(2026, 0, 1, 0, i).toISOString(),+ }));+ await mergeCommissionFeedbackFromSync(batch, { source: { via: 'sync', peerId: 'peer-a' } });+ const live = await listFeedbackForCommission('c9');+ expect(live).toHaveLength(MAX_LIVE_FEEDBACK_PER_COMMISSION);+ });+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';diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 4b3e963f34..1e3b626862 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -176,6 +176,14 @@ 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),+ // Brief-scoped LWW clock (#2686). The federation compares THIS, not `updatedAt`+ // — because `updatedAt` is bumped by machine-local edits (a schedule change, a+ // recordCommissionRun append) that must NOT let a stale brief win the LWW or a+ // schedule-only edit push a stale brief. `briefUpdatedAt` advances ONLY when a+ // federated field (name/targetAbility/brief/generation/feedbackWindow) changes.+ // Pre-#2686 records fall back to `updatedAt`.+ briefUpdatedAt: isStr(raw.briefUpdatedAt) ? raw.briefUpdatedAt+ : (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@@ -206,26 +214,47 @@ export function sanitizeCommissionForSync(raw) {return sanitizeCommission(raw);}-/** Re-attach the receiver's local-only schedule/runs/assignment onto a winning remote. */+// The MACHINE-LOCAL fields that never travel on the wire — the receiver keeps its+// OWN values for all of these. `enabled` is machine-local too (#2686): a remotely-+// inserted commission must NOT arm a cron on the receiver, so each machine decides+// whether/when it runs. `feedback` is preserved so a remote brief-win can't wipe a+// commission's un-migrated legacy inline reactions before the boot backfill runs.+const LOCAL_COMMISSION_FIELDS = ['schedule', 'runs', 'assignment', 'enabled', 'feedback'];+// The federated brief fields — a patch touching any of these advances the brief+// LWW clock (`briefUpdatedAt`); a machine-local-only patch does not.+const FEDERATED_COMMISSION_FIELDS = ['name', 'targetAbility', 'brief', 'generation', 'feedbackWindow'];++/** Re-attach the receiver's local-only fields onto a winning remote; bump the UI clock. */function preserveLocalCommissionFields(remote, local) {if (!local) return remote;- return { ...remote, schedule: local.schedule, runs: local.runs, assignment: local.assignment };+ const out = { ...remote };+ for (const f of LOCAL_COMMISSION_FIELDS) out[f] = local[f];+ // The wire form set `updatedAt = briefUpdatedAt`; restore a real UI "last-changed"+ // clock (max of the two) while keeping the federated brief clock as the LWW key.+ out.updatedAt = new Date().toISOString();+ return out;}/*** 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.+ * remote is sanitized here (drop-on-floor → null); a missing local INSERTS the+ * brief in a DORMANT state (enabled:false, no usable schedule) so it never fires+ * on the receiver until the user opts in; else the newer BRIEF clock wins, and the+ * receiver's machine-local schedule/runs/assignment/enabled/feedback carry forward+ * (they never travel), so a peer's brief edit can't arm or reset this machine.*/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;+ if (!local) {+ // Dormant insert: enabled:false + the sanitizer's null-time schedule (no cron)+ // so editing only the synced brief on the receiver can't silently arm a daily+ // run. The user explicitly enables + schedules it locally to activate.+ return { next: { ...remote, enabled: false }, inserted: true, remoteWins: true, changed: true };+ }+ const sanitizedLocal = sanitizeCommission(local);+ const remoteWins = compareNewerWins(remote.briefUpdatedAt, sanitizedLocal.briefUpdatedAt);+ const next = remoteWins ? preserveLocalCommissionFields(remote, sanitizedLocal) : local;const changed = JSON.stringify(next) !== JSON.stringify(local);return { next, inserted: false, remoteWins, changed };}@@ -458,6 +487,7 @@ export async function updateCommission(id, patch) {const currentRaw = await store.readRaw(id);if (!currentRaw) return null;const current = sanitizeCommission(currentRaw);+ const nowIso = new Date().toISOString();const next = sanitizeCommission({...current,...patch,@@ -483,7 +513,14 @@ export async function updateCommission(id, patch) {assignment: patch.assignment ? patch.assignment : current.assignment,id,createdAt: current.createdAt,- updatedAt: new Date().toISOString(),+ updatedAt: nowIso,+ // Advance the federated BRIEF clock ONLY when a federated field changes —+ // a machine-local edit (schedule/assignment) must not poison the LWW key or+ // it could push a stale brief to peers / make a real brief edit lose. When it+ // DOES advance, it equals `updatedAt` (same `nowIso`); a local-only edit+ // leaves it at the prior value (< updatedAt).+ briefUpdatedAt: FEDERATED_COMMISSION_FIELDS.some((k) => k in patch)+ ? nowIso : current.briefUpdatedAt,});await store.writeRaw(id, next);return next;@@ -510,7 +547,10 @@ export async function deleteCommission(id) {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 });+ // Bump the BRIEF clock too — the tombstone is a brief-level change that must+ // win the briefUpdatedAt-keyed LWW on peers (otherwise it ties the pre-delete+ // brief and never propagates).+ await store.writeRaw(id, { ...current, deleted: true, deletedAt: now, updatedAt: now, briefUpdatedAt: now });return true;});if (!existed) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);@@ -633,10 +673,11 @@ export async function getCommissionForSync(id) {return raw ? sanitizeCommissionForSync(raw) : null;}-/** Every LIVE commission as `{ id, updatedAt }` for full-sync coverage compare. */+/** Every LIVE commission as `{ id, updatedAt }` for full-sync coverage compare.+ * `updatedAt` is the BRIEF clock (the wire LWW key), so coverage compares like-for-like. */export async function listCommissionsForSync() {const raw = await commissionStore().listRaw();- return raw.map(sanitizeCommissionForSync).filter(Boolean).map((r) => ({ id: r.id, updatedAt: r.updatedAt }));+ return raw.map(sanitizeCommissionForSync).filter(Boolean).map((r) => ({ id: r.id, updatedAt: r.briefUpdatedAt }));}/** Every commission id — live only by default, or all (incl. tombstones) for the sweep. */@@ -702,7 +743,9 @@ export async function restoreCommission(id, 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(),+ enabled: current.enabled,+ // Advance the brief clock so the restore wins the next LWW and re-pushes.+ deleted: false, deletedAt: null, updatedAt: new Date().toISOString(), briefUpdatedAt: new Date().toISOString(),});await store.writeRaw(id, next);return next;diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 3dc147d36b..893982c577 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -306,14 +306,43 @@ describe('commission BRIEF federation (#2686)', () => {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' };+ it('mergeCommissionsFromSync inserts a remote commission DORMANT (no cron, disabled) so it never double-runs', async () => {+ const remote = { id: 'commission-peer', name: 'From peer A', enabled: true, 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).+ // Dormant on the receiver: no usable schedule AND disabled, so the user must+ // explicitly enable + schedule it locally to activate — no double-run.expect(got.schedule.atLocalTime).toBeNull();+ expect(got.enabled).toBe(false);+ });++ it('a schedule-only edit does NOT advance the brief clock; a brief edit does', async () => {+ const created = await createCommission(validInput());+ const briefClock0 = records.get(created.id).briefUpdatedAt;+ await updateCommission(created.id, { schedule: { kind: 'DAILY', atLocalTime: '05:00' } });+ const afterSched = records.get(created.id);+ // Machine-local edit → brief clock preserved, so a peer's brief edit isn't+ // beaten by it (deterministic: the schedule path copies current.briefUpdatedAt).+ expect(afterSched.briefUpdatedAt).toBe(briefClock0);+ await updateCommission(created.id, { name: 'Renamed' });+ const afterName = records.get(created.id);+ // Federated edit → brief clock advances to the update moment (== updatedAt).+ expect(afterName.briefUpdatedAt).toBe(afterName.updatedAt);+ });++ it('a tombstone advances the brief clock so the delete wins the LWW on peers', async () => {+ const created = await createCommission(validInput());+ await deleteCommission(created.id);+ const tomb = records.get(created.id);+ expect(tomb.deleted).toBe(true);+ // Delete bumps the brief clock to the delete moment (== updatedAt == deletedAt),+ // so a peer's briefUpdatedAt-keyed LWW applies the tombstone.+ expect(tomb.briefUpdatedAt).toBe(tomb.updatedAt);+ expect(tomb.briefUpdatedAt).toBe(tomb.deletedAt);+ // The wire form's LWW key (updatedAt) is the brief clock — a peer will apply it.+ expect(sanitizeCommissionForSync(tomb).briefUpdatedAt).toBe(tomb.briefUpdatedAt);});it('getCommissionForSync surfaces a tombstone after delete', async () => {