# Research: update_toc Function Investigation

**Date:** 2026-01-19
**Context:** Issue #1 reports that update_toc overwrites custom hierarchical SUMMARY.md with flat structure
**Project:** /Users/masa/Projects/md-book (Writer-Reader)

---

## Executive Summary

**Finding: The `update_toc` function does not exist in this codebase.**

The md-book project (named "Writer-Reader") is a segment-based book manuscript editor with git integration. It does not contain any TOC (Table of Contents) or SUMMARY.md generation functionality.

---

## Codebase Analysis

### Source Files Examined

| File | Purpose | TOC/SUMMARY Related |
|------|---------|---------------------|
| `/Users/masa/Projects/md-book/src/writer_reader/__init__.py` | Package metadata | No |
| `/Users/masa/Projects/md-book/src/writer_reader/cli.py` | CLI commands (serve, segment, assemble, init) | No |
| `/Users/masa/Projects/md-book/src/writer_reader/project.py` | Project initialization | No |
| `/Users/masa/Projects/md-book/src/writer_reader/segmenter.py` | Chapter segmentation/assembly | No |
| `/Users/masa/Projects/md-book/src/writer_reader/server.py` | Flask API server | No |

### Search Results

- `grep -i "update_toc"` - **No matches found**
- `grep -i "toc"` - **No matches in Python files**
- `grep -i "summary"` - **No matches in source code** (only found in skill documentation files in .claude/)

### CLI Commands Available

```
writer-reader init     # Initialize new manuscript project
writer-reader segment  # Segment chapters into individual files
writer-reader serve    # Start editor server
writer-reader assemble # Assemble segments back into chapters
```

**Note:** No `update-toc` or similar command exists.

---

## Architecture Overview

### Current Functionality

The Writer-Reader project provides:

1. **Chapter Segmentation** (`segmenter.py`)
   - Breaks chapters into segments based on `---` dividers and `##` headers
   - Creates `_meta.yaml` files per chapter
   - Creates `_index.yaml` master index

2. **Project Initialization** (`project.py`)
   - Creates directory structure: chapters/, segments/, research/, outlines/
   - Generates `book.yaml` config
   - Creates README.md and sample chapter

3. **Web Editor** (`server.py`)
   - Flask API for reading/writing segments
   - Git integration (status, diff, commit, push)

4. **Assembly** (`segmenter.py`)
   - Reassembles segments back into chapter files

### File Structure Generated

```
book/
├── chapters/           # Source chapter markdown files
├── segments/           # Segmented chapters
│   ├── ch01-title/
│   │   ├── _meta.yaml
│   │   ├── 01-section.md
│   │   └── ...
│   └── _index.yaml
├── book.yaml           # Project config
└── README.md
```

**Notable:** No SUMMARY.md is generated by this project.

---

## Hypothesis About Issue #1

The Issue #1 reference to `update_toc` overwriting SUMMARY.md suggests one of the following:

### Possibility 1: Feature Request (Most Likely)
Issue #1 may be a **feature request** to add SUMMARY.md generation functionality. The user might be expecting mdBook-compatible output.

### Possibility 2: Confusion with mdBook Tool
The "md-book" project name may have created confusion with **mdBook** (the Rust-based documentation generator), which does use SUMMARY.md for table of contents.

### Possibility 3: Planned/Incomplete Feature
The `update_toc` functionality may have been planned but never implemented.

---

## Recommendations

### If Issue #1 is a Feature Request

To implement `update_toc` with a `preserve_structure` option:

1. **Add new CLI command** in `cli.py`:
```python
@main.command()
@click.argument("book_dir", type=click.Path(exists=True), default=".")
@click.option("--preserve-structure", "-p", is_flag=True,
              help="Preserve existing SUMMARY.md hierarchy")
def update_toc(book_dir: str, preserve_structure: bool):
    """Update SUMMARY.md table of contents."""
    from .toc import update_summary
    # Implementation
```

2. **Create new module** `src/writer_reader/toc.py`:
   - Parse existing SUMMARY.md to extract hierarchy (if preserve_structure=True)
   - Scan chapters/ or segments/ for content
   - Generate SUMMARY.md maintaining hierarchy or creating flat structure

3. **Hierarchy Preservation Logic**:
   - Parse SUMMARY.md markdown to extract indent levels
   - Match existing entries with discovered files
   - Add new files at appropriate level
   - Preserve custom nesting that user created

### Suggested Algorithm for preserve_structure

```python
def update_summary(book_dir: Path, preserve_structure: bool = False):
    summary_path = book_dir / "SUMMARY.md"

    if preserve_structure and summary_path.exists():
        # Parse existing structure
        existing = parse_summary_structure(summary_path)
        # Get current files
        current_files = discover_chapter_files(book_dir)
        # Merge: keep existing hierarchy, add new files
        merged = merge_with_existing(existing, current_files)
        return generate_summary(merged)
    else:
        # Generate flat structure
        files = discover_chapter_files(book_dir)
        return generate_flat_summary(files)
```

### Markdown Parsing Patterns in Codebase

The existing codebase has patterns for parsing markdown structure in `segmenter.py`:

```python
# Line-by-line parsing
if line.startswith("# "):     # Chapter title
if line.startswith("## "):    # Section header
if line.strip() == "---":     # Horizontal rule
```

This pattern can be extended for SUMMARY.md parsing:

```python
def parse_summary_structure(content: str) -> list[dict]:
    """Parse SUMMARY.md preserving hierarchy."""
    entries = []
    for line in content.split("\n"):
        # Match markdown links: - [Title](path.md)
        match = re.match(r"^(\s*)-\s*\[([^\]]+)\]\(([^)]+)\)", line)
        if match:
            indent = len(match.group(1))
            level = indent // 2  # Assuming 2-space indentation
            entries.append({
                "title": match.group(2),
                "path": match.group(3),
                "level": level
            })
    return entries
```

---

## Files to Create/Modify for Implementation

| File | Action | Purpose |
|------|--------|---------|
| `src/writer_reader/toc.py` | **Create** | TOC generation and parsing logic |
| `src/writer_reader/cli.py` | **Modify** | Add `update-toc` command |
| `tests/test_toc.py` | **Create** | Tests for TOC functionality |

---

## Conclusion

The `update_toc` function does not currently exist in the Writer-Reader codebase. Issue #1 is likely a **feature request** to add mdBook-compatible SUMMARY.md generation with the ability to preserve user-defined hierarchical structure.

The codebase has existing patterns for markdown parsing in `segmenter.py` that can be leveraged for implementing this feature.

---

**Research Status:** Complete (Informational)
**Ticket Integration:** No ticket context provided - file-based capture only
**Saved to:** `/Users/masa/Projects/md-book/docs/research/update-toc-research-2026-01-19.md`
