# FlowState CLI

Command-line interface for Epic FlowState with dynamic collection support.

## Installation

```bash
npm install -g @epic-flow/flowstate-cli
# or
yarn global add @epic-flow/flowstate-cli
```

## Quick Start

```bash
# Initialize a new project
flowstate init

# Add a server profile
flowstate server add production --url https://api.flowstate.dev --domain prod

# Authenticate
flowstate login
# Enter your email when prompted
# Enter the verification code sent to your email

# Work with any collection
flowstate collection tasks list
flowstate collection workspaces create --interactive
flowstate collection projects get proj_123
```

## Commands

### Project Initialization

```bash
flowstate init [options]
```

Initialize a new FlowState project with optional integrations.

### Server Management

Manage server profiles stored in `~/.flowstate/config.json`.

```bash
# Add a new server profile
flowstate server add <name> --url <url> --domain <domainId>
flowstate server add production --url https://api.flowstate.dev --domain prod

# List all server profiles
flowstate server list
#   NAME            URL                         DOMAIN          AUTH
# * flowstate-dev   https://localhost:7443      flowstate-dev   ✓ user@example.com
#   production      https://api.flowstate.dev   prod            ✗ Not logged in

# Switch active server
flowstate server use <name>
flowstate server use production

# Remove a server profile
flowstate server remove <name>

# Test server connection
flowstate server test [name]   # Tests active server if name omitted
```

### Authentication

Login using email + verification code (same as web app).

```bash
# Login to active server
flowstate login
# > Enter your email: user@example.com
# > Verification code sent! Check your email.
# > Enter code: 123456
# ✓ Logged in as user@example.com

# Login to specific server profile
flowstate login --profile production

# Check auth status
flowstate auth
# Server: flowstate-dev
# User: user@example.com
# Token expires: in 14 minutes

# Logout from active server
flowstate logout

# Logout from specific server
flowstate logout --profile production

# Logout from all servers
flowstate logout --all
```

### Collection Operations

Work with **any collection** in the database using a unified command structure.

#### Available Collections

All collections from `@epic-flow/collections` are automatically available:

- tasks
- projects
- milestones
- workspaces
- codebases
- users
- discussions
- approvals
- templates
- documents
- timeentries
- And more...

#### Create

```bash
# JSON data
flowstate collection <name> create --data '{"field":"value",...}'

# From file
flowstate collection <name> create --file data.json

# Interactive mode
flowstate collection <name> create --interactive
```

#### List

```bash
# All documents
flowstate collection <name> list

# With filter
flowstate collection <name> list --filter "status=active,completed=false"

# JSON filter with operators
flowstate collection <name> list --filter '{"status":{"$in":["To Do","In Progress"]}}'

# With sorting and pagination
flowstate collection <name> list --sort "createdAt:desc" --limit 20 --skip 10

# Different output formats
flowstate collection <name> list --format table   # Default: ASCII table
flowstate collection <name> list --format json    # JSON for scripting
flowstate collection <name> list --format csv     # CSV for spreadsheets
```

#### Get

```bash
# Get by ID
flowstate collection <name> get <id>

# YAML format
flowstate collection <name> get <id> --format yaml
```

#### Update

```bash
# Set specific fields
flowstate collection <name> update <id> --set field=value --set other=value

# JSON data
flowstate collection <name> update <id> --data '{"field":"newvalue"}'

# Interactive mode
flowstate collection <name> update <id> --interactive
```

#### Delete

```bash
# With confirmation
flowstate collection <name> delete <id>

# Skip confirmation
flowstate collection <name> delete <id> --force
```

#### Query

```bash
# Advanced RxDB queries
flowstate collection <name> query '{"field":{"$operator":"value"}}'

# Example: Find all active tasks due before a date
flowstate collection tasks query '{
  "status": {"$in": ["To Do", "In Progress"]},
  "dueAt": {"$lt": "2025-10-31"},
  "completed": false
}'
```

## Examples

### Task Management

