Metadata-Version: 2.4
Name: kosmo-cli
Version: 0.2.0
Summary: A local developer-environment and dependency orchestration CLI for Python projects.
Author: Sanket
License-Expression: MIT
Project-URL: Homepage, https://github.com/Sanket-builds/Kosmo
Project-URL: Repository, https://github.com/Sanket-builds/Kosmo
Project-URL: Issues, https://github.com/Sanket-builds/Kosmo/issues
Keywords: cli,developer-tools,python,dependency-management,venv
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
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: Topic :: Software Development :: Build Tools
Classifier: Topic :: System :: Installation/Setup
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer>=0.12.0
Requires-Dist: rich>=13.0.0
Requires-Dist: tomlkit>=0.12.0
Requires-Dist: packaging>=23.0
Requires-Dist: textual>=0.60.0
Requires-Dist: tomli>=2.0.0; python_version < "3.11"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Dynamic: license-file

# Kosmo

[![PyPI version](https://img.shields.io/pypi/v/kosmo-cli.svg)](https://pypi.org/project/kosmo-cli/)
[![Python versions](https://img.shields.io/pypi/pyversions/kosmo-cli.svg)](https://pypi.org/project/kosmo-cli/)
[![CI](https://github.com/Sanket-builds/Kosmo/actions/workflows/ci.yml/badge.svg)](https://github.com/Sanket-builds/Kosmo/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

**A local developer-environment and dependency orchestration CLI for Python projects.**

**Kosmo kills the Python setup grind.**

Forget the usual `venv`, `pip install`, dependency-syncing chaos. Kosmo turns project setup into a single, opinionated workflow powered by `pyproject.toml`.

Create environments. Manage dependencies. Sync installs. Run health checks. Migrate legacy projects — or onboard bare `.py` folders without a `requirements.txt`.

**One tool. Zero setup drama.**

![Kosmo Demo Placeholder](docs/assets/kosmo-demo.gif)
*(Demo GIF placeholder: `kosmo` Textual dashboard, `kosmo setup` live server launch, and `kosmo doctor`)*

---

## Why Kosmo?

- **`pyproject.toml` is the single source of truth.** Every `kosmo add`, `remove`, and `update` runs inside `.venv` first and updates `pyproject.toml` only when `pip` succeeds — leaving `pyproject.toml` untouched if an install fails, while preserving your comments and formatting via `tomlkit`.
- **Zero-config onboarding & migration (`kosmo setup`).** Have a `requirements.txt`, `setup.py`, `setup.cfg`, or `Pipfile`? Kosmo migrates it to `pyproject.toml`. Have only `.py` files and no dependency file at all? Kosmo scans your `import` statements via Python's `ast`, filters out the standard library and local modules, maps aliases (`cv2` → `opencv-python`, `PIL` → `pillow`, `yaml` → `pyyaml`), installs them into `.venv`, and launches your app.
- **Errors that explain themselves.** When an app fails to boot during `kosmo setup`, Kosmo never fails silently. It diagnoses the root cause from the server log, prints **why** it failed and **what to do next**, shows the last 30 log lines, and offers to run the fix automatically.
- **Real terminal UI.** Rich panels, tables, spinners, and clickable links in the CLI, plus a full-screen Textual dashboard when you run bare `kosmo`. Automatically falls back to plain ASCII when piped (`--plain`) or machine-readable JSON (`--json`).

> **Honest scope (what Kosmo is not):** Kosmo manages direct project dependencies in `pyproject.toml` using Python's built-in `venv` and `pip`. **It does not resolve or lock transitive dependencies into a cross-platform lockfile.** If you need deterministic, hash-locked builds across production deployments, use [uv](https://docs.astral.sh/uv/), [Poetry](https://python-poetry.org/), or [pip-tools](https://pip-tools.readthedocs.io/).

---

## Installation

**Supported:** Windows, macOS, and Linux on **Python 3.10 – 3.13+**.

### Recommended: `pipx` (isolated global CLI)

```bash
pipx install kosmo-cli
```

### Alternative: `pip`

```bash
pip install kosmo-cli
```

If your user scripts directory is not on `PATH`, you can always invoke Kosmo as a Python module:

```bash
python -m kosmo --help
```

---

## Quick Start

```bash
# Open the interactive Textual dashboard in an existing project
kosmo

# Or start a new project in the current directory
kosmo init

# Add a dependency (writes >=<installed_version> to pyproject.toml by default)
kosmo add requests

# Preview declared vs. installed diff without changing .venv
kosmo sync --dry-run

# Reconcile missing or mismatched packages
kosmo sync

# Run a full project health check
kosmo doctor
```

---

## Commands

| Command | Description |
|---------|-------------|
| `kosmo` | Launch the full-screen Textual project dashboard (summary, dependency table, live logs; keys: `s` sync, `d` doctor, `r` refresh, `q` quit) |
| `kosmo init` | Create `.venv` and `pyproject.toml` in the current directory |
| `kosmo status` | Show project config, `.venv`, and dependency sync status at a glance |
| `kosmo env` | Print `.venv` path, Python version, `pip` version, and interpreter path |
| `kosmo add <pkg>` | Install `<pkg>` in `.venv` and append `<pkg>>=<installed_version>` to `pyproject.toml` |
| `kosmo remove <pkg>` | Uninstall `<pkg>` from `.venv` and remove it from `pyproject.toml` (`-y` to skip prompt) |
| `kosmo update <pkg>` | Upgrade `<pkg>` in `.venv` and refresh its `>=<version>` constraint in `pyproject.toml` |
| `kosmo list` | List declared dependencies alongside their version constraints, installed versions, and sync status |
| `kosmo sync` | Install missing declared dependencies and upgrade version mismatches (`--dry-run` to preview, `-y` to auto-confirm; extra installed packages are reported but never auto-removed) |
| `kosmo doctor` | Run health checks on `pyproject.toml`, `.venv`, Python version, sync status, `.gitignore`, and `README` (`--report` prints a GitHub-issue diagnostic snippet) |
| `kosmo setup` | Onboard any project (migrate config or infer imports, create `.venv`, pick a free port, launch web app, and print its URL or failure diagnosis) |
| `kosmo jump` | Searchable project directory switcher (`--add`, `--list`, `--remove`, `--shell <bash\|zsh\|fish\|powershell>`) and test-failure location jumper (`--run pytest`) |

**Global flags** (accepted before any subcommand, e.g. `kosmo --json status`):
- `--plain`: Plain text output with ASCII-safe characters (auto-enabled when stdout is not a TTY; respects `NO_COLOR`).
- `--json`: Structured JSON output for scripting and CI.
- `--debug`: Show full Python tracebacks on unexpected errors.

---

## `kosmo setup`: Always a Link or a Reason

Run `kosmo setup` in any repository — whether it has `pyproject.toml`, `requirements.txt`, `setup.py`, `Pipfile`, or **only `.py` files**.

1. **Detect / Migrate:** Converts legacy dependency files to `pyproject.toml` (or infers third-party packages from `import` statements via AST analysis if no dependency file exists) and creates `.venv`.
2. **Pick a Port & Launch:** Detects FastAPI, Streamlit, Gradio, Flask, Django, Dash, or NiceGUI (or uses your `[tool.kosmo.run]` override), picks a free port, and starts the server with logs written to a temp file so output buffers never block.
3. **Report:** Polls until the port accepts connections and prints clickable links:

```text
╭─────────────────────── Application Links ────────────────────────╮
│ Fastapi server is running!                                       │
│                                                                  │
│   Local : http://127.0.0.1:8000                                  │
│   Docs  : http://127.0.0.1:8000/docs                             │
│                                                                  │
│ Command: .venv/bin/python -m uvicorn main:app --port 8000        │
╰──────────────────────────────────────────────────────────────────╯
```

Pass `kosmo setup --share` to bind `0.0.0.0` and print a LAN link (Kosmo warns you that this exposes the server to your local network). If no web framework is detected (CLI tool, bot, worker, or library), Kosmo clearly states there is no browser link to open and prints the exact command to run your code.

### Failure Diagnosis Table

When a launch fails, Kosmo inspects the log tail, explains **why**, tells you **what to do next**, and offers to run the fix automatically:

| Failure Pattern in Logs | Why It Happened | What Kosmo Suggests / Auto-Fixes |
|-------------------------|-----------------|----------------------------------|
| `No module named 'X'` | The app imports `X`, which isn't installed in `.venv` (or is declared but not synced) | Offers to run `kosmo add <pypi-pkg>` automatically (or `kosmo sync` if already in `pyproject.toml`) |
| `Address already in use` / `WinError 10048` | Requested port is already taken by another process | Offers to re-run with `kosmo setup --port <next_free_port>` |
| `Error loading ASGI app` / `Could not import module` | Kosmo guessed the wrong module or app variable name | Shows how to set `command` under `[tool.kosmo.run]` in `pyproject.toml` |
| `KeyError: 'SOME_ENV_VAR'` | Required environment variable is missing | Tells you to add `SOME_ENV_VAR=...` to `.env` |
| `Connection refused` / `OperationalError` | App requires an external database or service (Postgres, Redis, MySQL) that isn't running | Tells you to start the service and verify `.env`, then re-run |
| Timeout with process still alive | Server is still booting (e.g. downloading weights) or listening on a different port | Suggests `kosmo setup --timeout 60` or configuring `[tool.kosmo.run]` |
| Unrecognised crash | Application raised an unhandled exception on startup | Displays the last 30 log lines in a dim panel and suggests `kosmo doctor --report` |

---

## Configuration (`pyproject.toml`)

### Default Version Specifiers & Dev Dependencies

When you run `kosmo add requests`, Kosmo installs the latest compatible version into `.venv` and records a lower-bound constraint (`"requests>=2.32.3"`) in `[project].dependencies`. If you pass an explicit constraint (`kosmo add "requests==2.31.0"`), Kosmo preserves your exact specifier.

For development-only tools (`pytest`, `ruff`, `build`), declare them under `[project.optional-dependencies]`:

```toml
[project]
name = "my-api"
version = "0.1.0"
dependencies = [
    "fastapi>=0.110.0",
    "uvicorn>=0.29.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0.0",
]
```

Install dev dependencies into `.venv` with:

```bash
.venv/bin/python -m pip install -e ".[dev]"      # macOS / Linux
.venv\Scripts\python.exe -m pip install -e ".[dev]"  # Windows PowerShell
```

### Custom Run Override (`[tool.kosmo.run]`)

Override automatic framework detection in `kosmo setup` by adding `[tool.kosmo.run]` to `pyproject.toml`:

```toml
[tool.kosmo.run]
command = "uvicorn src.api:create_app --factory --port 9000"
url = "http://127.0.0.1:9000"
```

### Running Your App

You can start your project at any time by either:
1. Running `kosmo setup` (which launches web apps and checks port readiness),
2. Activating `.venv` (`source .venv/bin/activate` on macOS/Linux, `.venv\Scripts\Activate.ps1` on Windows PowerShell), or
3. Calling the venv interpreter directly (`.venv/bin/python main.py` or `.venv\Scripts\python.exe main.py`).

---

## Project Jumping (`kosmo jump`)

Because a child process cannot change its parent shell's working directory directly, `kosmo jump` prints the target project path and provides a tiny `kj` shell function that captures the path and runs `cd` / `Set-Location`.

Registered projects are stored in:
- **macOS / Linux:** `~/.config/kosmo/projects.toml` (or `$XDG_CONFIG_HOME/kosmo/projects.toml`)
- **Windows:** `%APPDATA%\kosmo\projects.toml`
- **Custom override:** `$KOSMO_CONFIG_DIR/projects.toml`

```bash
# Register the current directory
kosmo jump --add

# Print the 'kj' shell wrapper for bash, zsh, fish, or powershell
kosmo jump --shell powershell
kosmo jump --shell zsh

# Open the interactive searchable project picker (or pass a project name)
kosmo jump
kosmo jump my-api
```

You can also pipe test output or pass `--run` to jump directly to failing `file:line` locations in VS Code:

```bash
kosmo jump --run pytest
```

---

## Troubleshooting

| Symptom | Cause | Fix |
|---------|-------|-----|
| `kosmo: command not found` | Python's user scripts directory (`~/.local/bin` or `%APPDATA%\Python\Python3x\Scripts`) is not on `PATH` | Reinstall with `pipx install kosmo-cli && pipx ensurepath`, or run `python -m kosmo` |
| `venv` creation fails on Ubuntu / Debian (`ensurepip is not available`) | Debian/Ubuntu split `ensurepip` into a separate system package | Run `sudo apt install python3-venv` (or `sudo apt install python3.<minor>-venv`), then re-run `kosmo init` |
| PowerShell blocks `.venv\Scripts\Activate.ps1` (`running scripts is disabled`) | Default Windows PowerShell execution policy restricts local scripts | Run `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or skip activation and run `.venv\Scripts\python.exe` directly |
| Garbled box characters on legacy Windows consoles | Console code page (`cp437` / `cp1252`) lacks Unicode box glyphs | Pass `kosmo --plain <command>` or run inside Windows Terminal |
| Something else failed on your machine | Environment-specific path or Python issue | Run `kosmo doctor --report` and paste the output into a GitHub issue |

---

## Contributing

To set up a local development environment and run the test suite:

```bash
git clone https://github.com/Sanket-builds/Kosmo.git
cd Kosmo
python -m venv .venv

# Activate on Windows PowerShell:
.venv\Scripts\Activate.ps1

# Or activate on macOS / Linux:
source .venv/bin/activate

# Install in editable mode with dev dependencies
python -m pip install -e ".[dev]"

# Run the test suite
python -m pytest -v
```

---

## License

[MIT](LICENSE)
