# Tufte Press Skill Development Strategy

**Date**: 2025-11-10  
**Status**: Complete - Ready for deployment  
**Related**: `skills/tufte-press/`, `~/proj/tufte-press/`

## Objective

Evolve the tufte-press skill from a reference guide into a complete workflow tool that can:
1. Generate study card JSON from conversation context
2. Build PDFs using the tufte-press toolchain
3. Print handouts with duplex support

## Requirements Analysis

### Original Skill (Reference-Only)
- **Purpose**: Provide LLM authoring prompts and schema documentation
- **Limitation**: User had to manually generate JSON and use tufte-press repo separately
- **Dependencies**: None (lightweight, portable)

### Target Skill (Complete Workflow)
- **Purpose**: End-to-end automation from conversation → printed handout
- **Capabilities**:
  - Agent generates JSON directly from conversation
  - Automated PDF build with Nix environment handling
  - Optional print integration with CUPS
- **Dependencies**: tufte-press repository available in environment

## Implementation

### 1. Agent as Content Generator

**Key Insight**: The agent itself can act as the "educator-typesetter" that generates valid JSON.

**Process**:
1. Agent reviews conversation history
2. Extracts learning content (concepts, definitions, examples)
3. Structures content following strict JSON schema
4. Validates schema compliance before saving
5. Saves JSON to appropriate location

**Schema Rules** (enforced by agent):
- Lists MUST be JSON arrays, not newline-separated strings
- Margin notes MUST be self-contained (restate term being defined)
- Equations MUST have `equation_latex` attribute
- Practice strips have prompts only (NO answers)
- Self-check questions include answers
- Sources must be real or marked "[NEEDS CLARIFICATION]"

### 2. Build Automation Scripts

Created helper scripts in `skills/tufte-press/scripts/`:

#### `build-card.sh`
- Wrapper for tufte-press card-build.sh
- Automatically enters Nix development shell if needed
- Handles environment detection gracefully

```bash
# Auto-detects if in dev environment
# If not, enters nix develop and runs build
build-card.sh my-card.json
```

#### `generate-and-build.sh`
- Complete workflow orchestration
- Validates JSON → Builds PDF → Prints (optional)
- Color-coded logging and error handling

```bash
# Validate only
generate-and-build.sh my-card.json

# Build PDF
generate-and-build.sh my-card.json --build

# Build and print duplex
generate-and-build.sh my-card.json --build --print --duplex --copies 2
```

### 3. Print Integration

**CUPS Integration**:
- Uses `lp` command for printing
- Supports printer selection, copies, duplex
- Shows print queue status after submission
- Graceful fallback if printing unavailable

**Print Options**:
- `--printer NAME`: Specify printer
- `--copies N`: Number of copies
- `--duplex`: Enable 2-sided printing (long-edge for handouts)

### 4. Documentation Updates

#### SKILL.md
- Complete workflow instructions for agent
- Strict schema rules with examples
- Step-by-step process (extract → generate → build → print)
- Error handling guidance
- Self-contained margin note pattern

#### README.md
- User-facing documentation
- Installation instructions
- Usage examples
- Troubleshooting section
- Environment setup guide

## Testing

### Test Card Created
Generated `test-card.json` demonstrating:
- Valid metadata with sources
- Two-column layout
- Multiple content types (text, list, callout)
- Self-contained margin notes
- Practice strips and self-check questions
- Glossary entries

### Workflow Validated
1. ✅ JSON validation passes
2. ✅ PDF builds successfully (24KB output)
3. ✅ Nix environment auto-detection works
4. ✅ Error messages are clear and actionable
5. ✅ Build script enters dev shell automatically

### Build Output
```
📄 Tufte Press Study Card Workflow
====================================

▸ Validating JSON metadata...
✓ JSON validation complete!

▸ Building PDF from JSON...
✓ PDF generated: test-card.pdf

✓ Workflow complete!
  JSON: test-card.json
  PDF:  test-card.pdf
```

## File Structure

```
skills/tufte-press/
├── SKILL.md                          # Agent instructions (complete workflow)
├── README.md                         # User documentation
├── scripts/
│   ├── build-card.sh                # Nix wrapper for card-build.sh
│   └── generate-and-build.sh        # Complete workflow orchestration
└── examples/
    └── lambda-calculus-example.json  # Reference example
```

## Key Design Decisions

### 1. Agent Generates JSON Directly
**Rationale**: Agent has context from conversation, understands schema, can validate structure before saving. More efficient than providing prompts for external LLM.

### 2. Automatic Nix Shell Entry
**Rationale**: Users don't need to remember to enter dev environment. Script handles it automatically while still working if already in shell.

### 3. Validation Before Build
**Rationale**: Catch schema errors early before expensive LaTeX compilation. Provides clear feedback on what's wrong.

