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: review and selectively commit grounded catalog draft relationships (#7902)

Adam Eivy5aa0094b6222
diff --git a/client/src/components/brain/tabs/InboxTab.test.jsx b/client/src/components/brain/tabs/InboxTab.test.jsx
index 1f3ebf81c2..347e8ce374 100644
--- a/client/src/components/brain/tabs/InboxTab.test.jsx
+++ b/client/src/components/brain/tabs/InboxTab.test.jsx
@@ -70,9 +70,9 @@ beforeEach(() => {
describe('Brain inbox capture', () => {
it('sends an optional note when a URL is filed to Links', async () => {
render(<MemoryRouter><InboxTab /></MemoryRouter>);
- await waitFor(() => expect(getBrainInbox).toHaveBeenCalled());
+ const input = await screen.findByLabelText('New inbox thought');
- fireEvent.change(screen.getByLabelText('New inbox thought'), {
+ fireEvent.change(input, {
target: { value: 'https://example.com' },
});
fireEvent.change(screen.getByLabelText(/Why are you saving this link/i), {
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 10c9e61795..e280fc2c5c 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -5,7 +5,7 @@
* name + description). Full-width page; owns its own scroll.
*/
-import { useState, useEffect, useRef } from 'react';
+import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
import { formatCount } from '../utils/formatters';
@@ -16,6 +16,7 @@ import FilePickerButton from '../components/ui/FilePickerButton';
import Modal from '../components/ui/Modal';
import socket from '../services/socket';
import { startMemoRecording } from '../lib/audioRecorder';
+import { getRelationKind } from '../lib/catalogTypes';
import {
createCatalogScrap,
pruneCatalogScrap,
@@ -65,14 +66,10 @@ const KIND_SECTIONS = [
];
// Initial stage list, used until the server's `start` frame supplies the real
-// one. Mirrors server-side EXTRACTION_STAGES — three bible passes plus one
-// bundled light pass (`ideasScenesConcepts`) — so the panel never looks empty
-// between click and first frame.
+// one. Mirrors server-side EXTRACTION_STAGES — one catalog graph stage — so the
+// panel never looks empty between click and first frame.
const INITIAL_STAGES = [
- { id: 'characters', label: 'Characters', status: 'pending', count: 0 },
- { id: 'places', label: 'Places', status: 'pending', count: 0 },
- { id: 'objects', label: 'Objects', status: 'pending', count: 0 },
- { id: 'ideasScenesConcepts', label: 'Ideas, scenes & concepts', status: 'pending', count: 0 },
+ { id: 'catalog', label: 'Catalog graph', status: 'pending', count: 0 },
];
function StageIcon({ status }) {
@@ -101,6 +98,11 @@ export default function CatalogIngest() {
const [committing, setCommitting] = useState(false);
const [scrapId, setScrapId] = useState(null);
const [stages, setStages] = useState(INITIAL_STAGES);
+ const [plan, setPlan] = useState(null);
+ const [relationships, setRelationships] = useState([]);
+ const [isStructuredDraft, setIsStructuredDraft] = useState(false);
+ const [optedOutRelationships, setOptedOutRelationships] = useState(new Set());
+ const [overflow, setOverflow] = useState(null);
// The draft returned by extractFromCatalogScrap(): per-kind candidate arrays
// editable inline + checkbox-gated. Defaults all to selected.
const [draft, setDraft] = useState({ characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] });
@@ -201,6 +203,7 @@ export default function CatalogIngest() {
? ev.stages.map((s) => ({ ...s, status: s.status || 'pending' }))
: INITIAL_STAGES;
setStages(next);
+ if (ev.plan) setPlan(ev.plan);
return;
}
if (ev.runId && ev.runId !== activeRunIdRef.current) return;
@@ -229,6 +232,11 @@ export default function CatalogIngest() {
setPhase('paste');
setScrapId(null);
setStages(INITIAL_STAGES);
+ setPlan(null);
+ setRelationships([]);
+ setIsStructuredDraft(false);
+ setOptedOutRelationships(new Set());
+ setOverflow(null);
setDraft({ characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] });
setSelected({ characters: new Set(), places: new Set(), objects: new Set(), ideas: new Set(), scenes: new Set(), concepts: new Set() });
};
@@ -254,16 +262,29 @@ export default function CatalogIngest() {
Array.isArray(result.draft[s.key]) ? result.draft[s.key] : [],
]));
setDraft(d);
- setSelected(Object.fromEntries(KIND_SECTIONS.map((s) => [s.key, new Set(d[s.key].map((_, i) => i))])));
+ setSelected(Object.fromEntries(KIND_SECTIONS.map((s) => [
+ s.key,
+ new Set(d[s.key].map((c, i) => c.draftId || `legacy-${s.key}-${i}`)),
+ ])));
+ const rawRels = Array.isArray(result.draft.relationships) ? result.draft.relationships : [];
+ const hasStructuredRels = result.draft.relationships !== undefined;
+ const hasDraftIds = KIND_SECTIONS.some((s) => d[s.key].some((c) => Boolean(c.draftId)));
+ setIsStructuredDraft(hasStructuredRels || hasDraftIds);
+ setRelationships(rawRels);
+ setOptedOutRelationships(new Set());
+ setPlan(result.draft.plan || null);
+ setOverflow(result.draft.overflow || null);
// Prefer server-supplied stage list; otherwise mark defaults completed.
// The bundled `ideasScenesConcepts` stage has no matching `d[id]` array,
// so its count is the sum of the three light kinds it backs.
if (Array.isArray(result.draft.stages) && result.draft.stages.length > 0) {
setStages(result.draft.stages.map((s) => ({ ...s, status: s.status || 'completed' })));
} else {
- const countForStage = (id) => id === 'ideasScenesConcepts'
- ? d.ideas.length + d.scenes.length + d.concepts.length
- : d[id]?.length || 0;
+ const countForStage = (id) => {
+ if (id === 'catalog') return KIND_SECTIONS.reduce((sum, s) => sum + (d[s.key]?.length || 0), 0);
+ if (id === 'ideasScenesConcepts') return (d.ideas?.length || 0) + (d.scenes?.length || 0) + (d.concepts?.length || 0);
+ return d[id]?.length || 0;
+ };
setStages((prev) => prev.map((s) => ({ ...s, status: 'completed', count: countForStage(s.id) })));
}
setPhase('review');
@@ -431,10 +452,29 @@ export default function CatalogIngest() {
navigate('/catalog');
};
- const toggle = (kind, idx) => {
+ const candidateMap = useMemo(() => {
+ const map = new Map();
+ for (const section of KIND_SECTIONS) {
+ const arr = draft[section.key] || [];
+ arr.forEach((c, idx) => {
+ const id = c.draftId || `legacy-${section.key}-${idx}`;
+ map.set(id, { ...c, draftId: id, sectionKey: section.key, sectionType: section.type });
+ });
+ }
+ return map;
+ }, [draft]);
+
+ const isEntrySelected = useCallback((draftId) => {
+ for (const section of KIND_SECTIONS) {
+ if (selected[section.key]?.has(draftId)) return true;
+ }
+ return false;
+ }, [selected]);
+
+ const toggle = (kind, id) => {
setSelected((prev) => {
const next = new Set(prev[kind]);
- if (next.has(idx)) next.delete(idx); else next.add(idx);
+ if (next.has(id)) next.delete(id); else next.add(id);
return { ...prev, [kind]: next };
});
};
@@ -442,36 +482,82 @@ export default function CatalogIngest() {
const selectAll = (kind, on) => {
setSelected((prev) => ({
...prev,
- [kind]: on ? new Set(draft[kind].map((_, i) => i)) : new Set(),
+ [kind]: on ? new Set(draft[kind].map((c, i) => c.draftId || `legacy-${kind}-${i}`)) : new Set(),
}));
};
- const patchCandidate = (kind, idx, patch) => {
+ const patchCandidate = (kind, id, patch) => {
setDraft((prev) => ({
...prev,
- [kind]: prev[kind].map((c, i) => (i === idx ? { ...c, ...patch } : c)),
+ [kind]: prev[kind].map((c, i) => ((c.draftId || `legacy-${kind}-${i}`) === id ? { ...c, ...patch } : c)),
}));
};
+ const toggleRelationship = (relId) => {
+ setOptedOutRelationships((prev) => {
+ const next = new Set(prev);
+ if (next.has(relId)) next.delete(relId); else next.add(relId);
+ return next;
+ });
+ };
+
+ const selectAllRelationships = (on) => {
+ if (on) {
+ setOptedOutRelationships(new Set());
+ } else {
+ const allIds = relationships.map((r) => r.id || `${r.fromDraftId}:${r.toDraftId}:${r.kind}`);
+ setOptedOutRelationships(new Set(allIds));
+ }
+ };
+
+ const handleRetry = async () => {
+ if (!scrapId) return;
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ const result = await extractFromCatalogScrap(scrapId, brainRouteRef.current || {}, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result, 'paste');
+ };
+
const handleCommit = async () => {
if (!scrapId) return;
- // extractBible returns flat bible-shaped objects (role, personality,
- // background, motivations, slugline, era, significance, …); commit must
- // carry the whole shape minus the few keys catalog stores at the top
- // (name, tags, id — and `type` from the section, not the candidate).
+
+ const totalSelected = KIND_SECTIONS.reduce((sum, s) => sum + (selected[s.key]?.size || 0), 0);
+ const activeRelCount = isStructuredDraft
+ ? relationships.filter((r) => {
+ const relId = r.id || `${r.fromDraftId}:${r.toDraftId}:${r.kind}`;
+ return !optedOutRelationships.has(relId) && isEntrySelected(r.fromDraftId) && isEntrySelected(r.toDraftId);
+ }).length
+ : 0;
+
+ if (totalSelected > 200 || activeRelCount > 1000) {
+ toast.error('Draft exceeds capacity limits (maximum 200 entries and 1,000 relationships). Deselect items to continue.');
+ return;
+ }
+
const accepted = [];
for (const section of KIND_SECTIONS) {
const arr = draft[section.key];
const sel = selected[section.key];
for (let i = 0; i < arr.length; i += 1) {
- if (!sel.has(i)) continue;
const c = arr[i];
+ const itemId = c.draftId || `legacy-${section.key}-${i}`;
+ if (!sel.has(itemId)) continue;
const name = (c.name || '').trim();
if (!name) continue;
- const { draftId: _draftId, sourceIdentity: _sourceIdentity, id: _id, type: _type, name: _name, tags: _tags, payload: nestedPayload, description, ...rest } = c;
+ const { draftId, sourceIdentity: _sourceIdentity, id: _id, type: _type, name: _name, tags: _tags, payload: nestedPayload, description, span, ...rest } = c;
const payload = { ...rest, ...(nestedPayload && typeof nestedPayload === 'object' ? nestedPayload : {}) };
if (description !== undefined) payload.description = description;
- accepted.push({ type: section.type, name, payload, tags: Array.isArray(c.tags) ? c.tags : [] });
+ accepted.push({
+ type: section.type,
+ name,
+ payload,
+ tags: Array.isArray(c.tags) ? c.tags : [],
+ ...(draftId ? { draftId } : {}),
+ ...(span ? { span } : {}),
+ });
}
}
if (accepted.length === 0) {
@@ -479,8 +565,26 @@ export default function CatalogIngest() {
return;
}
setCommitting(true);
+
+ let relsToCommit = undefined;
+ if (isStructuredDraft) {
+ const acceptedIds = new Set(accepted.map((a) => a.draftId).filter(Boolean));
+ relsToCommit = relationships
+ .filter((r) => {
+ const relId = r.id || `${r.fromDraftId}:${r.toDraftId}:${r.kind}`;
+ return !optedOutRelationships.has(relId) && acceptedIds.has(r.fromDraftId) && acceptedIds.has(r.toDraftId);
+ })
+ .map(({ fromDraftId, toDraftId, kind, evidence }) => ({
+ fromDraftId,
+ toDraftId,
+ kind,
+ evidence,
+ }));
+ }
+
const result = await commitCatalogScrapDraft(scrapId, accepted, {
universeRef: universeRef === UNASSIGNED_UNIVERSE ? undefined : universeRef,
+ relationships: relsToCommit,
silent: true,
}).catch((err) => {
toast.error(err?.message || 'Commit failed');
@@ -702,7 +806,11 @@ export default function CatalogIngest() {
<div className="bg-port-card border border-port-border rounded-lg p-6 space-y-3">
<p className="text-sm font-medium text-white flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin text-port-accent" aria-hidden="true" />
- {babble ? 'Pruning your brainstorm — one AI pass.' : 'Extracting ingredients — one pass per source chunk.'}
+ {babble
+ ? 'Pruning your brainstorm — one AI pass.'
+ : stages.length === 1 || plan?.mode === 'whole'
+ ? 'Extracting ingredients — one AI pass.'
+ : `Extracting ingredients — one pass per source chunk (${stages.length} chunk${stages.length === 1 ? '' : 's'}).`}
</p>
<ul className="space-y-1.5 mt-2">
{stages.map((s) => (
@@ -721,60 +829,103 @@ export default function CatalogIngest() {
</div>
)}
- {phase === 'review' && (
- <div className="space-y-5">
- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
- <p className="text-sm text-gray-300">
- Review the candidates below. Uncheck anything you don&apos;t want, edit names and descriptions inline, then commit the rest.
- </p>
- <div className="max-w-xs">
- <label htmlFor="ingest-universe-ref" className="block text-sm font-medium mb-1 text-white">Catalogue into</label>
- <select id="ingest-universe-ref" value={universeRef}
- onChange={(e) => {
- const next = e.target.value;
- setUniverseRef(next);
- safeWriteStorage(LAST_UNIVERSE_STORAGE_KEY, next);
- }}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent">
- <option value={UNASSIGNED_UNIVERSE}>Unassigned</option>
- {universes.map((u) => (
- <option key={u.id} value={u.id}>{u.name}</option>
- ))}
- </select>
+ {phase === 'review' && (() => {
+ const totalDraftEntries = KIND_SECTIONS.reduce((sum, s) => sum + (draft[s.key]?.length || 0), 0);
+ const selectedEntriesCount = KIND_SECTIONS.reduce((sum, s) => sum + (selected[s.key]?.size || 0), 0);
+ const activeRelationshipsCount = isStructuredDraft
+ ? relationships.filter((r) => {
+ const relId = r.id || `${r.fromDraftId}:${r.toDraftId}:${r.kind}`;
+ return !optedOutRelationships.has(relId) && isEntrySelected(r.fromDraftId) && isEntrySelected(r.toDraftId);
+ }).length
+ : 0;
+ const isOverLimit = selectedEntriesCount > 200 || activeRelationshipsCount > 1000;
+ const hasExtractedOverflow = totalDraftEntries > 200 || relationships.length > 1000 || Boolean(overflow);
+
+ return (
+ <div className="space-y-5">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <p className="text-sm text-gray-300">
+ Review the candidates below. Uncheck anything you don&apos;t want, edit names and descriptions inline, then commit the rest.
+ </p>
+ <div className="max-w-xs">
+ <label htmlFor="ingest-universe-ref" className="block text-sm font-medium mb-1 text-white">Catalogue into</label>
+ <select id="ingest-universe-ref" value={universeRef}
+ onChange={(e) => {
+ const next = e.target.value;
+ setUniverseRef(next);
+ safeWriteStorage(LAST_UNIVERSE_STORAGE_KEY, next);
+ }}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent">
+ <option value={UNASSIGNED_UNIVERSE}>Unassigned</option>
+ {universes.map((u) => (
+ <option key={u.id} value={u.id}>{u.name}</option>
+ ))}
+ </select>
+ </div>
</div>
- </div>
- {stages.some(stage => stage.status === 'failed') && (
- <div role="alert" className="bg-port-card border border-port-error rounded-lg p-4 text-sm space-y-2">
- <p>Extraction is incomplete. These candidates cover only the successful parts of your source. Retry ingestion to cover the failed parts.</p>
- {stages.filter(stage => stage.status === 'failed').map(stage => (
- <p key={stage.id}>{stage.label}: {stage.error || 'Extraction failed'}</p>
- ))}
+ {(isOverLimit || hasExtractedOverflow) && (
+ <div role="alert" className="bg-port-card border border-port-error rounded-lg p-4 text-sm space-y-1 text-port-error">
+ <p className="font-semibold">Draft exceeds capacity limits</p>
+ <p>
+ {isOverLimit
+ ? `Too many items selected (${selectedEntriesCount > 200 ? `${selectedEntriesCount} entries (max 200); ` : ''}${activeRelationshipsCount > 1000 ? `${activeRelationshipsCount} relationships (max 1,000); ` : ''}). Deselect items before committing.`
+ : `Extraction exceeded limits (${totalDraftEntries > 200 ? `${totalDraftEntries} entries (max 200); ` : ''}${relationships.length > 1000 ? `${relationships.length} relationships (max 1,000); ` : ''}). Deselect items before committing.`}
+ </p>
+ </div>
+ )}
+ {stages.some((stage) => stage.status === 'failed') && (
+ <div role="alert" className="bg-port-card border border-port-error rounded-lg p-4 text-sm space-y-2">
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <p className="text-white font-medium">Extraction is incomplete. These candidates cover only the successful parts of your source. Retry ingestion to cover the failed parts.</p>
+ <button
+ type="button"
+ onClick={handleRetry}
+ disabled={submitting}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium"
+ >
+ <RotateCcw size={12} aria-hidden="true" /> Retry extraction
+ </button>
+ </div>
+ {stages.filter((stage) => stage.status === 'failed').map((stage) => (
+ <p key={stage.id} className="text-port-error">{stage.label}: {stage.error || 'Extraction failed'}</p>
+ ))}
+ </div>
+ )}
+ {KIND_SECTIONS.map((section) => (
+ <ReviewSection
+ key={section.key}
+ section={section}
+ items={draft[section.key]}
+ selected={selected[section.key]}
+ onToggle={(id) => toggle(section.key, id)}
+ onSelectAll={(on) => selectAll(section.key, on)}
+ onPatch={(id, patch) => patchCandidate(section.key, id, patch)}
+ />
+ ))}
+ {isStructuredDraft && relationships.length > 0 && (
+ <RelationshipsReviewSection
+ relationships={relationships}
+ optedOutRelationships={optedOutRelationships}
+ candidateMap={candidateMap}
+ isEntrySelected={isEntrySelected}
+ onToggleRelationship={toggleRelationship}
+ onSelectAll={selectAllRelationships}
+ />
+ )}
+ <div className="sticky bottom-4 bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-end gap-2 shadow-lg">
+ <button type="button" onClick={reset} disabled={committing}
+ className="px-3 py-2 rounded-lg text-gray-400 hover:text-white text-sm">
+ Cancel
+ </button>
+ <button type="button" onClick={handleCommit} disabled={committing || isOverLimit}
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-success hover:bg-port-success/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
+ {committing ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle2 className="w-4 h-4" />}
+ {committing ? 'Committing…' : 'Commit Selected'}
+ </button>
</div>
- )}
- {KIND_SECTIONS.map((section) => (
- <ReviewSection
- key={section.key}
- section={section}
- items={draft[section.key]}
- selected={selected[section.key]}
- onToggle={(idx) => toggle(section.key, idx)}
- onSelectAll={(on) => selectAll(section.key, on)}
- onPatch={(idx, patch) => patchCandidate(section.key, idx, patch)}
- />
- ))}
- <div className="sticky bottom-4 bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-end gap-2 shadow-lg">
- <button type="button" onClick={reset} disabled={committing}
- className="px-3 py-2 rounded-lg text-gray-400 hover:text-white text-sm">
- Cancel
- </button>
- <button type="button" onClick={handleCommit} disabled={committing}
- className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-success hover:bg-port-success/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
- {committing ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle2 className="w-4 h-4" />}
- {committing ? 'Committing…' : 'Commit Selected'}
- </button>
</div>
- </div>
- )}
+ );
+ })()}
</div>
</section>
);
@@ -782,7 +933,7 @@ export default function CatalogIngest() {
function ReviewSection({ section, items, selected, onToggle, onSelectAll, onPatch }) {
const total = items.length;
- const count = selected.size;
+ const count = items.filter((c, idx) => selected.has(c.draftId || `legacy-${section.key}-${idx}`)).length;
if (total === 0) {
return (
<section className="bg-port-card border border-port-border rounded-lg p-4">
@@ -808,6 +959,7 @@ function ReviewSection({ section, items, selected, onToggle, onSelectAll, onPatc
</div>
<ul className="space-y-2">
{items.map((c, idx) => {
+ const itemId = c.draftId || `legacy-${section.key}-${idx}`;
const baseId = `${section.key}-${idx}`;
// Each type's primary editable field matches PRIMARY_CONTENT_KEY in
// Catalog.jsx: character → physicalDescription (canon shape from
@@ -819,17 +971,17 @@ function ReviewSection({ section, items, selected, onToggle, onSelectAll, onPatc
else if (section.type === 'place' || section.type === 'object') descField = 'description';
else descField = 'summary';
return (
- <li key={baseId} className="border border-port-border rounded p-3 bg-port-bg/40 flex items-start gap-2">
- <input id={`${baseId}-check`} type="checkbox" checked={selected.has(idx)} onChange={() => onToggle(idx)}
+ <li key={itemId} className="border border-port-border rounded p-3 bg-port-bg/40 flex items-start gap-2">
+ <input id={`${baseId}-check`} type="checkbox" checked={selected.has(itemId)} onChange={() => onToggle(itemId)}
className="accent-port-accent mt-1" aria-label={`Include ${c.name || section.label}`} />
<div className="flex-1 min-w-0 space-y-2">
<label htmlFor={`${baseId}-name`} className="sr-only">Name</label>
- <input id={`${baseId}-name`} type="text" value={c.name || ''} onChange={(e) => onPatch(idx, { name: e.target.value })}
+ <input id={`${baseId}-name`} type="text" value={c.name || ''} onChange={(e) => onPatch(itemId, { name: e.target.value })}
placeholder="Name" maxLength={200}
className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white focus:outline-none focus:border-port-accent" />
<label htmlFor={`${baseId}-desc`} className="sr-only">Description</label>
<textarea id={`${baseId}-desc`} rows={2} value={c[descField] ?? ''}
- onChange={(e) => onPatch(idx, { [descField]: e.target.value })} placeholder="Short description"
+ onChange={(e) => onPatch(itemId, { [descField]: e.target.value })} placeholder="Short description"
className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-200 focus:outline-none focus:border-port-accent" />
</div>
</li>
@@ -839,3 +991,115 @@ function ReviewSection({ section, items, selected, onToggle, onSelectAll, onPatc
</section>
);
}
+
+function RelationshipsReviewSection({
+ relationships,
+ optedOutRelationships,
+ candidateMap,
+ isEntrySelected,
+ onToggleRelationship,
+ onSelectAll,
+}) {
+ const total = relationships.length;
+ if (total === 0) return null;
+
+ const activeRelationships = relationships.filter((r) => {
+ const relId = r.id || `${r.fromDraftId}:${r.toDraftId}:${r.kind}`;
+ const fromSelected = isEntrySelected(r.fromDraftId);
+ const toSelected = isEntrySelected(r.toDraftId);
+ return fromSelected && toSelected && !optedOutRelationships.has(relId);
+ });
+ const activeCount = activeRelationships.length;
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <h2 className="text-lg font-semibold text-white">
+ Relationships <span className="text-sm font-normal text-gray-500">({activeCount} / {total} active)</span>
+ </h2>
+ <div className="flex items-center gap-1 text-xs">
+ <button
+ type="button"
+ onClick={() => onSelectAll(true)}
+ className="px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white"
+ >
+ Select All
+ </button>
+ <button
+ type="button"
+ onClick={() => onSelectAll(false)}
+ className="px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white"
+ >
+ Deselect All
+ </button>
+ </div>
+ </div>
+ <ul className="space-y-2">
+ {relationships.map((rel, idx) => {
+ const relId = rel.id || `${rel.fromDraftId}:${rel.toDraftId}:${rel.kind}`;
+ const fromItem = candidateMap.get(rel.fromDraftId);
+ const toItem = candidateMap.get(rel.toDraftId);
+ const fromName = (fromItem?.name || '').trim() || rel.fromDraftId;
+ const toName = (toItem?.name || '').trim() || rel.toDraftId;
+ const fromSelected = isEntrySelected(rel.fromDraftId);
+ const toSelected = isEntrySelected(rel.toDraftId);
+ const endpointsActive = fromSelected && toSelected;
+ const isOptedIn = !optedOutRelationships.has(relId);
+ const isChecked = endpointsActive && isOptedIn;
+ const kindObj = getRelationKind(rel.kind);
+ const kindLabel = kindObj?.label || rel.kind;
+ const inverseLabel = kindObj?.inverseLabel;
+
+ return (
+ <li
+ key={relId}
+ className={`border border-port-border rounded p-3 flex items-start gap-2 ${
+ endpointsActive ? 'bg-port-bg/40' : 'bg-port-bg/20 opacity-75'
+ }`}
+ >
+ <input
+ id={`rel-check-${idx}`}
+ type="checkbox"
+ checked={isChecked}
+ disabled={!endpointsActive}
+ onChange={() => endpointsActive && onToggleRelationship(relId)}
+ className="accent-port-accent mt-1 disabled:opacity-40 disabled:cursor-not-allowed"
+ aria-label={`Include relationship ${fromName} ${kindLabel} ${toName}`}
+ />
+ <div className="flex-1 min-w-0 space-y-1">
+ <div className="flex items-center gap-2 flex-wrap text-sm">
+ <span className="font-medium text-white">{fromName}</span>
+ <span className="text-port-accent text-xs">→</span>
+ <span className="text-xs px-2 py-0.5 rounded bg-port-bg border border-port-border text-port-accent font-medium">
+ {kindLabel}
+ </span>
+ <span className="text-port-accent text-xs">→</span>
+ <span className="font-medium text-white">{toName}</span>
+ {inverseLabel && (
+ <span className="text-[11px] text-gray-500">
+ (inverse: {inverseLabel})
+ </span>
+ )}
+ </div>
+ {rel.evidence && (
+ <blockquote className="text-xs text-gray-400 italic pl-2 border-l-2 border-port-border/80">
+ “{rel.evidence}”
+ </blockquote>
+ )}
+ {!endpointsActive && (
+ <div role="status" className="text-xs text-port-warning font-medium">
+ {!fromSelected && !toSelected
+ ? `Disabled — both ${fromName} and ${toName} are deselected`
+ : !fromSelected
+ ? `Disabled — ${fromName} is deselected`
+ : `Disabled — ${toName} is deselected`}
+ </div>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
diff --git a/client/src/pages/CatalogIngest.test.jsx b/client/src/pages/CatalogIngest.test.jsx
index b545f965c8..8d9025e5d2 100644
--- a/client/src/pages/CatalogIngest.test.jsx
+++ b/client/src/pages/CatalogIngest.test.jsx
@@ -113,3 +113,245 @@ it('keeps partial extraction failures visible in review and excludes draft metad
await waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith('partial-scrap',
[expect.objectContaining({ payload: { summary: 'A supported fragment.' } })], expect.anything()));
});
+
+it('preserves rename and reorder stability and updates relationship endpoint labels', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-stable' } });
+ extractFromCatalogScrap.mockResolvedValue({
+ scrap: { id: 'scrap-stable' },
+ draft: {
+ characters: [{ draftId: 'chr-1', name: 'Ada Lovelace', payload: { role: 'Mentor' } }],
+ objects: [{ draftId: 'obj-1', name: 'Pocket Watch', payload: { description: 'Golden watch' } }],
+ relationships: [
+ { fromDraftId: 'chr-1', toDraftId: 'obj-1', kind: 'owned-by', evidence: 'Ada carries the golden watch.' },
+ ],
+ },
+ });
+ commitCatalogScrapDraft.mockResolvedValue({ ingredients: [] });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'Ada and her watch' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Ada Lovelace');
+ expect(screen.getByDisplayValue('Pocket Watch')).toBeTruthy();
+
+ // Check relationship card shows initial names, kind badge, and evidence
+ expect(screen.getByText('Owned by')).toBeTruthy();
+ expect(screen.getByText('(inverse: Owns)')).toBeTruthy();
+ expect(screen.getByText('“Ada carries the golden watch.”')).toBeTruthy();
+
+ // Rename Ada Lovelace inline
+ fireEvent.change(screen.getByDisplayValue('Ada Lovelace'), { target: { value: 'Countess Ada' } });
+
+ // Relationship review card updates endpoint name to "Countess Ada"
+ expect(screen.getByText('Countess Ada')).toBeTruthy();
+
+ // Both items are still checked by stable draftId
+ expect(screen.getByRole('checkbox', { name: 'Include Countess Ada' })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'Include Pocket Watch' })).toBeChecked();
+
+ // Commit
+ fireEvent.click(screen.getByRole('button', { name: /Commit/ }));
+ await waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith(
+ 'scrap-stable',
+ [
+ expect.objectContaining({ draftId: 'chr-1', name: 'Countess Ada', type: 'character' }),
+ expect.objectContaining({ draftId: 'obj-1', name: 'Pocket Watch', type: 'object' }),
+ ],
+ expect.objectContaining({
+ relationships: [
+ expect.objectContaining({
+ fromDraftId: 'chr-1',
+ toDraftId: 'obj-1',
+ kind: 'owned-by',
+ evidence: 'Ada carries the golden watch.',
+ }),
+ ],
+ }),
+ ));
+});
+
+it('supports relationship link opt-out with explicit empty commit array', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-opt-out' } });
+ extractFromCatalogScrap.mockResolvedValue({
+ scrap: { id: 'scrap-opt-out' },
+ draft: {
+ characters: [{ draftId: 'chr-1', name: 'Ada Lovelace' }],
+ objects: [{ draftId: 'obj-1', name: 'Pocket Watch' }],
+ relationships: [
+ { fromDraftId: 'chr-1', toDraftId: 'obj-1', kind: 'owned-by', evidence: 'Ada carries the watch' },
+ ],
+ },
+ });
+ commitCatalogScrapDraft.mockResolvedValue({ ingredients: [] });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'Ada with watch' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Ada Lovelace');
+
+ // Opt-out of the relationship by unchecking it
+ const relCheckbox = screen.getByRole('checkbox', { name: 'Include relationship Ada Lovelace Owned by Pocket Watch' });
+ expect(relCheckbox).toBeChecked();
+ fireEvent.click(relCheckbox);
+ expect(relCheckbox).not.toBeChecked();
+
+ // Commit
+ fireEvent.click(screen.getByRole('button', { name: /Commit/ }));
+ await waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith(
+ 'scrap-opt-out',
+ expect.any(Array),
+ expect.objectContaining({
+ relationships: [], // Explicitly empty array!
+ }),
+ ));
+});
+
+it('disables relationship and provides feedback when an endpoint is deselected without auto-selecting', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-endpoint-desel' } });
+ extractFromCatalogScrap.mockResolvedValue({
+ scrap: { id: 'scrap-endpoint-desel' },
+ draft: {
+ characters: [{ draftId: 'chr-1', name: 'Ada Lovelace' }],
+ objects: [{ draftId: 'obj-1', name: 'Pocket Watch' }],
+ relationships: [
+ { fromDraftId: 'chr-1', toDraftId: 'obj-1', kind: 'owned-by', evidence: 'Ada carries the watch' },
+ ],
+ },
+ });
+ commitCatalogScrapDraft.mockResolvedValue({ ingredients: [] });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'Ada with watch' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Ada Lovelace');
+
+ // Deselect Pocket Watch
+ const watchCheckbox = screen.getByRole('checkbox', { name: 'Include Pocket Watch' });
+ fireEvent.click(watchCheckbox);
+ expect(watchCheckbox).not.toBeChecked();
+
+ // Relationship checkbox is now disabled
+ const relCheckbox = screen.getByRole('checkbox', { name: 'Include relationship Ada Lovelace Owned by Pocket Watch' });
+ expect(relCheckbox).toBeDisabled();
+
+ // Visible feedback in role="status"
+ expect(screen.getByRole('status')).toHaveTextContent('Disabled — Pocket Watch is deselected');
+
+ // Interacting with disabled relationship does not re-select Pocket Watch
+ fireEvent.click(relCheckbox);
+ expect(watchCheckbox).not.toBeChecked();
+
+ // Commit sends only Ada and empty relationships list
+ fireEvent.click(screen.getByRole('button', { name: /Commit/ }));
+ await waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith(
+ 'scrap-endpoint-desel',
+ [expect.objectContaining({ draftId: 'chr-1', name: 'Ada Lovelace' })],
+ expect.objectContaining({ relationships: [] }),
+ ));
+});
+
+it('renders alert and disables commit when draft entries exceed 200 or relationships exceed 1,000', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-overflow' } });
+ const ideas = Array.from({ length: 201 }, (_, i) => ({
+ draftId: `idea-${i}`,
+ name: `Idea ${i}`,
+ summary: `Summary ${i}`,
+ }));
+ extractFromCatalogScrap.mockResolvedValue({
+ scrap: { id: 'scrap-overflow' },
+ draft: { ideas, relationships: [] },
+ });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'many ideas' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Idea 0');
+
+ // Alert is visible
+ const alert = screen.getByRole('alert');
+ expect(alert).toHaveTextContent('Draft exceeds capacity limits');
+ expect(alert).toHaveTextContent('201 entries (max 200)');
+
+ // Commit button is disabled
+ const commitBtn = screen.getByRole('button', { name: /Commit/ });
+ expect(commitBtn).toBeDisabled();
+});
+
+it('renders alert and disables commit when relationships exceed 1,000', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-rel-overflow' } });
+ const rels = Array.from({ length: 1001 }, (_, i) => ({
+ id: `rel-${i}`,
+ fromDraftId: 'chr-1',
+ toDraftId: 'obj-1',
+ kind: 'related-to',
+ }));
+ extractFromCatalogScrap.mockResolvedValue({
+ scrap: { id: 'scrap-rel-overflow' },
+ draft: {
+ characters: [{ draftId: 'chr-1', name: 'Ada' }],
+ objects: [{ draftId: 'obj-1', name: 'Watch' }],
+ relationships: rels,
+ },
+ });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'many relations' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Ada');
+
+ const alert = screen.getByRole('alert');
+ expect(alert).toHaveTextContent('Draft exceeds capacity limits');
+ expect(alert).toHaveTextContent('1001 relationships (max 1,000)');
+
+ const commitBtn = screen.getByRole('button', { name: /Commit/ });
+ expect(commitBtn).toBeDisabled();
+});
+
+it('renders retry button on partial failures which re-extracts without silent auto-saving', async () => {
+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'scrap-retry' } });
+ extractFromCatalogScrap
+ .mockResolvedValueOnce({
+ scrap: { id: 'scrap-retry' },
+ draft: {
+ ideas: [{ draftId: 'idea-1', name: 'Incomplete Idea', summary: 'Some text' }],
+ stages: [
+ { id: 'chunk-1', label: 'Chunk 1', status: 'completed' },
+ { id: 'chunk-2', label: 'Chunk 2', status: 'failed', error: 'Provider quota limit' },
+ ],
+ },
+ })
+ .mockResolvedValueOnce({
+ scrap: { id: 'scrap-retry' },
+ draft: {
+ ideas: [
+ { draftId: 'idea-1', name: 'Incomplete Idea', summary: 'Some text' },
+ { draftId: 'idea-2', name: 'Complete Idea', summary: 'All good' },
+ ],
+ stages: [
+ { id: 'chunk-1', label: 'Chunk 1', status: 'completed' },
+ { id: 'chunk-2', label: 'Chunk 2', status: 'completed' },
+ ],
+ },
+ });
+
+ render(<MemoryRouter initialEntries={['/catalog/ingest']}><CatalogIngest /></MemoryRouter>);
+ fireEvent.change(screen.getByLabelText(/Raw text/), { target: { value: 'chunk retry test' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));
+
+ await screen.findByDisplayValue('Incomplete Idea');
+ expect(commitCatalogScrapDraft).not.toHaveBeenCalled();
+
+ // Retry extraction button in the partial failure alert
+ const retryBtn = screen.getByRole('button', { name: 'Retry extraction' });
+ fireEvent.click(retryBtn);
+
+ await screen.findByDisplayValue('Complete Idea');
+ expect(extractFromCatalogScrap).toHaveBeenCalledTimes(2);
+ expect(commitCatalogScrapDraft).not.toHaveBeenCalled();
+});
+
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 3b1f082f77..4725150c54 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -572,13 +572,14 @@ export default function CatalogIngredient() {
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <SourcesPanel sources={record.sources} />
+ <SourcesPanel sources={record.sources} evidence={payload?.evidence} />
<RefsPanel refsByKind={refsByKind} />
</div>
<RelationsPanel
record={record}
relations={relations}
+ evidence={payload?.evidence}
onAdd={handleAddRelation}
onRemove={handleRemoveRelation}
/>
@@ -880,13 +881,18 @@ function ReferenceSheetPanel({ payload, universeRef }) {
// "Relations" panel — ingredient↔ingredient edges. Outbound edges (this
// ingredient → other) are user-editable here; inbound edges (other → this
// ingredient) are read-only because the owning ingredient is the other end.
-function RelationsPanel({ record, relations, onAdd, onRemove }) {
+function RelationsPanel({ record, relations, evidence, onAdd, onRemove }) {
const [pickerOpen, setPickerOpen] = useState(false);
const [kind, setKind] = useState(RELATION_KINDS[0].id);
const [armedRelation, setArmedRelation] = useState(null);
const [removingRelation, setRemovingRelation] = useState(null);
const outbound = Array.isArray(relations.outbound) ? relations.outbound : [];
const inbound = Array.isArray(relations.inbound) ? relations.inbound : [];
+ const evidenceList = Array.isArray(evidence)
+ ? evidence.filter(Boolean)
+ : typeof evidence === 'string' && evidence.trim()
+ ? evidence.split('\n').map((s) => s.trim()).filter(Boolean)
+ : [];
// Hide the current record + everything already linked outbound from the
// picker so the user can't double-link or self-link.
@@ -927,35 +933,49 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
{outbound.length > 0 && (
<div>
<div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Outbound</div>
- <ul className="space-y-1.5">
+ <ul className="space-y-2">
{outbound.map((r) => {
const relationKey = `${r.toId}-${r.kind}`;
const relationName = r.other?.name || r.toId;
+ const matchedEvidence = evidenceList.find((e) =>
+ e.startsWith(`${r.kind} → ${relationName}:`) ||
+ (relationName && e.toLowerCase().includes(relationName.toLowerCase()))
+ );
+ const evidenceSnippet = matchedEvidence
+ ? (matchedEvidence.includes(': ') ? matchedEvidence.split(': ').slice(1).join(': ') : matchedEvidence)
+ : null;
return (
- <li key={relationKey} className="flex items-center gap-2 flex-wrap">
- <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.label || r.kind}</span>
- {chip(r.other)}
- {armedRelation === relationKey ? (
- <ConfirmButtonPair
- prompt="Remove?"
- confirmText="Remove"
- busyText="Removing"
- busy={removingRelation === relationKey}
- ariaLabel={`Confirm removal of relation to ${relationName}`}
- onCancel={() => setArmedRelation(null)}
- onConfirm={async () => {
- setRemovingRelation(relationKey);
- await onRemove(r.toId, r.kind);
- setRemovingRelation(null);
- setArmedRelation(null);
- }}
- />
- ) : (
- <button type="button" onClick={() => setArmedRelation(relationKey)}
- aria-label={`Remove relation to ${relationName}`}
- className="text-gray-500 hover:text-port-error">
- <X size={12} aria-hidden="true" />
- </button>
+ <li key={relationKey} className="space-y-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.label || r.kind}</span>
+ {chip(r.other)}
+ {armedRelation === relationKey ? (
+ <ConfirmButtonPair
+ prompt="Remove?"
+ confirmText="Remove"
+ busyText="Removing"
+ busy={removingRelation === relationKey}
+ ariaLabel={`Confirm removal of relation to ${relationName}`}
+ onCancel={() => setArmedRelation(null)}
+ onConfirm={async () => {
+ setRemovingRelation(relationKey);
+ await onRemove(r.toId, r.kind);
+ setRemovingRelation(null);
+ setArmedRelation(null);
+ }}
+ />
+ ) : (
+ <button type="button" onClick={() => setArmedRelation(relationKey)}
+ aria-label={`Remove relation to ${relationName}`}
+ className="text-gray-500 hover:text-port-error">
+ <X size={12} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ {evidenceSnippet && (
+ <p className="text-[11px] text-gray-400 italic pl-3 border-l border-port-border">
+ “{evidenceSnippet}”
+ </p>
)}
</li>
);
@@ -966,13 +986,32 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
{inbound.length > 0 && (
<div>
<div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Inbound</div>
- <ul className="space-y-1.5">
- {inbound.map((r) => (
- <li key={`${r.fromId}-${r.kind}`} className="flex items-center gap-2 flex-wrap">
- <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.inverseLabel || r.kind}</span>
- {chip(r.other)}
- </li>
- ))}
+ <ul className="space-y-2">
+ {inbound.map((r) => {
+ const inboundKey = `${r.fromId}-${r.kind}`;
+ const inboundName = r.other?.name || r.fromId;
+ const inboundMatched = evidenceList.find((e) =>
+ e.startsWith(`${r.kind} → `) &&
+ ((record.name && e.toLowerCase().includes(record.name.toLowerCase())) ||
+ (inboundName && e.toLowerCase().includes(inboundName.toLowerCase())))
+ );
+ const inboundSnippet = inboundMatched
+ ? (inboundMatched.includes(': ') ? inboundMatched.split(': ').slice(1).join(': ') : inboundMatched)
+ : null;
+ return (
+ <li key={inboundKey} className="space-y-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-gray-400">{getRelationKind(r.kind)?.inverseLabel || r.kind}</span>
+ {chip(r.other)}
+ </div>
+ {inboundSnippet && (
+ <p className="text-[11px] text-gray-400 italic pl-3 border-l border-port-border">
+ “{inboundSnippet}”
+ </p>
+ )}
+ </li>
+ );
+ })}
</ul>
</div>
)}
@@ -1435,8 +1474,13 @@ function GalleryPickerModal({ onClose, onPick }) {
// 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 }) {
+function SourcesPanel({ sources, evidence }) {
const list = Array.isArray(sources) ? sources : [];
+ const evidenceList = Array.isArray(evidence)
+ ? evidence.filter(Boolean)
+ : typeof evidence === 'string' && evidence.trim()
+ ? evidence.split('\n').map((s) => s.trim()).filter(Boolean)
+ : [];
return (
<section className="bg-port-card border border-port-border rounded-lg p-4">
<h2 className="text-sm font-semibold text-white mb-2">Source scraps</h2>
@@ -1483,6 +1527,18 @@ function SourcesPanel({ sources }) {
})}
</ul>
)}
+ {evidenceList.length > 0 && (
+ <div className="mt-4 pt-3 border-t border-port-border">
+ <h3 className="text-xs font-semibold text-gray-300 mb-2">Grounded evidence</h3>
+ <ul className="space-y-1.5 text-xs text-gray-400">
+ {evidenceList.map((item, idx) => (
+ <li key={idx} className="italic pl-2 border-l border-port-border">
+ “{item}”
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
</section>
);
}
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index 397d6dc83b..cb3f76784b 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -522,6 +522,54 @@ describe('CatalogIngredient — character sheet', () => {
expect(promptBox.value).not.toMatch(/neon noir/);
getUniverse.mockResolvedValue(null); // restore default
});
+
+ it('renders synthetic relations with directed/inverse labels and evidence snippets', async () => {
+ const fixtureWithRelations = {
+ ...CHAR_FIXTURE,
+ payload: {
+ ...CHAR_FIXTURE.payload,
+ evidence: [
+ 'owned-by → Pocket Watch: Ada carries this golden pocket watch everywhere',
+ 'used-by → Analytical Engine: Ada programmed the engine with punch cards',
+ ],
+ },
+ };
+ getCatalogIngredientDetails.mockImplementation(async () => ({
+ ...detailsOf(fixtureWithRelations),
+ relations: {
+ outbound: [
+ {
+ toId: 'cat-obj-1',
+ kind: 'owned-by',
+ other: { id: 'cat-obj-1', name: 'Pocket Watch', type: 'object' },
+ },
+ ],
+ inbound: [
+ {
+ fromId: 'cat-obj-2',
+ kind: 'used-by',
+ other: { id: 'cat-obj-2', name: 'Analytical Engine', type: 'object' },
+ },
+ ],
+ },
+ }));
+
+ await renderPage();
+
+ // Outbound uses getRelationKind('owned-by').label -> "Owned by" (appears in select option + relation list)
+ const ownedByElements = await screen.findAllByText('Owned by');
+ expect(ownedByElements.length).toBeGreaterThanOrEqual(2);
+ expect(screen.getByText('Pocket Watch')).toBeTruthy();
+ expect(screen.getAllByText(/Ada carries this golden pocket watch everywhere/).length).toBe(2);
+
+ // Inbound uses getRelationKind('used-by').inverseLabel -> "Uses"
+ expect(screen.getByText('Uses')).toBeTruthy();
+ expect(screen.getByText('Analytical Engine')).toBeTruthy();
+ expect(screen.getAllByText(/Ada programmed the engine with punch cards/).length).toBe(2);
+
+ // SourcesPanel grounded evidence
+ expect(screen.getByText('Grounded evidence')).toBeTruthy();
+ });
});
describe('buildGenerationPromptSeed', () => {
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index f2df736bdc..950c32a3fa 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -32,12 +32,19 @@ export const pruneCatalogScrap = (id, body, options) =>
// universe — the "Catalogue into" select on CatalogIngest (#7615). Omitted
// when the caller passes 'unassigned' (the "no universe" choice), reproducing
// prior behavior exactly (source link only, no homing ref).
-export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, ...options } = {}) =>
- request(`/catalog/scraps/${enc(id)}/commit`, {
+// `relationships` forwards explicit grounded graph relationships (including [] for structured drafts).
+export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, relationships, ...options } = {}, maybeRelationships) => {
+ const rels = maybeRelationships !== undefined ? maybeRelationships : relationships;
+ return request(`/catalog/scraps/${enc(id)}/commit`, {
method: 'POST',
- body: JSON.stringify({ accepted, ...(universeRef ? { universeRef, ...(role ? { role } : {}) } : {}) }),
+ body: JSON.stringify({
+ accepted,
+ ...(universeRef ? { universeRef, ...(role ? { role } : {}) } : {}),
+ ...(rels !== undefined ? { relationships: rels } : {}),
+ }),
...options,
});
+};
// --- Alternate ingest sources (url / file / voice / brain) --------------
// Each returns { scrap, draft } — the same shape as extractFromCatalogScrap —