> ## Documentation Index
> Fetch the complete documentation index at: https://docs.heylua.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Skill Management

> Commands for creating, compiling, testing, and deploying skills

## Overview

Skill management commands help you build, test, and deploy your AI skills.

<CardGroup cols={2}>
  <Card title="lua init" icon="plus">
    Create new skill project
  </Card>

  <Card title="lua compile" icon="gears">
    Compile TypeScript code
  </Card>

  <Card title="lua test" icon="flask">
    Test tools interactively
  </Card>

  <Card title="lua push" icon="upload">
    Upload version to server
  </Card>

  <Card title="lua deploy" icon="rocket">
    Deploy to production
  </Card>
</CardGroup>

## lua init

Initialize a new Lua skill project in the current directory.

```bash theme={null}
mkdir my-skill && cd my-skill
lua init                    # Minimal project (recommended)
lua init --with-examples    # Include 30+ example tools
```

### Options

| Option                        | Description                                                                                                |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `--with-examples`             | Include example skills, tools, jobs, webhooks, and processors                                              |
| `--agent-id <id>`             | Use existing agent by ID (non-interactive)                                                                 |
| `--agent-name <name>`         | Name for new agent (requires `--org-id` or `--org-name`)                                                   |
| `--org-id <id>`               | Use existing organization by ID                                                                            |
| `--org-name <name>`           | Create new organization with this name                                                                     |
| `--model <model>`             | LLM model code to use (e.g. `openai/gpt-4o`). Skips the model picker.                                      |
| `--force`                     | Skip confirmations / overwrite existing project                                                            |
| `--restore-sources`           | Automatically restore project source files from backup (requires `--agent-id`)                             |
| `--from-agent-id <id>`        | **Duplicate an existing agent** into a new one (clones skills, persona, MCP servers, env, project backup). |
| `--include-resources`         | Include resources + RAG when duplicating                                                                   |
| `--include-custom-data`       | Include custom data tables when duplicating                                                                |
| `--include-inquiry-form`      | Include inquiry forms when duplicating                                                                     |
| `--include-devices`           | Include device + trigger definitions when duplicating                                                      |
| `--include-ecommerce-catalog` | Include ecommerce catalog (products, baskets) when duplicating                                             |
| `--promo-code <code>`         | Apply a promo code at agent creation for bonus credits                                                     |

### Non-Interactive Mode

```bash theme={null}
# Use existing agent
lua init --agent-id abc123

# Create agent in existing organization
lua init --agent-name "My Bot" --org-id org456

# Create agent + new organization
lua init --agent-name "My Bot" --org-name "Acme Corp"

# Override existing project
lua init --agent-id abc123 --force

# With example code
lua init --agent-id abc123 --with-examples

# Restore from backup
lua init --agent-id abc123 --restore-sources

# Pick a specific LLM model up front
lua init --agent-name "My Bot" --org-name "Acme Corp" --model openai/gpt-4o

# Duplicate an existing agent (clones skills + persona + project backup)
lua init --from-agent-id baseAgent_agent_xxx

# Cross-org duplicate
lua init --from-agent-id baseAgent_agent_xxx --org-id org456

# Duplicate with optional buckets
lua init --from-agent-id baseAgent_agent_xxx \
  --include-resources \
  --include-custom-data \
  --include-devices \
  --include-ecommerce-catalog

# Apply a promo code at agent creation
lua init --agent-name "My Bot" --org-name "Acme Corp" --promo-code LAUNCH50
```

### What It Does

<Steps>
  <Step title="Choose Agent">
    Select existing agent or create new one
  </Step>

  <Step title="Configure Agent (if new)">
    * Enter business name
    * Enter agent name
    * Select business type
    * Select brand personality
    * Enter brand traits
    * Configure features
  </Step>

  <Step title="Create Project">
    * Copies template files
    * Creates `lua.skill.yaml`
    * Installs dependencies
    * Ready to customize!
  </Step>
</Steps>

### Interactive Prompts

