Metadata-Version: 2.4
Name: codedd-cli
Version: 0.1.11
Summary: CLI tool for CodeDD — run code audits from your terminal
License: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: code-audit,security,cli,codedd
Author: CodeDD
Author-email: info@codedd.ai
Requires-Python: >=3.10,<4.0
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Provides-Extra: esprima
Requires-Dist: defusedxml (>=0.7.1)
Requires-Dist: esprima (>=4.0.0) ; extra == "esprima"
Requires-Dist: httpx (>=0.27.0)
Requires-Dist: keyring (>=25.0.0)
Requires-Dist: langgraph (>=0.2.0)
Requires-Dist: lizard (>=1.17.0)
Requires-Dist: pyyaml (>=6.0.0)
Requires-Dist: radon (>=6.0.0)
Requires-Dist: rich (>=13.0.0)
Requires-Dist: tomli (>=2.0.0) ; python_version < "3.11"
Requires-Dist: tomli-w (>=1.0.0)
Requires-Dist: typer (>=0.9.0)
Project-URL: Homepage, https://codedd.ai
Project-URL: Repository, https://gitlab.com/codedd1/codedd-cli
Description-Content-Type: text/markdown

# CodeDD CLI

[![PyPI](https://img.shields.io/pypi/v/codedd-cli)](https://pypi.org/project/codedd-cli/)
[![Python](https://img.shields.io/pypi/pyversions/codedd-cli)](https://pypi.org/project/codedd-cli/)
[![License](https://img.shields.io/pypi/l/codedd-cli)](LICENSE)

**Run code audits from your terminal.** The CodeDD CLI runs a [CodeDD](https://codedd.ai) audit on your own machine, with your own LLM API keys. Source files stay local; CodeDD receives findings and metrics for consolidation, recommendations, and dashboards.

---

## What is CodeDD CLI?

CodeDD CLI is the official command-line interface for the CodeDD platform. You:

- **Define scope** — Add one or more local Git repository roots to an audit.
- **Run analysis locally** — File audits, vulnerability validation, complexity, dependencies, git history, and architecture are analysed on your machine.
- **Sync to CodeDD** — Findings and metrics are submitted to CodeDD, where consolidation, dependency enrichment, security scoring, and recommendations run on the server.

Built for teams that want CodeDD’s analytics, recommendations, and reporting without handing over their source code.

---

## What leaves your machine

| Data | Stays local | Sent to your LLM provider | Sent to CodeDD |
|------|:-----------:|:-------------------------:|:--------------:|
| Source files | ✓ | Files and snippets under analysis, using **your** API key | — |
| File audit and vulnerability findings | | | ✓ (file paths, line ranges, findings text) |
| Complexity metrics, LoC, file types | | | ✓ |
| Dependencies (manifests, lockfiles, imports) | | | ✓ (package names and versions) |
| Git statistics | | | ✓ (commit history metadata, author names) |
| Architecture components and relationships | | Optional LLM enhancement | ✓ |
| CLI token, LLM API keys | ✓ (OS keychain or environment) | | — |

Run `codedd audit start --show` to review what is sent to CodeDD. You choose whether the audit pauses once per stage (file results, security validation, complexity, dependencies, git statistics, cross-repo evidence, architecture) or before every request and batch. Either way, every payload is saved as JSON under `~/.codedd/transparency/<audit>/<run>/`, with an `index.md` listing each request, so you can check all batches afterwards. Declining a payload stops the audit before it is sent; run `codedd audit start` again to resume.

---

## Features

- **Scope management** — Add/remove local directories, sync with CodeDD, detect changes and re-confirm scope (delta updates). Removing a repo from local scope also attempts a best-effort removal of the matching repository on CodeDD.
- **Local file auditing** — LLM-based file analysis using your Anthropic, OpenAI, Google Gemini, or xAI Grok API key, with batching, configurable concurrency, and progress feedback.
- **Vulnerability validation** — Candidate findings are checked by an agentic LLM pipeline that reads the surrounding code, traces reachability, and looks for existing mitigations. Uses [Semgrep](https://semgrep.dev) when it is installed.
- **Complexity analysis** — Cyclomatic complexity, Halstead, and maintainability metrics (Radon/Lizard).
- **Dependency scanning** — Lockfile/manifest and import parsing; CodeDD enriches the results with vulnerability and licence data.
- **Git statistics** — Commit history and repository activity for team and delivery metrics.
- **Architecture analysis** — Local component and relationship extraction, technology detection, and cross-repository evidence for group audits.
- **Resumable audits** — Progress is checkpointed; an interrupted `codedd audit start` resumes where it stopped.
- **Issue remediation (`codedd fix`)** — Work through audit flags and dependency vulnerabilities from the terminal, by priority, per repository, or from an Issue Compass saved list. Built for interactive use and AI-agent loops (`context`, `summarize`, `--json`, exit codes).
- **Payment and budget** — Pre-flight checks, LoC budget deduction, or Stripe checkout when additional payment is required.
- **Secure auth** — Tokens and keys stored in the OS credential store (Windows Credential Locker, macOS Keychain, Linux Secret Service), or supplied through environment variables.

---

## Installation

### Requirements

- **Python 3.10–3.13**
- A [CodeDD](https://codedd.ai) account and a CLI token (Account → CLI Access → Generate Token)
- An API key for at least one LLM provider (Anthropic, OpenAI, Google Gemini, or xAI Grok)
- Optional: [Semgrep](https://semgrep.dev/docs/getting-started/) on your `PATH` for additional vulnerability evidence

### Install

```bash
pip install codedd-cli
```

Or as an isolated tool:

```bash
uv tool install codedd-cli
# or: pipx install codedd-cli
```

Verify:

```bash
codedd --version
```

On Linux, the OS credential store needs a Secret Service provider such as gnome-keyring or KWallet (typically present on desktop environments). Headless servers, containers, and CI runners generally do not; use environment variables instead of `codedd auth login` / `codedd config set-key` (see [Environment variables](#environment-variables)).

### Upgrade and uninstall

```bash
pip install -U codedd-cli       # or: uv tool upgrade codedd-cli / pipx upgrade codedd-cli
pip uninstall codedd-cli        # or: uv tool uninstall codedd-cli / pipx uninstall codedd-cli
```

If `codedd --version` shows an older version than you installed, another copy is earlier on your `PATH` (`where codedd` on Windows, `which -a codedd` on macOS/Linux).

---

## Quick start

### 1. Authenticate once

Generate a CLI token at [codedd.ai](https://codedd.ai) (Account → CLI Access), then:

```bash
codedd auth login --token <your_token>
```

Or run `codedd auth login` and paste the token when prompted. Check with `codedd auth status`.

On headless Linux or in CI, skip login and export `CODEDD_API_TOKEN` instead (see [Environment variables](#environment-variables)).

### 2. Select the audit

```bash
codedd audits list
codedd audits select
```

Choose a **group audit** (multiple repos) or a **single audit** (one repo). The selected audit is the active context for all `scope` and `audit` commands.

### 3. Define local scope

Add the local paths that correspond to the repositories in that audit (each path must be a Git repository root with commits):

```bash
codedd scope add /path/to/my-repo
codedd scope list
codedd scope confirm
```

`scope confirm` scans paths, file types, and LoC, and registers scope with CodeDD.
If files change later, `codedd audit start` detects the drift and asks you to re-confirm.

### 4. Configure an LLM key

```bash
codedd config set-key anthropic
# or: openai | gemini | grok
```

Alternatively, export a provider key (see [Environment variables](#environment-variables)). Environment variables take precedence over the keychain.

With more than one key configured, `codedd config provider both` uses them in fallback order.

### 5. Start the audit

```bash
codedd audit start
```

What `codedd audit start` does, in order:

```text
A. Scope sync      -> re-confirm prompt if local files changed
B. Pre-flight      -> checks audit status, payment, and budget on CodeDD
C. Payment         -> budget deduction or browser checkout
D. Local analysis  -> file audit (LLM), vulnerability validation, complexity,
                      dependencies, git stats, architecture
E. Submission      -> structured results to CodeDD (retries on transient errors)
F. Completion      -> server-side consolidation and recommendations
```

Follow progress with `codedd audit status --watch`. Results and recommendations appear in the CodeDD dashboard.

### 6. Fix issues (optional, after the audit completes)

**Group audit** (multiple repos):

```bash
codedd fix status                          # repos ranked by severity
codedd fix repo my-service                 # scope to one repository
codedd fix flags next --auto               # next unresolved flag (red first)
codedd fix resolve --comment "Fixed null check in auth handler"
```

**Single-repo audit:**

```bash
codedd fix fetch flags
codedd fix flags next --auto
codedd fix resolve --comment "Updated lodash to 4.17.21"
```

`codedd fix resolve` records the comment, marks the issue fixed, and prints the next one, so the loop is one command per issue. Repeat until the output shows `QUEUE EMPTY`.

For dependency vulnerabilities, swap `flags` for `vulns` (`codedd fix fetch vulns`, `codedd fix vulns next --auto`, `codedd fix vulns affected-files <package>`).

To work through an Issue Compass saved list from the web UI, run `codedd fix selections list`, then `codedd fix selections use <n>`. Flag commands then use that list’s audit automatically.

Without a saved list, filter the flag queue from the terminal. `codedd fix filter set --preset llm` keeps AI findings that are open or inconclusive and hides AI-invalidated, resolved and user-invalidated ones; `--preset llm-validated` also hides findings the AI never validated. `codedd fix flags list` shows the filtered queue without advancing it, and `codedd fix resolve <uuid>` closes any listed flag directly.

---

## Costs

- **CodeDD** — Audits run through the CLI are billed like any CodeDD audit, by lines of code in scope. `codedd audit start` checks your budget before any analysis runs and offers checkout if more is needed.
- **LLM provider** — Model usage is billed by your provider to the API key you configure. `codedd config concurrency <n>` controls how many requests run in parallel, not the total volume.
- The CLI itself is free.

---

## Commands reference

Every command supports `--help`.

### Authentication

| Command | Description |
|--------|-------------|
| `codedd auth login` | Log in with a CLI token (prompt or `--token`) |
| `codedd auth logout` | Clear stored credentials |
| `codedd auth status` | Show current account and token state |

### Audits

| Command | Description |
|--------|-------------|
| `codedd audits list` | List audits (`--type single\|group`, `--limit`, `--page`) |
| `codedd audits select [uuid]` | Set active audit (interactive if UUID omitted) |

### Scope

| Command | Description |
|--------|-------------|
| `codedd scope add <path> [path ...]` | Add Git repository root(s) to the active audit’s scope |
| `codedd scope remove <n> [--yes]` | Remove directory by list number; if it is registered on CodeDD, the repository is also deleted there (irreversible) after confirmation (`--yes` skips the prompt; non-interactive runs without `--yes` update local scope only) |
| `codedd scope list` | List directories in scope |
| `codedd scope clear` | Remove all directories from scope |
| `codedd scope status` | Show scope and sync state per directory |
| `codedd scope confirm` | Scan, preview, and register scope with CodeDD |
| `codedd scope sync` | Compare local vs CodeDD and show changes |

### Audit execution

| Command | Description |
|--------|-------------|
| `codedd audit start` | Sync scope, run pre-flight and payment, then run the local audit and submit to CodeDD |
| `codedd audit status [--watch] [--interval N]` | Show pipeline progress for an active or resumable audit; `--watch` polls until it completes |

`codedd audit start` options:

| Option | Effect |
|--------|--------|
| `--yes` | Auto-confirm prompts (CI) |
| `--skip-sync` | Skip the scope sync check |
| `--show` | Review payloads sent to CodeDD; asks whether to pause once per stage or at every request (see [What leaves your machine](#what-leaves-your-machine)) |
| `--show-interactive` | Like `--show`, but pause before every request and batch without asking |
| `--show-force-interactive` | With `--show-interactive`, skip the offer to switch to per-stage review on large audits |
| `--debug-llm` | Print LLM request/response debug output |
| `--debug-llm-full-prompt` | Include the full system prompt in `--debug-llm` output (sensitive) |

### Issue remediation (`codedd fix`)

Requires a completed audit with remediation data on CodeDD.

| Command | Description |
|--------|-------------|
| `codedd fix status [--json]` | Dashboard of open flags/vulns; repos ranked by severity in group audits |
| `codedd fix repo [name\|uuid]` | Scope the fix workflow to one repository (group audits) |
| `codedd fix fetch flags\|vulns` | Load the issue overview (interactive repository pick when needed) |
| `codedd fix flags next [--auto] [--json]` | Next unresolved flag; `--auto` prioritises red issues |
| `codedd fix flags list [--preset P] [--status S] [--all] [--json]` | Read-only list of flags in queue order, with counts per source, status and type |
| `codedd fix flags show <uuid> [--json]` | Full detail and fix kit for one flag, without loading it into the session |
| `codedd fix filter set\|show\|clear` | Filter flag commands by `--source`, `--status` (`open`, `validated`, `not-validated`, `inconclusive`, `ai-invalid`, ...), `--type`, `--color` or a `--preset` (`llm`, `llm-validated`, `llm-security`, `llm-closed`, `sonar`) |
| `codedd fix flags invalidate [<uuid>] [--reason "<text>"]` | Mark the current (or given) flag invalid and advance |
| `codedd fix vulns next [--auto] [--severity S] [--used-only] [--json]` | Next vulnerability; `--auto` prioritises critical |
| `codedd fix vulns affected-files <package> [--json]` | List local files importing a vulnerable package |
| `codedd fix resolve [<uuid>] [--comment "<text>"] [--commit <ref>]` | Record progress, mark the current (or given) issue resolved, and print the next one; `--commit` links the fix to a commit |
| `codedd fix comment "<text>" [--target <uuid>]` | Record progress without resolving |
| `codedd fix context [--json]` / `summarize` | Session snapshot for AI agents |
| `codedd fix selections list\|show\|use\|clear` | Issue Compass saved flag lists from the web UI |
| `codedd fix access status\|enable\|disable` | Remediation access (organisation initiator) |

Comment text can also be supplied with `--comment-file <path>` or on stdin (`codedd fix comment -`), which avoids shell quoting for multi-line notes.

**Exit codes** (for scripts and AI-agent loops): `0` issue delivered or action succeeded, `1` error, `3` no unresolved issues left in the current scope. Commands that deliver an issue also print a loop protocol block — remaining count, the exact next command, and the stop condition — so long remediation runs do not depend on instructions surviving in an agent’s context window.

### Configuration

| Command | Description |
|--------|-------------|
| `codedd config show` | Show current config (API URL, active audit, scope, etc.) |
| `codedd config set <key> <value>` | Set a config value |
| `codedd config set-key [anthropic\|openai\|gemini\|grok]` | Store an LLM API key in the OS keychain |
| `codedd config show-keys` | List which providers have keys configured (not the keys themselves) |
| `codedd config remove-key <provider>` | Remove a stored LLM API key |
| `codedd config provider [anthropic\|openai\|gemini\|grok\|both]` | Set the preferred LLM provider |
| `codedd config concurrency <n>` | Max concurrent LLM requests (1–75, default 4) |

### AI agents

| Command | Description |
|--------|-------------|
| `codedd ai-docs` | Print the full reference for AI coding agents: authentication, audit workflow, the remediation loop, JSON output, and error recovery |

Point an agent at `codedd ai-docs` before it runs `codedd fix` so it follows the loop protocol and exit codes.

---

## Configuration

- **Config file:** `~/.codedd/config.toml`. Stores API URL, active audit, scope directories, LLM provider, and concurrency. Owner-only permissions where supported.
- **Secrets:** On desktop, the CLI token and LLM API keys are stored in the system keychain, not in the config file. On headless systems, supply them through environment variables; the CLI does not write secrets to disk.

Optional `[audit]` keys (defaults shown) tune how long the CLI waits after opening a payment browser flow:

- `payment_poll_interval_seconds` (default `5`)
- `payment_poll_max_wait_seconds` (default `600`)

### Environment variables

| Variable | Purpose |
|---------|---------|
| `CODEDD_API_TOKEN` | CLI token (for CI or headless Linux). Takes precedence over a stored keyring token. |
| `CODEDD_ANTHROPIC_API_KEY` / `ANTHROPIC_API_KEY` | Anthropic API key. `CODEDD_*` wins if both are set. |
| `CODEDD_OPENAI_API_KEY` / `OPENAI_API_KEY` | OpenAI API key. |
| `CODEDD_GEMINI_API_KEY` / `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Google Gemini API key. |
| `CODEDD_GROK_API_KEY` / `XAI_API_KEY` / `GROK_API_KEY` | xAI Grok API key. |

Headless / CI example:

```bash
export CODEDD_API_TOKEN=codedd_cli_...
export ANTHROPIC_API_KEY=sk-ant-...
codedd audit start --yes
```

---

## Troubleshooting

| Symptom | Fix |
|---------|-----|
| Keyring / credential-store error on Linux | No Secret Service provider is running. Use `CODEDD_API_TOKEN` and a provider key environment variable instead. |
| “No active audit selected” | Run `codedd audits select`. For flag remediation, `codedd fix selections use <n>` also works. |
| Audit was interrupted | Run `codedd audit start` again; completed stages are skipped. `codedd audit status` shows where it stopped. |
| Scope drift prompt on every run | Files changed since `scope confirm`. Confirm the new scope, or use `--skip-sync` if the change is intentional and already registered. |
| `codedd --version` shows an old version | Another install is earlier on your `PATH`; see [Upgrade and uninstall](#upgrade-and-uninstall). |
| Garbled symbols in the Windows console | Update to the latest CLI (it switches the console to UTF-8), or set `PYTHONIOENCODING=utf-8`. |

---

## Security

- Tokens and LLM keys are kept in the OS credential store or environment variables, never in plaintext on disk.
- TLS certificate verification is always enabled for API requests.
- The config file and `~/.codedd` directory use owner-only permissions where supported.
- Tokens expire after 90 days (server-configurable); generate a new one from the CodeDD dashboard.

Report security issues to [info@codedd.ai](mailto:info@codedd.ai) rather than in public issues.

---

## Development

```bash
poetry install --with dev
poetry run pytest
poetry run ruff check .
```

---

## License

Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).

---

## Support

- **Issues:** [GitLab Issues](https://gitlab.com/codedd1/codedd-cli/-/work_items)
- **Product:** [CodeDD](https://codedd.ai)

