Skip to content

Add get_markdown_from_node_id MCP method for exporting nodes to markdown - #320

Merged
malibio merged 4 commits into
mainfrom
feature/issue-309-add-markdown-export-mcp-method
Oct 21, 2025
Merged

malibio merged 4 commits into
mainfrom
feature/issue-309-add-markdown-export-mcp-method

Conversation

@malibio

@malibio malibio commented Oct 21, 2025

Copy link
Copy Markdown
Collaborator

Closes #309

malibio and others added 4 commits October 21, 2025 12:54
Implements efficient markdown export functionality that allows AI agents to read and understand NodeSpace content in a clean, scannable format.

**Key Features:**
- Bulk query approach: Fetches all container nodes in single DB call
- In-memory hierarchy reconstruction: No N+1 query problem
- Minimal metadata: Only node IDs in HTML comments for AI readability
- Configurable depth limiting (max_depth parameter, default: 20)
- Sibling order preservation: Maintains visual ordering via before_sibling_id chain
- Recursive export: Traverses parent-child relationships

**Implementation:**
- Added GetMarkdownParams struct (node_id, include_children, max_depth)
- Implemented handle_get_markdown_from_node_id handler
- Added export_node_hierarchy for in-memory traversal
- Added sort_by_sibling_chain for maintaining node order
- Registered handler in MCP server.rs
- Added tool schema to initialize.rs capabilities

**Testing:**
- 8 comprehensive test cases covering:
  - Simple export, max depth limiting, children inclusion
  - Round-trip import/export, hierarchy preservation
  - Code blocks, missing nodes, invalid params

Closes #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ts passing)

BREAKING CHANGE: First markdown element now becomes the container node instead
of creating a separate wrapper node with container_title.

## What Was Done

### Core Implementation ✅
- Modified `ParserContext` to start empty and track first node as container
- Updated `create_node()` to set `container_node_id=None` for first node only
- Added `is_first_node()` helper to track when creating the container
- All subsequent nodes have `container_node_id` pointing to first node
- The `container_title` parameter is now effectively ignored (backward compat maintained)

### Test Updates ✅
Updated 14 tests successfully:
- `test_simple_markdown_with_headings` - Node counts reduced by 1
- `test_heading_hierarchy` - Container is now "# H1" not "Hierarchy Test"
- `test_nested_lists` - Node count: 4 (was 5)
- `test_task_list_with_checked_items` - Node count: 3 (was 4)
- `test_code_block_with_language` - Code block IS container, check [0] not [1]
- `test_code_block_without_language` - Same as above
- `test_mixed_content` - Node count: 9 (was 10)
- `test_empty_markdown` - Now expects error (no container can be created)
- `test_content_preservation` - Node count: 3 (was 4)
- `test_deep_heading_hierarchy` - Node count: 7 (was 8)
- `test_get_markdown_simple` - Expects "# Hello World" not "Test"
- `test_get_markdown_max_depth` - Expects "# Root" not "Deep Hierarchy"
- `test_get_markdown_no_children` - Expects "# Root" not "Test"
- Several others with count adjustments

## What Remains (11/25 tests failing)

### Pattern 1: Tests checking container structure
These tests expect `container.content` to be the `container_title` parameter.
They need updating to expect the first markdown element instead.

**Files affected:**
- `test_container_node_structure` (line ~328)
  - Change: `assert_eq!(container.content, "Container Test")`
  - To: `assert_eq!(container.content, "# Test")`

### Pattern 2: Tests accessing node indices
These tests access `node_ids[1]` or later indices. Need to verify if they're:
- Checking the container (change to `[0]`)
- Checking subsequent nodes (keep as `[1]`, `[2]`, etc.)

**Files affected:**
- Line 418 in `test_heading_hierarchy` - Check context
- Line 461 in `test_content_preservation` - Check context
- Line 488 in `test_sibling_ordering` - Check context
- Line 526 in `test_deep_heading_hierarchy` - Check context
- Line 573 in `test_nodes_metadata_in_response` - Check context

### Pattern 3: Export tests expecting container_title
These export tests look for `container_title` content in the markdown output.
They need to expect the first element content instead.

**Files affected:**
- `test_get_markdown_preserves_hierarchy` - Expects "Hierarchy Test", should expect "# Container"
- `test_get_markdown_with_code_blocks` - Expects "Code Test", should expect code block
- `test_roundtrip_import_export` - May need adjustment to content expectations
- `test_inline_code_in_text` - May need count/content adjustments
- `test_task_list_with_checked_items` - May need count adjustments

## How to Complete

### Step 1: Fix container content assertions
```bash
# Find tests checking old container_title
grep -n 'container.content.*Test' packages/core/src/mcp/handlers/markdown_test.rs

# Replace with first element content:
# OLD: assert_eq!(container.content, "Container Test");
# NEW: assert_eq!(container.content, "# Test"); // or whatever the first element is
```

### Step 2: Fix node index access
```bash
# Find remaining node_ids[1] accesses
grep -n 'node_ids\[1\]' packages/core/src/mcp/handlers/markdown_test.rs

# For each occurrence, check if it's:
# - Getting the container? Change to node_ids[0]
# - Getting the second node? Keep as node_ids[1]
```

### Step 3: Run tests iteratively
```bash
# Run tests and fix one at a time
cargo test -p nodespace-core --lib mcp::handlers::markdown::markdown_test::tests::test_container_node_structure -- --nocapture

# After each fix, run all tests to track progress
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1
```