<Tabs>
  <Tab title="Minimal (Default)">
    ```bash theme={null}
    $ lua init
    ? What would you like to do? Create new agent
    ? Enter business name: My Coffee Shop
    ? Enter agent name: CoffeeBot
    ? Select business type: Food & Beverage
    ? Select brand personality: Friendly
    ? Enter brand traits: Warm, welcoming, knowledgeable
    🔄 Creating agent...
    ✅ Agent created successfully!
    ✅ Created lua.skill.yaml
    ✅ Copied template files
    ✅ Updated LuaAgent configuration
    📦 Installing dependencies...
    ✅ Lua skill project initialized successfully!
    💡 Tip: Use `lua init --with-examples` to include example code
    ```
  </Tab>

  <Tab title="With Examples">
    ```bash theme={null}
    $ lua init --with-examples
    ? What would you like to do? Create new agent
    ? Enter business name: My Coffee Shop
    ? Enter agent name: CoffeeBot
    ...
    ✅ Created lua.skill.yaml
    ✅ Copied template files
    ✅ Included example skills, tools, jobs, and webhooks
    ✅ Updated LuaAgent configuration
    📦 Installing dependencies...
    ✅ Lua skill project initialized with examples!
    💡 Check the examples/ folder for sample skills, tools, jobs, and webhooks
    ```
  </Tab>

  <Tab title="Existing Agent">
    ```bash theme={null}
    $ lua init
    ? What would you like to do? Select existing agent
    ? Select organization: My Organization
    ? Select agent: CoffeeBot
    ✅ Created lua.skill.yaml
    ✅ Copied template files
    📦 Installing dependencies...
    ✅ Lua skill project initialized successfully!
    ```
  </Tab>
</Tabs>

### What Gets Created

<Tabs>
  <Tab title="Minimal (Default)">
    ```
    your-skill/
    ├── src/
    │   └── index.ts              # Empty agent ready to customize
    ├── lua.skill.yaml            # Configuration (auto-managed)
    ├── package.json              # Dependencies
    ├── tsconfig.json             # TypeScript config
    ├── .env.example              # Environment variables template
    └── README.md                 # Quick start guide
    ```

    A clean slate - build your agent from scratch!
  </Tab>

  <Tab title="With Examples">
    ```
    your-skill/
    ├── src/
    │   └── index.ts              # Agent configuration
    ├── examples/                 # Reference code
    │   ├── skills/               # Example skills & tools
    │   │   ├── tools/            # 30+ tool implementations
    │   │   └── *.skill.ts        # Skill definitions
    │   ├── webhooks/             # HTTP endpoint examples
    │   ├── jobs/                 # Scheduled task examples
    │   ├── preprocessors/        # Message filter examples
    │   ├── postprocessors/       # Response formatter examples
    │   └── services/             # Helper utilities
    ├── lua.skill.yaml
    ├── package.json
    ├── tsconfig.json
    ├── .env.example
    └── README.md
    ```

    Examples in a separate folder - copy what you need!
  </Tab>
</Tabs>

### Configuration File

`lua.skill.yaml` is created with:

```yaml theme={null}
agent:
  agentId: agent_abc123
  orgId: org_xyz789

skills: []  # Auto-populated during compilation
```

<Warning>
  **The `lua.skill.yaml` file is auto-managed by the CLI.** Do not manually edit it except for incrementing version numbers. All configuration belongs in your code (`src/index.ts`).
</Warning>

<Note>
  Persona is stored in your `LuaAgent` code (in `src/index.ts`), not in YAML. The YAML file is state-only and tracks IDs and versions.
</Note>

## lua compile

Compile TypeScript skill into deployable JavaScript bundles.

```bash theme={null}
lua compile
```

### What It Does

<Steps>
  <Step title="Analyze Code">
    Detects all tools from your `src/index.ts` file
  </Step>

  <Step title="Bundle Tools">
    Uses esbuild to create optimized JavaScript bundles
  </Step>

  <Step title="Extract Metadata">
    Extracts tool names, descriptions, and schemas
  </Step>

  <Step title="Create Deployment">
    Generates deployment artifacts in `dist/` directory
  </Step>

  <Step title="Update Config">
    Creates/updates skills in `lua.skill.yaml`
  </Step>
</Steps>

### Output

```
dist/
├── deployment.json          # Deployment metadata
├── index.js                 # Main skill bundle
└── tools/                   # Individual tool bundles
    ├── GetWeatherTool.js
    ├── UserDataTool.js
    └── ...

.lua/
├── deploy.json              # Legacy format
├── get_weather.js           # Uncompressed (debugging)
└── ...
```

