# Vigthoria CLI

AI-powered terminal coding assistant for Vigthoria Coder subscribers, integrated with Vigthoria's AI models, repository workflows, Cortex routing, and subscription system.

```
╔═══════════════════════════════════════════════════════════╗
║                                                           ║
║   VIGTHORIA CLI - AI-Powered Coding Assistant             ║
║                                                           ║
╚═══════════════════════════════════════════════════════════╝
```

## Features

- 🤖 **Interactive Chat** - Natural language coding assistance
- 🧠 **Compact Session Memory** - Resume long conversations with summarized context instead of bloated transcripts
- ✏️ **File Editing** - AI-powered code modifications with diff preview
- 🔧 **Code Generation** - Generate code from descriptions
- 📖 **Code Explanation** - Understand complex code
- 🐛 **Bug Fixing** - Automatic issue detection and fixing
- 📊 **Code Review** - Quality analysis and suggestions
- 🔐 **Secure Auth** - Integration with Vigthoria accounts
- 📦 **Project Context** - Understands your codebase
- 🗂️ **Vigthoria Repo** - Push/Pull projects to your personal cloud repository
- 🔍 **Deep Codebase Search** - Indexed search across files, symbols, and content via ripgrep
- ✏️ **Atomic Multi-File Edits** - Coordinated changes across multiple files with rollback
- 🧩 **Sub-Agent Delegation** - Spawn focused sub-agents for parallel investigation
- 🔒 **Persistent Permissions** - Per-project tool approvals saved across sessions
- 📝 **Multi-Line Input** - Block mode ({{{ }}}) and line continuation (\\) for complex prompts

## Installation

The `vigthoria-cli` package installs the `vigthoria`, `vig`, and `vigthoria-chat` commands. Use the platform installer for automatic setup and updates, or install the npm package globally on Node.js 20.19 or later.

### Quick Install (Linux/macOS)

```bash
curl -fsSL https://cli.vigthoria.io/install.sh | bash
```

### Quick Install (Windows PowerShell)

```powershell
irm https://cli.vigthoria.io/install.ps1 | iex
```

### npm Install (All Platforms)

```bash
npm install -g vigthoria-cli
```

### Manual Install

```bash
# Clone from Vigthoria Market
git clone https://market.vigthoria.io/vigthoria/vigthoria-cli.git
cd vigthoria-cli

# Or from Vigthoria Community
git clone https://community.vigthoria.io/repos/vigthoria-cli.git
cd vigthoria-cli

# Install dependencies
npm install

# Build
npm run build

# Link globally
npm link
```

## Troubleshooting Installation

### Network Issues (npm ENOTFOUND)

If you see `ENOTFOUND registry.npmjs.org`, try these solutions:

1. **Check internet connection:**
   ```bash
   ping registry.npmjs.org
   ```

2. **If behind a corporate proxy:**
   ```bash
   npm config set proxy http://proxy.company.com:8080
   npm config set https-proxy http://proxy.company.com:8080
   ```

3. **Try an alternative npm registry:**
   ```bash
   npm config set registry https://registry.npmmirror.com
   npm install -g vigthoria-cli
   # Reset to default after:
   npm config delete registry
   ```

4. **Direct tarball download:**
   ```bash
   # Download directly
   npm install -g https://coder.vigthoria.io/releases/vigthoria-cli-latest.tgz
   ```

5. **Use Git clone method (no npm registry needed):**
   ```bash
   git clone https://market.vigthoria.io/vigthoria/vigthoria-cli.git
   cd vigthoria-cli && npm install && npm run build && npm link
   ```

### Windows-Specific Issues

**PowerShell Execution Policy:**
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```

**PATH not updated:** Open a new terminal after installation.

**Permissions:** Run PowerShell as Administrator if you get access denied errors.

**Update and diagnostics:** After installing or upgrading, run `vigthoria update` to check for the current release and `vigthoria doctor` to verify Node.js, platform, PATH, authentication, and network readiness.

## Quick Start

### 1. Login

```bash
vigthoria login
```

Options:
- Email & Password
- API Token
- Browser OAuth

Production login fixes in version 1.9.3:
- `vigthoria login --email you@example.com --password "your-password"` now performs direct email/password authentication without requiring interactive prompts.
- When device-code login is not supported by the server, the CLI falls back to a cross-platform email/password prompt.
- HTML or proxy error responses from auth endpoints are sanitized into human-readable messages, so raw HTML is never printed to the terminal.

Cortex routing in version 1.9.3:
- Use `vigthoria chat --cortex` to enable Cortex detective/architect routing through LegionOptions for deeper planning, analysis, and production-readiness audits.
- `vig c --cortex` provides the same Cortex routing shortcut for quick terminal sessions.

### 2. Start Chatting

```bash
vigthoria chat
# or
vig c

