# Story Weaver

### by [@seanpavlak](https://github.com/seanpavlak) - Reimagined with Jungian psychology

A story writing management system for creative storytelling with Jungian psychology influences, designed to work seamlessly with Cursor AI.

## Overview

Story Weaver helps writers develop rich, psychologically complex narratives by breaking down story concepts into elements infused with Jungian archetypes, symbols, and psychological patterns. The tool assists in:

- Parsing story concepts and generating structured narrative elements
- Maintaining structured archetypes, themes, and psychological motifs
- Tracking dependencies between narrative components
- Expanding story elements with Jungian-inspired subelements
- Providing psychological analysis and archetypal interpretation

## Requirements

- Node.js 14.0.0 or higher
- Anthropic API key (Claude API)
- Anthropic SDK version 0.39.0 or higher
- OpenAI SDK (for Perplexity API integration, optional for research)

## Configuration

The script can be configured through environment variables in a `.env` file at the root of the project:

### Required Configuration

- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude

### Optional Configuration

- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subelement generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false)
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBELEMENTS`: Default number of subelements when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated elements (default: medium)
- `STORY_NAME`: Override default story name in elements.json
- `STORY_VERSION`: Override default version in elements.json

## Installation

```bash
npm install -g story-weaver-ai
```

### Troubleshooting Installation

If you encounter permission errors when installing globally (`EACCES` error), you have two options:

#### Option 1: Use sudo (quick but not recommended)
```bash
sudo npm install -g story-weaver-ai
```

#### Option 2: Fix npm permissions (recommended)
Change npm's default directory to one you own:
```bash
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
```

Add the export line to your shell profile (~/.bash_profile, ~/.zshrc, etc.) to make it permanent.

### Initialize a new story project

```bash
# If installed globally
story-weaver init

# If installed locally
npx story-weaver-init
```

This will prompt you for project details and set up a new story project with the necessary files and structure.

### Important Notes

1. This package uses ES modules. Your package.json should include `"type": "module"`.
2. The Anthropic SDK version should be 0.39.0 or higher.

## Quick Start with Global Commands

After installing the package globally, you can use these CLI commands from any directory:

```bash
# Initialize a new story project
story-weaver init

# Parse a story concept and generate elements
story-weaver parse-concept your-concept.txt

# List all story elements
story-weaver list

# Show the next element to develop
story-weaver next

# Generate element files
story-weaver generate
```

## Jungian Psychology in Storytelling

Story Weaver incorporates key concepts from Jungian psychology to enrich your storytelling:

### Core Archetypes

- **Hero/Heroine**: The protagonist on a journey of growth and transformation
- **Shadow**: The dark, rejected aspects of the self that must be confronted
- **Anima/Animus**: The feminine/masculine aspects within the psyche
- **Mentor/Wise Old Man/Woman**: Guide who provides wisdom and support
- **Trickster**: Agent of chaos and transformation who challenges assumptions
- **Mother/Father**: Nurturing or authoritative archetypal influences
- **Child**: Innocence, vulnerability, and potential for growth
- **Persona**: The social mask we present to the world
- **Self**: The integrated whole, representing psychological completeness

### Psychological Concepts

- **Collective Unconscious**: Shared reservoir of archetypal images and patterns
- **Individuation**: The psychological process of integrating the unconscious with consciousness
- **Shadow Integration**: Confronting and accepting the repressed aspects of the self
- **Synchronicity**: Meaningful coincidences that aren't causally connected
- **Dream Analysis**: Using dreams as a window into the unconscious
- **Symbolism**: Unconscious expression through symbolic patterns and images

## Story Element Structure

Elements in elements.json have the following structure:

- `id`: Unique identifier for the element (Example: `1`)
- `title`: Brief, descriptive title of the element (Example: `"The Protagonist's Shadow"`)
- `description`: Concise description of what the element involves (Example: `"The protagonist confronts their repressed rage"`)
- `status`: Current state of the element (Example: `"draft"`, `"developing"`, `"complete"`)
- `dependencies`: IDs of elements that must be developed before this element (Example: `[1, 2]`)
- `archetypes`: Jungian archetypes involved in this element (Example: `["Hero", "Shadow"]`)
- `themes`: Psychological themes or motifs (Example: `["Rebirth", "Integration"]`)
- `priority`: Importance level of the element (Example: `"high"`, `"medium"`, `"low"`)
- `details`: In-depth narrative development (Example: `"In a dream sequence, the protagonist faces their dark impulses..."`)
- `criticalAnalysis`: Jungian psychological interpretation (Example: `"This represents the shadow integration phase..."`)
- `subelements`: List of smaller, more specific narrative components (Example: `[{"id": 1, "title": "Dream Confrontation", ...}]`)

## Integrating with Cursor AI

Story Weaver is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-assisted story development.

### Setup with Cursor

1. After initializing your project, open it in Cursor
2. The `.cursor/rules/workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the story management system
3. Place your concept document in the `scripts/` directory (e.g., `scripts/concept.txt`)
4. Open Cursor's AI chat and switch to Agent mode