### Example Output

```bash theme={null}
$ lua compile
🔨 Compiling Lua skill...
📦 Found 15 tools to bundle...
📦 Bundling GetWeatherTool...
📦 Bundling UserDataTool...
📦 Bundling ProductsTool...
... (more tools)
📦 Bundling main index...
✅ Skill compiled successfully - 15 tools bundled
```

### Features

* ✅ **Automatic Detection** - Finds all tools in your code
* ✅ **Fast Bundling** - Uses esbuild for speed
* ✅ **Type Safety** - Validates TypeScript
* ✅ **Dependency Management** - Bundles all dependencies
* ✅ **Skill Creation** - Auto-creates skills in config
* ✅ **Drift Detection** - Checks for server/local differences

### Compile Options

```bash theme={null}
lua compile              # Default: compile without drift check
lua compile --sync       # Enable drift detection and prompt if found
lua compile --verbose    # Show detailed compilation output
lua compile --debug      # Extra-verbose logging + keep temp files for inspection
```

| Flag        | Description                                                                             |
| ----------- | --------------------------------------------------------------------------------------- |
| `--sync`    | Enable drift detection during compile (prompts if drift found)                          |
| `--verbose` | Show detailed compilation output                                                        |
| `--debug`   | Enable debug mode — extra verbose logging and preserves temp build files for inspection |

<Card title="Learn More" href="/cli/sync-command">
  See lua sync for details on drift detection
</Card>

## lua test

Test individual tools locally in a sandboxed environment.

```bash theme={null}
lua test
```

### Options

| Option           | Description                           |
| ---------------- | ------------------------------------- |
| `--name <name>`  | Entity name to test (non-interactive) |
| `--input <json>` | JSON input string for testing         |

### Non-Interactive Mode

```bash theme={null}
# Test a skill/tool
lua test skill --name get_weather --input '{"city": "London"}'

# Test a webhook
lua test webhook --name payment-hook --input '{"query": {}, "headers": {}, "body": {"type": "payment"}}'

# Test a job
lua test job --name daily-report

# Test preprocessor
lua test preprocessor --name filter --input '{"message": "hello", "channel": "web"}'

# Test postprocessor
lua test postprocessor --name formatter --input '{"message": "hi", "response": "hello", "channel": "web"}'
```

### How It Works

<Steps>
  <Step title="Compile">
    Compiles your skill first
  </Step>

  <Step title="List Tools">
    Shows all available tools
  </Step>

  <Step title="Select Tool">
    Choose which tool to test
  </Step>

  <Step title="Enter Inputs">
    Dynamic prompts based on tool's schema
  </Step>

  <Step title="Execute">
    Runs tool in secure VM sandbox
  </Step>

  <Step title="View Results">
    Shows output or error messages
  </Step>
</Steps>

### Example Session

```bash theme={null}
$ lua test
🧪 Testing Lua skill...
📦 Compiling code first...
✅ Skill compiled successfully
📄 Loaded environment variables from .env file

? 🔧 Select a tool to test:
❯ get_weather - Get the weather for a given city
  create_product - Create a new product
  search_products - Search products
  get_user_data - Get user data
  
✅ Selected tool: get_weather

📝 Enter input values:
? city (required): London

🚀 Executing tool...
Input: {
  "city": "London"
}
✅ Tool execution successful!
Output: {
  "weather": "3",
  "city": "London",
  "temperature": 15.2,
  "description": "Windspeed 12.3 km/h"
}
```

### Features

* ✅ **Dynamic Prompts** - Based on Zod schema
* ✅ **Type Validation** - Validates inputs automatically
* ✅ **Environment Loading** - Loads `.env` and `lua.skill.yaml` variables
* ✅ **Secure Sandbox** - Isolated VM execution
* ✅ **Detailed Errors** - Clear error messages

### Testing Complex Inputs

```bash theme={null}
# Nested objects
? shippingAddress.street (required): 123 Main St
? shippingAddress.city (required): New York
? shippingAddress.zip (required): 10001

# Arrays
? items[0].id (required): product_123
? items[0].quantity (required): 2
? Add another item? No

# Optional fields
? description (optional): [Press Enter to skip]
```

