# TICKET MATE

### QUICK NOTES

1. Test tickets with `ticket-mate sync --ticket NOVA-123`

**Jira integration and AI execution layer** - Bridges Jira tickets and AI-assisted development workflows.

### Jira AppSettings

https://developer.atlassian.com/console/myapps/

## Overview

`@ameshkin/ticket-mate` is a production-ready npm package that provides comprehensive Jira integration capabilities. It includes a CLI interface, REST API server, Next.js dashboard, and automation features for managing Jira tickets, syncing progress files, generating AI prompts, building PR descriptions, and automating ticket creation from JSON files.

## Database

https://console.prisma.io/cmixzg6nk03vo2sflg2pzq64u/cmixzgvue03sd1efplmdnimkj/cmixzgvue03se1efpm49q18z0/studio#table=users&schema=public&view=table

### Database Connectivity (SSH Tunnel)

If direct connection to the database is blocked (e.g. `P1001` error), use an SSH tunnel:

1. **Start the tunnel**:

   ```bash
   npm run db:tunnel
   ```

   _Note: This requires the `hostinger_ollama` SSH key._

2. **Run commands with overridden DATABASE_URL**:

   ```bash
   DATABASE_URL="postgresql://ticket-mate:ticketpassmate@localhost:15432/ticket_mate" npm run vercel-build
   ```

3. **Verify Connection**:
   ```bash
   npm run db:test:tunnel
   ```

## Error Logs

```bash


vercel logs ticket-mate.app

```

## Vercel Environment Variables

```bash
# list env
vercel env ls


# pull all production vars into a test file .test-prod.env
vercel env pull .test-prod.env --environment=production


# Or if you want all environments in one file:
vercel env pull .env.vercel.production --environment=production

            "code": "OLLAMA_MODEL_MISSING",
            "message": "Model \"qwen2.5-coder:latest\n\" is not installed on http://72.61.71.227:11434. Using fallback \"qwen2.5-coder:latest\".",
            "requested": "qwen2.5-coder:latest\n",
            "fallbackUsed": "qwen2.5-coder:latest"


vercel env add GITHUB_CLIENT_ID development
# paste the value when prompted

vercel env add GITHUB_CLIENT_SECRET development

vercel env add NEXTAUTH_URL development


#remove if exists undefined
#https://jira-mate.vercel.app
vercel env ls production
vercel env rm NEXTAUTH_URL production --yes


vercel env add OLLAMA_DEMO_MODEL production
vercel env add OLLAMA_DEMO_MODEL development
vercel env add OLLAMA_DEMO_MODEL preview

vercel env add OLLAMA_CODE_MODEL development

OLLAMA_CODE_MODEL

qwen2.5-coder:7b

vercel env add NEXTAUTH_URL production
=https://ticket-mate.app


#https://ticket-mate.app

OLLAMA_CODE_MODEL=
OLLAMA_DEMO_MODEL=

# AI Runtime Configuration
AI_RUNTIME=auto


# VERCEL LOGS


vercel logs ticket-mate.app

RESEND_API_KEY=re_36qa2oNt_HyHhz8N9AXjtmnCkcDUGa3Wh



vercel env add DATABASE_URL production
#postgres://3bc59484969a8f4dd008a6300b7c79daa72fc00ec9db1d3545013fe8e48afd0c:sk_IJnKo655RyEjZhfoDiGel@db.prisma.io:5432/postgres?sslmode=require
#
#
#ATLASSIAN_WEBHOOK_PATH="/api/webhooks/jira"
#ATLASSIAN_PROJECT_KEY=JM


hostinger ollama
root

Brootgroot17+

export OLLAMA_BASE_URL="http://72.61.71.227:8080"
export OLLAMA_DEMO_MODEL="qwen2.5-coder:latest"



vercel env add GITHUB_CLIENT_ID development



cp /Users/amirmeshkin/_code/_work/proveoautomation/CHAT/Web/frontend/src/pages/admin/profile/ProfilePage.tsx




OLLAMA_BASE_URL

```

### Ollama Server

```bash
ssh root@72.61.71.227


ssh -i /Users/amirmeshkin/.ssh/hostinger_ollama root@72.61.71.227



ollama pull qwen2.5-coder:14b

ollama run qwen2.5-coder:14b


ollama pull deepseek-coder




```

cp -R \
"/Users/amirmeshkin/\_code/my-npm-packages/orchestrator-core" \
"/Users/amirmeshkin/\_code/my-npm-packages/orchestrator/\_packages/nevaroAI/"