```bash
# Create a task
flowstate collection tasks create --data '{
  "name": "implement-feature",
  "title": "Implement New Feature",
  "description": "Add dynamic CLI support",
  "status": "To Do",
  "type": "todo",
  "completed": false,
  "projectId": "proj_123",
  "milestoneId": "mil_456",
  "trashed": false
}'

# List in-progress tasks
flowstate collection tasks list --filter "status=In Progress" --format table

# Update task status
flowstate collection tasks update task_789 --set status="Complete" --set completed=true

# Delete completed tasks
flowstate collection tasks list --filter "completed=true" --format json | \
  jq -r '.[].id' | \
  xargs -I {} flowstate collection tasks delete {} --force
```

### Workspace Management

```bash
# Create workspace interactively
flowstate collection workspaces create --interactive

# List active workspaces
flowstate collection workspaces list --filter "status=active"

# View workspace details
flowstate collection workspaces get wks_abc123

# Archive workspace
flowstate collection workspaces update wks_abc123 --set status="archived"
```

### Project Management

```bash
# List all projects
flowstate collection projects list

# Find projects by organization
flowstate collection projects query '{"orgId":"org_123","status":"active"}'

# Export projects to CSV
flowstate collection projects list --format csv > projects.csv
```

## Configuration

Global configuration is stored in `~/.flowstate/config.json`. This config is shared between CLI and MCP server.

```json
{
  "version": "1.0.0",
  "activeServerId": "flowstate-dev",
  "servers": {
    "flowstate-dev": {
      "id": "flowstate-dev",
      "name": "FlowState Dev",
      "url": "https://localhost:7443",
      "domainId": "flowstate-dev",
      "auth": {
        "accessToken": "eyJhbG...",
        "refreshToken": "eyJhbG...",
        "expiresAt": 1768412132000,
        "userId": "user_abc123",
        "email": "user@example.com"
      }
    },
    "production": {
      "id": "production",
      "name": "Production",
      "url": "https://api.flowstate.dev",
      "domainId": "prod",
      "auth": null
    }
  }
}
```

### Config Fields

| Field                         | Description                             |
| ----------------------------- | --------------------------------------- |
| `activeServerId`              | Currently active server profile         |
| `servers.<id>.url`            | Server URL                              |
| `servers.<id>.domainId`       | Domain ID for multi-tenant isolation    |
| `servers.<id>.auth`           | Auth tokens (set via `flowstate login`) |
| `servers.<id>.auth.expiresAt` | Token expiration timestamp (ms)         |

### MCP Server Configuration

The MCP server can use the shared config via `--profile` flag:

```json
{
  "mcpServers": {
    "flowstate": {
      "command": "npx",
      "args": ["@epicdm/flowstate-mcp", "--profile", "flowstate-dev"]
    }
  }
}
```

Or use environment variables:

```bash
RXDB_SERVER_URL=http://localhost:7080
AUTH_TOKEN=your-token
DOMAIN_ID=your-domain
```

## Filter Syntax

### Simple Filters

Key=value pairs separated by commas:

```bash
--filter "status=active,completed=false"
```

### JSON Filters

Full RxDB query syntax:

```bash
# Exact match
--filter '{"status":"active"}'

# Operators
--filter '{"count":{"$gt":10}}'
--filter '{"status":{"$in":["To Do","In Progress"]}}'
--filter '{"name":{"$regex":"test.*"}}'

# Array match
--filter '{"tagIds":{"$elemMatch":"priority:high"}}'

# Combined
--filter '{"status":"active","createdAt":{"$gt":"2025-01-01"}}'
```

## Scripting

The CLI is designed for automation:

```bash
#!/bin/bash

# Get all active tasks and update their status
flowstate collection tasks list --filter "status=To Do" --format json | \
  jq -r '.[].id' | \
  while read task_id; do
    flowstate collection tasks update "$task_id" --set status="In Progress"
  done

# Export weekly report
START_DATE=$(date -d "7 days ago" +%Y-%m-%d)
flowstate collection tasks query "{\"completedAt\":{\"\$gte\":\"$START_DATE\"}}" \
  --format csv > weekly-completed-tasks.csv
```

## Development

```bash
# Install dependencies
yarn install

# Build
yarn build

# Run tests
yarn test

# Run locally
node dist/cli.js --help
```

## Architecture

The CLI uses runtime reflection to auto-discover collections from `@epic-flow/collections`:

- **CommandRegistry**: Discovers collections on startup
- **CollectionManager**: Provides generic CRUD operations
- **QueryBuilder**: Parses filter syntax to RxDB queries
- **OutputFormatter**: Formats results as table/JSON/CSV
- **InteractivePrompts**: Schema-driven interactive input

Adding a new collection to `@epic-flow/collections` automatically makes it available in the CLI.

### TODO Scanner

Scan project for TODO comments and sync with FlowState tasks:

```bash
# Scan entire project
flowstate scan-todos

# Dry run (preview without changes)
flowstate scan-todos --dry-run

# Scan specific file
flowstate scan-todos --file src/components/Auth.tsx

# Generate summary only (no sync)
flowstate scan-todos --summary-only

# Verbose output
flowstate scan-todos --verbose
```

#### How It Works

1. **Scans** source files for TODO comments
2. **Creates** tasks for new TODOs without taskId
3. **Syncs** existing TODOs with tasks using timestamps
4. **Updates** comments with task metadata
5. **Generates** summary files

#### Comment Format

```typescript
// TODO: Fix authentication bug
// After sync: // TODO: [task_abc123|To Do:2025-10-24T15:30:00.000Z] Fix authentication bug
```

#### Optional Git Hook

Install automatic scanning after commits:

```bash
flowstate scan-todos install-hook todo-scan
```

### File Mapping System

Track file-to-entity relationships without modifying source files.

The File Mapping System stores associations between source files and FlowState entities (tasks, documents, specs) in `.flowstate/mappings/` JSON files instead of embedding metadata in your source code.

#### Key Benefits

- **Clean git diffs** - No embedded metadata pollution in source files
- **Zero merge conflicts** - No competing metadata changes
- **Bidirectional lookups** - Find files by ID or IDs by file
- **Content hashing** - Automatic change detection
- **Team-shareable** - Mapping files committed to git

#### Quick Start

```bash
# Scan TODOs with mapping system (read-only mode)
flowstate scan-todos --use-mapping-system

# Migrate existing embedded IDs to mappings
flowstate migrate-mappings --dry-run  # Preview first
flowstate migrate-mappings             # Perform migration

# Query mappings
flowstate mappings list --file src/api.ts
flowstate mappings list --task task_abc123
flowstate mappings list                # Show summary
```

#### How It Works

**Traditional approach (embedded IDs):**

```typescript
// TODO: [task_abc123|To Do:2025-11-02] Implement retry logic
```

**With mapping system:**

```typescript
// TODO: Implement retry logic
```

The association is stored in `.flowstate/mappings/todos.json`:

```json
{
  "src/api.ts:42": {
    "taskId": "task_abc123",
    "text": "Implement retry logic",
    "status": "active"
  }
}
```

#### File Structure

```
.flowstate/
└── mappings/
    ├── todos.json       # TODO → Task mappings
    ├── markdown.json    # Markdown → Document mappings
    ├── files.json       # Code → Spec mappings
    └── commits.json     # Commit → Task mappings
```

#### Migration Guide

Migrate existing embedded IDs to mapping system:

```bash
# Preview migration (safe, read-only)
flowstate migrate-mappings --dry-run

# Migrate everything
flowstate migrate-mappings

# Migrate specific type only
flowstate migrate-mappings --type todos
flowstate migrate-mappings --type markdown
```

**Important:** Migration never modifies source files. It only extracts IDs and creates mappings.

#### Commands

**List mappings:**

```bash
# Show all mappings
flowstate mappings list

# Show mappings for specific file
flowstate mappings list --file src/api.ts

# Find files for task
flowstate mappings list --task task_abc123

# Find files for document
flowstate mappings list --document steering_arch_001

# List by type
flowstate mappings list --type todos
```

**Scan with mapping system:**

```bash
# Use mapping system (recommended)
flowstate scan-todos --use-mapping-system

# Preview first
flowstate scan-todos --use-mapping-system --dry-run

# Specific file
flowstate scan-todos --use-mapping-system --file src/api.ts
```

#### Documentation

For comprehensive documentation, see:

- [File Mapping System Guide](./docs/mapping-system.md) - Complete documentation
- [Migration Example](./MIGRATION_EXAMPLE.md) - Sample migration output