## lua push

Push your compiled components to the Lua server.

```bash theme={null}
lua push                 # Interactive selection
lua push skill           # Push a skill
lua push persona         # Push persona
lua push webhook         # Push a webhook
lua push job             # Push a job
lua push preprocessor    # Push a preprocessor
lua push postprocessor   # Push a postprocessor
lua push mcp             # Push an MCP server
lua push all --force     # Push all components
```

### Options

| Option                | Description                                                                                                                                                                                                                     |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--name <name>`       | Entity name to push (non-interactive)                                                                                                                                                                                           |
| `--set-version <ver>` | Version to set (e.g., 1.0.5)                                                                                                                                                                                                    |
| `--force`             | Skip all confirmation prompts                                                                                                                                                                                                   |
| `--auto-deploy`       | Automatically deploy to production after push                                                                                                                                                                                   |
| `--no-include-source` | Skip the per-skill source attach after push. Default is to attach, so the admin Builder UI source panel reflects your CLI edits. The attach is non-fatal — a failure logs a warning but doesn't fail the push.                  |
| `--fresh`             | (Only for `lua push backup`) Build the backup manifest by walking the project directory from disk, instead of reading the compiled `dist-v2/manifest.json`. Use this to capture out-of-band file changes (e.g. Builder writes). |

<Note>
  **Auto-backup-push:** Every `lua push <primitive>` now synchronously runs a fresh-from-disk backup as the final step. If the backup fails, the command exits non-zero — no more silent partial success where the primitive landed but local source never reached the canonical store.
</Note>

### Non-Interactive Mode

```bash theme={null}
# Push specific skill with version
lua push skill --name mySkill --set-version 1.0.5

# Push all components
lua push all --force

# Push and auto-deploy to production
lua push all --force --auto-deploy

# Push webhook with version
lua push webhook --name payment-hook --set-version 2.0.0

# Push job with version
lua push job --name daily-report --set-version 1.0.0
```

<Note>
  **Push All:** Use `lua push all --force` to push all components at once. Add `--auto-deploy` to also activate/deploy them.
</Note>

### Usage Modes

<Tabs>
  <Tab title="Interactive Mode">
    **Default behavior - prompts for selection**

    ```bash theme={null}
    $ lua push
    ? What would you like to push?
      › skill
        persona
    ```

    Best for: When you're not sure or want to see options
  </Tab>

  <Tab title="Direct Mode - Skill">
    **Skip prompt and push skill directly**

    ```bash theme={null}
    $ lua push skill
    # No prompt - goes straight to pushing skill
    ```

    Best for: Quick iterations, automation, when you know what you want
  </Tab>

  <Tab title="Direct Mode - Persona">
    **Skip prompt and push persona directly**

    ```bash theme={null}
    $ lua push persona
    # No prompt - goes straight to pushing persona
    ```

    Best for: Persona-only updates, faster workflow
  </Tab>
</Tabs>

### What It Does (Skills)

<Steps>
  <Step title="Select Skill (if interactive)">
    Choose which skill to push (if multiple)
  </Step>

  <Step title="Enter Version">
    Enter new version number (auto-suggests next patch)

    ```
    Current version: 1.0.0
    ? Enter new version to push: (1.0.1)
    ```
  </Step>

  <Step title="Update Configuration">
    Updates version in `lua.skill.yaml`
  </Step>

  <Step title="Authenticate">
    Validates your API key
  </Step>

  <Step title="Compile">
    Automatically compiles the skill
  </Step>

  <Step title="Upload">
    Uploads bundles to server
  </Step>

  <Step title="Optional Deploy">
    Choose to deploy immediately or later

    ```
    ? Would you like to deploy this version to production now? (y/N)
    ```
  </Step>
</Steps>

### Example: Push Only (Interactive)

```bash theme={null}
$ lua push
? What would you like to push?
  › skill
    persona

📦 Pushing skill: customer-service

Current version: 1.0.0
? Enter new version to push: (1.0.1) ⏎

📝 Updating version from 1.0.0 to 1.0.1
✅ Authenticated
🔄 Compiling skill...
✅ Skill compiled successfully - 10 tools bundled
🔄 Pushing version to server...
✅ Version 1.0.1 of "customer-service" pushed successfully

