# CodePulse CLI — Full Documentation (Part 1/3) > Version: **5.2.0** | Package: `@archpulse/codepulse` | License: MIT | Node.js ≥ 16 --- ## Table of Contents - [Part 1](#): Overview, Stack, Architecture, Installation, Configuration, `scan` - [Part 2](#): `watch`, `diff`, `time-machine`, `health-trend`, `heatmap`, `coupling`, `audit` - [Part 3](#): `profile`, `ghost`, `synth`, `verify`, `pr-risk`, `review`, `agent`, `license`, `detect-reward-hacking`, MCP Server, GitHub Actions, Plugins, i18n --- ## 1. What is CodePulse **CodePulse** is a CLI tool for deep static and structural code analysis, designed for large JS/TS and Python projects. Its philosophy is **"Engineering Honesty"**: the tool honestly reveals architectural issues without hiding them. ### Key Features - Builds a **dependency graph** of the entire project using AST analysis. - Detects **God Files** (monolithic files), **Critical Nodes**, and **circular dependencies**. - Computes a **Health Score** (0–100) as an aggregated codebase health metric. - Identifies **hotspots** — files with high complexity AND frequent changes. - Analyzes **Temporal Coupling** (time-based coupling) via git history. - Runs **external linters** (ESLint, Oxlint, Ruff, Cppcheck, ShellCheck, GolangCI-Lint, etc.). - Provides an **MCP Server** for integration with AI agents (Claude, Cursor, Cline, Gemini, Copilot, etc.). - Supports a **Time Machine** — analyzing the evolution of metrics across git history. - Generates **HTML reports**, **SARIF files**, and **SVG badges**. - Sends **webhook alerts** to Slack, Discord, and Telegram when the Health Score degrades. - Works as a **GitHub Action** to embed into CI/CD pipelines. --- ## 2. Technology Stack | Category | Technology | Purpose | |---|---|---| | Language | TypeScript 6.0 | Entire CLI codebase | | Build Tool | `tsc` | Compilation into `dist/` | | CLI Framework | Commander.js 14 | Parsing commands and flags | | AST (JS/TS) | `@babel/parser` + `@babel/traverse` | Parsing JS/TS files | | AST (Advanced) | `ts-morph` 28 | Deep TypeScript analysis | | TUI Dashboard | `blessed` + `blessed-contrib` | Terminal User Interface (`watch`, `heatmap`) | | Pseudoterminal | `node-pty` | Embedded terminal inside `watch` | | File Watcher | `chokidar` 5 | Monitoring file changes | | Spinners | `ora` | Progress indicators | | Colors | `chalk` 4 | Colored terminal output | | Templates | `handlebars` | HTML reports | | Glob | `glob` 13 | File search via glob patterns | | GitHub API | `@octokit/rest` + `@actions/core` | GitHub Actions integration / PR comments | | MCP | `@modelcontextprotocol/sdk` | MCP Server for AI agents | | Tests | `vitest` 4 | Unit tests | --- ## 3. Project Architecture ``` codepulse-cli/ ├── src/ │ ├── index.ts # CLI Entry Point │ ├── explain.ts # Knowledge base for architectural concepts │ ├── mcp-setup.ts # MCP configuration (writes configs for agents) │ ├── mcp-paths.ts # Paths to MCP config files │ │ │ ├── cli/commands/ # Commander.js CLI command registration │ │ ├── advanced-commands.ts # coupling, pr-risk, explain, time-machine, profile, plugins │ │ └── ... │ │ │ ├── commands/ # Implementations of all commands │ │ ├── scan.ts (412 lines) # codepulse scan │ │ ├── watch.ts (1868 lines) # codepulse watch — God File TUI Dashboard │ │ ├── diff.ts (435 lines) # codepulse diff │ │ ├── time-machine.ts (197 lines) # codepulse time-machine │ │ ├── health-trend.ts (369 lines) # codepulse health-trend │ │ ├── heatmap.ts (247 lines) # codepulse heatmap │ │ ├── coupling.ts (60 lines) # codepulse coupling │ │ ├── audit.ts (98 lines) # codepulse audit │ │ ├── profile.ts (174 lines) # codepulse profile │ │ ├── ghost.ts (65 lines) # codepulse ghost │ │ ├── review.ts (117 lines) # codepulse review │ │ ├── synth.ts (80 lines) # codepulse synth │ │ ├── verify.ts (218 lines) # codepulse verify │ │ ├── pr-risk.ts (195 lines) # codepulse pr-risk │ │ ├── reward-hacking.ts(131 lines) # codepulse detect-reward-hacking │ │ ├── agent.ts (342 lines) # codepulse agent │ │ ├── license.ts (204 lines) # codepulse license │ │ ├── badge.ts # SVG badge │ │ ├── install-deps.ts (398 lines) # Linter auto-installation │ │ └── output.ts # Formatting statistics │ │ │ ├── analyzer/ # Analyzer Core │ │ ├── index.ts # Main analyze() function │ │ ├── scanner.ts # File scanning (glob) │ │ ├── ast.ts # Babel-based JS/TS AST parsing │ │ ├── graph.ts # Dependency graph, centrality, critical nodes │ │ ├── git.ts # Git metrics: churn, temporal coupling │ │ ├── workers.ts # Worker threads for parallel analysis │ │ ├── cache.ts # Cache with zlib compression │ │ ├── python.ts # Python file analysis │ │ ├── rust.ts # Rust file analysis │ │ ├── generic.ts # Analysis of other languages │ │ ├── ast-fingerprint.ts # AST fingerprinting (function duplicates) │ │ ├── architecture.ts # Architectural layer validation │ │ ├── context.ts # Loading .codepulse.json │ │ ├── zlib.ts # Compression utilities │ │ └── time-machine/ │ │ ├── engine.ts # Git history analysis engine │ │ ├── cache.ts # Snapshot cache (.codepulse-cache/snapshots/) │ │ ├── sampling.ts # Commit sampling strategies │ │ └── git-diff.ts # Diff between commits │ │ │ ├── rules/ # Rules and Linters │ │ ├── index.ts # Orchestrator (runs all rules) │ │ ├── security.ts # Regex-based security vulnerability patterns │ │ ├── fastLinter.ts # Fast built-in linter │ │ ├── agents/registry.ts # AI agent registry + CodePulse master rules │ │ └── linters/ # Adapters for external linters │ │ ├── javascript.ts # ESLint / Oxlint │ │ ├── python.ts # Ruff │ │ ├── rust.ts # Clippy │ │ ├── go.ts # GolangCI-Lint, Revive │ │ ├── cpp.ts # Cppcheck │ │ ├── lua.ts # Luacheck, Selene │ │ └── shell.ts # ShellCheck │ │ │ ├── mcp/ # MCP Server │ │ ├── server.ts # MCP Server startup (stdio transport) │ │ ├── handlers-health.ts # codepulse_identity, get_project_stats, analyze_project... │ │ ├── handlers-architecture.ts# visualize_subgraph, get_blast_radius, find_cycles... │ │ ├── handlers-agent.ts # optimize_context, simulate_edit, store_memory... │ │ └── definitions/ # JSON schemas for MCP tools │ │ │ ├── reporter/ │ │ ├── html.ts # HTML report generation │ │ ├── sarif.ts # SARIF file generation │ │ ├── health.ts # Health Score calculation │ │ └── stats.ts # Stats aggregation │ │ │ ├── utils/ │ │ ├── i18n.ts # Internationalization (7 languages) │ │ ├── webhooks.ts # Alerts: Slack, Discord, Telegram │ │ ├── plugins.ts # Plugin loader │ │ └── terminal.ts # Terminal symbols (UTF-8 / ASCII fallback) │ │ │ └── locales/ # UI translations (JSON) │ └── en.json, ru.json, ua.json, de.json, fr.json, ko.json, cs.json │ ├── plugins/ # Directory for custom plugins ├── rules/ # Custom rules ├── translations/ # README files in other languages ├── action.yml # GitHub Action └── .codepulse.json # Project configuration ``` --- ## 4. Installation ### Globally via npm ```bash npm install -g @archpulse/codepulse ``` ### Via npx (without installation) ```bash npx @archpulse/codepulse scan . ``` ### From source ```bash git clone https://github.com/archpulse/codepulse-cli.git cd codepulse-cli npm install npm run build npm link # makes 'codepulse' globally accessible ``` ### System Requirements - **Node.js ≥ 16.0.0** - Git (for metrics: churn, temporal coupling, time machine) - Optional: `oxlint`, `ruff`, `cppcheck`, `shellcheck`, `golangci-lint` (CodePulse can install them automatically using the `install-deps` command) --- ## 5. Configuration: `.codepulse.json` The `.codepulse.json` file in the project root controls the analyzer's behavior. ### Annotated Complete Schema ```json { "exclude": ["benchmark", "dist", "node_modules"], "rootDir": "src", "godFileLines": 500, "godFileImports": 20, "criticalNodeThreshold": 15, "alerts": { "slack": "$CODEPULSE_SLACK_WEBHOOK", "discord": "$CODEPULSE_DISCORD_WEBHOOK", "telegram": { "token": "$TELEGRAM_BOT_TOKEN", "chatId": "$TELEGRAM_CHAT_ID" }, "threshold": 80, "branches": ["main", "master"] }, "architecture": { "layers": [ { "name": "Domain", "pattern": "src/domain/**", "allowDependenciesFrom": [] }, { "name": "Application", "pattern": "src/commands/**", "allowDependenciesFrom": ["Domain"] } ] } } ``` ### Options | Parameter | Type | Default | Description | |---|---|---|---| | `exclude` | `string[]` | `[]` | Directories or glob patterns to exclude from analysis | | `rootDir` | `string` | `"."` | The root directory for scanning | | `godFileLines` | `number` | `500` | Line threshold for a file to be designated as a God File | | `godFileImports` | `number` | `20` | Import count threshold for a file to be designated as a God File | | `criticalNodeThreshold` | `number` | `15` | Centrality threshold for a node to be designated as a Critical Node | | `alerts.slack` | `string` | — | Slack Incoming Webhook URL | | `alerts.discord` | `string` | — | Discord Webhook URL | | `alerts.telegram.token` | `string` | — | Telegram Bot token | | `alerts.telegram.chatId` | `string` | — | Telegram chat or channel ID | | `alerts.threshold` | `number` | `80` | Health Score < threshold will trigger an alert | | `alerts.branches` | `string[]` | `["main","master"]` | Branches that trigger webhook alerts | | `architecture.layers` | `Layer[]` | — | Define architectural layers and their allowed dependencies | > **Environment Variables:** Values formatted as `"$VAR_NAME"` are automatically expanded from `process.env` when loading the configuration. ### Architectural Layers (`architecture.layers`) Define boundaries between modules. If a layer violates dependency rules, CodePulse records an `architecture-violation`. ```json { "name": "Infrastructure", "pattern": "src/db/**", "allowDependenciesFrom": ["Domain", "Application"] } ``` - `name` — Any custom name for the layer - `pattern` — Glob pattern mapping to the files in the layer - `allowDependenciesFrom` — List of layers this layer is allowed to depend on (import from) --- ## 6. The `scan` Command The core command — performs a complete, one-time analysis of the project. ### Syntax ```bash codepulse scan [dir] [options] ``` ### What `scan` does (Step-by-Step) 1. Validates the existence of the specified directory. 2. Automatically installs missing linters (`runInstallDepsForProject`). 3. Detects the linting engine: ESLint, Oxlint, or auto. 4. Executes `analyze()` — the core engine covering AST, dependency graphs, git metrics, external linters, and security rules. 5. Generates an HTML report at `.codepulse-report/index.html`. 6. Computes the Health Score and generates an SVG badge at `.codepulse-report/badge.svg`. 7. Generates a SARIF file (optional). 8. Dispatches webhook alerts to Slack/Discord/Telegram if configured and thresholds are breached. 9. Prints the final summary to the terminal. ### All Flags | Flag | Description | |---|---| | `--json` | Outputs results in JSON to stdout (disables UI output) | | `--sarif` | Generates a SARIF file for GitHub Code Scanning | | `--open` | Opens the HTML report in a browser after analysis completes | | `--strict` | Strict mode: makes `dead-export` and `god-file` report as `error` | | `--debug` | Shows only programmatic errors (skips linter diagnostics) | | `--ld` | Linter diagnostics only (debug mode for linters) | | `--focus ` | Filters issues by type | | `--severity ` | Filters issues by severity: `error`, `warning`, `info` | | `--group-by ` | Groups output: `file`, `type`, `severity` | | `--max-issues ` | Limits the output to at most N issues | | `--ignore-warnings` / `-iw` | Hides warnings | | `--fail-on ` | Exits with status 1 if any issues of the specified severity exist | | `--precision` / `--eslint` | Forces ESLint usage (more accurate but slower) | | `--engine oxlint` | Forces Oxlint usage (faster) | ### Short Aliases (automatically normalized) | Short Form | Expands to | |---|---| | `-ld` | `--ld` | | `-iw` | `--ignore-warnings` | | `-diw` | `--debug --ignore-warnings` | | `-ldiw` | `--ld --ignore-warnings` | ### Issue Types (`--focus`) | Type | Description | |---|---| | `dead-export` | Unused export | | `god-file` | Monolithic file (God File) | | `critical-node` | Critical node with high centrality | | `circular-dependency` | Circular dependency | | `vulnerability` | Security vulnerability pattern | | `architecture-violation` | Architectural boundary violation | | `linter` | Diagnostic from external linter | | `high-complexity` | High cyclomatic complexity | | `duplication` | Code duplication | ### Examples ```bash # Basic scan codepulse scan . # JSON output for CI/CD codepulse scan . --json # Errors only codepulse scan . --severity error # Strict mode + exit with 1 on errors codepulse scan . --strict --fail-on error # Focus on dead code codepulse scan . --focus dead-export # Group by file codepulse scan . --group-by file # SARIF for GitHub Code Scanning codepulse scan . --sarif # ESLint (precise analysis) codepulse scan . --precision # Open the HTML report in the browser codepulse scan . --open # Limit to at most 10 errors codepulse scan . --severity error --max-issues 10 ``` ### Terminal Output ``` ◆ CodePulse v5 — Engineering Honesty Scanning /path/to/project Engine: Auto (Resolving...) ✔ Analysis complete! Report: .codepulse-report/index.html Badge: .codepulse-report/badge.svg Score: 87/100 Files: 101 Lines: 16486 AvgComplexity: 2.90 Issues: 2 errors 1 warning (3 total) ``` ### How the Health Score is Computed | Factor | Penalty | |---|---| | God Files | −10 per file | | Circular Dependencies | −8 per cycle | | Critical Nodes | −5 per node | | Vulnerabilities | −7 per item | | Dead Exports | −1 per item | | Architectural Violations | −6 per item | | Hotspots | −2 per item | Range: **0–100**. Color: 🟢 ≥ 90 / 🟡 ≥ 70 / 🔴 < 70. --- # CodePulse CLI — Full Documentation (Part 2/3) ## 7. The `watch` Command An interactive real-time TUI dashboard. Monitors files and recalculates metrics on every save. ### Syntax ```bash codepulse watch [dir] ``` ### What `watch` does 1. Initializes a Blessed screen (full-window terminal UI). 2. Performs an initial project analysis. 3. Starts watching files via `chokidar` (700ms debounce). 4. Re-runs `analyze()` and updates all dashboard panels on every change. 5. Sends optional webhook alerts when the score degrades. ### Dashboard Panels | Panel | Position | Description | |---|---|---| | **Health Gauge** | Top row, full width | Health Score bar (0–100%) | | **Cockpit Terminal** | Top left | Embedded terminal to run codepulse commands | | **Telemetry** | Top right | Score, Files, Lines, Errors, Warnings, AvgComplexity | | **Complexity Chart** | Middle left | Historical average complexity chart (last 10 scans) | | **Hotspots Table** | Middle right | Top 5 hotspots by score | | **Hazard Log** | Bottom left | Table of all discovered issues (Severity / File:line / Message) | | **Warp Log** | Bottom right | Event log: git commits, webhook statuses, reload events | | **Heatmap** (hidden) | Below visible area | Risk heatmap (toggle on via Add Mode) | | **Coupling** (hidden) | Below visible area | Temporal Coupling panel (toggle on via Add Mode) | | **MCP Box** (hidden) | Below visible area | MCP server status panel (toggle on via Add Mode) | | **Clock Bar** | Bottom row | Clock (12h/24h depending on locale) | ### Control Keys | Key | Action | |---|---| | `Tab` | Switch between panels (cycle) | | `1`–`9` | Jump directly to a panel by index | | `Esc` | Unfocus current panel (scroll mode) | | `c` | Collapse/expand the active panel | | `+` / `-` | Increase/decrease panel height | | `[` / `]` | Decrease/increase panel width | | `a` | Enter **Add Mode** (add a hidden panel or terminal) | | `s` | Enter **Swap Mode** (swap two panels) | | `x` | Close the active panel | | `Alt + ↑` / `Alt + ↓` | Scroll viewport up/down (Niri-style layout) | | `Ctrl+C` | Exit `watch` | ### Cockpit Terminal (Embedded Terminal) The top-left panel contains an embedded terminal to execute codepulse commands directly inside the dashboard. Press `Tab` to focus, enter a command, and press `Enter`. **Available commands in the Cockpit:** ``` scan audit coupling heatmap health-trend ghost dead graph badge review synth verify detect-reward-hacking diff pr-risk explain time-machine profile stats plugins list help ``` Command output is displayed in the panel's log area (up to 120 lines). ANSI color codes are automatically stripped. ### Supported Extensions for `watch` ``` .ts .tsx .js .jsx .py .java .cpp .c .cs .lua .css .scss .html ``` ### Ignored Patterns ``` **/node_modules/** **/.git/** **/dist/** **/build/** **/coverage/** **/.codepulse-report/** **/*.min.js ``` ### Add Mode (`a`) In Add Mode (the status bar turns yellow): - Press `1`–`9` to restore one of the closed panels. - Press `t` to create a new **bash panel** (a full pseudoterminal via `node-pty`). - Press `h` to show the list of available panels. - `Esc` — Cancel. ### Swap Mode (`s`) Allows swapping the layout of two panels. Select the active panel, press `s`, then press the number key of the target panel. ### Technical Details of `watch` - **Debounce:** 700 ms between the last file change and executing analysis. - **Polling:** 1000 ms interval for normal files, 3000 ms for binary files. - **Blink:** Indicators blink every 500 ms. - **Clock:** Updated every second; format is locale-aware (12-hour for en/ko, 24-hour for others). - **Monkey-patch:** Intercepts `pty.js` imports and redirects them to `node-pty` for compatibility with `blessed`. - **Viewport:** Scrollable (Niri-style layout) — panels can reside below the visible screen bounds. --- ## 8. The `diff` Command Compares the architectural state of the current branch against a target branch. ### Syntax ```bash codepulse diff [options] ``` ### What `diff` does 1. Resolves and saves the current branch name. 2. Analyzes the current branch state (`analyze()`). 3. Stashes uncommitted changes via `git stash` if any are present. 4. Checks out the target branch (`git checkout `) and analyzes it. 5. Checks out the original branch and restores changes with `git stash pop`. 6. Generates a comparison report. ### Metrics Compared | Metric | Description | |---|---| | **Health Score** | Delta (current − target) | | **God Files** | Added God Files / removed God Files | | **Circular Dependencies** | New cycles / resolved cycles | | **Issues (Errors/Warnings)** | New / resolved issues | | **Critical Nodes** | New / resolved critical nodes | ### Flags | Flag | Description | |---|---| | `--json` | Outputs the report in JSON format | | `--threshold ` | Exits with status 1 if Health Score drops by more than N points | ### Examples ```bash # Compare with main branch codepulse diff main # Compare and fail CI if score drops by more than 5 points codepulse diff main --threshold 5 # JSON output codepulse diff develop --json ``` ### Example Output ``` ╭─ CodePulse Diff Report ────────────────────────────╮ │ Current: feature/new-module → Target: main │ ├─────────────────────────────────────────────────────┤ │ Health Score: 85 → 90 (▲5) │ ├─────────────────────────────────────────────────────┤ │ God Files │ │ + NEW src/commands/big-feature.ts │ ├─────────────────────────────────────────────────────┤ │ Issues Delta │ │ + 3 new errors │ │ − 1 resolved warning │ ├─────────────────────────────────────────────────────┤ │ 3 new issues │ 1 resolved │ ╰─────────────────────────────────────────────────────╯ ``` --- ## 9. The `time-machine` Command Analyzes the historical evolution of project architecture through git history. ### Syntax ```bash codepulse time-machine [dir] [options] ``` ### What `time-machine` does 1. Traverses git history based on the selected sampling strategy. 2. For each sampled commit: checks out → runs `analyze()` → saves a snapshot. 3. Uses a snapshot cache (`.codepulse-cache/snapshots/`) to skip analyzing commits that were already processed. 4. Outputs summary evolution statistics. ### Sampling Strategies (`--strategy`) | Strategy | Flag Example | Description | |---|---|---| | `max-points` | `--strategy max-points --commits 30` | Evenly samples N commits across the entire history (default) | | `every-nth` | `--strategy every-nth --commits 10` | Samples every N-th commit | | `interval` | `--strategy interval --interval weekly` | Samples based on temporal intervals: `daily`, `weekly`, or `monthly` | | `tag-only` | `--strategy tag-only` | Samples tagged commits (releases) only | ### Flags | Flag | Description | |---|---| | `--commits ` | Total number of commits to sample (default: 30) | | `--strategy ` | Sampling strategy: `max-points`, `every-nth`, `interval`, `tag-only` | | `--interval ` | Sampling interval for `interval` strategy: `daily`, `weekly`, `monthly` | | `--since ` | Only analyze commits after the specified date (e.g., `2024-01-01`) | | `--json` | Outputs results in JSON format | ### Examples ```bash # 30 evenly-spaced samples across the entire git history codepulse time-machine . # Weekly samples for the last 6 months starting from 2024-01-01 codepulse time-machine . --strategy interval --interval weekly --since 2024-01-01 # Release tags only codepulse time-machine . --strategy tag-only # Export as JSON for further processing codepulse time-machine . --json > history.json ``` ### Example Output ``` ════════════════════════════════════════════════════ Dependency Graph Time Machine ════════════════════════════════════════════════════ Commits scanned: 150 Snapshots taken: 30 AST parses: 87 Cache hits: 63 (cache efficiency: 42%) Timeline: Jan 2024 → May 2026 Files: 45 → 101 Lines: 4200 → 16486 Avg Complexity: 2.1 → 2.9 Dependencies: 120 → 340 (+220) Evolution Insights (v2): Health Score: 95 → 82 (▼13) Regressions: Detected 2 major complexity spikes. ! a3f5b2c: feat: add watch TUI dashboard... ! 8d1e094: refactor: merge all handlers... Risky Module Forecasting: Trend: Degrading Projected Cplx: 4.2 (in next 3 months) WARNING Architectural drift detected. Refactoring recommended soon. ✓ Snapshots saved to .codepulse-cache/snapshots/ ``` ### Snapshot Cache Snapshots are persisted in `.codepulse-cache/snapshots/`. Each snapshot contains: - `sha` — Commit hash - `date` — Commit timestamp - `message` — Commit message - `stats` — `{ files, totalLines, avgComplexity, healthScore, hotspots[] }` - `graph` — `{ nodes[], edges[], circularDependencies[] }` --- ## 10. The `health-trend` Command Visualizes metric trends using saved history snapshots. ### Syntax ```bash codepulse health-trend [dir] [options] ``` ### What `health-trend` does 1. Reads saved snapshots from `.codepulse-cache/snapshots/`. 2. If no snapshots are found, automatically triggers `time-machine` with 15 sample points. 3. Renders sparklines (Unicode spark charts) for each tracked metric. 4. Flags trends (Improving / Regressing / Stable), highlights best/worst historical milestones, and detects complexity spikes. ### Flags | Flag | Description | |---|---| | `--since ` | Only processes snapshots recorded after the specified date | | `--json` | Outputs trends in JSON format | ### Example Output ``` ══════════════════════════════════════════════════════════════ Health Score Evolution ══════════════════════════════════════════════════════════════ Health ▅▆▇▇▆▅▄▄▅▆▆▇▇ 95 → 82 (↓13) Regressing ✗ Complex ▂▂▃▃▃▄▄▄▄▅▅▅▅ 2.1 → 2.9 (↑0.8) Regressing ✗ Files ▂▃▃▄▄▄▅▅▆▆▆▇▇ 45 → 101 (+56) Growing Issues ▁▁▁▂▂▂▃▃▄▄▄▅▅ 0 → 3 (↑3) Regressing ✗ Timeline: Jan 2024 ──────────────────── May 2026 Snapshots: 30 commits analyzed Key Moments: ✓ Best: a1b2c3 (Mar 2024) → Score: 97 ✗ Worst: 9f8e7d (Apr 2026) → Score: 78 ! Spike: 4c3b2a (Jan 2026) → Complexity jumped 35% ``` ### JSON Structure (`--json`) ```json { "snapshots": [ { "sha": "abc1234", "date": "2024-01-15", "health": 95, "complexity": 2.1, "files": 45, "issues": 0 } ], "trends": { "health": { "first": 95, "last": 82, "delta": -13, "direction": "down" }, "complexity": { "first": 2.1, "last": 2.9, "delta": 0.8, "direction": "up" }, "files": { "first": 45, "last": 101, "delta": 56, "direction": "up" }, "issues": { "first": 0, "last": 3, "delta": 3, "direction": "up" } } } ``` --- ## 11. The `heatmap` Command An interactive terminal heatmap of file risk indices. ### Syntax ```bash codepulse heatmap [dir] ``` ### What `heatmap` does 1. Executes `analyze()` on the target project. 2. For each file, computes its **Risk Score** using the formula: ``` Risk = Complexity × log₂(Churn + 1) × (1 + Centrality / MaxCentrality) ``` 3. Sorts all files by Risk Score. 4. Renders a Blessed TUI with three layout sections: - **Header** — Global project summary statistics. - **Bar Chart** — Top 12 directories by relative risk index. - **Table** — Scrollable checklist of all files ordered by risk index. ### Risk Levels | Level | Range | Color | |---|---|---| | Low | 0–3 | 🟢 Green | | Medium | 3–7 | 🟡 Yellow | | High | 7+ | 🔴 Red | ### Keys | Key | Action | |---|---| | `↑` / `↓` | Scroll file list table | | `q` / `Esc` / `Ctrl+C` | Exit | ### Example ``` ╔═══ CodePulse Heatmap ══════════════════════════════════╗ ║ Project: my-app Files: 101 Avg Risk: 1.8 High: 0 ║ ║ Risk = complexity × log₂(churn + 1) × (1 + c/maxC) ║ ╠═══ Risk by Directory ══════════════════════════════════╣ ║ [commands ████████] [analyzer ██████] [mcp ████] ║ ╠═══ Files by Risk Score ════════════════════════════════╣ ║ File Risk Complexity Churn Cntrl ║ ║ src/commands/watch.ts 5.50 8.10 6 0.043 ║ ║ src/analyzer/index.ts 3.21 5.20 4 0.031 ║ ║ ... ║ ╠═══ Legend ═════════════════════════════════════════════╣ ║ ■ Low (0-3) ■ Medium (3-7) ■ High (7+) q: quit ║ ╚════════════════════════════════════════════════════════╝ ``` --- ## 12. The `coupling` Command Discovers files that are frequently changed together within the same git commits (Temporal Coupling). ### Syntax ```bash codepulse coupling [dir] ``` ### What is Temporal Coupling? If files A and B are modified together in 80% of their shared commits, they are **temporally coupled**. This is a hidden logical dependency that does not appear in the static `import` graph. High temporal coupling usually indicates that files violate the Single Responsibility Principle (SRP) or share an implicit architectural dependency. ### Example Output ``` Temporal Coupling Detector (Files that frequently change together in the same commit) File A File B Degree ──────────────────────────────────────────────────────────────────────────── src/commands/watch.ts src/analyzer/index.ts 87% src/mcp/handlers-health.ts src/mcp/handlers-architecture.ts 72% src/rules/index.ts src/rules/security.ts 65% ... * threshold: 50% co-change rate. Filtered by 8 pairs. ``` ### Applications - Discovering hidden coupling before starting a refactoring. - Understanding which files must be tested in tandem. - Powering predictive warnings in the `pr-risk` command. --- ## 13. The `audit` Command Performs a deep architectural audit and generates an `AUDIT.md` report. ### Syntax ```bash codepulse audit [dir] ``` ### What `audit` does 1. Executes `analyze()` in precision mode (via ESLint). 2. Computes the Health Score. 3. Generates a comprehensive `AUDIT.md` report in the project root. 4. Renders a summary executive overview in the terminal. ### Structure of `AUDIT.md` ```markdown # 🏥 CodePulse Architectural Audit Report **Date:** 2026-05-20T17:00:00.000Z **Project Health Score:** 87/100 ## 📋 Executive Summary The project architecture is healthy but showing signs of technical debt... ## 🗺️ Architectural Landmarks ### ⚡ Critical Nodes (High Centrality) - **src/analyzer/index.ts** (Centrality: 0.87) - **src/commands/watch.ts** (Centrality: 0.43) ### 🐘 God Files (High Complexity & Coupling) - **src/commands/watch.ts** (Complexity: 8.1, Lines: 1868) ### 🔄 Circular Dependencies - src/analyzer → src/rules → src/analyzer ## ✅ Recommended Actions 1. Break Cycles: Refactor the identified circular dependencies... 2. Decompose God Files: Split watch.ts into smaller modules... 3. Increase Test Coverage: Ensure Critical Nodes have near-100% test coverage. ``` ### Terminal Output ``` Audit Executive Summary ──────────────────────────────────────── Health Score: 87/100 Critical Nodes: 2 God Files: 1 Cycles: 0 ──────────────────────────────────────── Tip: Use 'codepulse explain' to deep dive into specific findings. ``` ### Health Score Classifications | Range | Summary Message | |---|---| | > 90 | "The project architecture is in excellent shape..." | | 70–90 | "The project architecture is healthy but showing signs of technical debt..." | | < 70 | "CRITICAL: The project architecture is highly coupled and complex..." | --- # CodePulse CLI — Full Documentation (Part 3/3) ## 14. The `profile` Command Correlates execution profiler outputs (V8 cpuprofile or Python cProfile) with static AST code complexity metrics. ### Syntax ```bash codepulse profile [options] ``` ### Flags | Flag | Description | |---|---| | `-d, --dir ` | Project directory (default: `.`) | | `--lang ` | Overrides language selection (auto-detected from file extension by default) | | `--top ` | Limits output to top N performance hotspots (default: 20) | | `--json` | Outputs findings in JSON format | ### Supported Profiler Formats | Extension | Format | |---|---| | `.cpuprofile` | V8 CPU Profile (Node.js / Chrome DevTools) | | `.prof`, `.pstats` | Python cProfile output | ### Debt Classifications | Category | Description | |---|---| | `active-hotspot` | High complexity AND high execution duration | | `dormant-debt` | High complexity but low execution frequency (rarely called) | | `io-bound` | Long execution time but low code complexity (likely I/O bound) | ### Examples ```bash # Analyze a V8 CPU profile codepulse profile cpu.cpuprofile --dir ./my-app # Analyze a Python profile, override language to Python, and show the top 10 bottlenecks codepulse profile app.prof --lang py --top 10 # Output results in JSON format codepulse profile cpu.cpuprofile --json ``` --- ## 15. The `ghost` Command Calculates the logical "Blast Radius" of a file — how many components are downstream dependencies and would be impacted by modifying it. ### Syntax ```bash codepulse ghost [options] ``` ### What `ghost` does 1. Resolves the target file in the dependency graph. 2. Identifies all direct dependents (files importing this file). 3. Traverses the graph transitively to calculate the entire downstream dependency footprint. 4. Outputs the relative percentage of impacted project files. ### Example Output ``` Blast Radius: src/analyzer/index.ts ────────────────────────────────────────────────────── ⚠️ Changes to this file directly impact 12 modules: ➔ src/commands/scan.ts ➔ src/commands/watch.ts ➔ src/mcp/handlers-health.ts ... ────────────────────────────────────────────────────── Total Project Impact: 45 / 101 files (44.6%) ⚠️ WARNING: HIGH BLAST RADIUS. This is a Core Architectural Node. ``` --- ## 16. The `synth` Command Synthesizes a targeted structural testing checklist based on the project's critical nodes and god files. ### Syntax ```bash codepulse synth [dir] ``` ### What `synth` does 1. Extracts the Top 3 Critical Nodes and Top 3 God Files. 2. Generates semantic test scenario recommendations for each highlight. 3. Outputs the plan as `STRESS_TEST_PLAN.md`. ### Structure of `STRESS_TEST_PLAN.md` ```markdown # 🧪 CodePulse Synthetic Test Plan ## 🎯 Priority Targets ### 🔴 watch.ts (God File) - [ ] Integration Boundary Test - [ ] Dependency Failure Simulation - [ ] Concurrency Stress - [ ] State Mutation Audit ## 🛠️ Implementation Heuristics 1. Mock Everything 2. Fuzzing 3. Snapshot Testing ``` --- ## 17. The `verify` Command Executes a comprehensive, smart project validation pipeline: Typecheck → Build → Lint → Impacted Tests. ### Syntax ```bash codepulse verify [dir] ``` ### What `verify` does 1. Automatically identifies the active environment (e.g., `typescript-node`, `javascript-node`, `python`). 2. Runs environment-specific validation steps: - **TypeScript**: `tsc --noEmit` → `npm run build` → `npm run lint` - **Python**: `ruff check .` 3. Scans for changed files using `git diff --name-only HEAD`. 4. Utilizes the dependency graph to isolate which test files are downstream of those changes. 5. Executes only the impacted unit tests (vitest / jest). 6. In case of verification failures, provides AI-driven Root Cause Analysis. ### Example Output ``` Starting Project Verification in /path/to/project ────────────────────────────────────────────────── ✔ Typecheck ✔ Build ✔ Lint ✔ Tests passed: 3 / 3 ────────────────────────────────────────────────── ✅ Verification successful! Project is in GOD MODE. ✓ ``` --- ## 18. The `pr-risk` Command Evaluates the architectural impact and structural risk of code changes in a Pull Request. ### Syntax ```bash # Via CLI flag parameter codepulse pr-risk --files src/a.ts,src/b.ts # Via stdin (piped from git diff) git diff --name-only HEAD | codepulse pr-risk ``` ### Flags | Flag | Description | |---|---| | `--files ` | Comma-separated list of modified files | | `--stdin` | Reads the file list from stdin | | `--threshold ` | Risk threshold score for exiting with status 1 (default: 60) | ### File Risk Formula ``` Centrality Score = min(centrality/50, 1) × 30 Complexity Score = min(complexity/30, 1) × 25 Churn Score = min(churn/50, 1) × 15 God File penalty +20 Critical Node penalty +15 ───────────────────────────────────────────────── Total Risk Score = min(sum, 100) ``` ### Temporal Coupling Warnings If file A has been edited, but file B (temporally coupled to A with degree ≥ 70%) is not included in the changes, the command prints a warning. ### Example Output ``` 🔴 PR Risk Score: 72/100 ──────────────────────────────────────── src/analyzer/index.ts ● High centrality (43) ● Risk contribution: 55 pts src/commands/watch.ts ● God File detected ● Risk contribution: 72 pts ⚠️ Missing from PR but temporally coupled: • src/commands/scan.ts (coupled with src/analyzer/index.ts) ``` --- ## 19. The `review` Command Performs a comprehensive CI/CD code review: analyzes structure, validates PR changes, and posts an integrated markdown review directly to the GitHub Pull Request. ### Syntax ```bash codepulse review [dir] [options] ``` ### Flags | Flag | Description | |---|---| | `--github` | Publishes the audit review as a PR comment | | `--json` | Outputs the findings in JSON format | ### What `review` does 1. Executes `analyze()`. 2. Pinpoints the list of changed files in this commit (`git diff HEAD^ HEAD`). 3. Checks for regressions, critical errors, and the emergence of new God Files. 4. Calculates the Impact Score for each modified file. 5. Generates a clean Markdown review report. 6. If `--github` is specified, uses `@octokit/rest` to publish this report as a comment on the active PR. ### Environment Variables for `--github` ```bash GITHUB_TOKEN=... # Token with write access to PR comments GITHUB_EVENT_PATH=... # Path to event.json (configured automatically by Actions) GITHUB_REPOSITORY=... # owner/repo FAIL_ON_CRITICAL=true # Exit with status 1 if critical regressions are found ``` --- ## 20. The `agent` Command Configures rules, protocols, and prompt contexts for developer AI Assistants (Cursor, Cline, Claude, Copilot, etc.). ### Syntax ```bash codepulse agent [prompt-name] codepulse agent config # TUI Prompt Configurator codepulse agent prompt config # Add a custom prompt template ``` ### Supported AI Agents (23 total) | Agent | Config Target Filename | |---|---| | Cline / Roo-Cline | `.clinerules` | | Cursor | `.cursorrules` | | Windsurf | `.windsurfrules` | | GitHub Copilot | `.github/copilot-instructions.md` | | Claude Code | `CLAUDE.md` | | Claude Rules | `.clauderules` | | Codex CLI | `.codexrules` / `CODEX.md` | | Aider | `.aider.conf.yml` | | Gemini CLI | `.gemini-instructions.md` | | Qwen | `.qwenrules` | | AMP | `.amprules` | | OpenCode | `.opencoderules` | | Kilo | `.kilorules` | | Trae | `.traerules` | | Pi Coding Agent | `.pirules` | | Kiro CLI | `.kirorules` | | PearAI | `.pearrules` | | Supermaven | `.supermavenrules` | | Void | `.voidrules` | | **Antigravity** | `.antigravityrules` | | Cody (Sourcegraph) | `.cody/AGENT.md` | | Continue.dev | `.continue/rules/codepulse.md` | ### Built-in Prompt Strategies | Prompt Name | Description | |---|---| | `default` | CodePulse Master Rules (5-phase analysis protocol) | | `creative` | Creative Architect Mode — brainstorm designs thoroughly before implementing | | `productivity` | Direct Action Mode — clean, fast implementations without overengineering | ### Examples ```bash # Setup Claude with the default ruleset codepulse agent claude default # Setup Cursor with the creative strategy prompt codepulse agent cursor creative # Open the TUI Prompt Configurator dashboard codepulse agent config # Register a custom prompt template codepulse agent prompt config ``` ### CodePulse Master Rules (`default`) Sets up a strict 5-phase execution protocol for AI Agents: 1. **PHASE 1 — Reconnaissance**: Call `codepulse_identity` to obtain a high-level project map. 2. **PHASE 2 — Structural Audit**: Validate boundaries via `get_layers` and `get_architecture_violations`. 3. **PHASE 3 — Pre-flight Risk**: Check `get_file_context` before modifying any files. 4. **PHASE 4 — Surgical Execution**: Use `find_similar_functions` to de-duplicate AST syntax. 5. **PHASE 5 — Validation**: Re-run `get_project_stats` and `get_architecture_violations` to verify stability. --- ## 21. The `license` Command Generates a standard `LICENSE` file based on popular open-source templates. ### Syntax ```bash codepulse license [author-name] codepulse license help # Displays list of supported licenses ``` ### Supported License Types `mit` · `isc` · `bsd-2` · `bsd-3` · `unlicense` · `apache` · `gpl` · `agpl` · `lgpl` · `mpl` ### Example ```bash codepulse license mit "John Doe" # → Generates a ./LICENSE file populated with the current year and the author name. ``` --- ## 22. The `detect-reward-hacking` Command Uses AST analysis (`ts-morph`) to identify patterns associated with "reward hacking" (shortcuts designed to trick metrics) in AI-generated code. ### Syntax ```bash codepulse detect-reward-hacking [dir] ``` ### Detection Patterns | Pattern | Code | Description | |---|---|---| | Hardcoded I/O shortcuts | `IO_SHORTCUT` | Hardcoded return conditions like `if (input === "x") return "y"` | | Large literal lookup tables | `BENCHMARK_HACK` | Objects containing >8 literal keys, often used to bypass calculations | | Validation bypasses | `VALIDATION_BYPASS` | Conditions containing `IS_BENCHMARK`, `is_test`, or `bypass` flags | ### Example Output ``` 🕵️ Detected 2 Reward Hacking patterns! [IO_SHORTCUT] src/calculator.ts:42 Suspicious hardcoded input-output shortcut detected. > if (input === "2+2") return "4"; [BENCHMARK_HACK] src/solver.ts:15 Suspiciously large literal lookup table (12 entries). > { "test1": "result1", "test2": "result2", ... ``` --- ## 23. The `install-deps` Command Automatically installs external linters required to analyze the project's languages. ### Syntax ```bash codepulse install-deps ``` ### Supported Linters & Managers | Linter | Language | Managers | |---|---|---| | `oxlint` | JS/TS | npm (global) | | `ruff` | Python | pip / pacman / apk | | `cppcheck` | C/C++ | apt / pacman / dnf / brew | | `shellcheck` | Shell | apt / pacman / brew | | `golangci-lint` | Go | go install / brew / scoop | | `revive` | Go | go install | | `luacheck` | Lua | luarocks / apt | | `selene` | Lua | cargo / brew / scoop | | `clippy` | Rust | rustup / cargo | **Detected Package Managers:** `apt-get`, `pacman`, `dnf`, `zypper`, `apk` (Linux), `brew` (macOS), `choco`, `scoop`, `winget` (Windows). **`runInstallDepsForProject`** is called automatically during a `scan`: it inspects files by extension and installs only the tools matching the project's language footprint. --- ## 24. MCP Server CodePulse contains a fully featured **Model Context Protocol (MCP) server** to power advanced integrations with AI Agents. ### Execution ```bash codepulse mcp # Starts the MCP server (stdio transport) codepulse mcp setup # Installs the MCP configuration into agent configs ``` ### Available MCP Tools **Project Health & Insights:** | Tool Name | Description | |---|---| | `codepulse_identity` | Full project health check: scores, god files, and critical nodes | | `get_project_stats` | Fast numeric KPIs (file count, lines, average complexity) | | `analyze_project` | Search and filter discovered code issues (by focus, severity, limit) | | `find_dead_code` | Identifies unused exports | | `get_hotspots` | Lists files featuring both high complexity and high change frequency | | `explain_concept` | Explains architectural concepts (god-file, dead-export, etc.) | **Architecture & Graph:** | Tool Name | Description | |---|---| | `get_file_context` | Context of a file: complexity, centrality, temporal coupling | | `get_file_dependencies` | Retrieves direct imports and dependents of a file | | `get_blast_radius` | Calculates downstream transitive blast radius of a file | | `visualize_subgraph` | Renders a Mermaid diagram of dependencies for a file | | `get_directory_context` | Delivers an architectural review of a specific directory | | `find_cycles_for_file` | Checks for circular dependency loops involving a file | | `get_layers` | Displays defined architectural layers | | `get_architecture_violations` | Identifies dependencies breaking layer boundaries | **Semantic Code Analysis:** | Tool Name | Description | |---|---| | `get_evolutionary_risk` | Correlates file age, complexity, and churn rate to predict code rot | | `get_authorship_metadata` | Identifies the main authors of a file via git blame | | `find_similar_functions` | Identifies structurally similar logic using AST fingerprinting | | `identify_orphans` | Lists files that are not imported by any other file | | `predict_change_impact` | Traces potential impact when changing a specific export or symbol | | `simulate_edit` | AST-validates proposed file changes before writing | **Agent Utilities:** | Tool Name | Description | |---|---| | `optimize_context_for_claude` | Returns the minimal set of files relevant to a specific goal | | `store_memory` | Records a persistent architectural design decision in project memory | | `get_memories` | Retrieves stored contextual decisions | | `list_plugins` | Lists loaded active plugins | | `request_architecture_review` | Runs a check to confirm changes respect architectural guidelines | | `get_semantic_slice` | Retrieves the exact contents of a specific function, class, or export | | `suggest_split_strategy` | Formulates a refactoring layout plan to break up a God File | ### MCP Config in Claude Desktop (`mcp-setup`) ```bash codepulse mcp setup ``` Populates the MCP configuration settings directly inside the configuration targets of supported agents (Claude Desktop, Cursor, etc.). --- ## 25. GitHub Actions ### Usage ```yaml - name: CodePulse Review uses: archpulse/codepulse-cli@v5 with: command: review # review | verify | audit | dir: . github_token: ${{ secrets.GITHUB_TOKEN }} fail_on_critical: true ``` ### Parameters | Parameter | Default | Description | |---|---|---| | `command` | `review` | Target CLI command: `review`, `verify`, `audit`, etc. | | `dir` | `.` | Target project directory | | `github_token` | `${{ github.token }}` | GitHub API token for writing PR comments | | `fail_on_critical` | `true` | Exit with status 1 if critical regressions are found | ### Example: Full CI Pipeline ```yaml name: CodePulse CI on: [pull_request] jobs: architecture-review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # Fetch full history for temporal coupling & time machine support - name: CodePulse Review uses: archpulse/codepulse-cli@v5 with: command: review github_token: ${{ secrets.GITHUB_TOKEN }} - name: CodePulse Verify uses: archpulse/codepulse-cli@v5 with: command: verify - name: PR Risk Assessment run: | git diff --name-only HEAD^ HEAD | npx @archpulse/codepulse pr-risk --threshold 70 ``` --- ## 26. Plugins CodePulse features an extensible plugin architecture to load custom architectural rule packs. ### Locations ``` plugins/ # Located inside the project root ~/.codepulse/plugins # Located globally under home directory ``` ### Plugin Structure ```typescript export default { name: "my-plugin", version: "1.0.0", description: "Custom architectural rules", author: "Your Name", category: "rules", rules: [ { id: "no-direct-db-import", check: (file, result) => { // Validation logic return []; // Returns an array of Issue[] } } ] }; ``` ### Command to list plugins ```bash codepulse plugins list # Plain terminal display codepulse plugins list --json # Structured JSON display ``` --- ## 27. Internationalization (i18n) CodePulse features locale-aware support across 7 target languages. ### Supported Locales | Language Code | Language | Time Format | |---|---|---| | `en` | English | 12-hour format (AM/PM) | | `ru` | Russian | 24-hour format | | `ua` | Ukrainian | 24-hour format | | `de` | German | 24-hour format | | `fr` | French | 24-hour format | | `ko` | Korean | 12-hour format | | `cs` | Czech | 24-hour format | ### Language Selection ```bash codepulse lang ru # Switch system locale to Russian codepulse lang en # Switch system locale to English ``` Selection is saved persistently under `~/.gemini/tmp/codepulse-cli/settings.json`. ### README Translations README files are maintained individually under the `translations/` directory: - `README.ru.md`, `README.ua.md`, `README.de.md` - `README.fr.md`, `README.ko.md`, `README.cs.md` --- ## 28. Webhook Alerts CodePulse dispatches push-notification alerts when a project's Health Score falls below set margins. ### Configuration (`.codepulse.json`) ```json { "alerts": { "slack": "$CODEPULSE_SLACK_WEBHOOK", "discord": "$CODEPULSE_DISCORD_WEBHOOK", "telegram": { "token": "$TELEGRAM_BOT_TOKEN", "chatId": "-1001234567890" }, "threshold": 80, "branches": ["main", "master"] } } ``` ### Alert Dispatch Rules 1. Dispatched only if `Health Score < threshold`. 2. Dispatched only if the active branch matches the listed `branches` array. 3. Placeholder strings (e.g., `XXXXXXXX`) are skipped automatically. ### Alert Payload Contents - Project Name. - Git metadata: Branch, commit SHA, author, and commit message. - Current Health Score and threshold setting. - Statistics overview: God Files, Circular Deps, Critical Nodes, Dead Exports, and Hotspots. --- ## 29. Exit Codes | Exit Code | Condition | |---|---| | `0` | Successful completion | | `1` | Critical issues found (when using `--fail-on error` or `--strict`) | | `1` | PR Risk Score exceeds threshold | | `1` | Health Score drop exceeds `--threshold` delta (during `diff`) | | `1` | Project validation fails (during `verify`) | | `1` | Specified directory could not be located | --- ## 30. Quick Reference Sheet ```bash # Core scan codepulse scan . codepulse scan . --json --fail-on error # Real-time monitoring codepulse watch . # Git-based diff comparison codepulse diff main --threshold 5 # Metric history and forecasting codepulse time-machine . --strategy interval --interval weekly codepulse health-trend . # Visualization dashboards codepulse heatmap . codepulse coupling . # In-depth architectural audit codepulse audit . # CI/CD workflows codepulse review . --github codepulse verify . git diff --name-only HEAD | codepulse pr-risk --threshold 60 # Single file blast radius codepulse ghost src/analyzer/index.ts # AI agent workspace setup codepulse agent claude default codepulse mcp # Execution profiling codepulse profile cpu.cpuprofile --dir . # Utilities codepulse license mit "John Doe" codepulse install-deps codepulse detect-reward-hacking . codepulse synth . codepulse explain god-file codepulse lang ru ```