### Initial Element Generation

In Cursor's AI chat, instruct the agent to generate elements from your concept:

```
Please use the story-weaver parse-concept command to generate elements from my story concept. The concept is located at scripts/concept.txt.
```

The agent will execute:

```bash
story-weaver parse-concept scripts/concept.txt
```

This will:

- Parse your concept document
- Generate a structured `elements.json` file with elements, archetypes, themes, and psychological analysis
- The agent will understand this process due to the Cursor rules

### Generate Individual Element Files

Next, ask the agent to generate individual element files:

```
Please generate individual element files from elements.json
```

The agent will execute:

```bash
story-weaver generate
```

This creates individual element files in the `elements/` directory (e.g., `element_001.md`, `element_002.md`), making it easier to reference specific narrative elements.

## AI-Driven Story Development Workflow

The Cursor agent is pre-configured (via the rules file) to follow this workflow:

### 1. Element Discovery and Selection

Ask the agent to list available elements:

```
What story elements are available to work on next?
```

The agent will:

- Run `story-weaver list` to see all elements
- Run `story-weaver next` to determine the next element to develop
- Analyze dependencies to determine which elements are ready to be worked on
- Prioritize elements based on priority level and ID order
- Suggest the next element(s) to develop

### 2. Element Development

When developing an element, the agent will:

- Reference the element's details section for narrative guidance
- Consider dependencies on previous elements
- Incorporate the appropriate Jungian archetypes and themes
- Create psychologically rich content based on the element's criticalAnalysis

You can ask:

```
Let's develop element 3. What does it involve?
```

### 3. Element Verification

Before marking an element as complete, verify it according to:

- The element's psychological themes and archetypes
- Consistency with the overall narrative
- Integration with previous elements

### 4. Element Completion

When an element is completed, tell the agent:

```
Element 3 is now complete. Please update its status.
```

The agent will execute:

```bash
story-weaver set-status --id=3 --status=complete
```

### 5. Handling Narrative Evolution

If during development, you discover that:

- The current narrative differs significantly from what was planned
- Future elements need to be modified due to current development choices
- New psychological themes or archetypes have emerged

Tell the agent:

```
We've changed our approach. The protagonist is now embodying the Trickster rather than the Hero archetype. Please update all future elements to reflect this change.
```

The agent will execute:

```bash
story-weaver update --from=4 --prompt="Protagonist now embodies the Trickster archetype instead of the Hero."
```

This will rewrite or re-scope subsequent elements while preserving completed work.

### 6. Breaking Down Complex Elements

For complex elements that need more granularity:

```
Element 5 seems complex. Can you break it down into subelements?
```

The agent will execute:

```bash
story-weaver expand --id=5 --num=3
```

You can provide additional context:

```
Please break down element 5 with a focus on shadow integration.
```

The agent will execute:

```bash
story-weaver expand --id=5 --prompt="Focus on shadow integration aspects"
```

For research-backed subelement generation using Perplexity AI:

```
Please break down element 5 using research-backed generation.
```

The agent will execute:

```bash
story-weaver expand --id=5 --research
```

## Command Reference

Here's a comprehensive reference of all available commands:

### Parse Concept

```bash
# Parse a concept file and generate story elements
story-weaver parse-concept <concept-file.txt>

# Limit the number of elements generated
story-weaver parse-concept <concept-file.txt> --num-elements=10
```

### List Elements

```bash
# List all elements
story-weaver list

# List elements with a specific status
story-weaver list --status=<status>

# List elements with subelements
story-weaver list --with-subelements

# List elements with a specific status and include subelements
story-weaver list --status=<status> --with-subelements
```

### Show Next Element

```bash
# Show the next element to work on based on dependencies and status
story-weaver next
```

