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

add Brain → Catalog ingestion bridge with creative-note capture flag

[._.]/ Adam Eivy7a50d0528df4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7ba6bfb0a6..a1a62054d9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
## Creative onramp
- **[issue-1633] A new "Start a Story" page gives you one clear front door for beginning a story.** Instead of guessing whether to open the Story Builder, the Importer, or the Writers Room, you now pick how you want to begin — from an idea, from an existing work, or by writing prose — and the page routes you into the right tool. You can also choose up front whether to start a fresh universe or attach the story to one you already have; that choice carries through to the Story Builder and Importer automatically. All the existing pages stay exactly where they were — this just adds a signposted entry point (reachable from the sidebar, ⌘K, and voice). (First phase of the larger creative-onramp effort; prose-mode universe linking comes later.)
+- **[issue-1633] Brain notes can now flow into the creative Catalog — making it the one place your ideas, characters, and scenes collect as reusable ingredients.** Two new paths: (1) every Brain record (idea, journal memory, project, admin item, person) gets a **Send to Catalog** button that runs it through the same extract→review→commit pipeline as paste/URL/voice, so a captured thought becomes typed ingredients (characters/scenes/ideas/…) you confirm before keeping. (2) A sticky **Creative** toggle on the Brain capture box (Inbox + Quick Capture) flags a note as a creative idea at capture time — todos and links stay out — and a **Send N creative notes → Catalog** action in the inbox batches the flagged notes into one ingest review when you're ready. Reuses the existing catalog ingest flow end-to-end; no new data model. (`server/services/catalogIngestSources.js`, `server/services/brain.js`, `client/src/components/brain/tabs/InboxTab.jsx`, `client/src/components/QuickBrainCapture.jsx`, `client/src/pages/CatalogIngest.jsx`)
## Chief of Staff
diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsx
index 9ac1c1fb64..f7d7048f53 100644
--- a/client/src/components/QuickBrainCapture.jsx
+++ b/client/src/components/QuickBrainCapture.jsx
@@ -1,14 +1,18 @@
import { useState, useMemo, useRef } from 'react';
import { Link } from 'react-router-dom';
-import { Send } from 'lucide-react';
+import { Send, Sparkles } from 'lucide-react';
import toast from './ui/Toast';
import * as api from '../services/api';
+import { useLocalStorageBool } from '../hooks';
import { isUrl as isUrlShared, normalizeUrl } from '../utils/urlNormalize';
export default function QuickBrainCapture() {
const [input, setInput] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const submittingRef = useRef(false);
+ // Sticky "Creative" flag (shared key with the Inbox capture toggle) so a
+ // creative thought captured here is flagged for the catalog the same way.
+ const [creative, setCreative] = useLocalStorageBool('brain.captureCreative', false);
const isUrl = useMemo(() => isUrlShared(input), [input]);
@@ -38,7 +42,7 @@ export default function QuickBrainCapture() {
toast.success(result.isGitHubRepo ? 'GitHub repo added' : 'Link saved');
}
} else {
- const result = await api.captureBrainThought(text).catch(err => {
+ const result = await api.captureBrainThought(text, undefined, undefined, { creative }).catch(err => {
toast.error(err.message || 'Failed to capture thought');
setInput(prev => prev || text);
return null;
@@ -69,6 +73,18 @@ export default function QuickBrainCapture() {
onChange={e => setInput(e.target.value)}
className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
/>
+ <button
+ type="button"
+ onClick={() => setCreative(v => !v)}
+ aria-pressed={creative}
+ disabled={isUrl}
+ className={`flex items-center px-2.5 py-2 rounded-lg border text-sm transition-colors min-h-[40px] disabled:opacity-40 disabled:cursor-not-allowed ${creative
+ ? 'bg-purple-500/20 text-purple-300 border-purple-500/40'
+ : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}
+ title={isUrl ? 'URLs are saved as links, not creative ideas' : 'Creative mode: flag this thought for the Catalog'}
+ >
+ <Sparkles size={14} />
+ </button>
<button
type="submit"
disabled={!input.trim() || isSubmitting}
@@ -79,7 +95,7 @@ export default function QuickBrainCapture() {
</form>
{input.trim() && (
<p className="mt-2 text-xs text-gray-500">
- {isUrl ? 'Will save as link' : 'Will capture as thought'}
+ {isUrl ? 'Will save as link' : creative ? 'Will capture as a creative thought' : 'Will capture as thought'}
</p>
)}
</div>
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsx
index a667c7a093..a44721e409 100644
--- a/client/src/components/brain/tabs/InboxTab.jsx
+++ b/client/src/components/brain/tabs/InboxTab.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react';
+import { useNavigate } from 'react-router-dom';
import * as api from '../../../services/api';
import socket from '../../../services/socket';
import {
@@ -14,11 +15,14 @@ import {
Trash2,
Save,
X,
+ Sparkles,
+ Library,
Brain
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
+import { useLocalStorageBool } from '../../../hooks';
import {
DESTINATIONS,
@@ -28,7 +32,12 @@ import { timeAgo } from '../../../utils/formatters';
import VoiceCapture from '../VoiceCapture';
export default function InboxTab({ onRefresh, settings }) {
+ const navigate = useNavigate();
const [inputText, setInputText] = useState('');
+ // Sticky "Creative" capture mode (shared localStorage key with Quick Capture):
+ // when on, captured thoughts are flagged so they can later be batch-sent to the
+ // creative catalog (vs todos/refs that stay out).
+ const [creative, setCreative] = useLocalStorageBool('brain.captureCreative', false);
const [entries, setEntries] = useState([]);
const [loading, setLoading] = useState(true);
const [showNeedsReview, setShowNeedsReview] = useState(true);
@@ -91,12 +100,13 @@ export default function InboxTab({ onRefresh, settings }) {
id: tempId,
capturedText: text,
status: 'classifying',
- capturedAt: new Date().toISOString()
+ capturedAt: new Date().toISOString(),
+ ...(creative ? { creative: true } : {})
};
setInputText('');
setEntries(prev => [optimisticEntry, ...prev]);
- const result = await api.captureBrainThought(text).catch(err => {
+ const result = await api.captureBrainThought(text, undefined, undefined, { creative }).catch(err => {
toast.error(err.message || 'Failed to capture thought');
setEntries(prev => prev.filter(e => e.id !== tempId));
return null;
@@ -226,6 +236,24 @@ export default function InboxTab({ onRefresh, settings }) {
const doneEntries = entries.filter(e => e.status === 'done');
const errorEntries = entries.filter(e => e.status === 'error');
+ // Creative notes the user flagged at capture, not yet marked done — the pool
+ // the "Send to Catalog" batch action draws from. Pending (optimistic) entries
+ // are excluded so we never ship a thought the server hasn't confirmed.
+ const creativeEntries = entries.filter(
+ e => e.creative && e.status !== 'done' && !String(e.id).startsWith('_pending_')
+ );
+ // Batch-send creative notes into the catalog ingest flow. We hand the combined
+ // text to /catalog/ingest (router state) where the user runs extract→review→
+ // commit — turning loose creative thoughts into typed catalog ingredients.
+ const handleSendCreativeToCatalog = () => {
+ if (!creativeEntries.length) return;
+ const rawText = creativeEntries
+ .map(e => e.capturedText)
+ .filter(Boolean)
+ .join('\n\n---\n\n');
+ navigate('/catalog/ingest', { state: { prefill: { title: 'Creative notes from Brain', rawText } } });
+ };
+
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -262,6 +290,18 @@ export default function InboxTab({ onRefresh, settings }) {
className="flex-1 px-4 py-3 bg-port-card border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-hidden focus:border-port-accent"
/>
<VoiceCapture onTranscript={handleVoiceTranscript} />
+ <button
+ type="button"
+ onClick={() => setCreative(v => !v)}
+ aria-pressed={creative}
+ className={`px-3 py-3 rounded-lg border transition-colors flex items-center gap-1.5 text-sm ${creative
+ ? 'bg-purple-500/20 text-purple-300 border-purple-500/40'
+ : 'bg-port-card text-gray-400 border-port-border hover:text-gray-200'}`}
+ title="Creative mode: flag captures as creative ideas you can send to the Catalog"
+ >
+ <Sparkles className="w-4 h-4" />
+ <span className="hidden sm:inline">Creative</span>
+ </button>
<button
type="submit"
disabled={!inputText.trim()}
@@ -273,12 +313,31 @@ export default function InboxTab({ onRefresh, settings }) {
</div>
<p className="mt-2 text-xs text-gray-500">
Capture a thought — type or use the mic. AI will classify and route it automatically.
+ {creative && <span className="text-purple-300"> Creative mode on — captures are flagged for the Catalog.</span>}
{settings?.confidenceThreshold && (
<span> Confidence threshold: {Math.round(settings.confidenceThreshold * 100)}%</span>
)}
</p>
</form>
+ {/* Creative batch action — appears once any captured note is flagged
+ creative. Sends them all into the catalog ingest review in one hop. */}
+ {creativeEntries.length > 0 && (
+ <div className="xl:col-span-2 flex items-center justify-between gap-3 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg">
+ <span className="text-sm text-purple-200 flex items-center gap-2">
+ <Sparkles className="w-4 h-4 flex-shrink-0" />
+ {creativeEntries.length} creative {creativeEntries.length === 1 ? 'note' : 'notes'} ready to become catalog ingredients
+ </span>
+ <button
+ type="button"
+ onClick={handleSendCreativeToCatalog}
+ className="px-3 py-1.5 bg-purple-500/20 hover:bg-purple-500/30 text-purple-200 border border-purple-500/40 rounded-lg text-sm transition-colors flex items-center gap-1.5 flex-shrink-0"
+ >
+ <Library className="w-4 h-4" /> Send to Catalog
+ </button>
+ </div>
+ )}
+
{/* Needs Review rail — right column on xl+, first after the form on mobile.
Capped to the viewport and given its own scroll on xl+ so a long
Needs-Review queue stays reachable instead of growing past the fold
@@ -603,7 +662,12 @@ export default function InboxTab({ onRefresh, settings }) {
>
<div className="flex items-start justify-between gap-2 mb-2">
<div className="flex-1">
- <p className="text-white">{entry.capturedText}</p>
+ <p className="text-white">
+ {entry.creative && (
+ <Sparkles className="inline w-3.5 h-3.5 text-purple-300 mr-1.5 -mt-0.5" aria-label="Creative note" />
+ )}
+ {entry.capturedText}
+ </p>
{entry.classification?.cleanedUp && entry.classification.cleanedUp !== entry.capturedText && (
<p className="text-sm text-gray-300 mt-1 pl-3 border-l-2 border-port-accent/30">
{entry.classification.cleanedUp}
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index 6bd31cf078..dafdba2b31 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
+import { useNavigate } from 'react-router-dom';
import * as api from '../../../services/api';
import {Plus,
Edit2,
@@ -8,6 +9,7 @@ import {Plus,
CheckCircle2,
Search,
AlertTriangle,
+ Library,
MessageSquareText} from 'lucide-react';
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
@@ -28,6 +30,7 @@ import CopyableId from '../../ui/CopyableId';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
export default function MemoryTab({ onRefresh }) {
+ const navigate = useNavigate();
const [activeType, setActiveType] = useState('memories');
const [records, setRecords] = useState([]);
const [loading, setLoading] = useState(true);
@@ -250,6 +253,18 @@ export default function MemoryTab({ onRefresh }) {
}
};
+ // Send a brain record into the creative catalog. We hand the ids to the
+ // catalog ingest page (via router state) so the LLM extraction + live stage
+ // checklist run there — the brain note becomes typed catalog ingredients the
+ // user reviews and commits. Every MEMORY_TABS type is a supported bridge type.
+ const handleSendToCatalog = (record) => {
+ // Hand off just the ids — the catalog resolves the record and derives its
+ // title/text server-side via the brain-bridge ingest.
+ navigate('/catalog/ingest', {
+ state: { brainIngest: { brainType: activeType, brainId: record.id } },
+ });
+ };
+
const startEdit = (record) => {
setEditingId(record.id);
setEditForm({ ...record, tagInput: (record.tags || []).join(', ') });
@@ -583,6 +598,13 @@ export default function MemoryTab({ onRefresh }) {
<CheckCircle2 size={14} />
</button>
)}
+ <button
+ onClick={() => handleSendToCatalog(record)}
+ className="p-1.5 text-gray-400 hover:text-purple-300 rounded hover:bg-purple-500/20"
+ title="Send to Catalog"
+ >
+ <Library size={14} />
+ </button>
<button
onClick={() => startEdit(record)}
className="p-1.5 text-gray-400 hover:text-white rounded hover:bg-port-border/50"
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 40c431dfe6..8bb31ac5a3 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -6,7 +6,7 @@
*/
import { useState, useEffect, useRef } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useNavigate, useLocation } from 'react-router-dom';
import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
@@ -19,6 +19,7 @@ import {
ingestCatalogUrl,
ingestCatalogFile,
ingestCatalogVoice,
+ ingestCatalogBrain,
} from '../services/apiCatalog';
// One review section per ingredient type. The first three are bible-shaped
@@ -60,6 +61,7 @@ function StageIcon({ status }) {
export default function CatalogIngest() {
const navigate = useNavigate();
+ const location = useLocation();
const [phase, setPhase] = useState('paste'); // 'paste' | 'extracting' | 'review'
const [title, setTitle] = useState('');
const [rawText, setRawText] = useState('');
@@ -86,6 +88,7 @@ export default function CatalogIngest() {
const [recording, setRecording] = useState(false);
const recorderRef = useRef(null);
const fileInputRef = useRef(null);
+ const brainHandledRef = useRef(false);
// Stop the mic if the page unmounts mid-recording (navigating away), so the
// MediaRecorder stream isn't left live with no UI to stop it.
@@ -201,6 +204,46 @@ export default function CatalogIngest() {
enterReviewFromResult(result);
};
+ // Brain → catalog handoff: the brain UI navigates here with
+ // location.state.brainIngest = { brainType, brainId, title }, then we run the
+ // SAME extract→review flow as URL/file/voice (live stage checklist included).
+ const handleBrainIngest = async ({ brainType, brainId }) => {
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ const result = await ingestCatalogBrain({ brainType, brainId }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Brain ingest failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result);
+ };
+
+ // Handle inbound router-state handoffs once on mount:
+ // - brainIngest { brainType, brainId } → run the brain-bridge extract→review.
+ // - prefill { title, rawText } → drop the text into the paste box so
+ // the user reviews/edits it, then clicks Extract (the creative-notes batch
+ // send from the brain inbox uses this).
+ // Either way we clear the history state afterwards so a refresh/back doesn't
+ // re-trigger the handoff (and, for brainIngest, a second LLM-billed run).
+ useEffect(() => {
+ if (brainHandledRef.current) return;
+ const brainIngest = location.state?.brainIngest;
+ const prefill = location.state?.prefill;
+ let handled = false;
+ if (brainIngest?.brainType && brainIngest?.brainId) {
+ handled = true;
+ handleBrainIngest(brainIngest);
+ } else if (typeof prefill?.rawText === 'string' && prefill.rawText.trim()) {
+ handled = true;
+ setSourceMode('paste');
+ setTitle(prefill.title || '');
+ setRawText(prefill.rawText);
+ }
+ if (handled) {
+ brainHandledRef.current = true;
+ navigate('.', { replace: true, state: {} });
+ }
+ }, []);
+
const handleFilePicked = async (e) => {
const file = e.target.files?.[0];
e.target.value = ''; // allow re-picking the same file
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 172e4627d3..1fb261dc4d 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -9,9 +9,9 @@ export const updateBrainSettings = (settings) => request('/brain/settings', {
});
// Brain - Capture & Inbox
-export const captureBrainThought = (text, providerOverride, modelOverride) => request('/brain/capture', {
+export const captureBrainThought = (text, providerOverride, modelOverride, { creative } = {}) => request('/brain/capture', {
method: 'POST',
- body: JSON.stringify({ text, providerOverride, modelOverride })
+ body: JSON.stringify({ text, providerOverride, modelOverride, creative })
});
export const getBrainInbox = (options = {}) => {
const params = new URLSearchParams();
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index d6453d9ccd..7e5616c669 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -38,7 +38,7 @@ export const extractFromCatalogScrap = (id, body = {}, options) =>
export const commitCatalogScrapDraft = (id, accepted, options) =>
request(`/catalog/scraps/${enc(id)}/commit`, { method: 'POST', body: JSON.stringify({ accepted }), ...options });
-// --- Alternate ingest sources (url / file / voice) ----------------------
+// --- Alternate ingest sources (url / file / voice / brain) --------------
// Each returns { scrap, draft } — the same shape as extractFromCatalogScrap —
// so CatalogIngest can drop straight into its review phase.
@@ -51,6 +51,10 @@ export const ingestCatalogFile = (body = {}, options) =>
export const ingestCatalogVoice = (body = {}, options) =>
request('/catalog/ingest/voice', { method: 'POST', body: JSON.stringify(body), ...options });
+// Brain → catalog bridge: ingest an existing brain record by { brainType, brainId }.
+export const ingestCatalogBrain = (body = {}, options) =>
+ request('/catalog/ingest/brain', { method: 'POST', body: JSON.stringify(body), ...options });
+
// --- Ingredients --------------------------------------------------------
export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...options } = {}) => {
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 65be89e359..09e3a33b47 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -67,7 +67,10 @@ export const inboxLogRecordSchema = z.object({
status: inboxStatusEnum,
filed: filedSchema.optional(),
correction: correctionSchema.optional(),
- error: errorSchema.optional()
+ error: errorSchema.optional(),
+ // User-marked creative note (see captureInputSchema.creative). Drives the
+ // "Send creative notes to Catalog" batch action in the inbox.
+ creative: z.boolean().optional()
});
// People Record schema
@@ -171,7 +174,11 @@ export const reviewRecordSchema = z.object({
export const captureInputSchema = z.object({
text: z.string().min(1).max(10000),
providerOverride: z.string().optional(),
- modelOverride: z.string().optional()
+ modelOverride: z.string().optional(),
+ // Opt-in flag: the user marked this note as a creative idea at capture time
+ // (vs a todo/reference). Creative notes are later batch-sendable into the
+ // creative catalog as ingredients (see catalog brain-bridge ingest).
+ creative: z.boolean().optional()
});
// Resolve review input schema
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 7901050db9..88f66b0459 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -222,6 +222,22 @@ export const catalogVoiceIngestSchema = z.object({
providerOverride: z.string().trim().min(1).max(120).optional(),
}).strict();
+// Brain-bridge ingest. Instead of pasted/fetched text, the source is an existing
+// brain record (an idea, journal memory, project, admin item, or person). The
+// route resolves the record by `{ brainType, brainId }`, folds its prose into
+// one rawText block, and runs the SAME extraction pipeline — so a captured
+// thought becomes typed catalog ingredients (characters/scenes/ideas/…) the
+// user reviews and commits. This is the "make the catalog the universal sink"
+// ingestion bridge: brain entries finally flow into the catalog the way
+// paste/url/file/voice already do. The supported types mirror
+// `BRAIN_INGEST_GETTERS` in catalogIngestSources.js (keep the two in lockstep).
+export const CATALOG_BRAIN_INGEST_TYPES = Object.freeze(['ideas', 'memories', 'projects', 'admin', 'people']);
+export const catalogBrainIngestSchema = z.object({
+ brainType: z.enum(CATALOG_BRAIN_INGEST_TYPES),
+ brainId: z.string().trim().min(1).max(200),
+ providerOverride: z.string().trim().min(1).max(120).optional(),
+}).strict();
+
export const catalogIngredientCreateSchema = z.object({
type: ingredientTypeGate,
name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
diff --git a/server/routes/brain.js b/server/routes/brain.js
index 7268ef59c5..89415eadcb 100644
--- a/server/routes/brain.js
+++ b/server/routes/brain.js
@@ -66,8 +66,8 @@ const router = Router();
* Capture a thought, classify it, and store it
*/
router.post('/capture', asyncHandler(async (req, res) => {
- const { text, providerOverride, modelOverride } = validateRequest(captureInputSchema, req.body);
- const result = await brainService.captureThought(text, providerOverride, modelOverride);
+ const { text, providerOverride, modelOverride, creative } = validateRequest(captureInputSchema, req.body);
+ const result = await brainService.captureThought(text, providerOverride, modelOverride, { creative });
res.json(result);
}));
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index ec4d8a0d36..43fab7962f 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -33,6 +33,7 @@ import {
catalogUrlIngestSchema,
catalogFileIngestSchema,
catalogVoiceIngestSchema,
+ catalogBrainIngestSchema,
catalogUserTypeSchema,
catalogUserTypesSettingsSchema,
REF_KINDS,
@@ -43,7 +44,7 @@ import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalog
import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredientsForScrap } from '../services/catalogExtraction.js';
-import { ingestFromUrl, ingestFromFile, ingestFromVoice } from '../services/catalogIngestSources.js';
+import { ingestFromUrl, ingestFromFile, ingestFromVoice, ingestFromBrain } from '../services/catalogIngestSources.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
@@ -138,6 +139,14 @@ router.post('/ingest/voice', asyncHandler(async (req, res) => {
res.status(201).json(result);
}));
+// Brain → catalog bridge: ingest an existing brain record (idea/memory/etc.)
+// through the same extraction pipeline so it lands on the identical review phase.
+router.post('/ingest/brain', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogBrainIngestSchema, req.body);
+ const result = await ingestFromBrain(body);
+ res.status(201).json(result);
+}));
+
router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
validateRequest(catalogScrapCommitSchema, req.body);
const scrap = await catalogDB.getScrap(req.params.id);
diff --git a/server/services/brain.js b/server/services/brain.js
index c736cdf2fd..0d10b9b58f 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -133,7 +133,7 @@ function safeParseJsonResponse(content) {
* Returns immediately after creating the inbox entry.
* AI classification runs in the background and emits a socket event on completion.
*/
-export async function captureThought(text, providerOverride, modelOverride) {
+export async function captureThought(text, providerOverride, modelOverride, { creative = false } = {}) {
const meta = await storage.loadMeta();
const provider = providerOverride || meta.defaultProvider;
const model = modelOverride || meta.defaultModel;
@@ -162,6 +162,7 @@ export async function captureThought(text, providerOverride, modelOverride) {
const inboxEntry = await storage.createInboxLog({
capturedText: text,
source: 'brain_ui',
+ ...(creative ? { creative: true } : {}),
...(mode === 'off'
? {}
: { ai: { providerId: provider, modelId: model, promptTemplateId: 'brain-classifier' } }),
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index c1237cdae6..37ca6b61fc 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -198,6 +198,26 @@ describe('brain service', () => {
})
);
});
+
+ it('flags the inbox entry when captured as creative', async () => {
+ storage.createInboxLog.mockResolvedValue({ id: 'inbox-004', status: 'classifying' });
+
+ await captureThought('a sentient city', undefined, undefined, { creative: true });
+
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.objectContaining({ creative: true })
+ );
+ });
+
+ it('omits the creative flag by default (non-creative captures stay unflagged)', async () => {
+ storage.createInboxLog.mockResolvedValue({ id: 'inbox-005', status: 'classifying' });
+
+ await captureThought('buy milk');
+
+ expect(storage.createInboxLog).toHaveBeenCalledWith(
+ expect.not.objectContaining({ creative: expect.anything() })
+ );
+ });
});
// ===========================================================================
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index ae417b975a..0ba14e8cb1 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -1,18 +1,23 @@
/**
- * Catalog ingest sources — URL / file / voice-memo entry points.
+ * Catalog ingest sources — URL / file / voice-memo / brain-bridge entry points.
*
* Each source produces raw text + a scrap with a typed `source_kind`, then
* hands off to the SAME extraction pipeline the textarea-paste flow uses
* (`extractIngredients`). So they emit identical `catalog:extract:progress`
* frames and the client lands on the same paste→review→commit UI.
*
- * url — fetch the page via the browser service, pull main text,
- * source_kind 'url', metadata { url, title }.
- * file — text already read client-side (.txt/.md), source_kind 'file',
- * metadata { filename, mime }.
- * voice-memo — base64 WAV → Whisper transcript, audio persisted under
- * data/audio to mint a media_key, source_kind 'voice-memo',
- * metadata { mediaKey, mimeType, durationApproxMs? }.
+ * url — fetch the page via the browser service, pull main text,
+ * source_kind 'url', metadata { url, title }.
+ * file — text already read client-side (.txt/.md), source_kind 'file',
+ * metadata { filename, mime }.
+ * voice-memo — base64 WAV → Whisper transcript, audio persisted under
+ * data/audio to mint a media_key, source_kind 'voice-memo',
+ * metadata { mediaKey, mimeType, durationApproxMs? }.
+ * brain-bridge — an existing brain record (idea / memory / project / admin /
+ * person), its prose folded into one rawText block,
+ * source_kind 'brain-bridge', metadata { brainType, brainId,
+ * brainTitle, brainTags }. This is the ingestion bridge that
+ * makes the catalog the universal sink for captured thoughts.
*
* Keeping this orchestration out of the route handlers lets the unit tests
* mock the network/Whisper boundaries without spinning up Express.
@@ -22,6 +27,7 @@ import { randomUUID } from 'crypto';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import * as catalogDB from './catalogDB.js';
+import * as brainStorage from './brainStorage.js';
import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
import {
@@ -221,3 +227,87 @@ export async function ingestFromVoice(
});
return { scrap, draft, mediaKey };
}
+
+// Supported brain record types → their by-id storage getter. Mirrors
+// `CATALOG_BRAIN_INGEST_TYPES` in catalogValidation.js (the route validates the
+// type against that enum before we get here; this map is the resolution side).
+// We import the leaf `brainStorage` rather than `brain.js` so this stays a pure
+// read — no AI/classification side effects ride along.
+const BRAIN_INGEST_GETTERS = {
+ ideas: brainStorage.getIdeaById,
+ memories: brainStorage.getMemoryEntryById,
+ projects: brainStorage.getProjectById,
+ admin: brainStorage.getAdminById,
+ people: brainStorage.getPersonById,
+};
+
+/**
+ * Fold a brain record's prose into a single ingest-ready text block. Each brain
+ * type keeps its body in different fields (an idea's `oneLiner` + `notes`, a
+ * memory's `content`, a project/admin's `nextAction` + `notes`, a person's
+ * `context` + `followUps`), so map per-type rather than guessing. The record's
+ * title/name is prepended as context for the extractor, and any record tags ride
+ * along in metadata so the user can keep them on the committed ingredients.
+ * Returns `{ title, rawText, tags }`.
+ */
+export function brainRecordToIngestText(brainType, record) {
+ const title = (record?.title || record?.name || '').trim();
+ const parts = [];
+ const push = (v) => { if (typeof v === 'string' && v.trim()) parts.push(v.trim()); };
+ switch (brainType) {
+ case 'ideas':
+ push(record?.oneLiner);
+ push(record?.notes);
+ break;
+ case 'memories':
+ push(record?.content);
+ break;
+ case 'projects':
+ case 'admin':
+ if (record?.nextAction) push(`Next: ${record.nextAction}`);
+ push(record?.notes);
+ break;
+ case 'people':
+ push(record?.context);
+ if (Array.isArray(record?.followUps) && record.followUps.length) {
+ push(`Follow-ups: ${record.followUps.join('; ')}`);
+ }
+ break;
+ default:
+ // Best-effort for any future type the enum admits before this map does.
+ for (const k of ['oneLiner', 'content', 'notes', 'context', 'summary', 'description']) {
+ push(record?.[k]);
+ }
+ }
+ const body = parts.join('\n\n').trim();
+ const rawText = clampText(title ? `${title}\n\n${body}`.trim() : body);
+ const tags = Array.isArray(record?.tags) ? record.tags.filter((t) => typeof t === 'string') : [];
+ return { title: title || 'Brain entry', rawText, tags };
+}
+
+/**
+ * Ingest from an existing brain record. Resolves the record by `{ brainType,
+ * brainId }`, folds its prose into rawText, and runs the same scrap→extract
+ * pipeline as every other source — returning `{ scrap, draft }` so the client
+ * lands on the identical review phase. This is the brain → catalog bridge: a
+ * captured idea/journal/etc. becomes typed catalog ingredients the user reviews
+ * and commits, making the catalog the universal sink for creative atoms.
+ */
+export async function ingestFromBrain({ brainType, brainId, providerOverride } = {}) {
+ const getter = BRAIN_INGEST_GETTERS[brainType];
+ if (!getter) throw new Error(`unsupported brain type for catalog ingest: ${brainType}`);
+ const record = await getter(brainId);
+ if (!record) throw new Error(`brain ${brainType} entry not found: ${brainId}`);
+ // rawText is already trimmed by brainRecordToIngestText, so a falsy check is
+ // sufficient to catch an empty record.
+ const { title, rawText, tags } = brainRecordToIngestText(brainType, record);
+ if (!rawText) throw new Error('brain entry had no text to ingest');
+ return createScrapAndExtract({
+ title,
+ rawText,
+ sourceKind: 'brain-bridge',
+ metadata: { brainType, brainId, brainTitle: title, brainTags: tags },
+ providerOverride,
+ log: (s) => `🧠 Catalog brain ingest: ${brainType}/${brainId} → scrap ${s.id} (${rawText.length} chars)`,
+ });
+}
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index a756a51623..46ea9dd84a 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -21,6 +21,13 @@ vi.mock('./catalogExtraction.js', () => ({
extractIngredients: vi.fn(),
extractIngredientsForScrap: vi.fn(),
}));
+vi.mock('./brainStorage.js', () => ({
+ getIdeaById: vi.fn(),
+ getMemoryEntryById: vi.fn(),
+ getProjectById: vi.fn(),
+ getAdminById: vi.fn(),
+ getPersonById: vi.fn(),
+}));
vi.mock('./voice/stt.js', () => ({
transcribe: vi.fn(),
}));
@@ -51,6 +58,7 @@ vi.mock('../lib/fileUtils.js', () => ({
const catalogDB = await import('./catalogDB.js');
const catalogExtraction = await import('./catalogExtraction.js');
const browserService = await import('./browserService.js');
+const brainStorage = await import('./brainStorage.js');
const fsp = await import('fs/promises');
const dnsp = await import('dns/promises');
const {
@@ -58,6 +66,8 @@ const {
ingestFromUrl,
ingestFromFile,
ingestFromVoice,
+ ingestFromBrain,
+ brainRecordToIngestText,
} = await import('./catalogIngestSources.js');
const DRAFT = { runId: 'r1', characters: [], stages: [] };
@@ -214,3 +224,69 @@ describe('ingestFromVoice', () => {
expect(writtenPath).toContain('/tmp/data/audio');
});
});
+
+describe('brainRecordToIngestText', () => {
+ it('folds an idea record (title + oneLiner + notes) into one block', () => {
+ const { title, rawText, tags } = brainRecordToIngestText('ideas', {
+ title: 'The city remembers',
+ oneLiner: 'A surveillance net becomes sentient.',
+ notes: 'It helps the protagonist.',
+ tags: ['sci-fi', 'ai'],
+ });
+ expect(title).toBe('The city remembers');
+ expect(rawText).toBe('The city remembers\n\nA surveillance net becomes sentient.\n\nIt helps the protagonist.');
+ expect(tags).toEqual(['sci-fi', 'ai']);
+ });
+
+ it('uses content for a memory and name for a person', () => {
+ expect(brainRecordToIngestText('memories', { title: 'Rooftop', content: 'Rain, neon.' }).rawText)
+ .toBe('Rooftop\n\nRain, neon.');
+ const person = brainRecordToIngestText('people', { name: 'Elena', context: 'Detective.', followUps: ['call', 'verify'] });
+ expect(person.title).toBe('Elena');
+ expect(person.rawText).toBe('Elena\n\nDetective.\n\nFollow-ups: call; verify');
+ });
+
+ it('falls back to a default title and drops non-string tags', () => {
+ const out = brainRecordToIngestText('memories', { content: 'orphan note', tags: ['ok', 5, null] });
+ expect(out.title).toBe('Brain entry');
+ expect(out.rawText).toBe('orphan note');
+ expect(out.tags).toEqual(['ok']);
+ });
+});
+
+describe('ingestFromBrain', () => {
+ it('resolves an idea, creates a brain-bridge scrap, and runs extraction', async () => {
+ brainStorage.getIdeaById.mockResolvedValue({
+ id: 'idea-1', title: 'Neon detective', oneLiner: 'Noir in a sentient city.', tags: ['noir'],
+ });
+ const { scrap, draft } = await ingestFromBrain({ brainType: 'ideas', brainId: 'idea-1' });
+ expect(draft).toBe(DRAFT);
+ const createArgs = catalogDB.createChunkedScrap.mock.calls[0][0];
+ expect(createArgs.sourceKind).toBe('brain-bridge');
+ expect(createArgs.title).toBe('Neon detective');
+ expect(createArgs.rawText).toBe('Neon detective\n\nNoir in a sentient city.');
+ expect(createArgs.metadata).toEqual({
+ brainType: 'ideas', brainId: 'idea-1', brainTitle: 'Neon detective', brainTags: ['noir'],
+ });
+ expect(catalogExtraction.extractIngredientsForScrap).toHaveBeenCalledWith(
+ expect.objectContaining({ scrapId: scrap.id }),
+ );
+ });
+
+ it('rejects an unsupported brain type before any lookup', async () => {
+ await expect(ingestFromBrain({ brainType: 'links', brainId: 'x' })).rejects.toThrow(/unsupported brain type/);
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
+ });
+
+ it('throws when the brain record is missing', async () => {
+ brainStorage.getMemoryEntryById.mockResolvedValue(null);
+ await expect(ingestFromBrain({ brainType: 'memories', brainId: 'gone' })).rejects.toThrow(/not found/);
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
+ });
+
+ it('throws when the record has no text to ingest', async () => {
+ brainStorage.getMemoryEntryById.mockResolvedValue({ id: 'm1', title: ' ', content: '' });
+ await expect(ingestFromBrain({ brainType: 'memories', brainId: 'm1' })).rejects.toThrow(/no text/);
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
+ });
+});