### 4. Print as Optional Step
**Rationale**: Not all users have printers configured. PDF generation is core functionality, printing is convenience feature.

### 5. Build in Same Directory as JSON
**Rationale**: Keep outputs co-located with sources for easy reference. Follows tufte-press convention of using `cards/build/` for artifacts.

## Integration with tufte-press Repository

**Dependency**: Skill requires tufte-press repo at `~/proj/tufte-press` (or `$TUFTE_PRESS_REPO`)

**Uses from tufte-press**:
- `scripts/metadata-validate.sh` - JSON schema validation
- `scripts/card-build.sh` - PDF generation pipeline
- `docs/card-generator/json_to_tufte_tex.py` - JSON → LaTeX converter
- `tex/tuftepress.cls` - LaTeX document class
- `flake.nix` - Nix development environment

**Wraps, doesn't duplicate**: Skill provides workflow automation, not reimplementation.

## Deployment Strategy

### Global Skill (Recommended)
Deploy to `~/.claude/skills/tufte-press/` and `~/.config/opencode/skills/tufte-press/` via Nix:

```nix
# In ~/proj/dotfiles or system config
inputs.skills.url = "path:/home/dan/proj/skills";

services.ai-skills = {
  enable = true;
  selectedSkills = [ "tufte-press" "worklog" ];
  deployTargets = [ "claude" "opencode" ];
};
```

### Environment Requirement
Set `TUFTE_PRESS_REPO` if not using default location:

```bash
export TUFTE_PRESS_REPO=/path/to/tufte-press
```

Or add to shell configuration:

```nix
environment.sessionVariables.TUFTE_PRESS_REPO = "/home/dan/proj/tufte-press";
```

## Usage Patterns

### Simple Generation
```
User: Create a study card about binary search
Agent: [generates JSON, saves to file]
```

### Build and Review
```
User: Create a study card about recursion and build it
Agent: [generates JSON, builds PDF, shows location]
```

### Complete Workflow
```
User: Create a 2-page study card about graph algorithms and print it
Agent: [generates JSON, builds PDF, sends to printer with duplex]
```

### From Conversation
```
User: [discusses topic for 10 messages]
User: Turn our conversation into a study card
Agent: [extracts concepts, generates structured JSON, builds PDF]
```

## Benefits

1. **Efficient**: No manual JSON authoring, validation, or build commands
2. **Integrated**: Uses conversation context for content extraction
3. **Validated**: Schema checking before expensive build step
4. **Automated**: Handles Nix environment, build process, printing
5. **Flexible**: Can generate JSON only, or go all the way to printed handouts
6. **Educational**: Enforces best practices (self-contained notes, real citations)

## Future Enhancements

Possible improvements (not implemented):

1. **Template Selection**: Different card styles (technical, historical, problem-solving)
2. **Multi-Card Generation**: Batch process multiple topics from conversation
3. **Citation Lookup**: Automatic DOI/citation search for mentioned sources
4. **Diagram Integration**: Generate TikZ or GraphViz from descriptions
5. **Spaced Repetition**: Generate Anki cards from study card content
6. **Version Control**: Track card revisions, show diffs
7. **Web Preview**: HTML rendering before PDF build

## Lessons Learned

1. **Agent as generator works well**: LLM can follow strict schema with proper prompts
2. **Self-contained notes are critical**: Prevents confusion, enables standalone reference
3. **Early validation saves time**: Catch errors before LaTeX compilation
4. **Automatic environment handling**: Users shouldn't think about Nix shells
5. **Print is convenience**: PDF generation is core, printing is nice-to-have
6. **Clear error messages matter**: Schema validation output must be actionable

## Success Criteria

- ✅ Agent generates valid JSON from conversation
- ✅ JSON validates against tufte-press schema
- ✅ PDF builds successfully with proper typography
- ✅ Margin notes are self-contained
- ✅ Scripts handle Nix environment automatically
- ✅ Error messages are clear and helpful
- ✅ Print integration works with CUPS
- ✅ Complete workflow tested end-to-end

## Related Documentation

- `skills/tufte-press/SKILL.md` - Agent instructions
- `skills/tufte-press/README.md` - User documentation
- `~/proj/tufte-press/docs/card-generator/llm-card-authoring-prompt.md` - Original prompt
- `~/proj/tufte-press/cards/metadata-schema.json` - JSON schema
- `docs/CROSS-REPO-SKILL-COLLABORATION.md` - Skill deployment patterns

## Conclusion

The evolved tufte-press skill provides a complete, conversation-aware workflow for generating educational study cards. It leverages the agent's ability to extract content from context, structure it according to strict schemas, and automate the build and print process. The skill is production-ready and tested end-to-end.