### Step 4: Verify export tests
The export tests may already be mostly fixed. Check that they:
- Don't expect `container_title` content
- Expect the first markdown element as the container
- Have correct node counts (reduced by 1)

### Step 5: Final verification
```bash
# All tests should pass
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1

# Run quality checks
bun run quality:fix

# Update the PR
git add -A
git commit -m "Fix remaining markdown import tests - first element is container"
git push
```

## Architecture Notes for Next Agent

### Key Insight
The original design created a wrapper container node, then parsed markdown as children:
```
Container (title="Test") ← wrapper
  └─ # Heading ← first parsed element
     └─ Text
```

New design makes the first element the container:
```
# Heading (container_node_id=None) ← IS the container
  └─ Text (container_node_id=heading_id)
```

### Why This Matters
1. **Export clarity**: When exporting, you get the actual content, not a wrapper title
2. **Database efficiency**: One less node per import
3. **Semantic correctness**: The document structure matches the markdown structure
4. **container_title deprecated**: Parameter is no longer meaningful but kept for compatibility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Complete the refactoring where the first markdown element becomes the container
node instead of creating a wrapper. All 25 tests now passing.

## Changes Made

### Test Fixes (11 tests)
1. **test_container_node_structure** (line 348)
   - Changed node_type from "text" to "header"
   - Changed content from "Container Test" to "# Test"

2. **test_inline_code_in_text** (line 419)
   - Changed from node_ids[1] to node_ids[0] (text IS container)

3. **test_sibling_ordering** (lines 461-496)
   - Changed all indices from [1,2,3] to [0,1,2]
   - Updated sibling chain references accordingly

4. **test_deep_heading_hierarchy** (lines 526-595)
   - Changed all indices from [1-7] to [0-6]
   - Updated parent_id references to match new indices

5. **test_nodes_metadata_in_response** (line 638)
   - Changed expected count from 4 to 3 nodes
   - Changed first node_type from "text" to "header"

6. **test_task_list_with_checked_items** (line 187-205)
   - Removed skip(1) to include container in iteration
   - Kept unchecked_count at 2 (first + third tasks)

7-11. **Export tests** - All fixed by the export function change below

### Export Function Fix (markdown.rs:586-590)
**Critical bug fix:** Changed top-level node finding logic:
- OLD: `.filter(|n| n.parent_id.is_none())` - looked for orphan nodes
- NEW: `.filter(|n| n.parent_id.as_ref() == Some(&root_node.id))` - finds direct children

**Why this matters:** With first-element-as-container, children have
`parent_id = container_id`, not `None`. The old logic would never find children.

## Test Results
- All 25 tests passing
- Export roundtrip working correctly
- Hierarchy preservation verified

## Related
- Completes refactoring started in commit e251b06
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Implements all recommendations from pragmatic code review, including critical
fixes, important improvements, and optional enhancements.

## Critical Fixes

### 1. Container Node Query Logic (markdown.rs:553-578)
**Problem**: Root node fetched separately but not included in nodes_map
**Fix**: Added root node to nodes_map after bulk query
**Impact**: Ensures complete hierarchy in memory for traversal

### 2. Sibling Chain Sorting Algorithm (markdown.rs:677-750)
**Problem**: Backwards map logic confusing, silent duplicate dropping
**Fix**:
- Build forward map (before_sibling_id -> nodes after it)
- Added duplicate detection with warning logs
- Added cycle detection to prevent infinite loops
**Impact**: Clearer semantics, data integrity checks, safer traversal

### 3. Breaking Change Documentation (mcp-integration.md:721-803)
**Added**: Comprehensive migration guide with:
- Visual comparison of old vs new container model
- Example code migration
- Backward compatibility notes
- Timeline and rationale

## Important Improvements

### 4. Protocol Version Constant (initialize.rs:10)
**Change**: Extracted hardcoded version to MCP_PROTOCOL_VERSION constant
**Impact**: Easier version updates, reduced chance of mismatches

### 5. Max Depth Warning Enhancement (markdown.rs:633-640)
**Change**: Added content preview (first 50 chars) to max depth warning
**Impact**: Better debugging - developers can identify which content causes deep nesting

### 6. Container Model Comment (markdown.rs:591-592)
**Added**: Explanatory comment about first-element-as-container model
**Impact**: Future developers understand the data structure

## Test Updates

### 7. Tool Count Test (initialize_test.rs:87-107)
**Change**: Updated expected tool count from 6 to 7
**Added**: get_markdown_from_node_id to expected tools list
**Impact**: Tests now reflect new export tool

## Technical Details

**Cycle Detection Algorithm**:
- Uses HashSet to track visited nodes during sibling chain traversal
- Logs error and breaks loop if circular reference detected
- Prevents infinite loops without requiring corrupted data tests

**Duplicate Detection**:
- Uses Vec in after_map instead of single value
- Warns when multiple nodes share same before_sibling_id
- Helps identify data corruption issues in production

**Why No Circular Reference Test**:
- Would require manually constructing corrupted data
- NodeService should prevent this at database layer
- Cycle detection provides runtime safety without explicit test

## Verification

- ✅ All 67 MCP tests passing
- ✅ All 25 markdown handler tests passing
- ✅ Quality checks (clippy, rustfmt) passing
- ✅ No lint suppressions required