? Would you like to deploy this version to production now? No

[Version pushed, use 'lua deploy' to deploy later]
```

### Example: Push Only (Direct Mode)

```bash theme={null}
$ lua push skill
📦 Pushing skill: customer-service

Current version: 1.0.0
? Enter new version to push: (1.0.1) ⏎

📝 Updating version from 1.0.0 to 1.0.1
✅ Authenticated
🔄 Compiling skill...
✅ Skill compiled successfully - 10 tools bundled
🔄 Pushing version to server...
✅ Version 1.0.1 of "customer-service" pushed successfully

? Would you like to deploy this version to production now? No

[Version pushed, use 'lua deploy' to deploy later]
```

### Example: Push and Deploy

```bash theme={null}
$ lua push
📦 Pushing skill: order-management

Current version: 0.5.0
? Enter new version to push: 1.0.0

📝 Updating version from 0.5.0 to 1.0.0
✅ Authenticated
🔄 Compiling skill...
✅ Skill compiled successfully - 8 tools bundled
🔄 Pushing version to server...
✅ Version 1.0.0 of "order-management" pushed successfully

? Would you like to deploy this version to production now? Yes

⚠️  WARNING: You are about to deploy to PRODUCTION!
⚠️  This will affect ALL users immediately.

? Are you absolutely sure you want to deploy? Yes

🔄 Publishing version...
✅ Version 1.0.0 deployed successfully to production
```

### Version Management

<Tabs>
  <Tab title="Auto-Increment">
    The command auto-suggests the next patch version:

    ```
    Current: 1.0.0  → Suggests: 1.0.1
    Current: 1.5.9  → Suggests: 1.5.10
    Current: 2.0.0  → Suggests: 2.0.1
    ```

    Press Enter to accept or type your own version
  </Tab>

  <Tab title="Custom Version">
    You can enter any valid semver version:

    ```
    Current: 0.5.0
    ? Enter: 1.0.0  # Major release

    Current: 1.2.3
    ? Enter: 1.3.0  # Minor update

    Current: 2.0.0
    ? Enter: 2.0.1-beta  # Pre-release
    ```
  </Tab>

  <Tab title="Semantic Versioning">
    Follow semver conventions:

    * **MAJOR** (2.0.0): Breaking changes
    * **MINOR** (1.1.0): New features
    * **PATCH** (1.0.1): Bug fixes

    ```yaml theme={null}
    # In lua.skill.yaml
    skills:
      - name: my-skill
        version: 1.0.1  # Auto-updated by push
    ```
  </Tab>
</Tabs>

<Note>
  **Version Conflict Avoidance**: When using `--force`, the CLI automatically checks the server for the highest existing version and suggests the next available version. This prevents "Version already exists" errors during automated deployments.
</Note>

### Deploy Now or Later?

<Tabs>
  <Tab title="Deploy Later (Recommended)">
    **Push now, test, deploy when ready**

    ```bash theme={null}
    $ lua push
    ? Deploy now? No  # Default

    # Test in sandbox
    $ lua chat → Sandbox mode

    # Deploy when satisfied
    $ lua deploy
    ```

    **Best for:**

    * Major changes
    * Need more testing
    * Team coordination
    * Off-peak deployment
  </Tab>

  <Tab title="Deploy Immediately">
    **One-command deployment**

    ```bash theme={null}
    $ lua push
    ? Deploy now? Yes
    ? Absolutely sure? Yes
    ✅ Deployed
    ```

    **Best for:**

    * Critical hotfixes
    * Small bug fixes
    * Well-tested changes
    * Urgent updates
  </Tab>
</Tabs>

### Important Notes

<Warning>
  **Version Management:**

  * Always increments version (cannot overwrite)
  * Version is updated in `lua.skill.yaml`
  * All versions are preserved on server
  * Can deploy any previous version

  **Immediate Deployment:**

  * Requires two confirmations for safety
  * Affects all users immediately
  * Have rollback plan ready
  * Monitor after deployment
</Warning>

### Version Management

The version number is the **only field** in `lua.skill.yaml` you should manually edit:

```yaml theme={null}
skills:
  - name: my-skill
    version: 1.0.1  # Increment this before pushing
