**Important Note**: This prompt may run in non-interactive environments (e.g., CI/CD, automation scripts).

**Non-interactive mode**:
- Do NOT use `AskUserQuestion` or any interactive tools
- When user input is needed:
  - Use reasonable defaults (e.g., use `feat` for commit type)
  - Skip optional confirmation steps
  - Document assumptions made

**Interactive mode**:
- Follow normal interactive flow, prompt user for input

---

<task>
Analyze all uncommitted changes in the workspace (including staged and unstaged states), intelligently group them into multiple logical commits.
</task>

<context>
User is working in a Git repository at:
<project_path>
{{ projectPath }}
</project_path>

{{#if needPush}}
<push_control>
needPush parameter is set to {{needPush}}.
If true: After all commits are created, check fastforward relationship and push if safe.
If false: Only create local commits, do not push.
</push_control>
{{/if}}

<target_branch_control>
targetBranchMode is set to {{targetBranchMode}}.
{{#if targetBranchName}}
targetBranchName is set to {{targetBranchName}}.
{{/if}}
Rules:
- If `targetBranchMode=current`: stay on the current branch and do not create a new branch
- If `targetBranchMode=new-custom`: create a new branch from the current branch with `targetBranchName` before any commit
- If `targetBranchMode=ai-generated-new`: derive a kebab-case branch name from the current changes, then create it from the current branch before any commit
- Do not switch to any other pre-existing branch
</target_branch_control>

You need to:
1. Use Git commands to get all uncommitted changes in the workspace (including staged and unstaged states)
2. Analyze all uncommitted file changes to understand their semantic relationships
3. Intelligently group files into 1 or more logical commits
4. **Directly use Git commands to execute each commit** (do not return a plan, execute directly)
</context>

<working_directory>
Use this project path as the working directory: {{ projectPath }}
</working_directory>

{{#if gitProfileName}}
<git_profile>
Use the selected Git identity for every generated commit:
- Selected name: {{gitProfileName}}
- Selected email: {{gitProfileEmail}}
- Git stores two identities in commit history: `Author` and `Committer`
- `--author="Name <email>"` only changes the Author
- `git -c user.name="Name" -c user.email="email" commit ...` only changes the Committer for that one command
- For every generated commit, you MUST set both Author and Committer to the selected identity
- Preferred command pattern:
  `git -c user.name="{{gitProfileName}}" -c user.email="{{gitProfileEmail}}" commit --author="{{gitProfileName}} <{{gitProfileEmail}}>" ...`
- If you need an alternative low-level fallback, you may set `GIT_COMMITTER_NAME` and `GIT_COMMITTER_EMAIL`, but the `git -c ... commit --author=...` form is preferred
- Keep the commit grouping and wording consistent with this identity.
</git_profile>
{{/if}}

<tools>
You can use the following tools:
- Bash(git:*) - Execute Git commands
- Read - Read file contents
- Write/Edit - Write files (if needed)
- Bash(cat:*, ls:*, find:*) - View file information
</tools>

<requirements>
  <requirement>
    **Target branch handling**:
    - If `targetBranchMode=current`, all commits MUST stay on the current branch
    - If `targetBranchMode=new-custom`, you MUST create a new branch from the current branch with `git switch -c "<targetBranchName>"` before the first commit
    - If `targetBranchMode=ai-generated-new`, you MUST generate a kebab-case branch name from the change context, then create it from the current branch with `git switch -c "<generated-branch>"`
    - Do NOT switch to any other pre-existing branch
    - If new branch creation fails, return an error instead of continuing with commits
  </requirement>
  <requirement>
    **Intelligent grouping**: Organize file changes into multiple logical commits based on their semantic relationships
    - Do not execute any git reset operations (state management is handled by the backend)
  </requirement>
  <requirement>
    **Important**: Each commit must include Co-Authored-By information
    - Use this format: `git commit -m "type(scope): subject" -m "" -m "Co-Authored-By: Hagicode <noreply@hagicode.com>"`
    - Or include Co-Authored-By line directly in the commit message
  </requirement>
  {{#if gitProfileName}}
  <requirement>
    **Git identity enforcement**:
    - For every generated commit, set both `Author` and `Committer` to `{{gitProfileName}} <{{gitProfileEmail}}>`
    - Do NOT use `--author` alone, because that would leave the Committer identity unchanged
    - Prefer `git -c user.name="{{gitProfileName}}" -c user.email="{{gitProfileEmail}}" commit --author="{{gitProfileName}} <{{gitProfileEmail}}>" ...`
    - If you need to verify the recorded identities after a commit, use `git log --format=fuller -1`
  </requirement>
  {{/if}}
  <requirement>
    Group files based on semantic relationships:
    - Files for the same feature/functional area go in the same commit
    - Files for the same component/module go in the same commit
    - Configuration changes should be separate from code changes
    - Documentation changes should be separate from feature changes
    - Test files should be grouped with the implementation they test

    **File Grouping Decision Tree**:
    ```
    File grouping decision tree
    ├── Is it a config file (package.json, tsconfig.json, .env, etc.)?
    │   ├── Yes → Separate commit (type: chore or build)
    │   └── No → Continue
    ├── Is it a doc file (README.md, *.md, docs/**)?
    │   ├── Yes → Separate commit (type: docs)
    │   └── No → Continue
    ├── Is it related to the same feature?
    │   ├── Yes → Merge into same commit
    │   └── No → Separate commits
    └── Is it a cross-module change?
        ├── Yes → Group by module
        └── No → Group by feature
    ```

    **Grouping Examples**:
    - `src/auth/login.ts` + `src/auth/auth.service.ts` → Same commit (same module)
    - `src/components/Button.tsx` + `src/components/Button.test.tsx` → Same commit (test with implementation)
    - `package.json` + `tsconfig.json` → Same commit (config changes)
    - `README.md` + `docs/api.md` → Same commit (documentation changes)
    - `src/auth/login.ts` + `src/utils/date.ts` → Separate commits (different modules)
  </requirement>
  <requirement>
    Follow Conventional Commits specification:
    https://www.conventionalcommits.org/
  </requirement>
  <requirement>
    Use one of the following types:
    - feat: A new feature
    - fix: A bug fix
    - docs: Documentation only changes
    - style: Changes that do not affect the meaning of the code
    - refactor: A code change that neither fixes a bug nor adds a feature
    - perf: A code change that improves performance
    - test: Adding missing tests or correcting existing tests
    - build: Changes that affect the build system or external dependencies
    - ci: Changes to CI configuration files and scripts
    - chore: Other changes that don't modify src or test files
    - revert: Reverts a previous commit
  </requirement>
  <requirement>
    Subject line must:
    - Use imperative mood (add, not added)
    - Be 50-72 characters max
    - Not end with a period
    - Begin with type(scope): prefix
  </requirement>
  <requirement>
    Ensure every file is committed
  </requirement>
</requirements>

<historical_format_analysis>
  <requirement>
    **Historical Format Consistency**: Before generating commit messages, you MUST analyze the current repository's commit history to match the existing style

    1. Use `git log -n 15 --pretty=format:"%H|%s|%b%n---%n"` to get recent commit history
    2. Analyze the commits to identify:
       - Structure pattern: Does the project use multiple paragraphs? Are there "Changes:" or "Capabilities:" sections?
       - Language pattern: Are commit messages in English, Chinese, or mixed?
       - Common types: Which commit types (feat, fix, docs, etc.) are most frequently used?
       - Special formatting: Are there Co-Authored-By lines? Any other project-specific conventions?

    3. Generate commit messages that follow the detected patterns

    **Special Scenarios**:
    - **Empty repository/First commit**: If there are no previous commits (new repository), use standard Conventional Commits format without custom patterns. Use `feat` or `chore` for commit type.
    - **Mixed languages**: If the history contains mixed languages, follow the primary language or the last used language.
    - **No clear pattern**: If there's no clear pattern in commit history, use the standard Conventional Commits format.
  </requirement>
</historical_format_analysis>

<constraints>
  <constraint>Do not execute any git reset operations</constraint>
  <constraint>Ignore files and directories defined in .gitignore</constraint>
  <constraint>Group files into separate commits by functional logic</constraint>
  <constraint>Each commit should contain logically related file changes</constraint>
  <constraint>Follow Conventional Commits format for commit messages</constraint>
</constraints>

<workflow>
Follow these steps:

1. **Get file changes**: Use `git status --porcelain` or `git diff` commands to get all uncommitted file changes

2. **Analyze files**: Use Read tool to examine the changed files and understand the nature of changes

3. **Intelligent grouping**: Group files by semantic relationships

4. **Prepare the target branch**:
   a. If `targetBranchMode` is `current`, keep the current branch unchanged
   b. If `targetBranchMode` is `new-custom`, create the provided `targetBranchName` from the current branch
   c. If `targetBranchMode` is `ai-generated-new`, generate an English kebab-case branch name; if it conflicts, append a stable suffix; then create that branch from the current branch
   d. Record the final resolved target branch name

5. **Execute commits** (for each group):
   a. Use `git add <file1> <file2> ...` to stage all files in this group
   b. Execute the commit with the correct Git identity
   {{#if gitProfileName}}
      - Use:
        `git -c user.name="{{gitProfileName}}" -c user.email="{{gitProfileEmail}}" commit --author="{{gitProfileName}} <{{gitProfileEmail}}>" -m "type(scope): subject" -m "" -m "Co-Authored-By: Hagicode <noreply@hagicode.com>"`
   {{else}}
      - Use:
        `git commit -m "type(scope): subject" -m "" -m "Co-Authored-By: Hagicode <noreply@hagicode.com>"`
   {{/if}}
   c. Record the commit hash

6. **Verify**: Use `git log --oneline -n 10` to verify commits were successfully created
   {{#if gitProfileName}}
   - Also use `git log --format=fuller -1` when needed to confirm both Author and Committer were recorded with the selected identity
   {{/if}}

{{#if needPush}}
7. **Push to remote (if needPush is true)**:
   a. Use `git remote -v` to identify the remote repository
   b. Use the resolved target branch as the only push target
   c. If the resolved target branch is the original current branch, check fastforward with `git merge-base --is-ancestor origin/<target-branch> HEAD`
   d. If the resolved target branch is newly created and the remote branch does not exist, execute `git push --set-upstream origin <target-branch>`
   e. If the resolved target branch already exists on the remote, run the fastforward safety check first, then execute `git push origin <target-branch>` when safe
   f. If fastforward is NOT safe (command returns non-zero): skip the push, record the reason, and continue
   g. Record the push result (success/skipped)

8. **Report results**: Return a concise summary listing all executed commits and push status
{{else}}
7. **Report results**: Return a concise summary listing all executed commits
{{/if}}
</workflow>

<output_format>
After completing all commits, you **must** return a summary in this exact format (Important: use `---` as the delimiter between commits):

---
Commit 1: {commit_hash}
{commit_message}
---
Commit 2: {commit_hash}
{commit_message}
---
...

**Format Requirements**:
- Each commit result starts with `---` on its own line
- First line format: `Commit N: {commit_hash}` (N is the commit number)
- Second and subsequent lines contain the commit message (may span multiple lines)
- Use `---` separator between commits (on its own line)
- End the last commit with `---` as well

**Complete Output Example**:
---
Commit 1: abc123def456
feat(auth): add user login functionality

Implement JWT-based authentication with login form and API endpoints.

Co-Authored-By: Hagicode <noreply@hagicode.com>
---
Commit 2: 789ghi012jkl
docs(readme): update installation instructions

Add new setup steps for Docker environment.

Co-Authored-By: Hagicode <noreply@hagicode.com>
---

If any commit fails, report the error in the corresponding commit segment.
Do not append any statistics section; output MUST include commit blocks only.
</output_format>

<final_instruction>
Important: You must directly execute Git commands to complete the commits, do not just return a plan.
Ensure all files are committed and each commit includes the correct Co-Authored-By information.

**Output Format Requirement**: When returning results, you **must** use `---` delimiters between each commit. This is the required format for backend parsing of multi-commit results.
</final_instruction>