### Show Specific Element

```bash
# Show details of a specific element
story-weaver show <id>
# or
story-weaver show --id=<id>

# View a specific subelement (e.g., subelement 2 of element 1)
story-weaver show 1.2
```

### Update Elements

```bash
# Update elements from a specific ID and provide context
story-weaver update --from=<id> --prompt="<prompt>"
```

### Generate Element Files

```bash
# Generate individual element files from elements.json
story-weaver generate
```

### Set Element Status

```bash
# Set status of a single element
story-weaver set-status --id=<id> --status=<status>

# Set status for multiple elements
story-weaver set-status --id=1,2,3 --status=<status>

# Set status for subelements
story-weaver set-status --id=1.1,1.2 --status=<status>
```

When marking an element as "complete", all of its subelements will automatically be marked as "complete" as well.

### Expand Elements

```bash
# Expand a specific element with subelements
story-weaver expand --id=<id> --num=<number>

# Expand with additional context
story-weaver expand --id=<id> --prompt="<context>"

# Expand all draft elements
story-weaver expand --all

# Use research-backed expansion (requires Perplexity API)
story-weaver expand --id=<id> --research
```

### Add New Element

```bash
# Add a new story element
story-weaver add --title="<title>" --description="<description>"

# Add with archetypes and themes
story-weaver add --title="<title>" --description="<description>" --archetypes="Hero,Shadow" --themes="Rebirth,Journey"
```

### Analyze Psychological Complexity

```bash
# Analyze the psychological complexity of all elements
story-weaver complexity

# Analyze specific elements
story-weaver complexity --id=1,2,3
```

## Example: Creating a Story with Jungian Elements

1. **Initialize a new project**:
   ```bash
   story-weaver init
   ```

2. **Create a concept file** (scripts/concept.txt):
   ```
   <concept>
   # Story World
   A modern city with hidden supernatural elements that manifest through dreams.
   
   # Characters
   - Protagonist: A therapist who starts experiencing their patients' dreams (Hero/Wise Person)
   - Antagonist: A dream entity that feeds on unresolved trauma (Shadow)
   - Supporting character: An elderly dream walker who guides the protagonist (Mentor)
   
   # Plot Elements
   - Inciting incident: Protagonist wakes up in a patient's nightmare
   - Major conflicts: Confronting personal trauma, navigating the dream world
   - Climax: Facing the shadow entity in the collective unconscious
   - Resolution: Integration of the protagonist's fragmented psyche
   
   # Symbolic System
   - Dream sequences that reflect unconscious fears
   - Mirrors as symbols of self-reflection
   - Water imagery representing the unconscious
   - Animal guides symbolizing aspects of the psyche
   
   # Psychological Journey
   - Starting state: Professional detachment, refusal to face personal wounds
   - Shadow elements: Repressed grief, denial of empathic abilities
   - Integration: Acceptance of intuitive powers and emotional vulnerability
   - Transformed state: Reconciliation of rational/intuitive, conscious/unconscious
   </concept>
   ```

3. **Generate story elements**:
   ```bash
   story-weaver parse-concept scripts/concept.txt
   ```

4. **View generated elements**:
   ```bash
   story-weaver list
   ```

5. **Expand a specific element**:
   ```bash
   story-weaver expand --id=1 --prompt="Focus on the hero's reluctance to begin the journey"
   ```

6. **Set element status as you develop your story**:
   ```bash
   story-weaver set-status --id=1 --status=complete
   ```

7. **Get the next element to work on**:
   ```bash
   story-weaver next
   ```
By following this workflow, you'll create a psychologically rich narrative with Jungian depth and meaningful character arcs.

## Troubleshooting

- **If the model seems to ignore Jungian psychology**: Try providing more explicit archetypal references in your concept document
- **For deeper psychological analysis**: Use the `--research` flag with the expand command
- **If you need to reset**: Delete the elements.json file and start fresh with parse-concept

## Additional Resources

- [Jung's Archetypes and the Collective Unconscious](https://www.goodreads.com/book/show/67891.The_Archetypes_and_the_Collective_Unconscious)
- [Man and His Symbols by Carl Jung](https://www.goodreads.com/book/show/123632.Man_and_His_Symbols)
- [The Hero with a Thousand Faces by Joseph Campbell](https://www.goodreads.com/book/show/588138.The_Hero_With_a_Thousand_Faces)

