Metadata-Version: 2.4
Name: ctxme
Version: 0.2.0
Summary: Context Platform CLI
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: click<9.0,>=8.1
Requires-Dist: keyring<25.0,>=24.3
Requires-Dist: httpx<0.29,>=0.28.1
Requires-Dist: packaging<25.0,>=23.0
Requires-Dist: platformdirs<5.0,>=4.2
Requires-Dist: pydantic<3.0,>=2.7
Requires-Dist: pydantic-settings<3.0,>=2.2
Requires-Dist: pyperclip<2.0,>=1.9
Requires-Dist: rich<14.0,>=13.7
Requires-Dist: typer>=0.12
Requires-Dist: typing-extensions<5.0,>=4.9
Provides-Extra: dev
Requires-Dist: pytest<9.0,>=8.3; extra == "dev"
Requires-Dist: pytest-mock<4.0,>=3.12; extra == "dev"

# 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).

## Global Options

- `ctx --version` – show the CLI version and exit
- `ctx --output json <command>` (`-o json`) – emit errors as a machine-parseable JSON envelope instead of Rich-formatted text. This governs **error output only**: successful command output stays in the normal text format. To get JSON for successful output, use the per-command `--json` flag (see [JSON Output](#json-output) below).
- `ctx --install-completion <shell>` / `ctx --show-completion <shell>` – shell completion setup (see [Shell Completion](#shell-completion))

## 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 --default-project <project>` (`-p`) – set the default project key
- `ctx set-project <project>` – set the default project key (same effect as `config --default-project`)
- `ctx current` – show the current default project (local only, no API call)
- `ctx status` – show local config + auth status (no API call)
- `ctx auth login` – device flow sign-in (opens browser, stores API key in keychain). Use `--scopes read,write,admin` to request specific scopes for the issued key (default: `read,write`; requests above your role's ceiling are denied at verification)
- `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

To point the CLI at a different backend, use the environment variables `CLI__API_BASE_URL` and
`CLI__USE_MOCK_CLIENT` (see [Environment Variables](#environment-variables)). `ctx config` also
accepts hidden `--api` and `--mode` flags, but these are **dev-only** options intentionally left
out of `--help`; they are not a supported configuration surface.

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

All commands emit Rich-formatted tables/panels with user-friendly messaging. Most accept
`--project`/`-p` to target a project other than the default, and `--json` for machine-parseable
success output.

### Items

Item commands are available at the top level and, identically, under the `ctx items` group
(`ctx list` ≡ `ctx items list`, etc.).

- `ctx list` – list items for the default (`set-project`) or `--project` project (`--folder`/`-f` to filter by folder, `--recursive`, `--all`, `--limit`, `--sort`, `--order`, `--cursor`/`--no-limit` for pagination)
- `ctx get <item>` – download an item to the current directory (file items use original filename; `--stdout`/`--clipboard` only for text MIME types; `--json --stdout` emits one JSON object with metadata + content)
- `ctx read <item>` – retrieve text content for AI consumption (writes cache metadata by default; `--stdout` prints content only; `--json --stdout` emits one JSON object with metadata + content and skips cache writes; `--max-chars` to limit length)
- `ctx create <item> --data "<text>"` – create or update an inline item (`--title`, `--tag`, `--folder`, `--mime-type` optional; `--force` to overwrite without prompting)
- `ctx create <item> --src <path>` – upload a file as a context item
- `ctx upload <path>` – upload a file as an item (equivalent to `create --src`; `--key`/`-k` to override the derived item key)
- `ctx update <item>` – update item metadata: `--title`, `--mime-type`, `--folder`, and tag operations (`--tag` replaces all tags; `--add-tag`/`--remove-tag`/`--clear-tags` for incremental changes)
- `ctx delete <item>` – delete an item (use `--force` to skip confirmation)
- `ctx search <query>` – search for items (see [Search Modes](#search-modes) below; `--tag` to filter, `--all`/`--limit` for cross-project search)
- `ctx folders` – list folder paths and item counts (`--parent` to list direct children of a folder)
- `ctx mv <item> --folder <path>` – move an item to a folder (empty string `""` moves it to the project root)

Hidden aliases exist for backwards compatibility: `ls` (alias of `list`), `put` (alias of
`create`), `rm` (alias of `delete`), and `up` (alias of `upload`). They work but do not appear
in `--help`; prefer the canonical names.

### Projects

- `ctx projects list` – list available projects (`ctx projects ls` is a hidden alias)
- `ctx projects current` – show the current default project (local only)
- `ctx projects create <name>` – create a new project (`--key`/`-k` for an explicit project key, `--description`/`-d` optional)
- `ctx projects delete <key>` – delete a project (`--yes`/`-y` to skip the confirmation prompt when deleting the default project)

### Auth

- `ctx auth login` – device-flow sign-in (`--scopes` to request specific key scopes, `--no-open-browser` to print the verification URL instead of opening it)
- `ctx auth logout` – remove the stored API key from the keychain
- `ctx auth status` – show current authentication status
- `ctx auth set-key <key>` – store an API key securely in the OS keychain

### Usage

- `ctx usage llm` – list recent LLM invocations for your account (**requires an admin-scoped key**; see `ctx auth login --scopes`). Filters: `--project`, `--since`/`--until` (ISO-8601), `--status`, `--workload`, `--model`, `--limit`, `--cursor` (pagination, requires `--json`)

```bash
# Recent failed LLM calls for one project, as JSON
ctx usage llm --project my-project --status error --json
```

### Wiki

The `ctx wiki` group manages and queries the generated project wiki:

- `ctx wiki status` – show wiki generation state, staleness, and coverage
- `ctx wiki generate` – trigger wiki generation or refresh
- `ctx wiki list` – list wiki pages (`--page-type`, `--include-stale`, `--limit`, `--cursor`)
- `ctx wiki get <slug>` – show a wiki page's content and metadata
- `ctx wiki search <query>` – search wiki pages (`--page-type`, `--include-stale`, `--limit`)
- `ctx wiki query "<question>"` – ask the wiki for a synthesized, cited answer (`--file-back` files novel answers back as new wiki pages, visible to the whole account; `--limit` caps retrieved pages)
- `ctx wiki settings` – show or change wiki settings (`--llm-opt-in`/`--no-llm-opt-in` toggles external LLM processing for the project's wiki)
- `ctx wiki runs` – show wiki maintenance run history (`--status`, `--trigger`, `--limit`, `--cursor`)
- `ctx wiki schema get` – print the wiki schema page body (pipe to a file to edit)
- `ctx wiki schema set [file]` – replace the wiki schema from a file or stdin (ETag-aware conditional write)

```bash
# Generate the wiki, watch progress, then ask it a question
ctx wiki generate
ctx wiki status
ctx wiki query "How does authentication work?"

# Edit the wiki schema
ctx wiki schema get > schema.md
ctx wiki schema set schema.md
```

### Maintenance

- `ctx update-check` – check for newer versions of the CLI (also runs automatically at startup; see `CTXME_UPDATE_CHECK` below)

## JSON Output

There are two distinct JSON mechanisms — they are independent and do not imply each other:

- **Per-command `--json`** – switches a command's **successful** output to machine-parseable JSON
  (e.g. `ctx list --json`, `ctx read <item> --json`). Supported by most commands; see each
  command's `--help`.
- **Global `--output json`** (`-o json`) – switches **error** output to a machine-parseable JSON
  envelope. It does **not** change successful command output; `ctx --output json status` still
  prints the normal text output. Combine both when scripting: `ctx -o json get <item> --json --stdout`.

### Combined JSON + Stdout for `get` and `read`

`ctx get <item> --json --stdout` returns exactly one JSON document to stdout. It includes
item metadata plus a `content` field in the same payload.

Example shape for inline items:

```json
{
  "project_key": "core",
  "item_key": "welcome",
  "title": "welcome",
  "mime_type": "text/plain",
  "tags": [],
  "folder": null,
  "content_type": "inline",
  "content": "..."
}
```

For file items, payload also includes `file_id`, `size`, and `original_filename`.
`content` is included only for text-compatible MIME types (`text/*`, JSON/XML/YAML/JS).
Binary files still follow existing stdout guardrails (for example PDFs without `--text`):
the command fails instead of emitting partial success JSON. In global JSON mode
(`--output json`), this uses the standard JSON error envelope.

`--json --clipboard` remains invalid for `get` and `read`, and `ctx get --json --dest` remains
invalid.

`ctx read <item> --json --stdout` returns a combined, non-cache schema:

```json
{
  "content": "...",
  "chars": 123,
  "truncated": false,
  "project_key": "core",
  "item_key": "welcome",
  "title": "welcome",
  "mime_type": "text/plain",
  "tags": [],
  "folder": null
}
```

`--max-chars` truncation still applies in this mode. Combined-mode `read` intentionally omits
`path`; standalone `ctx read --json` continues to return the cache `path` schema.

## 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 `--src` or `ctx upload` to upload supported files
  (`.txt`, `.md`, `.pdf`, `.docx`, `.csv`, `.tsv`, `.html`)

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 create my-notes --data "Meeting notes from today"

# Upload a file
ctx create quarterly-report --src ./report.docx

# List items with processing status
ctx list
```

### Polling for Processing Status

When uploading files, extraction and indexing happen asynchronously. You can poll for completion:

```bash
# Upload a file (returns processing status)
ctx create my-document --src document.pdf

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

Alternatively, rerun `ctx list` 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 list

# 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, list, create, ...
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