```

Then push:

```bash theme={null}
lua push
```

### Requirements

* Must be in skill directory with `lua.skill.yaml`
* Must have valid API key (`lua auth configure`)
* Version must not already exist on server

## lua deploy

Deploy a specific version of any primitive to production (all users).

```bash theme={null}
lua deploy [type]
```

`type` is optional — when omitted, an interactive menu lets you pick. Valid types: `skill`, `webhook`, `job`, `preprocessor`, `postprocessor`, `persona`, `all`.

### Options

| Option                | Description                                             |
| --------------------- | ------------------------------------------------------- |
| `--name <name>`       | Entity name to deploy (non-interactive selection)       |
| `--set-version <ver>` | Version to deploy, or `'latest'` for the newest version |
| `--force`             | Skip confirmation prompt                                |

<Note>
  **Deprecated flags** — still accepted for backward compatibility but prefer the generic equivalents above:

  | Deprecated              | Use instead           |
  | ----------------------- | --------------------- |
  | `--skill-name <name>`   | `--name <name>`       |
  | `--skill-version <ver>` | `--set-version <ver>` |
</Note>

### Usage

```bash theme={null}
# Interactive — prompts for type, entity, and version
lua deploy

# Deploy a specific primitive type
lua deploy skill
lua deploy webhook
lua deploy job
lua deploy preprocessor
lua deploy postprocessor
lua deploy persona

# Deploy latest version of every primitive at once
lua deploy all --force
```

### Non-Interactive Mode

```bash theme={null}
# Deploy a specific skill version
lua deploy skill --name mySkill --set-version 1.0.5 --force

# Deploy latest webhook version
lua deploy webhook --name myWebhook --set-version latest --force

# Deploy latest of everything (CI/CD)
lua deploy all --force
```

### What It Does

<Steps>
  <Step title="Select Type">
    Choose the primitive type (or pass as argument to skip)
  </Step>

  <Step title="Select Entity">
    Pick which skill / webhook / job / etc. to deploy (auto-selected if only one exists)
  </Step>

  <Step title="Fetch Versions">
    Lists all pushed versions from the server
  </Step>

  <Step title="Select Version">
    Choose which version to deploy (or pass `--set-version latest`)
  </Step>

  <Step title="Confirm">
    Shows warning about production deployment (skip with `--force`)
  </Step>

  <Step title="Deploy">
    Publishes the selected version — immediately live for all users
  </Step>
</Steps>

### Example

```bash theme={null}
$ lua deploy skill
📦 Deploying Skill: mySkill
🔄 Fetching available versions...

? Select a version to deploy:
  1.0.2 - Created: Oct 3, 2025 by you@example.com
  1.0.1 - Created: Oct 2, 2025 by you@example.com
❯ 1.0.0 (CURRENT) - Created: Oct 1, 2025 by you@example.com

