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
rechunk and soft-delete child chunks with their parent scrap
[._.]/ Adam Eivy99b5ebe43a1b
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 66e21793d5..4ca8d948e4 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -312,23 +312,73 @@ export async function updateScrap(id, patch = {}) {}}if (fields.length === 0) return getScrap(id);- params.push(id);- // `AND deleted = false` keeps PATCH consistent with GET — a PATCH on a- // soft-deleted row returns zero rows so the route 404s, instead of silently- // mutating a row the next GET would refuse to return.- const result = await query(- `UPDATE catalog_scraps SET ${fields.join(', ')} WHERE id = $${idx} AND deleted = false RETURNING *`,- params,- );- return rowToScrap(result.rows[0]);++ // Editing a chunked parent's rawText makes its stored child chunks stale —+ // and extractIngredientsForScrap prefers existing children over the parent+ // text, so a re-extract would silently union the OLD corpus. When rawText is+ // patched on a parent/standalone scrap, rebuild the children from the new+ // text in the SAME transaction as the parent update so the two never diverge.+ const rechunk = patch.rawText !== undefined;++ return withTransaction(async (client) => {+ const exec = client.query.bind(client);+ params.push(id);+ // `AND deleted = false` keeps PATCH consistent with GET — a PATCH on a+ // soft-deleted row returns zero rows so the route 404s, instead of silently+ // mutating a row the next GET would refuse to return.+ const result = await exec(+ `UPDATE catalog_scraps SET ${fields.join(', ')} WHERE id = $${idx} AND deleted = false RETURNING *`,+ params,+ );+ const updated = rowToScrap(result.rows[0]);+ if (!updated) return null;++ // Only a parent/standalone scrap rechunks — patching a child (which the UI+ // never exposes) must not spawn grandchildren.+ if (rechunk && updated.parentScrapId === null) {+ // Tombstone the old children (deleted=true so the removal propagates to+ // peers; a plain DELETE would leave them as live orphans on a synced peer)+ // then re-derive fresh chunks from the new full text. listChildScraps+ // filters deleted=false, so only the fresh children are ever read.+ await exec(+ `UPDATE catalog_scraps SET deleted = true, deleted_at = NOW()+ WHERE parent_scrap_id = $1 AND deleted = false`,+ [id],+ );+ const chunks = chunkRawText(updated.rawText);+ if (chunks.length > 1) {+ for (let i = 0; i < chunks.length; i++) {+ await createScrap(+ {+ title: updated.title,+ rawText: chunks[i],+ sourceKind: updated.sourceKind,+ metadata: updated.metadata,+ chunkIndex: i + 1,+ parentScrapId: id,+ },+ { client },+ );+ }+ }+ }+ return updated;+ });}export async function deleteScrap(id, { hard = false } = {}) {if (hard) {+ // ON DELETE CASCADE (parent_scrap_id FK) removes the child chunk rows.await query(`DELETE FROM catalog_scraps WHERE id = $1`, [id]);} else {+ // Soft-delete the parent AND its child chunks together. Children are hidden+ // from the list but still sync as live scraps, so leaving them deleted=false+ // would leak orphaned chunk rows to peers (the FK CASCADE only fires on a+ // hard delete). `parent_scrap_id = id` matches the children, `id = $1` the+ // parent; `deleted = false` avoids re-stamping deleted_at on already-gone rows.await query(- `UPDATE catalog_scraps SET deleted = true, deleted_at = NOW() WHERE id = $1`,+ `UPDATE catalog_scraps SET deleted = true, deleted_at = NOW()+ WHERE (id = $1 OR parent_scrap_id = $1) AND deleted = false`,[id],);}diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.jsindex 971ccf8181..8cd3f9f816 100644--- a/server/services/catalogDB.test.js+++ b/server/services/catalogDB.test.js@@ -288,6 +288,44 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {}});+ it('patching a chunked parent rawText rebuilds its children from the new text', async () => {+ if (!requireDb('rechunk on patch')) return;+ const para = 'lorem ipsum dolor sit amet '.repeat(200); // ~5400 chars+ const rawText = Array.from({ length: 5 }, (_, i) => `Para ${i}: ${para}`).join('\n\n');+ const parent = await catalogDB.createChunkedScrap({ title: 'Editable', rawText, sourceKind: 'paste' });+ createdScrapIds.add(parent.id);+ const firstChildIds = (await catalogDB.listChildScraps(parent.id)).map((c) => c.id);+ expect(firstChildIds.length).toBeGreaterThan(1);++ // Edit the parent text → children must be rebuilt from the NEW corpus.+ const newText = Array.from({ length: 6 }, (_, i) => `Edited ${i}: ${para}`).join('\n\n');+ const updated = await catalogDB.updateScrap(parent.id, { rawText: newText });+ expect(updated.rawText).toBe(newText);++ const children = await catalogDB.listChildScraps(parent.id);+ // Fresh children (old ones tombstoned, not returned) and they reassemble the NEW text.+ expect(children.map((c) => c.rawText).join('')).toBe(newText);+ for (const oldId of firstChildIds) {+ expect(children.some((c) => c.id === oldId), `stale child ${oldId} still live`).toBe(false);+ }+ });++ it('soft-deleting a chunked parent soft-deletes its children too', async () => {+ if (!requireDb('soft delete cascade')) return;+ const para = 'lorem ipsum dolor sit amet '.repeat(200);+ const rawText = Array.from({ length: 5 }, (_, i) => `Para ${i}: ${para}`).join('\n\n');+ const parent = await catalogDB.createChunkedScrap({ title: 'Deletable', rawText, sourceKind: 'paste' });+ createdScrapIds.add(parent.id);+ const childIds = (await catalogDB.listChildScraps(parent.id)).map((c) => c.id);+ expect(childIds.length).toBeGreaterThan(1);++ await catalogDB.deleteScrap(parent.id); // soft delete (the API path)++ // No live children remain — they don't leak to peers as orphaned live rows.+ expect(await catalogDB.listChildScraps(parent.id)).toHaveLength(0);+ expect(await catalogDB.getScrap(parent.id)).toBeNull();+ });+it('exportSliceForRef bundles ingredients + scraps + refs for a ref', async () => {if (!requireDb('export slice')) return;const ing = await catalogDB.createIngredient({