## Related

- Addresses feedback from pragmatic-code-review agent
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the feature/issue-309-add-markdown-export-mcp-method branch from ef1456c to 1270987 Compare October 21, 2025 11:01
@malibio
malibio merged commit 08cbaef into main Oct 21, 2025
@malibio
malibio deleted the feature/issue-309-add-markdown-export-mcp-method branch October 21, 2025 11:06
malibio added a commit that referenced this pull request Feb 4, 2026
…own (#320)

* Add get_markdown_from_node_id MCP method for exporting nodes to markdown

Implements efficient markdown export functionality that allows AI agents to read and understand NodeSpace content in a clean, scannable format.

**Key Features:**
- Bulk query approach: Fetches all container nodes in single DB call
- In-memory hierarchy reconstruction: No N+1 query problem
- Minimal metadata: Only node IDs in HTML comments for AI readability
- Configurable depth limiting (max_depth parameter, default: 20)
- Sibling order preservation: Maintains visual ordering via before_sibling_id chain
- Recursive export: Traverses parent-child relationships

**Implementation:**
- Added GetMarkdownParams struct (node_id, include_children, max_depth)
- Implemented handle_get_markdown_from_node_id handler
- Added export_node_hierarchy for in-memory traversal
- Added sort_by_sibling_chain for maintaining node order
- Registered handler in MCP server.rs
- Added tool schema to initialize.rs capabilities

**Testing:**
- 8 comprehensive test cases covering:
  - Simple export, max depth limiting, children inclusion
  - Round-trip import/export, hierarchy preservation
  - Code blocks, missing nodes, invalid params

Closes #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Refactor markdown import - first element is container (14/25 tests passing)

BREAKING CHANGE: First markdown element now becomes the container node instead
of creating a separate wrapper node with container_title.

## What Was Done

### Core Implementation ✅
- Modified `ParserContext` to start empty and track first node as container
- Updated `create_node()` to set `container_node_id=None` for first node only
- Added `is_first_node()` helper to track when creating the container
- All subsequent nodes have `container_node_id` pointing to first node
- The `container_title` parameter is now effectively ignored (backward compat maintained)

### Test Updates ✅
Updated 14 tests successfully:
- `test_simple_markdown_with_headings` - Node counts reduced by 1
- `test_heading_hierarchy` - Container is now "# H1" not "Hierarchy Test"
- `test_nested_lists` - Node count: 4 (was 5)
- `test_task_list_with_checked_items` - Node count: 3 (was 4)
- `test_code_block_with_language` - Code block IS container, check [0] not [1]
- `test_code_block_without_language` - Same as above
- `test_mixed_content` - Node count: 9 (was 10)
- `test_empty_markdown` - Now expects error (no container can be created)
- `test_content_preservation` - Node count: 3 (was 4)
- `test_deep_heading_hierarchy` - Node count: 7 (was 8)
- `test_get_markdown_simple` - Expects "# Hello World" not "Test"
- `test_get_markdown_max_depth` - Expects "# Root" not "Deep Hierarchy"
- `test_get_markdown_no_children` - Expects "# Root" not "Test"
- Several others with count adjustments

## What Remains (11/25 tests failing)

### Pattern 1: Tests checking container structure
These tests expect `container.content` to be the `container_title` parameter.
They need updating to expect the first markdown element instead.

**Files affected:**
- `test_container_node_structure` (line ~328)
  - Change: `assert_eq!(container.content, "Container Test")`
  - To: `assert_eq!(container.content, "# Test")`

### Pattern 2: Tests accessing node indices
These tests access `node_ids[1]` or later indices. Need to verify if they're:
- Checking the container (change to `[0]`)
- Checking subsequent nodes (keep as `[1]`, `[2]`, etc.)

**Files affected:**
- Line 418 in `test_heading_hierarchy` - Check context
- Line 461 in `test_content_preservation` - Check context
- Line 488 in `test_sibling_ordering` - Check context
- Line 526 in `test_deep_heading_hierarchy` - Check context
- Line 573 in `test_nodes_metadata_in_response` - Check context

### Pattern 3: Export tests expecting container_title
These export tests look for `container_title` content in the markdown output.
They need to expect the first element content instead.

**Files affected:**
- `test_get_markdown_preserves_hierarchy` - Expects "Hierarchy Test", should expect "# Container"
- `test_get_markdown_with_code_blocks` - Expects "Code Test", should expect code block
- `test_roundtrip_import_export` - May need adjustment to content expectations
- `test_inline_code_in_text` - May need count/content adjustments
- `test_task_list_with_checked_items` - May need count adjustments

## How to Complete

### Step 1: Fix container content assertions
```bash
# Find tests checking old container_title
grep -n 'container.content.*Test' packages/core/src/mcp/handlers/markdown_test.rs

# Replace with first element content:
# OLD: assert_eq!(container.content, "Container Test");
# NEW: assert_eq!(container.content, "# Test"); // or whatever the first element is
```

### Step 2: Fix node index access
```bash
# Find remaining node_ids[1] accesses
grep -n 'node_ids\[1\]' packages/core/src/mcp/handlers/markdown_test.rs

# For each occurrence, check if it's:
# - Getting the container? Change to node_ids[0]
# - Getting the second node? Keep as node_ids[1]
```

### Step 3: Run tests iteratively
```bash
# Run tests and fix one at a time
cargo test -p nodespace-core --lib mcp::handlers::markdown::markdown_test::tests::test_container_node_structure -- --nocapture

# After each fix, run all tests to track progress
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1
```

### Step 4: Verify export tests
The export tests may already be mostly fixed. Check that they:
- Don't expect `container_title` content
- Expect the first markdown element as the container
- Have correct node counts (reduced by 1)

### Step 5: Final verification
```bash
# All tests should pass
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1

# Run quality checks
bun run quality:fix

# Update the PR
git add -A
git commit -m "Fix remaining markdown import tests - first element is container"
git push
```

## Architecture Notes for Next Agent

### Key Insight
The original design created a wrapper container node, then parsed markdown as children:
```
Container (title="Test") ← wrapper
  └─ # Heading ← first parsed element
     └─ Text
```

New design makes the first element the container:
```
# Heading (container_node_id=None) ← IS the container
  └─ Text (container_node_id=heading_id)
```

### Why This Matters
1. **Export clarity**: When exporting, you get the actual content, not a wrapper title
2. **Database efficiency**: One less node per import
3. **Semantic correctness**: The document structure matches the markdown structure
4. **container_title deprecated**: Parameter is no longer meaningful but kept for compatibility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix remaining markdown import tests - first element is container

Complete the refactoring where the first markdown element becomes the container
node instead of creating a wrapper. All 25 tests now passing.

## Changes Made

### Test Fixes (11 tests)
1. **test_container_node_structure** (line 348)
   - Changed node_type from "text" to "header"
   - Changed content from "Container Test" to "# Test"

2. **test_inline_code_in_text** (line 419)
   - Changed from node_ids[1] to node_ids[0] (text IS container)

3. **test_sibling_ordering** (lines 461-496)
   - Changed all indices from [1,2,3] to [0,1,2]
   - Updated sibling chain references accordingly

4. **test_deep_heading_hierarchy** (lines 526-595)
   - Changed all indices from [1-7] to [0-6]
   - Updated parent_id references to match new indices

5. **test_nodes_metadata_in_response** (line 638)
   - Changed expected count from 4 to 3 nodes
   - Changed first node_type from "text" to "header"

6. **test_task_list_with_checked_items** (line 187-205)
   - Removed skip(1) to include container in iteration
   - Kept unchecked_count at 2 (first + third tasks)

7-11. **Export tests** - All fixed by the export function change below

### Export Function Fix (markdown.rs:586-590)
**Critical bug fix:** Changed top-level node finding logic:
- OLD: `.filter(|n| n.parent_id.is_none())` - looked for orphan nodes
- NEW: `.filter(|n| n.parent_id.as_ref() == Some(&root_node.id))` - finds direct children

**Why this matters:** With first-element-as-container, children have
`parent_id = container_id`, not `None`. The old logic would never find children.

## Test Results
- All 25 tests passing
- Export roundtrip working correctly
- Hierarchy preservation verified

## Related
- Completes refactoring started in commit e251b06
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback - improve implementation quality

Implements all recommendations from pragmatic code review, including critical
fixes, important improvements, and optional enhancements.

## Critical Fixes

### 1. Container Node Query Logic (markdown.rs:553-578)
**Problem**: Root node fetched separately but not included in nodes_map
**Fix**: Added root node to nodes_map after bulk query
**Impact**: Ensures complete hierarchy in memory for traversal

### 2. Sibling Chain Sorting Algorithm (markdown.rs:677-750)
**Problem**: Backwards map logic confusing, silent duplicate dropping
**Fix**:
- Build forward map (before_sibling_id -> nodes after it)
- Added duplicate detection with warning logs
- Added cycle detection to prevent infinite loops
**Impact**: Clearer semantics, data integrity checks, safer traversal

### 3. Breaking Change Documentation (mcp-integration.md:721-803)
**Added**: Comprehensive migration guide with:
- Visual comparison of old vs new container model
- Example code migration
- Backward compatibility notes
- Timeline and rationale

## Important Improvements

### 4. Protocol Version Constant (initialize.rs:10)
**Change**: Extracted hardcoded version to MCP_PROTOCOL_VERSION constant
**Impact**: Easier version updates, reduced chance of mismatches

### 5. Max Depth Warning Enhancement (markdown.rs:633-640)
**Change**: Added content preview (first 50 chars) to max depth warning
**Impact**: Better debugging - developers can identify which content causes deep nesting

### 6. Container Model Comment (markdown.rs:591-592)
**Added**: Explanatory comment about first-element-as-container model
**Impact**: Future developers understand the data structure

## Test Updates

### 7. Tool Count Test (initialize_test.rs:87-107)
**Change**: Updated expected tool count from 6 to 7
**Added**: get_markdown_from_node_id to expected tools list
**Impact**: Tests now reflect new export tool

## Technical Details

**Cycle Detection Algorithm**:
- Uses HashSet to track visited nodes during sibling chain traversal
- Logs error and breaks loop if circular reference detected
- Prevents infinite loops without requiring corrupted data tests

**Duplicate Detection**:
- Uses Vec in after_map instead of single value
- Warns when multiple nodes share same before_sibling_id
- Helps identify data corruption issues in production

**Why No Circular Reference Test**:
- Would require manually constructing corrupted data
- NodeService should prevent this at database layer
- Cycle detection provides runtime safety without explicit test

## Verification

- ✅ All 67 MCP tests passing
- ✅ All 25 markdown handler tests passing
- ✅ Quality checks (clippy, rustfmt) passing
- ✅ No lint suppressions required

## Related

- Addresses feedback from pragmatic-code-review agent
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
…own (#320)

* Add get_markdown_from_node_id MCP method for exporting nodes to markdown

Implements efficient markdown export functionality that allows AI agents to read and understand NodeSpace content in a clean, scannable format.

**Key Features:**
- Bulk query approach: Fetches all container nodes in single DB call
- In-memory hierarchy reconstruction: No N+1 query problem
- Minimal metadata: Only node IDs in HTML comments for AI readability
- Configurable depth limiting (max_depth parameter, default: 20)
- Sibling order preservation: Maintains visual ordering via before_sibling_id chain
- Recursive export: Traverses parent-child relationships

**Implementation:**
- Added GetMarkdownParams struct (node_id, include_children, max_depth)
- Implemented handle_get_markdown_from_node_id handler
- Added export_node_hierarchy for in-memory traversal
- Added sort_by_sibling_chain for maintaining node order
- Registered handler in MCP server.rs
- Added tool schema to initialize.rs capabilities

**Testing:**
- 8 comprehensive test cases covering:
  - Simple export, max depth limiting, children inclusion
  - Round-trip import/export, hierarchy preservation
  - Code blocks, missing nodes, invalid params

Closes #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Refactor markdown import - first element is container (14/25 tests passing)

BREAKING CHANGE: First markdown element now becomes the container node instead
of creating a separate wrapper node with container_title.

## What Was Done

### Core Implementation ✅
- Modified `ParserContext` to start empty and track first node as container
- Updated `create_node()` to set `container_node_id=None` for first node only
- Added `is_first_node()` helper to track when creating the container
- All subsequent nodes have `container_node_id` pointing to first node
- The `container_title` parameter is now effectively ignored (backward compat maintained)

### Test Updates ✅
Updated 14 tests successfully:
- `test_simple_markdown_with_headings` - Node counts reduced by 1
- `test_heading_hierarchy` - Container is now "# H1" not "Hierarchy Test"
- `test_nested_lists` - Node count: 4 (was 5)
- `test_task_list_with_checked_items` - Node count: 3 (was 4)
- `test_code_block_with_language` - Code block IS container, check [0] not [1]
- `test_code_block_without_language` - Same as above
- `test_mixed_content` - Node count: 9 (was 10)
- `test_empty_markdown` - Now expects error (no container can be created)
- `test_content_preservation` - Node count: 3 (was 4)
- `test_deep_heading_hierarchy` - Node count: 7 (was 8)
- `test_get_markdown_simple` - Expects "# Hello World" not "Test"
- `test_get_markdown_max_depth` - Expects "# Root" not "Deep Hierarchy"
- `test_get_markdown_no_children` - Expects "# Root" not "Test"
- Several others with count adjustments

## What Remains (11/25 tests failing)

### Pattern 1: Tests checking container structure
These tests expect `container.content` to be the `container_title` parameter.
They need updating to expect the first markdown element instead.

**Files affected:**
- `test_container_node_structure` (line ~328)
  - Change: `assert_eq!(container.content, "Container Test")`
  - To: `assert_eq!(container.content, "# Test")`

### Pattern 2: Tests accessing node indices
These tests access `node_ids[1]` or later indices. Need to verify if they're:
- Checking the container (change to `[0]`)
- Checking subsequent nodes (keep as `[1]`, `[2]`, etc.)

**Files affected:**
- Line 418 in `test_heading_hierarchy` - Check context
- Line 461 in `test_content_preservation` - Check context
- Line 488 in `test_sibling_ordering` - Check context
- Line 526 in `test_deep_heading_hierarchy` - Check context
- Line 573 in `test_nodes_metadata_in_response` - Check context

### Pattern 3: Export tests expecting container_title
These export tests look for `container_title` content in the markdown output.
They need to expect the first element content instead.

**Files affected:**
- `test_get_markdown_preserves_hierarchy` - Expects "Hierarchy Test", should expect "# Container"
- `test_get_markdown_with_code_blocks` - Expects "Code Test", should expect code block
- `test_roundtrip_import_export` - May need adjustment to content expectations
- `test_inline_code_in_text` - May need count/content adjustments
- `test_task_list_with_checked_items` - May need count adjustments

## How to Complete

### Step 1: Fix container content assertions
```bash
# Find tests checking old container_title
grep -n 'container.content.*Test' packages/core/src/mcp/handlers/markdown_test.rs

# Replace with first element content:
# OLD: assert_eq!(container.content, "Container Test");
# NEW: assert_eq!(container.content, "# Test"); // or whatever the first element is
```

### Step 2: Fix node index access
```bash
# Find remaining node_ids[1] accesses
grep -n 'node_ids\[1\]' packages/core/src/mcp/handlers/markdown_test.rs

# For each occurrence, check if it's:
# - Getting the container? Change to node_ids[0]
# - Getting the second node? Keep as node_ids[1]
```

### Step 3: Run tests iteratively
```bash
# Run tests and fix one at a time
cargo test -p nodespace-core --lib mcp::handlers::markdown::markdown_test::tests::test_container_node_structure -- --nocapture

# After each fix, run all tests to track progress
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1
```

### Step 4: Verify export tests
The export tests may already be mostly fixed. Check that they:
- Don't expect `container_title` content
- Expect the first markdown element as the container
- Have correct node counts (reduced by 1)

### Step 5: Final verification
```bash
# All tests should pass
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1

# Run quality checks
bun run quality:fix

# Update the PR
git add -A
git commit -m "Fix remaining markdown import tests - first element is container"
git push
```

## Architecture Notes for Next Agent

### Key Insight
The original design created a wrapper container node, then parsed markdown as children:
```
Container (title="Test") ← wrapper
  └─ # Heading ← first parsed element
     └─ Text
```

New design makes the first element the container:
```
# Heading (container_node_id=None) ← IS the container
  └─ Text (container_node_id=heading_id)
```

### Why This Matters
1. **Export clarity**: When exporting, you get the actual content, not a wrapper title
2. **Database efficiency**: One less node per import
3. **Semantic correctness**: The document structure matches the markdown structure
4. **container_title deprecated**: Parameter is no longer meaningful but kept for compatibility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix remaining markdown import tests - first element is container

Complete the refactoring where the first markdown element becomes the container
node instead of creating a wrapper. All 25 tests now passing.

## Changes Made

### Test Fixes (11 tests)
1. **test_container_node_structure** (line 348)
   - Changed node_type from "text" to "header"
   - Changed content from "Container Test" to "# Test"

2. **test_inline_code_in_text** (line 419)
   - Changed from node_ids[1] to node_ids[0] (text IS container)

3. **test_sibling_ordering** (lines 461-496)
   - Changed all indices from [1,2,3] to [0,1,2]
   - Updated sibling chain references accordingly

4. **test_deep_heading_hierarchy** (lines 526-595)
   - Changed all indices from [1-7] to [0-6]
   - Updated parent_id references to match new indices

5. **test_nodes_metadata_in_response** (line 638)
   - Changed expected count from 4 to 3 nodes
   - Changed first node_type from "text" to "header"

6. **test_task_list_with_checked_items** (line 187-205)
   - Removed skip(1) to include container in iteration
   - Kept unchecked_count at 2 (first + third tasks)

7-11. **Export tests** - All fixed by the export function change below

### Export Function Fix (markdown.rs:586-590)
**Critical bug fix:** Changed top-level node finding logic:
- OLD: `.filter(|n| n.parent_id.is_none())` - looked for orphan nodes
- NEW: `.filter(|n| n.parent_id.as_ref() == Some(&root_node.id))` - finds direct children

**Why this matters:** With first-element-as-container, children have
`parent_id = container_id`, not `None`. The old logic would never find children.

## Test Results
- All 25 tests passing
- Export roundtrip working correctly
- Hierarchy preservation verified

## Related
- Completes refactoring started in commit e251b06
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback - improve implementation quality

Implements all recommendations from pragmatic code review, including critical
fixes, important improvements, and optional enhancements.

## Critical Fixes

### 1. Container Node Query Logic (markdown.rs:553-578)
**Problem**: Root node fetched separately but not included in nodes_map
**Fix**: Added root node to nodes_map after bulk query
**Impact**: Ensures complete hierarchy in memory for traversal

### 2. Sibling Chain Sorting Algorithm (markdown.rs:677-750)
**Problem**: Backwards map logic confusing, silent duplicate dropping
**Fix**:
- Build forward map (before_sibling_id -> nodes after it)
- Added duplicate detection with warning logs
- Added cycle detection to prevent infinite loops
**Impact**: Clearer semantics, data integrity checks, safer traversal

### 3. Breaking Change Documentation (mcp-integration.md:721-803)
**Added**: Comprehensive migration guide with:
- Visual comparison of old vs new container model
- Example code migration
- Backward compatibility notes
- Timeline and rationale

## Important Improvements

### 4. Protocol Version Constant (initialize.rs:10)
**Change**: Extracted hardcoded version to MCP_PROTOCOL_VERSION constant
**Impact**: Easier version updates, reduced chance of mismatches

### 5. Max Depth Warning Enhancement (markdown.rs:633-640)
**Change**: Added content preview (first 50 chars) to max depth warning
**Impact**: Better debugging - developers can identify which content causes deep nesting

### 6. Container Model Comment (markdown.rs:591-592)
**Added**: Explanatory comment about first-element-as-container model
**Impact**: Future developers understand the data structure

## Test Updates

### 7. Tool Count Test (initialize_test.rs:87-107)
**Change**: Updated expected tool count from 6 to 7
**Added**: get_markdown_from_node_id to expected tools list
**Impact**: Tests now reflect new export tool

## Technical Details

**Cycle Detection Algorithm**:
- Uses HashSet to track visited nodes during sibling chain traversal
- Logs error and breaks loop if circular reference detected
- Prevents infinite loops without requiring corrupted data tests

**Duplicate Detection**:
- Uses Vec in after_map instead of single value
- Warns when multiple nodes share same before_sibling_id
- Helps identify data corruption issues in production

**Why No Circular Reference Test**:
- Would require manually constructing corrupted data
- NodeService should prevent this at database layer
- Cycle detection provides runtime safety without explicit test

## Verification

- ✅ All 67 MCP tests passing
- ✅ All 25 markdown handler tests passing
- ✅ Quality checks (clippy, rustfmt) passing
- ✅ No lint suppressions required

## Related

- Addresses feedback from pragmatic-code-review agent
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
…own (#320)

* Add get_markdown_from_node_id MCP method for exporting nodes to markdown

Implements efficient markdown export functionality that allows AI agents to read and understand NodeSpace content in a clean, scannable format.

**Key Features:**
- Bulk query approach: Fetches all container nodes in single DB call
- In-memory hierarchy reconstruction: No N+1 query problem
- Minimal metadata: Only node IDs in HTML comments for AI readability
- Configurable depth limiting (max_depth parameter, default: 20)
- Sibling order preservation: Maintains visual ordering via before_sibling_id chain
- Recursive export: Traverses parent-child relationships

**Implementation:**
- Added GetMarkdownParams struct (node_id, include_children, max_depth)
- Implemented handle_get_markdown_from_node_id handler
- Added export_node_hierarchy for in-memory traversal
- Added sort_by_sibling_chain for maintaining node order
- Registered handler in MCP server.rs
- Added tool schema to initialize.rs capabilities

**Testing:**
- 8 comprehensive test cases covering:
  - Simple export, max depth limiting, children inclusion
  - Round-trip import/export, hierarchy preservation
  - Code blocks, missing nodes, invalid params

Closes #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Refactor markdown import - first element is container (14/25 tests passing)

BREAKING CHANGE: First markdown element now becomes the container node instead
of creating a separate wrapper node with container_title.

## What Was Done

### Core Implementation ✅
- Modified `ParserContext` to start empty and track first node as container
- Updated `create_node()` to set `container_node_id=None` for first node only
- Added `is_first_node()` helper to track when creating the container
- All subsequent nodes have `container_node_id` pointing to first node
- The `container_title` parameter is now effectively ignored (backward compat maintained)

### Test Updates ✅
Updated 14 tests successfully:
- `test_simple_markdown_with_headings` - Node counts reduced by 1
- `test_heading_hierarchy` - Container is now "# H1" not "Hierarchy Test"
- `test_nested_lists` - Node count: 4 (was 5)
- `test_task_list_with_checked_items` - Node count: 3 (was 4)
- `test_code_block_with_language` - Code block IS container, check [0] not [1]
- `test_code_block_without_language` - Same as above
- `test_mixed_content` - Node count: 9 (was 10)
- `test_empty_markdown` - Now expects error (no container can be created)
- `test_content_preservation` - Node count: 3 (was 4)
- `test_deep_heading_hierarchy` - Node count: 7 (was 8)
- `test_get_markdown_simple` - Expects "# Hello World" not "Test"
- `test_get_markdown_max_depth` - Expects "# Root" not "Deep Hierarchy"
- `test_get_markdown_no_children` - Expects "# Root" not "Test"
- Several others with count adjustments

## What Remains (11/25 tests failing)

### Pattern 1: Tests checking container structure
These tests expect `container.content` to be the `container_title` parameter.
They need updating to expect the first markdown element instead.

**Files affected:**
- `test_container_node_structure` (line ~328)
  - Change: `assert_eq!(container.content, "Container Test")`
  - To: `assert_eq!(container.content, "# Test")`

### Pattern 2: Tests accessing node indices
These tests access `node_ids[1]` or later indices. Need to verify if they're:
- Checking the container (change to `[0]`)
- Checking subsequent nodes (keep as `[1]`, `[2]`, etc.)

**Files affected:**
- Line 418 in `test_heading_hierarchy` - Check context
- Line 461 in `test_content_preservation` - Check context
- Line 488 in `test_sibling_ordering` - Check context
- Line 526 in `test_deep_heading_hierarchy` - Check context
- Line 573 in `test_nodes_metadata_in_response` - Check context

### Pattern 3: Export tests expecting container_title
These export tests look for `container_title` content in the markdown output.
They need to expect the first element content instead.

**Files affected:**
- `test_get_markdown_preserves_hierarchy` - Expects "Hierarchy Test", should expect "# Container"
- `test_get_markdown_with_code_blocks` - Expects "Code Test", should expect code block
- `test_roundtrip_import_export` - May need adjustment to content expectations
- `test_inline_code_in_text` - May need count/content adjustments
- `test_task_list_with_checked_items` - May need count adjustments

## How to Complete

### Step 1: Fix container content assertions
```bash
# Find tests checking old container_title
grep -n 'container.content.*Test' packages/core/src/mcp/handlers/markdown_test.rs

# Replace with first element content:
# OLD: assert_eq!(container.content, "Container Test");
# NEW: assert_eq!(container.content, "# Test"); // or whatever the first element is
```

### Step 2: Fix node index access
```bash
# Find remaining node_ids[1] accesses
grep -n 'node_ids\[1\]' packages/core/src/mcp/handlers/markdown_test.rs

# For each occurrence, check if it's:
# - Getting the container? Change to node_ids[0]
# - Getting the second node? Keep as node_ids[1]
```

### Step 3: Run tests iteratively
```bash
# Run tests and fix one at a time
cargo test -p nodespace-core --lib mcp::handlers::markdown::markdown_test::tests::test_container_node_structure -- --nocapture

# After each fix, run all tests to track progress
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1
```

### Step 4: Verify export tests
The export tests may already be mostly fixed. Check that they:
- Don't expect `container_title` content
- Expect the first markdown element as the container
- Have correct node counts (reduced by 1)

### Step 5: Final verification
```bash
# All tests should pass
cargo test -p nodespace-core --lib mcp::handlers::markdown -- --test-threads=1

# Run quality checks
bun run quality:fix

# Update the PR
git add -A
git commit -m "Fix remaining markdown import tests - first element is container"
git push
```

## Architecture Notes for Next Agent

### Key Insight
The original design created a wrapper container node, then parsed markdown as children:
```
Container (title="Test") ← wrapper
  └─ # Heading ← first parsed element
     └─ Text
```

New design makes the first element the container:
```
# Heading (container_node_id=None) ← IS the container
  └─ Text (container_node_id=heading_id)
```

### Why This Matters
1. **Export clarity**: When exporting, you get the actual content, not a wrapper title
2. **Database efficiency**: One less node per import
3. **Semantic correctness**: The document structure matches the markdown structure
4. **container_title deprecated**: Parameter is no longer meaningful but kept for compatibility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix remaining markdown import tests - first element is container

Complete the refactoring where the first markdown element becomes the container
node instead of creating a wrapper. All 25 tests now passing.

## Changes Made

### Test Fixes (11 tests)
1. **test_container_node_structure** (line 348)
   - Changed node_type from "text" to "header"
   - Changed content from "Container Test" to "# Test"

2. **test_inline_code_in_text** (line 419)
   - Changed from node_ids[1] to node_ids[0] (text IS container)

3. **test_sibling_ordering** (lines 461-496)
   - Changed all indices from [1,2,3] to [0,1,2]
   - Updated sibling chain references accordingly

4. **test_deep_heading_hierarchy** (lines 526-595)
   - Changed all indices from [1-7] to [0-6]
   - Updated parent_id references to match new indices

5. **test_nodes_metadata_in_response** (line 638)
   - Changed expected count from 4 to 3 nodes
   - Changed first node_type from "text" to "header"

6. **test_task_list_with_checked_items** (line 187-205)
   - Removed skip(1) to include container in iteration
   - Kept unchecked_count at 2 (first + third tasks)

7-11. **Export tests** - All fixed by the export function change below

### Export Function Fix (markdown.rs:586-590)
**Critical bug fix:** Changed top-level node finding logic:
- OLD: `.filter(|n| n.parent_id.is_none())` - looked for orphan nodes
- NEW: `.filter(|n| n.parent_id.as_ref() == Some(&root_node.id))` - finds direct children

**Why this matters:** With first-element-as-container, children have
`parent_id = container_id`, not `None`. The old logic would never find children.

## Test Results
- All 25 tests passing
- Export roundtrip working correctly
- Hierarchy preservation verified

## Related
- Completes refactoring started in commit e251b06
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback - improve implementation quality

Implements all recommendations from pragmatic code review, including critical
fixes, important improvements, and optional enhancements.

## Critical Fixes

### 1. Container Node Query Logic (markdown.rs:553-578)
**Problem**: Root node fetched separately but not included in nodes_map
**Fix**: Added root node to nodes_map after bulk query
**Impact**: Ensures complete hierarchy in memory for traversal

### 2. Sibling Chain Sorting Algorithm (markdown.rs:677-750)
**Problem**: Backwards map logic confusing, silent duplicate dropping
**Fix**:
- Build forward map (before_sibling_id -> nodes after it)
- Added duplicate detection with warning logs
- Added cycle detection to prevent infinite loops
**Impact**: Clearer semantics, data integrity checks, safer traversal

### 3. Breaking Change Documentation (mcp-integration.md:721-803)
**Added**: Comprehensive migration guide with:
- Visual comparison of old vs new container model
- Example code migration
- Backward compatibility notes
- Timeline and rationale

## Important Improvements

### 4. Protocol Version Constant (initialize.rs:10)
**Change**: Extracted hardcoded version to MCP_PROTOCOL_VERSION constant
**Impact**: Easier version updates, reduced chance of mismatches

### 5. Max Depth Warning Enhancement (markdown.rs:633-640)
**Change**: Added content preview (first 50 chars) to max depth warning
**Impact**: Better debugging - developers can identify which content causes deep nesting

### 6. Container Model Comment (markdown.rs:591-592)
**Added**: Explanatory comment about first-element-as-container model
**Impact**: Future developers understand the data structure

## Test Updates

### 7. Tool Count Test (initialize_test.rs:87-107)
**Change**: Updated expected tool count from 6 to 7
**Added**: get_markdown_from_node_id to expected tools list
**Impact**: Tests now reflect new export tool

## Technical Details

**Cycle Detection Algorithm**:
- Uses HashSet to track visited nodes during sibling chain traversal
- Logs error and breaks loop if circular reference detected
- Prevents infinite loops without requiring corrupted data tests

**Duplicate Detection**:
- Uses Vec in after_map instead of single value
- Warns when multiple nodes share same before_sibling_id
- Helps identify data corruption issues in production

**Why No Circular Reference Test**:
- Would require manually constructing corrupted data
- NodeService should prevent this at database layer
- Cycle detection provides runtime safety without explicit test

## Verification

- ✅ All 67 MCP tests passing
- ✅ All 25 markdown handler tests passing
- ✅ Quality checks (clippy, rustfmt) passing
- ✅ No lint suppressions required

## Related

- Addresses feedback from pragmatic-code-review agent
- Issue #309

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add get_markdown_from_node_id MCP method for exporting nodes to markdown

1 participant