? ⚠️  Warning: This version will be deployed to all users. Do you want to proceed? Yes
🔄 Publishing version...
✅ Skill "mySkill" v1.0.0 deployed successfully
```

### Features

* Works for all primitive types — not just skills
* Shows all available versions with currently deployed one highlighted
* Requires explicit confirmation (skip with `--force`)
* Immediate deployment (no rollback delay)
* `lua deploy all --force` deploys latest version of every primitive in one command

<Warning>
  **Deployment is immediate!**

  All users will get the new version right away. Test thoroughly with `lua chat` first!
</Warning>

## lua push backup

<Note>
  Backup your project source files to cloud storage for disaster recovery and team collaboration.
</Note>

Push your project source files to cloud storage for safekeeping. Uses content-addressed storage with automatic deduplication for efficient backups.

```bash theme={null}
lua push backup                 # Backup project sources
lua push backup --force         # Force backup even if up-to-date
lua push backup --skip-compile  # Skip compilation (assume already compiled)
```

### Options

| Option           | Description                                          |
| ---------------- | ---------------------------------------------------- |
| `--force`        | Force backup even if hash matches previous backup    |
| `--skip-compile` | Skip compilation step (assumes dist/ already exists) |

### What Gets Backed Up

The backup includes all source files tracked in your compilation manifest:

* **Source Code**: `src/` directory (TypeScript files)
* **Configuration**: `lua.skill.yaml`, `tsconfig.json`, `package.json`
* **Environment Template**: `.env.example` (if exists)
* **Documentation**: `README.md` (if exists)

<Warning>
  **NOT backed up**: `node_modules/`, `dist/`, `.env` (secrets), `.git/` (use Git for version control)
</Warning>

### How It Works

<Steps>
  <Step title="Compile Project">
    Ensures manifest is fresh (runs `lua compile` if needed)
  </Step>

  <Step title="Calculate Project Hash">
    Creates a content hash of all source files for deduplication
  </Step>

  <Step title="Check Existing Backup">
    Verifies if this exact project state already exists on server
  </Step>

  <Step title="Upload New Files">
    Uploads only new/changed files (content-addressed storage)

    * Compares file hashes with server
    * Uploads missing blobs in batches
    * Deduplicates identical files across backups
  </Step>

  <Step title="Save Manifest">
    Saves the project structure and file references to MongoDB
  </Step>

  <Step title="Update Local Tracking">
    Updates `lua.skill.yaml` with backup hash for drift detection
  </Step>
</Steps>

### Example Output

```bash theme={null}
$ lua push backup
ℹ️  Project hash: 8f3d4a2b1c9e...
🔄 Checking server for existing backup...
🔄 Checking which files need upload...
ℹ️  Files: 42 total, 38 already stored, 4 to upload
ℹ️  Upload size: 12.3 KB (base64)
🔄 Uploading 4 new files to storage...
🔄 Uploaded 4/4 files...
🔄 Saving backup manifest...
✅ Backup pushed successfully!
   Files: 42
   New uploads: 4
   Deduplicated: 38
   Hash: 8f3d4a2b1c9e...
```

### Restoring from Backup

To restore a backed-up project on a new machine:

```bash theme={null}
# Initialize with restore flag
lua init --agent-id abc123 --restore-sources
```

This will:

1. Create a new project directory
2. Download all source files from cloud storage
3. Restore the exact project state from backup
4. Install dependencies

**Interactive restore:**

```bash theme={null}
$ lua init --agent-id abc123
? Would you like to restore project sources from backup? Yes
🔄 Fetching backup manifest...
✅ Found backup with 42 files
🔄 Downloading source files...
🔄 Downloaded 42/42 files...
✅ Sources restored successfully!
💡 Run 'lua compile' to rebuild from restored sources
```

### Use Cases

<Tabs>
  <Tab title="Disaster Recovery">
    **Recover from lost laptop or corrupted files:**

    ```bash theme={null}
    # On new machine
    lua init --agent-id abc123 --restore-sources
    npm install
    lua compile
    lua test
    ```

    All your source code is back!
  </Tab>

  <Tab title="Team Collaboration">
    **Share project with team members:**

    ```bash theme={null}
    # Team member A pushes backup
    lua push backup

    # Team member B clones it
    lua init --agent-id abc123 --restore-sources
    ```

    No Git setup required for quick sharing.
  </Tab>

  <Tab title="Migration">
    **Move project between machines:**

    ```bash theme={null}
    # Old machine
    lua push backup

    # New machine
    lua init --agent-id abc123 --restore-sources
    ```

    Fresh install with all your code intact.
  </Tab>

  <Tab title="CI/CD Safety Net">
    **Automatic backups before deployments:**

    ```bash theme={null}
    # In CI pipeline
    lua push backup --force
    lua push all --force --auto-deploy
    ```

    Always have a recovery point.
  </Tab>
</Tabs>

### Content-Addressed Storage

Backups use **content-addressed storage** (like Git):

* Each file is stored by its SHA-256 hash
* Identical files are stored only once
* Subsequent backups only upload changed files
* Extremely efficient for large projects with small changes

**Example:** If you change one line in one file, only that file is re-uploaded. The other 99 files reference existing blobs.

### Best Practices

<AccordionGroup>
  <Accordion title="Backup Before Major Changes">
    ```bash theme={null}
    lua push backup  # Safety checkpoint
    # Make risky changes
    lua test
    lua push skill
    ```

    If something breaks, restore from backup.
  </Accordion>

  <Accordion title="Use Git for Version Control">
    **Backup ≠ Version Control**

    * **Backup**: Disaster recovery, single snapshot
    * **Git**: Full history, branching, collaboration

    Use both:

    ```bash theme={null}
    git commit -m "Add feature"  # Version control
    lua push backup              # Disaster recovery snapshot
    ```
  </Accordion>

  <Accordion title="Backup Before Deployment">
    ```bash theme={null}
    lua push backup --force
    lua push all --force --auto-deploy
    ```

    Always have a recovery point before production changes.
  </Accordion>

  <Accordion title="Regular Backups in CI/CD">
    Add to your deployment pipeline:

    ```yaml theme={null}
    - name: Backup sources
      run: lua push backup --force

    - name: Deploy
      run: lua push all --force --auto-deploy
    ```
  </Accordion>
</AccordionGroup>

## Complete Workflow

### New Project Workflow

```bash theme={null}
# 1. Authenticate
lua auth configure

