# CLI User Guide

Complete command reference for the Research Development Framework.

All commands use the unified `rdf` CLI entrypoint with JSON output support.

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Command Overview](#command-overview)
3. [Core Commands](#core-commands)
4. [Utility Commands](#utility-commands)
5. [Autonomy Levels](#autonomy-levels)
6. [JSON Output](#json-output)
7. [Common Workflows](#common-workflows)
8. [Configuration](#configuration)

---

## Quick Start

### Write an Essay

```bash
./rdf essay "Freemasonry in the 1800's" --pages 20
```

### Write a Book

```bash
./rdf outline "History of Western Esotericism" --chapters 5 --pages 100
./rdf book projects/books/BOOK_xxx/outline.yaml
```

### Search and Research

```bash
./rdf search "consciousness in esoteric thought" --limit 10
./rdf research "How did views on consciousness evolve?" --strict
```

### Get Help

```bash
./rdf --help
./rdf <command> --help
./rdf commands              # List all commands as JSON
```

---

## Command Overview

### Core Commands (12)

| Command | Purpose | Default Autonomy |
|---------|---------|------------------|
| `rdf ingest` | Add documents to library | N/A |
| `rdf search` | Search the library | N/A |
| `rdf fetch` | Retrieve bounded chunk text | N/A |
| `rdf research` | Autonomous research | N/A |
| `rdf quotes` | Extract evidence | N/A |
| `rdf outline` | Generate book outline | N/A |
| `rdf book` | Book compilation workflow | supervised |
| `rdf essay` | Essay generation | full |
| `rdf write` | Universal entry point | varies |
| `rdf validate` | Claim verification | N/A |
| `rdf polish` | Style refinement | N/A |
| `rdf queue` | Review queue management | N/A |
| `rdf status` | Workflow state | N/A |

### Utility Commands (5)

| Command | Purpose |
|---------|---------|
| `rdf health` | Library health scan |
| `rdf edit-meta` | Metadata corrections |
| `rdf assess` | Mechanical document assessment |
| `rdf graph` | Knowledge graph queries |
| `rdf diff` | File comparison |

---

## Core Commands

### rdf ingest

Add documents to the library.

```bash
./rdf ingest <path> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--ocr-profile <name>` | OCR profile for poor scans (standard, academic) |
| `--force` | Re-process existing documents |
| `--format json` | JSON output |

**Examples:**
```bash
# Ingest all PDFs from directory
./rdf ingest NEW_DOCS/

# Ingest with OCR for scanned documents
./rdf ingest old_scan.pdf --ocr-profile standard

# Re-process existing document
./rdf ingest document.pdf --force
```

---

### rdf search

Search the library using keyword, semantic, or hybrid search.

```bash
./rdf search "<query>" [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--mode <mode>` | Search mode: keyword, semantic, hybrid (default: hybrid) |
| `--limit <n>` | Maximum results (default: 10) |
| `--summary` | Token-efficient output (titles only) |
| `--format json` | JSON output |

**Examples:**
```bash
# Basic search
./rdf search "consciousness in Steiner's work"

# Semantic search with limit
./rdf search "evolution of thought" --mode semantic --limit 20

# Summary for quick overview
./rdf search "alchemy" --summary --format json
```

---

### rdf fetch

Retrieve bounded chunk text by ID.

```bash
./rdf fetch <chunk_id> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--max-chars <n>` | Maximum characters to return |
| `--from-search` | Treat ID as search result ID |
| `--format json` | JSON output |

**Examples:**
```bash
# Fetch full chunk
./rdf fetch chunk_023_045

# Fetch with character limit
./rdf fetch chunk_023_045 --max-chars 2000

# Fetch from search result
./rdf fetch result_001 --from-search
```

---

### rdf research

Autonomous iterative research on a topic.

```bash
./rdf research "<question>" [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--strict` | Library only, no web search (default) |
| `--allow-web` | Enable web search for gaps |
| `--max-iterations <n>` | Limit search rounds |
| `--budget <n.nn>` | API cost limit in USD |
| `-o <file>` | Output file |
| `--format json` | JSON output |

**Examples:**
```bash
# Research with library only
./rdf research "How did Steiner's views evolve?" --strict

# Research with web fallback
./rdf research "Recent developments in consciousness studies" --allow-web

# Research with budget limit
./rdf research "Complex topic" --max-iterations 5 --budget 1.00
```

---

### rdf quotes

Extract verbatim evidence on a topic.

```bash
./rdf quotes "<topic>" [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--max <n>` | Maximum quotes |
| `--min-length <n>` | Minimum quote length |
| `--format json` | JSON output |

**Examples:**
```bash
# Extract quotes
./rdf quotes "consciousness" --max 30

# JSON output for processing
./rdf quotes "alchemy symbols" --format json
```

**Output:** Creates `quote_bank.json` with citations.

---

### rdf outline

Generate a book outline from a topic description.

```bash
./rdf outline "<topic>" --chapters <n> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--chapters <n>` | Number of chapters (required) |
| `--pages <n>` | Target page count |
| `--style <name>` | Style: academic, accessible, narrative, popular |
| `--preview` | Preview without saving |
| `--format json` | JSON output |

**Examples:**
```bash
# Generate outline
./rdf outline "History of Western Esotericism" --chapters 5 --pages 100

# Preview before saving
./rdf outline "Alchemy in the Renaissance" --chapters 3 --preview

# Academic style
./rdf outline "Philosophical Hermeticism" --chapters 4 --style academic
```

**Output:** Creates `projects/books/BOOK_xxx/outline.yaml`

---

### rdf book

Run the book compilation workflow.

```bash
./rdf book <outline.yaml> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--autonomy <level>` | full, supervised, interactive (default: supervised) |
| `--phases <range>` | Run specific phases (e.g., 1-4, 5) |
| `--resume <id>` | Resume from checkpoint |
| `--plan` | Show execution plan without running |
| `--strict` | Library only |
| `--delegate-drafting` | Use internal LLM to generate drafts (default: return briefs for Claude Code) |
| `--evidence-first` | Quote-binning workflow to prevent hallucination |
| `--writing-preset <name>` | Style: academic, accessible, narrative, concise, popular, technical, journalistic, literary, textbook, conversational |
| `--polish-drafts` | Apply polishing pass after draft generation |
| `--format json` | JSON output |

**Opt-in Generation Model:**

By default, Phase 5 returns chapter briefs for Claude Code to write:
```bash
# DEFAULT: Returns briefs for Claude Code to write
./rdf book outline.yaml --phases 5

# OPT-IN: CLI generates drafts using internal LLM
./rdf book outline.yaml --phases 5 --delegate-drafting
```

**Examples:**
```bash
# Full book workflow (supervised)
./rdf book projects/books/BOOK_xxx/outline.yaml

# Full autonomy - no pauses
./rdf book outline.yaml --autonomy full

# Run specific phases
./rdf book outline.yaml --phases 1-4

# Resume after review
./rdf book --resume BOOK_xxx --phases 5

# Delegate drafting to CLI's internal LLM
./rdf book outline.yaml --delegate-drafting --writing-preset narrative
```

---

### rdf essay

Single-command essay generation.

```bash
./rdf essay "<topic>" [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--pages <n>` | Target page count (default: 10) |
| `--style <name>` | Style: academic, accessible, narrative, popular |
| `--evidence-first` | Require evidence before claims |
| `--strict` | Library only |
| `--delegate-drafting` | Use internal LLM to generate draft (default: return brief for Claude Code) |
| `--format json` | JSON output |

**Opt-in Generation Model:**

By default, returns an essay brief for Claude Code to write:
```bash
# DEFAULT: Returns brief with research for Claude Code to write
./rdf essay "Topic" --pages 20

# OPT-IN: CLI generates draft using internal LLM
./rdf essay "Topic" --pages 20 --delegate-drafting
```

**Examples:**
```bash
# Get essay brief for Claude Code to write (DEFAULT)
./rdf essay "Freemasonry in the 1800s" --pages 20

# Delegate drafting to CLI's internal LLM
./rdf essay "Hermetic Philosophy" --pages 15 --style academic --delegate-drafting

# Academic essay with evidence-first
./rdf essay "Complex Topic" --pages 25 --style academic --evidence-first
```

**Output:** Creates `essays/ESSAY_xxx/essay_brief.json` (default) or `essays/ESSAY_xxx/essay.md` (with --delegate-drafting)

---

### rdf write

Universal entry point - infers essay vs book from parameters.

```bash
./rdf write "<topic>" [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--pages <n>` | Target page count |
| `--chapters <n>` | Number of chapters (triggers book mode) |
| `--type <type>` | Explicit type: essay, book |
| `--style <name>` | Writing style |
| `--autonomy <level>` | Autonomy level |
| `--format json` | JSON output |

**Examples:**
```bash
# Essay (no chapters specified)
./rdf write "Consciousness in Western Thought" --pages 20

# Book (chapters specified)
./rdf write "History of Alchemy" --chapters 5 --pages 100

# Explicit type
./rdf write "Short Topic" --type essay --pages 10
```

---

### rdf validate

Verify claims in a draft against library sources.

```bash
./rdf validate <file> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--top-k <n>` | Sources per claim |
| `--format json` | JSON output |

**Examples:**
```bash
# Validate chapter
./rdf validate chapter_01.md

# JSON output for processing
./rdf validate chapter_01.md --format json
```

**Output:** Creates queue items for issues, produces `validation_report.json`

---

### rdf polish

Apply style refinement to a draft.

```bash
./rdf polish <file> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--preset <name>` | Style: academic, accessible, narrative, concise, popular, technical, journalistic, literary, textbook, conversational |
| `--style <text>` | Custom style description (free text) |
| `--reference-style <file>` | Mimic voice from sample |
| `--use-internal-model` | Use internal LLM to rewrite (default: return suggestions for Claude Code) |
| `--validate` | Run validation after polishing |
| `--format json` | JSON output |

**Opt-in Generation Model:**

By default, returns editing suggestions for Claude Code to apply:
```bash
# DEFAULT: Returns suggestions for Claude Code to apply
./rdf polish chapter_01.md --preset academic

# OPT-IN: CLI rewrites using internal LLM
./rdf polish chapter_01.md --preset academic --use-internal-model
```

**Examples:**
```bash
# Get suggestions for Claude Code to apply (DEFAULT)
./rdf polish chapter_01.md --preset academic

# Delegate polishing to CLI's internal LLM
./rdf polish chapter_01.md --preset accessible --use-internal-model

# Polish with reference voice (delegated)
./rdf polish essay.md --reference-style sample_voice.txt --use-internal-model
```

**Validation Dependency:**

By default, `rdf polish` requires `rdf validate` to be run first on the same file. This is defined in `tools.json` under `workflow_constraints.never_before.polish: ["validate"]`.

If you attempt to polish a file that hasn't been validated, you'll receive a `QUEUE_GATE_BLOCKED` error:

```json
{
  "status": "error",
  "code": "QUEUE_GATE_BLOCKED",
  "message": "polish requires validate to complete first",
  "actionable_advice": "Run: rdf validate chapter_01.md"
}
```

This constraint can be configured in `config/project.yaml`:
```yaml
agent_safety:
  validation_required_before_polish: true  # Set to false to disable
```

---

### rdf queue

Manage review queues for governance.

```bash
./rdf queue <action> [options]
```

**Actions:**
| Action | Description |
|--------|-------------|
| `list [type]` | List pending items (gap, validation, web, metadata) |
| `approve <id>` | Approve item |
| `reject <id>` | Reject item |
| `stats` | Queue statistics |

**Options:**
| Flag | Description |
|------|-------------|
| `--strategy <name>` | Approval strategy (for gaps) |
| `--reason <code>` | Rejection reason |
| `--note <text>` | Additional note |
| `--format json` | JSON output |

**Examples:**
```bash
# List all pending
./rdf queue list

# List validation issues
./rdf queue list validation

# Approve with strategy
./rdf queue approve gap_001 --strategy library_only

# Reject with reason
./rdf queue reject val_002 --reason hallucination --note "Entity not found"
```

---

### rdf status

Show current workflow state, including active workflows and resume tokens.

```bash
./rdf status [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--last <id>` | Show specific workflow |
| `--type <type>` | Filter by type (book, essay) |
| `--limit <n>` | Maximum workflows |
| `--format json` | JSON output |

**Examples:**
```bash
# Show all active workflows
./rdf status

# Show specific workflow
./rdf status --last BOOK_xxx

# Show only books
./rdf status --type book
```

**Resume Tokens:**

When a workflow pauses at a checkpoint (in supervised or interactive mode), it generates a **resume token**. This token is stored in `workflow_state.json` and identifies the exact checkpoint where the workflow paused.

```json
{
  "workflow_id": "BOOK_001",
  "current_phase": 4,
  "checkpoint": "post_research",
  "resume_token": "RESUME_BOOK_001_post_research",
  "paused_at": "2025-12-14T10:30:00Z"
}
```

**Using Resume Tokens:**
```bash
# Resume a paused workflow
./rdf book --resume BOOK_001

# The CLI reads workflow_state.json to determine where to continue
```

The `rdf status` command shows all active workflows with their current phase and whether they're paused at a checkpoint, so you can see which workflows need attention.

---

## Utility Commands

### rdf context

Agent session warm-start - returns a context packet optimized for Claude Code to resume a session.

```bash
./rdf context [project_id] [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--list` | List all projects |
| `--format json` | JSON output (default) |

**What It Returns:**

The context packet includes:
- **meta**: Project ID, title, type, last activity timestamp
- **position**: Current phase, progress, chapter info
- **active_context**: Last synthesis, pending gaps, research summary
- **blocking_items**: Queue items that need attention
- **next_actions**: Suggested next steps
- **resource_status**: Tavily credits, budget remaining

**Examples:**
```bash
# Get context for specific project
./rdf context BOOK_xxx --format json

# Auto-detect most recent active project
./rdf context

# List all projects
./rdf context --list
```

**Usage for Session Resume:**

When starting a new Claude Code session, run `rdf context` first to efficiently load all necessary state:

```bash
# Instead of reading 5+ files manually:
./rdf context BOOK_20251212134640_xxx --format json

# Returns everything needed to continue:
# - Where you left off (phase, chapter, subject)
# - What's blocking (queue items)
# - What to do next (suggested actions)
```

---

### rdf capabilities

Agent bootstrapping meta-tool - returns a complete capability manifest optimized for Claude Code to discover what RDF can do.

```bash
./rdf capabilities [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--format json` | JSON output (default) |
| `--format text` | Human-readable text output |

**What It Returns:**

The capability manifest includes:
- **version**: RDF version and API version
- **commands**: Complete command reference with flags, examples, and LLM usage
- **workflows**: Standard workflow sequences (book, essay, research)
- **configuration**: Current configuration status (embeddings, generation, entity extraction)
- **error_codes**: All error codes with explanations
- **library_status**: Document and chunk counts
- **opt_in_generation**: Explanation of the opt-in generation model
- **session_management**: Commands for warm-start and status

**Examples:**
```bash
# Get full capability manifest (JSON)
./rdf capabilities --format json

# Human-readable summary
./rdf capabilities --format text
```

**Usage for Agent Bootstrapping:**

When Claude Code starts a fresh session and needs to discover RDF's capabilities:

```bash
# Single call to learn everything about RDF
./rdf capabilities --format json

# Returns:
# - All available commands with their flags
# - Which commands use LLMs and which models
# - Current configuration status
# - Opt-in generation behavior
# - Library health summary
```

This replaces the need to read multiple documentation files and provides a token-efficient capability discovery mechanism.

---

### rdf health

Scan library for issues.

```bash
./rdf health [options]
```

**Examples:**
```bash
./rdf health
./rdf health --format json
```

---

### rdf edit-meta

Edit document metadata.

```bash
./rdf edit-meta <DOC_ID> [options]
```

**Examples:**
```bash
./rdf edit-meta DOC_023 --title "Correct Title" --author "Real Author"
```

---

### rdf assess

Get mechanical metadata about a document.

```bash
./rdf assess <DOC_ID> [options]
```

**Output includes:**
- OCR quality score
- Language detection
- Page count
- Has TOC
- Chunk statistics
- Extraction warnings
- Duplicate likelihood

**Examples:**
```bash
./rdf assess DOC_023
./rdf assess DOC_023 --format json
```

---

### rdf graph

Query the knowledge graph.

```bash
./rdf graph query "<concept>" [options]
```

**Examples:**
```bash
./rdf graph query "consciousness" --format json
```

---

### rdf diff

Compare two files.

```bash
./rdf diff <file_a> <file_b> [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--format unified` | Unified diff output (default) |
| `--format json` | JSON diff with line details |

**Examples:**
```bash
# Unified diff
./rdf diff chapter_01.md chapter_01_polished.md

# JSON diff
./rdf diff original.md revised.md --format json
```

---

### rdf config

Manage RDF configuration settings. Critical for entity extraction/GraphRAG setup.

```bash
./rdf config [action] [options]
```

**Actions:**
| Action | Description |
|--------|-------------|
| `show` | Display current configuration (default) |
| `check` | Check what needs configuration |
| `entity-extraction` | Configure entity extraction provider |

**Options (for entity-extraction):**
| Flag | Description |
|------|-------------|
| `--provider <name>` | Provider: gliner, openai, hybrid |
| `--relation-backend <name>` | For hybrid: openai or llama |
| `--openai-model <model>` | OpenAI model (default: gpt-4o-mini) |
| `--extract-relations` | Enable relationship extraction |
| `--format json` | JSON output |

**Examples:**
```bash
# Check configuration status
./rdf config
./rdf config check --format json

# Configure entity extraction (recommended)
./rdf config entity-extraction --provider hybrid

# Configure with specific settings
./rdf config entity-extraction --provider hybrid --openai-model gpt-4o

# GLiNER only (free, no API required)
./rdf config entity-extraction --provider gliner
```

**Configuration Required Response:**

When entity extraction is needed but not configured, commands return:

```json
{
  "status": "error",
  "code": "CONFIGURATION_REQUIRED",
  "message": "Entity extraction has not been configured.",
  "actionable_advice": "Run: rdf config entity-extraction",
  "decision_packet": {
    "decision_id": "entity_extraction_provider",
    "question": "Which entity extraction provider should be used?",
    "options": [
      {"id": "gliner", "label": "GLiNER (Fast/Free)"},
      {"id": "openai", "label": "OpenAI (Quality)"},
      {"id": "hybrid", "label": "Hybrid (Recommended)"}
    ],
    "default": "hybrid"
  }
}
```

Claude Code should recognize this response and prompt the user to make a configuration choice, then run the appropriate `rdf config entity-extraction --provider <choice>` command.

---

### rdf entity

Manage entities in the knowledge graph - find duplicates, merge entities, create aliases.

```bash
./rdf entity <action> [options]
```

**Actions:**
| Action | Description |
|--------|-------------|
| `duplicates` | Find potential duplicate entities using fuzzy matching |
| `merge <primary_id> <duplicate_id>` | Merge two entities |
| `alias <entity_id> <alias>` | Add an alias to an entity |
| `show <entity_id>` | Show entity details |
| `health` | Entity health check (orphans, missing types, duplicates) |
| `list` | List all entities |

**Options:**
| Flag | Description |
|------|-------------|
| `--threshold <n>` | Similarity threshold for duplicate detection (default: 0.8) |
| `--type <type>` | Filter by entity type (person, place, concept, etc.) |
| `--limit <n>` | Maximum results |
| `--queue` | Create merge request in review queue instead of direct merge |
| `--reason <text>` | Reason for merge (required for direct merge) |
| `--format json` | JSON output |

**Examples:**
```bash
# Find potential duplicates
./rdf entity duplicates --threshold 0.75 --format json

# Find duplicates of specific type
./rdf entity duplicates --type person --limit 20

# Show entity details
./rdf entity show ENT_001 --format json

# Merge entities (direct)
./rdf entity merge ENT_001 ENT_002 --reason "same_person"

# Merge via review queue (safer)
./rdf entity merge ENT_001 ENT_002 --queue

# Add alias
./rdf entity alias ENT_001 "R. Steiner"

# Entity health check
./rdf entity health --format json

# List all entities
./rdf entity list --type person --limit 50
```

**Duplicate Detection Output:**
```json
{
  "status": "success",
  "data": {
    "duplicate_pairs": [
      {
        "entity_a": {"id": "ENT_001", "name": "Rudolf Steiner"},
        "entity_b": {"id": "ENT_002", "name": "R. Steiner"},
        "similarity": 0.92,
        "suggested_action": "merge"
      }
    ],
    "total_candidates": 5
  }
}
```

**Queue-Based Merging:**

For safety, entity merges can go through the review queue:

```bash
# Create merge request
./rdf entity merge ENT_001 ENT_002 --queue

# Review pending merges
./rdf queue list --type concept_merge

# Approve merge
./rdf queue approve MERGE_001
```

---

### rdf export

Export bibliographies and project data in various formats.

```bash
./rdf export bibliography [options]
```

**Options:**
| Flag | Description |
|------|-------------|
| `--project <id>` | Project ID (e.g., BOOK_xxx). If not specified, exports all library sources |
| `--format <fmt>` | Output format: bibtex, ris, csl-json (default: bibtex) |
| `--output <file>` | Output file path. If not specified, prints to stdout |
| `--validate` | Validate sources and report issues instead of exporting |
| `--json-output` | Output results as JSON |

**Supported Formats:**
| Format | Extension | Use With |
|--------|-----------|----------|
| BibTeX | `.bib` | LaTeX, most reference managers |
| RIS | `.ris` | EndNote, Zotero, Mendeley |
| CSL-JSON | `.json` | Pandoc, Zotero |

**Examples:**
```bash
# Export project bibliography as BibTeX
./rdf export bibliography --project BOOK_xxx --format bibtex --output refs.bib

# Export as RIS for Zotero
./rdf export bibliography --project BOOK_xxx --format ris --output refs.ris

# Export as CSL-JSON for Pandoc
./rdf export bibliography --format csl-json --output refs.json

# Export all library sources
./rdf export bibliography --format bibtex --output library.bib

# Validate sources before export
./rdf export bibliography --project BOOK_xxx --validate

# Validate with JSON output
./rdf export bibliography --project BOOK_xxx --validate --json-output
```

**BibTeX Output Example:**
```bibtex
@book{steiner1894philosophy,
  author = {Steiner, Rudolf},
  title = {Philosophy of Freedom},
  year = {1894},
  publisher = {Rudolf Steiner Press},
  note = {RDF Document ID: DOC_023}
}
```

**Validation Output:**
```json
{
  "status": "success",
  "data": {
    "total_sources": 45,
    "valid_sources": 42,
    "issues": [
      "DOC_012: Missing title",
      "DOC_034: Missing author"
    ],
    "warnings": [
      "DOC_015: Missing year",
      "DOC_023: No publisher, journal, or URL"
    ],
    "is_valid": false
  }
}
```

---

## Autonomy Levels

Control how much the agent pauses for review.

| Level | Flag | Checkpoints | Best For |
|-------|------|-------------|----------|
| **Full** | `--autonomy full` | None (errors only) | "Just write it" |
| **Supervised** | `--autonomy supervised` | After research, after draft | Balanced oversight |
| **Interactive** | `--autonomy interactive` | All checkpoints | Careful work |

### Checkpoint Matrix

| Checkpoint | Full | Supervised | Interactive |
|------------|------|------------|-------------|
| `post_search` | Skip | Skip | **Pause** |
| `post_research` | Skip | **Pause** | **Pause** |
| `post_quotes` | Skip | Skip | **Pause** |
| `post_draft` | Skip | **Pause** | **Pause** |
| `post_validation` | Skip | Skip | **Pause** |
| `post_polish` | Skip | Skip | **Pause** |

### Defaults

- **Essays:** `--autonomy full` (run to completion)
- **Books:** `--autonomy supervised` (pause at key points)

---

## JSON Output

All commands support `--format json` for structured output.

### Standard Response Wrapper

```json
{
  "status": "success",
  "code": "SUCCESS",
  "message": "Operation completed",
  "data": {},
  "warnings": [],
  "queue_items_created": 0,
  "next_suggested_commands": []
}
```

### Pause for Review

```json
{
  "status": "success",
  "code": "PAUSED_FOR_REVIEW",
  "message": "Research complete. Review gaps before drafting.",
  "data": {
    "checkpoint": "post_research",
    "workflow_id": "BOOK_xxx",
    "resume_token": "RESUME_xxx_post_research",
    "review_artifacts": [
      {"path": "projects/books/BOOK_xxx/gaps.md", "description": "Gaps requiring strategy"}
    ],
    "decision_packet": {
      "decision_id": "gap_fill_strategy",
      "question": "How should gaps be handled?",
      "options": [
        {"id": "library_only", "label": "Library only", "risk": "May be incomplete"},
        {"id": "allow_web", "label": "Allow web", "risk": "Requires approval"},
        {"id": "skip", "label": "Skip gaps", "risk": "Gaps noted in draft"}
      ],
      "default": "library_only"
    }
  }
}
```

### Error Response

```json
{
  "status": "error",
  "code": "GAP_THRESHOLD_NOT_MET",
  "message": "Coverage 40% below threshold 50%",
  "data": {"coverage": 40, "threshold": 50},
  "actionable_advice": "Run rdf research on missing topics or lower threshold."
}
```

---

## Common Workflows

### Daily Ingest

```bash
cp ~/downloads/*.pdf NEW_DOCS/
./rdf ingest NEW_DOCS/
./rdf health --format json
```

### Research Session

```bash
./rdf search "topic" --summary
./rdf research "question" --strict -o report.md
./rdf quotes "topic" --format json
```

### Evidence-First Essay

```bash
./rdf essay "Topic" --pages 20 --evidence-first --style academic
```

### Supervised Book

```bash
./rdf outline "Topic" --chapters 5 --pages 100
./rdf book projects/books/BOOK_xxx/outline.yaml --autonomy supervised
# Review gaps.md
./rdf book --resume BOOK_xxx --phases 5
./rdf validate projects/books/BOOK_xxx/chapter_01.md
./rdf polish projects/books/BOOK_xxx/chapter_01.md --preset academic
```

### Validate and Polish

```bash
./rdf validate chapter.md --format json
./rdf queue list validation
./rdf queue approve val_001
./rdf polish chapter.md --preset accessible
```

---

## Configuration

### Default Flags

Configured in `config/project.yaml`:

```yaml
defaults:
  autonomy_essay: "full"
  autonomy_book: "supervised"
  strict_library_only: true
```

### Safety Settings

```yaml
agent_safety:
  allow_web_search: false
  require_approved_web_sources: true
  validation_required_before_polish: true
```

### Override with CLI

```bash
# Override strict default
./rdf research "topic" --allow-web

# Override autonomy default
./rdf book outline.yaml --autonomy full
```
