# CODEBUDDY.md

This file provides guidance to CodeBuddy Code when working with code in this repository.

## Project Overview

**StigmergyLite** (formerly git-autoinstaller) is a Node.js npm package that automates development environment setup. It detects, installs, and configures Git, OpenCode, Bun, and multiple AI CLI tools (CodeBuddy, iFlow CLI, Qoder CLI, Qwen CLI) across Windows, macOS, and Linux platforms.

**Version:** 1.0.4
**Main Repository:** https://github.com/ptreezh/stigmergylite
**License:** MIT

## Common Commands

### Building and Testing

```bash
# Run tests
npm test

# Run specific test file
node test.js
node simple-test.js
node test-install-uninstall.js

# Install the package (triggers install.js post-install hook)
npm install

# Run CLI globally (after global install)
stigmergylite [options]
```

### CLI Usage

```bash
# Full installation (Git + all CLI tools)
stigmergylite

# Silent mode
stigmergylite --silent

# Install only Git, no CLI tools
stigmergylite --no-clis

# Install specific CLI tools
stigmergylite --iflow          # iFlow CLI only
stigmergylite --qoder          # Qoder CLI only
stigmergylite --qwen           # Qwen CLI only
stigmergylite --codebuddy      # CodeBuddy only

# Install all CLI tools
stigmergylite --all-clis

# Detection only (no auto-install)
stigmergylite --no-auto-install
```

### Publishing

```bash
# Build and publish to npm (handled by GitHub Actions)
# Triggered by pushing tags like v1.0.5
git tag v1.0.5
git push origin v1.0.5
```

## Architecture

### Core Structure

```
stigmergylite/
├── index.js              # Main GitAutoInstaller class (956 lines)
├── cli.js                # CLI interface with argument parsing
├── install.js            # npm post-install hook
├── package.json          # Package configuration
└── Tests & Examples
    ├── test.js           # Comprehensive test suite
    ├── simple-test.js    # Basic functionality test
    ├── example-simple.js # Basic usage example
    └── example-codebuddy.js # CodeBuddy integration example
```

### GitAutoInstaller Class (index.js:8-956)

The core class orchestrates the entire installation process. Key architectural patterns:

1. **Options-Based Configuration**: Constructor accepts options object controlling behavior:
   - `silent`: Suppress output (default: false)
   - `autoInstall`: Automatically install missing tools (default: true)
   - `configureGitBash`: Configure Git Bash environment variables (default: true)
   - `installOpenCode`, `installBun`, `installOhMyOpenCode`: Install base tools (default: true)
   - `installIflowCLI`, `installQoderCLI`, `installQwenCLI`, `installCodebuddy`: Install CLI tools (default: true)
   - `gitConfig`: Git configuration object (userName, userEmail, defaultBranch)

2. **Cross-Platform Detection**: `detectOS()` returns `'windows' | 'macos' | 'linux' | 'unknown'` using Node.js `os.platform()`

3. **Environment Detection**: `detectEnvironment()` checks for Docker containers and sudo permissions to adapt installation strategy

4. **Command Existence Checking**: `commandExists(command)` uses `which.sync()` to test for executable availability before installation

5. **Promise-Based Async**: All methods return Promises and use async/await for clarity

6. **New: User-Level Installation**: Three new methods support installation without admin/sudo privileges:
   - `installGitOnWindowsUser()`: Downloads MinGit portable version using Node.js HTTPS, extracts with PowerShell
   - `installGitOnLinuxUser()`: Downloads precompiled Git binary using curl/wget, extracts with tar
   - `installGitOnMacOSUser()`: Downloads precompiled Git binary using curl, extracts with tar

7. **New: File Download Helper**: `downloadFile(url, destPath)` provides cross-platform HTTP/HTTPS file download with progress tracking

8. **New: PATH Persistence**: `persistUserPath(gitBinPath, osType)` makes Git available to other processes:
   - **Windows**: Modifies user-level registry `HKEY_CURRENT_USER\Environment` (no admin required)
   - **Linux**: Updates `~/.bashrc` (no sudo required)
   - **macOS**: Updates `~/.bashrc` and `~/.zshrc` (no admin required)

### Installation Flow (install() method at index.js:751-859)

The main installation process follows these steps in order:

