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: enroll SongBook songs in the brain memory bridge and knowledge graph (#4105)

[._.]/ Adam Eivy1823b88b835f
diff --git a/.changelog/next/added-issue-4105.md b/.changelog/next/added-issue-4105.md
new file mode 100644
index 0000000000..fdc0bb78d9
--- /dev/null
+++ b/.changelog/next/added-issue-4105.md
@@ -0,0 +1 @@
+- SongBook songs are enrolled in the brain memory bridge and knowledge graph — they embed for semantic search and appear as graph nodes with shared-tag and similarity edges
diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.js
index 8b06ddd2e5..514e7bbb06 100644
--- a/client/src/components/brain/constants.js
+++ b/client/src/components/brain/constants.js
@@ -1,4 +1,4 @@
-import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen, Upload, Target, BookText } from 'lucide-react';
+import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen, Upload, Target, BookText, Music } from 'lucide-react';
// Main navigation tabs.
// `fullBleed: true` marks a tab that fills the available height and owns its
@@ -72,6 +72,11 @@ export const DESTINATIONS = {
icon: BookText,
color: 'bg-teal-500/20 text-teal-400 border-teal-500/30'
},
+ songs: {
+ label: 'SongBook',
+ icon: Music,
+ color: 'bg-rose-500/20 text-rose-400 border-rose-500/30'
+ },
unknown: {
label: 'Unknown',
icon: MessageSquare,
@@ -81,8 +86,8 @@ export const DESTINATIONS = {
// Destinations a user can file an inbox entry to by hand (Route / Fix pickers).
// Mirrors the server's `manualDestinationEnum` — NOT `Object.keys(DESTINATIONS)`,
-// which also holds display-only entries (`links`, `goals`, `journals`) the
-// resolve/fix endpoints reject.
+// which also holds display-only entries (`links`, `goals`, `journals`, `songs`)
+// the resolve/fix endpoints reject.
export const MANUAL_DESTINATIONS = ['people', 'projects', 'ideas', 'admin', 'memories'];
/**
@@ -149,6 +154,7 @@ export const BRAIN_TYPE_HEX = {
admin: '#22c55e',
memories: '#ec4899',
goals: '#f97316',
- journals: '#14b8a6'
+ journals: '#14b8a6',
+ songs: '#f43f5e'
};
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsx
index fb767f3ad2..ef1fa3bd38 100644
--- a/client/src/components/brain/tabs/BrainGraph.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.jsx
@@ -19,7 +19,7 @@ const EDGE_COLORS = {
linked: '#ffffff'
};
-const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'goals', 'journals'];
+const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'songs', 'goals', 'journals'];
// Widest the hover tooltip renders. Single source for both its max-width and
// the clamp that keeps it inside the viewport — as a CSS class plus a mirrored
@@ -34,7 +34,23 @@ const TYPE_GETTERS = {
admin: api.getBrainAdminItem,
memories: api.getBrainMemory,
goals: api.getBrainGoal,
- journals: api.getBrainJournalEntry
+ journals: api.getBrainJournalEntry,
+ songs: api.getSong
+};
+
+// Prose body for the detail panel, in the order the panel prefers it. Every
+// candidate is type-checked rather than `||`-chained straight through: a
+// SongBook record's `content` is an OBJECT (`{ format, text }`), not a string,
+// and handing that to React throws "Objects are not valid as a React child".
+// Mirrors `entitySummary` in server/services/brainGraph.js — the panel falls
+// back to the node's server-computed summary, so the two must agree on which
+// field a record reads as.
+const BODY_FIELDS = ['description', 'context', 'oneLiner', 'artist', 'notes', 'content'];
+export const recordBody = (record) => {
+ for (const field of BODY_FIELDS) {
+ if (typeof record?.[field] === 'string' && record[field]) return record[field];
+ }
+ return '';
};
function GraphEdges({ simEdges, selectedId }) {
@@ -344,7 +360,7 @@ export default function BrainGraph() {
if (!graphData?.nodes?.length) {
return (
<div className="text-center py-12 text-gray-500">
- No brain entities to graph. Add people, projects, ideas, admin items, memories, goals, or journal entries to see relationships.
+ No brain entities to graph. Add people, projects, ideas, admin items, memories, songs, goals, or journal entries to see relationships.
</div>
);
}
@@ -437,7 +453,7 @@ export default function BrainGraph() {
))}
</div>
- {/* Type filter checkboxes — wrap on mobile (seven of them never fit a
+ {/* Type filter checkboxes — wrap on mobile (eight of them never fit a
phone row) with a taller tap target than the 12px swatch alone. */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 sm:ml-auto">
{BRAIN_TYPES.map(type => {
@@ -688,9 +704,9 @@ export default function BrainGraph() {
<div className="mb-3">
{fullRecord ? (
<div className="space-y-3">
- {(fullRecord.description || fullRecord.context || fullRecord.oneLiner || fullRecord.notes || fullRecord.content) && (
+ {recordBody(fullRecord) && (
<p className="text-sm text-gray-300 whitespace-pre-wrap">
- {fullRecord.description || fullRecord.context || fullRecord.oneLiner || fullRecord.notes || fullRecord.content}
+ {recordBody(fullRecord)}
</p>
)}
{typeof fullRecord.progress === 'number' && (
diff --git a/client/src/components/brain/tabs/BrainGraph.test.jsx b/client/src/components/brain/tabs/BrainGraph.test.jsx
index 94c7cbbf03..809e219f72 100644
--- a/client/src/components/brain/tabs/BrainGraph.test.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.test.jsx
@@ -24,10 +24,11 @@ vi.mock('../../../services/api', () => ({
getBrainMemory: vi.fn(),
getBrainGoal: vi.fn(),
getBrainJournalEntry: vi.fn(),
+ getSong: vi.fn(),
}));
import * as api from '../../../services/api';
-import BrainGraph from './BrainGraph';
+import BrainGraph, { recordBody } from './BrainGraph';
const GRAPH = {
hasEmbeddings: true,
@@ -54,7 +55,7 @@ beforeEach(() => {
// a resolved default and let individual tests override the one they assert.
for (const getter of [
api.getBrainPerson, api.getBrainProject, api.getBrainIdea, api.getBrainAdminItem,
- api.getBrainMemory, api.getBrainGoal, api.getBrainJournalEntry,
+ api.getBrainMemory, api.getBrainGoal, api.getBrainJournalEntry, api.getSong,
]) getter.mockResolvedValue(null);
});
@@ -151,3 +152,23 @@ describe('canvas sizing', () => {
expect(shell.className).toMatch(/h-\[clamp\([^\]]*vh[^\]]*\)\]/);
});
});
+
+describe('recordBody (SongBook nodes, #4105)', () => {
+ it('never returns a non-string field — a song\'s `content` is an object', () => {
+ // Rendering `{ format, text }` into the panel throws "Objects are not valid
+ // as a React child", so the chain must type-check every candidate rather
+ // than `||` its way into the sheet body.
+ const song = { title: 'Example Song', content: { format: 'chordpro', text: '[C]la' } };
+ expect(recordBody(song)).toBe('');
+ expect(recordBody({ ...song, artist: 'Placeholder Band' })).toBe('Placeholder Band');
+ expect(recordBody({ ...song, artist: 'Placeholder Band', notes: 'Bridge needs work' }))
+ .toBe('Placeholder Band');
+ });
+
+ it('still reads a string `content` (memories, journals) and prefers description', () => {
+ expect(recordBody({ content: 'a good day' })).toBe('a good day');
+ expect(recordBody({ description: 'goal blurb', notes: 'aside' })).toBe('goal blurb');
+ expect(recordBody(null)).toBe('');
+ expect(recordBody({})).toBe('');
+ });
+});
diff --git a/server/services/brainGraph.js b/server/services/brainGraph.js
index bc29362184..069b276f7c 100644
--- a/server/services/brainGraph.js
+++ b/server/services/brainGraph.js
@@ -28,7 +28,7 @@ import { loadBridgeMap, bridgeKey } from './brainMemoryBridge.js';
import { getBrainProjections, journalHasBody } from './brainSearchIndex.js';
import { getGoals } from './identity.js';
-const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];
+const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'songs'];
// Edges shown per node are capped so a densely-tagged hub can't reintroduce the
// combinatorial blow-up inside a bounded view.
@@ -60,6 +60,20 @@ const clampLimit = (limit, fallback) => {
// projection-backed search index, so the two can never drift on what a node is
// called or which records are skipped.
const entityLabel = (record) => record.name || record.title || '(untitled)';
+
+// One-line gist for the node tooltip / detail panel. Every candidate is
+// type-checked rather than `||`-chained straight through, because `content` is
+// a STRING on memories/journals but an OBJECT (`{ format, text }`) on a
+// SongBook record — an untyped chain would put `[object Object]` in the
+// tooltip. `artist` sits ahead of `notes` so a song reads as "who plays it"
+// rather than whatever practice note happens to be attached.
+const SUMMARY_FIELDS = ['context', 'oneLiner', 'artist', 'notes', 'content'];
+const entitySummary = (record) => {
+ for (const field of SUMMARY_FIELDS) {
+ if (typeof record[field] === 'string' && record[field]) return record[field];
+ }
+ return '';
+};
const goalLabel = (goal) => goal.title || '(untitled goal)';
const isInactiveGoal = (goal) => goal.status === 'completed' || goal.status === 'abandoned';
const journalDate = (entry) => entry.id || entry.date;
@@ -75,7 +89,7 @@ async function loadNodes() {
id: record.id,
brainType: type,
label: entityLabel(record),
- summary: record.context || record.oneLiner || record.notes || record.content || '',
+ summary: entitySummary(record),
tags: record.tags || [],
importance: 0.6,
status: record.status
diff --git a/server/services/brainGraph.test.js b/server/services/brainGraph.test.js
index eebf40ca8b..f081c24b47 100644
--- a/server/services/brainGraph.test.js
+++ b/server/services/brainGraph.test.js
@@ -128,11 +128,11 @@ describe('getBrainGraphSearchIndex', () => {
onlyType('people', [{ id: 'p1', name: 'A' }]);
await getBrainGraphSearchIndex();
- // 5 entity types + journals, one scan each.
- expect(brainStorage.getAll).toHaveBeenCalledTimes(6);
+ // 6 entity types (incl. songs) + journals, one scan each.
+ expect(brainStorage.getAll).toHaveBeenCalledTimes(7);
await getBrainGraphSearchIndex();
- expect(brainStorage.getAll).toHaveBeenCalledTimes(6);
+ expect(brainStorage.getAll).toHaveBeenCalledTimes(7);
});
it('keeps unrendered payloads and journal bodies out of the projections it reads', async () => {
@@ -186,6 +186,39 @@ describe('getBrainGraphOverview', () => {
expect(result.nodes.map(n => n.label).sort()).toEqual(['Alice', 'Phoenix']);
});
+ it('summarizes a SongBook node with its artist, never its content object (#4105)', async () => {
+ onlyType('songs', [{
+ id: 's1',
+ title: 'Example Song',
+ artist: 'Placeholder Band',
+ tags: ['acoustic'],
+ // The sheet body is an object on a song record, not a string — the
+ // summary chain must never fall through to it.
+ content: { format: 'chordpro', text: '[C]la la la' }
+ }]);
+ const result = await getBrainGraphOverview({ limit: 100 });
+ expect(result.nodes).toHaveLength(1);
+ expect(result.nodes[0]).toMatchObject({
+ id: 's1',
+ brainType: 'songs',
+ label: 'Example Song',
+ summary: 'Placeholder Band',
+ tags: ['acoustic']
+ });
+ });
+
+ it('emits shared_tag edges between a song and another brain record (#4105)', async () => {
+ brainStorage.getAll.mockImplementation(async (type) => {
+ if (type === 'songs') return [{ id: 's1', title: 'Example Song', tags: ['practice', 'guitar'] }];
+ if (type === 'projects') return [{ id: 'pr1', title: 'Learn guitar', tags: ['practice', 'guitar'] }];
+ return [];
+ });
+ const result = await getBrainGraphOverview({ limit: 100 });
+ const tagEdges = result.edges.filter(e => e.type === 'shared_tag');
+ expect(tagEdges).toHaveLength(1);
+ expect([tagEdges[0].source, tagEdges[0].target].sort()).toEqual(['pr1', 's1']);
+ });
+
it('falls back to "(untitled)" when an entity has no name/title', async () => {
onlyType('ideas', [{ id: 'i1', tags: [] }]);
const result = await getBrainGraphOverview({ limit: 100 });
@@ -398,4 +431,10 @@ describe('goals and journal nodes', () => {
expect(ids).not.toContain('2026-01-01');
expect(ids).toContain('2026-01-02');
});
+
+ it('includes SongBook records as graph nodes labelled by title (#4105)', async () => {
+ onlyType('songs', [{ id: 's1', title: 'Example Song', artist: 'Placeholder Band' }]);
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes).toEqual([{ id: 's1', label: 'Example Song', brainType: 'songs' }]);
+ });
});
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
index 7723d5bcc2..33b699ac5a 100644
--- a/server/services/brainMemoryBridge.js
+++ b/server/services/brainMemoryBridge.js
@@ -1,8 +1,8 @@
/**
* 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.
+ * Mirrors brain records (projects, ideas, admin, memories/journal, digests, reviews, people,
+ * songs) 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
@@ -30,9 +30,35 @@ const TYPE_MAP = {
memories: { type: 'observation', category: 'personal' },
digests: { type: 'context', category: 'digest' },
reviews: { type: 'context', category: 'review' },
- journals: { type: 'observation', category: 'daily-log' }
+ journals: { type: 'observation', category: 'daily-log' },
+ songs: { type: 'context', category: 'songbook' }
};
+// Append-only JSONL stores — no per-record events, no deletes, walked with
+// their own getters rather than brainStorage.getAll.
+const JSONL_TYPES = ['digests', 'reviews'];
+
+// Whole-store read for an append-only JSONL type (the `1000` cap is "all of
+// them" — these files are small and cached by brainStorage).
+const readJsonlStore = (type) =>
+ (type === 'digests' ? brainStorage.getDigests : brainStorage.getReviews)(1000);
+
+// The id-keyed entity stores the bridge mirrors. DERIVED from TYPE_MAP (minus
+// the JSONL stores and the Daily Log, both of which have their own walk) so
+// adding a type to the map above automatically enrolls it in the bulk sync, the
+// embedding-coverage tally, the refresh reconcile, and the live event
+// listeners. Those four sites used to restate the list, and a new type wired
+// into TYPE_MAP but missed in one of them would sync but never re-embed (or
+// count, or archive) — silently.
+const BRIDGED_ENTITY_TYPES = Object.keys(TYPE_MAP)
+ .filter((type) => type !== 'journals' && !JSONL_TYPES.includes(type));
+
+// Entity stores plus the Daily Log: everything keyed by a canonical record the
+// bridge can re-read, which is what the coverage tally and the refresh
+// reconcile walk. (JSONL stores are append-only, so they can never orphan a
+// mapped memory entry.)
+const RECONCILABLE_TYPES = [...BRIDGED_ENTITY_TYPES, 'journals'];
+
// ─── Bridge Map ─────────────────────────────────────────────────────────────
// Maps "brainType:brainId" → memoryId so updates hit the same memory entry
@@ -129,6 +155,28 @@ function composeDailyLogContent(r) {
return parts.join('\n');
}
+// SongBook repertoire entry (brain type `songs`). The sheet body
+// (`content.text`, up to 200k chars of tab/ChordPro notation) is deliberately
+// LEFT OUT: it is positional notation, not prose, so it adds no semantic signal
+// to an embedding while blowing the embedder's char budget — one long song
+// would push the record into generateMemoryEmbedding's over-budget LLM
+// summarization branch for nothing. What the user actually searches for is the
+// song's identity and their own notes about it.
+function composeSongContent(r) {
+ const parts = [`Song: ${r.title}`];
+ if (r.artist) parts.push(`Artist: ${r.artist}`);
+ if (r.instrument) parts.push(`Instrument: ${r.instrument}`);
+ if (r.stage) parts.push(`Stage: ${r.stage}`);
+ const setup = [
+ r.key && `Key: ${r.key}`,
+ r.tuning && `Tuning: ${r.tuning}`,
+ r.capo ? `Capo: ${r.capo}` : null
+ ].filter(Boolean);
+ if (setup.length) parts.push(setup.join(' · '));
+ if (r.notes) parts.push(r.notes);
+ return parts.join('\n');
+}
+
export const CONTENT_COMPOSERS = {
people: composePeopleContent,
projects: composeProjectContent,
@@ -137,7 +185,8 @@ export const CONTENT_COMPOSERS = {
memories: composeJournalContent,
digests: composeDigestContent,
reviews: composeReviewContent,
- journals: composeDailyLogContent
+ journals: composeDailyLogContent,
+ songs: composeSongContent
};
// ─── Core Mapping ───────────────────────────────────────────────────────────
@@ -253,8 +302,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMi
const isEmbedded = makeEmbeddedChecker(map, missingMemIds);
// Entity stores (JSON-based)
- const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories'];
- for (const type of entityTypes) {
+ for (const type of BRIDGED_ENTITY_TYPES) {
const records = await brainStorage.getAll(type);
for (const record of records) {
// Skip archived records
@@ -316,10 +364,8 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMi
}
// 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 type of JSONL_TYPES) {
+ const records = await readJsonlStore(type);
for (const record of records) {
const key = bridgeKey(type, record.id);
if (onlyMissing) {
@@ -353,7 +399,7 @@ export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMi
// mirrored stores: digests/reviews are append-only (never deleted) and
// links/buckets/inbox aren't mirrored, so neither can orphan a memory entry.
if (refresh && !dryRun) {
- const reconcilableTypes = new Set(['people', 'projects', 'ideas', 'admin', 'memories', 'journals']);
+ const reconcilableTypes = new Set(RECONCILABLE_TYPES);
for (const mapKey of Object.keys(map)) {
const sep = mapKey.indexOf(':');
if (sep === -1) continue;
@@ -405,14 +451,14 @@ export async function getEmbeddingCoverage() {
// same key syncAllBrainData bridges under. `listLiveIds` already drops
// tombstones and archived records, and it has no page cap (the old
// `listJournals({ limit: 10000 })` silently stopped counting past 10k days).
- for (const type of ['people', 'projects', 'ideas', 'admin', 'memories', 'journals']) {
+ for (const type of RECONCILABLE_TYPES) {
for (const id of await brainStorage.listLiveIds(type)) tally(bridgeKey(type, id));
}
// digests/reviews are append-only JSONL: one whole-file read each, behind
// brainStorage's own cache — not a per-record disk walk, so they stay as-is.
- for (const [type, getter] of [['digests', brainStorage.getDigests], ['reviews', brainStorage.getReviews]]) {
- const records = await getter(1000);
+ for (const type of JSONL_TYPES) {
+ const records = await readJsonlStore(type);
for (const record of records) tally(bridgeKey(type, record.id));
}
@@ -622,7 +668,7 @@ export function initBridge() {
// re-reads each record's CANONICAL state (resyncBrainRecord), so the archived/
// deleted/tombstoned branches are handled there uniformly and an event whose
// payload is already stale by flush time still converges correctly.
- for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {
+ for (const type of BRIDGED_ENTITY_TYPES) {
brainEvents.on(`${type}:upserted`, ({ id }) => queueResync([{ type, id }]));
// A `:deleted` event is a genuine LOCAL user delete (remove() emits it;
// applyRemoteRecord is event-silent), so hard-prune the mapped vector row
@@ -631,8 +677,9 @@ export function initBridge() {
}
// JSONL appends (digests, reviews)
- brainEvents.on('digests:added', (record) => handleJsonlAdded('digests', record));
- brainEvents.on('reviews:added', (record) => handleJsonlAdded('reviews', record));
+ for (const type of JSONL_TYPES) {
+ brainEvents.on(`${type}:added`, (record) => handleJsonlAdded(type, record));
+ }
// Daily log — per-entry events so a single append doesn't re-embed every
// day of the user's history. (An earlier version listened for the
diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.js
index 84e0a538e6..b5d04c8256 100644
--- a/server/services/brainMemoryBridge.test.js
+++ b/server/services/brainMemoryBridge.test.js
@@ -492,7 +492,7 @@ describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recov
});
describe('brainMemoryBridge — getEmbeddingCoverage (issue #3508)', () => {
- const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];
+ const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'songs'];
beforeEach(() => {
listLiveIds.mockImplementation(async () => []);
@@ -545,3 +545,107 @@ describe('brainMemoryBridge — getEmbeddingCoverage (issue #3508)', () => {
expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 1, missing: 0 });
});
});
+
+describe('brainMemoryBridge — SongBook enrollment (issue #4105)', () => {
+ const SONG = Object.freeze({
+ id: 's1',
+ title: 'Example Song',
+ artist: 'Placeholder Band',
+ instrument: 'guitar',
+ stage: 'learning',
+ key: 'G',
+ tuning: 'Drop D',
+ capo: 2,
+ notes: 'Bridge needs work',
+ tags: ['acoustic'],
+ // The sheet body — deliberately NOT embedded (see composeSongContent).
+ content: { format: 'chordpro', text: '[C]la '.repeat(20000) }
+ });
+
+ it('maps a song to a memory payload without its sheet body', async () => {
+ const bridge = await loadBridge();
+
+ const payload = bridge.brainRecordToMemory('songs', SONG);
+
+ expect(payload.category).toBe('songbook');
+ expect(payload.tags).toEqual(expect.arrayContaining(['acoustic', 'brain', 'songs']));
+ expect(payload.content).toContain('Example Song');
+ expect(payload.content).toContain('Placeholder Band');
+ expect(payload.content).toContain('Stage: learning');
+ expect(payload.content).toContain('Key: G');
+ expect(payload.content).toContain('Capo: 2');
+ expect(payload.content).toContain('Bridge needs work');
+ // The 200k-char tab/ChordPro body is notation, not prose: embedding it adds
+ // no semantic signal and would push the record into the embedder's
+ // over-budget LLM-summarization branch.
+ expect(payload.content).not.toContain('[C]la');
+ expect(payload.content.length).toBeLessThan(1000);
+ });
+
+ it('omits the setup line entirely when a song has no key/tuning/capo', async () => {
+ const bridge = await loadBridge();
+
+ const payload = bridge.brainRecordToMemory('songs', {
+ id: 's2', title: 'Bare Song', capo: 0, content: { format: 'tab', text: '' }
+ });
+
+ expect(payload.content).toBe('Song: Bare Song');
+ });
+
+ it('re-embeds a song on :upserted through the debounced queue', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+ getById.mockResolvedValue(SONG);
+
+ brainEvents.emit('songs:upserted', { id: 's1', record: { id: 's1' } });
+ expect(createMemory).not.toHaveBeenCalled(); // queued, not embedded inline
+
+ await bridge.flushPendingResync();
+
+ expect(getById).toHaveBeenCalledWith('songs', 's1');
+ expect(createMemory).toHaveBeenCalledTimes(1);
+ });
+
+ it('hard-prunes the mapped memory when a song is deleted locally', async () => {
+ const bridge = await loadBridge();
+ const { brainEvents } = await import('./brainStorage.js');
+ bridge.initBridge();
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('songs', 's1')]: 'mem-song' });
+ getById.mockResolvedValue(null); // tombstoned
+
+ brainEvents.emit('songs:deleted', { id: 's1' });
+ await bridge.flushPendingResync();
+
+ expect(deleteMemory).toHaveBeenCalledWith('mem-song', true);
+ });
+
+ it('includes songs in the bulk sync and the embedding-coverage tally', async () => {
+ const bridge = await loadBridge();
+ getAll.mockImplementation(async (type) => (type === 'songs' ? [SONG] : []));
+ listLiveIds.mockImplementation(async (type) => (type === 'songs' ? ['s1'] : []));
+
+ // Unmapped in a fresh bridge map → the tally counts it as a backfill
+ // target rather than skipping the store entirely.
+ expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 1, missing: 1 });
+
+ const stats = await bridge.syncAllBrainData();
+ expect(stats.synced).toBe(1);
+ expect(createMemory).toHaveBeenCalledTimes(1);
+
+ // …and the bulk sync clears it.
+ expect(await bridge.getEmbeddingCoverage()).toEqual({ total: 1, missing: 0 });
+ });
+
+ it('archives an orphaned song mapping in the refresh reconcile', async () => {
+ const bridge = await loadBridge();
+ getAll.mockResolvedValue([]);
+ getById.mockResolvedValue(null);
+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('songs', 's-gone')]: 'mem-orphan' });
+
+ const refreshed = await bridge.syncAllBrainData({ refresh: true });
+
+ expect(updateMemory).toHaveBeenCalledWith('mem-orphan', { status: 'archived' });
+ expect(refreshed.archived).toBe(1);
+ });
+});
diff --git a/server/services/brainSearchIndex.js b/server/services/brainSearchIndex.js
index 873460b2a2..dfb27e6e05 100644
--- a/server/services/brainSearchIndex.js
+++ b/server/services/brainSearchIndex.js
@@ -47,10 +47,13 @@ import { safeDate } from '../lib/fileUtils.js';
* from `capturedText` / `name` / `context` / `title` / `oneLiner` / `notes`
* / `nextAction` / `content` / `mood` / `url` / `description`.
* - `getBrainGraphSearchIndex` (server/services/brainGraph.js) derives each
- * node's label from `name || title` and drops archived records, so the five
+ * node's label from `name || title` and drops archived records, so the
* graph entity types also project `name`, `title` and `archived`.
* `journals` is graph-only (the Daily Log is not a unified-search source), and
- * projects no body — see `journalHasBody` below.
+ * projects no body — see `journalHasBody` below. `songs` (SongBook) is
+ * graph-only too, and projects only its label field: the sheet body lives in
+ * `content.text` (up to 200k chars of tab/ChordPro per song) and nothing here
+ * renders it, so it must never reach the cache.
*/
const PROJECTED_FIELDS = Object.freeze({
inbox: Object.freeze(['capturedText']),
@@ -61,6 +64,7 @@ const PROJECTED_FIELDS = Object.freeze({
memories: Object.freeze(['name', 'title', 'content', 'mood', 'archived']),
links: Object.freeze(['title', 'url', 'description']),
journals: Object.freeze(['date']),
+ songs: Object.freeze(['title', 'archived']),
});
/**
diff --git a/server/services/brainSearchIndex.test.js b/server/services/brainSearchIndex.test.js
index 1a7df9b74f..79d3437a33 100644
--- a/server/services/brainSearchIndex.test.js
+++ b/server/services/brainSearchIndex.test.js
@@ -39,10 +39,16 @@ describe('brainSearchIndex', () => {
expect(BRAIN_PROJECTION_TYPES).toContain(type)
}
expect(BRAIN_PROJECTION_TYPES).toContain('journals')
+ // Graph-only types (not unified-search sources) still have to be projected,
+ // or getBrainGraphSearchIndex throws on them.
+ expect(BRAIN_PROJECTION_TYPES).toContain('songs')
+ expect(BRAIN_SEARCH_TYPES).not.toContain('songs')
})
it('rejects a type it does not index', async () => {
- await expect(getBrainProjections('songs')).rejects.toThrow(/unknown projection type/)
+ // `buckets` is a real brain entity store with no projection — the graph and
+ // unified search both ignore it.
+ await expect(getBrainProjections('buckets')).rejects.toThrow(/unknown projection type/)
})
it('projects only the fields its consumers read', async () => {