# Claude Code Agent Workflow for Writing Projects

This document provides technical guidance for Claude Code when orchestrating writing projects using the RDF prompt library.

**Key Principle:** CLI for data integrity, LLM for generation. Never ask the LLM to generate bibliographies or search—use CLI commands.

**Prompt Format:** All prompts are in markdown (.md) format for easy human reading and editing.

---

## Workflow Overview (9 Phases)

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                    CLAUDE CODE WRITING WORKFLOW                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  PHASE 1-4: CLI-DRIVEN                                                       │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐            │
│  │  INGEST    │→ │   SCOPE    │→ │  RESEARCH  │→ │    GAP     │            │
│  │ rdf ingest │  │ rdf outline│  │ rdf search │  │ rdf quotes │            │
│  └────────────┘  │ + REFINE   │  │ rdf research│  │ Analysis   │            │
│                  └────────────┘  └────────────┘  └────────────┘            │
│                                                         │                    │
│                                                         ▼                    │
│  PHASE 5-9: PROMPT-DRIVEN                                                    │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐  ┌────────────┐            │
│  │ SYNTHESIS  │→ │  DRAFTING  │→ │  REVISION  │→ │   POLISH   │            │
│  │ research_  │  │ scholarly_ │  │ history_   │  │ micro_     │            │
│  │ synthesis  │  │ narrative  │  │ editor     │  │ enrichment │            │
│  └────────────┘  └────────────┘  └────────────┘  └────────────┘            │
│                                                         │                    │
│                                                         ▼                    │
│  PHASE 9: COMPILATION                                                        │
│  ┌────────────────────────────────────────────────────────────┐            │
│  │ ./rdf biblio (CLI!)  →  book_editor_review  →  Export      │            │
│  └────────────────────────────────────────────────────────────┘            │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

**Critical:** Phase 5 (Synthesis) is MANDATORY. Never draft from raw research files.

---

## Phase Detection

When user initiates a writing task, determine current phase:

| User Says | Phase | Action |
|-----------|-------|--------|
| "Write chapter X" | Drafting | Load drafting prompt |
| "Draft the introduction" | Drafting | Load drafting prompt |
| "Edit this chapter" | Revision | Load revision prompt |
| "Revise the prose" | Revision | Load revision prompt |
| "Polish this" | Polish | Load polish prompt |
| "Final review" | Polish | Load polish prompt |
| "Check consistency across chapters" | Post-processing | Load cohesion_check |

---

## Prompt Selection Algorithm

### Step 1: Identify Phase

```
IF task mentions "write", "draft", "create" → DRAFTING
IF task mentions "edit", "revise", "improve" → REVISION
IF task mentions "polish", "final", "refine" → POLISH
IF task mentions "consistency", "across chapters" → POST-PROCESSING
```

### Step 2: Identify Project Type

```
IF chapters > 1 OR project is book → project_type = "book"
IF single document, 5-30 pages → project_type = "essay"
IF single document, < 5 pages → project_type = "article"
```

### Step 3: Select Prompt by Content Type

| Content Type | Drafting | Revision | Polish |
|--------------|----------|----------|--------|
| Historical | scholarly_narrative | history_editor | micro_enrichment |
| Philosophical/Esoteric | living_thought | general_editor | micro_enrichment |
| Academic Essay | essay_academic | general_editor | micro_enrichment |
| General Nonfiction | scholarly_narrative | general_editor | micro_enrichment |

### Step 4: Load and Customize

```yaml
# Read the prompt file
prompt_file = prompts/{phase}/{prompt_id}.md

# Customize parameters for current chapter
parameters:
  chapter_number: [from outline]
  chapter_title: [from outline]
  chapter_focus: [from outline]
  outline_points: [from outline]
```

---

## Detailed Phase Instructions

### DRAFTING PHASE

**Prerequisites (verify before starting):**
- [ ] Research completed (`rdf research` output exists)
- [ ] Outline approved (`outline.yaml` exists)
- [ ] Quotes extracted (`rdf quotes` for key topics)

**Agent Actions:**
1. Browse `prompts/` directories to select appropriate prompt
2. Load selected prompt from `prompts/drafting/`
3. Read chapter details from `outline.yaml`
4. Customize prompt parameters:
   ```yaml
   chapter_number: [N]
   chapter_title: "[Title from outline]"
   chapter_focus: "[From outline description]"
   outline_points: [From outline subsections]
   key_sources: [From rdf quotes output]
   ```
5. Apply prompt to generate chapter draft
6. Save draft to `projects/books/BOOK_xxx/drafts/chapter_N_draft.md`

**Output Artifact:**
```
projects/books/BOOK_xxx/drafts/chapter_N_draft.md
```

---

### REVISION PHASE

**Prerequisites (verify before starting):**
- [ ] First draft exists for this chapter
- [ ] No structural changes needed (if needed, go back to drafting)

**Agent Actions:**
1. Read draft from `drafts/chapter_N_draft.md`
2. Select revision prompt based on content type
3. Load prompt from `prompts/revision/`
4. Customize parameters:
   ```yaml
   chapter_number: [N]
   chapter_title: "[Title]"
   edit_level: "moderate"  # or based on draft quality
   preserve_footnotes: true  # if applicable
   ```
5. Apply prompt to revise chapter
6. Save to `projects/books/BOOK_xxx/revised/chapter_N_revised.md`

**Output Artifact:**
```
projects/books/BOOK_xxx/revised/chapter_N_revised.md
```

