Skip to content

Add mentions relation management and backlink queries #105

Closed

Description

@malibio

Problem Statement

The @mention system creates `nodespace://` links in node content, but the bidirectional relationships are NOT automatically persisted to the `node_mentions` table. This means:

  • ❌ Backlinks don'''t work (can'''t query "what mentions this node?")
  • ❌ Mention relationships are lost when content changes
  • ❌ Removed mentions aren'''t cleaned up from database
  • ❌ Frontend has to manually call `createNodeMention()` (currently not being done)

Scope

This issue implements Phases 1 & 2 ONLY:

  • ✅ Phase 1: Backend Query Exposure (get mentions/backlinks)
  • ✅ Phase 2: Automatic Mention Persistence (auto-sync on save)
  • ❌ Phase 3: Backlinks UI - See separate issue (will be created)
  • ❌ Phase 4: Delete command - Not needed (CASCADE DELETE handles it)

Current State

What EXISTS (Backend Infrastructure - COMPLETE ✅):

  1. Database Table (`node_mentions`):
    ```sql
    CREATE TABLE node_mentions (
    node_id TEXT NOT NULL, -- Source node (contains the @mention)
    mentions_node_id TEXT NOT NULL, -- Target node (being mentioned)
    PRIMARY KEY (node_id, mentions_node_id),
    FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    FOREIGN KEY (mentions_node_id) REFERENCES nodes(id) ON DELETE CASCADE
    );
    CREATE INDEX idx_mentions_source ON node_mentions(node_id);
    CREATE INDEX idx_mentions_target ON node_mentions(mentions_node_id);
    ```

  2. Rust Backend (`packages/core/src/services/node_service.rs`):

    • ✅ `create_mention()` - Insert mention relationship (line 1839)
    • ✅ `delete_mention()` - Remove mention relationship (line 1888)
    • ✅ `get_outgoing_mentions()` - Get nodes THIS node mentions (line 1954)
    • ✅ `get_incoming_mentions()` - Get nodes that mention THIS node (line 2007)
    • ✅ `populate_mentions()` - Populate mentions/mentioned_by arrays (line 1770)
  3. Node Model (`packages/core/src/models/node.rs`):
    ```rust
    pub struct Node {
    // ... other fields
    pub mentions: Vec, // Outgoing: nodes this node mentions
    pub mentioned_by: Vec, // Incoming: nodes that mention this node (BACKLINKS)
    }
    ```

  4. Tauri Commands (`packages/desktop-app/src-tauri/src/commands/nodes.rs`):

    • ✅ `create_node_mention(mentioningNodeId, mentionedNodeId)` (exposed to frontend)
  5. Frontend Adapter (`packages/desktop-app/src/lib/services/backend-adapter.ts:529`):

    • ✅ `createNodeMention(mentioningNodeId, mentionedNodeId)` wrapper

What'''s MISSING (Frontend Integration - THIS ISSUE):

  1. Automatic Mention Persistence: When node content is saved with mentions, automatically create/update mention relationships in database
  2. Mention Extraction: Parse content to detect `nodespace://` links (markdown format) and extract target node IDs
  3. Diff Detection: Compare old mentions vs new mentions to add/remove relationships efficiently
  4. Deletion Handling: Remove mention relationships when links are removed from content
  5. Frontend Query Methods: No methods to get backlinks/mentioned_by from frontend

Mention Format

The actual format used in the codebase (from tests and content-processor):

```markdown

Markdown link format (PRIMARY)

@node Title
@my Node

Plain URI format (ALSO SUPPORTED)

nodespace://node-id
nodespace://node/node-123
```

Examples from codebase:
```typescript
// From textarea-controller.test.ts:
'''@my Node'''

// From content-processor-nodespace.test.ts:
'''Node A'''
'''Node B'''
```

Extraction regex:
```typescript
// Markdown format: @text
const markdownRegex = /\[@[^\]]+\]\(nodespace:\/\/(?:node\/)?([a-f0-9-]{36}(?:\?[^)]*)?)\)/gi;

// Plain format: nodespace://node-id
const plainRegex = /nodespace:\/\/(?:node\/)?([a-f0-9-]{36})/gi;
```

Implementation Tasks

Phase 1: Backend Query Exposure (HIGH PRIORITY)

Add Tauri commands for querying mentions:

Create in `packages/desktop-app/src-tauri/src/commands/nodes.rs`:

```rust
/// Get outgoing mentions (nodes that this node mentions)
#[tauri::command]
pub async fn get_outgoing_mentions(
service: State<'''_, NodeService>,
node_id: String,
) -> Result<Vec, CommandError> {
service
.get_outgoing_mentions(&node_id)
.await
.map_err(CommandError::from)
}

/// Get incoming mentions (nodes that mention this node - BACKLINKS)
#[tauri::command]
pub async fn get_incoming_mentions(
service: State<'''_, NodeService>,
node_id: String,
) -> Result<Vec, CommandError> {
service
.get_incoming_mentions(&node_id)
.await
.map_err(CommandError::from)
}

/// Delete a mention relationship
#[tauri::command]
pub async fn delete_node_mention(
service: State<'''_, NodeService>,
mentioning_node_id: String,
mentioned_node_id: String,
) -> Result<(), CommandError> {
service
.delete_mention(&mentioning_node_id, &mentioned_node_id)
.await
.map_err(CommandError::from)
}
```

Register commands in `packages/desktop-app/src-tauri/src/lib.rs`:
```rust
.invoke_handler(tauri::generate_handler![
// ... existing commands
get_outgoing_mentions,
get_incoming_mentions,
delete_node_mention,
])
```

Add to frontend adapter (`backend-adapter.ts`):

```typescript
async getOutgoingMentions(nodeId: string): Promise<string[]> {
try {
return await invoke<string[]>('''get_outgoing_mentions''', { nodeId });
} catch (error) {
const err = toError(error);
throw new NodeOperationError(err.message, nodeId, '''getOutgoingMentions''');
}
}

async getIncomingMentions(nodeId: string): Promise<string[]> {
try {
return await invoke<string[]>('''get_incoming_mentions''', { nodeId });
} catch (error) {
const err = toError(error);
throw new NodeOperationError(err.message, nodeId, '''getIncomingMentions''');
}
}

async deleteNodeMention(mentioningNodeId: string, mentionedNodeId: string): Promise {
try {
await invoke('''delete_node_mention''', {
mentioningNodeId,
mentionedNodeId
});
} catch (error) {
const err = toError(error);
throw new NodeOperationError(
err.message,
`${mentioningNodeId} -> ${mentionedNodeId}`,
'''deleteNodeMention'''
);
}
}
```

Update BackendAdapter interface:
```typescript
export interface BackendAdapter {
// ... existing methods

/**

  • Get nodes that this node mentions (outgoing mentions)
    */
    getOutgoingMentions(nodeId: string): Promise<string[]>;

/**

  • Get nodes that mention this node (backlinks/incoming mentions)
    */
    getIncomingMentions(nodeId: string): Promise<string[]>;

/**

  • Delete a mention relationship
    */
    deleteNodeMention(mentioningNodeId: string, mentionedNodeId: string): Promise;
    }
    ```

Phase 2: Automatic Mention Persistence (CRITICAL)

Create MentionSyncService (`packages/desktop-app/src/lib/services/mention-sync-service.ts`):

```typescript
import { backendAdapter } from '''./backend-adapter''';

export class MentionSyncService {
/**

  • Extract nodespace:// links from content
  • Supports both markdown format and plain URIs
  • Returns array of unique mentioned node IDs
    */
    extractMentions(content: string): string[] {
    const mentions = new Set();
// Match markdown format: [@text](nodespace://node-id)
const markdownRegex = /\\[@[^\\]]+\\]\\(nodespace:\\/\\/(?:node\\/)?([a-f0-9-]{36})(?:\\?[^)]*)?\\)/gi;
let match;

while ((match = markdownRegex.exec(content)) !== null) {
  mentions.add(match[1]); // Extract node ID
}

// Match plain format: nodespace://node-id
const plainRegex = /(?<!\\()nodespace:\\/\\/(?:node\\/)?([a-f0-9-]{36})/gi;
while ((match = plainRegex.exec(content)) !== null) {
  mentions.add(match[1]);
}

return Array.from(mentions);

}

/**

  • Sync mentions when node content changes
  • Compares old vs new mentions and updates database:
    • Adds new mention relationships
    • Removes deleted mention relationships
  • This is called automatically when node content is saved.
  • @PARAM nodeId - The node whose content changed
  • @PARAM oldContent - Previous content (undefined if new node)
  • @PARAM newContent - New content
    */
    async syncMentions(
    nodeId: string,
    oldContent: string | undefined,
    newContent: string
    ): Promise {
    const oldMentions = new Set(oldContent ? this.extractMentions(oldContent) : []);
    const newMentions = new Set(this.extractMentions(newContent));
// Calculate diff
const toAdd = [...newMentions].filter(id => !oldMentions.has(id));
const toRemove = [...oldMentions].filter(id => !newMentions.has(id));

// Don'\''t create self-references
const validToAdd = toAdd.filter(id => id !== nodeId);
const validToRemove = toRemove.filter(id => id !== nodeId);

// Update database
for (const mentionedId of validToAdd) {
  try {
    await backendAdapter.createNodeMention(nodeId, mentionedId);
  } catch (error) {
    console.warn(\`Failed to create mention: \${nodeId} -> \${mentionedId}\`, error);
  }
}

for (const mentionedId of validToRemove) {
  try {
    await backendAdapter.deleteNodeMention(nodeId, mentionedId);
  } catch (error) {
    console.warn(\`Failed to delete mention: \${nodeId} -> \${mentionedId}\`, error);
  }
}

}
}

export const mentionSyncService = new MentionSyncService();
```