## Dojo LMS

Typed command surface for the FlowState Dojo learning management API covering courses, modules, items, enrollments, teams, and utility endpoints.

### Authentication

The `dojo` command resolves its API URL and token in this order:

1. Command flags: `--api-url <url>`, `--token <jwt>` (attached to the top-level `dojo` command)
2. Environment variables: `FLOWSTATE_DOJO_URL`, `FLOWSTATE_DOJO_TOKEN`
3. `~/.flowstate/config.json` under key `dojo: { apiUrl, token }`
4. Default URL: `https://dojo.epicflowstate.ai`

Public endpoints (`lead-subscribe`, `url-metadata`) work without a token. All other commands exit with a clear message if no token is resolved:

```
Missing Dojo API token. Set FLOWSTATE_DOJO_TOKEN, use --token <jwt>, or configure ~/.flowstate/config.json.
```

### Commands

```bash
flowstate dojo [--api-url <url>] [--token <jwt>] <subcommand>
```

All commands support `--json` for machine-readable output.

#### Courses

```bash
flowstate dojo courses list [--status draft|published|archived] [--search <q>] [--sort-by <f>] [--sort-order asc|desc] [--page <n>] [--limit <n>]
flowstate dojo courses create --name <name> --code <code> [--description <d>] [--format self_paced|instructor_led|blended] [--category <c>] [--tags <csv>] [--image-url <u>] [--allow-self-enrollment] [--min-tier-level <n>] [--single-purchase-enabled] [--single-purchase-price <cents>] [--start-date <iso>] [--end-date <iso>] [--duration-hours <n>]
flowstate dojo courses get <courseId>
flowstate dojo courses update <courseId> [--name <n>] [--code <c>] [--description <d>] ...
flowstate dojo courses delete <courseId>
flowstate dojo courses publish <courseId>
```

#### Modules

```bash
flowstate dojo modules list <courseId>
flowstate dojo modules create <courseId> --name <name> [--description <d>] [--position <n>] [--prerequisite-ids <csv>] [--require-sequential-progress]
flowstate dojo modules update <moduleId> [--name <n>] [--description <d>] ...
flowstate dojo modules delete <moduleId>
```

#### Items

```bash
flowstate dojo items create <moduleId> --type page|assignment|quiz|discussion|file|video|external_url|scorm --title <t> [--content <c>] [--position <n>] [--completion-type view|submit|score|manual] [--duration-minutes <n>] [--required]
flowstate dojo items update <itemId> [--title <t>] [--content <c>] ...
flowstate dojo items delete <itemId>
flowstate dojo items complete <itemId>
```

#### Enrollments

```bash
flowstate dojo enrollments list [--status active|completed|dropped|expired] [--page <n>] [--limit <n>]
flowstate dojo enrollments enroll --course-id <courseId>
```

#### Teams

```bash
flowstate dojo teams members <teamId> [--page <n>] [--limit <n>]
flowstate dojo teams content <teamId> [--page <n>] [--limit <n>]
flowstate dojo teams events <teamId> --event-id <eventId> [--page <n>] [--limit <n>]
```

#### Utility

```bash
flowstate dojo profile                                          # Authenticated user profile
flowstate dojo tokens                                           # Authenticated user token balance
flowstate dojo lead-subscribe --email <e> [--name <n>] [--source <s>]   # Public — no auth
flowstate dojo url-metadata <url>                                         # Public — Open Graph metadata
```

### Examples

```bash
# Authenticate via environment
export FLOWSTATE_DOJO_URL=https://dojo.epicflowstate.ai
export FLOWSTATE_DOJO_TOKEN=<jwt>

# Browse catalog
flowstate dojo courses list --status published --limit 10

# Create + publish a course
flowstate dojo courses create \
  --name "Intro to FlowState" \
  --code "fs-101" \
  --description "Get started with FlowState" \
  --format self_paced \
  --category "getting-started" \
  --tags "beginner,cli,platform" \
  --allow-self-enrollment
flowstate dojo courses publish course_abc123

# Build out structure
flowstate dojo modules create course_abc123 --name "Setup" --position 1
flowstate dojo items create mod_xyz789 --type video --title "Installing the CLI" --content https://example.com/video.mp4 --position 1 --duration-minutes 8

# Enroll and track
flowstate dojo enrollments enroll --course-id course_abc123
flowstate dojo enrollments list --status active

# Use --json for scripting
flowstate dojo courses list --status published --json | jq -r '.items[].code'
```