# 2. Initialize
mkdir my-skill && cd my-skill
lua init

# 3. Test
lua test

# 4. Push
lua push

# 5. Deploy
lua deploy
```

### Development Workflow

```bash theme={null}
# Configure environment if needed
lua env sandbox        # Add new API keys locally
lua env production     # Update production env vars

# Make changes to src/tools/*.ts

# Test your agent
lua chat  # Choose sandbox mode

# Optional: Test specific tools
lua test  # For debugging individual tools

# When satisfied, push (direct mode - faster!)
lua push skill

# Update production persona if needed
lua persona production # Or: lua push persona

# Deploy to production
lua deploy
```

### Quick Fix Workflow

```bash theme={null}
# 1. Edit file
vim src/tools/MyTool.ts

# 2. Test
lua test

# 3. Push and deploy (direct mode)
lua push skill
lua deploy
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="No lua.skill.yaml found">
    **Error**: `❌ No lua.skill.yaml found`

    **Solution**: Run command from skill directory or run `lua init` first
  </Accordion>

  <Accordion title="Version already exists">
    **Error**: `❌ Version 1.0.0 already exists on the server`

    **Solution**: Increment version in `lua.skill.yaml`:

    ```yaml theme={null}
    skills:
      - version: 1.0.1  # Increment this
    ```
  </Accordion>

  <Accordion title="Compilation failed">
    **Error**: `❌ No index.ts found`

    **Solution**: Create `src/index.ts` with skill definition:

    ```typescript theme={null}
    import { LuaSkill } from "lua-cli";
    const skill = new LuaSkill({...});
    ```
  </Accordion>

  <Accordion title="Tool validation error">
    **Error**: `❌ Tool name invalid`

    **Solution**: Tool names can only contain: `a-z`, `A-Z`, `0-9`, `-`, `_`

    ```typescript theme={null}
    // ✅ Good
    name = "get_weather"

    // ❌ Bad
    name = "get weather"  // No spaces
    ```
  </Accordion>

  <Accordion title="Missing dependencies">
    **Error**: `❌ Cannot find module 'lua-cli'`

    **Solution**: Install dependencies:

    <CodeGroup>
      ```bash npm theme={null}
      npm install
      ```

      ```bash yarn theme={null}
      yarn install
      ```

      ```bash pnpm theme={null}
      pnpm install
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Test Before Pushing">
    Always test locally first:

    ```bash theme={null}
    lua test     # Test individual tools
    lua chat     # Test conversationally
    lua push     # Then push
    ```
  </Accordion>

  <Accordion title="Use Semantic Versioning">
    * **PATCH** (1.0.1): Bug fixes
    * **MINOR** (1.1.0): New features
    * **MAJOR** (2.0.0): Breaking changes
  </Accordion>

  <Accordion title="Test in Sandbox Before Deploy">
    ```bash theme={null}
    lua push     # Upload version
    lua chat     # Test in sandbox
    # If good, then:
    lua deploy   # Deploy to production
    ```
  </Accordion>

  <Accordion title="Keep Version History">
    Don't delete old versions - they serve as rollback points
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Development Mode" icon="code" href="/cli/development">
    Learn about live development with auto-reload
  </Card>

  <Card title="Build Your First Skill" icon="hammer" href="/getting-started/first-skill">
    Follow a complete tutorial
  </Card>
</CardGroup>