# local project execution
npx vigthoria-chat

vigthoria chat-resume
# or
vigthoria chat --resume
```

Long-running sessions are compacted automatically into memory summaries so follow-up prompts keep project context without dragging the full raw transcript forever.

### 3. Edit Files

```bash
vigthoria edit src/index.ts
# or
vig e src/index.ts
```

## Testing

### Local Functional Suite

```bash
npm test
```

This runs the built CLI smoke and direct Agent Mode suite, including the browser-backed HTML proof.

### Direct Agent Proof

```bash
npm run proof:agent
```

This creates a fresh broken HTML file, repairs it with `agent --prompt`, and verifies the result in a headless browser.

### Live Community Repo E2E

```bash
export VIGTHORIA_COMMUNITY_EMAIL="your-community-email"
export VIGTHORIA_COMMUNITY_PASSWORD="your-community-password"
export VIGTHORIA_REPO_TARGET="UsGuard"
npm run test:repo:live
```

Optional:

```bash
export VIGTHORIA_REPAIR_REPO_NAME="UsGuard-cli-repair-e2e"
```

This lists repos, pulls the target repo, runs an Agent Mode repair pass, and pushes the repaired copy back to Vigthoria Community.

### Live Game Generation + Push

```bash
export VIGTHORIA_COMMUNITY_EMAIL="your-community-email"
export VIGTHORIA_COMMUNITY_PASSWORD="your-community-password"
export VIGTHORIA_GAME_REPO_NAME="tower-defense-cli-e2e"
npm run test:game:live
```

This generates a tower defense game from scratch with Agent Mode, validates it in a headless browser, and pushes it to Vigthoria Community.

## Commands

### Chat Mode

```bash
vigthoria chat [options]

Options:
  -m, --model <model>   Select AI model (agent, code, code-35b, code-9b, balanced, balanced-4b, cloud, ultra)
  -p, --project <path>  Set project context path
  -r, --resume          Resume the latest session for this project
      --cortex          Enable Cortex detective/architect routing through LegionOptions for deeper planning and analysis
```

In chat mode, you can use these special commands:
- `/file <path>` - Add file to context
- `/edit <path>` - Switch to edit mode
- `/diff` - Show pending changes
- `/apply` - Apply pending changes
- `/model <name>` - Switch AI model
- `/context` - Show compact session memory and current context state
- `/compact` - Compact the current session into a memory summary
- `/clear` - Clear conversation
- `/help` - Show commands
- `/exit` - Exit chat

### Edit File

```bash
vigthoria edit <file> [options]

Options:
  -i, --instruction <text>  Editing instruction
  -m, --model <model>       Select AI model
```

Example:
```bash
vigthoria edit src/api.ts -i "Add error handling to all endpoints"
```

### Generate Code

```bash
vigthoria generate <description> [options]

Options:
  -l, --language <lang>  Target language (default: typescript)
  -o, --output <file>    Output file path
  -m, --model <model>    Select AI model
```

Example:
```bash
vigthoria generate "REST API endpoint for user authentication" -l typescript -o src/auth.ts
```

### Explain Code

```bash
vigthoria explain <file> [options]

Options:
  -l, --lines <range>     Line range (e.g., 1-50)
  -d, --detail <level>    Detail level (brief, normal, detailed)
```

Example:
```bash
vigthoria explain src/complex.ts -l 50-100 -d detailed
```

### Fix Code

```bash
vigthoria fix <file> [options]

Options:
  -t, --type <type>  Fix type (bugs, style, security, performance)
  --apply            Auto-apply fixes
```

Example:
```bash
vigthoria fix src/index.ts -t security --apply
```

### Code Review

```bash
vigthoria review <file> [options]

Options:
  -f, --format <format>  Output format (text, json, markdown)
```

Example:
```bash
vigthoria review src/app.ts -f markdown > review.md
```

### Configuration

```bash
# Interactive configuration
vigthoria config

# Set value
vigthoria config --set model=vigthoria-code

# Get value
vigthoria config --get model

# List all settings
vigthoria config --list

# Reset to defaults
vigthoria config --reset
```

### Initialize Project

```bash
vigthoria init
```

Creates a `.vigthoria.json` file with project-specific settings.

### Vigthoria Repository (Cloud Storage)

Push and pull your projects to/from your personal Vigthoria Repository - your cloud workspace for projects.

#### Push a Project

```bash
# Push current directory to Vigthoria Repo
vigthoria repo push