Integrate with SharedNodeStore (`shared-node-store.ts`):

In the `setNode()` method, add mention syncing:

```typescript
import { mentionSyncService } from '''./mention-sync-service''';

class SharedNodeStore {
// ... existing code

setNode(node: Node, source: UpdateSource): void {
const oldNode = this.nodes.get(node.id);

// Store the node
this.nodes.set(node.id, node);
this.notifySubscribers(node.id);

// Sync mentions if content changed (async - don'\''t block)
if (oldNode?.content !== node.content) {
  // Fire and forget - mentions sync in background
  mentionSyncService.syncMentions(
    node.id,
    oldNode?.content,
    node.content
  ).catch(error => {
    console.error('\''Failed to sync mentions for node'\'', node.id, error);
  });
}

}
}
```

Testing Requirements

Unit Tests (`mention-sync-service.test.ts`)

```typescript
import { describe, it, expect, beforeEach, vi } from '''vitest''';
import { MentionSyncService } from '''./mention-sync-service''';
import { backendAdapter } from '''./backend-adapter''';

describe('''MentionSyncService''', () => {
let service: MentionSyncService;

beforeEach(() => {
service = new MentionSyncService();
vi.clearAllMocks();
});

describe('''extractMentions''', () => {
it('''should extract mentions from markdown format''', () => {
const content = '''Check @node A for details''';
const mentions = service.extractMentions(content);

  expect(mentions).toHaveLength(1);
  expect(mentions[0]).toBe('\''123e4567-e89b-12d3-a456-426614174000'\'');
});

it('\''should extract multiple mentions'\'', () => {
  const content = \`
    See [@Node A](nodespace://node-a-id) and
    also [@Node B](nodespace://node-b-id)
  \`;
  const mentions = service.extractMentions(content);
  
  expect(mentions).toHaveLength(2);
  expect(mentions).toContain('\''node-a-id'\'');
  expect(mentions).toContain('\''node-b-id'\'');
});

it('\''should extract plain nodespace:// URIs'\'', () => {
  const content = '\''Check nodespace://987e6543-e21c-34d5-b678-526614174000'\'';
  const mentions = service.extractMentions(content);
  
  expect(mentions).toHaveLength(1);
  expect(mentions[0]).toBe('\''987e6543-e21c-34d5-b678-526614174000'\'');
});

it('\''should handle mixed markdown and plain formats'\'', () => {
  const content = \`
    Markdown: [@Node A](nodespace://node-a-id)
    Plain: nodespace://node-b-id
  \`;
  const mentions = service.extractMentions(content);
  
  expect(mentions).toHaveLength(2);
});

it('\''should deduplicate mentions'\'', () => {
  const content = \`
    [@Node A](nodespace://same-id)
    [@Node A Again](nodespace://same-id)
  \`;
  const mentions = service.extractMentions(content);
  
  expect(mentions).toHaveLength(1);
  expect(mentions[0]).toBe('\''same-id'\'');
});

it('\''should ignore invalid UUIDs'\'', () => {
  const content = '\''[@Bad](nodespace://not-a-uuid)'\'';
  const mentions = service.extractMentions(content);
  
  expect(mentions).toHaveLength(0);
});

});

describe('''syncMentions''', () => {
it('''should add new mentions''', async () => {
const spy = vi.spyOn(backendAdapter, '''createNodeMention''');

  const oldContent = '\''No mentions here'\'';
  const newContent = '\''[@Node A](nodespace://new-mention-id)'\'';
  
  await service.syncMentions('\''source-node'\'', oldContent, newContent);
  
  expect(spy).toHaveBeenCalledWith('\''source-node'\'', '\''new-mention-id'\'');
});

it('\''should remove deleted mentions'\'', async () => {
  const spy = vi.spyOn(backendAdapter, '\''deleteNodeMention'\'');
  
  const oldContent = '\''[@Node A](nodespace://old-mention-id)'\'';
  const newContent = '\''No mentions anymore'\'';
  
  await service.syncMentions('\''source-node'\'', oldContent, newContent);
  
  expect(spy).toHaveBeenCalledWith('\''source-node'\'', '\''old-mention-id'\'');
});

it('\''should handle both additions and removals'\'', async () => {
  const createSpy = vi.spyOn(backendAdapter, '\''createNodeMention'\'');
  const deleteSpy = vi.spyOn(backendAdapter, '\''deleteNodeMention'\'');
  
  const oldContent = '\''[@Old](nodespace://old-id)'\'';
  const newContent = '\''[@New](nodespace://new-id)'\'';
  
  await service.syncMentions('\''source-node'\'', oldContent, newContent);
  
  expect(createSpy).toHaveBeenCalledWith('\''source-node'\'', '\''new-id'\'');
  expect(deleteSpy).toHaveBeenCalledWith('\''source-node'\'', '\''old-id'\'');
});

it('\''should not create self-references'\'', async () => {
  const spy = vi.spyOn(backendAdapter, '\''createNodeMention'\'');
  
  const content = '\''[@Self](nodespace://my-own-id)'\'';
  
  await service.syncMentions('\''my-own-id'\'', undefined, content);
  
  expect(spy).not.toHaveBeenCalled();
});

it('\''should handle empty old content (new node)'\'', async () => {
  const spy = vi.spyOn(backendAdapter, '\''createNodeMention'\'');
  
  const newContent = '\''[@Node A](nodespace://mention-id)'\'';
  
  await service.syncMentions('\''new-node'\'', undefined, newContent);
  
  expect(spy).toHaveBeenCalledWith('\''new-node'\'', '\''mention-id'\'');
});

});
});
```

