Skip to content

Markdown Import/Export for AI Integration #61

Closed

Description

@malibio

Phase 3.1: Markdown Import/Export for AI Integration

Parent Epic: #54
Depends on: #56 (pattern detection)
Early Development: Can start with mocked node conversion APIs
Integrates with: All ContentEditable foundation work

Overview

Implement comprehensive markdown import/export functionality that enables seamless AI integration, allowing users to export NodeSpace content as markdown for AI processing (ChatGPT, Claude) and import AI-generated markdown back into the NodeSpace hierarchy.

Early Development Note

✅ Can start early with mocked node conversion APIs after pattern detection (#56) is available. Focus on markdown parsing/generation while other features develop in parallel.

Context

This feature bridges NodeSpace's sophisticated node hierarchy with AI tools that work with markdown:

Export Flow (NodeSpace → AI)

NodeSpace Hierarchy:
Project Overview
├─ Research Phase  
│  ├─ Market Analysis
│  └─ Competitor Review
└─ Implementation
   └─ **Timeline: 4 weeks**

Exported Markdown:
# Project Overview
- Research Phase
  - Market Analysis  
  - Competitor Review
- Implementation
  - **Timeline: 4 weeks**

Import Flow (AI → NodeSpace)

AI-Generated Markdown:
# Strategic Plan
## Market Research
- Survey customers
- Analyze trends
> Key insight: Mobile-first approach

NodeSpace Result:
Strategic Plan (header node)
├─ Market Research (header node)
│  ├─ Survey customers (child node)
│  ├─ Analyze trends (child node)  
│  └─ Key insight: Mobile-first approach (quote node)

Key Innovation: Perfect AI Workflow Integration

Enable seamless AI collaboration:

  • Export: Convert NodeSpace hierarchy to markdown for AI processing
  • Import: Parse AI-generated markdown into NodeSpace node structure
  • Round-trip: Maintain content fidelity through export→AI→import cycles
  • Smart parsing: Recognize hierarchy patterns and convert to physical nodes

Implementation Approach

Markdown Export Engine

interface MarkdownExporter {
  // Export node tree to markdown
  exportTree(rootNode: Node): string;
  
  // Export selected nodes
  exportSelection(nodeIds: string[]): string;
  
  // Export with formatting preservation
  exportWithFormatting(nodes: Node[], options: ExportOptions): string;
}

interface ExportOptions {
  includeMetadata: boolean;
  preserveHierarchy: boolean; 
  formatHeaders: boolean;
  convertToStandardMarkdown: boolean;
}

Markdown Import Engine

interface MarkdownImporter {
  // Parse markdown to node structure
  importMarkdown(markdown: string): Promise<NodeHierarchy>;
  
  // Import at specific location
  importAtNode(markdown: string, targetNodeId: string): Promise<NodeCreation>;
  
  // Batch import multiple documents
  importBatch(markdownFiles: MarkdownDocument[]): Promise<ImportResults>;
}

interface NodeHierarchy {
  rootNodes: Node[];
  childRelationships: NodeRelationship[];
  formattingMetadata: FormattingData[];
}

Technical Architecture

Export Implementation

Hierarchy Traversal

class HierarchyExporter {
  exportNode(node: Node, depth: number = 0): string {
    const indent = '  '.repeat(depth);
    let markdown = '';
    
    // Convert node content based on type
    switch (node.type) {
      case 'header':
        markdown += `${'#'.repeat(node.headerLevel)} ${node.content}\n`;
        break;
      case 'text':
        if (depth > 0) {
          markdown += `${indent}- ${node.content}\n`;
        } else {
          markdown += `${node.content}\n\n`;
        }
        break;
      case 'quote':
        markdown += `${indent}> ${node.content}\n`;
        break;
    }
    
    // Export children recursively
    for (const child of node.children) {
      markdown += this.exportNode(child, depth + 1);
    }
    
    return markdown;
  }
}

Content Formatting

// Preserve inline markdown formatting during export
function preserveInlineFormatting(content: string): string {
  // NodeSpace formatted content → Standard markdown
  return content
    .replace(/\*\*(.*?)\*\*/g, '**$1**')  // Bold
    .replace(/\*(.*?)\*/g, '*$1*')        // Italic
    .replace(/`(.*?)`/g, '`$1`')          // Code
    .replace(/\[(.*?)\]\((.*?)\)/g, '[$1]($2)'); // Links
}

Import Implementation

Markdown Parsing

class MarkdownParser {
  parseToHierarchy(markdown: string): NodeHierarchy {
    const lines = markdown.split('\n');
    const nodes: Node[] = [];
    const stack: NodeWithLevel[] = [];
    
    for (const line of lines) {
      const node = this.parseLine(line);
      if (\!node) continue;
      
      // Determine hierarchy level
      const level = this.getHierarchyLevel(line);
      
      // Build parent-child relationships
      this.buildHierarchy(node, level, stack);
      nodes.push(node);
    }
    
    return this.constructHierarchy(nodes);
  }
  
  parseLine(line: string): Node | null {
    // Use pattern detection from #56 
    const patterns = [
      { regex: /^(#{1,6})\s+(.+)$/, type: 'header' },
      { regex: /^(\s*)-\s+(.+)$/, type: 'bullet' },  
      { regex: /^(\s*)>\s+(.+)$/, type: 'quote' },
      { regex: /^```(.*)$/, type: 'code' },
    ];
    
    for (const pattern of patterns) {
      const match = line.match(pattern.regex);
      if (match) {
        return this.createNode(pattern.type, match, line);
      }
    }
    
    return this.createTextNode(line);
  }
}

Smart Hierarchy Detection

// Convert markdown indentation to NodeSpace relationships
function detectHierarchyFromIndentation(lines: ParsedLine[]): NodeRelationship[] {
  const relationships: NodeRelationship[] = [];
  const parentStack: Node[] = [];
  
  for (const line of lines) {
    const currentLevel = line.indentLevel;
    
    // Find appropriate parent based on indentation
    while (parentStack.length > currentLevel) {
      parentStack.pop();
    }
    
    if (parentStack.length > 0) {
      relationships.push({
        parentId: parentStack[parentStack.length - 1].id,
        childId: line.node.id
      });
    }
    
    parentStack.push(line.node);
  }
  
  return relationships;
}

User Experience Workflows

AI Collaboration Workflow

Complete AI Integration Flow:

1. User selects NodeSpace content
2. Clicks "Export to Markdown" 
3. Markdown copied to clipboard
4. User pastes into ChatGPT/Claude
5. AI processes and returns enhanced markdown
6. User clicks "Import from Markdown"
7. AI content becomes NodeSpace nodes with proper hierarchy

Result: Seamless AI collaboration without losing NodeSpace structure

Document Migration Workflow

Markdown File Import:

1. User has existing .md files
2. Clicks "Import Markdown File"
3. System parses markdown structure
4. Converts headers → header nodes
5. Converts bullets → child node relationships
6. Converts quotes → quote nodes
7. Preserves all formatting and hierarchy

Result: Legacy markdown documents become NodeSpace node trees

Early Development Strategy

Phase 1: Core Parser (Can start immediately after #56)

Phase 2: Export Engine (Parallel development)

  • Implement node tree → markdown conversion
  • Focus on hierarchy preservation and formatting
  • Test with mocked node structures
  • Ensure round-trip fidelity (export → import preserves structure)

Phase 3: Integration (When other features are ready)

Acceptance Criteria

Export Functionality

  • Export node tree to valid standard markdown
  • Preserve hierarchy using markdown indentation/bullets
  • Maintain inline formatting (bold, italic, code, links)
  • Export selected nodes or entire tree
  • Generate clean, readable markdown for AI tools

Import Functionality

  • Parse standard markdown files into NodeSpace nodes
  • Convert markdown headers to header nodes
  • Convert markdown bullets to child node relationships
  • Convert blockquotes to quote nodes
  • Handle nested structures and complex hierarchies
  • Preserve inline formatting during import

AI Integration

  • Round-trip export→AI→import preserves content structure
  • Compatible with ChatGPT, Claude, and other AI markdown formats
  • Handles AI-generated content variations gracefully
  • Maintains NodeSpace node relationships after AI processing

User Experience

  • Import/export feels fast and reliable
  • Clear feedback during processing
  • Error handling for malformed markdown
  • Undo support for import operations
  • Batch processing for multiple files

Technical Quality

  • Robust parsing handles edge cases
  • Performance is good with large documents
  • Memory efficient for batch operations
  • Cross-browser compatibility maintained
  • Clean integration with NodeSpace APIs

Testing Strategy

Unit Tests

  • Markdown parsing algorithms
  • Node hierarchy construction
  • Export formatting preservation
  • Edge case handling (malformed markdown, empty nodes)

Integration Tests (Initially Mocked)

User Experience Tests

  • Real-world markdown documents
  • AI collaboration workflows
  • Document migration scenarios
  • Performance with large files

AI Integration Tests

  • ChatGPT markdown format compatibility
  • Claude markdown format compatibility
  • Various AI output pattern handling
  • Round-trip content preservation

Coordination Requirements

Early Development Interfaces

// Mock interfaces for parallel development
interface MockNodeConversion {
  createNode(type: NodeType, content: string): Promise<MockNode>;
  createChildRelationship(parentId: string, childId: string): Promise<void>;
  applyFormatting(nodeId: string, formatting: FormattingData): Promise<void>;
}

Pattern Detection Integration

Future Integration Points

Resources & References

AI Tool Compatibility

  • ChatGPT: Standard markdown format expectations
  • Claude: Markdown structure preferences
  • GitHub Copilot: Code block and formatting patterns

Markdown Standards

  • CommonMark: Standard markdown specification
  • GitHub Flavored Markdown: Extended syntax support
  • Mermaid: Diagram syntax integration

NodeSpace Integration

Definition of Done

  • Can export NodeSpace content as clean, standard markdown
  • Can import markdown files and create proper NodeSpace node hierarchies
  • AI collaboration workflow works seamlessly (export→AI→import)
  • Round-trip fidelity is maintained (structure + formatting preserved)
  • Performance is good with real-world document sizes
  • Early development with mocked APIs enables parallel work
  • Ready to integrate with smart conversion features when available
  • Comprehensive test coverage including AI integration scenarios

This markdown import/export capability transforms NodeSpace into a powerful AI collaboration platform while preserving the sophisticated node hierarchy system that makes it unique.

🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]

Activity

  1. added
    enhancement
    on Aug 11, 2025
  2. self-assigned this
    on Aug 12, 2025
  3. malibio commented on Aug 16, 2025

    @malibio
    CollaboratorAuthor

    ✅ COMPLETED - Part of Epic #63 which has been successfully implemented. The ContentEditable foundation with smart markdown features is working correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions