aico-cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -0
  3. package/bin/aico.mjs +2 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.mjs +1475 -0
  7. package/dist/index.d.mts +154 -0
  8. package/dist/index.d.ts +154 -0
  9. package/dist/index.mjs +10 -0
  10. package/dist/shared/aico-cli.D4gky7Vp.mjs +2322 -0
  11. package/package.json +57 -0
  12. package/templates/CLAUDE.md +5 -0
  13. package/templates/en/memory/mcp.md +6 -0
  14. package/templates/en/memory/personality.md +1 -0
  15. package/templates/en/memory/rules.md +45 -0
  16. package/templates/en/memory/technical-guides.md +97 -0
  17. package/templates/en/workflow/bmad/commands/bmad-init.md +103 -0
  18. package/templates/en/workflow/git/commands/git-cleanBranches.md +101 -0
  19. package/templates/en/workflow/git/commands/git-commit.md +152 -0
  20. package/templates/en/workflow/git/commands/git-rollback.md +89 -0
  21. package/templates/en/workflow/plan/agents/planner.md +116 -0
  22. package/templates/en/workflow/plan/agents/ui-ux-designer.md +91 -0
  23. package/templates/en/workflow/plan/commands/feat.md +105 -0
  24. package/templates/en/workflow/sixStep/commands/workflow.md +230 -0
  25. package/templates/settings.json +33 -0
  26. package/templates/zh-CN/memory/mcp.md +34 -0
  27. package/templates/zh-CN/memory/personality.md +1 -0
  28. package/templates/zh-CN/memory/rules.md +45 -0
  29. package/templates/zh-CN/memory/technical-guides.md +126 -0
  30. package/templates/zh-CN/workflow/bmad/commands/bmad-init.md +109 -0
  31. package/templates/zh-CN/workflow/git/commands/git-cleanBranches.md +101 -0
  32. package/templates/zh-CN/workflow/git/commands/git-commit.md +152 -0
  33. package/templates/zh-CN/workflow/git/commands/git-rollback.md +90 -0
  34. package/templates/zh-CN/workflow/plan/agents/planner.md +116 -0
  35. package/templates/zh-CN/workflow/plan/agents/ui-ux-designer.md +91 -0
  36. package/templates/zh-CN/workflow/plan/commands/feat.md +105 -0
  37. package/templates/zh-CN/workflow/sixStep/commands/workflow.md +199 -0
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "aico-cli",
3
+ "version": "0.0.1",
4
+ "packageManager": "pnpm@9.15.9",
5
+ "description": "AI CLI",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://code.devcloud.cnpc:8091/gitlab/AI-AGENT/tpl/ai-cli.git"
9
+ },
10
+ "license": "MIT",
11
+ "author": "WYP",
12
+ "main": "dist/index.mjs",
13
+ "module": "dist/index.mjs",
14
+ "types": "dist/index.d.mts",
15
+ "bin": {
16
+ "aico": "bin/aico.mjs"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "bin",
21
+ "templates"
22
+ ],
23
+ "scripts": {
24
+ "dev": "tsx ./src/cli.ts",
25
+ "build": "unbuild",
26
+ "typecheck": "tsc",
27
+ "prepublishOnly": "npm run build",
28
+ "test": "vitest",
29
+ "test:ui": "vitest --ui",
30
+ "test:coverage": "vitest --coverage",
31
+ "test:run": "vitest run",
32
+ "test:watch": "vitest watch",
33
+ "changeset": "changeset",
34
+ "version": "changeset version",
35
+ "release": "pnpm build && changeset publish"
36
+ },
37
+ "dependencies": {
38
+ "ansis": "^3.17.0",
39
+ "cac": "^6.7.14",
40
+ "dayjs": "^1.11.13",
41
+ "find-up-simple": "^1.0.1",
42
+ "inquirer": "^12.9.0",
43
+ "pathe": "^2.0.3",
44
+ "tinyexec": "^1.0.1"
45
+ },
46
+ "devDependencies": {
47
+ "@changesets/cli": "^2.29.5",
48
+ "@types/inquirer": "^9.0.8",
49
+ "@types/node": "^22.17.0",
50
+ "@vitest/coverage-v8": "^3.2.4",
51
+ "@vitest/ui": "^3.2.4",
52
+ "tsx": "^4.20.3",
53
+ "typescript": "^5.9.2",
54
+ "unbuild": "^3.6.0",
55
+ "vitest": "^3.2.4"
56
+ }
57
+ }
@@ -0,0 +1,5 @@
1
+ @language.md
2
+ @personality.md
3
+ @rules.md
4
+ @technical-guides.md
5
+ @mcp.md
@@ -0,0 +1,6 @@
1
+ ### Prioritize using MCP service
2
+
3
+ - `Context7`: Query latest library documentation/examples
4
+ - `DeepWiki`: Query related GitHub repository documentation/examples
5
+ - `Exa`: Use Exa AI for web search - real-time web search, can capture specific URL content. Supports configurable result count and returns most relevant website content
6
+ - `Playwright`: Direct browser control for browser-related operations
@@ -0,0 +1 @@
1
+ You are an experienced [professional domain, e.g., Software Development Engineer / System Designer / Code Architect], specializing in building [core strengths, e.g., high-performance / maintainable / robust / domain-driven] solutions.
@@ -0,0 +1,45 @@
1
+ Your mission is: **Review, understand, and iteratively improve/advance a [project type, e.g., existing codebase / software project / technical process].**
2
+
3
+ Throughout the entire workflow, you must internalize and strictly adhere to the following core programming principles, ensuring that every output and recommendation reflects these concepts:
4
+
5
+ - **Keep It Simple, Stupid (KISS):** Pursue ultimate simplicity and intuitiveness in code and design, avoiding unnecessary complexity.
6
+ - **You Aren't Gonna Need It (YAGNI):** Implement only the functionality that is clearly needed now, resist over-engineering and unnecessary future feature reservations.
7
+ - **SOLID Principles:**
8
+ - **S (Single Responsibility Principle):** Each component, class, and function should have only one clear responsibility.
9
+ - **O (Open/Closed Principle):** Software entities should be open for extension but closed for modification.
10
+ - **L (Liskov Substitution Principle):** Subtypes must be substitutable for their base types seamlessly.
11
+ - **I (Interface Segregation Principle):** Interfaces should be specific and focused, avoiding "fat interfaces."
12
+ - **D (Dependency Inversion Principle):** Depend on abstractions, not concrete implementations.
13
+ - **Don't Repeat Yourself (DRY):** Identify and eliminate repetitive patterns in code or logic to improve reusability.
14
+ - **Documentation Sync:** Code changes must be synchronized with relevant documentation updates.
15
+
16
+ **Please strictly follow the workflow and output requirements below:**
17
+
18
+ 1. **Deep Understanding and Initial Analysis (Understanding Phase):**
19
+
20
+ - Thoroughly review the provided [materials/code/project description], comprehensively understanding its current architecture, core components, business logic, and pain points.
21
+ - Based on this understanding, preliminarily identify potential applications or violations of **KISS, YAGNI, DRY, SOLID** principles within the project.
22
+
23
+ 2. **Clear Objectives and Iterative Planning (Planning Phase):**
24
+
25
+ - Based on user requirements and understanding of the existing project, clearly define the specific task scope and measurable expected outcomes for this iteration.
26
+ - When planning solutions, prioritize how to achieve simpler, more efficient, and more scalable improvements through applying the above principles, rather than blindly adding features.
27
+
28
+ 3. **Step-by-Step Implementation and Specific Improvements (Execution Phase):**
29
+
30
+ - Provide detailed explanations of your improvement proposals and break them down into logically clear, actionable steps.
31
+ - For each step, specifically explain how you will operate and how these operations embody **KISS, YAGNI, DRY, SOLID** principles. For example:
32
+ - "Split this module into smaller services to follow SRP and OCP."
33
+ - "To avoid DRY violations, abstract the repetitive XXX logic into a common function."
34
+ - "Simplified the user flow for Y feature, embodying the KISS principle."
35
+ - "Removed Z redundant design, following the YAGNI principle."
36
+ - Focus on specific implementation details for [project type, e.g., code quality optimization / architecture refactoring / feature enhancement / user experience improvement / performance tuning / maintainability improvement / bug fixes].
37
+
38
+ 4. **Summary, Reflection, and Outlook (Reporting Phase):**
39
+ - Check if documentation needs updating (README, CHANGELOG, API docs, etc.).
40
+ - Provide a clear, structured summary report that includes **actual code/design change recommendations (if applicable)**.
41
+ - The report must include:
42
+ - **Core tasks completed in this iteration** and their specific outcomes.
43
+ - **How you specifically applied** **KISS, YAGNI, DRY, SOLID** **principles in this iteration**, with brief explanations of the benefits they brought (e.g., reduced code volume, improved readability, enhanced extensibility).
44
+ - **Challenges encountered** and how they were overcome.
45
+ - **Clear plans and recommendations for next steps.**
@@ -0,0 +1,97 @@
1
+ # Technical Execution Guidelines
2
+
3
+ This document provides best practices for Claude Code when executing technical tasks.
4
+
5
+ ## Dangerous Operations Confirmation
6
+
7
+ **Important**: The following operations require explicit user confirmation before execution:
8
+
9
+ ### Operations Requiring Confirmation
10
+ - **File System**: Delete files/directories, bulk modifications, move system files
11
+ - **Code Commits**: `git commit`, `git push`, `git reset --hard`
12
+ - **System Config**: Modify environment variables, system settings, permissions
13
+ - **Data Operations**: Database deletions, schema changes, bulk updates
14
+ - **Network Requests**: Send sensitive data, call production APIs
15
+ - **Package Management**: Global install/uninstall, update core dependencies
16
+
17
+ ### Confirmation Process
18
+ Before executing dangerous operations:
19
+ 1. Clearly explain the operation and its impacts
20
+ 2. Wait for explicit user confirmation (e.g., "yes", "confirm", "proceed")
21
+ 3. If user hesitates or declines, provide more information or alternatives
22
+
23
+ ## Command Execution Best Practices
24
+
25
+ ### Path Handling Standards
26
+
27
+ **Important**: Always use double quotes to wrap file paths when executing commands.
28
+
29
+ ```bash
30
+ # ✅ Correct
31
+ cd "C:\Users\name\My Documents"
32
+ node "/path/with spaces/app.js"
33
+
34
+ # ❌ Incorrect
35
+ cd C:\Users\name\My Documents
36
+ ```
37
+
38
+ ### Cross-Platform Compatibility
39
+ - Prefer forward slashes `/` as path separators
40
+ - When using backslashes, ensure paths are double-quoted
41
+
42
+ ## Search Tool Usage
43
+
44
+ ### Content Search
45
+ **Always prioritize `rg` (ripgrep)** - faster and won't timeout.
46
+
47
+ ```bash
48
+ # ✅ Preferred
49
+ rg "pattern" .
50
+ rg -t js "console.log" .
51
+
52
+ # ⚠️ Fallback
53
+ grep -r "pattern" .
54
+ ```
55
+
56
+ > Note: If `rg` unavailable, remind user to install: `brew/scoop/apt install ripgrep`
57
+
58
+ ### File Finding
59
+ - Use Glob tool for pattern matching
60
+ - Use LS tool for directory listings
61
+ - Avoid using `find` command
62
+
63
+ ## Tool Usage Principles
64
+
65
+ 1. **Prefer Specialized Tools**: Use Read, Write, Edit instead of cat, echo
66
+ 2. **Batch Operations**: Call multiple tools simultaneously for efficiency
67
+ 3. **Error Handling**: Check path quoting first when commands fail
68
+
69
+ ## Performance Optimization
70
+
71
+ - Use Task tool for complex searches in large projects
72
+ - Understand project structure before searching
73
+ - Use file type filters wisely for efficiency
74
+
75
+ ## Documentation Update Check
76
+
77
+ Automatically check documentation update needs after task completion:
78
+
79
+ ### Criteria
80
+ - **New Features**: Update README, CHANGELOG, usage docs
81
+ - **API Changes**: Update API docs, type definitions, interface specs
82
+ - **Config Changes**: Update config guides, CLAUDE.md, env var docs
83
+ - **Bug Fixes**: Usually no doc updates needed (unless usage affected)
84
+
85
+ ### Process
86
+ 1. Analyze code change type and impact scope
87
+ 2. Auto-identify documentation files in project
88
+ 3. List documents needing updates
89
+ 4. Request user confirmation: `The following docs may need updates: [doc list]. Would you like me to update them?`
90
+ 5. Update relevant docs after confirmation
91
+
92
+ ### Common Document Types
93
+ - **README.md**: Features, usage, configuration
94
+ - **CHANGELOG.md**: Version history
95
+ - **CLAUDE.md**: AI assistant config and instructions
96
+ - **API Docs**: Interface definitions, parameters
97
+ - **Config Docs**: Environment variables, settings
@@ -0,0 +1,103 @@
1
+ # /bmad-init Command
2
+
3
+ This command initializes BMad Method in your project.
4
+
5
+ ## When this command is invoked:
6
+
7
+ 1. Check if BMad is already installed by looking for `.bmad-core/install-manifest.yaml`
8
+ 2. If installed, check version in manifest against latest version
9
+ 3. If not installed or outdated, execute: `npx bmad-method@latest install -f -d . -i claude-code`
10
+ 4. Display success message and prompt user to restart Claude Code
11
+
12
+ ## Implementation
13
+
14
+ ```javascript
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { execSync } = require('child_process');
18
+
19
+ async function initBmad() {
20
+ // Check if already installed and get version
21
+ const manifestPath = path.join(process.cwd(), '.bmad-core', 'install-manifest.yaml');
22
+ let needsInstall = true;
23
+ let currentVersion = null;
24
+
25
+ if (fs.existsSync(manifestPath)) {
26
+ try {
27
+ // Simple version check - just check if file exists
28
+ // Full YAML parsing would require js-yaml package
29
+ const manifestContent = fs.readFileSync(manifestPath, 'utf8');
30
+ const versionMatch = manifestContent.match(/version:\s*(.+)/);
31
+ if (versionMatch) {
32
+ currentVersion = versionMatch[1].trim();
33
+ }
34
+
35
+ // Get latest version from npm
36
+ const latestVersion = execSync('npm view bmad-method version', { encoding: 'utf8' }).trim();
37
+
38
+ if (currentVersion === latestVersion) {
39
+ console.log(`✅ BMad Method is up to date (v${currentVersion})`);
40
+ console.log('You can use BMad commands to begin your workflow');
41
+ needsInstall = false;
42
+ } else {
43
+ console.log(`🔄 BMad Method update available: v${currentVersion} → v${latestVersion}`);
44
+ }
45
+ } catch (error) {
46
+ console.log('⚠️ Could not verify BMad version, will reinstall');
47
+ }
48
+ }
49
+
50
+ if (needsInstall === false) {
51
+ return;
52
+ }
53
+
54
+ // Install BMad
55
+ console.log('🚀 Installing BMad Method...');
56
+ try {
57
+ execSync('echo -e "1\\n" | npx bmad-method@latest install -f -d . -i claude-code', {
58
+ stdio: 'inherit',
59
+ cwd: process.cwd(),
60
+ shell: true
61
+ });
62
+
63
+ console.log('✅ BMad Method installed successfully!');
64
+ console.log('');
65
+ console.log('═══════════════════════════════════════════════════════════════');
66
+ console.log('📌 IMPORTANT: Please restart Claude Code to load BMad agents');
67
+ console.log('═══════════════════════════════════════════════════════════════');
68
+ console.log('');
69
+ console.log('📂 Installation Details:');
70
+ console.log(' • All agents and task commands are installed in:');
71
+ console.log(' .claude/commands/BMad/');
72
+ console.log('');
73
+ console.log('🔧 Git Configuration (Optional):');
74
+ console.log(' If you prefer not to commit BMad workflow files, add these to .gitignore:');
75
+ console.log(' • .bmad-core');
76
+ console.log(' • .claude/commands/BMad');
77
+ console.log(' • docs/');
78
+ console.log('');
79
+ console.log('🚀 Getting Started:');
80
+ console.log(' 1. Restart Claude Code');
81
+ console.log(' 2. For first-time users, run:');
82
+ console.log(' /BMad:agents:bmad-orchestrator *help');
83
+ console.log(' This will start the BMad workflow guidance system');
84
+ console.log('');
85
+ console.log('💡 Tip: The BMad Orchestrator will help you choose the right workflow');
86
+ console.log(' and guide you through the entire development process.');
87
+
88
+ } catch (error) {
89
+ console.error('❌ Failed to install BMad:', error.message);
90
+ process.exit(1);
91
+ }
92
+ }
93
+
94
+ // Execute
95
+ initBmad();
96
+ ```
97
+
98
+ ## Notes
99
+
100
+ - This command requires npm/npx to be available
101
+ - The installation will download the latest BMad Method package
102
+ - User must restart Claude Code after installation for agents to load properly
103
+ - BMad Method includes its own built-in state tracking system
@@ -0,0 +1,101 @@
1
+ ---
2
+ description: Safely find and clean up merged or stale Git branches with dry-run mode and custom base/protected branches support
3
+ allowed-tools: Read(**), Exec(git fetch, git config, git branch, git remote, git push, git for-each-ref, git log), Write()
4
+ argument-hint: [--base <branch>] [--stale <days>] [--remote] [--force] [--dry-run] [--yes]
5
+ # examples:
6
+ # - /git-cleanBranches --dry-run
7
+ # - /git-cleanBranches --base release/v2.1 --stale 90
8
+ # - /git-cleanBranches --remote --yes
9
+ ---
10
+
11
+ # Claude Command: Clean Branches
12
+
13
+ This command **safely** identifies and cleans up **merged** or **stale** Git branches.
14
+ Runs in **read-only preview (`--dry-run`)** mode by default, requiring explicit instructions to perform deletions.
15
+
16
+ ---
17
+
18
+ ## Usage
19
+
20
+ ```bash
21
+ # [Safest] Preview branches to be cleaned without executing any deletions
22
+ /git-cleanBranches --dry-run
23
+
24
+ # Clean local branches merged to main and inactive for over 90 days (requires individual confirmation)
25
+ /git-cleanBranches --stale 90
26
+
27
+ # Clean local and remote branches merged to release/v2.1 (auto-confirm)
28
+ /git-cleanBranches --base release/v2.1 --remote --yes
29
+
30
+ # [Dangerous] Force delete an unmerged local branch
31
+ /git-cleanBranches --force outdated-feature
32
+ ```
33
+
34
+ ### Options
35
+ - `--base <branch>`: Specify the base branch for cleanup (defaults to repository's `main`/`master`).
36
+ - `--stale <days>`: Clean branches with no commits for specified days (disabled by default).
37
+ - `--remote`: Also clean remote merged/stale branches.
38
+ - `--dry-run`: **Default behavior**. Only list branches to be deleted without executing any operations.
39
+ - `--yes`: Skip individual confirmations and delete all identified branches directly (suitable for CI/CD).
40
+ - `--force`: Use `-D` to force delete local branches (even if unmerged).
41
+
42
+ ---
43
+
44
+ ## What This Command Does
45
+
46
+ 1. **Configuration and Safety Checks**
47
+ - **Update Information**: Automatically executes `git fetch --all --prune` to ensure branch status is current.
48
+ - **Read Protected Branches**: Reads the list of branches that should not be cleaned from Git config (see "Configuration" below).
49
+ - **Determine Base**: Uses `--base` parameter or auto-detected `main`/`master` as comparison baseline.
50
+
51
+ 2. **Analysis and Identification (Find)**
52
+ - **Merged Branches**: Find local (and remote if `--remote` is added) branches fully merged to `--base`.
53
+ - **Stale Branches**: If `--stale <days>` is specified, find branches with last commit N days ago.
54
+ - **Exclude Protected Branches**: Remove all configured protected branches from cleanup list.
55
+
56
+ 3. **Report and Preview (Report)**
57
+ - Clearly list "merged branches to be deleted" and "stale branches to be deleted".
58
+ - Without `--yes` parameter, **command ends here**, waiting for user confirmation to re-execute (without `--dry-run`).
59
+
60
+ 4. **Execute Cleanup (Execute)**
61
+ - **Only executed without `--dry-run` and after user confirmation** (or with `--yes`).
62
+ - Delete identified branches one by one, unless user chooses to skip in interactive confirmation.
63
+ - Local: `git branch -d <branch>`; Remote: `git push origin --delete <branch>`.
64
+ - If `--force` is specified, local deletion uses `git branch -D <branch>`.
65
+
66
+ ---
67
+
68
+ ## Configuration (Configure Once, Use Forever)
69
+
70
+ To prevent accidental deletion of important branches (e.g., `develop`, `release/*`), add protection rules to the repository's Git config. The command reads them automatically.
71
+
72
+ ```bash
73
+ # Protect develop branch
74
+ git config --add branch.cleanup.protected develop
75
+
76
+ # Protect all branches starting with release/ (wildcard)
77
+ git config --add branch.cleanup.protected 'release/*'
78
+
79
+ # View all configured protected branches
80
+ git config --get-all branch.cleanup.protected
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Best Practices for Embedded Devs
86
+
87
+ - **Prioritize `--dry-run`**: Develop the habit of previewing before executing.
88
+ - **Leverage `--base`**: When maintaining long-term `release` branches, use it to clean `feature` or `hotfix` branches merged to that release.
89
+ - **Careful with `--force`**: Don't force delete unless you're 100% certain an unmerged branch is useless.
90
+ - **Team Collaboration**: Notify the team channel before cleaning shared remote branches.
91
+ - **Regular Runs**: Run monthly or quarterly to keep the repository clean.
92
+
93
+ ---
94
+
95
+ ## Why This Version Is Better
96
+
97
+ - ✅ **Safer**: Default read-only preview with configurable protected branch list.
98
+ - ✅ **More Flexible**: Supports custom base branches, perfectly fits `release` / `develop` workflows.
99
+ - ✅ **More Compatible**: Avoids commands with inconsistent behavior across systems like `date -d`.
100
+ - ✅ **More Intuitive**: Condenses complex 16-step checklist into a single command with safety options.
101
+ - ✅ **Consistent Style**: Shares similar parameter design and documentation structure with `/commit` command.
@@ -0,0 +1,152 @@
1
+ ---
2
+ description: Analyze changes with Git only and auto-generate conventional commit messages with optional emoji; suggests splitting commits when needed, runs local Git hooks by default (use --no-verify to skip)
3
+ allowed-tools: Read(**), Exec(git status, git diff, git add, git restore --staged, git commit, git rev-parse, git config), Write(.git/COMMIT_EDITMSG)
4
+ argument-hint: [--no-verify] [--all] [--amend] [--signoff] [--emoji] [--scope <scope>] [--type <type>]
5
+ # examples:
6
+ # - /git-commit # Analyze current changes, generate commit message
7
+ # - /git-commit --all # Stage all changes and commit
8
+ # - /git-commit --no-verify # Skip Git hooks
9
+ # - /git-commit --emoji # Include emoji in commit message
10
+ # - /git-commit --scope ui --type feat # Specify scope and type
11
+ # - /git-commit --amend --signoff # Amend last commit with signature
12
+ ---
13
+
14
+ # Claude Command: Commit (Git-only)
15
+
16
+ This command works **without any package manager/build tools**, using only **Git** to:
17
+ - Read changes (staged/unstaged)
18
+ - Determine if changes should be **split into multiple commits**
19
+ - Generate **Conventional Commits** style messages with optional emoji for each commit
20
+ - Execute `git add` and `git commit` as needed (runs local Git hooks by default; use `--no-verify` to skip)
21
+
22
+ ---
23
+
24
+ ## Usage
25
+
26
+ ```bash
27
+ /git-commit
28
+ /git-commit --no-verify
29
+ /git-commit --emoji
30
+ /git-commit --all --signoff
31
+ /git-commit --amend
32
+ /git-commit --scope ui --type feat --emoji
33
+ ```
34
+
35
+ ### Options
36
+ - `--no-verify`: Skip local Git hooks (`pre-commit`/`commit-msg` etc.).
37
+ - `--all`: When staging area is empty, automatically `git add -A` to include all changes in the commit.
38
+ - `--amend`: **Amend** the last commit without creating a new one (preserves author and timestamp unless local Git config specifies otherwise).
39
+ - `--signoff`: Add `Signed-off-by` line (use when following DCO process).
40
+ - `--emoji`: Include emoji prefix in commit message (omit for plain text).
41
+ - `--scope <scope>`: Specify commit scope (e.g., `ui`, `docs`, `api`), written to message header.
42
+ - `--type <type>`: Force commit type (e.g., `feat`, `fix`, `docs`), overrides automatic detection.
43
+
44
+ > Note: If the framework doesn't support interactive confirmation, enable `confirm: true` in front-matter to avoid mistakes.
45
+
46
+ ---
47
+
48
+ ## What This Command Does
49
+
50
+ 1. **Repository/Branch Validation**
51
+ - Check if in a Git repository using `git rev-parse --is-inside-work-tree`.
52
+ - Read current branch/HEAD status; if in rebase/merge conflict state, prompt to resolve conflicts first.
53
+
54
+ 2. **Change Detection**
55
+ - Get staged and unstaged changes using `git status --porcelain` and `git diff`.
56
+ - If staged files = 0:
57
+ - If `--all` is passed → Execute `git add -A`.
58
+ - Otherwise prompt choice: continue analyzing unstaged changes for **suggestions**, or cancel to manually group staging.
59
+
60
+ 3. **Split Suggestions (Split Heuristics)**
61
+ - Cluster by **concerns**, **file modes**, **change types** (e.g., source code vs docs/tests; different directories/packages; additions vs deletions).
62
+ - If **multiple independent changesets** or large diff detected (e.g., > 300 lines / across multiple top-level directories), suggest splitting commits with pathspecs for each group (for subsequent `git add <paths>`).
63
+
64
+ 4. **Commit Message Generation (Conventional with Optional Emoji)**
65
+ - Auto-infer `type` (`feat`/`fix`/`docs`/`refactor`/`test`/`chore`/`perf`/`style`/`ci`/`revert`...) and optional `scope`.
66
+ - Generate message header: `[<emoji>] <type>(<scope>)?: <subject>` (first line ≤ 72 chars, imperative mood, emoji included only with `--emoji` flag).
67
+ - Generate message body: bullet points (motivation, implementation details, impact scope, BREAKING CHANGE if any).
68
+ - Write draft to `.git/COMMIT_EDITMSG` for use with `git commit`.
69
+
70
+ 5. **Execute Commit**
71
+ - Single commit scenario: `git commit [-S] [--no-verify] [-s] -F .git/COMMIT_EDITMSG`
72
+ - Multiple commit scenario (if split accepted): Provide clear instructions for `git add <paths> && git commit ...` per group; execute sequentially if allowed.
73
+
74
+ 6. **Safe Rollback**
75
+ - If mistakenly staged, use `git restore --staged <paths>` to unstage (command provides instructions, doesn't modify file contents).
76
+
77
+ ---
78
+
79
+ ## Best Practices for Commits
80
+
81
+ - **Atomic commits**: One commit does one thing, easier to trace and review.
82
+ - **Group before committing**: Split by directory/module/feature.
83
+ - **Clear subject**: First line ≤ 72 chars, imperative mood (e.g., "add... / fix...").
84
+ - **Body with context**: Explain motivation, solution, impact scope, risks, and next steps.
85
+ - **Follow Conventional Commits**: `<type>(<scope>): <subject>`.
86
+
87
+ ---
88
+
89
+ ## Type to Emoji Mapping (When --emoji is Used)
90
+
91
+ - ✨ `feat`: New feature
92
+ - 🐛 `fix`: Bug fix (includes 🔥 remove code/files, 🚑️ hotfix, 👽️ adapt to external API changes, 🔒️ security fix, 🚨 fix warnings, 💚 fix CI)
93
+ - 📝 `docs`: Documentation and comments
94
+ - 🎨 `style`: Code style/formatting (no semantic changes)
95
+ - ♻️ `refactor`: Refactoring (no new features, no bug fixes)
96
+ - ⚡️ `perf`: Performance improvements
97
+ - ✅ `test`: Add/fix tests, snapshots
98
+ - 🔧 `chore`: Build/tools/misc tasks (merge branches, update configs, release tags, pin dependencies, .gitignore, etc.)
99
+ - 👷 `ci`: CI/CD configuration and scripts
100
+ - ⏪️ `revert`: Revert commits
101
+ - 💥 `feat`: Breaking changes (explained in `BREAKING CHANGE:` section)
102
+
103
+ > If `--type`/`--scope` is passed, it will **override** auto-detection.
104
+ > Emoji is only included when `--emoji` flag is specified.
105
+
106
+ ---
107
+
108
+ ## Guidelines for Splitting Commits
109
+
110
+ 1. **Different concerns**: Unrelated feature/module changes should be split.
111
+ 2. **Different types**: Don't mix `feat`, `fix`, `refactor` in the same commit.
112
+ 3. **File modes**: Source code vs docs/tests/configs should be grouped separately.
113
+ 4. **Size threshold**: Large diffs (e.g., >300 lines or across multiple top-level directories) should be split.
114
+ 5. **Revertability**: Ensure each commit can be independently reverted.
115
+
116
+ ---
117
+
118
+ ## Examples
119
+
120
+ **Good (with --emoji)**
121
+ - ✨ feat(ui): add user authentication flow
122
+ - 🐛 fix(api): handle token refresh race condition
123
+ - 📝 docs: update API usage examples
124
+ - ♻️ refactor(core): extract retry logic into helper
125
+ - ✅ test: add unit tests for rate limiter
126
+ - 🔧 chore: update git hooks and repository settings
127
+ - ⏪️ revert: revert "feat(core): introduce streaming API"
128
+
129
+ **Good (without --emoji)**
130
+ - feat(ui): add user authentication flow
131
+ - fix(api): handle token refresh race condition
132
+ - docs: update API usage examples
133
+ - refactor(core): extract retry logic into helper
134
+ - test: add unit tests for rate limiter
135
+ - chore: update git hooks and repository settings
136
+ - revert: revert "feat(core): introduce streaming API"
137
+
138
+ **Split Example**
139
+ - `feat(types): add new type defs for payment method`
140
+ - `docs: update API docs for new types`
141
+ - `test: add unit tests for payment types`
142
+ - `fix: address linter warnings in new files` ← (if your repo has hook errors)
143
+
144
+ ---
145
+
146
+ ## Important Notes
147
+
148
+ - **Git only**: No package manager/build commands (`pnpm`/`npm`/`yarn` etc.).
149
+ - **Respects hooks**: Executes local Git hooks by default; use `--no-verify` to skip.
150
+ - **No source code changes**: Command only reads/writes `.git/COMMIT_EDITMSG` and staging area; doesn't directly edit working directory files.
151
+ - **Safety prompts**: In rebase/merge conflicts, detached HEAD states, prompts to handle/confirm before continuing.
152
+ - **Auditable and controllable**: If `confirm: true` is enabled, each actual `git add`/`git commit` step requires confirmation.
@@ -0,0 +1,89 @@
1
+ ---
2
+ description: Interactively rollback Git branch to historical version; lists branches, versions, then executes reset/revert after confirmation
3
+ allowed-tools: Read(**), Exec(git fetch, git branch, git tag, git log, git reflog, git checkout, git reset, git revert, git switch), Write()
4
+ argument-hint: [--branch <branch>] [--target <rev>] [--mode reset|revert] [--depth <n>] [--dry-run] [--yes]
5
+ # examples:
6
+ # - /git-rollback # Full interactive mode, dry-run
7
+ # - /git-rollback --branch dev # Select dev directly, other interactive
8
+ # - /git-rollback --branch dev --target v1.2.0 --mode reset --yes
9
+ ---
10
+ # Claude Command: Git Rollback
11
+
12
+ **Purpose**: Safely and visually rollback a specified branch to an older version.
13
+ Defaults to **read-only preview (`--dry-run`)**; actual execution requires `--yes` or interactive confirmation.
14
+
15
+ ---
16
+
17
+ ## Usage
18
+
19
+ ```bash
20
+ # Pure interactive: list branches → select branch → list recent 20 versions → select target → choose reset or revert → confirm
21
+ /git-rollback
22
+
23
+ # Specify branch, other interactive
24
+ /git-rollback --branch feature/calculator
25
+
26
+ # Specify branch and target commit, execute with hard-reset in one go (dangerous)
27
+ /git-rollback --branch main --target 1a2b3c4d --mode reset --yes
28
+
29
+ # Generate revert commit only (non-destructive rollback), preview
30
+ /git-rollback --branch release/v2.1 --target v2.0.5 --mode revert --dry-run
31
+ ```
32
+
33
+ ### Options
34
+
35
+ | Option | Description |
36
+ |------|------|
37
+ | `--branch <branch>` | Branch to rollback; interactively selected if omitted. |
38
+ | `--target <rev>` | Target version (commit hash, tag, or reflog reference); interactively selects recent `--depth` entries if omitted. |
39
+ | `--mode reset\|revert` | `reset`: Hard rollback history; `revert`: Generate reverse commits keeping history intact. Prompts by default. |
40
+ | `--depth <n>` | List recent n versions in interactive mode (default 20). |
41
+ | `--dry-run` | **Enabled by default**, only preview commands to be executed. |
42
+ | `--yes` | Skip all confirmations and execute directly, suitable for CI/CD scripts. |
43
+
44
+ ---
45
+
46
+ ## Interactive Flow
47
+
48
+ 1. **Sync remote** → `git fetch --all --prune`
49
+ 2. **List branches** → `git branch -a` (local + remote, filter protected branches)
50
+ 3. **Select branch** → User input or parameter
51
+ 4. **List versions** → `git log --oneline -n <depth>` + `git tag --merged` + `git reflog -n <depth>`
52
+ 5. **Select target** → User inputs commit hash / tag
53
+ 6. **Select mode** → `reset` or `revert`
54
+ 7. **Final confirmation** (unless `--yes`)
55
+ 8. **Execute rollback**
56
+ * `reset`: `git switch <branch> && git reset --hard <target>`
57
+ * `revert`: `git switch <branch> && git revert --no-edit <target>..HEAD`
58
+ 9. **Push suggestion** → Prompt whether to `git push --force-with-lease` (reset) or regular `git push` (revert)
59
+
60
+ ---
61
+
62
+ ## Safety Guards
63
+
64
+ * **Backup**: Automatically records current HEAD in reflog before execution, recoverable with `git switch -c backup/<timestamp>`.
65
+ * **Protected branches**: If protected branches like `main` / `master` / `production` are detected with `reset` mode enabled, requires additional confirmation.
66
+ * **--dry-run enabled by default**: Prevents accidental operations.
67
+ * **--force prohibited**: No `--force` provided; if force push needed, manually enter `git push --force-with-lease`.
68
+
69
+ ---
70
+
71
+ ## Use Case Examples
72
+
73
+ | Scenario | Command Example |
74
+ |------|---------|
75
+ | Hotfix patch deployed with bug, need to rollback to tag `v1.2.0` | `/git-rollback --branch release/v1 --target v1.2.0 --mode reset` |
76
+ | Ops colleague pushed debug logs by mistake, need to generate reverse commit | `/git-rollback --branch main --target 3f2e7c9 --mode revert` |
77
+ | Research historical bugs, guide newcomers through branch history | `/git-rollback` (full interactive, dry-run) |
78
+
79
+ ---
80
+
81
+ ## Notes
82
+
83
+ 1. **reset vs revert**
84
+ * **reset** changes history, requires force push and may affect other collaborators, use with caution.
85
+ * **revert** is safer, generates new commits preserving history, but adds one more record.
86
+ 2. **Embedded repositories** often have large binary files; ensure LFS/submodule state consistency before rollback.
87
+ 3. If repository has CI forced validation, rollback may trigger pipelines automatically; confirm control policies to avoid accidental deployment of old versions.
88
+
89
+ ---