# Context Platform CLI

Typer-powered command-line interface for managing Context Platform projects and items.

> **Note:** Both `ctx` and `ctxme` commands are available. They are identical - use whichever you prefer. Examples below use `ctx`.

## Installation

From the repo root (uv workspace):

```bash
uv sync --all-extras --all-groups
```

`ctx` will then be available via `uv run ctx ...` (or activate `.venv` and call directly).

## Configuration

The CLI stores settings under the platform-specific config directory (see `platformdirs`). Override
the path in scripts/tests with the `CTXME_CONFIG_DIR` environment variable.

Key commands:

- `ctx config --api <url>` – set the backend API base URL (switches to live mode)
- `ctx config --mode mock|live` – toggle between the built-in mock client and HTTP client
- `ctx set-project <project>` – set the default project key
- `ctx auth login` – device flow sign-in (opens browser, stores API key in keychain)
- `ctx auth status` – show stored API key prefix + backend metadata
- `ctx auth set-key <key>` – manually persist API keys using the OS keychain
- `ctx auth logout` – remove stored API key

API keys are **never** written to disk; only stored through `keyring`.

For local development, you can set `CLI__API_KEY` to override the keychain without
modifying OS credentials. This value is read from the **process environment only**
(not from `.env` files) and is visible in process listings, so use it for local
testing only.

## Commands

- `ctx ls` – list items for the default (`set-project`) or `--project` project
- `ctx get <item>` – download an item to the current directory (file items use original filename; `--stdout`/`--clipboard` only for text MIME types)
- `ctx put <item> --data "<text>"` – create or update an item (`--title`, `--tag` optional)
- `ctx put <item> --file <path>` – upload a file as a context item
- `ctx remove <item>` – delete an item (use `--force` to skip confirmation)
- `ctx search <query>` – search for items (see Search Modes below)
- `ctx projects list` / `ctx projects ls` – list available projects
- `ctx projects current` – show the current default project (local only)
- `ctx set-project <project>` – set the default project key
- `ctx status` – show local config + auth status (no API call)

All commands emit Rich-formatted tables/panels with user-friendly messaging.

### Search Modes

The `search` command intelligently determines which projects to search based on your configuration:

1. **Explicit project search** (using `--project` flag):

   ```bash
   ctx search "machine learning" --project my-research
   ```

   Searches only the specified project.

2. **Default project search** (when default project is set):

   ```bash
   ctx set-project my-main-project
   ctx search "API documentation"
   ```

   Searches only your default project.

3. **Implicit all-projects search** (no default project configured):

   ```bash
   # No default project set
   ctx search "kubernetes config"
   # Output: Searching across all projects (no default project set)
   ```

   Automatically searches all projects with an informational message.

4. **Explicit all-projects search** (using `--all` flag):
   ```bash
   ctx search "error handling" --all --limit 20
   ```
   Searches across all projects regardless of default project configuration.

**Note:** The `--project` and `--all` flags are mutually exclusive. Use one or the other, not both.

If you have no projects yet, the search command will prompt you to create one:

```bash
ctx search "test"
# Output: No projects found. Create one with: ctx projects create <name>
```

### Unified Context Items

The CLI uses a unified API that handles both inline text and file uploads:

- **Inline content**: Use `--data` to provide text content directly
- **File uploads**: Use `--file` to upload files (text files and PDFs supported)

When listing items, you'll see:

- `content_type`: Whether the item is `inline` text or a `file`
- `processing_status`: `ready` (searchable), `processing` (being indexed), or `failed`

Example:

```bash
# Create inline item
ctx put my-notes --data "Meeting notes from today"

# Upload a PDF file
ctx put quarterly-report --file ./report.pdf

# List items with processing status
ctx ls
```

#### Polling for Processing Status

When uploading PDFs, processing happens asynchronously. You can poll for completion:

```bash
# Upload a PDF (returns 202 Accepted with processing status)
ctx put my-document --file document.pdf

# Use ctx ls to check processing status
ctx ls
```

Alternatively, rerun `ctx ls` until the status shows `ready` or `failed`.

## Environment Variables

| Variable                      | Description                                                                            |
| ----------------------------- | -------------------------------------------------------------------------------------- |
| `CTXME_DEBUG`                 | Set to `1` to enable debug output (shows API URL, mode, and full tracebacks on errors) |
| `CTXME_CONFIG_DIR`            | Override the default config directory path                                             |
| `CTXME_CACHE_DIR`             | Override the default cache directory path                                              |
| `CTXME_UPDATE_CHECK`          | Set to `0`, `false`, or `no` to disable automatic update checks at startup             |
| `CTXME_UPDATE_CHECK_INTERVAL` | Override the update check interval in seconds (default: 86400 / 24 hours)              |
| `CLI__API_BASE_URL`           | Override the backend API URL (takes precedence over config file)                       |
| `CLI__API_KEY`                | Override the API key (process env only; takes precedence over keychain)                |
| `CLI__DEFAULT_PROJECT`        | Override the default project (takes precedence over config file)                       |
| `CLI__USE_MOCK_CLIENT`        | Set to `true` to use the mock client                                                   |

**Example: Use `CLI__API_KEY` for local testing**

```bash
# Local testing without touching the keychain
export CLI__API_KEY="ctxme_a74558fa64f4a99a5666a47b4954ea99"
export CLI__API_BASE_URL="http://localhost:8000"
uv run ctx ls

# Return to keychain-based auth
unset CLI__API_KEY
```

**Example: View full configuration details**

```bash
CTXME_DEBUG=1 ctx status
# Output:
# API: https://api.example.com
# Mode: live
# Auth: Signed in
# Project: my-project (default)
```

When `ctx get` saves to a directory, it sanitizes item keys into safe filenames (no path
separators or `..`).

## Tests

```bash
uv run pytest cli/tests
```

Tests cover configuration round-trips, keyring helpers (via an in-memory backend), and representative
Typer command flows.

## Shell Completion

Enable tab completion for commands, subcommands, and flags. Works for both `ctx` and `ctxme`.

### Installation

**Bash:**

```bash
ctx --install-completion bash
# or: ctxme --install-completion bash
```

**Zsh:**

```bash
ctx --install-completion zsh
```

**Fish:**

```bash
ctx --install-completion fish
```

**PowerShell:**

```bash
ctx --install-completion powershell
```

### Usage

```bash
ctx <TAB>        # Shows: auth, config, get, ls, put, ...
ctx auth <TAB>   # Shows: login, logout, status, set-key
ctx get --<TAB>  # Shows: --project, --dest, --stdout, --force, ...
```

### Troubleshooting

- Restart shell after installation
- Ensure completion script is sourced in shell config
- Check `ctx --show-completion <shell>` for manual setup