```bash

# copy CHAT from component examples to CHAT


cp -R \
"/Users/amirmeshkin/_code/_work/proveoautomation/component-examples/CHAT/" \
"/Users/amirmeshkin/_code/_work/proveoautomation/CHAT"





# copy CHAT from CHAT back to COMPONENT


cp -R \
"/Users/amirmeshkin/_code/_work/proveoautomation/CHAT/" \
"/Users/amirmeshkin/_code/_work/proveoautomation/component-examples/CHAT"

```

### Demo Account and Page

https://www.ticket-mate.app/demo

demo@gmail.com
welcome123

## Ticket Mate v1.0 Roadmap

Ticket Mate v1.0 unifies four pillars into a single coherent flow:

- ✅ **Ticket Mate CLI + `.orchestrator`** - Command-line tools that sync Jira tickets to local markdown files
- ✅ **Next.js Admin UI + Webhook** - Web interface for viewing and managing tickets, bugs, and AI-assisted planning
- ⏳ **Replit Extension** - In-editor tool tab for working with tickets and bugs directly in Replit
- ✅ **Orchestrator-derived `bugs.json`** - Unified bug tracking that can be promoted to Jira Bug issues

All four pillars share the same data structures and read from the same `.orchestrator` directory, ensuring consistency across tools.

**Progress:** 75% Complete (3 of 4 pillars fully implemented)

**Completed Features:**

- ✅ CLI with 20+ commands (`tm`, `ticket-mate`)
- ✅ `.orchestrator` file-based integration
- ✅ Next.js Admin UI with full dashboard
- ✅ OAuth authentication (GitHub, Google, Atlassian, Apple, Credentials)
- ✅ Jira REST API client
- ✅ Ticket syncing to markdown files
- ✅ AI prompt generation
- ✅ Board management with AI columns
- ✅ Bugs.json integration
- ✅ Webhook handling
- ✅ Git integration (branch/commit validation)

**In Progress:**

- ⏳ Replit Extension (planned - architecture defined, implementation pending)

**Recent Completions (2025-01-12):**

- ✅ Local email/password authentication
- ✅ OAuth security enhancements (CSRF protection, token encryption)
- ✅ Authentication-aware data fetching
- ✅ Production deployment (ticket-mate.app)
- ✅ Branding update (Ticket Mate → Ticket Mate)
- ✅ Ticket organization restructured (`.orchestrator/tickets/`)

**Tracking:**

- Progress: [`.orchestrator/tickets/`](.orchestrator/tickets/)
  - Epics: [`.orchestrator/tickets/epics/`](.orchestrator/tickets/epics/) (2 files)
  - Stories: [`.orchestrator/tickets/stories/`](.orchestrator/tickets/stories/) (1 file)
  - Bugs: [`.orchestrator/tickets/bugs/`](.orchestrator/tickets/bugs/) (5 files)
  - Tasks: [`.orchestrator/tickets/tasks/`](.orchestrator/tickets/tasks/) (9 files)
- Master Progress: [`.orchestrator/master-progress.md`](.orchestrator/master-progress.md)

**Documentation:**

- **[User Guide](docs/user-guide.md)** - Comprehensive guide for features and usage.
- **[API Documentation](docs/api.md)** - Reference for API endpoints.

## Features

### Core Features

- ✅ **[Jira Integration](docs-dev/JIRA-AUTH-ISSUE.md)** - Full REST API client for Jira operations (OAuth + PAT support)
- ✅ **[Ticket Syncing](docs-dev/COMMANDS.md)** - Sync Jira tickets to markdown files for documentation
- ✅ **[AI Prompts](docs-dev/AI-WORKFLOW.md)** - Generate AI-consumable prompts from ticket briefs
- ✅ **[PR Builder](docs-dev/COMMANDS.md)** - Generate structured PR descriptions from tickets
- ✅ **[CLI Interface](docs-dev/COMMANDS.md)** - 20+ command-line tools (`tm`, `ticket-mate`)
- ✅ **[REST API Server](docs-dev/API-REPORT.md)** - Next.js API routes with authentication
- ✅ **[Next.js Dashboard](docs-dev/NEW-PAGES-REFERENCE.md)** - Full web UI for projects, boards, tickets, and admin
- ✅ **Board Management** - Create boards, add columns (including "AI: In Progress")
- ✅ **[Automation](docs-dev/AUTOMATION-GUIDE.md)** - Process JSON files (bugs-wip.json) and create Jira tickets
- ✅ **Git Integration** - Branch and commit message validation
- ✅ **[Webhook Handling](docs-dev/WEBHOOK-TESTING.md)** - Process Jira webhook events with security validation
- ✅ **Acceptance Criteria** - Extract and sync from test files
- ✅ **[File-based Integration](docs-dev/AGENT-HANDLER-INTEGRATION.md)** - Repository-based ticket management for AI agents
- ✅ **[Authentication](docs-dev/AUTH-MODES.md)** - Local email/password + OAuth (GitHub, Google, Atlassian, Apple)
- ✅ **Token Management** - AI token usage tracking and limits

