npm package: @segosolutions/auto-task
Description: Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude
Author: Sego Solutions
Latest version: 1.7.11

# @segosolutions/auto-task

[![npm version](https://img.shields.io/npm/v/@segosolutions/auto-task.svg)](https://www.npmjs.com/package/@segosolutions/auto-task)
[![npm downloads](https://img.shields.io/npm/dm/@segosolutions/auto-task.svg)](https://www.npmjs.com/package/@segosolutions/auto-task)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org/)
[![Claude Code](https://img.shields.io/badge/Claude%20Code-required-blueviolet.svg)](https://claude.ai/code)

> Automated task processing for [Sego PM](https://sego.pm) - runs Claude locally to process high-confidence tasks in the background.

```
   ____                      _         _            _____         _
  / ___|  ___  __ _  ___    / \  _   _| |_ ___     |_   _|_ _ ___| | __
  \___ \ / _ \/ _` |/ _ \  / _ \| | | | __/ _ \ _____| |/ _` / __| |/ /
   ___) |  __/ (_| | (_) |/ ___ \ |_| | || (_) |_____| | (_| \__ \   <
  |____/ \___|\__, |\___/_/   \_\__,_|\__\___/       |_|\__,_|___/_|\_\
              |___/
```

---

## What Does This Do?

The Sego Auto-Task Monitor watches your Sego PM projects and automatically processes tasks that meet your confidence threshold. When a client submits a request, the monitor:

1. **Detects** new client requests or eligible tasks
2. **Claims** the task (prevents duplicate processing)
3. **Executes** using your local Claude CLI with full project context
4. **Completes** and moves the task to review with detailed output

This means less manual work for you and faster turnaround for your clients.

---

## Prerequisites

> **Important:** The monitor uses the Claude Agent SDK by default. For legacy CLI mode, see the CLI Mode section below.

### Claude Agent SDK (Default)

The Agent SDK is included as a dependency and will be used automatically. No additional installation required.

### Claude Code CLI (Legacy Mode)

If you prefer to use the legacy CLI subprocess mode, install and authenticate:

```bash
# Install globally
npm install -g @anthropic-ai/claude-code

# Authenticate (opens browser)
claude auth login

# Verify it works
claude --version

# Run monitor in CLI mode
sego-auto-task --use-cli-mode
```

> **Note:** Claude Code requires an Anthropic account with API access.

### Sego PM API Key (Required)

Generate an API key from your [Developer Settings](https://sego.pm/developer/api-keys) in Sego PM.

---

## Quick Start

Get up and running in under 5 minutes:

```bash
# Step 1: Install globally
npm install -g @segosolutions/auto-task

# Step 2: Run the interactive setup wizard
sego-auto-task init

# Step 3: Start monitoring (that's it - smart defaults handle the rest!)
sego-auto-task
```

That's it! The monitor will now process eligible tasks automatically.

### Smart Defaults

When you run `sego-auto-task` with a configured `.env` file, intelligent defaults are applied:

- **Agent SDK** is used by default (no `--use-agent-sdk` flag needed)
- **Stream progress** is enabled by default (real-time updates in web UI)
- **SSE/real-time mode** is enabled when `PROJECT_ID` is set
- **Auto-commit/push** are disabled by default for safety

The startup banner shows the source of each setting (`[cli]`, `[env]`, or `[default]`) so you always know where your configuration comes from.

### One-Liner (For the impatient)

```bash
npm i -g @segosolutions/auto-task && sego-auto-task init
```

---

## Installation

### NPM Global (Recommended)

```bash
npm install -g @segosolutions/auto-task
```

After installation, the `sego-auto-task` command is available globally.

### NPX (No Install)

Run without installing:

```bash
npx @segosolutions/auto-task --help
```

### Yarn Global

```bash
yarn global add @segosolutions/auto-task
```

### PNPM Global

```bash
pnpm add -g @segosolutions/auto-task
```

### Project Local (Dev Dependency)

Install as a dev dependency for project-specific use:

```bash
npm install --save-dev @segosolutions/auto-task

# Run via npx
npx sego-auto-task
```

---

## Configuration

### Interactive Setup (Recommended)

The easiest way to configure is the setup wizard:

```bash
sego-auto-task init
```

This will:
- Prompt for your API key
- Validate the connection
- Optionally set a project filter
- Save configuration to `.env`

### Non-Interactive Setup

For CI/CD or scripted setups:

```bash
SEGO_API_KEY=sk_live_xxx sego-auto-task init --yes
```

### Environment Variables

Create a `.env` file in your project directory (or use `sego-auto-task init`):

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SEGO_API_KEY` | Yes | - | Your Sego PM API key |
| `SEGO_API_URL` | No | `https://sego.pm` | API endpoint URL |
| `SEGO_PROJECT_ID` | No | All projects | Filter to a specific project |
| `SEGO_WORKING_DIR` | No | Current directory | Working directory for Claude |
| `USE_CLI_MODE` | No | `false` | Use legacy CLI subprocess instead of Agent SDK |
| `STREAM_PROGRESS` | No | `true` | Stream agent progress events to the web app |
| `CONVERSATION_ONLY` | No | `false` | Only handle conversations, skip auto-tasks |
| `AUTO_COMMIT` | No | `false` | Automatically commit changes after task completion |
| `AUTO_PUSH` | No | `false` | Automatically push commits to remote (requires AUTO_COMMIT) |

**Example `.env` file:**

```bash
# Required
SEGO_API_KEY=sk_live_your_key_here

# Optional
SEGO_API_URL=https://sego.pm
SEGO_PROJECT_ID=proj_abc123
SEGO_WORKING_DIR=/path/to/project

# Feature flags
STREAM_PROGRESS=true     # Stream progress events to web app (default: true)
CONVERSATION_ONLY=false  # Only process conversations, skip auto-tasks
AUTO_COMMIT=false        # Automatically commit changes after task completion
AUTO_PUSH=false          # Automatically push commits to remote
```

### CLI Options

All options can be passed via command line (overrides environment variables):

| Option | Description | Default |
|--------|-------------|---------|
| `--api-key <key>` | Sego PM API key | `$SEGO_API_KEY` |
| `--api-url <url>` | Sego PM API URL | `https://sego.pm` |
| `--project-id <id>` | Filter to specific project | All projects |
| `--poll <seconds>` | Poll interval for checking tasks | `30` |
| `--timeout <minutes>` | Task processing timeout | `10` |
| `--client-request-timeout <minutes>` | Client request analysis timeout | `2` |
| `--no-sse` | Disable real-time SSE mode | SSE enabled |
| `--dry-run` | Check for tasks without processing | `false` |
| `--use-cli-mode` | Use legacy CLI subprocess instead of Agent SDK | `false` |
| `--no-stream-progress` | Disable streaming progress events to the web app | Streaming enabled |
| `--conversation-only` | Only handle conversational sessions, skip auto-task processing | `false` |
| `--auto-commit` | Automatically commit changes after task completion | `false` |
| `--auto-push` | Automatically push commits to remote (requires --auto-commit) | `false` |
| `--working-dir <path>` | Working directory for Claude | Current directory |
| `--no-update-check` | Skip update check on startup | Check enabled |
| `-V, --version` | Show version number | |
| `-h, --help` | Show help | |

---

## Usage Examples

### Basic Usage

```bash
# Start with default settings (uses .env)
sego-auto-task

# Use inline API key
sego-auto-task --api-key=sk_live_xxx
```

### Development Mode

```bash
# Connect to local Sego PM instance
sego-auto-task --api-url=http://localhost:3000

# Test without processing (see what would be processed)
sego-auto-task --dry-run
```

### Project-Specific Monitoring

```bash
# Only monitor a specific project
sego-auto-task --project-id=cmiursa7x0001qptpaehaq7hg
```

### Custom Timeouts

```bash
# Longer timeout for complex tasks (30 minutes)
sego-auto-task --timeout=30 --client-request-timeout=5

# Faster polling (check every 15 seconds)
sego-auto-task --poll=15
```

### Polling Only (No Real-time)

```bash
# Disable SSE, rely only on polling
sego-auto-task --no-sse --poll=60
```

### Conversation Only (No Auto-Task Processing)

```bash
# Only handle conversational chat sessions, skip automatic task processing
sego-auto-task --conversation-only --project-id=cmiursa7x0001qptpaehaq7hg

# This mode will:
# - Process conversational sessions (chat back-and-forth)
# - Skip non-conversational client request analysis
# - Skip automatic backlog task processing
# - Skip polling for eligible tasks
```

---

## How It Works

The monitor runs in hybrid mode combining real-time and polling:

### SSE Mode (Real-time)

- Listens for client request events via Server-Sent Events
- Processes new requests immediately as they arrive
- Requires `--project-id` for targeted monitoring

### Polling Mode (Batch)

- Checks every 30 seconds (configurable) for eligible tasks
- Processes tasks where:
  - Project has auto-task enabled
  - Task is in `BACKLOG` status
  - Task's AI confidence >= project threshold

### Processing Flow

```
New Request/Task Found
        |
        v
   Claim Task (mark IN_PROGRESS)
        |
        v
   Run Claude Agent SDK with project context
        |
        v
   Complete (move to IN_REVIEW)
        |
        v
   Post results as task comment
```

> **Note:** The monitor uses the Agent SDK by default for execution. Use `--use-cli-mode` to switch to the legacy CLI subprocess mode.

---

## Project Configuration (Sego PM)

Enable auto-task processing for your project in Sego PM:

### Via Web UI

1. Go to your project settings
2. Enable "Auto-Task Processing"
3. Set your confidence threshold (recommended: 0.85)

### Via API

```bash
curl -X PATCH https://sego.pm/api/mcp/projects/{projectId}/auto-task \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"enabled": true, "confidenceThreshold": 0.85}'
```

---

## Running as a Service

### Using PM2 (Recommended)

```bash
# Install PM2
npm install -g pm2

# Start the monitor as a daemon
pm2 start sego-auto-task --name "sego-monitor" -- --api-key=sk_live_xxx

# View logs
pm2 logs sego-monitor

# Auto-restart on reboot
pm2 save
pm2 startup
```

### Using systemd (Linux)

Create `/etc/systemd/system/sego-auto-task.service`:

```ini
[Unit]
Description=Sego Auto-Task Monitor
After=network.target

[Service]
Type=simple
User=your-user
WorkingDirectory=/path/to/your/project
Environment=SEGO_API_KEY=sk_live_...
ExecStart=/usr/local/bin/sego-auto-task
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

Then enable and start:

```bash
sudo systemctl enable sego-auto-task
sudo systemctl start sego-auto-task
sudo systemctl status sego-auto-task
```

### Using launchd (macOS)

Create `~/Library/LaunchAgents/com.segosolutions.auto-task.plist`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.segosolutions.auto-task</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/sego-auto-task</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>SEGO_API_KEY</key>
        <string>sk_live_...</string>
    </dict>
    <key>WorkingDirectory</key>
    <string>/path/to/your/project</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/sego-auto-task.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/sego-auto-task.err</string>
</dict>
</plist>
```

Then load:

```bash
launchctl load ~/Library/LaunchAgents/com.segosolutions.auto-task.plist
```

### Using Docker

```dockerfile
FROM node:20-alpine

# Install Claude CLI and auto-task
RUN npm install -g @anthropic-ai/claude-code @segosolutions/auto-task

# Set working directory
WORKDIR /app

# Environment variables (or mount .env)
ENV SEGO_API_KEY=sk_live_...

CMD ["sego-auto-task"]
```

Build and run:

```bash
docker build -t sego-auto-task .
docker run -d --name sego-monitor sego-auto-task
```

---

## Troubleshooting

### "Claude Agent SDK is not available"

The monitor uses the Agent SDK by default. This is bundled with the package, so this error is rare. If you encounter it:

1. Reinstall the package: `npm install -g @segosolutions/auto-task`
2. Or use legacy CLI mode: `sego-auto-task --use-cli-mode`

### "Claude CLI is not available" (Legacy Mode)

If using `--use-cli-mode`, the Claude Code CLI must be installed and authenticated:

```bash
# Install Claude CLI
npm install -g @anthropic-ai/claude-code

# Authenticate with Anthropic
claude auth login

# Verify installation
claude --version
```

If you see permission errors, try:

```bash
sudo npm install -g @anthropic-ai/claude-code
```

Or fix npm permissions (recommended for macOS/Linux):

```bash
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc  # or ~/.zshrc
source ~/.bashrc
```

### "API key is required"

Set your API key via one of these methods:

```bash
# Option 1: Environment variable
export SEGO_API_KEY=sk_live_your_key

# Option 2: CLI flag
sego-auto-task --api-key=sk_live_your_key

# Option 3: .env file
echo "SEGO_API_KEY=sk_live_your_key" > .env

# Option 4: Interactive setup
sego-auto-task init
```

### "Invalid API key or unable to connect"

1. **Verify your API key is correct and not expired**

2. **Check network connectivity:**
   ```bash
   curl -I https://sego.pm
   ```

3. **Test API authentication:**
   ```bash
   curl -H "Authorization: Bearer sk_live_..." https://sego.pm/api/mcp/tasks
   ```

4. **For local development**, ensure `--api-url` points to your local server:
   ```bash
   sego-auto-task --api-url=http://localhost:3000
   ```

### Tasks Not Being Processed

Check these common causes:

1. **Project settings:** Auto-task must be enabled for the project in Sego PM

2. **Task status:** Task must be in `BACKLOG` status

3. **Confidence threshold:** Task's AI confidence must meet or exceed the project threshold

4. **Test with dry-run:**
   ```bash
   sego-auto-task --dry-run
   ```
   This shows what tasks would be processed without actually processing them.

5. **Check the console output** for any error messages or skipped tasks

### SSE Connection Issues

If real-time events aren't working:

1. **Ensure `--project-id` is set** (required for SSE mode):
   ```bash
   sego-auto-task --project-id=your_project_id
   ```

2. **Check that the API URL supports SSE**

3. **Try disabling SSE** to use polling only:
   ```bash
   sego-auto-task --no-sse
   ```

### Monitor Keeps Stopping

If the monitor exits unexpectedly:

1. **Check logs for error messages**

2. **Increase timeout** for long-running tasks:
   ```bash
   sego-auto-task --timeout=30
   ```

3. **Use PM2** for automatic restarts:
   ```bash
   pm2 start sego-auto-task --name sego --restart-delay=5000
   ```

### Permission Errors on macOS

If you get permission errors during global install:

```bash
# Fix npm permissions (recommended)
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
source ~/.zshrc

# Then reinstall
npm install -g @segosolutions/auto-task
```

### "Command not found: sego-auto-task"

The npm global bin directory may not be in your PATH:

```bash
# Find where npm installs global packages
npm config get prefix

# Add to PATH (adjust path as needed)
export PATH="$(npm config get prefix)/bin:$PATH"

# Make permanent
echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.bashrc
```

---

## Development

Want to contribute or run from source?

### Setup

```bash
# Clone the repository
git clone https://github.com/nickgs/sego-pm.git
cd sego-pm/auto-task-monitor

# Install dependencies
pnpm install

# Run in development mode
pnpm dev -- --api-key=sk_dev_xxx

# Type check
pnpm typecheck

# Build for production
pnpm build
```

### Project Structure

```
auto-task-monitor/
├── src/
│   ├── index.ts          # CLI entry point
│   ├── monitor.ts        # Main monitor logic
│   ├── claude-runner.ts  # Claude CLI integration
│   ├── config.ts         # Configuration loading
│   ├── init.ts           # Setup wizard
│   └── version-check.ts  # Update notifications
├── dist/                 # Built output
├── package.json
└── README.md
```

### Testing Locally

```bash
# Run with local API
pnpm dev -- --api-url=http://localhost:3000 --dry-run

# Build and test the built version
pnpm build
node dist/index.cjs --help
```

---

## Changelog

### v1.4.0

- **Smart defaults**: Agent SDK and stream progress enabled by default
- **Auto-commit/push**: Automatically commit and push changes after task completion
- **Config source tracking**: Startup banner shows where each setting comes from (`[cli]`, `[env]`, `[default]`)
- New CLI flags: `--auto-commit`, `--auto-push`, `--no-stream-progress`
- New env vars: `AUTO_COMMIT`, `AUTO_PUSH`, `STREAM_PROGRESS`
- Replaced `--use-agent-sdk` with `--use-cli-mode` (legacy mode)

### v1.0.1

- Fixed repository URLs in package.json
- Improved error messages

### v1.0.0

- Initial release
- SSE and polling hybrid mode
- Interactive setup wizard
- Automatic update checks
- Claude CLI integration

---

## FAQ

### How does this differ from processing tasks in the Sego PM web UI?

The auto-task monitor runs Claude **locally** on your machine, using your local codebase context. This means:
- Claude has access to your full project files
- Processing happens on your hardware
- No additional API costs beyond your existing Claude subscription

### What confidence threshold should I use?

We recommend starting with **0.85** (85%). This ensures only well-understood tasks are automatically processed. You can lower it as you gain confidence in the system.

### Can I run multiple monitors?

Yes, but only one monitor should process each project to avoid conflicts. Use `--project-id` to assign different projects to different monitors.

### Does this work with self-hosted Sego PM?

Yes! Use `--api-url` to point to your self-hosted instance:

```bash
sego-auto-task --api-url=https://your-sego-instance.com
```

### How do I stop the monitor?

Press `Ctrl+C` for graceful shutdown, or:

```bash
# If using PM2
pm2 stop sego-monitor

# If using systemd
sudo systemctl stop sego-auto-task
```

---

## Support

- **Documentation:** [https://sego.pm/docs](https://sego.pm/docs)
- **Issues:** [GitHub Issues](https://github.com/nickgs/sego-pm/issues)
- **Email:** [hello@segosolutions.com](mailto:hello@segosolutions.com)

---

## License

MIT - see [LICENSE](./LICENSE)

---

<p align="center">
  Built with Claude by <a href="https://segosolutions.com">Sego Solutions</a>
</p>