Integration Tests (`mention-integration.test.ts`)

```typescript
describe('''Mention Integration''', () => {
it('''should persist mentions when node is saved''', async () => {
// Create node with mention
const node = {
id: '''source-node''',
content: '''Check @target''',
// ... other fields
};

sharedNodeStore.setNode(node, { type: '\''viewer'\'', viewerId: '\''test'\'' });

// Wait for async sync
await new Promise(resolve => setTimeout(resolve, 100));

// Verify mention was created in database
const mentions = await backendAdapter.getOutgoingMentions('\''source-node'\'');
expect(mentions).toContain('\''target-node'\'');

});

it('''should query backlinks correctly''', async () => {
// Node A mentions Node B
await backendAdapter.createNodeMention('''node-a''', '''node-b''');

// Query backlinks for Node B
const backlinks = await backendAdapter.getIncomingMentions('\''node-b'\'');

expect(backlinks).toContain('\''node-a'\'');

});
});
```

File Changes Required

New Files:

  • `/packages/desktop-app/src/lib/services/mention-sync-service.ts` - Auto-sync service
  • `/packages/desktop-app/src/tests/services/mention-sync-service.test.ts` - Unit tests
  • `/packages/desktop-app/src/tests/integration/mention-integration.test.ts` - Integration tests

Modified Files:

  • `/packages/desktop-app/src-tauri/src/commands/nodes.rs` - Add query/delete commands
  • `/packages/desktop-app/src-tauri/src/lib.rs` - Register new commands
  • `/packages/desktop-app/src/lib/services/backend-adapter.ts` - Add interface methods and implementations
  • `/packages/desktop-app/src/lib/services/shared-node-store.ts` - Integrate mention syncing

Acceptance Criteria

Phase 1: Backend Query Exposure

  • `get_outgoing_mentions` Tauri command works
  • `get_incoming_mentions` Tauri command works (BACKLINKS)
  • `delete_node_mention` Tauri command works
  • Frontend adapter has all three methods
  • Tests verify queries return correct node IDs

Phase 2: Automatic Mention Persistence

  • MentionSyncService extracts mentions from both markdown and plain formats
  • Mention relationships auto-created when content saved
  • Mention relationships auto-deleted when mentions removed from content
  • Diff detection prevents unnecessary database operations
  • Self-references are prevented
  • Works with all node types (text, task, date)
  • Errors don'''t block node saves (mentions sync in background)

Dependencies

Performance Considerations

From Issue #163:

  • Current `populate_mentions()` has N+1 query pattern (acceptable for now <50 nodes)
  • Future optimization: Implement batch queries when mentions table grows large
  • Target: <50ms for typical queries (<100 mentions per node)

Async Syncing:

  • Mention syncing is fire-and-forget (doesn'''t block UI)
  • Errors are logged but don'''t prevent saves
  • Database operations are batched naturally by content changes

Notes for Implementers

Dependency Verification:

Testing Strategy:

  • Write unit tests FIRST (TDD approach)
  • Use real backend for integration tests (infrastructure exists)
  • Test database at `/Users/malibio/.nodespace/database/nodespace-dev.db`

Current Architecture (Already Built):

  1. ✅ Database table exists with proper indexes
  2. ✅ Rust backend has all CRUD operations
  3. ✅ CASCADE DELETE works (automatic cleanup on node deletion)
  4. ✅ Markdown link format is standard: `@text`

Why This Matters:

  • Users expect bidirectional linking (backlinks are core knowledge management)
  • Without auto-sync, mentions become orphaned when content changes
  • Enables powerful graph queries and navigation features

Priority:

  • Phase 1: HIGH (enables backlink queries - foundation)
  • Phase 2: CRITICAL (makes mentions actually work automatically)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions