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

show a catalog ingredient's source scrap by title, with one-click siblings (#7617)

[._.]/ Adam Eivycff7315704ba
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index b173f6da93..de8ad7c882 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -16,7 +16,7 @@
*/
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { Link, useNavigate } from 'react-router';
+import { Link, useNavigate, useLocation } from 'react-router';
import { Sparkles, Plus, Search, FileInput, Loader2, RefreshCw, Wand2, X, LayoutGrid, Library, FolderPlus, Settings as SettingsIcon } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import Drawer from '../components/Drawer';
@@ -62,6 +62,7 @@ const REMIX_TARGETS = [
export default function Catalog() {
const navigate = useNavigate();
+ const location = useLocation();
// Catalog type definitions belong to this feature, so keep their settings
// drawer deep-linkable while leaving the catalog filters in the same URL.
const [settingsParam, setSettingsParam] = useDrawerTab('settings', null, ['1']);
@@ -81,7 +82,15 @@ export default function Catalog() {
const selectedUniverse = searchParams.get('universe') || '';
const selectedSeries = searchParams.get('series') || '';
const selectedTag = searchParams.get('tag') || '';
- const view = searchParams.get('view') === 'albums' ? 'albums' : 'grid';
+ // Source-scrap filter (#7617) — "everything extracted from this piece", set by
+ // the "From the same source" link on the ingredient detail page. Orthogonal to
+ // the album view: it always renders as a flat grid (a scrap's siblings aren't
+ // grouped by universe), and a click-through carries the scrap's title via
+ // router state for the filter banner label — a nice-to-have that a reload/
+ // share loses, while the filter itself (URL-driven) survives either.
+ const selectedScrap = searchParams.get('scrap') || '';
+ const scrapTitle = location.state?.scrapTitle || '';
+ const view = selectedScrap ? 'grid' : (searchParams.get('view') === 'albums' ? 'albums' : 'grid');
// Two-stage search: `searchInput` is what the user is typing; `q` is the
// debounced value that drives the list fetch (and is mirrored to the URL).
@@ -168,8 +177,9 @@ export default function Catalog() {
if (q) p.q = q;
if (selectedSeries) { p.refKind = 'series'; p.refId = selectedSeries; }
else if (selectedUniverse) { p.refKind = 'universe'; p.refId = selectedUniverse; }
+ if (selectedScrap) p.scrapId = selectedScrap;
return p;
- }, [selectedType, selectedTag, q, selectedSeries, selectedUniverse]);
+ }, [selectedType, selectedTag, q, selectedSeries, selectedUniverse, selectedScrap]);
// Fetch one page for the current filters; returns the items array (or null on
// error, already toasted). The caller owns replace-vs-append and its loading
@@ -261,12 +271,12 @@ export default function Catalog() {
return all.filter((s) => s.universeId === selectedUniverse);
}, [facets, selectedUniverse]);
- const hasActiveFilters = !!(selectedType || selectedUniverse || selectedSeries || selectedTag || q);
+ const hasActiveFilters = !!(selectedType || selectedUniverse || selectedSeries || selectedTag || q || selectedScrap);
const clearFilters = () => {
setSearchInput('');
setQ('');
- updateParams({ type: '', universe: '', series: '', tag: '', q: '' });
+ updateParams({ type: '', universe: '', series: '', tag: '', q: '', scrap: '' });
};
const handleCreate = async (e) => {
@@ -658,6 +668,23 @@ export default function Catalog() {
))}
</div>
+ {/* Source-scrap filter banner (#7617) — set by the "From the same source"
+ link on an ingredient's detail page. Shows the title when it arrived
+ via that link's router state; a reload/share still filters correctly
+ (the URL owns the filter) but falls back to a generic label since the
+ title didn't travel with it. */}
+ {selectedScrap && (
+ <div className="flex items-center justify-between gap-2 mb-4 px-3 py-2 rounded-lg border border-port-border bg-port-card text-sm text-gray-300">
+ <span className="truncate">
+ Filtered by source{scrapTitle ? <>: <span className="text-white font-medium">{scrapTitle}</span></> : ' scrap'}
+ </span>
+ <button type="button" onClick={() => updateParams({ scrap: '' })}
+ className="inline-flex items-center gap-1 text-xs text-gray-400 hover:text-white shrink-0">
+ <X size={12} aria-hidden="true" /> Clear
+ </button>
+ </div>
+ )}
+
{/* Universe / Series / Tag dropdowns + Clear filters. Two columns on a
phone (a fixed min-width would overflow a 320px viewport), free-flowing
from `sm` up. */}
diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsx
index 78b4727f8a..6a1ab9ab6e 100644
--- a/client/src/pages/Catalog.test.jsx
+++ b/client/src/pages/Catalog.test.jsx
@@ -356,6 +356,29 @@ describe('Catalog page', () => {
});
});
+ it('filters to a source scrap via `?scrap=`, shows the filter banner, and clears it on demand (#7617)', async () => {
+ renderCatalog('/catalog?scrap=cat-scrap-1');
+ await waitFor(() => {
+ expect(listCatalogIngredients).toHaveBeenLastCalledWith(
+ expect.objectContaining({ scrapId: 'cat-scrap-1' }),
+ );
+ });
+ expect(screen.getByText(/Filtered by source/)).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
+ await waitFor(() => expect(screen.getByTestId('catalog-location').textContent).toBe('/catalog'));
+ expect(screen.queryByText(/Filtered by source/)).toBeNull();
+ });
+
+ it('shows the source scrap title in the filter banner when it arrives via router state', async () => {
+ render(
+ <MemoryRouter initialEntries={[{ pathname: '/catalog', search: '?scrap=cat-scrap-1', state: { scrapTitle: 'Notebook Page Three' } }]}>
+ <Catalog />
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(screen.getByText('Notebook Page Three')).toBeTruthy());
+ });
+
it('paginates with "Load more", appending the next page at the right offset', async () => {
const firstPage = Array.from({ length: 60 }, (_, i) => ({
id: `p-${i}`, name: `Item ${i}`, type: 'idea', payload: {}, tags: [],
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 920d7fd834..dc0e1033a5 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -1431,6 +1431,13 @@ function GalleryPickerModal({ onClose, onPick }) {
);
}
+// Source scraps + "From the same source" siblings (#7617). Each source scrap's
+// TITLE is the click-through to `/catalog?scrap=<id>` — every other extraction
+// from that piece, one click, one shareable link (selection lives in the URL
+// per client/src/AGENTS.md). The scrap's id is a fallback label only for a
+// scrap whose title didn't come through (e.g. hard-deleted; `scrapTitle` is
+// null via the route's LEFT JOIN). A scrap with no OTHER live extractions
+// renders no "From the same source" stub — an empty list is not useful chrome.
function SourcesPanel({ sources }) {
const list = Array.isArray(sources) ? sources : [];
return (
@@ -1439,13 +1446,44 @@ function SourcesPanel({ sources }) {
{list.length === 0 ? (
<p className="text-xs text-gray-500">Created manually — no source scrap.</p>
) : (
- <ul className="space-y-1.5">
- {list.map((s, i) => (
- <li key={s.scrapId || i} className="text-xs text-gray-300 flex items-center justify-between gap-2">
- <span className="font-mono truncate" title={s.scrapId}>{s.scrapId}</span>
- {s.extractedAt && <span className="text-gray-500 whitespace-nowrap">{formatDateTime(s.extractedAt)}</span>}
- </li>
- ))}
+ <ul className="space-y-3">
+ {list.map((s, i) => {
+ const siblings = Array.isArray(s.siblings) ? s.siblings : [];
+ return (
+ <li key={s.scrapId || i} className="text-xs text-gray-300">
+ <div className="flex items-center justify-between gap-2">
+ {s.scrapId ? (
+ <Link to={`/catalog?scrap=${encodeURIComponent(s.scrapId)}`}
+ state={{ scrapTitle: s.scrapTitle || undefined }}
+ className="truncate hover:text-port-accent hover:underline"
+ title={s.scrapTitle || s.scrapId}>
+ {s.scrapTitle || s.scrapId}
+ </Link>
+ ) : (
+ <span className="font-mono truncate">(unknown source)</span>
+ )}
+ {s.extractedAt && <span className="text-gray-500 whitespace-nowrap">{formatDateTime(s.extractedAt)}</span>}
+ </div>
+ {siblings.length > 0 && (
+ <div className="mt-1.5 pl-2 border-l border-port-border">
+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">From the same source</div>
+ <div className="flex flex-wrap gap-1.5">
+ {siblings.map((sib) => {
+ const badge = CATALOG_BADGE_BY_ID[sib.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
+ return (
+ <Link key={sib.id} to={`/catalog/${encodeURIComponent(sib.type || 'idea')}/${encodeURIComponent(sib.id)}`}
+ className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200 hover:opacity-80">
+ <span className="truncate max-w-[12rem]">{sib.name || sib.id}</span>
+ <span className={`text-[9px] uppercase tracking-wider px-1 py-0.5 rounded border ${badge}`}>{sib.type}</span>
+ </Link>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </li>
+ );
+ })}
</ul>
)}
</section>
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index c6d2843f08..6d6070b7cb 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -260,6 +260,45 @@ describe('CatalogIngredient — character sheet', () => {
expect(screen.getByDisplayValue('Being underestimated.')).toBeTruthy();
});
+ it('shows the source scrap by TITLE (not the bare id) and links to it, with siblings from the same source (#7617)', async () => {
+ getCatalogIngredientDetails.mockImplementation(async () => detailsOf({
+ ...CHAR_FIXTURE,
+ sources: [{
+ scrapId: 'cat-scrap-abc123',
+ scrapTitle: 'Notebook Page Three',
+ extractedAt: '2026-01-01T00:00:00.000Z',
+ siblings: [{ id: 'cat-plc-1', name: 'Sibling Place', type: 'place' }],
+ }],
+ }));
+ renderPage();
+ await waitFor(() => expect(screen.getByText('Notebook Page Three')).toBeTruthy());
+ // Never the raw id — that's the bug this issue fixes.
+ expect(screen.queryByText('cat-scrap-abc123')).toBeNull();
+ const scrapLink = screen.getByText('Notebook Page Three').closest('a');
+ expect(scrapLink.getAttribute('href')).toBe('/catalog?scrap=cat-scrap-abc123');
+ // The sibling extraction from the same source scrap is listed and links to
+ // its own detail page.
+ expect(screen.getByText('From the same source')).toBeTruthy();
+ const siblingLink = screen.getByText('Sibling Place').closest('a');
+ expect(siblingLink.getAttribute('href')).toBe('/catalog/place/cat-plc-1');
+ });
+
+ it('renders no "From the same source" stub for a solo extraction or a manually-created ingredient (#7617)', async () => {
+ getCatalogIngredientDetails.mockImplementation(async () => detailsOf({
+ ...CHAR_FIXTURE,
+ sources: [{ scrapId: 'cat-scrap-solo', scrapTitle: 'Lone Page', extractedAt: null, siblings: [] }],
+ }));
+ renderPage();
+ await waitFor(() => expect(screen.getByText('Lone Page')).toBeTruthy());
+ expect(screen.queryByText('From the same source')).toBeNull();
+
+ // No source scrap at all (created manually) — the existing message, no stub.
+ getCatalogIngredientDetails.mockImplementation(async () => detailsOf({ ...CHAR_FIXTURE, sources: [] }));
+ renderPage();
+ await waitFor(() => expect(screen.getByText('Created manually — no source scrap.')).toBeTruthy());
+ expect(screen.queryByText('From the same source')).toBeNull();
+ });
+
it('renders EDITABLE array editors (color palette + stats + aliases) seeded from payload', async () => {
renderPage();
await waitFor(() => expect(screen.getByRole("button", { name: /Add color/i })).toBeTruthy());
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index e04fe13306..e94c09f97c 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -50,7 +50,7 @@ export const ingestCatalogBrain = (body = {}, options) =>
// --- Ingredients --------------------------------------------------------
-export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked, orphaned, limit, offset, ...options } = {}) => {
+export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked, orphaned, scrapId, limit, offset, ...options } = {}) => {
const params = new URLSearchParams();
if (type) params.set('type', type);
if (tag) params.set('tag', tag);
@@ -66,6 +66,9 @@ export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked,
} else if (orphaned) {
params.set('orphaned', 'true');
}
+ // Source-scrap filter (#7617) — "everything extracted from this piece".
+ // Orthogonal to the album filters above, so it composes with them.
+ if (scrapId) params.set('scrapId', scrapId);
if (limit) params.set('limit', String(limit));
if (offset) params.set('offset', String(offset));
return request(`/catalog/ingredients${params.toString() ? `?${params}` : ''}`, options);
diff --git a/client/src/services/apiCatalog.test.js b/client/src/services/apiCatalog.test.js
index 6e8e5e46c5..4f5a15a419 100644
--- a/client/src/services/apiCatalog.test.js
+++ b/client/src/services/apiCatalog.test.js
@@ -83,6 +83,13 @@ describe('listCatalogIngredients filter passthrough (#1762)', () => {
expect(path).not.toContain('unlinked');
expect(path).not.toContain('orphaned');
});
+
+ it('sends scrapId for the source-scrap filter, composed with a ref filter (#7617)', async () => {
+ await listCatalogIngredients({ scrapId: 'cat-scrap-1', refKind: 'universe', refId: 'u-1' });
+ const [path] = request.mock.calls[0];
+ expect(decodeURIComponent(path)).toContain('scrapId=cat-scrap-1');
+ expect(decodeURIComponent(path)).toContain('refKind=universe');
+ });
});
describe('getCatalogFacets (#1762)', () => {
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 4481e3d5d6..a2c3598091 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -32,6 +32,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**Examples.**
- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.
- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).
+- `catalog_scraps` / `catalog_ingredient_sources` — the catalog's SECOND grouping seam alongside refs (universe/series/work): a scrap is the raw pasted/imported text an ingredient was extracted from, and `catalog_ingredient_sources` links `(ingredient_id, scrap_id)` with an optional `span`. The ingredient detail page's `GET /ingredients/:id/details` joins the scrap's `title` onto each source link and batches every sibling ingredient extracted from the SAME scrap (`listSiblingIngredientsBySource`) in the one round-trip, so "what else came out of this piece?" is a rendered list, never a second fetch. `GET /ingredients?scrapId=<id>` (and `/catalog?scrap=<id>` client-side) filters the catalog to one scrap's whole extraction set — a provenance dimension orthogonal to the universe/series ref filters, so it composes with them rather than joining their mutual-exclusivity rule (#7617).
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and PII must not ride the federation layer (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 2e73c76c7d..cba4c70c58 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -311,6 +311,11 @@ export const catalogIngredientQuerySchema = z.object({
refId: z.string().trim().min(1).max(120).optional(),
unlinked: booleanish.optional(),
orphaned: booleanish.optional(),
+ // Source-scrap filter (#7617): "everything extracted from this piece" — a
+ // provenance dimension, orthogonal to the universe/series homing album
+ // filters above, so it composes with them instead of joining their
+ // mutual-exclusivity refinement below.
+ scrapId: z.string().trim().min(1).max(120).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
offset: z.coerce.number().int().min(0).optional(),
}).strict()
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index 29119d2efb..b1c68467f8 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -268,6 +268,15 @@ describe('catalogValidation — catalogIngredientQuerySchema', () => {
it('rejects an unknown refKind', () => {
expect(() => catalogIngredientQuerySchema.parse({ refKind: 'galaxy', refId: 'g-1' })).toThrow();
});
+
+ it('accepts scrapId and composes it with a ref/album filter (#7617, orthogonal provenance dimension)', () => {
+ expect(catalogIngredientQuerySchema.parse({ scrapId: 'cat-scrap-1' }).scrapId).toBe('cat-scrap-1');
+ // Unlike unlinked/orphaned/refKind, scrapId is NOT part of the mutual
+ // exclusivity refinement — it composes with a ref filter without throwing.
+ const out = catalogIngredientQuerySchema.parse({ refKind: 'universe', refId: 'u-1', scrapId: 'cat-scrap-1' });
+ expect(out.scrapId).toBe('cat-scrap-1');
+ expect(out.refId).toBe('u-1');
+ });
});
describe('catalogValidation — catalogIngredientLinkSchema', () => {
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index c0c98e75c1..488984443b 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -200,6 +200,7 @@ router.get('/ingredients', asyncHandler(async (req, res) => {
refId: params.refId,
unlinked: params.unlinked === true,
orphaned: params.orphaned === true,
+ scrapId: params.scrapId,
limit: params.limit ?? 50,
offset: params.offset ?? 0,
}));
@@ -250,12 +251,23 @@ router.get('/ingredients/:id/details', asyncHandler(async (req, res) => {
catalogDB.listMediaForIngredient(req.params.id),
catalogDB.getMissingMediaForIngredient(req.params.id),
]);
+ // "From the same source" (#7617): sibling ingredients extracted from each of
+ // THIS ingredient's source scraps, batched in one query so the detail page
+ // needs no second round-trip to answer "what else came out of this piece?".
+ const siblingsByScrap = await catalogDB.listSiblingIngredientsBySource(
+ req.params.id,
+ sources.map((s) => s.scrapId),
+ );
+ const sourcesWithSiblings = sources.map((s) => ({
+ ...s,
+ siblings: siblingsByScrap.get(s.scrapId) || [],
+ }));
const includeEmbedding = req.query.includeEmbedding === 'true';
const { embedding, ...rest } = ing;
res.json({
ingredient: includeEmbedding ? { ...rest, embedding } : rest,
refs,
- sources,
+ sources: sourcesWithSiblings,
relations, // { outbound, inbound }
revisions: Array.isArray(revisions?.items) ? revisions.items : [],
media, // array of attachments
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index 470f47279e..be7116e1a4 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -278,6 +278,31 @@ describe.skipIf(!runDb)('GET /api/catalog/ingredients/:id/details — batched hy
expect(r.status).toBe(404);
});
+ it('joins the source scrap title and lists sibling extractions, without a stub for a solo extraction (#7617)', async () => {
+ const scrap = await catalogDB.createScrap({ title: `Route Scrap ${NONCE}`, rawText: 'Two characters, one page.', sourceKind: 'paste' });
+ createdScrapIds.add(scrap.id);
+ const a = await catalogDB.createIngredient({ type: 'character', name: `Details Sibling A ${NONCE}` });
+ const b = await catalogDB.createIngredient({ type: 'character', name: `Details Sibling B ${NONCE}` });
+ const solo = await catalogDB.createIngredient({ type: 'idea', name: `Details Solo ${NONCE}` });
+ [a, b, solo].forEach((i) => createdIngredientIds.add(i.id));
+ await catalogDB.linkIngredientToSource(a.id, scrap.id);
+ await catalogDB.linkIngredientToSource(b.id, scrap.id);
+
+ const rA = await request(makeApp()).get(`/api/catalog/ingredients/${a.id}/details`);
+ expect(rA.status).toBe(200);
+ expect(rA.body.sources).toHaveLength(1);
+ expect(rA.body.sources[0].scrapTitle).toBe(`Route Scrap ${NONCE}`);
+ expect(rA.body.sources[0].siblings).toEqual([{ id: b.id, name: `Details Sibling B ${NONCE}`, type: 'character' }]);
+
+ // An ingredient with no other extraction from its scrap gets an EMPTY
+ // siblings array, not an absent field — the client renders no stub for it.
+ const soloScrap = await catalogDB.createScrap({ title: `Route Solo Scrap ${NONCE}`, rawText: 'Just one.', sourceKind: 'paste' });
+ createdScrapIds.add(soloScrap.id);
+ await catalogDB.linkIngredientToSource(solo.id, soloScrap.id);
+ const rSolo = await request(makeApp()).get(`/api/catalog/ingredients/${solo.id}/details`);
+ expect(rSolo.body.sources[0].siblings).toEqual([]);
+ });
+
it('omits dangling "Appears in" refs whose target was soft-deleted (#1812)', async () => {
const liveUni = `details-live-uni-${NONCE}`;
const deadUni = `details-dead-uni-${NONCE}`;
@@ -342,3 +367,21 @@ describe.skipIf(!runDb)('GET /api/catalog/facets + ingredient filters (#1762)',
expect(combined.status).toBe(400);
});
});
+
+describe.skipIf(!runDb)('GET /api/catalog/ingredients?scrapId= (#7617)', () => {
+ it('filters to ingredients extracted from the given source scrap', async () => {
+ const scrap = await catalogDB.createScrap({ title: `Filter Scrap ${NONCE}`, rawText: 'Filter probe text.', sourceKind: 'paste' });
+ createdScrapIds.add(scrap.id);
+ const inScrap = await catalogDB.createIngredient({ type: 'character', name: `Scrap Filter In ${NONCE}` });
+ const outOfScrap = await catalogDB.createIngredient({ type: 'character', name: `Scrap Filter Out ${NONCE}` });
+ createdIngredientIds.add(inScrap.id);
+ createdIngredientIds.add(outOfScrap.id);
+ await catalogDB.linkIngredientToSource(inScrap.id, scrap.id);
+
+ const r = await request(makeApp()).get(`/api/catalog/ingredients?scrapId=${scrap.id}`);
+ expect(r.status).toBe(200);
+ const ids = r.body.items.map((i) => i.id);
+ expect(ids).toContain(inScrap.id);
+ expect(ids).not.toContain(outOfScrap.id);
+ });
+});
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
index 08a9ceceb7..b39fc11011 100644
--- a/server/services/catalogDB.test.js
+++ b/server/services/catalogDB.test.js
@@ -353,6 +353,40 @@ describe.skipIf(!runDb)('catalogDB (Postgres CRUD round-trip)', () => {
expect(hydrated[0].rawText).toContain('long coat');
});
+ it('listSourcesForIngredient joins the scrap title, and listSiblingIngredientsBySource finds co-extractions (#7617)', async () => {
+ if (!requireDb('scrap title join + siblings')) return;
+ const scrap = await catalogDB.createScrap({ title: 'Shared Notebook Page', rawText: 'Two ideas on one page.', sourceKind: 'paste' });
+ createdScrapIds.add(scrap.id);
+ const a = await catalogDB.createIngredient({ type: 'character', name: 'Sibling A' });
+ const b = await catalogDB.createIngredient({ type: 'place', name: 'Sibling B' });
+ const solo = await catalogDB.createIngredient({ type: 'idea', name: 'Solo Extraction' });
+ [a, b, solo].forEach((i) => createdIngredientIds.add(i.id));
+ await catalogDB.linkIngredientToSource(a.id, scrap.id);
+ await catalogDB.linkIngredientToSource(b.id, scrap.id);
+
+ // The title rides along with the source link — no second fetch needed.
+ const sourcesA = await catalogDB.listSourcesForIngredient(a.id);
+ expect(sourcesA).toHaveLength(1);
+ expect(sourcesA[0].scrapTitle).toBe('Shared Notebook Page');
+
+ // A's siblings on this scrap are B (not itself).
+ const siblingsByScrap = await catalogDB.listSiblingIngredientsBySource(a.id, [scrap.id]);
+ const siblingsForScrap = siblingsByScrap.get(scrap.id);
+ expect(siblingsForScrap).toHaveLength(1);
+ expect(siblingsForScrap[0]).toMatchObject({ id: b.id, name: 'Sibling B', type: 'place' });
+
+ // A solo extraction (the only ingredient sourced from its scrap) has no
+ // siblings — the caller renders no "From the same source" stub for it.
+ const soloScrap = await catalogDB.createScrap({ title: 'Lone Page', rawText: 'Just one idea.', sourceKind: 'paste' });
+ createdScrapIds.add(soloScrap.id);
+ await catalogDB.linkIngredientToSource(solo.id, soloScrap.id);
+ const soloSiblings = await catalogDB.listSiblingIngredientsBySource(solo.id, [soloScrap.id]);
+ expect(soloSiblings.get(soloScrap.id)).toEqual([]);
+
+ // An ingredient with no source scrap at all gets an empty map, not a crash.
+ expect(await catalogDB.listSiblingIngredientsBySource(a.id, [])).toEqual(new Map());
+ });
+
it('createChunkedScrap stores one parent for short input and no children', async () => {
if (!requireDb('chunked scrap short')) return;
const parent = await catalogDB.createChunkedScrap({
diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.js
index d2ebd7bcfb..d773fde17c 100644
--- a/server/services/catalogDB/ingredients.js
+++ b/server/services/catalogDB/ingredients.js
@@ -311,7 +311,7 @@ const THUMBNAIL_KEY_SUBQUERY = `(
LIMIT 1
) AS thumbnail_key`;
-export async function listIngredients({ ids, type, tag, query: q, refKind = null, refId = null, unlinked = false, orphaned = false, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
+export async function listIngredients({ ids, type, tag, query: q, refKind = null, refId = null, unlinked = false, orphaned = false, scrapId = null, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
const conditions = ['deleted = false'];
const params = [];
let idx = 1;
@@ -368,6 +368,15 @@ export async function listIngredients({ ids, type, tag, query: q, refKind = null
conditions.push(`NOT ${HAS_LIVE_HOMING_REF}`);
}
}
+ // Source-scrap filter (#7617): "everything extracted from this piece" — a
+ // provenance dimension independent of the ids/type/tag/q/ref branches above,
+ // so it composes with any of them (unlike unlinked/orphaned/refKind, which
+ // are mutually exclusive album views enforced at the schema level).
+ if (scrapId) {
+ conditions.push(`EXISTS (SELECT 1 FROM catalog_ingredient_sources cis
+ WHERE cis.ingredient_id = catalog_ingredients.id AND cis.scrap_id = $${idx++})`);
+ params.push(scrapId);
+ }
if (embeddingMissing) {
conditions.push('embedding IS NULL');
}
diff --git a/server/services/catalogDB/refs.js b/server/services/catalogDB/refs.js
index 5c4cb7559c..1d041852b4 100644
--- a/server/services/catalogDB/refs.js
+++ b/server/services/catalogDB/refs.js
@@ -27,12 +27,19 @@ export async function linkIngredientToSource(ingredientId, scrapId, span = null,
);
}
+// Joins the scrap's `title` onto each source link (#7617) so the detail page
+// can render "extracted from <title>" instead of the bare `cat-scrap-<uuid>`.
+// `LEFT JOIN` (not `JOIN`) so a source row survives a hard-deleted scrap —
+// `scrapTitle` just comes back null, same posture as an orphaned ref.
export async function listSourcesForIngredient(ingredientId) {
const result = await query(
- `SELECT * FROM catalog_ingredient_sources WHERE ingredient_id = $1`,
+ `SELECT s.*, sc.title AS scrap_title
+ FROM catalog_ingredient_sources s
+ LEFT JOIN catalog_scraps sc ON sc.id = s.scrap_id
+ WHERE s.ingredient_id = $1`,
[ingredientId],
);
- return result.rows.map(rowToSource);
+ return result.rows.map((row) => ({ ...rowToSource(row), scrapTitle: row.scrap_title ?? null }));
}
export async function listSourcesForScrap(scrapId) {
@@ -43,6 +50,30 @@ export async function listSourcesForScrap(scrapId) {
return result.rows.map(rowToSource);
}
+// Sibling ingredients extracted from the same source scrap(s) as `ingredientId`
+// (#7617) — "what else came out of this piece?" in the ONE `/details` round-trip
+// the detail page already makes, rather than a second fetch per scrap. Batches
+// across every scrap the ingredient sources from in one query (mirrors the
+// `listRefsForIngredients` batching shape). Returns `Map<scrapId, Array<{ id,
+// name, type }>>`; excludes the caller's own row and soft-deleted siblings.
+export async function listSiblingIngredientsBySource(ingredientId, scrapIds) {
+ const ids = [...new Set(scrapIds)].filter(Boolean);
+ if (ids.length === 0) return new Map();
+ const result = await query(
+ `SELECT s.scrap_id, i.id, i.name, i.type
+ FROM catalog_ingredient_sources s
+ JOIN catalog_ingredients i ON i.id = s.ingredient_id
+ WHERE s.scrap_id = ANY($1) AND s.ingredient_id != $2 AND i.deleted = false
+ ORDER BY i.name ASC`,
+ [ids, ingredientId],
+ );
+ const grouped = new Map(ids.map((id) => [id, []]));
+ for (const row of result.rows) {
+ grouped.get(row.scrap_id)?.push({ id: row.id, name: row.name, type: row.type });
+ }
+ return grouped;
+}
+
export async function linkIngredientToRef(ingredientId, refKind, refId, role) {
// ON CONFLICT DO UPDATE revives a soft-deleted row instead of leaving it
// tombstoned. The trigger only bumps sync_sequence when `deleted` or