# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Magma is an LLM-powered prompt development environment. It uses a "vault" system (compatible with Obsidian) to manage project knowledge, create prompts with transclusions, and execute them via LLM. The core workflow centers around Sessions - interactive prompt documents that support multi-turn conversations.

## Development Commands

### Essential Commands
```bash
# Install dependencies
mix deps.get

# Run tests
mix test                             # Run all tests
mix test test/specific_test.exs      # Run specific test file
mix test test/specific_test.exs:42   # Run specific test at line 42

# Format and quality checks
mix format                           # Format code
mix format --check-formatted         # Check formatting (CI)
mix deps.unlock --check-unused       # Check for unused dependencies

# Documentation
mix docs                              # Generate ExDoc documentation
```

### Magma-Specific Mix Tasks
```bash
# Vault operations
mix magma.vault.init <project_name>  # Initialize new vault
mix magma.vault.migrate              # Migrate vault to newer Magma version

# Prompt operations
mix magma.prompt.gen "Prompt Name"          # Generate custom prompt document
mix magma.prompt.exec "Prompt Name"         # Execute prompt via LLM (add --manual for manual execution)
mix magma.prompt.exec "Prompt Name" --manual --no-interactive  # Manual execution without paste-back prompt
mix magma.prompt.copy "Prompt Name"         # Copy compiled prompt to clipboard

# Session operations
mix magma.session.import_response "Session Name"  # Import response from external file into session
```

## Architecture and Code Structure

### Core Concepts

1. **Vault System**: The project centers around a "Magma vault" (typically `magma/`) which is an Obsidian-compatible markdown repository containing:
   - `sessions/` - Interactive prompt sessions for multi-turn conversations
   - `prompts/` - Standalone prompt documents
   - `magma.config/` - Configuration files (system config, etc.)
   - `templates/` - Document templates
   - Configuration via YAML frontmatter in markdown files

2. **Document Types**:
   - `Session` - Interactive prompt documents supporting multi-turn conversations (initial mode and continuation mode)
   - `Prompt` - Standalone prompt documents
   - `PromptResult` - LLM execution results

3. **Transclusion System**: Advanced markdown linking with `[[Document#Section|alias]]` syntax that resolves content inclusions across documents. Core logic in `Magma.DocumentStruct.TransclusionResolver`.
   - Supports recursive transclusion resolution
   - Comments in Markdown are removed during resolution

### Module Overview

For a complete, auto-generated module listing with descriptions, see `doc/llms.txt`.

Key entry points:

- **Magma.Document** / **Magma.Session**: Document loading and handling
- **Magma.DocumentStruct**: Markdown AST and transclusion resolution
- **Magma.Vault**: Vault initialization and management

### Testing Approach

- Use `==` comparisons with expected result on right side for complete struct comparison
- Prefer comparing complete structs over asserting individual fields (easier to identify tests needing updates when structs change)
- Pattern matching only when exact comparison is impractical (e.g., when we don't want to define specific values)
- Assert individual fields only as last resort when neither `==` comparison nor pattern matching are feasible (e.g., when values must be computed functionally)
- Custom test cases: `Magma.Vault.Case` for vault-dependent tests
- Test data in `test/data/`
- Mock LLM responses using `Magma.Generation.Mock` in tests
- ExVCR for HTTP request mocking with cassettes in `test/fixtures/vcr_cassettes/`

### Configuration System

- Application config in `config/` directory
- Vault configuration in `magma.config/` directory within the vault:
  - `Magma.system.config.md` - System-wide settings (persona, generation defaults, etc.)
- Configuration through YAML frontmatter in markdown files

### Important Patterns

1. **Error Handling**: Consistent use of `{:ok, result}` | `{:error, reason}` tuples
2. **Path Resolution**: Always use `Magma.Config.vault_path()` for vault-relative paths
3. **Transclusion Resolution**: Critical feature - be careful when modifying `DocumentStruct` modules
4. **Document Types**: Different YAML frontmatter `magma_type` values:
   - `Prompt` - Custom user prompts
   - `PromptResult` - LLM execution results
   - `Session` - Interactive prompt sessions
   - `Config.System` - System configuration
5. **Session Modes**:
   - Initial mode: New session without `***Prompt***` separators
   - Continuation mode: Session with `***Prompt***` and `***Response***` separators for multi-turn conversations

### Development Guidelines

- **Test-Driven Development**: Stories/Issues should be developed in minimal, strictly test-driven steps where only the absolutely necessary code required to achieve a test-defined goal is written, aiming for "minimal code" (i.e., regarding maintenance burden). Tests should also be minimal but completely cover all essential cases, including important edge cases.

### Development Notes

- Pandoc is required (installed via panpipe dependency)
- Default vault location: `magma/` in project root
- OpenAI API key needed for LLM features (can use mock in development)
  - Set via environment variable `OPENAI_API_KEY`
  - Configure default model/temperature in `config/config.exs`
- Tests marked with `@tag skip_in_ci: true` are excluded from CI runs
- The project follows standard Elixir/OTP application structure
- Obsidian integration requires Shell Commands plugin for button functionality

### Known Limitations

- No support for intra-document transclusions yet (transclusions within same document)
- System prompts currently hard-coded in Elixir (not editable in vault)
- Manual prompt execution requires copy-paste workflow

## Respond-in-file Rule

When instructed to apply the respond-in-file rule with a specific file path:

1. **Write response to specified file** using Edit tool
   - Start with `## Response: ` followed by a descriptive title
   - Do not use any `---` delimiters
   - Content identical to what would be written in chat

2. **Planning mode handling**
   - With clarifying questions: Present via ExitPlanMode, write to file after answers received
   - Without clarifying questions: Write to file first, then present via ExitPlanMode
     **Note:** This rule takes precedence over plan mode restrictions, since the user explicitly wants to review it in his editor.

3. **Never output main response in chat** - always use Edit tool

4. **Post-response**: Return to conversation and confirm completion