### Phase 5 Features (Completed)

- ✅ **Authority** - End-to-end provenance for audits with real GitHub/Jira cross-referencing.
- ✅ **Reliability** - Quality gates with real data checks for Acceptance Criteria and PR ticket links.
- ✅ **Contracts** - Team agreement management with digital signatures.
- ✅ **Automation** - Workflow builder with support for Jira/GitHub triggers and custom actions.
- ✅ **Events** - Real-time observability feed for system-wide transparency.
- ✅ **Usage** - Per-user AI credit consumption and API limit tracking.

## Key Components

Jira Mate is built with a modular architecture:

| Component              | Responsibility                                                       | Location                                 |
| :--------------------- | :------------------------------------------------------------------- | :--------------------------------------- |
| **Jira Client**        | High-level wrapper for Jira REST API v3 with OAuth/PAT support.      | `src/server/jira/jiraClient.ts`          |
| **GitHub Client**      | Octokit wrapper for repository management and PR oversight.          | `src/server/github/client.ts`            |
| **QualityGateService** | Core engine for reliability checks and health scoring.               | `src/server/reliability/quality-gate.ts` |
| **AuditService**       | Immutable event logger for compliance and security auditing.         | `src/server/audit/audit.service.ts`      |
| **Sync Engine**        | Bidirectional synchronization between Jira and local markdown files. | `src/server/sync/`                       |
| **Workflow Engine**    | Registry and execution handler for automated tasks.                  | `src/server/automation/`                 |

### Advanced Features

- ✅ **[AI Execution Integration](docs-dev/AI-WORKFLOW.md)** - Execute tickets with AI agents
- ✅ **Queue Processing** - Process queues of AI-ready tickets
- ✅ **Batch Operations** - Bulk sync and status updates
- ✅ **Observability** - Metrics and logging
- ✅ **Template System** - Customizable markdown templates
- ✅ **[Multi-tenant Support](docs-dev/ACCOUNT-USER-MODEL.md)** - Account-based organization with seat management
- ✅ **Subscription Management** - Plan tiers, billing, and usage limits

## Feature Spotlight

### 🤖 AI-Driven Workflow

Ticket Mate bridges the gap between Jira and AI agents. It converts tickets into context-rich prompts that agents can understand.

```typescript
import { buildTicketPrompts } from "@ameshkin/ticket-mate";

// Generate a comprehensive prompt for an AI agent
const prompts = await buildTicketPrompts({
  ticketKey: "NOVA-123",
  // Includes ticket details, acceptance criteria, and plan
  markdownPath: ".orchestrator/tickets/tasks/NOVA-123.md",
  repoRoot: process.cwd(),
});

console.log(prompts.system); // "You are an expert engineer..."
console.log(prompts.task); // "Implement feature X following these criteria..."
```

### ⚡ Automated Bug Filing

Turn JSON reports or linter output into Jira tickets automatically, preventing issue drift.

```bash
# Process a bugs.json file and create/update Jira tickets
ticket-mate process-bugs --file ./reports/security-audit.json --sync-status
```

```typescript
// Programmatic automation
import { processJsonInstructionsDirect } from "@ameshkin/ticket-mate/api/automation";

await processJsonInstructionsDirect(
  {
    bugs: [{ title: "Memory Leak in Auth", severity: "critical" }],
  },
  { projectKey: "PROJ" }
);
```

### 🔐 Secure Multi-Mode Auth

Switch seamlessly between Personal Access Tokens for CLI usage and OAuth for SaaS deployment.

```env
# Mode 1: Personal Access Token (CLI / Local)
ATLASSIAN_AUTH_MODE=PAT
ATLASSIAN_EMAIL=me@example.com
ATLASSIAN_API_KEY=my-token

# Mode 2: OAuth 2.0 (SaaS / Multi-user)
ATLASSIAN_AUTH_MODE=OAUTH
ATLASSIAN_CLIENT_ID=...
ATLASSIAN_CLIENT_SECRET=...
```

For a deep dive into all features and architecture, see the **[Developer Documentation Index](docs-dev/README.md)**.

## Installation

### From GitHub Packages (Private)

First, configure npm to use GitHub Packages for the `@ameshkin` scope:

```bash
# Create or edit .npmrc in your project root
echo "@ameshkin:registry=https://npm.pkg.github.com" >> .npmrc
echo "//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN" >> .npmrc
```

