Metadata-Version: 2.4
Name: codedd-cli
Version: 0.1.10
Summary: CLI tool for CodeDD — run code audits from your terminal
License: MIT
License-File: LICENSE
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 :: MIT 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: 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

**Run code audits from your terminal.** The CodeDD CLI lets you define scope locally, run file-level and complexity analysis on your machine (using your own LLM API keys), and sync results to [CodeDD](https://codedd.ai) 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 (LLM-based) and complexity metrics run on your machine; only metadata and results are sent to CodeDD.
- **Sync to CodeDD** — Scope metadata, audit results, complexity data, dependencies, and architecture are submitted to CodeDD, where consolidation, dependency enrichment, security scoring, and recommendations run on the server.

Ideal for teams who want to keep source code local while still using CodeDD’s analytics, recommendations, and reporting.

---

## 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 from CodeDD when the server still has it registered (with safe fallbacks if the API is unreachable or ambiguous).
- **Local file auditing** — LLM-based file analysis using your Anthropic or OpenAI API keys; supports batching and progress feedback.
- **Complexity analysis** — Cyclomatic complexity and Halstead metrics (Radon/Lizard) run locally and are submitted to CodeDD.
- **Dependency scanning** — Local lockfile/manifest and import parsing; dependency data is sent to CodeDD for vulnerability and license analysis.
- **Architecture analysis** — Local component/relationship extraction with optional LLM enhancement; additional local heuristics infer technologies, coupling, and communication-style signals (aligned with CodeDD payloads). Phase 3 synthesis and storage run on CodeDD.
- **Issue remediation (`codedd fix`)** — Work through audit flags and dependency vulnerabilities from the terminal: fetch overviews, get the next issue by priority, record progress, mark resolved, and scope to a repo or Issue Compass saved list. Designed for interactive use and AI-agent workflows (`context`, `summarize`, `--json`).
- **Payment and budget** — Pre-flight checks, LoC budget deduction, or Stripe checkout when additional payment is required.
- **Secure auth** — CLI tokens stored in the OS credential store (Windows Credential Locker, macOS Keychain, Linux Secret Service).

---

## Installation

### Requirements

- **Python 3.10+** (3.10–3.13 supported; see `pyproject.toml` classifiers)
- A [CodeDD](https://codedd.ai) account and a CLI token (Account → CLI Access → Generate Token)

### From source (development)

```bash
git clone https://gitlab.com/codedd1/codedd-cli
cd codedd-cli
pip install -e .
```

### From PyPI

```bash
pip 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)).

---

## Quick start (recommended workflow)

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

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

Optional sanity check:

```bash
codedd auth status
```

### 2. Select the active audit context

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

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

### 3. Define local scope

Add 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` performs a metadata scan (paths, file types, LoC) and registers scope with CodeDD.  
If files change later, `codedd audit start` auto-checks sync and prompts for re-confirmation when needed.

### 4. Configure LLM key(s)

Configure at least one provider key (used for local file-level auditing):

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

Alternatively, export a provider key (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`, or the `CODEDD_*` equivalents). Environment variables take precedence over the keychain.

Optional (recommended if both are configured):

```bash
codedd config provider both
```

### 5. Start the audit

```bash
codedd audit start
```

The CLI will:

- Sync scope with CodeDD (and prompt to re-confirm if local files changed).
- Run pre-flight checks (payment, LoC budget).
- Optionally open payment in the browser or deduct from budget.
- Fetch the plan, run local analysis, submit structured results, and trigger server-side post-processing.

Results and recommendations are available in the CodeDD dashboard; you can also run `codedd audits list` to see status.

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

Once an audit has finished and remediation data is available on CodeDD, use `codedd fix` to work through flags and vulnerabilities locally:

**Group / portfolio 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 remediation loop is a single command per issue. Repeat it 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>`).

Issue Compass saved lists from the web UI can narrow flag remediation: `codedd fix selections list`, then `codedd fix selections use <n>`.

Run `codedd ai-docs fix` for the full remediation reference (AI-agent workflows, JSON output, access controls).

---

## Workflow overview

Use this exact order for a predictable run:

```text
1. codedd auth login
2. codedd audits select
3. codedd scope add <repo-path> [more paths...]
4. codedd scope confirm
5. codedd config set-key <anthropic|openai>   # at least one
6. codedd audit start
```

What `codedd audit start` does, in order:

```text
A. Auto-sync scope -> if changed, asks to re-confirm
B. Pre-flight on CodeDD -> checks status/payment/budget
C. Payment path -> budget deduction OR checkout flow
D. Local execution -> file audit (LLM), complexity, dependencies, git stats, architecture
E. Submission -> sends structured outputs to CodeDD (with retries on transient API errors)
F. Completion -> triggers server-side consolidation/recommendations
```

If you update files after confirming scope:

```text
Run: codedd audit start
-> CLI detects drift
-> Re-confirm prompt appears
-> Continue with updated scope
```

| Step              | Where it runs | What happens |
|-------------------|---------------|--------------|
| Scope add/confirm | Local         | Scan dirs, count files/LoC; register or delta-update scope on CodeDD. |
| Pre-flight        | CodeDD        | Check payment, budget, status. |
| File audit        | Local         | LLM (Anthropic/OpenAI) analyses each file; results sent to CodeDD. |
| Complexity        | Local         | Radon/Lizard; metrics sent to CodeDD. |
| Dependencies      | Local + CodeDD| Lockfiles/imports scanned locally; package/vuln data stored and enriched on CodeDD. |
| Git statistics    | Local + CodeDD| Commit history and core repo stats collected locally and submitted; CodeDD can derive further timeline/churn views from that history. |
| Architecture      | Local + CodeDD| Components/relations extracted locally; persisted and processed on CodeDD. |
| Recommendations   | CodeDD        | Consolidation, technical debt, security, licenses, etc. |

---

## Commands reference

### 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>` | Remove directory by list number |
| `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 (if needed), pre-flight, pay/budget, then run full local audit and submit to CodeDD. Use `--skip-sync` to skip scope sync; `--yes` to auto-confirm; `--show` for one-shot transparency summary; `--show-interactive` for per-request confirmations (debug); `--show-force-interactive` to override large-audit guardrails; `--debug-llm` for LLM debug output; `--debug-llm-full-prompt` to include the full proprietary system prompt in that output (sensitive). |
| `codedd audit status` | Show pipeline step progress for an active or resumable audit. |

### Issue remediation (`codedd fix`)

Requires a completed audit with remediation data on CodeDD. Select the audit first (`codedd audits select`).

| Command | Description |
|--------|-------------|
| `codedd fix status [--json]` | Dashboard of open flags/vulns; repos ranked by severity in group audits |
| `codedd fix repo [name\|uuid]` | Scope fix workflow to one sub-audit (group audits) |
| `codedd fix fetch flags\|vulns` | Load issue overview (interactive sub-audit pick when needed) |
| `codedd fix flags next [--auto] [--json]` | Next unresolved flag; `--auto` prioritizes red issues |
| `codedd fix flags invalidate [--reason "<text>"]` | Mark current flag as invalid and advance |
| `codedd fix vulns next [--auto] [--severity S] [--used-only] [--json]` | Next vulnerability; `--auto` prioritizes critical |
| `codedd fix vulns affected-files <package> [--json]` | List local files importing a vulnerable package |
| `codedd fix resolve [--comment "<text>"]` | Record progress, mark resolved, and print the next issue |
| `codedd fix comment "<text>"` | 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\|activate\|deactivate` | Remediation Module access (org initiator) |

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

**Exit codes** (for scripted 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 — the remaining count, the exact next command, and the stop condition — on every invocation, so long remediation runs do not depend on the instruction surviving in an agent's context window.

See `codedd ai-docs fix` for detailed examples and agent integration patterns.

### 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]` | 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 <anthropic\|openai>` | Remove a stored LLM API key from keychain |
| `codedd config provider [anthropic\|openai\|both]` | Set preferred LLM provider |
| `codedd config concurrency <n>` | Set max concurrent LLM requests (1–75, default 4) |

---

## Configuration

- **Config file:** `~/.codedd/config.toml` (TOML). Stores API URL, active audit, scope directories, LLM provider, concurrency. Permissions are restricted to the owner (Unix).
- **Secrets:** On desktop, the CLI token and LLM API keys are stored in the system keychain (Windows Credential Locker, macOS Keychain, Linux Secret Service), not in the config file. On headless systems, supply them via 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 (used when the OS keyring is unavailable, e.g. 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
```


---

## Security

- On desktop, CLI tokens and LLM keys are stored in the OS credential store, not in plaintext on disk. On headless Linux, containers, and CI, supply them through environment variables; the CLI does not write those secrets to disk.
- TLS certificate verification is always enabled for API requests.
- Config file and `~/.codedd` directory use owner-only permissions where supported.
- Tokens expire after 90 days (server-configurable); re-generate from the CodeDD dashboard when needed.

---

## Development

```bash
pip install -e .
pip install pytest pytest-httpx pytest-mock ruff
pytest
ruff check .
```

---

## License

MIT License — see [LICENSE](LICENSE).

---

## Support

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

