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): prune commissions per-id — backend-truth eligibility, queued revalidate
[._.]/ Adam Eivyac8a302c7237
diff --git a/server/services/creativeCommissions/db.js b/server/services/creativeCommissions/db.jsindex f7193ea7f4..815b234df3 100644--- a/server/services/creativeCommissions/db.js+++ b/server/services/creativeCommissions/db.js@@ -96,6 +96,24 @@ export async function deleteRaw(id) {await query(`DELETE FROM creative_commissions WHERE id = $1`, [id]);}+/**+ * Ids eligible for pruneTombstoned, by the SAME `deleted_at` column predicate+ * the DELETE uses. The column is the backend's truth — writeRaw normalizes+ * malformed/out-of-range timestamps into it while preserving the JSON verbatim,+ * so an eligibility check against the raw JSON `deletedAt` can diverge from+ * what the DELETE would actually remove.+ */+export async function listPrunable(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return [];+ const cutoffIso = new Date(olderThanMs).toISOString();+ const { rows } = await query(+ `SELECT id FROM creative_commissions+ WHERE deleted = TRUE AND deleted_at IS NOT NULL AND deleted_at < $1`,+ [cutoffIso],+ );+ return rows.map((r) => r.id);+}+/** Hard-remove tombstoned commissions whose `deleted_at` is older than the cutoff; returns their ids. */export async function pruneTombstoned(olderThanMs) {if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex a0dd08d87d..a840e94880 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -315,6 +315,13 @@ function makeFileBackend(dir) {(await cs.loadAll()).filter((r) => includeDeleted || live(r)).map((r) => r.id),writeRaw: async (id, record) => { await ensureTypeIndex(); await cs.saveOneNow(id, record); return record; },deleteRaw: (id) => cs.deleteOneNow(id),+ // Same predicate as pruneTombstoned below — this backend's truth is the JSON.+ listPrunable: async (olderThanMs) => {+ if (!Number.isFinite(olderThanMs)) return [];+ return (await cs.loadAll())+ .filter((r) => r?.deleted === true && isStr(r.deletedAt) && Date.parse(r.deletedAt) < olderThanMs)+ .map((r) => r.id);+ },pruneTombstoned: async (olderThanMs) => {if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };const stale = (await cs.loadAll()).filter((r) => r?.deleted === true && isStr(r.deletedAt) && Date.parse(r.deletedAt) < olderThanMs);@@ -336,6 +343,7 @@ function makePgBackend(db) {listIds: db.listIds,writeRaw: db.writeRaw,deleteRaw: db.deleteRaw,+ listPrunable: db.listPrunable,pruneTombstoned: db.pruneTombstoned,};}@@ -379,6 +387,7 @@ function createFacade(dir) {listIds: async (opts) => (await getBackend()).listIds(opts),writeRaw: async (id, record) => (await getBackend()).writeRaw(id, record),deleteRaw: async (id) => (await getBackend()).deleteRaw(id),+ listPrunable: async (olderThanMs) => (await getBackend()).listPrunable(olderThanMs),pruneTombstoned: async (olderThanMs) => (await getBackend()).pruneTombstoned(olderThanMs),queueRecordWrite,// Under PG, report ok WITHOUT forcing backend selection (the early boot@@ -782,19 +791,34 @@ export async function mergeCommissionsFromSync(remoteRecords, { source = { via:/** Hard-remove tombstoned commissions older than the cutoff; evicts each base hash. */export async function pruneTombstonedCommissions(olderThanMs) {- // Tombstone each stale commission's feedback BEFORE hard-pruning the- // commission. Once the prune removes the record there is nothing left for a- // later sweep to rediscover, so a failure after the prune would leave the- // feedback live (and peer-pushed) forever. In this order a failure throws,- // the commission tombstone stays put, and the next sweep retries both halves.- if (Number.isFinite(olderThanMs)) {- const stale = (await commissionStore().listRaw({ includeDeleted: true }))- .filter((r) => r?.deleted === true && isStr(r.deletedAt) && Date.parse(r.deletedAt) < olderThanMs);- for (const r of stale) await tombstoneFeedbackForCommission(r.id);+ if (!Number.isFinite(olderThanMs)) return { pruned: 0, ids: [] };+ const store = commissionStore();+ // Eligibility comes from the BACKEND's own predicate (`listPrunable` mirrors+ // pruneTombstoned's — on PG that is the normalized `deleted_at` column, which+ // writeRaw corrects while leaving the JSON verbatim), so the set we tombstone+ // feedback for is exactly the set the delete would remove. Then each id is+ // revalidated and deleted INSIDE its per-id write queue — the same queue+ // restoreCommission and the peer merge write through — so a restore that+ // lands mid-sweep either runs before us (we see deleted:false and keep its+ // feedback) or after (it finds the record gone and reports ERR_TARGET_GONE,+ // exactly as if it raced the old bulk prune). Feedback is tombstoned before+ // the row delete: a failure there throws, the commission tombstone stays+ // put, and the next sweep retries both halves — never an orphaned rating.+ const candidates = await store.listPrunable(olderThanMs);+ const ids = [];+ for (const id of candidates) {+ const pruned = await store.queueRecordWrite(id, async () => {+ const rec = await store.readRaw(id, { includeDeleted: true });+ if (!rec || rec.deleted !== true) return false; // restored mid-sweep — keep its feedback+ await tombstoneFeedbackForCommission(id);+ await store.deleteRaw(id);+ return true;+ });+ if (!pruned) continue;+ ids.push(id);+ await deleteSyncBaseHash(CREATIVE_COMMISSION_KIND, id).catch(() => {});}- const result = await commissionStore().pruneTombstoned(olderThanMs);- for (const id of result.ids || []) await deleteSyncBaseHash(CREATIVE_COMMISSION_KIND, id).catch(() => {});- return result;+ return { pruned: ids.length, ids };}/**diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 48d6ecc977..818536e4dd 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -54,6 +54,7 @@ const {getCommissionForSync,mergeCommissionsFromSync,pruneTombstonedCommissions,+ commissionStore,ERR_VALIDATION,ERR_NOT_FOUND,} = await import('./store.js');@@ -288,6 +289,37 @@ describe('pruneTombstonedCommissions', () => {expect(rows.length).toBeGreaterThan(0);for (const f of rows) expect(f.deleted).toBe(true);});++ it('a restore landing mid-sweep keeps its feedback (revalidated inside the per-id queue)', async () => {+ const created = await createCommission(validInput());+ await recordCommissionRun(created.id, { id: 'run-A', status: 'completed' });+ await submitCommissionFeedback(created.id, { runId: 'run-A', rating: 'up', note: 'keep me' });+ await deleteCommission(created.id);+ records.set(created.id, { ...records.get(created.id), deletedAt: '2020-01-01T00:00:00.000Z' });++ // Hold the commission's write queue with a gated "restore" so the sweep's+ // eligibility listing sees the stale tombstone, then let the restore land+ // FIRST — the sweep's queued revalidation must then skip the commission.+ const store = commissionStore();+ let releaseRestore;+ const gate = new Promise((resolve) => { releaseRestore = resolve; });+ const restoreDone = store.queueRecordWrite(created.id, async () => {+ await gate;+ const rec = await store.readRaw(created.id, { includeDeleted: true });+ await store.writeRaw(created.id, { ...rec, deleted: false, deletedAt: null });+ });+ const prunePromise = pruneTombstonedCommissions(Date.parse('2021-01-01T00:00:00.000Z'));+ await new Promise((resolve) => setTimeout(resolve, 10)); // let listPrunable observe the tombstone+ releaseRestore();+ const result = await prunePromise;+ await restoreDone;++ expect(result).toEqual({ pruned: 0, ids: [] });+ expect(records.get(created.id)).toMatchObject({ deleted: false }); // restore won+ const rows = [...feedbackRecords.values()].filter((f) => f.commissionId === created.id);+ expect(rows.length).toBeGreaterThan(0);+ for (const f of rows) expect(f.deleted).not.toBe(true); // ratings survived+ });});describe('sanitizeFeedbackEntry', () => {