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: typed memory links with their own id, type, note and creator (#10493)

[._.]/ Adam Eivybdbd9b7dbf86
diff --git a/client/src/components/cos/tabs/MemoryGraph.jsx b/client/src/components/cos/tabs/MemoryGraph.jsx
index 0aa093ba49..6efaecc77b 100644
--- a/client/src/components/cos/tabs/MemoryGraph.jsx
+++ b/client/src/components/cos/tabs/MemoryGraph.jsx
@@ -30,7 +30,16 @@ const TYPE_HEX = {
// with no distinct per-page behavior worth pinning, so it stays
// module-private.
const memoryNodeColor = (node) => TYPE_HEX[node.type] || '#6b7280';
-export const memoryEdgeColor = (edge) => (edge.type === 'linked' ? '#3b82f6' : '#6b7280');
+// Typed links (#10493) get their own hue; an untyped/legacy 'related' link stays blue.
+const LINK_TYPE_HEX = {
+ supersedes: '#a855f7',
+ contradicts: '#ef4444',
+ 'derived-from': '#f59e0b',
+ 'applies-to': '#10b981'
+};
+export const memoryEdgeColor = (edge) => (
+ edge.type === 'linked' ? (LINK_TYPE_HEX[edge.linkType] || '#3b82f6') : '#6b7280'
+);
export const memoryEdgeIntensity = (edge, dimmed) =>
dimmed ? 0.06 : (edge.type === 'linked' ? 0.6 * edge.weight : 0.3 * edge.weight);
@@ -77,7 +86,7 @@ export default function MemoryGraph() {
? connectedEdges.map(e => {
const otherId = e.source === selectedNode.id ? e.target : e.source;
const n = graph.idMap.get(otherId);
- return n ? { ...n, edgeType: e.type, weight: e.weight } : null;
+ return n ? { ...n, edgeType: e.type, linkType: e.linkType, weight: e.weight } : null;
}).filter(Boolean)
: [];
@@ -301,7 +310,7 @@ export default function MemoryGraph() {
<span className="inline-block w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: TYPE_HEX[cn.type] }} />
<span className="text-xs text-gray-300 truncate flex-1">{cn.summary}</span>
<span className="text-[10px] text-gray-600 shrink-0">
- {cn.edgeType === 'linked' ? 'linked' : `${formatPercent(cn.weight * 100, { decimals: 0 })}`}
+ {cn.edgeType === 'linked' ? (cn.linkType && cn.linkType !== 'related' ? cn.linkType : 'linked') : `${formatPercent(cn.weight * 100, { decimals: 0 })}`}
</span>
</button>
))}
diff --git a/client/src/components/cos/tabs/MemoryGraph.test.jsx b/client/src/components/cos/tabs/MemoryGraph.test.jsx
index 362f2a416e..9b448f187c 100644
--- a/client/src/components/cos/tabs/MemoryGraph.test.jsx
+++ b/client/src/components/cos/tabs/MemoryGraph.test.jsx
@@ -207,6 +207,12 @@ describe('edge appearance (graph3d extraction)', () => {
expect(memoryEdgeColor({ type: 'similar' })).toBe('#6b7280');
});
+ it('colors typed links by linkType and keeps related blue', () => {
+ expect(memoryEdgeColor({ type: 'linked', linkType: 'related' })).toBe('#3b82f6');
+ expect(memoryEdgeColor({ type: 'linked', linkType: 'contradicts' })).toBe('#ef4444');
+ expect(memoryEdgeColor({ type: 'linked', linkType: 'supersedes' })).not.toBe('#3b82f6');
+ });
+
it('scales both edge kinds by weight, unlike BrainGraph\'s flat linked intensity', () => {
expect(memoryEdgeIntensity({ type: 'linked', weight: 0.5 }, false)).toBeCloseTo(0.3);
expect(memoryEdgeIntensity({ type: 'similar', weight: 0.5 }, false)).toBeCloseTo(0.15);
diff --git a/server/lib/README.md b/server/lib/README.md
index 19949d996b..8d26daa915 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -500,6 +500,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `bm25.js` | BM25 ranking + inverted-index helpers. |
| `vectorMath.js` | Vector math utilities (cosine, etc.). |
+| `memoryLinkTypes.js` | Closed vocabulary for CoS memory links (`MEMORY_LINK_TYPES`: `related` symmetric, `supersedes` / `contradicts` / `derived-from` / `applies-to` directed), `DEFAULT_MEMORY_LINK_TYPE`, `isSymmetricMemoryLinkType`. |
| `memoryQuery.js` | Pure memory-index helpers: meta projection, filter/sort, search/hybrid meta filters, RRF fusion. |
| `memoryStats.js` | macOS-correct memory accounting (handles "Pages free" quirk). |
| `rrfRanking.js` | Pure `reciprocalRankFusion(textResults, vectorResults, options)` — merges two ranked lists via RRF scoring (Cormack 2009). Used by `catalogDB.hybridSearchIngredients`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index b6373f1ec9..24235fd698 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -457,6 +457,7 @@ export * from './xPostMedia.js';
// === Search & indexing ===
export * from './bm25.js';
+export * from './memoryLinkTypes.js';
export * from './memoryQuery.js';
export * from './memoryStats.js';
export * from './rrfRanking.js';
diff --git a/server/lib/memoryLinkTypes.js b/server/lib/memoryLinkTypes.js
new file mode 100644
index 0000000000..7188eb8dd2
--- /dev/null
+++ b/server/lib/memoryLinkTypes.js
@@ -0,0 +1,24 @@
+/**
+ * Closed vocabulary for CoS memory links (`memory_links.link_type`).
+ *
+ * `related` is symmetric (stored as a reverse pair, the pre-typed behavior);
+ * every other type is directed source -> target and stored as one row.
+ */
+
+export const DEFAULT_MEMORY_LINK_TYPE = 'related';
+
+export const MEMORY_LINK_TYPES = Object.freeze([
+ 'related',
+ 'supersedes',
+ 'contradicts',
+ 'derived-from',
+ 'applies-to'
+]);
+
+export const isMemoryLinkType = (value) => MEMORY_LINK_TYPES.includes(value);
+
+/** Only `related` gets a reverse row. */
+export const isSymmetricMemoryLinkType = (type) => type === DEFAULT_MEMORY_LINK_TYPE;
+
+/** Absent (null/undefined) means the legacy default; anything else must be a known type. */
+export const normalizeMemoryLinkType = (value) => (value == null ? DEFAULT_MEMORY_LINK_TYPE : value);
diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.js
index 0cd16f02f0..d34a85de9c 100644
--- a/server/lib/memoryValidation.js
+++ b/server/lib/memoryValidation.js
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { partialWithoutDefaults } from './zodCompat.js';
+import { MEMORY_LINK_TYPES } from './memoryLinkTypes.js';
// Memory ids are directory names in the file-backed store. Keep route input
// constrained to one plain path segment before it reaches any filesystem code.
@@ -186,8 +187,15 @@ export const memoryDecaySchema = z.object({
// Link memories request schema
export const memoryLinkSchema = z.object({
sourceId: z.string().guid(),
- targetId: z.string().guid()
-});
+ targetId: z.string().guid(),
+ // Omitted means the legacy symmetric 'related' link, so older clients keep working.
+ linkType: z.enum(MEMORY_LINK_TYPES).optional(),
+ note: z.string().max(2000).optional(),
+ createdBy: z.string().trim().min(1).max(100).optional()
+}).refine(
+ (v) => v.sourceId !== v.targetId || (v.linkType ?? 'related') === 'related',
+ { message: 'A directed link needs two different memories', path: ['targetId'] }
+);
// Single sync memory item schema (incoming from remote peer)
const syncMemoryItemSchema = z.object({
diff --git a/server/lib/memoryValidation.test.js b/server/lib/memoryValidation.test.js
index 59ca411ff2..984ccb3503 100644
--- a/server/lib/memoryValidation.test.js
+++ b/server/lib/memoryValidation.test.js
@@ -484,6 +484,12 @@ describe('memoryValidation.js', () => {
}).success).toBe(false);
});
+ it('accepts a known link type and rejects an unknown one', () => {
+ const ids = { sourceId: '550e8400-e29b-41d4-a716-446655440000', targetId: '550e8400-e29b-41d4-a716-446655440001' };
+ expect(memoryLinkSchema.safeParse({ ...ids, linkType: 'derived-from', note: 'why' }).success).toBe(true);
+ expect(memoryLinkSchema.safeParse({ ...ids, linkType: 'nope' }).success).toBe(false);
+ });
+
it('should require both fields', () => {
expect(memoryLinkSchema.safeParse({
sourceId: '550e8400-e29b-41d4-a716-446655440000'
diff --git a/server/routes/memory.js b/server/routes/memory.js
index 99a08710ed..8c484972ae 100644
--- a/server/routes/memory.js
+++ b/server/routes/memory.js
@@ -145,8 +145,8 @@ router.post('/consolidate', asyncHandler(async (req, res) => {
// POST /api/memory/link - Link two memories
router.post('/link', asyncHandler(async (req, res) => {
- const { sourceId, targetId } = validateRequest(memoryLinkSchema, req.body);
- const result = await memory.linkMemories(sourceId, targetId);
+ const { sourceId, targetId, linkType, note, createdBy } = validateRequest(memoryLinkSchema, req.body);
+ const result = await memory.linkMemories(sourceId, targetId, { linkType, note, createdBy });
res.json(result);
}));
diff --git a/server/routes/memory.test.js b/server/routes/memory.test.js
index 51b685f909..132cd457eb 100644
--- a/server/routes/memory.test.js
+++ b/server/routes/memory.test.js
@@ -46,7 +46,7 @@ vi.mock('../services/memorySync.js', () => ({
applyRemoteChanges: vi.fn()
}));
-import { ensureBackend, getMemories, getTimeline, archiveMemory, purgeMemory, applyDecay } from '../services/memoryBackend.js';
+import { ensureBackend, getMemories, getTimeline, archiveMemory, purgeMemory, applyDecay, linkMemories } from '../services/memoryBackend.js';
import { checkHealth } from '../lib/db.js';
import * as memorySync from '../services/memorySync.js';
@@ -426,4 +426,38 @@ describe('Memory Routes', () => {
expect(applyDecay).toHaveBeenCalledWith(0.02);
});
});
+
+ describe('POST /api/memory/link', () => {
+ const sourceId = '550e8400-e29b-41d4-a716-446655440000';
+ const targetId = '550e8400-e29b-41d4-a716-446655440001';
+
+ it('passes a typed link and its note through to the backend', async () => {
+ linkMemories.mockResolvedValue({ success: true, sourceId, targetId, linkType: 'supersedes', linkId: 'id-1' });
+
+ const response = await request(app).post('/api/memory/link')
+ .send({ sourceId, targetId, linkType: 'supersedes', note: 'newer decision' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.linkType).toBe('supersedes');
+ expect(linkMemories).toHaveBeenCalledWith(sourceId, targetId, { linkType: 'supersedes', note: 'newer decision', createdBy: undefined });
+ });
+
+ it('keeps an untyped legacy call valid (backend defaults it to related)', async () => {
+ linkMemories.mockResolvedValue({ success: true, sourceId, targetId, linkType: 'related', linkId: 'id-2' });
+
+ const response = await request(app).post('/api/memory/link').send({ sourceId, targetId });
+
+ expect(response.status).toBe(200);
+ expect(linkMemories).toHaveBeenCalledWith(sourceId, targetId, { linkType: undefined, note: undefined, createdBy: undefined });
+ });
+
+ it('rejects an unknown link type and a directed self-link with 400', async () => {
+ const unknown = await request(app).post('/api/memory/link').send({ sourceId, targetId, linkType: 'befriends' });
+ const self = await request(app).post('/api/memory/link').send({ sourceId, targetId: sourceId, linkType: 'supersedes' });
+
+ expect(unknown.status).toBe(400);
+ expect(self.status).toBe(400);
+ expect(linkMemories).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 2b09daa63f..588b0105b1 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -120,13 +120,37 @@ CREATE TABLE IF NOT EXISTS post_attempts (
CREATE INDEX IF NOT EXISTS idx_post_attempts_run ON post_attempts (run_id, position);
CREATE INDEX IF NOT EXISTS idx_post_attempts_skill ON post_attempts (module, drill_type);
--- Memory relationships (bidirectional links)
+-- Memory relationships. Typed (#10493): 'related' is symmetric and stored as a
+-- reverse pair; every other link_type is directed and stored as one row.
CREATE TABLE IF NOT EXISTS memory_links (
source_id UUID REFERENCES memories(id) ON DELETE CASCADE,
target_id UUID REFERENCES memories(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW(),
- PRIMARY KEY (source_id, target_id)
-);
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ link_type VARCHAR(32) NOT NULL DEFAULT 'related',
+ note TEXT,
+ created_by VARCHAR(100),
+ PRIMARY KEY (source_id, target_id, link_type)
+);
+-- Upgrade path for installs whose table predates typed links: existing rows take
+-- the 'related' default (and a fresh id), so nothing is lost.
+ALTER TABLE memory_links ADD COLUMN IF NOT EXISTS id UUID NOT NULL DEFAULT gen_random_uuid();
+ALTER TABLE memory_links ADD COLUMN IF NOT EXISTS link_type VARCHAR(32) NOT NULL DEFAULT 'related';
+ALTER TABLE memory_links ADD COLUMN IF NOT EXISTS note TEXT;
+ALTER TABLE memory_links ADD COLUMN IF NOT EXISTS created_by VARCHAR(100);
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint c
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
+ WHERE c.conrelid = 'memory_links'::regclass AND c.contype = 'p' AND a.attname = 'link_type'
+ ) THEN
+ ALTER TABLE memory_links DROP CONSTRAINT memory_links_pkey;
+ ALTER TABLE memory_links ADD PRIMARY KEY (source_id, target_id, link_type);
+ END IF;
+END$$;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_links_id ON memory_links (id);
+CREATE INDEX IF NOT EXISTS idx_memory_links_target ON memory_links (target_id);
-- Relationship / Tribe graph. People live in Postgres so they can be joined to
-- Brain memories, touchpoint history, and calendar event references.
diff --git a/server/services/memory.js b/server/services/memory.js
index 49cb703a6c..a4e7828b9c 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -13,6 +13,7 @@
import { v4 as uuidv4 } from '../lib/uuid.js';
import { persistentMindMemoryProtection } from '../lib/persistentMindMemory.js';
+import { DEFAULT_MEMORY_LINK_TYPE, isSymmetricMemoryLinkType } from '../lib/memoryLinkTypes.js';
import { cosEvents } from './cosEvents.js';
import { findTopK, findAboveThreshold, clusterBySimilarity } from '../lib/vectorMath.js';
import * as notifications from './notifications.js';
@@ -606,7 +607,16 @@ export async function getRelatedMemories(id, limit = 10) {
for (const relId of memory.relatedMemories) {
const meta = indexMap.get(relId);
if (meta && meta.status === 'active') {
- related.push({ ...meta, relationship: 'linked', similarity: 1.0 });
+ related.push({ ...meta, relationship: 'linked', similarity: 1.0, linkType: DEFAULT_MEMORY_LINK_TYPE, direction: 'outgoing' });
+ }
+ }
+ for (const link of memory.typedLinks || []) {
+ const meta = indexMap.get(link.targetId);
+ if (meta && meta.status === 'active') {
+ related.push({
+ ...meta, relationship: 'linked', similarity: 1.0, linkId: link.id, linkType: link.linkType,
+ direction: 'outgoing', note: link.note, createdBy: link.createdBy
+ });
}
}
@@ -668,9 +678,13 @@ export async function getGraphData() {
const edgeKey = [memory.id, targetId].sort().join('-');
if (!seenEdges.has(edgeKey)) {
seenEdges.add(edgeKey);
- edges.push({ source: memory.id, target: targetId, type: 'linked', weight: 1.0 });
+ edges.push({ source: memory.id, target: targetId, type: 'linked', linkType: DEFAULT_MEMORY_LINK_TYPE, weight: 1.0 });
}
}
+ for (const link of full.typedLinks || []) {
+ if (!memoriesById.has(link.targetId)) continue;
+ edges.push({ source: memory.id, target: link.targetId, type: 'linked', linkType: link.linkType, weight: 1.0 });
+ }
}
// Add similarity edges (top 3 per node, > 0.8 similarity)
@@ -712,13 +726,26 @@ export async function getMemoryIdsMissingEmbedding() {
/**
* Link two memories
*/
-export async function linkMemories(sourceId, targetId) {
+export async function linkMemories(sourceId, targetId, { linkType = DEFAULT_MEMORY_LINK_TYPE, note = null, createdBy = 'user' } = {}) {
return withMemoryLock(async () => {
const source = await loadMemory(sourceId);
const target = await loadMemory(targetId);
if (!source || !target) return { success: false, error: 'Memory not found' };
+ // Directed types live on the source record only (dev/test file backend).
+ if (!isSymmetricMemoryLinkType(linkType)) {
+ source.typedLinks = source.typedLinks || [];
+ let link = source.typedLinks.find(l => l.targetId === targetId && l.linkType === linkType);
+ if (!link) {
+ link = { id: uuidv4(), targetId, linkType, note, createdBy, createdAt: new Date().toISOString() };
+ source.typedLinks.push(link);
+ source.updatedAt = link.createdAt;
+ await saveMemory(source);
+ }
+ return { success: true, sourceId, targetId, linkType, linkId: link.id };
+ }
+
// Add bidirectional links
if (!source.relatedMemories.includes(targetId)) {
source.relatedMemories.push(targetId);
@@ -732,7 +759,7 @@ export async function linkMemories(sourceId, targetId) {
await saveMemory(target);
}
- return { success: true, sourceId, targetId };
+ return { success: true, sourceId, targetId, linkType, linkId: null };
});
}
diff --git a/server/services/memory.test.js b/server/services/memory.test.js
index c39b431585..387faf23d5 100644
--- a/server/services/memory.test.js
+++ b/server/services/memory.test.js
@@ -1463,6 +1463,26 @@ describe('memory service', () => {
expect(memorySaves.length).toBe(2);
});
+ it('stores a directed typed link on the source only', async () => {
+ const source = { id: 'src', relatedMemories: [], updatedAt: '' };
+ const target = { id: 'tgt', relatedMemories: [], updatedAt: '' };
+ let callCount = 0;
+ readJSONFile.mockImplementation((path, def) => {
+ if (path.includes('memory.json')) {
+ callCount++;
+ return Promise.resolve(callCount <= 1 ? { ...source } : { ...target });
+ }
+ return Promise.resolve(def);
+ });
+
+ const result = await linkMemories('src', 'tgt', { linkType: 'contradicts', note: 'n' });
+
+ expect(result).toMatchObject({ success: true, linkType: 'contradicts', linkId: expect.any(String) });
+ const memorySaves = atomicWrite.mock.calls.filter(c => c[0].includes('memory.json'));
+ expect(memorySaves.length).toBe(1);
+ expect(JSON.stringify(memorySaves[0][1])).toContain('"linkType":"contradicts"');
+ });
+
it('should return error when source not found', async () => {
readJSONFile.mockImplementation((path, def) => Promise.resolve(def));
diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.js
index 9f43a724af..1fc0e28f3d 100644
--- a/server/services/memoryBackend.js
+++ b/server/services/memoryBackend.js
@@ -215,9 +215,9 @@ export async function getMemoryIdsMissingEmbedding() {
return b.getMemoryIdsMissingEmbedding();
}
-export async function linkMemories(sourceId, targetId) {
+export async function linkMemories(sourceId, targetId, options) {
const b = await getBackend();
- return b.linkMemories(sourceId, targetId);
+ return b.linkMemories(sourceId, targetId, options);
}
export async function consolidateMemories(threshold, dryRun) {
diff --git a/server/services/memoryDB.db.test.js b/server/services/memoryDB.db.test.js
index 0e742e6f34..656f4b5f7b 100644
--- a/server/services/memoryDB.db.test.js
+++ b/server/services/memoryDB.db.test.js
@@ -264,7 +264,9 @@ describe.skipIf(!runDb)('memoryDB CRUD (#3447)', () => {
memoryDB.createMemory({ type: 'fact', content: 'Bidirectional B.' }),
]);
- expect(await memoryDB.linkMemories(a.id, b.id)).toEqual({ success: true, sourceId: a.id, targetId: b.id });
+ expect(await memoryDB.linkMemories(a.id, b.id)).toEqual({
+ success: true, sourceId: a.id, targetId: b.id, linkType: 'related', linkId: expect.any(String)
+ });
expect((await memoryDB.getMemory(a.id)).relatedMemories).toEqual([b.id]);
expect((await memoryDB.getMemory(b.id)).relatedMemories).toEqual([a.id]);
@@ -272,6 +274,35 @@ describe.skipIf(!runDb)('memoryDB CRUD (#3447)', () => {
expect(missing).toEqual({ success: false, error: 'Memory not found' });
});
+ it('stores a directed typed link as one row, reads it back with its type from both ends, and keeps untyped links symmetric', async () => {
+ const [older, newer] = await Promise.all([
+ memoryDB.createMemory({ type: 'decision', content: 'Typed link older decision.' }),
+ memoryDB.createMemory({ type: 'decision', content: 'Typed link newer decision.' }),
+ ]);
+
+ const typed = await memoryDB.linkMemories(newer.id, older.id, { linkType: 'supersedes', note: 'replaces it', createdBy: 'task-1' });
+ expect(typed).toMatchObject({ success: true, linkType: 'supersedes', linkId: expect.any(String) });
+ // Directed: exactly one row, no reverse.
+ const rows = await query('SELECT source_id, target_id, link_type FROM memory_links WHERE source_id = ANY($1)', [[older.id, newer.id]]);
+ expect(rows.rows).toEqual([{ source_id: newer.id, target_id: older.id, link_type: 'supersedes' }]);
+
+ const fromNewer = (await memoryDB.getRelatedMemories(newer.id)).find((r) => r.id === older.id);
+ expect(fromNewer).toMatchObject({ linkType: 'supersedes', direction: 'outgoing', note: 'replaces it', createdBy: 'task-1', linkId: typed.linkId });
+ const fromOlder = (await memoryDB.getRelatedMemories(older.id)).find((r) => r.id === newer.id);
+ expect(fromOlder).toMatchObject({ linkType: 'supersedes', direction: 'incoming' });
+
+ // The same pair may carry a second, different relationship; the legacy call is still a symmetric pair.
+ await memoryDB.linkMemories(newer.id, older.id);
+ const pair = await query('SELECT source_id, link_type FROM memory_links WHERE source_id = ANY($1) ORDER BY link_type, source_id', [[older.id, newer.id]]);
+ expect(pair.rows.filter((r) => r.link_type === 'related')).toHaveLength(2);
+ expect(pair.rows.filter((r) => r.link_type === 'supersedes')).toHaveLength(1);
+
+ const graph = await memoryDB.getGraphData();
+ const edges = graph.edges.filter((e) => [e.source, e.target].includes(older.id) && [e.source, e.target].includes(newer.id) && e.type === 'linked');
+ expect(edges.map((e) => e.linkType).sort()).toEqual(['related', 'supersedes']);
+ expect(edges.find((e) => e.linkType === 'supersedes')).toMatchObject({ source: newer.id, target: older.id });
+ });
+
it('archives and purges', async () => {
const soft = await memoryDB.createMemory({ type: 'fact', content: 'Soft delete me.' });
await memoryDB.archiveMemory(soft.id);
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index 7a8c5c01cf..44132345bd 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -14,6 +14,7 @@ import { cosEvents } from './cosEvents.js';
import * as notifications from './notifications.js';
import { DEFAULT_MEMORY_CONFIG, generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';
import { getInstanceId } from './instanceIdentity.js';
+import { DEFAULT_MEMORY_LINK_TYPE, isSymmetricMemoryLinkType } from '../lib/memoryLinkTypes.js';
const protectedMindMemoryTags = Object.values(PERSISTENT_MIND_MEMORY_PROTECTION_TAGS);
@@ -741,15 +742,31 @@ export async function getRelatedMemories(id, limit = 10) {
const related = [];
// Get explicitly linked memories
+ // Symmetric links are stored as a reverse pair, so the outgoing row covers
+ // them; a directed link is one row, so also read the ones pointing AT this
+ // memory (direction 'incoming') or "B supersedes A" would be invisible from A.
const links = await query(`
- SELECT m.id, m.type, m.category, m.tags, m.summary, m.importance, m.created_at, m.status, m.source_app_id
+ SELECT m.id, m.type, m.category, m.tags, m.summary, m.importance, m.created_at, m.status, m.source_app_id,
+ ml.id AS link_id, ml.link_type, ml.note, ml.created_by,
+ CASE WHEN ml.source_id = $1 THEN 'outgoing' ELSE 'incoming' END AS direction
FROM memory_links ml
- JOIN memories m ON m.id = ml.target_id
- WHERE ml.source_id = $1 AND m.status = 'active'
+ JOIN memories m ON m.id = CASE WHEN ml.source_id = $1 THEN ml.target_id ELSE ml.source_id END
+ WHERE (ml.source_id = $1 OR (ml.target_id = $1 AND ml.link_type <> 'related'))
+ AND m.status = 'active'
+ ORDER BY ml.created_at
`, [id]);
for (const row of links.rows) {
- related.push({ ...rowToMeta(row), relationship: 'linked', similarity: 1.0 });
+ related.push({
+ ...rowToMeta(row),
+ relationship: 'linked',
+ similarity: 1.0,
+ linkId: row.link_id,
+ linkType: row.link_type,
+ direction: row.direction,
+ note: row.note,
+ createdBy: row.created_by
+ });
}
// Get similar by embedding
@@ -803,18 +820,21 @@ export async function getGraphData() {
}));
// Build edges from explicit links
+ // A symmetric 'related' pair is stored twice; keep one row per pair. Directed
+ // types are one row each and keep their source -> target orientation.
const linksResult = await client.query(`
- SELECT DISTINCT ON (LEAST(source_id, target_id), GREATEST(source_id, target_id))
- source_id AS source, target_id AS target
+ SELECT ml.source_id AS source, ml.target_id AS target, ml.link_type
FROM memory_links ml
JOIN memories ms ON ms.id = ml.source_id AND ms.status = 'active'
JOIN memories mt ON mt.id = ml.target_id AND mt.status = 'active'
+ WHERE ml.link_type <> 'related' OR ml.source_id < ml.target_id
`);
const edges = linksResult.rows.map(r => ({
source: r.source,
target: r.target,
type: 'linked',
+ linkType: r.link_type,
weight: 1.0
}));
@@ -880,7 +900,7 @@ export async function getMemoryIdsMissingEmbedding() {
/**
* Link two memories
*/
-export async function linkMemories(sourceId, targetId) {
+export async function linkMemories(sourceId, targetId, { linkType = DEFAULT_MEMORY_LINK_TYPE, note = null, createdBy = 'user' } = {}) {
// Verify both exist
const check = await query(
'SELECT id FROM memories WHERE id = ANY($1)',
@@ -888,14 +908,21 @@ export async function linkMemories(sourceId, targetId) {
);
if (check.rows.length < 2) return { success: false, error: 'Memory not found' };
- // Insert bidirectional links
+ // Only the symmetric 'related' type gets a reverse row; a directed type is one row.
+ const values = isSymmetricMemoryLinkType(linkType)
+ ? '($1, $2, $3, $4, $5), ($2, $1, $3, $4, $5)'
+ : '($1, $2, $3, $4, $5)';
await query(
- `INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2), ($2, $1)
+ `INSERT INTO memory_links (source_id, target_id, link_type, note, created_by) VALUES ${values}
ON CONFLICT DO NOTHING`,
- [sourceId, targetId]
+ [sourceId, targetId, linkType, note, createdBy]
);
- return { success: true, sourceId, targetId };
+ const stored = await query(
+ 'SELECT id FROM memory_links WHERE source_id = $1 AND target_id = $2 AND link_type = $3',
+ [sourceId, targetId, linkType]
+ );
+ return { success: true, sourceId, targetId, linkType, linkId: stored.rows[0]?.id ?? null };
}
// =============================================================================