1. **OS/Environment Detection** (lines 758-760): Detect platform and Docker/sudo status
2. **Git Detection/Installation** (lines 763-784): Check if Git exists, install if needed and autoInstall is true
3. **Git Bash Configuration** (lines 787-789): Set `process.env.GIT_BASH_PATH` and `process.env.GIT_INSTALL_ROOT`
4. **Git Configuration** (lines 792-794): Apply user.name, user.email, and defaultBranch settings if provided
5. **OpenCode Installation** (lines 797-800): `npm install -g opencode-ai`
6. **Bun Installation** (lines 803-806): `npm install -g bun`
7. **Oh My OpenCode Installation** (lines 809-812): `bunx oh-my-opencode install --no-tui --claude=no --chatgpt=no --gemini=no`
8. **CodeBuddy Installation** (lines 815-818): `npm i -g @tencent-ai/codebuddy-code`
9. **iFlow CLI Installation** (lines 821-824): `npm i -g @iflow-ai/iflow-cli`
10. **Qoder CLI Installation** (lines 827-830): `npm install -g @qoder-ai/qodercli`
11. **Qwen CLI Installation** (lines 833-836): `npm i -g @qwen-code/qwen-code`

Each CLI installation method (index.js:551-689) follows the same pattern:
- Check if command already exists using `commandExists()`
- Execute `npm install -g <package>` command via `execSync()`
- Verify installation by running command with `--version` flag

### Git Installation Strategy

**Package now supports installation in restricted environments without admin/sudo privileges!**

**Windows** (index.js:343-403): Tries package managers in order, then falls back to portable version:
1. `winget install --id Git.Git` - ❌ Requires administrator privileges
2. `choco install git` - ❌ Requires administrator privileges
3. `scoop install git` - ❌ Requires Scoop to be pre-installed
4. **NEW: User-level portable Git** - ✅ Downloads MinGit portable version using Node.js HTTPS, extracts with PowerShell, no admin required
5. Falls back to manual installation instructions - ⚠️ User must manually download and install with admin rights

**macOS** (index.js:407-435): Tries:
1. `brew install git` - ❌ Requires Homebrew to be installed first
2. `xcode-select --install` - ❌ Requires administrator privileges
3. **NEW: User-level precompiled binary** - ✅ Downloads macOS Git binary using curl, extracts to user directory, no admin required

**Linux** (index.js:439-506): Tries distro-specific managers:
1. Debian/Ubuntu: `sudo apt-get install -y git-all` - ❌ Requires sudo privileges
2. Fedora/RHEL/CentOS: `sudo dnf install -y git-all` - ❌ Requires sudo privileges
3. Older Fedora/RHEL/CentOS: `sudo yum install -y git-all` - ❌ Requires sudo privileges
4. Arch Linux: `sudo pacman -S --noconfirm git` - ❌ Requires sudo privileges
5. **NEW: User-level precompiled binary** - ✅ Downloads Linux Git binary using curl/wget, extracts to user directory, no sudo required

### Git Bash Path Detection (index.js:197-273)

On **Windows**, searches multiple paths:
- `C:\Program Files\Git\bin\bash.exe`
- `C:\Program Files\Git\usr\bin\bash.exe`
- `C:\Program Files (x86)\Git\bin\bash.exe`
- `E:\PortableGit\bin\bash.exe` (and other common locations)
- Infers from `git.exe` location using `path.dirname(gitPath) + '/bash.exe'`

