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: bridge brain data into CoS memory system for semantic search

Adam Eivy34bbfc8133d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e51d7a24d0..b4ecefa4df 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,10 @@
- PostgreSQL status in system health details endpoint (`/api/system/health/details`) with warnings when DB is disconnected or schema missing
- Backend status banners on CoS Memory and Brain Memory pages showing file-fallback warning with retry button
- `getMemoryBackendStatus` API client helper
+- Brain→Memory bridge: mirrors brain captures (projects, ideas, admin, journal, digests, reviews, people) into CoS memory system with embeddings for semantic search by agents
+- Source filter toggle (All/CoS/Brain) and source badges on Memory tab
+- `appId` filtering on memory list and search APIs
+- Migration script for existing brain data (`server/scripts/migrateBrainToMemories.js`)
## Changed
diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsx
index 510c70aa0f..84423eaa12 100644
--- a/client/src/components/cos/tabs/MemoryTab.jsx
+++ b/client/src/components/cos/tabs/MemoryTab.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
-import { RefreshCw, Trash2, X, Check, XCircle, Pencil, AlertTriangle } from 'lucide-react';
+import { RefreshCw, Trash2, X, Check, XCircle, Pencil, AlertTriangle, Brain, Bot } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
@@ -20,6 +20,7 @@ export default function MemoryTab({ apps = [] }) {
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState(null);
const [filters, setFilters] = useState({ types: [] });
+ const [sourceFilter, setSourceFilter] = useState('all'); // 'all' | 'cos' | 'brain'
const view = searchParams.get('view') || 'list';
const setView = useCallback((v) => {
@@ -57,9 +58,10 @@ export default function MemoryTab({ apps = [] }) {
const fetchData = useCallback(async () => {
setLoading(true);
+ const appId = sourceFilter === 'brain' ? 'brain' : sourceFilter === 'cos' ? '__not_brain' : undefined;
const [memoriesRes, pendingRes, statsRes, embRes, backendRes] = await Promise.all([
- api.getMemories({ limit: 100, ...filters }).catch(() => ({ memories: [] })),
- api.getMemories({ status: 'pending_approval', limit: 50 }).catch(() => ({ memories: [] })),
+ api.getMemories({ limit: 100, ...filters, appId }).catch(() => ({ memories: [] })),
+ api.getMemories({ status: 'pending_approval', limit: 50, appId }).catch(() => ({ memories: [] })),
api.getMemoryStats().catch(() => null),
api.getEmbeddingStatus().catch(() => null),
api.getMemoryBackendStatus().catch(() => null)
@@ -70,7 +72,7 @@ export default function MemoryTab({ apps = [] }) {
setEmbeddingStatus(embRes);
setBackendStatus(backendRes);
setLoading(false);
- }, [filters]);
+ }, [filters, sourceFilter]);
const handleApprove = async (id) => {
await api.approveMemory(id);
@@ -94,7 +96,8 @@ export default function MemoryTab({ apps = [] }) {
return;
}
setLoading(true);
- const results = await api.searchMemories(searchQuery, { limit: 20 }).catch(() => ({ memories: [] }));
+ const appId = sourceFilter === 'brain' ? 'brain' : sourceFilter === 'cos' ? '__not_brain' : undefined;
+ const results = await api.searchMemories(searchQuery, { limit: 20, appId }).catch(() => ({ memories: [] }));
setSearchResults(results.memories || []);
setLoading(false);
};
@@ -180,8 +183,25 @@ export default function MemoryTab({ apps = [] }) {
)}
</div>
- {/* Type Filters */}
- <div className="flex flex-wrap gap-2">
+ {/* Source + Type Filters */}
+ <div className="flex flex-wrap items-center gap-2">
+ {/* Source filter */}
+ {['all', 'cos', 'brain'].map(src => (
+ <button
+ key={src}
+ onClick={() => setSourceFilter(src)}
+ className={`px-3 py-2 min-h-[36px] text-xs rounded-full border transition-colors flex items-center gap-1.5 ${
+ sourceFilter === src
+ ? 'border-port-accent text-port-accent bg-port-accent/10'
+ : 'border-port-border text-gray-500 hover:text-gray-300'
+ }`}
+ >
+ {src === 'brain' && <Brain size={12} />}
+ {src === 'cos' && <Bot size={12} />}
+ {src === 'all' ? 'All Sources' : src === 'cos' ? 'CoS' : 'Brain'}
+ </button>
+ ))}
+ <span className="w-px h-5 bg-port-border" />
{MEMORY_TYPES.map(type => (
<button
key={type}
@@ -352,6 +372,15 @@ export default function MemoryTab({ apps = [] }) {
{memory.type}
</span>
<span className="text-xs text-gray-500">{memory.category}</span>
+ {memory.sourceAppId === 'brain' ? (
+ <span className="flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/30">
+ <Brain size={10} /> Brain
+ </span>
+ ) : (
+ <span className="flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-port-accent/10 text-port-accent border border-port-accent/30">
+ <Bot size={10} /> CoS
+ </span>
+ )}
{memory.similarity && (
<span className="text-xs text-port-accent">{(memory.similarity * 100).toFixed(0)}% match</span>
)}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 516423577b..66f9179515 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -803,6 +803,7 @@ export const getMemories = (options = {}) => {
if (options.categories) params.set('categories', options.categories.join(','));
if (options.tags) params.set('tags', options.tags.join(','));
if (options.status) params.set('status', options.status);
+ if (options.appId) params.set('appId', options.appId);
if (options.limit) params.set('limit', options.limit);
if (options.offset) params.set('offset', options.offset);
if (options.sortBy) params.set('sortBy', options.sortBy);
diff --git a/server/index.js b/server/index.js
index 3322d34170..9a0c901524 100644
--- a/server/index.js
+++ b/server/index.js
@@ -65,6 +65,7 @@ import * as agentActionExecutor from './services/agentActionExecutor.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
+import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
import { createAIToolkit } from 'portos-ai-toolkit/server';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
@@ -243,6 +244,8 @@ agentActionExecutor.init();
recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));
// Initialize brain scheduler for daily digests and weekly reviews
startBrainScheduler();
+// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
+initBrainMemoryBridge();
// Initialize backup scheduler for daily data backups
startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.js
index 9f86c96d4f..3c11aad2af 100644
--- a/server/lib/memoryValidation.js
+++ b/server/lib/memoryValidation.js
@@ -67,6 +67,7 @@ export const memorySearchSchema = z.object({
categories: z.array(z.string()).optional(),
tags: z.array(z.string()).optional(),
status: memoryStatusEnum.optional().default('active'),
+ appId: z.string().max(100).optional(),
minRelevance: z.number().min(0).max(1).optional().default(0.7),
limit: z.number().int().min(1).max(100).optional().default(20),
offset: z.number().int().min(0).optional().default(0)
@@ -78,6 +79,7 @@ export const memoryListSchema = z.object({
categories: z.array(z.string()).optional(),
tags: z.array(z.string()).optional(),
status: memoryStatusEnum.optional().default('active'),
+ appId: z.string().max(100).optional(),
limit: z.number().int().min(1).max(100).optional().default(50),
offset: z.number().int().min(0).optional().default(0),
sortBy: z.enum(['createdAt', 'updatedAt', 'importance', 'accessCount']).optional().default('createdAt'),
diff --git a/server/routes/memory.js b/server/routes/memory.js
index e9a1e10760..a562008925 100644
--- a/server/routes/memory.js
+++ b/server/routes/memory.js
@@ -30,6 +30,7 @@ router.get('/', asyncHandler(async (req, res) => {
categories: req.query.categories ? req.query.categories.split(',') : undefined,
tags: req.query.tags ? req.query.tags.split(',') : undefined,
status: req.query.status || 'active',
+ appId: req.query.appId || undefined,
limit: parseInt(req.query.limit, 10) || 50,
offset: parseInt(req.query.offset, 10) || 0,
sortBy: req.query.sortBy || 'createdAt',
@@ -115,7 +116,7 @@ router.get('/embeddings/status', asyncHandler(async (req, res) => {
// POST /api/memory/search - Semantic search
router.post('/search', asyncHandler(async (req, res) => {
- const { query, types, categories, tags, minRelevance, limit, offset } = validateRequest(memorySearchSchema, req.body);
+ const { query, types, categories, tags, appId, minRelevance, limit, offset } = validateRequest(memorySearchSchema, req.body);
// Generate query embedding
const queryEmbedding = await embeddings.generateQueryEmbedding(query, { types, categories });
@@ -128,6 +129,7 @@ router.post('/search', asyncHandler(async (req, res) => {
types,
categories,
tags,
+ appId,
minRelevance,
limit,
offset
diff --git a/server/scripts/migrateBrainToMemories.js b/server/scripts/migrateBrainToMemories.js
new file mode 100644
index 0000000000..08d388bbbe
--- /dev/null
+++ b/server/scripts/migrateBrainToMemories.js
@@ -0,0 +1,53 @@
+#!/usr/bin/env node
+
+/**
+ * Brain → CoS Memory Migration Script
+ *
+ * Reads all brain entity stores (people, projects, ideas, admin, memories/journal)
+ * and JSONL files (digests, reviews), then creates corresponding entries in the
+ * CoS memory system with embeddings.
+ *
+ * Usage:
+ * node server/scripts/migrateBrainToMemories.js # Dry run (default)
+ * node server/scripts/migrateBrainToMemories.js --execute # Write to memory system
+ *
+ * Records that already have a bridge mapping are skipped.
+ */
+
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+import { syncAllBrainData } from '../services/brainMemoryBridge.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+
+const args = process.argv.slice(2);
+const execute = args.includes('--execute');
+
+async function main() {
+ console.log('🧠🔗 Brain → Memory Migration');
+ console.log(` Mode: ${execute ? 'EXECUTE' : 'DRY RUN'}`);
+ console.log('');
+
+ const stats = await syncAllBrainData({ dryRun: !execute });
+
+ console.log('');
+ console.log('📊 Results:');
+ console.log(` Synced: ${stats.synced}`);
+ console.log(` Skipped: ${stats.skipped} (already mapped or archived)`);
+ console.log(` Errors: ${stats.errors}`);
+
+ if (!execute && stats.synced > 0) {
+ console.log('');
+ console.log('💡 Run with --execute to write to the memory system:');
+ console.log(' node server/scripts/migrateBrainToMemories.js --execute');
+ }
+}
+
+main().then(() => {
+ // Give async operations time to flush, then exit
+ setTimeout(() => process.exit(0), 1000);
+}).catch(err => {
+ console.error(`❌ Migration failed: ${err.message}`);
+ process.exit(1);
+});
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
new file mode 100644
index 0000000000..392a33f1e6
--- /dev/null
+++ b/server/services/brainMemoryBridge.js
@@ -0,0 +1,302 @@
+/**
+ * Brain → CoS Memory Bridge
+ *
+ * Mirrors brain records (projects, ideas, admin, memories/journal, digests, reviews, people)
+ * into the CoS memory system so agents can semantically search user-captured thoughts.
+ *
+ * Brain JSON files remain the operational data store for the brain UI.
+ * This bridge creates/updates corresponding entries in the memories table
+ * tagged with sourceAppId='brain'.
+ */
+
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { brainEvents } from './brainStorage.js';
+import * as brainStorage from './brainStorage.js';
+import * as memory from './memoryBackend.js';
+import * as embeddings from './memoryEmbeddings.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const BRIDGE_MAP_PATH = join(__dirname, '../../data/brain/memory-bridge-map.json');
+
+// brainType → { memoryType, category }
+const TYPE_MAP = {
+ people: { type: 'context', category: 'people' },
+ projects: { type: 'fact', category: 'project' },
+ ideas: { type: 'observation', category: 'ideas' },
+ admin: { type: 'fact', category: 'admin' },
+ memories: { type: 'observation', category: 'personal' },
+ digests: { type: 'context', category: 'digest' },
+ reviews: { type: 'context', category: 'review' }
+};
+
+// ─── Bridge Map ─────────────────────────────────────────────────────────────
+// Maps "brainType:brainId" → memoryId so updates hit the same memory entry
+
+let bridgeMap = null;
+
+async function loadBridgeMap() {
+ if (bridgeMap) return bridgeMap;
+ if (!existsSync(BRIDGE_MAP_PATH)) {
+ bridgeMap = {};
+ return bridgeMap;
+ }
+ const raw = await readFile(BRIDGE_MAP_PATH, 'utf-8');
+ bridgeMap = JSON.parse(raw);
+ return bridgeMap;
+}
+
+async function saveBridgeMap() {
+ const dir = dirname(BRIDGE_MAP_PATH);
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true });
+ await writeFile(BRIDGE_MAP_PATH, JSON.stringify(bridgeMap, null, 2));
+}
+
+function bridgeKey(brainType, brainId) {
+ return `${brainType}:${brainId}`;
+}
+
+// ─── Content Composers ─────────────────────────────────────────────────────
+// Each brain type has different fields; compose a single content string for memory storage.
+
+function composePeopleContent(r) {
+ const parts = [`Person: ${r.name}`];
+ if (r.context) parts.push(r.context);
+ if (r.followUps?.length) parts.push(`Follow-ups: ${r.followUps.join('; ')}`);
+ return parts.join('\n');
+}
+
+function composeProjectContent(r) {
+ const parts = [`Project: ${r.name}`, `Status: ${r.status}`];
+ if (r.nextAction) parts.push(`Next action: ${r.nextAction}`);
+ if (r.notes) parts.push(r.notes);
+ return parts.join('\n');
+}
+
+function composeIdeaContent(r) {
+ const parts = [`Idea: ${r.title}`];
+ if (r.oneLiner) parts.push(r.oneLiner);
+ if (r.notes) parts.push(r.notes);
+ return parts.join('\n');
+}
+
+function composeAdminContent(r) {
+ const parts = [`Admin: ${r.title}`, `Status: ${r.status}`];
+ if (r.dueDate) parts.push(`Due: ${r.dueDate}`);
+ if (r.nextAction) parts.push(`Next action: ${r.nextAction}`);
+ if (r.notes) parts.push(r.notes);
+ return parts.join('\n');
+}
+
+function composeJournalContent(r) {
+ const parts = [];
+ if (r.title) parts.push(r.title);
+ if (r.content) parts.push(r.content);
+ if (r.mood) parts.push(`Mood: ${r.mood}`);
+ return parts.join('\n');
+}
+
+function composeDigestContent(r) {
+ const parts = [];
+ if (r.digestText) parts.push(r.digestText);
+ if (r.topActions?.length) parts.push(`Top actions: ${r.topActions.join('; ')}`);
+ if (r.stuckThing) parts.push(`Stuck on: ${r.stuckThing}`);
+ if (r.smallWin) parts.push(`Small win: ${r.smallWin}`);
+ return parts.join('\n');
+}
+
+function composeReviewContent(r) {
+ const parts = [];
+ if (r.reviewText) parts.push(r.reviewText);
+ if (r.whatHappened?.length) parts.push(`What happened: ${r.whatHappened.join('; ')}`);
+ if (r.biggestOpenLoops?.length) parts.push(`Open loops: ${r.biggestOpenLoops.join('; ')}`);
+ if (r.suggestedActionsNextWeek?.length) parts.push(`Suggested actions: ${r.suggestedActionsNextWeek.join('; ')}`);
+ if (r.recurringTheme) parts.push(`Recurring theme: ${r.recurringTheme}`);
+ return parts.join('\n');
+}
+
+const CONTENT_COMPOSERS = {
+ people: composePeopleContent,
+ projects: composeProjectContent,
+ ideas: composeIdeaContent,
+ admin: composeAdminContent,
+ memories: composeJournalContent,
+ digests: composeDigestContent,
+ reviews: composeReviewContent
+};
+
+// ─── Core Mapping ───────────────────────────────────────────────────────────
+
+/**
+ * Convert a brain record into a memory-create payload.
+ */
+export function brainRecordToMemory(brainType, record) {
+ const mapping = TYPE_MAP[brainType];
+ if (!mapping) return null;
+
+ const composer = CONTENT_COMPOSERS[brainType];
+ const content = composer(record);
+ if (!content?.trim()) return null;
+
+ const summary = content.length > 200 ? content.substring(0, 197) + '...' : content;
+ const recordTags = record.tags || [];
+ const tags = [...new Set([...recordTags, 'brain', brainType])];
+
+ return {
+ type: mapping.type,
+ content,
+ summary,
+ category: mapping.category,
+ tags,
+ confidence: 1.0,
+ importance: 0.6,
+ sourceAppId: 'brain',
+ sourceAgentId: 'brain-bridge'
+ };
+}
+
+// ─── Sync ───────────────────────────────────────────────────────────────────
+
+/**
+ * Upsert a single brain record into the memory system.
+ * Creates a new memory or updates the existing one based on the bridge map.
+ */
+export async function syncBrainRecord(brainType, record) {
+ const memoryData = brainRecordToMemory(brainType, record);
+ if (!memoryData) return null;
+
+ const map = await loadBridgeMap();
+ const key = bridgeKey(brainType, record.id);
+ const existingMemoryId = map[key];
+
+ // Generate embedding
+ const embedding = await embeddings.generateMemoryEmbedding(memoryData).catch(() => null);
+
+ if (existingMemoryId) {
+ // Update existing memory
+ const updated = await memory.updateMemory(existingMemoryId, memoryData);
+ if (updated && embedding) {
+ await memory.updateMemoryEmbedding(existingMemoryId, embedding);
+ }
+ console.log(`🧠🔗 Updated brain→memory: ${brainType}/${record.id} → ${existingMemoryId}`);
+ return existingMemoryId;
+ }
+
+ // Create new memory
+ const created = await memory.createMemory(memoryData, embedding);
+ map[key] = created.id;
+ await saveBridgeMap();
+ console.log(`🧠🔗 Created brain→memory: ${brainType}/${record.id} → ${created.id}`);
+ return created.id;
+}
+
+/**
+ * Bulk sync all existing brain data into the memory system.
+ * Used for initial migration and catch-up.
+ * Returns { synced, skipped, errors }.
+ */
+export async function syncAllBrainData({ dryRun = false } = {}) {
+ const map = await loadBridgeMap();
+ const stats = { synced: 0, skipped: 0, errors: 0 };
+
+ // Entity stores (JSON-based)
+ const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories'];
+ for (const type of entityTypes) {
+ const records = await brainStorage.getAll(type);
+ for (const record of records) {
+ // Skip archived records
+ if (record.archived) {
+ stats.skipped++;
+ continue;
+ }
+ const key = bridgeKey(type, record.id);
+ if (map[key] && !dryRun) {
+ stats.skipped++;
+ continue;
+ }
+ if (dryRun) {
+ console.log(`🧠🔗 [dry-run] Would sync ${type}/${record.id}: ${record.name || record.title || '(untitled)'}`);
+ stats.synced++;
+ continue;
+ }
+ const memoryId = await syncBrainRecord(type, record).catch(err => {
+ console.error(`❌ Failed to sync ${type}/${record.id}: ${err.message}`);
+ stats.errors++;
+ return null;
+ });
+ if (memoryId) stats.synced++;
+ }
+ }
+
+ // JSONL stores (digests, reviews)
+ const jsonlTypes = ['digests', 'reviews'];
+ for (const type of jsonlTypes) {
+ const getter = type === 'digests' ? brainStorage.getDigests : brainStorage.getReviews;
+ const records = await getter(1000); // get all
+ for (const record of records) {
+ const key = bridgeKey(type, record.id);
+ if (map[key] && !dryRun) {
+ stats.skipped++;
+ continue;
+ }
+ if (dryRun) {
+ console.log(`🧠🔗 [dry-run] Would sync ${type}/${record.id}`);
+ stats.synced++;
+ continue;
+ }
+ const memoryId = await syncBrainRecord(type, record).catch(err => {
+ console.error(`❌ Failed to sync ${type}/${record.id}: ${err.message}`);
+ stats.errors++;
+ return null;
+ });
+ if (memoryId) stats.synced++;
+ }
+ }
+
+ return stats;
+}
+
+// ─── Event Handlers ─────────────────────────────────────────────────────────
+// Entity stores emit "{type}:changed" with the full store data object { records: { id: {...} } }
+// JSONL stores emit "{type}:added" with a single record
+
+function handleEntityChanged(brainType, storeData) {
+ if (!storeData?.records) return;
+ // Sync all non-archived records in the store
+ for (const [id, record] of Object.entries(storeData.records)) {
+ if (record.archived) continue;
+ syncBrainRecord(brainType, { id, ...record }).catch(err => {
+ console.error(`❌ Brain bridge sync failed for ${brainType}/${id}: ${err.message}`);
+ });
+ }
+}
+
+function handleJsonlAdded(brainType, record) {
+ if (!record?.id) return;
+ syncBrainRecord(brainType, record).catch(err => {
+ console.error(`❌ Brain bridge sync failed for ${brainType}/${record.id}: ${err.message}`);
+ });
+}
+
+// ─── Init ───────────────────────────────────────────────────────────────────
+
+/**
+ * Initialize the brain→memory bridge.
+ * Attaches event listeners to brainEvents so new/updated brain records
+ * are automatically mirrored to the CoS memory system.
+ */
+export function initBridge() {
+ // Entity store changes
+ for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {
+ brainEvents.on(`${type}:changed`, (data) => handleEntityChanged(type, data));
+ }
+
+ // JSONL appends (digests, reviews)
+ brainEvents.on('digests:added', (record) => handleJsonlAdded('digests', record));
+ brainEvents.on('reviews:added', (record) => handleJsonlAdded('reviews', record));
+
+ console.log('🧠🔗 Brain→Memory bridge initialized');
+}
diff --git a/server/services/memory.js b/server/services/memory.js
index b73604a280..a506dd6e91 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -241,7 +241,9 @@ export async function getMemories(options = {}) {
}
// Filter by app
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ memories = memories.filter(m => m.sourceAppId !== 'brain');
+ } else if (options.appId) {
memories = memories.filter(m => m.sourceAppId === options.appId);
}
@@ -512,7 +514,8 @@ export async function searchMemories(queryEmbedding, options = {}) {
if (options.types && options.types.length > 0 && !options.types.includes(meta.type)) return null;
if (options.categories && options.categories.length > 0 && !options.categories.includes(meta.category)) return null;
if (options.tags && options.tags.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null;
- if (options.appId && meta.sourceAppId !== options.appId) return null;
+ if (options.appId === '__not_brain' && meta.sourceAppId === 'brain') return null;
+ if (options.appId && options.appId !== '__not_brain' && meta.sourceAppId !== options.appId) return null;
return { ...meta, similarity: r.similarity };
})
@@ -655,7 +658,9 @@ export async function getTimeline(options = {}) {
}
// Filter by app
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ memories = memories.filter(m => m.sourceAppId !== 'brain');
+ } else if (options.appId) {
memories = memories.filter(m => m.sourceAppId === options.appId);
}
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index 3eb877b055..4027757838 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -174,7 +174,9 @@ export async function getMemories(options = {}) {
}
// Filter by app
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ conditions.push(`(source_app_id IS NULL OR source_app_id != 'brain')`);
+ } else if (options.appId) {
conditions.push(`source_app_id = $${paramIdx++}`);
params.push(options.appId);
}
@@ -411,7 +413,9 @@ export async function searchMemories(queryEmbedding, options = {}) {
conditions.push(`tags && $${paramIdx++}`);
params.push(options.tags);
}
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ conditions.push(`(source_app_id IS NULL OR source_app_id != 'brain')`);
+ } else if (options.appId) {
conditions.push(`source_app_id = $${paramIdx++}`);
params.push(options.appId);
}
@@ -463,7 +467,9 @@ export async function hybridSearchMemories(queryText, queryEmbedding, options =
filterConditions.push(`tags && $${paramIdx++}`);
filterParams.push(options.tags);
}
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ filterConditions.push(`(source_app_id IS NULL OR source_app_id != 'brain')`);
+ } else if (options.appId) {
filterConditions.push(`source_app_id = $${paramIdx++}`);
filterParams.push(options.appId);
}
@@ -586,7 +592,9 @@ export async function getTimeline(options = {}) {
conditions.push(`type = ANY($${paramIdx++})`);
params.push(options.types);
}
- if (options.appId) {
+ if (options.appId === '__not_brain') {
+ conditions.push(`(source_app_id IS NULL OR source_app_id != 'brain')`);
+ } else if (options.appId) {
conditions.push(`source_app_id = $${paramIdx++}`);
params.push(options.appId);
}