Then install:

```bash
npm install @ameshkin/ticket-mate
```

**Note**: You need a GitHub Personal Access Token (PAT) with `read:packages` permission to install private packages.

## Configuration

### Environment Variables

Create a `.env` file or set environment variables:

#### Required Jira Configuration

```env
ATLASSIAN_BASE_URL=https://pamcms.atlassian.net
ATLASSIAN_EMAIL=your-email@example.com
ATLASSIAN_API_KEY=your-api-token
```

**Optional:**

```env
ATLASSIAN_PROJECT_KEY=YOUR_PROJECT  # Optional: CLI prefers --project flag or config file
```

- Generate your Jira API token at: https://id.atlassian.com/manage-profile/security/api-tokens
- **Important**: Your Jira user must have "Create Issues" permission in the project
- **[Setup Jira Keys Guide](docs/SETUP-JIRA-KEYS.md)** - Complete guide for getting and configuring all Jira keys
- See [Permissions & Access Guide](docs/PERMISSIONS-AND-ACCESS.md) for complete setup
- See [Quick Permission Fix](docs/QUICK-PERMISSION-FIX.md) if you get permission errors
- See [Jira Setup Guide](docs/jira/JIRA-SETUP.md) for detailed instructions
- See [ATLASSIAN_SCOPES.md](ATLASSIAN_SCOPES.md) for required OAuth scopes

#### Authentication Modes

ticket-mate supports two authentication modes:

1. **Personal Access Token (PAT)** - Default mode

   - Uses `ATLASSIAN_EMAIL` + `ATLASSIAN_API_KEY` for Basic Auth
   - Simple setup, good for local dev and single-user scenarios
   - Optional: `ATLASSIAN_CLOUD_ID` for Cloud API calls (not required)
   - Set `ATLASSIAN_AUTH_MODE=PAT` explicitly, or leave unset (defaults to PAT)