# Push specific path
vigthoria repo push /path/to/project

# Push with visibility setting
vigthoria repo push --visibility private
vigthoria repo push --visibility public
vigthoria repo push --visibility restricted

# Force overwrite existing project
vigthoria repo push --force
```

#### Pull a Project

```bash
# Pull a project from your repo
vigthoria repo pull my-project

# Pull to specific output directory
vigthoria repo pull my-project --output /path/to/destination

# Overwrite existing directory
vigthoria repo pull my-project --force
```

#### List Projects

```bash
# List all your projects
vigthoria repo list
# or
vigthoria repo ls

# Filter by visibility
vigthoria repo list --visibility private
```

#### Check Sync Status

```bash
# Check if current project is synced
vigthoria repo status
```

#### Share a Project

```bash
# Generate shareable link (default 7 days)
vigthoria repo share my-project

# Custom expiration
vigthoria repo share my-project --expires 24h
vigthoria repo share my-project --expires 30d
```

#### Delete a Project

```bash
# Remove from Vigthoria Repo (local files unaffected)
vigthoria repo delete my-project
# or
vigthoria repo rm my-project
```

#### Clone a Public Project

```bash
# Clone from preview URL or project ID
vigthoria repo clone https://coder.vigthoria.io/preview/123
vigthoria repo clone 123
```

## Available Models

### Vigthoria Native Models

| Short Name | Full Model ID | Size | Best For |
|------------|---------------|------|----------|
| `balanced` / `balanced-4b` | `vigthoria-v3-balanced-4b` | 4B | All-purpose tasks |
| `code` / `code-v2` | `vigthoria-v2-code-8b` | 8B | Code generation & editing |
| `code-9b` | `vigthoria-v3-code-9b` | 9B | Fast coding specialist |
| `code` / `code-35b` | `vigthoria-v3-code-35b` | 35B | Large-scale code projects |
| `music` | `vigthoria-music-master-4b` | 4B | Music AI generation |

### External Models (Ollama Fallback)

| Short Name | Model | Best For |
|------------|-------|----------|
| `qwen-coder` | `qwen2.5-coder:7b` | Alternative coding |
| `qwen-coder-32b` | `qwen2.5-coder:32b` | Large coding tasks |
| `deepseek` | `deepseek-coder-v2` | DeepSeek coding |
| `deepseek-r1` | `deepseek-r1:8b` | Reasoning tasks |
| `llama3` | `llama3:8b-instruct` | General purpose |

### Using Specific Models

```bash
# Use short name
vigthoria chat -m code-v2

# Use full model ID directly
vigthoria chat -m vigthoria-v3-code-35b

# Force specific version
vigthoria chat -m vigthoria-v2-code-8b

# Use future models when available
vigthoria chat -m code-v4
```

## Configuration File

### Global Config

Located at `~/.config/vigthoria-cli/config.json`:

```json
{
  "apiUrl": "https://api.vigthoria.io",
  "preferences": {
    "defaultModel": "vigthoria-code",
    "theme": "dark",
    "autoApplyFixes": false,
    "showDiffs": true,
    "maxTokens": 4096
  },
  "project": {
    "ignorePatterns": [
      "node_modules",
      ".git",
      "dist"
    ]
  }
}
```

### Project Config

Create `.vigthoria.json` in your project root:

```json
{
  "defaultModel": "vigthoria-code",
  "ignorePatterns": ["build", "coverage"],
  "autoApplyFixes": false
}
```

## Shortcuts

For faster access, use the `vig` command:

```bash
vig c          # vigthoria chat
vig e <file>   # vigthoria edit
vig g <desc>   # vigthoria generate
vig x <file>   # vigthoria explain
vig f <file>   # vigthoria fix
vig r <file>   # vigthoria review
```

## Shell Completion

### Bash

```bash
source ~/.bash_completion.d/vigthoria
```

### Zsh

Add to `~/.zshrc`:
```bash
fpath=(~/.zsh/completion $fpath)
autoload -Uz compinit && compinit
```

## Environment Variables

```bash
# Custom API endpoint
export VIGTHORIA_API_URL="https://custom.api.vigthoria.io"

# Default model
export VIGTHORIA_DEFAULT_MODEL="vigthoria-code"

# API token (alternative to login)
export VIGTHORIA_TOKEN="your-api-token"
```

## Examples

### Working with Drupal Sites

The CLI automatically detects Drupal 8/9/10/11 projects and provides contextual assistance.

#### Setting Up a New Drupal Site

```bash
# Navigate to your Drupal project root (where composer.json or web/ folder is)
cd /path/to/drupal-project