On **macOS/Linux**: Uses system `/bin/bash` or returns null (Git commands don't require Git Bash)

### Environment Variables

After successful installation, the following environment variables are set for the current process:
- `GIT_BASH_PATH`: Full path to Git Bash executable (Windows) or system bash
- `GIT_INSTALL_ROOT`: Git installation root directory (Windows only)

Other tools can access these via `process.env.GIT_BASH_PATH` and `process.env.GIT_INSTALL_ROOT`.

### CLI Tool Installation Methods

All CLI tool installations follow the pattern at index.js:551-662:
- `installCodeBuddy()`: Installs `@tencent-ai/codebuddy-code`
- `installIflowCLI()`: Installs `@iflow-ai/iflow-cli`
- `installQoderCLI()`: Installs `@qoder-ai/qodercli`
- `installQwenCLI()`: Installs `@qwen-code/qwen-code`
- `installOpenCode()`: Installs `opencode-ai`
- `installBun()`: Installs `bun` via npm
- `installOhMyOpenCode()`: Uses `bunx oh-my-opencode install`

### Execute With Git Bash (index.js:885-952)

The `executeWithGitBash(command, options)` method runs commands through Git Bash:
- On Windows: Uses Git Bash executable directly
- On macOS/Linux: Uses system `/bin/bash` or attempts direct execution
- Returns Promise resolving to `{ stdout, stderr, code }`
- Useful for running Git commands or other bash scripts

### Post-Install Hook (install.js:1-39)

The npm install script automatically runs the installation when the package is installed, with a friendly message suggesting manual CLI usage for selective installations.

### Testing (test.js:1-87)

The test suite runs 6 tests sequentially:
1. OS detection
2. Git installation check
3. Git Bash path finding
4. Git Bash environment variable configuration
5. Command execution with Git Bash
6. Environment variable verification

No formal testing framework (Jest, Mocha) is used. Tests are manual assertions with try-catch error handling.

## Key Dependencies

- `which` (v4.0.0): Cross-platform executable path finding
- `cross-spawn` (v7.0.3): Cross-platform child process spawning
- `execa` (v8.0.1): Process execution with better error handling

## Important Notes

- The package name in package.json is `stigmergylite` but the main export class is still `GitAutoInstaller`
- The CLI command is `stigmergylite`, not `git-autoinstall`
- No build step required - pure Node.js execution
- Node.js >= 14.0.0 required, >= 16.13.0 or >= 18.0.0 recommended
- All installations use `execSync()` with 300-second timeout
- The project includes extensive Chinese-language documentation (README.md, QUICKSTART.md, SUMMARY.md)

## User-Level Installation Support (No Admin/Sudo Required)

**Fixed in latest version**: The package now supports automatic Git installation in restricted environments without administrator or sudo privileges.

### Windows User-Level Installation
- Uses **MinGit portable version** (minimal Git for Windows)
- Downloads via Node.js built-in HTTPS module
- Extracts using PowerShell `Expand-Archive` (built into Windows)
- Installs to `%USERPROFILE%\git-portable`
- Sets environment variables for current process
- **No administrator privileges required**

### Linux User-Level Installation
- Downloads **precompiled Git binary** for Linux
- Uses `curl` or `wget` (usually available) to download
- Extracts using `tar` (built into Linux)
- Installs to `~/git-user`
- Supports both x64 and ARM64 architectures
- Sets environment variables for current process
- **No sudo privileges required**

### macOS User-Level Installation
- Downloads **precompiled Git binary** for macOS
- Uses `curl` (built into macOS) to download
- Extracts using `tar` (built into macOS)
- Installs to `~/git-user`
- Supports both Intel (x64) and Apple Silicon (ARM64)
- Sets environment variables for current process
- **No admin privileges required**

### Important Notes for User-Level Installations

**CRITICAL: PATH Persistence - Git is now available to all processes and CLI tools!**

1. **Automatic PATH Persistence**:
   - **Windows**: Git path is automatically added to user-level PATH via registry (`HKEY_CURRENT_USER\Environment`)
   - **Linux**: Git path is automatically added to `~/.bashrc`
   - **macOS**: Git path is automatically added to both `~/.bashrc` and `~/.zshrc`
   - **No admin/sudo privileges required** for any of these operations

2. **Git Detection by Other Processes**:
   - ✅ After installation, **all processes** can detect Git using `which git` or system PATH
   - ✅ **Qoder CLI, CodeBuddy, iFlow CLI** and other tools will automatically find Git
   - ✅ No manual PATH configuration needed
   - ⚠️ Users must **restart their terminal** or run `source ~/.bashrc` (Linux/macOS) for PATH to take effect

3. **Environment Variables for Current Process**:
   - Git path is immediately available in the current Node.js process after installation
   - `process.env.GIT_BASH_PATH` and `process.env.GIT_INSTALL_ROOT` are set
   - Other Node.js modules running in the same process can use Git immediately

4. **CLI Tool Compatibility**:
   - Qoder CLI: Will detect Git automatically after terminal restart
   - CodeBuddy: Will detect Git automatically after terminal restart
   - iFlow CLI: Will detect Git automatically after terminal restart
   - All Git-dependent tools: Will work normally once PATH is updated

5. **Binary Download URLs**: The package uses specific Git releases from GitHub. If these become unavailable, the URLs in `installGitOnWindowsUser()`, `installGitOnLinuxUser()`, and `installGitOnMacOSUser()` may need to be updated.

6. **Architecture Detection**: Automatic detection of system architecture (x64 vs ARM64) ensures the correct binary is downloaded.

7. **Fallback Behavior**: If user-level installation fails, the package falls back to manual installation instructions.

8. **Terminal Restart Required**:
   - After installation, **new terminals will have Git in PATH automatically**
   - Current terminal needs to be restarted or configuration sourced:
     - Windows: Close and reopen terminal
     - Linux: Run `source ~/.bashrc`
     - macOS: Run `source ~/.zshrc` or `source ~/.bashrc`