### Regenerating Types

The Dojo API types are generated from a vendored copy of the OpenAPI spec at `specs/dojo-api.json`. When the `worker-dojo-api` publishes a new spec, refresh the types:

```bash
# Copy the platform Dojo gateway spec into the CLI and regenerate Dojo types
FLOWSTATE_PLATFORM_REPO=<flowstate-platform> yarn sync:platform-specs:dojo

# Rebuild
yarn build
```

The `prebuild` script runs `generate:types` automatically, so `yarn build` picks up spec changes in one step.

## Observability Platform

FlowState CLI includes a comprehensive observability platform for monitoring errors, logs, and user sessions across your applications.

### Features

- **Error Tracking** - Capture and analyze errors with stack traces and source maps
- **Log Management** - Centralized logging with filtering and search
- **Session Tracking** - User session monitoring with breadcrumbs
- **Real-time Streaming** - Live event monitoring with SSE
- **AI-Enhanced Debugging** - Pattern detection and fix suggestions
- **Task Integration** - Automatic task creation from errors
- **Context Tracking** - Session context for all CLI operations

### Quick Start

Initialize observability during project setup:

```bash
flowstate init
# Answer yes to "Set up observability platform?"
```

Or configure manually:

```bash
flowstate obs config set server-url http://localhost:7081
flowstate obs config set api-key your-api-key
flowstate obs config set default-project my-project
```

### Commands

#### Error Management

```bash
# List errors
flowstate obs errors list --level fatal

# View error details
flowstate obs errors view error-123

# View statistics
flowstate obs errors stats --time-range 7d

# Create task from error
flowstate obs errors view error-123 --create-task
```

#### Log Management

```bash
# List logs
flowstate obs logs list --level error

# Search logs
flowstate obs logs list --search "database error"

# View log details
flowstate obs logs view log-456
```

#### Session Management

```bash
# List sessions
flowstate obs sessions list

# View session details with breadcrumbs
flowstate obs sessions view session-abc123
```

#### Real-Time Streaming

```bash
# Stream all events
flowstate obs tail

# Stream only errors
flowstate obs tail --type error

# Stream fatal errors
flowstate obs tail --type error --level fatal

# Stream specific session
flowstate obs tail --session session-123
```

#### Configuration

```bash
# Show configuration
flowstate obs config show

# Get specific setting
flowstate obs config get session-tracking

# Set configuration
flowstate obs config set auto-link true
flowstate obs config set session-tracking true

# Reset to defaults
flowstate obs config reset
```

### Configuration Options

| Setting           | Default | Description                     |
| ----------------- | ------- | ------------------------------- |
| `enabled`         | `false` | Master switch for observability |
| `serverUrl`       | -       | Observability server URL        |
| `apiKey`          | -       | Authentication API key          |
| `defaultProject`  | -       | Default project for commands    |
| `autoLink`        | `false` | Auto-link errors to tasks       |
| `sessionTracking` | `false` | Track session context           |
| `autoCreateTasks` | `false` | Auto-create tasks from errors   |

### Task Creation from Errors

Automatically create FlowState tasks from errors with AI-generated fix suggestions:

```bash
flowstate obs errors view error-123 --create-task
```

**Features:**

- 9 error pattern types detected
- Priority assignment (critical/high/medium/low)
- 3-5 fix suggestions per pattern
- Full error context and breadcrumbs
- Automatic task linking

### Session Context Tracking

Enable session tracking to automatically capture context during all CLI operations:

```bash
flowstate obs config set session-tracking true
```

**Tracked Context:**

- User ID
- Task ID
- Project ID
- Git branch
- Working directory
- Workspace ID
- Codebase ID

### Documentation

- [OBSERVABILITY_CLI.md](./OBSERVABILITY_CLI.md) - Complete command reference
- [USAGE_EXAMPLES_OBS.md](./USAGE_EXAMPLES_OBS.md) - Practical usage examples and workflows

## License

MIT