# Start agent mode for autonomous assistance
vigthoria agent

# Ask Vigthoria to help with setup
you › Help me configure this Drupal site for local development

you › Create a custom module called "my_custom_feature" with a block plugin

you › Add a custom content type with these fields: title, body, featured_image, category
```

#### Scanning an Existing Drupal Site

```bash
# Navigate to Drupal root
cd /var/www/my-drupal-site

# Start chat with agent mode enabled
vigthoria chat --agent

# Scan and analyze the site
you › Scan this Drupal site and give me an overview of:
- Drupal version
- Installed modules
- Custom modules
- Active theme
- Any potential issues or outdated code

you › /file web/sites/default/settings.php

you › Check this site's database configuration and suggest security improvements
```

#### Common Drupal Tasks

```bash
# Generate Drupal code
vigthoria generate "Drupal 10 custom block plugin with configuration form" -l php -o web/modules/custom/my_module/src/Plugin/Block/MyBlock.php

# Review a Drupal module
vigthoria review web/modules/custom/my_module/my_module.module

# Fix Drupal coding standards
vigthoria fix web/modules/custom/my_module/*.php -t style --apply

# Explain complex Drupal code
vigthoria explain web/core/lib/Drupal/Core/Entity/EntityBase.php -d detailed
```

#### Drupal Agent Mode Commands

In agent mode, you can ask Vigthoria to:

```bash
you › Read my module's .info.yml and check dependencies

you › Search for all hook_form_alter implementations in custom modules

you › Create a migration YAML for importing content from a CSV

you › Update my module for Drupal 10 compatibility

you › Generate a Drush command to clear specific caches
```

### Interactive Coding Session

```bash
$ vigthoria chat

╔═══════════════════════════════════════════════════════════╗
║   VIGTHORIA CLI - AI-Powered Coding Assistant             ║
╚═══════════════════════════════════════════════════════════╝

you › /file src/api.ts
✓ Added src/api.ts to context (150 lines)

you › Add rate limiting to the authentication endpoint

vigthoria ›
I'll add rate limiting using express-rate-limit. Here's the implementation:

```typescript
import rateLimit from 'express-rate-limit';

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // 5 attempts
  message: 'Too many login attempts, please try again later'
});

app.post('/auth/login', authLimiter, authController.login);
```

you › /edit src/api.ts
What changes would you like to make?
> Add the rate limiting code you showed

[Diff preview shown]
Apply changes? (Y/n) y
✓ Changes applied to src/api.ts
```

### Batch Code Review

```bash
# Review all TypeScript files
for file in src/**/*.ts; do
  vigthoria review "$file" -f markdown >> review-report.md
done
```

### Git Pre-commit Hook

```bash
#!/bin/bash
# .git/hooks/pre-commit

changed_files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.ts$')

for file in $changed_files; do
  vigthoria fix "$file" -t style --apply
done
```

## Troubleshooting

### "Not authenticated" Error

```bash
vigthoria login
# or
export VIGTHORIA_TOKEN="your-token"
```

### "Subscription expired" Warning

Your Vigthoria Coder subscription has expired. Visit https://coder.vigthoria.io to renew.

### Connection Issues

```bash
# Check API status
vigthoria status

# Use different API endpoint
vigthoria config --set apiUrl=https://backup.api.vigthoria.io
```

### Reset Configuration

```bash
vigthoria config --reset
```

## Support

- **User Handbook (EN)**: [VIGTHORIA_CLI_USER_HANDBOOK_EN.md](../docs/VIGTHORIA_CLI_USER_HANDBOOK_EN.md)
- **Benutzerhandbuch (DE)**: [VIGTHORIA_CLI_USER_HANDBOOK_DE.md](../docs/VIGTHORIA_CLI_USER_HANDBOOK_DE.md)
- **PDF Handbooks**: [Download EN](https://landing.vigthoria.io/docs/pdf/VIGTHORIA_CLI_USER_HANDBOOK_EN.pdf) | [Download DE](https://landing.vigthoria.io/docs/pdf/VIGTHORIA_CLI_USER_HANDBOOK_DE.pdf)
- Documentation: https://docs.vigthoria.io/cli
- Issues: https://community.vigthoria.io/forums/cli-support
- Discord: https://discord.gg/vigthoria
- Email: support@vigthoria.io

## License

MIT License - See [LICENSE](LICENSE) for details.

---

Built with ❤️ by Vigthoria Technologies