---

### POLISH PHASE

**Prerequisites (verify before starting):**
- [ ] Revision is complete for this chapter
- [ ] No content changes needed

**Agent Actions:**
1. Read revised chapter from `revised/chapter_N_revised.md`
2. Load `micro_enrichment` prompt from `prompts/polish/`
3. Customize parameters:
   ```yaml
   chapter_number: [N]
   domain: "[esoteric|historical|etc]"
   preserve_tone: "[contemplative|analytical|etc]"
   max_changes_per_paragraph: 2
   ```
4. Apply prompt for subtle refinement
5. Save to `projects/books/BOOK_xxx/polished/chapter_N.md`

**Output Artifact:**
```
projects/books/BOOK_xxx/polished/chapter_N.md
```

---

### POST-PROCESSING PHASE (Books Only)

**Prerequisites (verify before starting):**
- [ ] ALL chapters have been polished
- [ ] Ready for final manuscript assembly

**Agent Actions:**
1. Gather all polished chapters
2. Load `cohesion_check` prompt from `prompts/polish/`
3. Configure review parameters:
   ```yaml
   total_chapters: [N]
   terminology_glossary: [key terms from project]
   recurring_themes: [from outline]
   review_depth: "thorough"
   ```
4. Run cohesion check across all chapters
5. Generate issues report
6. Apply fixes to individual chapters
7. Assemble final manuscript

**Output Artifacts:**
```
projects/books/BOOK_xxx/cohesion_report.md
projects/books/BOOK_xxx/final/[assembled manuscript]
```

---

## Project Directory Structure

When working on a book project, maintain this structure:

```
projects/books/BOOK_xxx/
├── outline.yaml              # Project outline
├── research_summary.md       # Research phase output
├── gaps.md                   # Research gaps identified
├── workflow_state.json       # Current workflow state
│
├── drafts/                   # Drafting phase outputs
│   ├── chapter_01_draft.md
│   ├── chapter_02_draft.md
│   └── ...
│
├── revised/                  # Revision phase outputs
│   ├── chapter_01_revised.md
│   ├── chapter_02_revised.md
│   └── ...
│
├── polished/                 # Polish phase outputs
│   ├── chapter_01.md
│   ├── chapter_02.md
│   └── ...
│
├── cohesion_report.md        # Post-processing output
│
└── final/                    # Final assembled manuscript
    └── manuscript.md
```

---

## Prompt Parameter Inheritance

Parameters can be set at multiple levels:

1. **Project Level** (in `outline.yaml`):
   ```yaml
   style_preset: "academic"
   audience: "educated_general"
   citation_style: "chicago"
   ```

2. **Chapter Level** (in outline chapter definition):
   ```yaml
   chapters:
     - number: 1
       title: "Introduction"
       focus: "Establishing the problem"
       style_override: "accessible"  # Override project default
   ```

3. **Prompt Level** (at runtime):
   - Agent customizes based on specific chapter needs
   - Override only when necessary

**Inheritance Order:** Project → Chapter → Runtime

---

## Error Handling

### Draft Quality Issues

If draft quality is too low for revision:
```
→ Return to DRAFTING phase
→ Use outline to regenerate specific sections
→ Do not attempt revision on incomplete content
```

### Structural Problems in Revision

If revision reveals structural issues:
```
→ Flag for user review
→ Document specific issues
→ Wait for approval before structural changes
→ Consider returning to DRAFTING for affected sections
```

### Voice Inconsistency in Polish

If polish phase detects voice inconsistency:
```
→ Note inconsistent sections
→ Apply polish with voice_preservation emphasis
→ Flag significant divergences for user review
```

---

## Checkpoints and User Review

At each phase transition, provide checkpoint summary:

```markdown
## Checkpoint: [Phase] Complete

### Completed
- Chapter X drafted/revised/polished
- [Details of what was done]

### Artifacts Created
- [List of files created/modified]

### Next Steps
- [What comes next in workflow]

### Issues Found
- [Any problems or concerns]

### User Action Needed
- [ ] Review [specific item]
- [ ] Approve to continue to [next phase]
```

---

## Quick Reference: Prompt Files

| Phase | Prompt ID | File Path | Best For |
|-------|-----------|-----------|----------|
| Drafting | scholarly_narrative | `prompts/drafting/scholarly_narrative.md` | Historical, research-based |
| Drafting | living_thought | `prompts/drafting/living_thought.md` | Philosophical, esoteric |
| Drafting | essay_academic | `prompts/drafting/essay_academic.md` | Academic essays |
| Revision | history_editor | `prompts/revision/history_editor.md` | Historical with footnotes |
| Revision | general_editor | `prompts/revision/general_editor.md` | General nonfiction |
| Polish | micro_enrichment | `prompts/polish/micro_enrichment.md` | Final refinement |
| Polish | cohesion_check | `prompts/polish/cohesion_check.md` | Cross-chapter review |

---

## Integration with RDF Commands

### Before Drafting
```bash
# Verify research is complete
./rdf status --project BOOK_xxx

# Get relevant quotes
./rdf quotes "chapter topic" --max 30 --format json

# Check outline
cat projects/books/BOOK_xxx/outline.yaml
```

### After Each Phase
```bash
# Update workflow state
./rdf status --update --project BOOK_xxx --phase [phase_name]
```

### For Validation (Optional)
```bash
# Validate claims against sources
./rdf validate chapter_N.md --format json

# Check queue for issues
./rdf queue list validation
```