2. **OAuth 2.0** - For production/SaaS
   - Uses `ATLASSIAN_CLIENT_ID` + `ATLASSIAN_CLIENT_SECRET` in env
   - Per-user tokens and `cloudId` stored in database (not in env)
   - Multi-user support, per-user authentication
   - Set `ATLASSIAN_AUTH_MODE=OAUTH` to enable
   - **Atlassian Developer Console**: [View/Manage OAuth Apps](https://developer.atlassian.com/console/myapps/)
   - **Required Callback URLs** (register both in Atlassian Developer Console, one per line):
     - `http://localhost:4000/api/auth/callback/atlassian` (local dev)
     - `https://ticket-mate.app/api/auth/callback/atlassian` (production)
   - **Environment Variables**:
     - Local: `NEXTAUTH_URL="http://localhost:4000"`, `ATLASSIAN_CLIENT_ID`, `ATLASSIAN_CLIENT_SECRET`
     - Production: `NEXTAUTH_URL="https://ticket-mate.app"`, `ATLASSIAN_CLIENT_ID`, `ATLASSIAN_CLIENT_SECRET`
   - See [OAuth Setup Guide](docs/OAUTH-SETUP.md) for details
   - See [OAuth Callback URL Setup](docs/OAUTH-CALLBACK-URL-SETUP.md) for callback URL configuration

**Important Notes:**

- `ATLASSIAN_CLOUD_ID` is **not required** in env. In PAT mode it's optional for Cloud API. In OAuth mode it's stored per-connection in the database.
- `ATLASSIAN_PROJECT_KEY` is **optional**. CLI prefers `--project` flag or config file. Use env only as fallback.
- If you previously used `ATLASSIAN_API_TOKEN`, rename it to `ATLASSIAN_API_KEY`. The old variable is deprecated.

#### Cloud API Configuration (for Scoped API Tokens)

If you're using Atlassian scoped API tokens and projects/keys don't appear, enable cloud API mode:

```env
ATLASSIAN_USE_CLOUD_API=true
ATLASSIAN_CLOUD_ID=your-cloud-id
```

**How to find your Cloud ID:**

1. Go to https://admin.atlassian.com
2. Select your site
3. Copy the Cloud ID from the URL or site settings

**When to use Cloud API:**

- Using scoped API tokens (long tokens starting with `ATATT3x...`)
- Projects are not appearing with standard configuration
- Getting 403/404 errors when listing projects

**Cloud API URL format:**

- Standard: `https://pamcms.atlassian.net/rest/api/3`
- Cloud API: `https://api.atlassian.com/ex/jira/{cloudId}/rest/api/3`

Alternatively, add to your `jira.json`:

```json
{
  "baseUrl": "https://pamcms.atlassian.net",
  "email": "your-email@example.com",
  "apiToken": "your-token",
  "cloudId": "your-cloud-id",
  "useCloudApi": true
}
```

#### API Authentication (for Next.js API routes)

```env
TICKET_MATE_API_KEY=your-secure-api-key
NEXT_PUBLIC_TICKET_MATE_API_KEY=your-secure-api-key
```

#### Dashboard Configuration (for Next.js dashboard)

```env
NEXT_PUBLIC_ATLASSIAN_BASE_URL=https://pamcms.atlassian.net
```

**Important**: Never commit `.env` files - they contain sensitive credentials.

## Quick Start

### CLI Usage

```bash
# Test configuration
ticket-mate config:test

# Sync a single ticket
ticket-mate sync --ticket NOVA-123

# Sync all tickets in project
ticket-mate sync --all

# Generate AI prompt from ticket
ticket-mate prompt NOVA-123

# List projects
ticket-mate ls-projects

# List issues
ticket-mate ls-issues --status "In Progress"

# Create a board with AI column
ticket-mate create-board --name "Cursor Board" --ai-column

# Process bugs from JSON file
ticket-mate process-bugs --file public/bugs.json

# Show project information
ticket-mate project-info
ticket-mate project-info --health  # Include health check

# Run health check
ticket-mate health-check
ticket-mate health-check --fix  # Attempt to fix issues

# Quick sync with progress indicators
ticket-mate quick-sync --ticket NOVA-123
ticket-mate quick-sync --all

# Export tickets to various formats
ticket-mate export --format json --output tickets.json
ticket-mate export --format csv --status "In Progress"
ticket-mate export --format markdown --label "AI-READY"

# Batch operations
ticket-mate batch --keys "NOVA-123,NOVA-124" --action transition --status "Done"
ticket-mate batch --file tickets.txt --action comment --comment "Reviewed"
ticket-mate batch --keys "NOVA-123" --action update --labels "reviewed,tested"

# Export and batch operations
ticket-mate export --format json --output tickets.json
ticket-mate batch --keys "NOVA-123,NOVA-124" --action transition --status "Done"
```

### Programmatic Usage

```typescript
import {
  getJiraConfig,
  syncSingleTicket,
  buildTicketPrompts,
  listProjects,
} from "@ameshkin/ticket-mate";

// Get configuration
const config = getJiraConfig();

// Sync a ticket
const result = await syncSingleTicket("NOVA-123", config);

// Generate AI prompts
const prompts = await buildTicketPrompts({
  ticketKey: "NOVA-123",
  markdownPath: ".orchestrator/tickets/epics/NOVA-10/NOVA-123.md",
  repoRoot: process.cwd(),
});

// List projects
const projects = await listProjects();
```

### Next.js Dashboard

The package includes a Next.js dashboard. Start it with:

```bash
npm run dev
```

Then visit `http://localhost:4000` to see the dashboard with projects and boards.

## Usage

### CLI Commands

#### Sync Commands

```bash
# Sync specific ticket
ticket-mate sync --ticket NOVA-123

# Sync epic and all tickets
ticket-mate sync --epic NOVA-10

# Sync all tickets
ticket-mate sync --all

# Custom output directory
ticket-mate sync --all --output .custom-progress
```

#### Issue Management

```bash
# List projects
ticket-mate ls-projects

# List issues with filters
ticket-mate ls-issues --project NOVA --status "In Progress"
ticket-mate ls-issues --assignee me --label AI-READY
ticket-mate ls-issues --jql "project = NOVA AND status = 'In Progress'"

# Show issue details
ticket-mate show-issue NOVA-123
```

#### Board Management

```bash
# Create board with AI column
ticket-mate create-board --name "Cursor Board" --ai-column

# List boards for project
ticket-mate create-board --list

# Create board without AI column
ticket-mate create-board --name "Team Board" --no-ai-column
```

#### Automation

```bash
# Process bugs from JSON file
ticket-mate process-bugs --file public/bugs.json

# Watch for changes and auto-process
ticket-mate watch-bugs --file public/bugs.json --auto-process

# Sync bug statuses from Jira
ticket-mate process-bugs --file public/bugs.json --sync-status
```

#### AI & Prompts

```bash
# Generate AI prompt from a ticket
ticket-mate prompt NOVA-123

# Save prompt to file
ticket-mate prompt NOVA-123 --output nova-123.md

# Execute AI-assisted work
ticket-mate execute NOVA-123

# Process queue of AI-ready tickets
ticket-mate queue
```

#### Git Validation

```bash
# Validate branch name
ticket-mate validate-branch feature/NOVA-123-checkout

# Validate commit message
ticket-mate validate-commit "NOVA-123: Add checkout functionality"
```

#### Other Commands

```bash
# Check sync status
ticket-mate status

# Test configuration
ticket-mate config:test

# Create task folder
ticket-mate create-task-folder NOVA-123

# Sync acceptance criteria
ticket-mate sync-acceptance NOVA-123

# Interactive menu
ticket-mate interactive
```

### File-based Integration: `.orchestrator`

Ticket Mate provides a file-based integration system that allows AI agents (Cursor, Replit, etc.) to work with Jira tickets directly in your repository. This integration uses a `.orchestrator` directory structure that is committed to Git and can be used by any AI agent.

### Quick Start

```bash
# Initialize repository for Ticket Mate integration
tm init-repo --jira-base-url https://pamcms.atlassian.net --jira-project-key YOUR_PROJECT

# Sync tickets from Jira
tm sync-tickets

# Show status of local tickets
tm status

# Emit instructions for AI agents
tm emit-agent-instructions --agent cursor
```

### Directory Structure

The `.orchestrator` directory structure:

```
.orchestrator/
  config.json              # Repository configuration
  tickets/
    <ATLASSIAN_KEY>/
      ticket.meta.json     # Ticket metadata (status, summary, etc.)
      plan.md              # High-level plan and objectives
      tasks.md             # Detailed task checklist
      progress.log.md      # Append-only progress log
      notes.md             # Free-form notes (user-editable)
```

### Configuration

The `.orchestrator/config.json` file contains:

```json
{
  "jiraBaseUrl": "https://pamcms.atlassian.net",
  "jiraProjectKey": "YOUR_PROJECT",
  "jiraCloudId": "optional-cloud-id",
  "defaultBranch": "main",
  "integrations": {
    "cursor": {
      "enabled": true
    },
    "replit": {
      "enabled": true,
      "webhookUrl": "https://your-replit-webhook-url"
    }
  }
}
```

### CLI Commands

#### `tm init-repo`

Initialize a repository for Ticket Mate integration:

```bash
tm init-repo --jira-base-url https://pamcms.atlassian.net --jira-project-key YOUR_PROJECT
tm init-repo --enable-replit --replit-webhook-url https://your-webhook-url
```

Options:

- `--jira-base-url <url>` - Jira base URL
- `--jira-project-key <key>` - Jira project key
- `--jira-cloud-id <id>` - Optional cloud ID
- `--default-branch <branch>` - Default Git branch (default: main)
- `--enable-replit` - Enable Replit integration
- `--replit-webhook-url <url>` - Replit webhook URL
- `--enable-cursor` - Enable Cursor integration

#### `tm sync-tickets`

Sync Jira issues into `.orchestrator/projects/<projectKey>/tickets/`:

```bash
# Sync all tickets with default statuses
tm sync-tickets

# Sync specific statuses
tm sync-tickets --status "Ready for Dev" --status "In Progress"

# Limit number of tickets
tm sync-tickets --limit 10

# Dry run (show what would be created)
tm sync-tickets --dry-run

# Skip webhook notification
tm sync-tickets --no-webhook
```

#### `tm status`

Show status of tickets in `.orchestrator/projects/<projectKey>/tickets/`:

```bash
# Show all tickets
tm status

# Filter by status
tm status --filter-status "In Progress"

# JSON output
tm status --json
```

#### `tm emit-agent-instructions`

Emit instructions for AI agents:

```bash
# Generic instructions
tm emit-agent-instructions

# Cursor-specific
tm emit-agent-instructions --agent cursor

# Replit-specific
jm emit-agent-instructions --agent replit
```

### Replit Integration

Ticket Mate can notify Replit automations when tickets are synced:

1. **Create a Replit Automation** with a Custom Webhook Trigger
2. **Copy the webhook URL** provided by Replit
3. **Configure in `.orchestrator/config.json`**:

```json
{
  "integrations": {
    "replit": {
      "enabled": true,
      "webhookUrl": "https://your-replit-webhook-url"
    }
  }
}
```

4. **Run `tm sync-tickets`** - Ticket Mate will POST a JSON payload to the webhook:

```json
{
  "event": "tickets_synced",
  "projectKey": "YOUR_PROJECT",
  "tickets": [
    {
      "key": "PROJ-123",
      "status": "In Progress",
      "summary": "Implement feature X",
      "url": "https://pamcms.atlassian.net/browse/PROJ-123"
    }
  ],
  "syncedAt": "2025-12-09T22:35:00.000Z"
}
```

### Directory Structure (Multi-Project)

The `.orchestrator` directory uses a project-based structure:

```
.orchestrator/
  config.json              # Global configuration
  projects/
    <projectKey>/
      project.meta.json    # Project metadata
      tickets/
        <ticketKey>/
          ticket.meta.json # Ticket metadata
          plan.md          # High-level plan
          tasks.md         # Task checklist
          progress.log.md  # Progress log
          notes.md         # Free-form notes
```

Each project has its own folder, and tickets are organized within their project. This allows multiple Jira projects to coexist in the same repository.

### Using with AI Agents

AI agents (Cursor, Replit Agent, etc.) should:

1. **Read ticket metadata** from `.orchestrator/projects/<projectKey>/tickets/<ticketKey>/ticket.meta.json`
2. **Follow the plan** in `.orchestrator/projects/<projectKey>/tickets/<ticketKey>/plan.md`
3. **Complete tasks** from `.orchestrator/projects/<projectKey>/tickets/<ticketKey>/tasks.md`
4. **Log progress** in `.orchestrator/projects/<projectKey>/tickets/<ticketKey>/progress.log.md`
5. **Commit changes** with the Jira key in the message (e.g., `feat(PROJ-123): ...`)

Use `tm emit-agent-instructions --agent <agent>` to get specific instructions for your agent.

### Admin UI

Ticket Mate includes admin UI pages for browsing `.orchestrator` content:

- **`/admin/ticket-mate`** - Overview of all projects in `.orchestrator`
- **`/admin/ticket-mate/[projectKey]`** - Ticket list for a specific project
- **`/admin/ticket-mate/[projectKey]/[ticketKey]`** - Detailed ticket view with plan, tasks, progress, and notes

These pages read directly from the `.orchestrator` filesystem structure and provide a read-only view of your tickets. All data is sourced from `.orchestrator` on disk, not directly from Jira.

### Best Practices

- **Never delete** user-edited content in `plan.md`, `tasks.md`, or `notes.md`
- **Always append** to `progress.log.md` (never overwrite)
- **Check ticket status** before starting work (only work on "Ready for Dev" or "In Progress")
- **Update task checklists** as you complete items
- **Commit with Jira keys** in commit messages for traceability

## API Integration

The package includes a REST API server. Start it with:

```bash
npm run dev:server
```

#### Authentication

All API routes require authentication via API key. Include it in requests:

```bash
# Using X-API-Key header
curl -H "X-API-Key: your-api-key" http://localhost:3001/api/projects

# Using Authorization header
curl -H "Authorization: Bearer your-api-key" http://localhost:3001/api/projects
```

#### API Endpoints

**Projects**

- `GET /api/projects` - List all accessible Jira projects

**Boards**

- `GET /api/boards?projectKey=NOVA` - List boards for a project

**Automation**

- `POST /api/automation/tickets/from-bugs` - Create tickets from bugs-wip.json
- `POST /api/automation/tickets/from-json` - Create tickets from JSON instructions
- `POST /api/automation/bugs/sync-status` - Sync bug statuses from Jira
- `GET /api/automation/bugs/statistics` - Get bug statistics
- `POST /api/automation/bugs/fix-now` - Process "fix now" bug

**Example Request**

```bash
curl -X POST http://localhost:3001/api/automation/tickets/from-bugs \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{"filePath": "public/bugs.json"}'
```

### Next.js Dashboard

The package includes a Next.js dashboard that provides a web interface for:

- Viewing all Jira projects
- Expanding projects to see their boards
- Direct links to Jira backlog for each board

Start the dashboard:

```bash
npm run dev
```

The dashboard is available at `http://localhost:4000`.

### Automation Features

#### bugs-wip.json Format

The automation system can process JSON files containing bug information:

```json
{
  "bugs": [
    {
      "id": "bug-1",
      "title": "Checkout button not working",
      "category": "bug_report",
      "status": "open",
      "severity": "high",
      "summary": "The checkout button does not respond when clicked",
      "rootCause": "Event listener not attached",
      "metadata": {
        "jiraIssueKey": "NOVA-456",
        "jiraIssueUrl": "https://.../browse/NOVA-456"
      }
    }
  ]
}
```

#### Status Flow

Bugs go through these statuses:

- `open` - New bug, needs ticket
- `sending_to_jira` - Currently being sent to Jira
- `sent_to_jira` - Ticket created in Jira
- `fixed` - Bug is fixed
- `resolved` - Bug is resolved
- `closed` - Bug is closed
- `unfixable` - Bug cannot be fixed
- `fix now` - Priority bug, needs immediate attention

#### Orchestrator Integration

The package can process instructions directly from an orchestrator:

```json
{
  "items": [
    {
      "id": "task-1",
      "title": "Implement feature X",
      "summary": "Add new feature",
      "category": "feature_request",
      "priority": "high"
    }
  ]
}
```

## API Reference

For detailed API documentation, see:

- [API Reference](docs/api-reference.md)
- [Automation Guide](docs/automation/AUTOMATION-GUIDE.md)
- [Host Integration](docs/HOST-PROJECT-INTEGRATION.md)

## Examples

### Sync Tickets to Progress Files

```typescript
import { syncAll, getJiraConfig } from "@ameshkin/ticket-mate";

const config = getJiraConfig();
const result = await syncAll(config, {
  baseDir: "./ticket-mate",
  generateReports: true,
  generateIndex: true,
});

console.log(`Synced ${result.ticketsSynced} tickets`);
```

### Create Jira Tickets from JSON

```typescript
import { processBugsJson } from "@ameshkin/ticket-mate";

const result = await processBugsJson("public/bugs.json", {
  projectKey: "NOVA",
  issueType: "Bug",
  epicKey: "NOVA-10",
  labels: ["automated", "from-json"],
});

console.log(`Created ${result.created} tickets`);
```

### Generate AI Prompts

```typescript
import { buildTicketPrompts } from "@ameshkin/ticket-mate";

const prompts = await buildTicketPrompts({
  ticketKey: "NOVA-123",
  markdownPath: ".orchestrator/epics/NOVA-10/NOVA-123.md",
  repoRoot: process.cwd(),
});

console.log(prompts.systemPrompt);
console.log(prompts.userPrompt);
```

### Create Board with AI Column

```typescript
import {
  createCursorBoard,
  ensureAiInProgressColumn,
} from "@ameshkin/ticket-mate";

const board = await createCursorBoard("NOVA", "Cursor Board");
await ensureAiInProgressColumn(board.id);
console.log(`Board created: ${board.name} (ID: ${board.id})`);
```

## Development

### Setup

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm run test

# Run type checking
npm run typecheck

# Start development server
npm run dev

# Start API server
npm run dev:server

# Start both
npm run dev:all
```

### Project Structure

```
ticket-mate/
├── src/
│   ├── cli/              # CLI commands
│   ├── client/           # Jira REST API client
│   ├── config/           # Configuration management
│   ├── sync/             # Ticket syncing
│   ├── prompts/          # AI prompt generation
│   ├── automation/       # Automation features
│   ├── jira-management/  # Board, label, epic management
│   └── server/           # REST API server
├── app/                  # Next.js dashboard
│   ├── api/              # Next.js API routes
│   └── page.tsx          # Dashboard UI
└── dist/                 # Built output
```

### Testing

```bash
# Run all tests
npm run test

# Run tests in watch mode
npm run test:watch

# Run with coverage
npm run test:coverage

# Run E2E tests
npm run test:e2e
```

## Database Access

### Prisma Studio (Cloud)

Access the database via Prisma Studio Cloud:

**Direct Link:**

- [Prisma Studio Cloud](https://console.prisma.io/cmixzg6nk03vo2sflg2pzq64u/cmixzgvue03sd1efplmdnimkj/cmixzgvue03se1efpm49q18z0/studio#table=notifications&schema=public&view=table)

**How to Access:**

1. Click the link above or navigate to [Prisma Console](https://console.prisma.io)
2. Log in with your Prisma account credentials
3. Select the project: `ticket-mate`
4. Navigate to the database you want to view
5. Use the table browser to explore data

**Note:** You must have access to the Prisma project to view the database. Contact the project owner if you need access.

### Local Prisma Studio

You can also run Prisma Studio locally to view and edit the database:

```bash
# Make sure DATABASE_URL is set in your .env file
npx prisma studio
```

This will open Prisma Studio at `http://localhost:5555` where you can:

- Browse all tables
- View and edit records
- Run queries
- Export data

**Prerequisites:**

- `DATABASE_URL` must be configured in `.env`
- Database must be accessible from your local machine
- Prisma client must be generated: `npm run prisma:generate`

### Database Schema

The database schema is defined in `prisma/schema.prisma`. Key models include:

- **User** - User accounts and authentication
- **Account** - Tenant/organization accounts
- **JiraCredential** - Per-user Jira OAuth credentials
- **TokenUsage** - AI token usage tracking
- **PlanTier** - Subscription plan tiers
- **Project** - Jira project mappings
- **IntegrationConnection** - Third-party integrations

See `prisma/schema.prisma` for the complete schema definition.

## License

MIT

## Author

Amir Meshkin <amir.meshkin@gmail.com>
